Compare commits

..

132 Commits

Author SHA1 Message Date
omkarht
96ca7c090f chore : add changeset for classDef style application
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-11-20 12:43:56 +05:30
omkarht
bf7c532e43 7167 : fix classDef style application for treemap diagramtype
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-11-19 19:46:35 +05:30
Sidharth Vinod
ecf9ea1134 Merge pull request #7099 from mermaid-js/fix/mindmap-level-node-rendering
7000: Fix mindmap rendering issue when Level 2 nodes exceed 11
2025-11-14 12:21:56 +00:00
darshanr0107
03e8589818 chore: add visual test
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-11-14 11:14:21 +05:30
Shubham P
6b9f26dac8 Merge pull request #7080 from mermaid-js/7079-c4context-componentqueue-ext-lexical-error
7079: add missing support for ComponentQueue_Ext in C4Context diagrams
2025-11-11 04:07:06 +00:00
Shubham P
ea590cdafe Merge pull request #7075 from mermaid-js/6889-fix-escaped-p-tags-in-sandbox-mode
6889: Fix escaped <p> tags in labels when securityLevel is set to "sandbox"
2025-11-11 04:05:37 +00:00
Shubham P
f3769c70bc Merge branch 'develop' into 7079-c4context-componentqueue-ext-lexical-error 2025-11-11 09:24:14 +05:30
Shubham P
4cf4d15197 Merge branch 'develop' into 6889-fix-escaped-p-tags-in-sandbox-mode 2025-11-11 09:23:23 +05:30
Shubham P
c02cf92656 Merge pull request #7149 from mermaid-js/renovate/patch-dompurify
fix(deps): update dependency dompurify to ^3.3.0
2025-11-10 10:15:31 +00:00
Shubham P
3a1266892d Merge pull request #7148 from mermaid-js/renovate/patch-all-patch
fix(deps): update all patch dependencies (patch)
2025-11-10 10:15:16 +00:00
renovate[bot]
67e81de557 fix(deps): update dependency dompurify to ^3.3.0 2025-11-10 02:54:45 +00:00
renovate[bot]
847b3aa24e fix(deps): update all patch dependencies 2025-11-10 02:54:19 +00:00
Sidharth Vinod
85a13da40f Merge pull request #7138 from mermaid-js/update-timings
Update E2E Timings
2025-11-07 21:42:11 +09:00
darshanr0107
9ec0e8f932 Merge branch 'develop' of https://github.com/mermaid-js/mermaid into 6889-fix-escaped-p-tags-in-sandbox-mode 2025-11-07 11:58:38 +05:30
darshanr0107
9585ee7533 chore:add e2e test
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-11-07 11:46:41 +05:30
github-actions[bot]
1269486124 chore: update E2E timings 2025-11-07 04:15:01 +00:00
Shubham P
f45ea0c60e Merge pull request #7096 from mermaid-js/renovate/npm-vite-vulnerability
chore(deps): update dependency vite to v7.1.11 [security]
2025-11-06 14:52:25 +00:00
renovate[bot]
d20955a56a chore(deps): update dependency vite to v7.1.11 [security] 2025-11-06 12:46:25 +00:00
Shubham P
fb66b3fbe3 Merge pull request #7049 from mermaid-js/renovate/major-eslint
chore(deps): update eslint (major)
2025-11-06 12:31:47 +00:00
Shubham P
82ea5d63bb Merge pull request #7017 from mermaid-js/renovate/peter-evans-create-pull-request-digest
chore(deps): update peter-evans/create-pull-request digest to 0edc001
2025-11-06 12:30:09 +00:00
renovate[bot]
881e74087a chore(deps): update eslint 2025-11-06 12:06:45 +00:00
renovate[bot]
09920c0497 chore(deps): update peter-evans/create-pull-request digest to 0edc001 2025-11-06 12:05:55 +00:00
Shubham P
8065d65cd7 Merge pull request #6973 from mermaid-js/renovate/patch-dompurify
fix(deps): update dependency dompurify to ^3.2.7
2025-11-06 11:52:40 +00:00
renovate[bot]
09b841f781 fix(deps): update dependency dompurify to ^3.2.7 2025-11-06 10:46:44 +00:00
Shubham P
d0f9dc0c9b Merge pull request #7018 from mermaid-js/renovate/patch-all-patch
fix(deps): update all patch dependencies (patch)
2025-11-06 10:28:10 +00:00
renovate[bot]
15e2824d53 fix(deps): update all patch dependencies 2025-11-06 10:04:11 +00:00
Shubham P
7eb582e860 Merge pull request #7135 from mermaid-js/fix/er-numeric-entity-test-conflict
refactor: update test description for standalone numeric entities in ER diagram
2025-11-06 09:51:04 +00:00
omkarht
6ca928f31f refactor: update test description for standalone numeric entities in ER diagram 2025-11-06 15:05:58 +05:30
darshanr0107
983120d945 fix: add test case for C4Context diagram with ComponentQueue_Ext
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-11-05 17:18:34 +05:30
darshanr0107
61f74ffc5e fix: incorrect section number logic by using index % (MAX_SECTIONS - 1)
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-11-05 14:54:51 +05:30
darshanr0107
74318f9337 chore: use MAX_SECTIONS constant instead of hardcoded value
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-11-05 14:28:59 +05:30
Sidharth Vinod
dfd59470dc Merge pull request #7129 from mermaid-js/sidv/injectVersion
feat: Optimize bundling to remove shipping package.json inside mermaid's JS bundle.
2025-11-04 18:42:32 +00:00
Sidharth Vinod
4aac6fa448 Merge pull request #7128 from CNOCTAVE/develop
add doc to use marmaid.js in GNU Octave
2025-11-04 17:42:28 +00:00
CNOCTAVE
5f96f80efb Merge branch 'develop' of https://github.com/CNOCTAVE/mermaid into develop 2025-11-05 01:16:47 +08:00
CNOCTAVE
545801e144 Update integrations-community.md 2025-11-05 01:16:17 +08:00
CNOCTAVE
0bd74759cc Merge branch 'develop' into develop 2025-11-05 01:13:00 +08:00
CNOCTAVE
e4cf266c1d remove changeset
remove changeset
2025-11-05 01:12:15 +08:00
CNOCTAVE
c0e1662e50 Update packages/mermaid/src/docs/ecosystem/integrations-community.md
Co-authored-by: Sidharth Vinod <github@sidharth.dev>
2025-11-05 01:08:04 +08:00
Sidharth Vinod
6546aed482 chore: forbid use of viewbox in code 2025-11-05 00:07:30 +07:00
Sidharth Vinod
b76ccae065 feat: Optimize bundling to remove shipping package.json inside mermaid's JS bundle.
Move all build time injected variables to `injected.` namespace to avoid conflicts.
2025-11-04 23:49:54 +07:00
Sidharth Vinod
287a9a3fcb chore: Add missing clean scripts
Co-authored-by: Alois Klink <alois@aloisklink.com>
2025-11-04 21:21:58 +07:00
Sidharth Vinod
7f5160fa4d chore: Remove NPM_TOKEN from release workflow 2025-11-04 21:12:10 +07:00
autofix-ci[bot]
7b0763f262 [autofix.ci] apply automated fixes 2025-11-04 12:43:03 +00:00
CNOCTAVE
38c289818c feat: add doc to use marmaid.js in GNU Octave
feat: add doc to use marmaid.js in GNU Octave. Resolve #7073
2025-11-04 20:34:13 +08:00
CNOCTAVE
57530076aa add doc to use marmaid.js in GNU Octave
add doc to use marmaid.js in GNU Octave. Resolve #7073
2025-11-04 20:29:53 +08:00
CNOCTAVE
f2d7877c7a Merge branch 'develop' of https://github.com/CNOCTAVE/mermaid into develop 2025-11-04 20:20:28 +08:00
Sidharth Vinod
62d2c6505e Merge pull request #7109 from arnaudrenaud/add-speccharts
docs: Add speccharts to `integrations-community.md`
2025-11-04 11:57:01 +00:00
autofix-ci[bot]
974236bbb8 [autofix.ci] apply automated fixes 2025-11-04 11:48:23 +00:00
Sidharth Vinod
cf0d1248a4 chore: Add speccharts to cspell 2025-11-04 18:42:42 +07:00
Alois Klink
ebefbd87a8 Merge pull request #7127 from mermaid-js/sidharthv96-patch-2
Refactor GitHub Actions workflow for lockfile validation
2025-11-04 07:43:17 +00:00
Sidharth Vinod
1e7b71a085 Refactor GitHub Actions workflow for lockfile validation
Removed Node.js setup step and pnpm action version.

Co-authored-by: Alois Klink <alois@mermaidchart.com>
2025-11-03 23:30:27 -08:00
Sidharth Vinod
f28f3c25aa Merge pull request #7116 from mermaid-js/sidv/lockfileValidation
fix: Lockfile validation
2025-10-30 02:29:50 +09:00
Sidharth Vinod
58137aa631 feat: Allow validation workflow to run on forks 2025-10-30 01:56:18 +09:00
Sidharth Vinod
e7719f14c5 fix: Prevent duplicate comments by validation workflow 2025-10-30 01:55:58 +09:00
Sidharth Vinod
35d9cead8a chore: Cleanup lockfile 2025-10-30 01:22:17 +09:00
Ashish Jain
13baf51b35 Merge 11.12.1 back to develop 2025-10-28 11:23:19 +01:00
Justin Greywolf
9af985ba9b Merge pull request #5814 from kairi003/feature/4706_allow_notes_in_namespace
feat: allow to put notes in namespaces on classDiagram
2025-10-27 19:21:00 +00:00
Arnaud Renaud
c7f8a11ded Add speccharts to integrations-community.md 2025-10-27 14:16:35 +01:00
Sidharth Vinod
762b44cf33 Merge pull request #7108 from mermaid-js/changeset-release/master
Version Packages
2025-10-27 18:35:34 +05:30
github-actions[bot]
02c0091106 Version Packages 2025-10-27 12:08:22 +00:00
Sidharth Vinod
16359adc33 Merge pull request #7107 from mermaid-js/patch/dagre-d3-es-7.0.13
fix: update dagre-d3-es to version 7.0.13
2025-10-27 17:35:36 +05:30
Shubham P
061632c580 Update .changeset/slick-wasps-bathe.md
Co-authored-by: Alois Klink <alois@mermaidchart.com>
2025-10-27 16:20:24 +05:30
shubhamparikh2704
cbf89462ac fix: update dagre-d3-es to version 7.0.13 2025-10-27 15:06:24 +05:30
kairi003
700aa100f2 fix: style broken caused by a mistake in merge 3f46c94a 2025-10-26 04:18:19 +09:00
kairi003
49103ea654 fix: update ClassDB and ClassTypes for improved type safety and consistency 2025-10-26 03:01:00 +09:00
kairi003
3f46c94ab2 Merge branch 'develop' into tmp/feature/4706_allow_notes_in_namespace 2025-10-26 02:39:38 +09:00
darshanr0107
b136acdc67 chore:add changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-22 17:53:48 +05:30
darshanr0107
bba5e5938e fix: mindmap rendering issue when level nodes exceed 11
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-22 17:06:21 +05:30
Knut Sveidqvist
fed8a523a4 Merge pull request #7076 from mermaid-js/6919-fix-incorrect-viewBox-casing
6919: correct viewBox casing in Radar & Packet
2025-10-21 12:20:04 +00:00
Knut Sveidqvist
33b4946e21 Merge branch 'develop' into 6919-fix-incorrect-viewBox-casing 2025-10-21 10:33:21 +02:00
Justin Greywolf
3d768f3adf Merge pull request #6975 from ilovelinux/fix/6974-ilovelinux-fix-classdiagram-example
Fix classDiagram example
2025-10-17 02:56:34 +00:00
darshanr0107
76e17ffd20 fix: add validation to ensure correct casing of 'viewBox' in all rendering tests
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-15 18:56:49 +05:30
darshanr0107
835de0012d fix:ComponentQueue_Ext throws lexical error
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-14 19:00:17 +05:30
darshanr0107
60f633101c chore: added changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-13 19:14:22 +05:30
Shubham P
18f51eb14e Merge pull request #6843 from saurabhg772244/saurabh/fix-edge-animation-for-hand-dranw-shapes
Fixed edge animation for hand drawn shapes
2025-10-13 13:14:24 +00:00
Shubham P
2bb57bf7d2 Merge pull request #6989 from mermaid-js/subgraph-td-direction
6338: allow direction TD inside subgraphs
2025-10-13 13:13:46 +00:00
Shubham P
a6276daffd Merge pull request #7055 from mermaid-js/sequence-diagram-participant-name-parsing
6853:  prevent browser freeze caused by invalid participant name in sequenceDiagram
2025-10-13 13:12:08 +00:00
darshanr0107
7def6eecbf fix: correct viewBox casing in radar and packet diagram
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-13 18:15:38 +05:30
darshanr0107
96a766dcdb chore: added changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-13 13:42:41 +05:30
darshanr0107
39d7ebd32e fix: escaped p tags in sandbox mode
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-13 13:16:58 +05:30
CNOCTAVE
34f40f0794 add doc to use marmaid.js in GNU Octave 2025-10-13 15:11:44 +08:00
CNOCTAVE
32ac2c689d add doc to use marmaid.js in GNU Octave 2025-10-13 15:02:46 +08:00
CNOCTAVE
dbcadc1d0b add doc to use marmaid.js in GNU Octave 2025-10-13 13:56:04 +08:00
Antonio Spadaro
ac411a7d7e Fix class diagram example 2025-10-11 22:56:37 +02:00
Justin Greywolf
d80a638e55 Merge pull request #6023 from yari-dewalt/fix_lollipop_stroke
Fix: Delete 'stroke: black' from lollipop marker so it matches themes and edge paths
2025-10-11 20:43:08 +00:00
Justin Greywolf
7a869c08a2 Merge pull request #6026 from yari-dewalt/bug/5669_class-diagram-fix-namespace-themes
Fix: Class diagram namespaces black lines, not responding to theme variables
2025-10-11 20:42:53 +00:00
Justin Greywolf
44e8cbb1de Merge branch 'develop' into bug/5669_class-diagram-fix-namespace-themes 2025-10-11 13:27:47 -07:00
Justin Greywolf
efe38b8425 Merge branch 'develop' into fix_lollipop_stroke 2025-10-11 13:26:59 -07:00
darshanr0107
6fecb985e8 fix: failing argos
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-09 11:50:44 +05:30
darshanr0107
69b338d8af fix: formatting issues
Co-authored-by: omkarht <omkar@mermaidchart.com>
2025-10-09 11:37:05 +05:30
darshanr0107
fa15ce8502 chore: added changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-08 13:23:28 +05:30
darshanr0107
6d0650918f fix: handle participant names with spaces correctly in sequenceDiagram
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-08 13:09:30 +05:30
Sidharth Vinod
ad82448084 Merge pull request #7053 from mermaid-js/changeset-release/master
Version Packages
2025-10-07 13:23:31 +05:30
github-actions[bot]
9498619d3c Version Packages 2025-10-07 07:36:05 +00:00
Sidharth Vinod
7a8557a1a2 Merge pull request #7036 from mermaid-js/knsv-patch-1
Update free plan diagram limit from 3 to 6
2025-10-07 13:03:39 +05:30
Sidharth Vinod
74863c94fb Merge pull request #7051 from mermaid-js/patch-parser-release
Pre Release
2025-10-07 12:34:22 +05:30
shubhamparikh2704
63df702146 chore: added changeset file 2025-10-07 10:47:16 +05:30
autofix-ci[bot]
421f8d4633 [autofix.ci] apply automated fixes 2025-10-03 07:41:08 +00:00
Knut Sveidqvist
bf6e1a594c Update free plan diagram limit from 3 to 6 2025-10-03 09:35:21 +02:00
darshanr0107
1a9d45abf0 fix: allow direction TD inside subgraphs
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-09-24 12:22:31 +05:30
Sidharth Vinod
0116b272b4 Merge pull request #6961 from mermaid-js/changeset-release/master
Version Packages
2025-09-18 10:50:42 +05:30
github-actions[bot]
634f3367da Version Packages 2025-09-17 17:48:06 +00:00
Saurabh Gore
bbb93b263d Merge branch 'develop' into saurabh/fix-edge-animation-for-hand-dranw-shapes 2025-09-13 11:37:21 +05:30
saurabhg772244
4240340a18 Merge branch 'develop' of github.com:mermaid-js/mermaid into saurabh/fix-edge-animation-for-hand-dranw-shapes 2025-09-11 11:36:26 +05:30
omkarht
ca10a259fa Merge branch 'develop' into saurabh/fix-edge-animation-for-hand-dranw-shapes 2025-09-05 16:28:39 +05:30
Saurabh Gore
0ed9c65572 Merge branch 'develop' into saurabh/fix-edge-animation-for-hand-dranw-shapes 2025-09-05 12:56:27 +05:30
saurabhg772244
56cc12690f Added option to skip screenshot for cypress tests 2025-09-05 12:47:07 +05:30
saurabhg772244
e6fb4a84da code refactor 2025-08-11 16:32:03 +05:30
saurabhg772244
32723b2de1 Added change set 2025-08-11 15:59:07 +05:30
saurabhg772244
18703782ee Fixed edge animation for hand drawn shapes 2025-08-11 15:52:49 +05:30
autofix-ci[bot]
47297f7c26 [autofix.ci] apply automated fixes 2025-02-26 17:49:51 +00:00
Yari DeWalt
967aa0629e Merge branch 'develop' into bug/5669_class-diagram-fix-namespace-themes 2025-02-26 09:45:14 -08:00
Yari DeWalt
04b20a79b9 Merge branch 'develop' into fix_lollipop_stroke 2025-02-26 09:20:16 -08:00
kairi
d60b09cafc Merge branch 'develop' into feature/4706_allow_notes_in_namespace 2024-12-01 09:20:39 +09:00
kairi003
875827f59b Merge branch 'develop' into feature/4706_allow_notes_in_namespace 2024-11-21 07:16:47 +09:00
kairi003
c4e08261b5 Merge branch 'develop' into feature/4706_allow_notes_in_namespace 2024-11-10 23:56:48 +09:00
kairi003
70f679d2fa add: e2e test for classDiagram-v3 2024-11-10 20:27:35 +09:00
kairi003
25c43fa439 add: horizontal rules to demos/classchart.html 2024-11-10 02:34:31 +09:00
kairi003
ec1c6325d4 refactor: Add type annotations and optimize redundant set loop 2024-11-10 02:34:31 +09:00
kairi003
309ff6be38 fix: Reimplement notes in namespaces for classRenderer-v3 (#5880) 2024-11-10 02:32:20 +09:00
kairi003
02d368df05 chore: relax git version constraint in Dockerfile to allow patch updates 2024-11-10 01:58:29 +09:00
kairi003
4ee1fe2ca4 Merge branch 'master' into feature/4706_allow_notes_in_namespace 2024-11-10 01:52:46 +09:00
yari-dewalt
4ff2ae9f4e Add styles for clusters and remove hard-coded styling for namespace nodes 2024-11-06 09:00:21 -08:00
Yari DeWalt
7a729e8f16 Merge branch 'develop' into fix_lollipop_stroke 2024-11-04 10:21:00 -08:00
yari-dewalt
3c7fd95617 Remove black stroke from lollipops so it matches edge paths 2024-11-04 10:15:51 -08:00
kairi003
2dd29bee25 add changelogs 2024-09-08 02:13:33 +09:00
kairi003
259a508d8a add e2e test 2024-09-08 01:31:26 +09:00
kairi
1963064369 Merge branch 'develop' into feature/4706_allow_notes_in_namespace 2024-09-08 00:27:14 +09:00
kairi
a101ce803c Merge branch 'develop' into feature/4706_allow_notes_in_namespace 2024-09-04 14:14:19 +09:00
kairi003
fc0c7936d1 feat: Add support for adding notes to namespaces in class diagrams 2024-09-03 15:27:31 +09:00
kairi003
2d2add5b44 Change: use Map for notes 2024-09-03 15:22:59 +09:00
kairi003
58fd5ddbaf Add: demo for notes in namespace on classDialog 2024-09-03 15:22:41 +09:00
127 changed files with 2968 additions and 6655 deletions

View File

@@ -1,92 +0,0 @@
/* eslint-disable no-console */
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
import { resolve, dirname } from 'node:path';
import { readFile, mkdir, access } from 'node:fs/promises';
import { existsSync } from 'node:fs';
const execAsync = promisify(exec);
interface AntlrGrammarConfig {
id: string;
grammar: string;
outputDir: string;
language: string;
generateVisitor?: boolean;
generateListener?: boolean;
}
interface AntlrConfig {
projectName: string;
grammars: AntlrGrammarConfig[];
mode: string;
}
export async function generateFromConfig(configFile: string): Promise<void> {
const configPath = resolve(configFile);
if (!existsSync(configPath)) {
throw new Error(`ANTLR config file not found: ${configPath}`);
}
const configContent = await readFile(configPath, 'utf-8');
const config: AntlrConfig = JSON.parse(configContent);
const configDir = dirname(configPath);
for (const grammarConfig of config.grammars) {
await generateGrammar(grammarConfig, configDir);
}
}
async function generateGrammar(grammarConfig: AntlrGrammarConfig, baseDir: string): Promise<void> {
const grammarFile = resolve(baseDir, grammarConfig.grammar);
const outputDir = resolve(baseDir, grammarConfig.outputDir);
// Check if grammar file exists
try {
await access(grammarFile);
} catch {
throw new Error(`Grammar file not found: ${grammarFile}`);
}
// Ensure output directory exists
await mkdir(outputDir, { recursive: true });
// Build ANTLR command arguments
// eslint-disable-next-line @cspell/spellchecker
const args = ['antlr-ng', `-Dlanguage=${grammarConfig.language}`];
if (grammarConfig.generateVisitor) {
args.push('--generate-visitor');
}
if (grammarConfig.generateListener) {
args.push('--generate-listener');
}
args.push('-o', `"${outputDir}"`, `"${grammarFile}"`);
const command = `npx ${args.join(' ')}`;
try {
await execAsync(command);
console.log(`Generated ANTLR files for ${grammarConfig.id}`);
} catch (error) {
console.error(`Failed to generate ANTLR files for ${grammarConfig.id}:`);
throw error;
}
}
// CLI interface
if (import.meta.url === `file://${process.argv[1]}`) {
const configFile = process.argv[2] || './packages/parser/antlr-config.json';
try {
await generateFromConfig(configFile);
console.log('ANTLR generation completed successfully!');
} catch (error) {
console.error('ANTLR generation failed:', error.message);
}
}

View File

@@ -1,5 +0,0 @@
import { generateFromConfig } from './antlr-cli.js';
export async function generateAntlr() {
await generateFromConfig('./packages/parser/antlr-config.json');
}

View File

@@ -28,7 +28,6 @@ const MERMAID_CONFIG_DIAGRAM_KEYS = [
'packet',
'architecture',
'radar',
'usecase',
] as const;
/**

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Prevent HTML tags from being escaped in sandbox label rendering

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Support edge animation in hand drawn look

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Resolved parsing error where direction TD was not recognized within subgraphs

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix(treemap): Fixed treemap classDef style application to properly apply user-defined styles

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Correct viewBox casing and make SVGs responsive

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Improve participant parsing and prevent recursive loops on invalid syntax

View File

@@ -1,5 +0,0 @@
---
'mermaid': patch
---
chore: Fix mindmap rendering in docs and apply tidytree layout

View File

@@ -1,5 +0,0 @@
---
'mermaid': patch
---
fix: Ensure edge label color is applied when using classDef with edge IDs

View File

@@ -1,5 +0,0 @@
---
'mermaid': patch
---
fix: Resolve gantt chart crash due to invalid array length

View File

@@ -1,5 +0,0 @@
---
'mermaid': minor
---
feat: Add IDs in architecture diagrams

View File

@@ -1,9 +0,0 @@
---
'mermaid': patch
---
chore: revert marked dependency from ^15.0.7 to ^16.0.0
- Reverted marked package version to ^16.0.0 for better compatibility
- This is a dependency update that maintains API compatibility
- All tests pass with the updated version

View File

@@ -0,0 +1,5 @@
---
'mermaid': minor
---
feat: allow to put notes in namespaces on classDiagram

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Support ComponentQueue_Ext to prevent parsing error

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Mindmap rendering issue when the number of Level 2 nodes exceeds 11

View File

@@ -1,3 +1,5 @@
!viewbox
# It should be viewBox
# This file contains coding related terms
ALPHANUM
antiscript
@@ -143,9 +145,6 @@ typeof
typestr
unshift
urlsafe
usecase
Usecase
USECASE
verifymethod
VERIFYMTHD
WARN_DOCSDIR_DOESNT_MATCH

View File

@@ -64,6 +64,7 @@ rscratch
shiki
Slidev
sparkline
speccharts
sphinxcontrib
ssim
stylis

View File

@@ -4,7 +4,6 @@ import { packageOptions } from '../.build/common.js';
import { generateLangium } from '../.build/generateLangium.js';
import type { MermaidBuildOptions } from './util.js';
import { defaultOptions, getBuildConfig } from './util.js';
import { generateAntlr } from '../.build/generateAntlr.js';
const shouldVisualize = process.argv.includes('--visualize');
@@ -96,7 +95,6 @@ const buildTinyMermaid = async () => {
const main = async () => {
await generateLangium();
await generateAntlr();
await mkdir('stats', { recursive: true });
const packageNames = Object.keys(packageOptions) as (keyof typeof packageOptions)[];
// it should build `parser` before `mermaid` because it's a dependency

View File

@@ -4,7 +4,6 @@ import cors from 'cors';
import { context } from 'esbuild';
import type { Request, Response } from 'express';
import express from 'express';
import { execSync } from 'child_process';
import { packageOptions } from '../.build/common.js';
import { generateLangium } from '../.build/generateLangium.js';
import { defaultOptions, getBuildConfig } from './util.js';
@@ -65,28 +64,6 @@ function eventsHandler(request: Request, response: Response) {
}
let timeoutID: NodeJS.Timeout | undefined = undefined;
let isGeneratingAntlr = false;
/**
* Generate ANTLR parser files from grammar files
*/
function generateAntlr(): void {
if (isGeneratingAntlr) {
console.log('⏳ ANTLR generation already in progress, skipping...');
return;
}
try {
isGeneratingAntlr = true;
console.log('🎯 ANTLR: Generating parser files...');
execSync('tsx scripts/antlr-generate.mts', { stdio: 'inherit' });
console.log('✅ ANTLR: Parser files generated successfully\n');
} catch (error) {
console.error('❌ ANTLR: Failed to generate parser files:', error);
} finally {
isGeneratingAntlr = false;
}
}
/**
* Debounce file change events to avoid rebuilding multiple times.
@@ -112,7 +89,7 @@ async function createServer() {
handleFileChange();
const app = express();
chokidar
.watch('**/src/**/*.{js,ts,g4,langium,yaml,json}', {
.watch('**/src/**/*.{js,ts,langium,yaml,json}', {
ignoreInitial: true,
ignored: [/node_modules/, /dist/, /docs/, /coverage/],
})
@@ -126,9 +103,6 @@ async function createServer() {
if (path.endsWith('.langium')) {
await generateLangium();
}
if (path.endsWith('.g4')) {
generateAntlr();
}
handleFileChange();
});

View File

@@ -71,6 +71,9 @@ export const getBuildConfig = (options: MermaidBuildOptions): BuildOptions => {
const external: string[] = ['require', 'fs', 'path'];
const outFileName = getFileName(name, options);
const { dependencies, version } = JSON.parse(
readFileSync(resolve(__dirname, `../packages/${packageName}/package.json`), 'utf-8')
);
const output: BuildOptions = buildOptions({
...rest,
absWorkingDir: resolve(__dirname, `../packages/${packageName}`),
@@ -82,15 +85,13 @@ export const getBuildConfig = (options: MermaidBuildOptions): BuildOptions => {
chunkNames: `chunks/${outFileName}/[name]-[hash]`,
define: {
// This needs to be stringified for esbuild
includeLargeFeatures: `${includeLargeFeatures}`,
'injected.includeLargeFeatures': `${includeLargeFeatures}`,
'injected.version': `'${version}'`,
'import.meta.vitest': 'undefined',
},
});
if (core) {
const { dependencies } = JSON.parse(
readFileSync(resolve(__dirname, `../packages/${packageName}/package.json`), 'utf-8')
);
// Core build is used to generate file without bundled dependencies.
// This is used by downstream projects to bundle dependencies themselves.
// Ignore dependencies and any dependencies of dependencies

View File

@@ -58,7 +58,7 @@ jobs:
echo "EOF" >> $GITHUB_OUTPUT
- name: Commit and create pull request
uses: peter-evans/create-pull-request@915d841dae6a4f191bb78faf61a257411d7be4d2
uses: peter-evans/create-pull-request@0edc001d28a2959cd7a6b505629f1d82f0a6e67d
with:
add-paths: |
cypress/timings.json

View File

@@ -42,5 +42,4 @@ jobs:
publish: pnpm changeset:publish
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
NPM_CONFIG_PROVENANCE: true

View File

@@ -20,7 +20,7 @@ jobs:
with:
persist-credentials: false
- name: Run analysis
uses: ossf/scorecard-action@05b42c624433fc40578a4040d5cf5e36ddca8cde # v2.4.2
uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3
with:
results_file: results.sarif
results_format: sarif

View File

@@ -1,7 +1,7 @@
name: Validate pnpm-lock.yaml
on:
pull_request:
pull_request_target:
paths:
- 'pnpm-lock.yaml'
- '**/package.json'
@@ -15,13 +15,8 @@ jobs:
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- name: Validate pnpm-lock.yaml entries
id: validate # give this step an ID so we can reference its outputs
@@ -55,16 +50,41 @@ jobs:
exit 1
fi
- name: Find existing lockfile validation comment
if: always()
uses: peter-evans/find-comment@v3
id: find-comment
with:
issue-number: ${{ github.event.pull_request.number }}
comment-author: 'github-actions[bot]'
body-includes: 'Lockfile Validation Failed'
- name: Comment on PR if validation failed
if: failure()
uses: peter-evans/create-or-update-comment@v4
uses: peter-evans/create-or-update-comment@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
issue-number: ${{ github.event.pull_request.number }}
comment-id: ${{ steps.find-comment.outputs.comment-id }}
edit-mode: replace
body: |
❌ **Lockfile Validation Failed**
The following issue(s) were detected:
${{ steps.validate.outputs.errors }}
Please address these and push an update.
_Posted automatically by GitHub Actions_
- name: Delete comment if validation passed
if: success() && steps.find-comment.outputs.comment-id != ''
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
await github.rest.issues.deleteComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: ${{ steps.find-comment.outputs.comment-id }},
});

5
.gitignore vendored
View File

@@ -51,8 +51,5 @@ demos/dev/**
tsx-0/**
vite.config.ts.timestamp-*
# autogenereated by langium-cli and antlr-cli
# autogenereated by langium-cli
generated/
# autogenereated by antlr-cli
.antlr/

View File

@@ -10,7 +10,6 @@ import type { TemplateType } from 'rollup-plugin-visualizer/dist/plugin/template
import istanbul from 'vite-plugin-istanbul';
import { packageOptions } from '../.build/common.js';
import { generateLangium } from '../.build/generateLangium.js';
import { generateAntlr } from '../.build/generateAntlr.js';
const visualize = process.argv.includes('--visualize');
const watch = process.argv.includes('--watch');
@@ -79,6 +78,8 @@ export const getBuildConfig = ({ minify, core, watch, entryName }: BuildOptions)
},
define: {
'import.meta.vitest': 'undefined',
'injected.includeLargeFeatures': 'true',
'injected.version': `'0.0.0'`,
},
resolve: {
extensions: [],
@@ -95,10 +96,6 @@ export const getBuildConfig = ({ minify, core, watch, entryName }: BuildOptions)
}),
...visualizerOptions(packageName, core),
],
define: {
// Needs to be string
includeLargeFeatures: 'true',
},
};
if (watch && config.build) {
@@ -124,7 +121,6 @@ const main = async () => {
};
await generateLangium();
await generateAntlr();
if (watch) {
await build(getBuildConfig({ minify: false, watch, core: false, entryName: 'parser' }));

View File

@@ -5,7 +5,7 @@ USER 0:0
RUN corepack enable \
&& corepack enable pnpm
RUN apk add --no-cache git~=2.43.4 \
RUN apk add --no-cache git~=2.43 \
&& git config --add --system safe.directory /mermaid
ENV NODE_OPTIONS="--max_old_space_size=8192"

View File

@@ -6,6 +6,7 @@ interface CypressConfig {
listUrl?: boolean;
listId?: string;
name?: string;
screenshot?: boolean;
}
type CypressMermaidConfig = MermaidConfig & CypressConfig;
@@ -90,20 +91,33 @@ export const renderGraph = (
export const openURLAndVerifyRendering = (
url: string,
options: CypressMermaidConfig,
{ screenshot = true, ...options }: CypressMermaidConfig,
validation?: any
): void => {
const name: string = (options.name ?? cy.state('runnable').fullTitle()).replace(/\s+/g, '-');
cy.visit(url);
cy.window().should('have.property', 'rendered', true);
cy.get('svg').should('be.visible');
if (validation) {
cy.get('svg').should(validation);
// Handle sandbox mode where SVG is inside an iframe
if (options.securityLevel === 'sandbox') {
cy.get('iframe').should('be.visible');
if (validation) {
cy.get('iframe').should(validation);
}
} else {
cy.get('svg').should('be.visible');
// cspell:ignore viewbox
cy.get('svg').should('not.have.attr', 'viewbox');
if (validation) {
cy.get('svg').should(validation);
}
}
verifyScreenshot(name);
if (screenshot) {
verifyScreenshot(name);
}
};
export const verifyScreenshot = (name: string): void => {

View File

@@ -114,4 +114,28 @@ describe('C4 diagram', () => {
{}
);
});
it('C4.6 should render C4Context diagram with ComponentQueue_Ext', () => {
imgSnapshotTest(
`
C4Context
title System Context diagram with ComponentQueue_Ext
Enterprise_Boundary(b0, "BankBoundary0") {
Person(customerA, "Banking Customer A", "A customer of the bank, with personal bank accounts.")
System(SystemAA, "Internet Banking System", "Allows customers to view information about their bank accounts, and make payments.")
Enterprise_Boundary(b1, "BankBoundary") {
ComponentQueue_Ext(msgQueue, "Message Queue", "RabbitMQ", "External message queue system for processing banking transactions")
System_Ext(SystemC, "E-mail system", "The internal Microsoft Exchange e-mail system.")
}
}
BiRel(customerA, SystemAA, "Uses")
Rel(SystemAA, msgQueue, "Sends messages to")
Rel(SystemAA, SystemC, "Sends e-mails", "SMTP")
`,
{}
);
});
});

View File

@@ -562,6 +562,20 @@ class C13["With Città foreign language"]
`
);
});
it('should add notes in namespaces', function () {
imgSnapshotTest(
`
classDiagram
note "This is a outer note"
note for C1 "This is a outer note for C1"
namespace Namespace1 {
note "This is a inner note"
note for C1 "This is a inner note for C1"
class C1
}
`
);
});
it('should render a simple class diagram with no members', () => {
imgSnapshotTest(
`

View File

@@ -709,6 +709,20 @@ class C13["With Città foreign language"]
`
);
});
it('should add notes in namespaces', function () {
imgSnapshotTest(
`
classDiagram
note "This is a outer note"
note for C1 "This is a outer note for C1"
namespace Namespace1 {
note "This is a inner note"
note for C1 "This is a inner note for C1"
class C1
}
`
);
});
it('should render a simple class diagram with no members', () => {
imgSnapshotTest(
`

View File

@@ -445,7 +445,7 @@ ORDER ||--|{ LINE-ITEM : contains
{ logLevel: 1 }
);
});
it('should render ER diagram with numeric entity names and attributes', () => {
it('should render ER diagram with standalone numeric entities', () => {
imgSnapshotTest(
`erDiagram
PRODUCT ||--o{ ORDER-ITEM : has

View File

@@ -1029,4 +1029,19 @@ graph TD
}
);
});
it('FDH49: should add edge animation', () => {
renderGraph(
`
flowchart TD
A(["Start"]) L_A_B_0@--> B{"Decision"}
B --> C["Option A"] & D["Option B"]
style C stroke-width:4px,stroke-dasharray: 5
L_A_B_0@{ animation: slow }
L_B_D_0@{ animation: fast }`,
{ look: 'handDrawn', screenshot: false }
);
cy.get('path#L_A_B_0').should('have.class', 'edge-animation-slow');
cy.get('path#L_B_D_0').should('have.class', 'edge-animation-fast');
});
});

View File

@@ -79,6 +79,18 @@ describe('Flowchart v2', () => {
{ htmlLabels: true, flowchart: { htmlLabels: true }, securityLevel: 'loose' }
);
});
it('6a: should render complex HTML in labels with sandbox security', () => {
imgSnapshotTest(
`flowchart TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
C -->|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
`,
{ securityLevel: 'sandbox', flowchart: { htmlLabels: true } }
);
});
it('7: should render a flowchart when useMaxWidth is true (default)', () => {
renderGraph(
`flowchart TD

View File

@@ -774,6 +774,21 @@ describe('Graph', () => {
expect(svg).to.not.have.attr('style');
});
});
it('40: should add edge animation', () => {
renderGraph(
`
flowchart TD
A(["Start"]) L_A_B_0@--> B{"Decision"}
B --> C["Option A"] & D["Option B"]
style C stroke-width:4px,stroke-dasharray: 5
L_A_B_0@{ animation: slow }
L_B_D_0@{ animation: fast }`,
{ screenshot: false }
);
// Verify animation classes are applied to both edges
cy.get('path#L_A_B_0').should('have.class', 'edge-animation-slow');
cy.get('path#L_B_D_0').should('have.class', 'edge-animation-fast');
});
it('58: handle styling with style expressions', () => {
imgSnapshotTest(
`
@@ -973,4 +988,19 @@ graph TD
}
);
});
it('70: should render a subgraph with direction TD', () => {
imgSnapshotTest(
`
flowchart LR
subgraph A
direction TD
a --> b
end
`,
{
fontFamily: 'courier',
}
);
});
});

View File

@@ -247,5 +247,31 @@ root
);
});
});
describe('Level 2 nodes exceeding 11', () => {
it('should render all Level 2 nodes correctly when there are more than 11', () => {
imgSnapshotTest(
`mindmap
root
Node1
Node2
Node3
Node4
Node5
Node6
Node7
Node8
Node9
Node10
Node11
Node12
Node13
Node14
Node15`,
{},
undefined,
shouldHaveRoot
);
});
});
/* The end */
});

View File

@@ -1,425 +0,0 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('Usecase diagram', () => {
it('should render a simple usecase diagram with actors and use cases', () => {
imgSnapshotTest(
`
usecase
actor User
actor Admin
User --> Login
Admin --> "Manage Users"
User --> "View Profile"
`
);
});
it('should render usecase diagram with quoted actor names', () => {
imgSnapshotTest(
`usecase
actor "Customer Service"
actor "System Administrator"
"Customer Service" --> "Handle Tickets"
"System Administrator" --> "Manage System"
`
);
});
it('should render usecase diagram with different arrow types', () => {
imgSnapshotTest(
`usecase
actor User
actor Admin
User --> Login
Admin <-- Logout
User -- "View Data"
`
);
});
it('should render usecase diagram with edge labels', () => {
imgSnapshotTest(
`usecase
actor Developer
actor Manager
Developer --important--> "Write Code"
Manager --review--> "Code Review"
Developer --urgent--> Manager
`
);
});
it('should render usecase diagram with node ID syntax', () => {
imgSnapshotTest(
`usecase
actor User
User --> a(Login)
User --> b("View Profile")
User --> c("Update Settings")
`
);
});
it('should render usecase diagram with comma-separated actors', () => {
imgSnapshotTest(
`usecase
actor "Customer Service", "Technical Support", "Sales Team"
actor SystemAdmin
"Customer Service" --> "Handle Tickets"
"Technical Support" --> "Resolve Issues"
"Sales Team" --> "Process Orders"
SystemAdmin --> "Manage System"
`
);
});
it('should render usecase diagram with actor metadata', () => {
imgSnapshotTest(
`usecase
actor User@{ "type" : "primary", "icon" : "user" }
actor Admin@{ "type" : "secondary", "icon" : "admin" }
actor System@{ "type" : "hollow", "icon" : "system" }
User --> Login
Admin --> "Manage Users"
System --> "Process Data"
`
);
});
it('should render usecase diagram with system boundaries (rect type)', () => {
imgSnapshotTest(
`usecase
actor Admin, User
systemBoundary "Authentication"
Login
Logout
"Reset Password"
end
"Authentication"@{ type: rect }
Admin --> Login
User --> Login
User --> "Reset Password"
`
);
});
it('should render usecase diagram with system boundaries (package type)', () => {
imgSnapshotTest(
`usecase
actor Admin, User
systemBoundary "Authentication"
Login
Logout
"Reset Password"
end
"Authentication"@{ type: package }
Admin --> Login
User --> Login
User --> "Reset Password"
`
);
});
it('should render complex usecase diagram with all features', () => {
imgSnapshotTest(
`usecase
actor "Customer Service"@{ "type" : "primary", "icon" : "user" }
actor "System Admin"@{ "type" : "secondary", "icon" : "admin" }
actor "Database"@{ "type" : "hollow", "icon" : "database" }
systemBoundary "Customer Support System"
"Handle Tickets"
"View Customer Info"
end
"Customer Support System"@{ type: package }
systemBoundary "Administration"
"User Management"
"System Config"
end
"Customer Service" --priority--> "Handle Tickets"
"Customer Service" --> "View Customer Info"
"System Admin" --manage--> "User Management"
"System Admin" --> "System Config"
"Database" <-- "Handle Tickets"
"Database" <-- "View Customer Info"
"Database" <-- "User Management"
`
);
});
it('should render usecase diagram with actor-to-actor relationships', () => {
imgSnapshotTest(
`usecase
actor Manager
actor Developer
actor Tester
Manager --supervises--> Developer
Manager --coordinates--> Tester
Developer --collaborates--> Tester
Developer --> "Write Code"
Tester --> "Test Code"
Manager --> "Review Progress"
`
);
});
it('should render usecase diagram with mixed relationship types', () => {
imgSnapshotTest(
`usecase
actor User
actor Admin
User --> "Basic Login"
Admin --> "Advanced Login"
User --includes--> "View Profile"
Admin --extends--> "Manage Profiles"
"Basic Login" <-- "Advanced Login"
`
);
});
it('should render usecase diagram with long labels and text wrapping', () => {
imgSnapshotTest(
`usecase
actor "Customer Service Representative"
actor "System Administrator with Extended Privileges"
"Customer Service Representative" --Process--> "Handle Complex Customer Support Tickets"
"System Administrator with Extended Privileges" --> "Manage System Configuration and User Permissions"
`
);
});
it('should render usecase diagram with special characters in names', () => {
imgSnapshotTest(
`usecase
actor "User@Company.com"
actor "Admin (Level-1)"
"User@Company.com" --> a("Login & Authenticate")
"Admin (Level-1)" --> b("Manage Users & Permissions")
`
);
});
it('should render usecase diagram when useMaxWidth is true (default)', () => {
renderGraph(
`usecase
actor User
actor Admin
User --> Login
Admin --> "Manage System"
User --> "View Profile"
`,
{ usecase: { useMaxWidth: true } }
);
cy.get('svg').should((svg) => {
expect(svg).to.have.attr('width', '100%');
const style = svg.attr('style');
expect(style).to.match(/^max-width: [\d.]+px;$/);
});
});
it('should render usecase diagram when useMaxWidth is false', () => {
renderGraph(
`usecase
actor User
actor Admin
User --> Login
Admin --> "Manage System"
`,
{ usecase: { useMaxWidth: false } }
);
cy.get('svg').should((svg) => {
const width = parseFloat(svg.attr('width'));
expect(width).to.be.greaterThan(200);
expect(svg).to.not.have.attr('style');
});
});
it('should render empty usecase diagram', () => {
imgSnapshotTest(`usecase`);
});
it('should render usecase diagram with only actors', () => {
imgSnapshotTest(
`usecase
actor User
actor Admin
actor Guest
`
);
});
it('should render usecase diagram with implicit use case creation', () => {
imgSnapshotTest(
`usecase
actor User
User --> Login
User --> Register
User --> "Forgot Password"
`
);
});
it('should render usecase diagram with nested system boundaries', () => {
imgSnapshotTest(
`usecase
actor User
actor Admin
systemBoundary "Main System"
Login
Logout
"Create User"
"Delete User"
end
User --> Login
User --> Logout
Admin --> "Create User"
Admin --> "Delete User"
`
);
});
it('should render usecase diagram with multiple edge labels on same relationship', () => {
imgSnapshotTest(
`usecase
actor Developer
actor Manager
Developer --"code review"--> Manager
Developer --"status update"--> Manager
Manager --"feedback"--> Developer
Manager --"approval"--> Developer
`
);
});
it('should render usecase diagram with various actor icon types', () => {
imgSnapshotTest(
`usecase
actor User@{ "icon": "user" }
actor Admin@{ "icon": "admin" }
actor Database@{ "icon": "database" }
actor API@{ "icon": "api" }
actor Mobile@{ "icon": "mobile" }
actor Web@{ "icon": "web" }
User --> "Access System"
Admin --> "Manage System"
Database --> "Store Data"
API --> "Provide Services"
Mobile --> "Mobile Access"
Web --> "Web Access"
`
);
});
it('should render usecase diagram with mixed arrow directions and labels', () => {
imgSnapshotTest(
`usecase
actor User
actor System
actor Admin
User --request--> System
System --response--> User
System <--monitor-- Admin
Admin --configure--> System
User -- "direct access" -- Admin
`
);
});
it('should render usecase diagram with boundary-less use cases', () => {
imgSnapshotTest(
`usecase
actor User
actor Admin
systemBoundary "Secure Area"
"Admin Panel"
"User Management"
end
User --> "Public Login"
User --> "Guest Access"
Admin --> "Public Login"
Admin --> "Admin Panel"
Admin --> "User Management"
`
);
});
it('should render usecase diagram with complex metadata combinations', () => {
imgSnapshotTest(
`usecase
actor "Primary User"@{ "type": "primary", "icon": "user", "fillColor": "lightblue" }
actor "Secondary User"@{ "type": "secondary", "icon": "client", "strokeColor": "red" }
actor "System Service"@{ "type": "hollow", "icon": "service", "strokeWidth": "3" }
"Primary User" --"high priority"--> a("Critical Process")
"Secondary User" --"low priority"--> b("Background Task")
"System Service" --"automated"--> c("System Maintenance")
`
);
});
it('should render usecase diagram with Unicode characters', () => {
imgSnapshotTest(
`usecase
actor "用户"@{ "icon": "user" }
actor "管理员"@{ "icon": "admin" }
"用户" --"登录"--> "系统访问"
"管理员" --"管理"--> "用户管理"
"用户" --> "数据查看"
`
);
});
it('should render large usecase diagram with many elements', () => {
imgSnapshotTest(
`usecase
actor User1, User2, User3, User4
actor Admin1, Admin2
actor System1@{ "icon": "system" }
actor System2@{ "icon": "database" }
systemBoundary "Module A"
"Feature A1"
"Feature A2"
"Admin A1"
end
"Module A"@{ type: package }
systemBoundary "Module B"
"Feature B1"
"Feature B2"
"Admin B1"
end
User1 --> "Feature A1"
User2 --> "Feature A2"
Admin1 --> "Admin A1"
User3 --> "Feature B1"
User4 --> "Feature B2"
Admin2 --> "Admin B1"
System1 <-- "Feature A1"
System1 <-- "Feature B1"
System2 <-- "Admin A1"
System2 <-- "Admin B1"
User1 --"collaborates"--> User2
Admin1 --"supervises"--> Admin2
`
);
});
});

View File

@@ -603,6 +603,10 @@
</div>
<div class="test">
<pre class="mermaid">
---
config:
theme: dark
---
classDiagram
test ()--() test2
</pre>

View File

@@ -2,227 +2,227 @@
"durations": [
{
"spec": "cypress/integration/other/configuration.spec.js",
"duration": 5841
"duration": 6099
},
{
"spec": "cypress/integration/other/external-diagrams.spec.js",
"duration": 2138
"duration": 2236
},
{
"spec": "cypress/integration/other/ghsa.spec.js",
"duration": 3370
"duration": 3405
},
{
"spec": "cypress/integration/other/iife.spec.js",
"duration": 2052
"duration": 2176
},
{
"spec": "cypress/integration/other/interaction.spec.js",
"duration": 12243
"duration": 12300
},
{
"spec": "cypress/integration/other/rerender.spec.js",
"duration": 2065
"duration": 2089
},
{
"spec": "cypress/integration/other/xss.spec.js",
"duration": 31288
"duration": 32033
},
{
"spec": "cypress/integration/rendering/appli.spec.js",
"duration": 3421
"duration": 3672
},
{
"spec": "cypress/integration/rendering/architecture.spec.ts",
"duration": 97
"duration": 103
},
{
"spec": "cypress/integration/rendering/block.spec.js",
"duration": 18500
"duration": 18135
},
{
"spec": "cypress/integration/rendering/c4.spec.js",
"duration": 5793
"duration": 5661
},
{
"spec": "cypress/integration/rendering/classDiagram-elk-v3.spec.js",
"duration": 40966
"duration": 41456
},
{
"spec": "cypress/integration/rendering/classDiagram-handDrawn-v3.spec.js",
"duration": 39176
"duration": 38910
},
{
"spec": "cypress/integration/rendering/classDiagram-v2.spec.js",
"duration": 23468
"duration": 24120
},
{
"spec": "cypress/integration/rendering/classDiagram-v3.spec.js",
"duration": 38291
"duration": 38454
},
{
"spec": "cypress/integration/rendering/classDiagram.spec.js",
"duration": 16949
"duration": 17099
},
{
"spec": "cypress/integration/rendering/conf-and-directives.spec.js",
"duration": 9480
"duration": 9844
},
{
"spec": "cypress/integration/rendering/current.spec.js",
"duration": 2753
"duration": 2951
},
{
"spec": "cypress/integration/rendering/erDiagram-unified.spec.js",
"duration": 88028
"duration": 90081
},
{
"spec": "cypress/integration/rendering/erDiagram.spec.js",
"duration": 15615
"duration": 19496
},
{
"spec": "cypress/integration/rendering/errorDiagram.spec.js",
"duration": 3706
"duration": 3829
},
{
"spec": "cypress/integration/rendering/flowchart-elk.spec.js",
"duration": 43905
"duration": 42517
},
{
"spec": "cypress/integration/rendering/flowchart-handDrawn.spec.js",
"duration": 31217
"duration": 31541
},
{
"spec": "cypress/integration/rendering/flowchart-icon.spec.js",
"duration": 7531
"duration": 7749
},
{
"spec": "cypress/integration/rendering/flowchart-shape-alias.spec.ts",
"duration": 25423
"duration": 25230
},
{
"spec": "cypress/integration/rendering/flowchart-v2.spec.js",
"duration": 49664
"duration": 49359
},
{
"spec": "cypress/integration/rendering/flowchart.spec.js",
"duration": 32525
"duration": 33028
},
{
"spec": "cypress/integration/rendering/gantt.spec.js",
"duration": 20915
"duration": 22271
},
{
"spec": "cypress/integration/rendering/gitGraph.spec.js",
"duration": 53556
"duration": 51837
},
{
"spec": "cypress/integration/rendering/iconShape.spec.ts",
"duration": 283038
"duration": 285060
},
{
"spec": "cypress/integration/rendering/imageShape.spec.ts",
"duration": 59434
"duration": 59517
},
{
"spec": "cypress/integration/rendering/info.spec.ts",
"duration": 3101
"duration": 3501
},
{
"spec": "cypress/integration/rendering/journey.spec.js",
"duration": 7099
"duration": 7405
},
{
"spec": "cypress/integration/rendering/kanban.spec.ts",
"duration": 7567
"duration": 7975
},
{
"spec": "cypress/integration/rendering/katex.spec.js",
"duration": 3817
"duration": 4312
},
{
"spec": "cypress/integration/rendering/marker_unique_id.spec.js",
"duration": 2624
"duration": 2630
},
{
"spec": "cypress/integration/rendering/mindmap-tidy-tree.spec.js",
"duration": 4246
"duration": 4541
},
{
"spec": "cypress/integration/rendering/mindmap.spec.ts",
"duration": 11967
"duration": 12134
},
{
"spec": "cypress/integration/rendering/newShapes.spec.ts",
"duration": 151914
"duration": 151160
},
{
"spec": "cypress/integration/rendering/oldShapes.spec.ts",
"duration": 116698
"duration": 118044
},
{
"spec": "cypress/integration/rendering/packet.spec.ts",
"duration": 4967
"duration": 5166
},
{
"spec": "cypress/integration/rendering/pie.spec.ts",
"duration": 6700
"duration": 7074
},
{
"spec": "cypress/integration/rendering/quadrantChart.spec.js",
"duration": 8963
"duration": 9518
},
{
"spec": "cypress/integration/rendering/radar.spec.js",
"duration": 5540
"duration": 5846
},
{
"spec": "cypress/integration/rendering/requirement.spec.js",
"duration": 2782
"duration": 3089
},
{
"spec": "cypress/integration/rendering/requirementDiagram-unified.spec.js",
"duration": 54797
"duration": 55361
},
{
"spec": "cypress/integration/rendering/sankey.spec.ts",
"duration": 6914
"duration": 7236
},
{
"spec": "cypress/integration/rendering/sequencediagram-v2.spec.js",
"duration": 20481
"duration": 26057
},
{
"spec": "cypress/integration/rendering/sequencediagram.spec.js",
"duration": 38490
"duration": 48401
},
{
"spec": "cypress/integration/rendering/stateDiagram-v2.spec.js",
"duration": 30766
"duration": 30364
},
{
"spec": "cypress/integration/rendering/stateDiagram.spec.js",
"duration": 16705
"duration": 16862
},
{
"spec": "cypress/integration/rendering/theme.spec.js",
"duration": 30928
"duration": 30553
},
{
"spec": "cypress/integration/rendering/timeline.spec.ts",
"duration": 8424
"duration": 8962
},
{
"spec": "cypress/integration/rendering/treemap.spec.ts",
"duration": 12533
"duration": 12486
},
{
"spec": "cypress/integration/rendering/xyChart.spec.js",
"duration": 21197
"duration": 21718
},
{
"spec": "cypress/integration/rendering/zenuml.spec.js",
"duration": 3455
"duration": 3882
}
]
}

View File

@@ -184,6 +184,7 @@
}
Admin --> Report : generates
</pre>
<hr />
<pre class="mermaid">
classDiagram
namespace Company.Project.Module {
@@ -240,6 +241,20 @@
Bike --> Square : "Logo Shape"
</pre>
<hr />
<pre class="mermaid">
classDiagram
note "This is a outer note"
note for Class1 "This is a outer note for Class1"
namespace ns {
note "This is a inner note"
note for Class1 "This is a inner note for Class1"
class Class1
class Class2
}
</pre>
<hr />
<script type="module">
import mermaid from './mermaid.esm.mjs';
mermaid.initialize({

View File

@@ -1,234 +0,0 @@
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet" />
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<link
href="https://cdn.jsdelivr.net/npm/@mdi/font@6.9.96/css/materialdesignicons.min.css"
rel="stylesheet"
/>
<link
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"
rel="stylesheet"
/>
<link
href="https://fonts.googleapis.com/css?family=Noto+Sans+SC&display=swap"
rel="stylesheet"
/>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Kalam:wght@300;400;700&display=swap"
rel="stylesheet"
/>
<link
href="https://fonts.googleapis.com/css2?family=Caveat:wght@400..700&family=Kalam:wght@300;400;700&family=Rubik+Mono+One&display=swap"
rel="stylesheet"
/>
<link
href="https://fonts.googleapis.com/css2?family=Kalam:wght@300;400;700&family=Rubik+Mono+One&display=swap"
rel="stylesheet"
/>
<link
href="https://fonts.googleapis.com/css2?family=Recursive:wght@300..1000&display=swap"
rel="stylesheet"
/>
<style>
.recursive-500 {
font-family: 'Recursive', serif;
font-optical-sizing: auto;
font-weight: 500;
font-style: normal;
font-variation-settings:
'slnt' 0,
'CASL' 0,
'CRSV' 0.5,
'MONO' 0;
}
body {
/* background: rgb(221, 208, 208); */
/* background: #333; */
/* font-family: 'Arial'; */
font-family: 'Recursive', serif;
font-optical-sizing: auto;
font-weight: 500;
font-style: normal;
font-variation-settings:
'slnt' 0,
'CASL' 0,
'CRSV' 0.5,
'MONO' 0;
/* color: white; */
/* font-size: 18px !important; */
}
.gridify.tiny {
background-image:
linear-gradient(transparent 11px, rgba(220, 220, 200, 0.8) 12px, transparent 12px),
linear-gradient(90deg, transparent 11px, rgba(220, 220, 200, 0.8) 12px, transparent 12px);
background-size:
100% 12px,
12px 100%;
}
.gridify.dots {
background-image: radial-gradient(
circle at center,
rgba(220, 220, 200, 0.8) 1px,
transparent 1px
);
background-size: 24px 24px;
}
h1 {
color: grey;
}
.mermaid2 {
display: none;
}
.mermaid svg {
font-size: 16px !important;
font-family: 'Recursive', serif;
font-optical-sizing: auto;
font-weight: 500;
font-style: normal;
font-variation-settings:
'slnt' 0,
'CASL' 0,
'CRSV' 0.5,
'MONO' 0;
}
pre {
width: 100%;
/*box-shadow: 4px 4px 0px 0px #0000000F;*/
}
</style>
</head>
<body class="gridify dots">
<p class="mb-20">Test Diagram</p>
<div class="w-full h-64">
<pre id="diagram4" class="mermaid">
usecase
direction LR
actor User1, User2, User3, User4
actor Admin1, Admin2
actor System1@{ "icon": "bell" }
actor System2@{ "icon": "database" }
systemBoundary "Module A"
"Feature A1"
"Feature A2"
"Admin A1"
end
"Module A"@{ type: package }
systemBoundary "Module B"
"Feature B1"
"Feature B2"
"Admin B1"
end
User1 --important--> "Feature A1"
User2 --> "Feature A2"
Admin1 --> "Admin A1"
User3 --> "Feature B1"
User4 --> "Feature B2"
Admin2 --> "Admin B1"
System1 <-- "Feature A1"
System1 <-- "Feature B1"
System2 <-- "Admin A1"
System2 <-- "Admin B1"
User1 --"collaborates"--> User2
Admin1 --"supervises"--> Admin2
</pre
>
</div>
<script type="module">
import mermaid from './mermaid.esm.mjs';
import layouts from './mermaid-layout-elk.esm.mjs';
const staticBellIconPack = {
prefix: 'fa6-regular',
icons: {
bell: {
body: '<path fill="currentColor" d="M224 0c-17.7 0-32 14.3-32 32v19.2C119 66 64 130.6 64 208v25.4c0 45.4-15.5 89.5-43.8 124.9L5.3 377c-5.8 7.2-6.9 17.1-2.9 25.4S14.8 416 24 416h400c9.2 0 17.6-5.3 21.6-13.6s2.9-18.2-2.9-25.4l-14.9-18.6c-28.3-35.5-43.8-79.6-43.8-125V208c0-77.4-55-142-128-156.8V32c0-17.7-14.3-32-32-32m0 96c61.9 0 112 50.1 112 112v25.4c0 47.9 13.9 94.6 39.7 134.6H72.3c25.8-40 39.7-86.7 39.7-134.6V208c0-61.9 50.1-112 112-112m64 352H160c0 17 6.7 33.3 18.7 45.3S207 512 224 512s33.3-6.7 45.3-18.7S288 465 288 448"/>',
width: 448,
},
},
width: 512,
height: 512,
};
mermaid.registerIconPacks([
{
name: 'logos',
loader: () =>
fetch('https://unpkg.com/@iconify-json/logos@1/icons.json').then((res) => res.json()),
},
{
name: 'fa',
loader: () =>
fetch('https://unpkg.com/@iconify-json/fa6-solid/icons.json').then((res) => res.json()),
},
]);
mermaid.registerLayoutLoaders(layouts);
mermaid.parseError = function (err, hash) {
console.error('Mermaid error: ', err);
};
window.callback = function () {
alert('A callback was triggered');
};
function callback() {
alert('It worked');
}
await mermaid.initialize({
startOnLoad: false,
theme: 'default',
// theme: 'forest',
// handDrawnSeed: 12,
// 'elk.nodePlacement.strategy': 'NETWORK_SIMPLEX',
layout: 'dagre',
// layout: 'elk',
// layout: 'fixed',
// htmlLabels: false,
flowchart: { titleTopMargin: 10 },
// fontFamily: 'Caveat',
// fontFamily: 'Kalam',
// fontFamily: 'courier',
fontFamily: 'Recursive',
sequence: {
actorFontFamily: 'courier',
noteFontFamily: 'courier',
messageFontFamily: 'courier',
},
kanban: {
htmlLabels: false,
},
fontSize: 16,
logLevel: 0,
securityLevel: 'loose',
callback,
});
// setTimeout(() => {
mermaid.init(undefined, document.querySelectorAll('.mermaid'));
// }, 1000);
mermaid.parseError = function (err, hash) {
console.error('In parse error:');
console.error(err);
};
</script>
</body>
</html>

View File

@@ -12,4 +12,4 @@
> `const` **configKeys**: `Set`<`string`>
Defined in: [packages/mermaid/src/defaultConfig.ts:295](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/defaultConfig.ts#L295)
Defined in: [packages/mermaid/src/defaultConfig.ts:292](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/defaultConfig.ts#L292)

View File

@@ -105,7 +105,7 @@ You can set this attribute to base the seed on a static string.
> `optional` **dompurifyConfig**: `Config`
Defined in: [packages/mermaid/src/config.type.ts:214](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.type.ts#L214)
Defined in: [packages/mermaid/src/config.type.ts:213](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.type.ts#L213)
---
@@ -179,7 +179,7 @@ See <https://developer.mozilla.org/en-US/docs/Web/CSS/font-family>
> `optional` **fontSize**: `number`
Defined in: [packages/mermaid/src/config.type.ts:216](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.type.ts#L216)
Defined in: [packages/mermaid/src/config.type.ts:215](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.type.ts#L215)
---
@@ -292,7 +292,7 @@ Defines which main look to use for the diagram.
> `optional` **markdownAutoWrap**: `boolean`
Defined in: [packages/mermaid/src/config.type.ts:217](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.type.ts#L217)
Defined in: [packages/mermaid/src/config.type.ts:216](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.type.ts#L216)
---
@@ -424,7 +424,7 @@ Defined in: [packages/mermaid/src/config.type.ts:198](https://github.com/mermaid
> `optional` **suppressErrorRendering**: `boolean`
Defined in: [packages/mermaid/src/config.type.ts:223](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.type.ts#L223)
Defined in: [packages/mermaid/src/config.type.ts:222](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.type.ts#L222)
Suppresses inserting 'Syntax error' diagram in the DOM.
This is useful when you want to control how to handle syntax errors in your application.
@@ -466,19 +466,11 @@ Defined in: [packages/mermaid/src/config.type.ts:196](https://github.com/mermaid
---
### usecase?
> `optional` **usecase**: `UsecaseDiagramConfig`
Defined in: [packages/mermaid/src/config.type.ts:213](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.type.ts#L213)
---
### wrap?
> `optional` **wrap**: `boolean`
Defined in: [packages/mermaid/src/config.type.ts:215](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.type.ts#L215)
Defined in: [packages/mermaid/src/config.type.ts:214](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.type.ts#L214)
---

View File

@@ -57,6 +57,8 @@ To add an integration to this list, see the [Integrations - create page](./integ
- [GitHub Writer](https://github.com/ckeditor/github-writer)
- [SVG diagram generator](https://github.com/SimonKenyonShepard/mermaidjs-github-svg-generator)
- [GitLab](https://docs.gitlab.com/ee/user/markdown.html#diagrams-and-flowcharts) ✅
- [GNU Octave](https://octave.org/) ✅
- [octave_mermaid_js](https://github.com/CNOCTAVE/octave_mermaid_js) ✅
- [Mermaid Plugin for JetBrains IDEs](https://plugins.jetbrains.com/plugin/20146-mermaid)
- [MonsterWriter](https://www.monsterwriter.com/) ✅
- [Joplin](https://joplinapp.org) ✅
@@ -272,6 +274,7 @@ Communication tools and platforms
- [reveal.js-mermaid-plugin](https://github.com/ludwick/reveal.js-mermaid-plugin)
- [Reveal CK](https://github.com/jedcn/reveal-ck)
- [reveal-ck-mermaid-plugin](https://github.com/tmtm/reveal-ck-mermaid-plugin)
- [speccharts: Turn your test suites into specification diagrams](https://github.com/arnaudrenaud/speccharts)
- [Vitepress Plugin](https://github.com/sametcn99/vitepress-mermaid-renderer)
<!--- cspell:ignore Blazorade HueHive --->

View File

@@ -47,7 +47,7 @@ Try the Ultimate AI, Mermaid, and Visual Diagramming Suite by creating an accoun
## Plans
- **Free** - A free plan that includes three diagrams.
- **Free** - A free plan that includes six diagrams.
- **Pro** - A paid plan that includes unlimited diagrams, access to the collaboration feature, and more.

View File

@@ -21,7 +21,7 @@ title: Animal example
classDiagram
note "From Duck till Zebra"
Animal <|-- Duck
note for Duck "can fly\ncan swim\ncan dive\ncan help in debugging"
note for Duck "can fly<br>can swim<br>can dive<br>can help in debugging"
Animal <|-- Fish
Animal <|-- Zebra
Animal : +int age
@@ -50,7 +50,7 @@ title: Animal example
classDiagram
note "From Duck till Zebra"
Animal <|-- Duck
note for Duck "can fly\ncan swim\ncan dive\ncan help in debugging"
note for Duck "can fly<br>can swim<br>can dive<br>can help in debugging"
Animal <|-- Fish
Animal <|-- Zebra
Animal : +int age

View File

@@ -344,7 +344,6 @@ Below is a comprehensive list of the newly introduced shapes and their correspon
| Display | Curved Trapezoid | `curv-trap` | Represents a display | `curved-trapezoid`, `display` |
| Divided Process | Divided Rectangle | `div-rect` | Divided process shape | `div-proc`, `divided-process`, `divided-rectangle` |
| Document | Document | `doc` | Represents a document | `doc`, `document` |
| Ellipse | Ellipse | `ellipse` | Ellipse shape | `oval` |
| Event | Rounded Rectangle | `rounded` | Represents an event | `event` |
| Extract | Triangle | `tri` | Extraction process | `extract`, `triangle` |
| Fork/Join | Filled Rectangle | `fork` | Fork or join in process flow | `join` |

View File

@@ -15,10 +15,8 @@
"git graph"
],
"scripts": {
"build": "pnpm antlr:generate && pnpm build:esbuild && pnpm build:types",
"build": "pnpm build:esbuild && pnpm build:types",
"build:esbuild": "pnpm run -r clean && tsx .esbuild/build.ts",
"antlr:generate": "tsx scripts/antlr-generate.mts",
"antlr:watch": "tsx scripts/antlr-watch.mts",
"build:mermaid": "pnpm build:esbuild --mermaid",
"build:viz": "pnpm build:esbuild --visualize",
"build:types": "pnpm --filter mermaid types:build-config && tsx .build/types.ts",
@@ -65,21 +63,21 @@
]
},
"devDependencies": {
"@applitools/eyes-cypress": "^3.55.2",
"@argos-ci/cypress": "^6.1.3",
"@applitools/eyes-cypress": "^3.56.3",
"@argos-ci/cypress": "^6.2.1",
"@changesets/changelog-github": "^0.5.1",
"@changesets/cli": "^2.29.7",
"@cspell/eslint-plugin": "^8.19.4",
"@cypress/code-coverage": "^3.14.6",
"@cspell/eslint-plugin": "^9.3.0",
"@cypress/code-coverage": "^3.14.7",
"@eslint/js": "^9.26.0",
"@rollup/plugin-typescript": "^12.1.4",
"@types/cors": "^2.8.19",
"@types/express": "^5.0.3",
"@types/express": "^5.0.5",
"@types/js-yaml": "^4.0.9",
"@types/jsdom": "^21.1.7",
"@types/lodash": "^4.17.20",
"@types/mdast": "^4.0.4",
"@types/node": "^22.18.6",
"@types/node": "^22.19.0",
"@types/rollup-plugin-visualizer": "^5.0.3",
"@vitest/coverage-v8": "^3.2.4",
"@vitest/spy": "^3.2.4",
@@ -90,23 +88,23 @@
"cors": "^2.8.5",
"cpy-cli": "^5.0.0",
"cross-env": "^7.0.3",
"cspell": "^9.2.1",
"cspell": "^9.3.0",
"cypress": "^14.5.4",
"cypress-image-snapshot": "^4.0.1",
"cypress-split": "^1.24.23",
"esbuild": "^0.25.10",
"cypress-split": "^1.24.25",
"esbuild": "^0.25.12",
"eslint": "^9.26.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-cypress": "^4.3.0",
"eslint-plugin-cypress": "^5.2.0",
"eslint-plugin-html": "^8.1.3",
"eslint-plugin-jest": "^28.14.0",
"eslint-plugin-jsdoc": "^50.8.0",
"eslint-plugin-jest": "^29.0.1",
"eslint-plugin-jsdoc": "^61.1.12",
"eslint-plugin-json": "^4.0.1",
"eslint-plugin-lodash": "^8.0.0",
"eslint-plugin-markdown": "^5.1.0",
"eslint-plugin-no-only-tests": "^3.3.0",
"eslint-plugin-tsdoc": "^0.4.0",
"eslint-plugin-unicorn": "^59.0.1",
"eslint-plugin-unicorn": "^62.0.0",
"express": "^5.1.0",
"globals": "^16.4.0",
"globby": "^14.1.0",
@@ -123,13 +121,13 @@
"prettier": "^3.6.2",
"prettier-plugin-jsdoc": "^1.3.3",
"rimraf": "^6.0.1",
"rollup-plugin-visualizer": "^6.0.3",
"rollup-plugin-visualizer": "^6.0.5",
"start-server-and-test": "^2.1.2",
"tslib": "^2.8.1",
"tsx": "^4.20.5",
"tsx": "^4.20.6",
"typescript": "~5.7.3",
"typescript-eslint": "^8.38.0",
"vite": "^7.0.7",
"vite": "^7.0.8",
"vite-plugin-istanbul": "^7.0.0",
"vitest": "^3.2.4"
},

View File

@@ -1,51 +0,0 @@
import type { DiagramMetadata } from '../types.js';
export default {
id: 'usecase',
name: 'Use Case Diagram',
description: 'Visualize system functionality and user interactions',
examples: [
{
title: 'Basic Use Case',
isDefault: true,
code: `usecase
actor User
actor Admin
User --> (Login)
User --> (View Profile)
Admin --> (Manage Users)
Admin --> (View Reports)`,
},
{
title: 'System Boundary',
code: `usecase
actor Customer
actor Support
SystemBoundary@{ type: rect } "E-commerce System" {
Customer --> (Browse Products)
Customer --> (Place Order)
Customer --> (Track Order)
}
SystemBoundary@{ type: package } "Admin Panel" {
Support --> (Process Orders)
Support --> (Handle Returns)
}`,
},
{
title: 'Actor Relationships',
code: `usecase
actor Developer1
actor Developer2
actor Manager
Developer1 --> (Write Code)
Developer2 --> (Review Code)
Manager --> (Approve Release)
Developer1 --> Developer2
Manager --> Developer1`,
},
],
} satisfies DiagramMetadata;

View File

@@ -21,7 +21,6 @@ import quadrantChart from './examples/quadrant-chart.js';
import packetDiagram from './examples/packet.js';
import blockDiagram from './examples/block.js';
import treemapDiagram from './examples/treemap.js';
import usecaseDiagram from './examples/usecase.js';
export const diagramData: DiagramMetadata[] = [
flowChart,
@@ -46,5 +45,4 @@ export const diagramData: DiagramMetadata[] = [
packetDiagram,
blockDiagram,
treemapDiagram,
usecaseDiagram,
];

View File

@@ -18,7 +18,9 @@
"elk",
"mermaid"
],
"scripts": {},
"scripts": {
"clean": "rimraf dist"
},
"repository": {
"type": "git",
"url": "https://github.com/mermaid-js/mermaid"

View File

@@ -19,7 +19,9 @@
"mermaid",
"layout"
],
"scripts": {},
"scripts": {
"clean": "rimraf dist"
},
"repository": {
"type": "git",
"url": "https://github.com/mermaid-js/mermaid"

View File

@@ -33,7 +33,7 @@
],
"license": "MIT",
"dependencies": {
"@zenuml/core": "^3.41.4"
"@zenuml/core": "^3.41.6"
},
"devDependencies": {
"mermaid": "workspace:^"

View File

@@ -1,5 +1,30 @@
# mermaid
## 11.12.1
### Patch Changes
- [#7107](https://github.com/mermaid-js/mermaid/pull/7107) [`cbf8946`](https://github.com/mermaid-js/mermaid/commit/cbf89462acecac7a06f19843e8d48cb137df0753) Thanks [@shubhamparikh2704](https://github.com/shubhamparikh2704)! - fix: Updated the dependency dagre-d3-es to 7.0.13 to fix GHSA-cc8p-78qf-8p7q
## 11.12.0
### Minor Changes
- [#6921](https://github.com/mermaid-js/mermaid/pull/6921) [`764b315`](https://github.com/mermaid-js/mermaid/commit/764b315dc16d0359add7c6b8e3ef7592e9bdc09c) Thanks [@quilicicf](https://github.com/quilicicf)! - feat: Add IDs in architecture diagrams
### Patch Changes
- [#6950](https://github.com/mermaid-js/mermaid/pull/6950) [`a957908`](https://github.com/mermaid-js/mermaid/commit/a9579083bfba367a4f4678547ec37ed7b61b9f5b) Thanks [@shubhamparikh2704](https://github.com/shubhamparikh2704)! - chore: Fix mindmap rendering in docs and apply tidytree layout
- [#6826](https://github.com/mermaid-js/mermaid/pull/6826) [`1d36810`](https://github.com/mermaid-js/mermaid/commit/1d3681053b9168354e48e5763023b6305cd1ca72) Thanks [@darshanr0107](https://github.com/darshanr0107)! - fix: Ensure edge label color is applied when using classDef with edge IDs
- [#6945](https://github.com/mermaid-js/mermaid/pull/6945) [`d318f1a`](https://github.com/mermaid-js/mermaid/commit/d318f1a13cd7429334a29c70e449074ec1cb9f68) Thanks [@darshanr0107](https://github.com/darshanr0107)! - fix: Resolve gantt chart crash due to invalid array length
- [#6918](https://github.com/mermaid-js/mermaid/pull/6918) [`cfe9238`](https://github.com/mermaid-js/mermaid/commit/cfe9238882cbe95416db1feea3112456a71b6aaf) Thanks [@shubhamparikh2704](https://github.com/shubhamparikh2704)! - chore: revert marked dependency from ^15.0.7 to ^16.0.0
- Reverted marked package version to ^16.0.0 for better compatibility
- This is a dependency update that maintains API compatibility
- All tests pass with the updated version
## 11.11.0
### Minor Changes

View File

@@ -1,6 +1,6 @@
{
"name": "mermaid",
"version": "11.11.0",
"version": "11.12.1",
"description": "Markdown-ish syntax for generating flowcharts, mindmaps, sequence diagrams, class diagrams, gantt charts, git graphs and more.",
"type": "module",
"module": "./dist/mermaid.core.mjs",
@@ -34,8 +34,6 @@
"scripts": {
"clean": "rimraf dist",
"dev": "pnpm -w dev",
"antlr:generate": "tsx ../../scripts/antlr-generate.mts",
"antlr:watch": "tsx ../../scripts/antlr-watch.mts",
"docs:code": "typedoc src/defaultConfig.ts src/config.ts src/mermaid.ts && prettier --write ./src/docs/config/setup",
"docs:build": "rimraf ../../docs && pnpm docs:code && pnpm docs:spellcheck && tsx scripts/docs.cli.mts",
"docs:verify": "pnpm docs:code && pnpm docs:spellcheck && tsx scripts/docs.cli.mts --verify",
@@ -49,7 +47,7 @@
"docs:verify-version": "tsx scripts/update-release-version.mts --verify",
"types:build-config": "tsx scripts/create-types-from-json-schema.mts",
"types:verify-config": "tsx scripts/create-types-from-json-schema.mts --verify",
"checkCircle": "npx madge --circular ./src --exclude '.*generated.*'",
"checkCircle": "npx madge --circular ./src",
"prepublishOnly": "pnpm docs:verify-version"
},
"repository": {
@@ -73,16 +71,15 @@
"@iconify/utils": "^3.0.2",
"@mermaid-js/parser": "workspace:^",
"@types/d3": "^7.4.3",
"antlr4ng": "^3.0.7",
"cytoscape": "^3.33.1",
"cytoscape-cose-bilkent": "^4.1.0",
"cytoscape-fcose": "^2.2.0",
"d3": "^7.9.0",
"d3-sankey": "^0.12.3",
"dagre-d3-es": "7.0.11",
"dayjs": "^1.11.18",
"dompurify": "^3.2.5",
"katex": "^0.16.22",
"dagre-d3-es": "7.0.13",
"dayjs": "^1.11.19",
"dompurify": "^3.3.0",
"katex": "^0.16.25",
"khroma": "^2.1.0",
"lodash-es": "^4.17.21",
"marked": "^16.3.0",
@@ -92,10 +89,10 @@
"uuid": "^11.1.0"
},
"devDependencies": {
"@adobe/jsonschema2md": "^8.0.5",
"@adobe/jsonschema2md": "^8.0.7",
"@iconify/types": "^2.0.0",
"@types/cytoscape": "^3.21.9",
"@types/cytoscape-fcose": "^2.2.4",
"@types/cytoscape-fcose": "^2.2.5",
"@types/d3-sankey": "^0.12.4",
"@types/d3-scale": "^4.0.9",
"@types/d3-scale-chromatic": "^3.1.0",
@@ -104,7 +101,7 @@
"@types/jsdom": "^21.1.7",
"@types/katex": "^0.16.7",
"@types/lodash-es": "^4.17.12",
"@types/micromatch": "^4.0.9",
"@types/micromatch": "^4.0.10",
"@types/stylis": "^4.2.7",
"@types/uuid": "^10.0.0",
"ajv": "^8.17.1",
@@ -126,7 +123,7 @@
"rimraf": "^6.0.1",
"start-server-and-test": "^2.1.2",
"type-fest": "^4.41.0",
"typedoc": "^0.28.13",
"typedoc": "^0.28.14",
"typedoc-plugin-markdown": "^4.8.1",
"typescript": "~5.7.3",
"unist-util-flatmap": "^1.0.0",

View File

@@ -189,7 +189,6 @@ This Markdown should be kept.
| Display | Curved Trapezoid | \`curv-trap\` | Represents a display | \`curved-trapezoid\`, \`display\` |
| Divided Process | Divided Rectangle | \`div-rect\` | Divided process shape | \`div-proc\`, \`divided-process\`, \`divided-rectangle\` |
| Document | Document | \`doc\` | Represents a document | \`doc\`, \`document\` |
| Ellipse | Ellipse | \`ellipse\` | Ellipse shape | \`oval\` |
| Event | Rounded Rectangle | \`rounded\` | Represents an event | \`event\` |
| Extract | Triangle | \`tri\` | Extraction process | \`extract\`, \`triangle\` |
| Fork/Join | Filled Rectangle | \`fork\` | Fork or join in process flow | \`join\` |

View File

@@ -210,7 +210,6 @@ export interface MermaidConfig {
packet?: PacketDiagramConfig;
block?: BlockDiagramConfig;
radar?: RadarDiagramConfig;
usecase?: UsecaseDiagramConfig;
dompurifyConfig?: DOMPurifyConfiguration;
wrap?: boolean;
fontSize?: number;
@@ -1624,50 +1623,6 @@ export interface RadarDiagramConfig extends BaseDiagramConfig {
*/
curveTension?: number;
}
/**
* The object containing configurations specific for usecase diagrams.
*
* This interface was referenced by `MermaidConfig`'s JSON-Schema
* via the `definition` "UsecaseDiagramConfig".
*/
export interface UsecaseDiagramConfig extends BaseDiagramConfig {
/**
* Font size for actor labels
*/
actorFontSize?: number;
/**
* Font family for actor labels
*/
actorFontFamily?: string;
/**
* Font weight for actor labels
*/
actorFontWeight?: string;
/**
* Font size for usecase labels
*/
usecaseFontSize?: number;
/**
* Font family for usecase labels
*/
usecaseFontFamily?: string;
/**
* Font weight for usecase labels
*/
usecaseFontWeight?: string;
/**
* Margin around actors
*/
actorMargin?: number;
/**
* Margin around use cases
*/
usecaseMargin?: number;
/**
* Padding around the entire diagram
*/
diagramPadding?: number;
}
/**
* This interface was referenced by `MermaidConfig`'s JSON-Schema
* via the `definition` "FontConfig".

View File

@@ -264,9 +264,6 @@ const config: RequiredDeep<MermaidConfig> = {
radar: {
...defaultConfigJson.radar,
},
usecase: {
...defaultConfigJson.usecase,
},
treemap: {
useMaxWidth: true,
padding: 10,

View File

@@ -28,7 +28,6 @@ import architecture from '../diagrams/architecture/architectureDetector.js';
import { registerLazyLoadedDiagrams } from './detectType.js';
import { registerDiagram } from './diagramAPI.js';
import { treemap } from '../diagrams/treemap/detector.js';
import { usecase } from '../diagrams/usecase/usecaseDetector.js';
import '../type.d.ts';
let hasLoadedDiagrams = false;
@@ -73,7 +72,7 @@ export const addDiagrams = () => {
}
);
if (includeLargeFeatures) {
if (injected.includeLargeFeatures) {
registerLazyLoadedDiagrams(flowchartElk, mindmap, architecture);
}
@@ -102,7 +101,6 @@ export const addDiagrams = () => {
xychart,
block,
radar,
treemap,
usecase
treemap
);
};

View File

@@ -0,0 +1,58 @@
import c4Db from '../c4Db.js';
import c4 from './c4Diagram.jison';
import { setConfig } from '../../../config.js';
setConfig({
securityLevel: 'strict',
});
describe.each([
['Component', 'component'],
['ComponentDb', 'component_db'],
['ComponentQueue', 'component_queue'],
['Component_Ext', 'external_component'],
['ComponentDb_Ext', 'external_component_db'],
['ComponentQueue_Ext', 'external_component_queue'],
])('parsing a C4 %s', function (macroName, elementName) {
beforeEach(function () {
c4.parser.yy = c4Db;
c4.parser.yy.clear();
});
it('should parse a C4 diagram with one Component correctly', function () {
c4.parser.parse(`C4Component
title Component diagram for Internet Banking Component
${macroName}(ComponentAA, "Internet Banking Component", "Technology", "Allows customers to view information about their bank accounts, and make payments.")`);
const yy = c4.parser.yy;
const shapes = yy.getC4ShapeArray();
expect(shapes.length).toBe(1);
const onlyShape = shapes[0];
expect(onlyShape).toMatchObject({
alias: 'ComponentAA',
descr: {
text: 'Allows customers to view information about their bank accounts, and make payments.',
},
label: {
text: 'Internet Banking Component',
},
techn: {
text: 'Technology',
},
typeC4Shape: {
text: elementName,
},
});
});
it('should handle a trailing whitespaces after Component', function () {
const whitespace = ' ';
const rendered = c4.parser.parse(`C4Component${whitespace}
title Component diagram for Internet Banking Component${whitespace}
${macroName}(ComponentAA, "Internet Banking Component", "Technology", "Allows customers to view information about their bank accounts, and make payments.")${whitespace}`);
expect(rendered).toBe(true);
});
});

View File

@@ -158,10 +158,10 @@ accDescr\s*"{"\s* { this.begin("acc_descr_multiline");}
"UpdateRelStyle" { this.begin("update_rel_style"); return 'UPDATE_REL_STYLE';}
"UpdateLayoutConfig" { this.begin("update_layout_config"); return 'UPDATE_LAYOUT_CONFIG';}
<person,person_ext,system_ext_queue,system_ext_db,system_ext,system_queue,system_db,system,boundary,enterprise_boundary,system_boundary,container_ext_db,container_ext_queue,container_ext,container_queue,container_db,container,container_boundary,component_ext_db,component_ext,component_queue,component_db,component,node,node_l,node_r,rel,birel,rel_u,rel_d,rel_l,rel_r,rel_b,rel_index,update_el_style,update_rel_style,update_layout_config><<EOF>> return "EOF_IN_STRUCT";
<person,person_ext,system_ext_queue,system_ext_db,system_ext,system_queue,system_db,system,boundary,enterprise_boundary,system_boundary,container_ext_db,container_ext_queue,container_ext,container_queue,container_db,container,container_boundary,component_ext_db,component_ext,component_queue,component_db,component,node,node_l,node_r,rel,birel,rel_u,rel_d,rel_l,rel_r,rel_b,rel_index,update_el_style,update_rel_style,update_layout_config>[(][ ]*[,] { this.begin("attribute"); return "ATTRIBUTE_EMPTY";}
<person,person_ext,system_ext_queue,system_ext_db,system_ext,system_queue,system_db,system,boundary,enterprise_boundary,system_boundary,container_ext_db,container_ext_queue,container_ext,container_queue,container_db,container,container_boundary,component_ext_db,component_ext,component_queue,component_db,component,node,node_l,node_r,rel,birel,rel_u,rel_d,rel_l,rel_r,rel_b,rel_index,update_el_style,update_rel_style,update_layout_config>[(] { this.begin("attribute"); }
<person,person_ext,system_ext_queue,system_ext_db,system_ext,system_queue,system_db,system,boundary,enterprise_boundary,system_boundary,container_ext_db,container_ext_queue,container_ext,container_queue,container_db,container,container_boundary,component_ext_db,component_ext,component_queue,component_db,component,node,node_l,node_r,rel,birel,rel_u,rel_d,rel_l,rel_r,rel_b,rel_index,update_el_style,update_rel_style,update_layout_config,attribute>[)] { this.popState();this.popState();}
<person,person_ext,system_ext_queue,system_ext_db,system_ext,system_queue,system_db,system,boundary,enterprise_boundary,system_boundary,container_ext_db,container_ext_queue,container_ext,container_queue,container_db,container,container_boundary,component_ext_db,component_ext_queue,component_ext,component_queue,component_db,component,node,node_l,node_r,rel,birel,rel_u,rel_d,rel_l,rel_r,rel_b,rel_index,update_el_style,update_rel_style,update_layout_config><<EOF>> return "EOF_IN_STRUCT";
<person,person_ext,system_ext_queue,system_ext_db,system_ext,system_queue,system_db,system,boundary,enterprise_boundary,system_boundary,container_ext_db,container_ext_queue,container_ext,container_queue,container_db,container,container_boundary,component_ext_db,component_ext_queue,component_ext,component_queue,component_db,component,node,node_l,node_r,rel,birel,rel_u,rel_d,rel_l,rel_r,rel_b,rel_index,update_el_style,update_rel_style,update_layout_config>[(][ ]*[,] { this.begin("attribute"); return "ATTRIBUTE_EMPTY";}
<person,person_ext,system_ext_queue,system_ext_db,system_ext,system_queue,system_db,system,boundary,enterprise_boundary,system_boundary,container_ext_db,container_ext_queue,container_ext,container_queue,container_db,container,container_boundary,component_ext_db,component_ext_queue,component_ext,component_queue,component_db,component,node,node_l,node_r,rel,birel,rel_u,rel_d,rel_l,rel_r,rel_b,rel_index,update_el_style,update_rel_style,update_layout_config>[(] { this.begin("attribute"); }
<person,person_ext,system_ext_queue,system_ext_db,system_ext,system_queue,system_db,system,boundary,enterprise_boundary,system_boundary,container_ext_db,container_ext_queue,container_ext,container_queue,container_db,container,container_boundary,component_ext_db,component_ext_queue,component_ext,component_queue,component_db,component,node,node_l,node_r,rel,birel,rel_u,rel_d,rel_l,rel_r,rel_b,rel_index,update_el_style,update_rel_style,update_layout_config,attribute>[)] { this.popState();this.popState();}
<attribute>",," { return 'ATTRIBUTE_EMPTY';}
<attribute>"," { }

View File

@@ -17,6 +17,7 @@ import type {
ClassRelation,
ClassNode,
ClassNote,
ClassNoteMap,
ClassMap,
NamespaceMap,
NamespaceNode,
@@ -33,15 +34,16 @@ const sanitizeText = (txt: string) => common.sanitizeText(txt, getConfig());
export class ClassDB implements DiagramDB {
private relations: ClassRelation[] = [];
private classes = new Map<string, ClassNode>();
private classes: ClassMap = new Map<string, ClassNode>();
private readonly styleClasses = new Map<string, StyleClass>();
private notes: ClassNote[] = [];
private notes: ClassNoteMap = new Map<string, ClassNote>();
private interfaces: Interface[] = [];
// private static classCounter = 0;
private namespaces = new Map<string, NamespaceNode>();
private namespaceCounter = 0;
private functions: any[] = [];
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
private functions: Function[] = [];
constructor() {
this.functions.push(this.setupToolTips.bind(this));
@@ -124,7 +126,7 @@ export class ClassDB implements DiagramDB {
annotations: [],
styles: [],
domId: MERMAID_DOM_ID_PREFIX + name + '-' + classCounter,
} as ClassNode);
});
classCounter++;
}
@@ -155,12 +157,12 @@ export class ClassDB implements DiagramDB {
public clear() {
this.relations = [];
this.classes = new Map();
this.notes = [];
this.classes = new Map<string, ClassNode>();
this.notes = new Map<string, ClassNote>();
this.interfaces = [];
this.functions = [];
this.functions.push(this.setupToolTips.bind(this));
this.namespaces = new Map();
this.namespaces = new Map<string, NamespaceNode>();
this.namespaceCounter = 0;
this.direction = 'TB';
commonClear();
@@ -178,7 +180,12 @@ export class ClassDB implements DiagramDB {
return this.relations;
}
public getNotes() {
public getNote(id: string | number): ClassNote {
const key = typeof id === 'number' ? `note${id}` : id;
return this.notes.get(key)!;
}
public getNotes(): ClassNoteMap {
return this.notes;
}
@@ -279,16 +286,19 @@ export class ClassDB implements DiagramDB {
}
}
public addNote(text: string, className: string) {
public addNote(text: string, className: string): string {
const index = this.notes.size;
const note = {
id: `note${this.notes.length}`,
id: `note${index}`,
class: className,
text: text,
index: index,
};
this.notes.push(note);
this.notes.set(note.id, note);
return note.id;
}
public cleanupLabel(label: string) {
public cleanupLabel(label: string): string {
if (label.startsWith(':')) {
label = label.substring(1);
}
@@ -354,7 +364,7 @@ export class ClassDB implements DiagramDB {
});
}
public getTooltip(id: string, namespace?: string) {
public getTooltip(id: string, namespace?: string): string | undefined {
if (namespace && this.namespaces.has(namespace)) {
return this.namespaces.get(namespace)!.classes.get(id)!.tooltip;
}
@@ -534,10 +544,11 @@ export class ClassDB implements DiagramDB {
this.namespaces.set(id, {
id: id,
classes: new Map(),
children: {},
classes: new Map<string, ClassNode>(),
notes: new Map<string, ClassNote>(),
children: new Map<string, NamespaceNode>(),
domId: MERMAID_DOM_ID_PREFIX + id + '-' + this.namespaceCounter,
} as NamespaceNode);
});
this.namespaceCounter++;
}
@@ -555,16 +566,23 @@ export class ClassDB implements DiagramDB {
*
* @param id - ID of the namespace to add
* @param classNames - IDs of the class to add
* @param noteNames - IDs of the notes to add
* @public
*/
public addClassesToNamespace(id: string, classNames: string[]) {
public addClassesToNamespace(id: string, classNames: string[], noteNames: string[]) {
if (!this.namespaces.has(id)) {
return;
}
for (const name of classNames) {
const { className } = this.splitClassNameAndType(name);
this.classes.get(className)!.parent = id;
this.namespaces.get(id)!.classes.set(className, this.classes.get(className)!);
const classNode = this.getClass(className);
classNode.parent = id;
this.namespaces.get(id)!.classes.set(className, classNode);
}
for (const noteName of noteNames) {
const noteNode = this.getNote(noteName);
noteNode.parent = id;
this.namespaces.get(id)!.notes.set(noteName, noteNode);
}
}
@@ -617,36 +635,32 @@ export class ClassDB implements DiagramDB {
const edges: Edge[] = [];
const config = getConfig();
for (const namespaceKey of this.namespaces.keys()) {
const namespace = this.namespaces.get(namespaceKey);
if (namespace) {
const node: Node = {
id: namespace.id,
label: namespace.id,
isGroup: true,
padding: config.class!.padding ?? 16,
// parent node must be one of [rect, roundedWithTitle, noteGroup, divider]
shape: 'rect',
cssStyles: ['fill: none', 'stroke: black'],
look: config.look,
};
nodes.push(node);
}
for (const namespace of this.namespaces.values()) {
const node: Node = {
id: namespace.id,
label: namespace.id,
isGroup: true,
padding: config.class!.padding ?? 16,
// parent node must be one of [rect, roundedWithTitle, noteGroup, divider]
shape: 'rect',
cssStyles: [],
look: config.look,
};
nodes.push(node);
}
for (const classKey of this.classes.keys()) {
const classNode = this.classes.get(classKey);
if (classNode) {
const node = classNode as unknown as Node;
node.parentId = classNode.parent;
node.look = config.look;
nodes.push(node);
}
for (const classNode of this.classes.values()) {
const node: Node = {
...classNode,
type: undefined,
isGroup: false,
parentId: classNode.parent,
look: config.look,
};
nodes.push(node);
}
let cnt = 0;
for (const note of this.notes) {
cnt++;
for (const note of this.notes.values()) {
const noteNode: Node = {
id: note.id,
label: note.text,
@@ -660,14 +674,15 @@ export class ClassDB implements DiagramDB {
`stroke: ${config.themeVariables.noteBorderColor}`,
],
look: config.look,
parentId: note.parent,
};
nodes.push(noteNode);
const noteClassId = this.classes.get(note.class)?.id ?? '';
const noteClassId = this.classes.get(note.class)?.id;
if (noteClassId) {
const edge: Edge = {
id: `edgeNote${cnt}`,
id: `edgeNote${note.index}`,
start: note.id,
end: noteClassId,
type: 'normal',
@@ -697,7 +712,7 @@ export class ClassDB implements DiagramDB {
nodes.push(interfaceNode);
}
cnt = 0;
let cnt = 0;
for (const classRelation of this.relations) {
cnt++;
const edge: Edge = {

View File

@@ -417,7 +417,7 @@ class C13["With Città foreign language"]
note "This is a keyword: ${keyword}. It truly is."
`;
parser.parse(str);
expect(classDb.getNotes()[0].text).toEqual(`This is a keyword: ${keyword}. It truly is.`);
expect(classDb.getNote(0).text).toEqual(`This is a keyword: ${keyword}. It truly is.`);
});
it.each(keywords)(
@@ -427,7 +427,7 @@ class C13["With Città foreign language"]
note "${keyword}"`;
parser.parse(str);
expect(classDb.getNotes()[0].text).toEqual(`${keyword}`);
expect(classDb.getNote(0).text).toEqual(`${keyword}`);
}
);
@@ -441,7 +441,7 @@ class C13["With Città foreign language"]
`;
parser.parse(str);
expect(classDb.getNotes()[0].text).toEqual(`This is a keyword: ${keyword}. It truly is.`);
expect(classDb.getNote(0).text).toEqual(`This is a keyword: ${keyword}. It truly is.`);
});
it.each(keywords)(
@@ -456,7 +456,7 @@ class C13["With Città foreign language"]
`;
parser.parse(str);
expect(classDb.getNotes()[0].text).toEqual(`${keyword}`);
expect(classDb.getNote(0).text).toEqual(`${keyword}`);
}
);

View File

@@ -8,7 +8,7 @@ import utils, { getEdgeId } from '../../utils.js';
import { interpolateToCurve, getStylesFromArray } from '../../utils.js';
import { setupGraphViewbox } from '../../setupGraphViewbox.js';
import common from '../common/common.js';
import type { ClassRelation, ClassNote, ClassMap, NamespaceMap } from './classTypes.js';
import type { ClassRelation, ClassMap, ClassNoteMap, NamespaceMap } from './classTypes.js';
import type { EdgeData } from '../../types.js';
const sanitizeText = (txt: string) => common.sanitizeText(txt, getConfig());
@@ -65,6 +65,9 @@ export const addNamespaces = function (
g.setNode(vertex.id, node);
addClasses(vertex.classes, g, _id, diagObj, vertex.id);
const classes: ClassMap = diagObj.db.getClasses();
const relations: ClassRelation[] = diagObj.db.getRelations();
addNotes(vertex.notes, g, relations.length + 1, classes, vertex.id);
log.info('setNode', node);
});
@@ -144,69 +147,74 @@ export const addClasses = function (
* @param classes - Classes
*/
export const addNotes = function (
notes: ClassNote[],
notes: ClassNoteMap,
g: graphlib.Graph,
startEdgeId: number,
classes: ClassMap
classes: ClassMap,
parent?: string
) {
log.info(notes);
notes.forEach(function (note, i) {
const vertex = note;
[...notes.values()]
.filter((note) => note.parent === parent)
.forEach(function (vertex) {
const cssNoteStr = '';
const cssNoteStr = '';
const styles = { labelStyle: '', style: '' };
const styles = { labelStyle: '', style: '' };
const vertexText = vertex.text;
const vertexText = vertex.text;
const radius = 0;
const shape = 'note';
const node = {
labelStyle: styles.labelStyle,
shape: shape,
labelText: sanitizeText(vertexText),
noteData: vertex,
rx: radius,
ry: radius,
class: cssNoteStr,
style: styles.style,
id: vertex.id,
domId: vertex.id,
tooltip: '',
type: 'note',
// TODO V10: Flowchart ? Keeping flowchart for backwards compatibility. Remove in next major release
padding: getConfig().flowchart?.padding ?? getConfig().class?.padding,
};
g.setNode(vertex.id, node);
log.info('setNode', node);
const radius = 0;
const shape = 'note';
const node = {
labelStyle: styles.labelStyle,
shape: shape,
labelText: sanitizeText(vertexText),
noteData: vertex,
rx: radius,
ry: radius,
class: cssNoteStr,
style: styles.style,
id: vertex.id,
domId: vertex.id,
tooltip: '',
type: 'note',
// TODO V10: Flowchart ? Keeping flowchart for backwards compatibility. Remove in next major release
padding: getConfig().flowchart?.padding ?? getConfig().class?.padding,
};
g.setNode(vertex.id, node);
log.info('setNode', node);
if (parent) {
g.setParent(vertex.id, parent);
}
if (!vertex.class || !classes.has(vertex.class)) {
return;
}
const edgeId = startEdgeId + i;
if (!vertex.class || !classes.has(vertex.class)) {
return;
}
const edgeId = startEdgeId + vertex.index;
const edgeData: EdgeData = {
id: `edgeNote${edgeId}`,
//Set relationship style and line type
classes: 'relation',
pattern: 'dotted',
// Set link type for rendering
arrowhead: 'none',
//Set edge extra labels
startLabelRight: '',
endLabelLeft: '',
//Set relation arrow types
arrowTypeStart: 'none',
arrowTypeEnd: 'none',
style: 'fill:none',
labelStyle: '',
curve: interpolateToCurve(conf.curve, curveLinear),
};
const edgeData: EdgeData = {
id: `edgeNote${edgeId}`,
//Set relationship style and line type
classes: 'relation',
pattern: 'dotted',
// Set link type for rendering
arrowhead: 'none',
//Set edge extra labels
startLabelRight: '',
endLabelLeft: '',
//Set relation arrow types
arrowTypeStart: 'none',
arrowTypeEnd: 'none',
style: 'fill:none',
labelStyle: '',
curve: interpolateToCurve(conf.curve, curveLinear),
};
// Add the edge to the graph
g.setEdge(vertex.id, vertex.class, edgeData, edgeId);
});
// Add the edge to the graph
g.setEdge(vertex.id, vertex.class, edgeData, edgeId);
});
};
/**
@@ -329,7 +337,7 @@ export const draw = async function (text: string, id: string, _version: string,
const namespaces: NamespaceMap = diagObj.db.getNamespaces();
const classes: ClassMap = diagObj.db.getClasses();
const relations: ClassRelation[] = diagObj.db.getRelations();
const notes: ClassNote[] = diagObj.db.getNotes();
const notes: ClassNoteMap = diagObj.db.getNotes();
log.info(relations);
addNamespaces(namespaces, g, id, diagObj);
addClasses(classes, g, id, diagObj);

View File

@@ -206,7 +206,7 @@ export const draw = function (text, id, _version, diagObj) {
);
});
const notes = diagObj.db.getNotes();
const notes = diagObj.db.getNotes().values();
notes.forEach(function (note) {
log.debug(`Adding note: ${JSON.stringify(note)}`);
const node = svgDraw.drawNote(diagram, note, conf, diagObj);

View File

@@ -5,7 +5,7 @@ export interface ClassNode {
id: string;
type: string;
label: string;
shape: string;
shape: 'classBox';
text: string;
cssClasses: string;
methods: ClassMember[];
@@ -149,6 +149,8 @@ export interface ClassNote {
id: string;
class: string;
text: string;
index: number;
parent?: string;
}
export interface ClassRelation {
@@ -177,6 +179,7 @@ export interface NamespaceNode {
id: string;
domId: string;
classes: ClassMap;
notes: ClassNoteMap;
children: NamespaceMap;
}
@@ -187,4 +190,5 @@ export interface StyleClass {
}
export type ClassMap = Map<string, ClassNode>;
export type ClassNoteMap = Map<string, ClassNote>;
export type NamespaceMap = Map<string, NamespaceNode>;

View File

@@ -275,8 +275,8 @@ statement
;
namespaceStatement
: namespaceIdentifier STRUCT_START classStatements STRUCT_STOP { yy.addClassesToNamespace($1, $3); }
| namespaceIdentifier STRUCT_START NEWLINE classStatements STRUCT_STOP { yy.addClassesToNamespace($1, $4); }
: namespaceIdentifier STRUCT_START classStatements STRUCT_STOP { yy.addClassesToNamespace($1, $3[0], $3[1]); }
| namespaceIdentifier STRUCT_START NEWLINE classStatements STRUCT_STOP { yy.addClassesToNamespace($1, $4[0], $4[1]); }
;
namespaceIdentifier
@@ -284,9 +284,12 @@ namespaceIdentifier
;
classStatements
: classStatement {$$=[$1]}
| classStatement NEWLINE {$$=[$1]}
| classStatement NEWLINE classStatements {$3.unshift($1); $$=$3}
: classStatement {$$=[[$1], []]}
| classStatement NEWLINE {$$=[[$1], []]}
| classStatement NEWLINE classStatements {$3[0].unshift($1); $$=$3}
| noteStatement {$$=[[], [$1]]}
| noteStatement NEWLINE {$$=[[], [$1]]}
| noteStatement NEWLINE classStatements {$3[1].unshift($1); $$=$3}
;
classStatement
@@ -333,8 +336,8 @@ relationStatement
;
noteStatement
: NOTE_FOR className noteText { yy.addNote($3, $2); }
| NOTE noteText { yy.addNote($2); }
: NOTE_FOR className noteText { $$ = yy.addNote($3, $2); }
| NOTE noteText { $$ = yy.addNote($2); }
;
classDefStatement

View File

@@ -13,6 +13,30 @@ const getStyles = (options) =>
}
.cluster-label text {
fill: ${options.titleColor};
}
.cluster-label span {
color: ${options.titleColor};
}
.cluster-label span p {
background-color: transparent;
}
.cluster rect {
fill: ${options.clusterBkg};
stroke: ${options.clusterBorder};
stroke-width: 1px;
}
.cluster text {
fill: ${options.titleColor};
}
.cluster span {
color: ${options.titleColor};
}
.nodeLabel, .edgeLabel {
color: ${options.classText};
}

View File

@@ -70,6 +70,31 @@ describe('Sanitize text', () => {
});
expect(result).not.toContain('javascript:alert(1)');
});
it('should allow HTML tags in sandbox mode', () => {
const htmlStr = '<p>This is a <strong>bold</strong> text</p>';
const result = sanitizeText(htmlStr, {
securityLevel: 'sandbox',
flowchart: { htmlLabels: true },
});
expect(result).toContain('<p>');
expect(result).toContain('<strong>');
expect(result).toContain('</strong>');
expect(result).toContain('</p>');
});
it('should remove script tags in sandbox mode', () => {
const maliciousStr = '<p>Hello <script>alert(1)</script> world</p>';
const result = sanitizeText(maliciousStr, {
securityLevel: 'sandbox',
flowchart: { htmlLabels: true },
});
expect(result).not.toContain('<script>');
expect(result).not.toContain('alert(1)');
expect(result).toContain('<p>');
expect(result).toContain('Hello');
expect(result).toContain('world');
});
});
describe('generic parser', () => {

View File

@@ -66,7 +66,7 @@ export const removeScript = (txt: string): string => {
const sanitizeMore = (text: string, config: MermaidConfig) => {
if (config.flowchart?.htmlLabels !== false) {
const level = config.securityLevel;
if (level === 'antiscript' || level === 'strict') {
if (level === 'antiscript' || level === 'strict' || level === 'sandbox') {
text = removeScript(text);
} else if (level !== 'loose') {
text = breakToPlaceholder(text);
@@ -333,7 +333,7 @@ const renderKatexUnsanitized = async (text: string, config: MermaidConfig): Prom
return text.replace(katexRegex, 'MathML is unsupported in this environment.');
}
if (includeLargeFeatures) {
if (injected.includeLargeFeatures) {
const { default: katex } = await import('katex');
const outputMode =
config.forceLegacyMathML || (!isMathMLSupported() && config.legacyMathML)

View File

@@ -962,6 +962,7 @@ You have to call mermaid.initialize.`
case 'round':
return 'roundedRect';
case 'ellipse':
// @ts-expect-error -- Ellipses are broken, see https://github.com/mermaid-js/mermaid/issues/5976
return 'ellipse';
default:
return vertex.type;

View File

@@ -140,6 +140,7 @@ that id.
.*direction\s+BT[^\n]* return 'direction_bt';
.*direction\s+RL[^\n]* return 'direction_rl';
.*direction\s+LR[^\n]* return 'direction_lr';
.*direction\s+TD[^\n]* return 'direction_td';
[^\s\"]+\@(?=[^\{\"]) { return 'LINK_ID'; }
[0-9]+ return 'NUM';
@@ -626,6 +627,8 @@ direction
{ $$={stmt:'dir', value:'RL'};}
| direction_lr
{ $$={stmt:'dir', value:'LR'};}
| direction_td
{ $$={stmt:'dir', value:'TD'};}
;
%%

View File

@@ -309,4 +309,21 @@ describe('when parsing subgraphs', function () {
expect(subgraphA.nodes).toContain('a');
expect(subgraphA.nodes).not.toContain('c');
});
it('should correctly parse direction TD inside a subgraph', function () {
const res = flow.parser.parse(`
graph LR
subgraph WithTD
direction TD
A1 --> A2
end
`);
const subgraphs = flow.parser.yy.getSubGraphs();
expect(subgraphs.length).toBe(1);
const subgraph = subgraphs[0];
expect(subgraph.dir).toBe('TD');
expect(subgraph.nodes).toContain('A1');
expect(subgraph.nodes).toContain('A2');
});
});

View File

@@ -1,8 +1,7 @@
import type { InfoFields, InfoDB } from './infoTypes.js';
import packageJson from '../../../package.json' assert { type: 'json' };
export const DEFAULT_INFO_DB: InfoFields = {
version: packageJson.version + (includeLargeFeatures ? '' : '-tiny'),
version: injected.version + (injected.includeLargeFeatures ? '' : '-tiny'),
} as const;
export const getVersion = (): string => DEFAULT_INFO_DB.version;

View File

@@ -293,5 +293,37 @@ describe('MindmapDb getData function', () => {
expect(edgeA1_aaa.section).toBe(1);
expect(edgeA_a2.section).toBe(2);
});
it('should wrap section numbers when there are more than 11 level 2 nodes', () => {
db.addNode(0, 'root', 'Example', 0);
for (let i = 1; i <= 15; i++) {
db.addNode(1, `child${i}`, `${i}`, 0);
}
const result = db.getData();
expect(result.nodes).toHaveLength(16);
const child1 = result.nodes.find((n) => n.label === '1') as MindmapLayoutNode;
const child11 = result.nodes.find((n) => n.label === '11') as MindmapLayoutNode;
const child12 = result.nodes.find((n) => n.label === '12') as MindmapLayoutNode;
const child13 = result.nodes.find((n) => n.label === '13') as MindmapLayoutNode;
const child14 = result.nodes.find((n) => n.label === '14') as MindmapLayoutNode;
const child15 = result.nodes.find((n) => n.label === '15') as MindmapLayoutNode;
expect(child1.section).toBe(0);
expect(child11.section).toBe(10);
expect(child12.section).toBe(0);
expect(child13.section).toBe(1);
expect(child14.section).toBe(2);
expect(child15.section).toBe(3);
expect(child12.cssClasses).toBe('mindmap-node section-0');
expect(child13.cssClasses).toBe('mindmap-node section-1');
expect(child14.cssClasses).toBe('mindmap-node section-2');
expect(child15.cssClasses).toBe('mindmap-node section-3');
});
});
});

View File

@@ -7,6 +7,7 @@ import type { MindmapNode } from './mindmapTypes.js';
import defaultConfig from '../../defaultConfig.js';
import type { LayoutData, Node, Edge } from '../../rendering-util/types.js';
import { getUserDefinedConfig } from '../../config.js';
import { MAX_SECTIONS } from './svgDraw.js';
// Extend Node type for mindmap-specific properties
export type MindmapLayoutNode = Node & {
@@ -203,7 +204,7 @@ export class MindmapDB {
// For other nodes, inherit parent's section number
if (node.children) {
for (const [index, child] of node.children.entries()) {
const childSectionNumber = node.level === 0 ? index : sectionNumber;
const childSectionNumber = node.level === 0 ? index % (MAX_SECTIONS - 1) : sectionNumber;
this.assignSections(child, childSectionNumber);
}
}

View File

@@ -5,7 +5,7 @@ import { parseFontSize } from '../../utils.js';
import type { MermaidConfig } from '../../config.type.js';
import type { MindmapDB } from './mindmapDb.js';
const MAX_SECTIONS = 12;
export const MAX_SECTIONS = 12;
type ShapeFunction = (
db: MindmapDB,

View File

@@ -16,7 +16,7 @@ const draw: DrawDefinition = (_text, id, _version, diagram: Diagram) => {
const svgWidth = bitWidth * bitsPerRow + 2;
const svg: SVG = selectSvgElement(id);
svg.attr('viewbox', `0 0 ${svgWidth} ${svgHeight}`);
svg.attr('viewBox', `0 0 ${svgWidth} ${svgHeight}`);
configureSvgSize(svg, svgHeight, svgWidth, config.useMaxWidth);
for (const [word, packet] of words.entries()) {

View File

@@ -2,6 +2,7 @@ import type { Diagram } from '../../Diagram.js';
import type { RadarDiagramConfig } from '../../config.type.js';
import type { DiagramRenderer, DrawDefinition, SVG, SVGGroup } from '../../diagram-api/types.js';
import { selectSvgElement } from '../../rendering-util/selectSvgElement.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
import type { RadarDB, RadarAxis, RadarCurve } from './types.js';
const draw: DrawDefinition = (_text, id, _version, diagram: Diagram) => {
@@ -53,11 +54,9 @@ const drawFrame = (svg: SVG, config: Required<RadarDiagramConfig>): SVGGroup =>
x: config.marginLeft + config.width / 2,
y: config.marginTop + config.height / 2,
};
// Initialize the SVG
svg
.attr('viewbox', `0 0 ${totalWidth} ${totalHeight}`)
.attr('width', totalWidth)
.attr('height', totalHeight);
configureSvgSize(svg, totalHeight, totalWidth, config.useMaxWidth ?? true);
svg.attr('viewBox', `0 0 ${totalWidth} ${totalHeight}`);
// g element to center the radar chart
return svg.append('g').attr('transform', `translate(${center.x}, ${center.y})`);
};

View File

@@ -32,13 +32,14 @@
<CONFIG>[^\}]+ { return 'CONFIG_CONTENT'; }
<CONFIG>\} { this.popState(); this.popState(); return 'CONFIG_END'; }
<ID>[^\<->\->:\n,;@\s]+(?=\@\{) { yytext = yytext.trim(); return 'ACTOR'; }
<ID>[^\<->\->:\n,;@]+?([\-]*[^\<->\->:\n,;@]+?)*?(?=((?!\n)\s)+"as"(?!\n)\s|[#\n;]|$) { yytext = yytext.trim(); this.begin('ALIAS'); return 'ACTOR'; }
<ID>[^<>:\n,;@\s]+(?=\s+as\s) { yytext = yytext.trim(); this.begin('ALIAS'); return 'ACTOR'; }
<ID>[^<>:\n,;@]+(?=\s*[\n;#]|$) { yytext = yytext.trim(); this.popState(); return 'ACTOR'; }
<ID>[^<>:\n,;@]*\<[^\n]* { this.popState(); return 'INVALID'; }
"box" { this.begin('LINE'); return 'box'; }
"participant" { this.begin('ID'); return 'participant'; }
"actor" { this.begin('ID'); return 'participant_actor'; }
"create" return 'create';
"destroy" { this.begin('ID'); return 'destroy'; }
<ID>[^<\->\->:\n,;]+?([\-]*[^<\->\->:\n,;]+?)*?(?=((?!\n)\s)+"as"(?!\n)\s|[#\n;]|$) { yytext = yytext.trim(); this.begin('ALIAS'); return 'ACTOR'; }
<ALIAS>"as" { this.popState(); this.popState(); this.begin('LINE'); return 'AS'; }
<ALIAS>(?:) { this.popState(); this.popState(); return 'NEWLINE'; }
"loop" { this.begin('LINE'); return 'loop'; }
@@ -145,6 +146,7 @@ line
: SPACE statement { $$ = $2 }
| statement { $$ = $1 }
| NEWLINE { $$=[]; }
| INVALID { $$=[]; }
;
box_section
@@ -411,4 +413,4 @@ text2
: TXT {$$ = yy.parseMessage($1.trim().substring(1)) }
;
%%
%%

View File

@@ -2609,5 +2609,17 @@ Bob->>Alice:Got it!
expect(actors.get('E').type).toBe('entity');
expect(actors.get('E').description).toBe('E');
});
it('should handle fail parsing when alias token causes conflicts in participant definition', async () => {
let error = false;
try {
await Diagram.fromText(`
sequenceDiagram
participant SAS MyServiceWithMoreThan20Chars <br> service decription
`);
} catch (e) {
error = true;
}
expect(error).toBe(true);
});
});
});

View File

@@ -21,7 +21,7 @@ const populate = (ast: TreemapAst, db: TreemapDB) => {
type: string;
value?: number;
classSelector?: string;
cssCompiledStyles?: string;
cssCompiledStyles?: string[];
}[] = [];
// Extract classes and styles from the treemap
@@ -44,7 +44,7 @@ const populate = (ast: TreemapAst, db: TreemapDB) => {
// Get styles as a string if they exist
const styles = item.classSelector ? db.getStylesForClass(item.classSelector) : [];
const cssCompiledStyles = styles.length > 0 ? styles.join(';') : undefined;
const cssCompiledStyles = styles.length > 0 ? styles : undefined;
const itemData = {
level,

View File

@@ -12,7 +12,7 @@ export function buildHierarchy(
type: string;
value?: number;
classSelector?: string;
cssCompiledStyles?: string;
cssCompiledStyles?: string[];
}[]
): TreemapNode[] {
if (!items.length) {
@@ -29,7 +29,7 @@ export function buildHierarchy(
};
node.classSelector = item?.classSelector;
if (item?.cssCompiledStyles) {
node.cssCompiledStyles = [item.cssCompiledStyles];
node.cssCompiledStyles = item.cssCompiledStyles;
}
if (item.type === 'Leaf' && item.value !== undefined) {

View File

@@ -1,90 +0,0 @@
import { BaseErrorListener } from 'antlr4ng';
import type { RecognitionException, Recognizer } from 'antlr4ng';
/**
* Custom error listener for ANTLR usecase parser
* Captures syntax errors and provides detailed error messages
*/
export class UsecaseErrorListener extends BaseErrorListener {
private errors: { line: number; column: number; message: string; offendingSymbol?: any }[] = [];
syntaxError(
_recognizer: Recognizer<any>,
offendingSymbol: any,
line: number,
charPositionInLine: number,
message: string,
_e: RecognitionException | null
): void {
this.errors.push({
line,
column: charPositionInLine,
message,
offendingSymbol,
});
}
reportAmbiguity(): void {
// Optional: handle ambiguity reports
}
reportAttemptingFullContext(): void {
// Optional: handle full context attempts
}
reportContextSensitivity(): void {
// Optional: handle context sensitivity reports
}
getErrors(): { line: number; column: number; message: string; offendingSymbol?: any }[] {
return this.errors;
}
hasErrors(): boolean {
return this.errors.length > 0;
}
clear(): void {
this.errors = [];
}
/**
* Create a detailed error with JISON-compatible hash property
*/
createDetailedError(): Error {
if (this.errors.length === 0) {
return new Error('Unknown parsing error');
}
const firstError = this.errors[0];
const message = `Parse error on line ${firstError.line}: ${firstError.message}`;
const error = new Error(message);
// Add hash property for JISON compatibility
Object.assign(error, {
hash: {
line: firstError.line,
loc: {
first_line: firstError.line,
last_line: firstError.line,
first_column: firstError.column,
last_column: firstError.column,
},
text: firstError.offendingSymbol?.text ?? '',
token: firstError.offendingSymbol?.text ?? '',
expected: [],
},
});
return error;
}
/**
* Get all error messages as a single string
*/
getErrorMessages(): string {
return this.errors
.map((error) => `Line ${error.line}:${error.column} - ${error.message}`)
.join('\n');
}
}

View File

@@ -1,65 +0,0 @@
lexer grammar UsecaseLexer;
// Keywords
ACTOR: 'actor';
SYSTEM_BOUNDARY: 'systemBoundary';
END: 'end';
DIRECTION: 'direction';
CLASS_DEF: 'classDef';
CLASS: 'class';
STYLE: 'style';
USECASE: 'usecase';
// Direction keywords
TB: 'TB';
TD: 'TD';
BT: 'BT';
RL: 'RL';
LR: 'LR';
// System boundary types
PACKAGE: 'package';
RECT: 'rect';
TYPE: 'type';
// Arrow types (order matters - longer patterns first)
SOLID_ARROW: '-->';
BACK_ARROW: '<--';
CIRCLE_ARROW: '--o';
CIRCLE_ARROW_REVERSED: 'o--';
CROSS_ARROW: '--x';
CROSS_ARROW_REVERSED: 'x--';
LINE_SOLID: '--';
// Symbols
COMMA: ',';
AT: '@';
LBRACE: '{';
RBRACE: '}';
COLON: ':';
LPAREN: '(';
RPAREN: ')';
CLASS_SEPARATOR: ':::';
// Hash color (must come before HASH to avoid conflicts)
HASH_COLOR: '#' [a-fA-F0-9]+;
// Number with optional unit
NUMBER: [0-9]+ ('.' [0-9]+)? ([a-zA-Z]+)?;
// Identifier
IDENTIFIER: [a-zA-Z_][a-zA-Z0-9_]*;
// String literals
STRING: '"' (~["\r\n])* '"' | '\'' (~['\r\n])* '\'';
// These tokens are defined last so they have lowest priority
// This ensures arrow tokens like '-->' are matched before DASH
DASH: '-';
DOT: '.';
PERCENT: '%';
// Whitespace and newlines
NEWLINE: [\r\n]+;
WS: [ \t]+ -> skip;

View File

@@ -1,429 +0,0 @@
import type { ParseTreeListener } from 'antlr4ng';
import { UsecaseParserCore } from './UsecaseParserCore.js';
import { log } from '../../../../logger.js';
import type { UsecaseDB } from '../../usecaseTypes.js';
/**
* Listener implementation that builds the usecase model
* Extends the core logic to ensure consistency with Visitor pattern
*/
export class UsecaseListener extends UsecaseParserCore implements ParseTreeListener {
constructor(db: UsecaseDB) {
super(db);
log.debug('👂 UsecaseListener: Constructor called');
}
// Standard ParseTreeListener methods
enterEveryRule = (ctx: any) => {
if (this.getEnvVar('ANTLR_DEBUG') === 'true') {
const ruleName = ctx.constructor.name;
log.debug('🔍 UsecaseListener: Entering rule:', ruleName);
}
};
exitEveryRule = (ctx: any) => {
if (this.getEnvVar('ANTLR_DEBUG') === 'true') {
const ruleName = ctx.constructor.name;
log.debug('🔍 UsecaseListener: Exiting rule:', ruleName);
}
};
visitTerminal = (_node: any) => {
// Optional: Handle terminal nodes
};
visitErrorNode = (_node: any) => {
log.debug('❌ UsecaseListener: Error node encountered');
};
// Actor statement
exitActorName = (ctx: any) => {
let actorName = '';
if (ctx.IDENTIFIER()) {
actorName = ctx.IDENTIFIER().getText();
} else if (ctx.STRING()) {
actorName = this.extractString(ctx.STRING().getText());
}
const actorId = this.generateId(actorName);
// Process metadata if present
let metadata: Record<string, string> | undefined;
if (ctx.metadata()) {
metadata = this.extractMetadata(ctx.metadata());
}
this.processActorStatement(actorId, actorName, metadata);
};
// Relationship statement
exitRelationshipStatement = (ctx: any) => {
let from = '';
let to = '';
let arrowType = 0;
let label: string | undefined;
// Get entity names
const entityNames = ctx.entityName();
if (entityNames && entityNames.length >= 2) {
from = this.extractEntityName(entityNames[0]);
to = this.extractEntityName(entityNames[1]);
} else if (ctx.actorDeclaration()) {
from = this.extractActorDeclaration(ctx.actorDeclaration());
if (entityNames && entityNames.length >= 1) {
to = this.extractEntityName(entityNames[0]);
}
}
// Get arrow type
const arrow = ctx.arrow();
if (arrow) {
const arrowResult = this.extractArrow(arrow);
arrowType = arrowResult.type;
label = arrowResult.label;
}
this.processRelationship(from, to, arrowType, label);
};
// System boundary statement
enterSystemBoundaryStatement = (ctx: any) => {
const boundaryName = ctx.systemBoundaryName();
let boundaryId = '';
let boundaryNameText = '';
if (boundaryName) {
if (boundaryName.IDENTIFIER()) {
boundaryNameText = boundaryName.IDENTIFIER().getText();
} else if (boundaryName.STRING()) {
boundaryNameText = this.extractString(boundaryName.STRING().getText());
}
boundaryId = this.generateId(boundaryNameText);
}
this.processSystemBoundaryStart(boundaryId, boundaryNameText);
};
exitSystemBoundaryStatement = (_ctx: any) => {
this.processSystemBoundaryEnd();
};
exitUsecaseInBoundary = (ctx: any) => {
let useCaseId = '';
let useCaseName = '';
let classes: string[] | undefined;
if (ctx.usecaseWithClass()) {
const withClass = ctx.usecaseWithClass();
if (withClass.IDENTIFIER()) {
const identifiers = withClass.IDENTIFIER();
if (Array.isArray(identifiers) && identifiers.length >= 2) {
useCaseId = identifiers[0].getText();
useCaseName = useCaseId;
classes = [identifiers[1].getText()];
}
} else if (withClass.STRING()) {
useCaseName = this.extractString(withClass.STRING().getText());
useCaseId = this.generateId(useCaseName);
const identifiers = withClass.IDENTIFIER();
if (identifiers) {
classes = [identifiers.getText()];
}
}
} else if (ctx.IDENTIFIER()) {
useCaseId = ctx.IDENTIFIER().getText();
useCaseName = useCaseId;
} else if (ctx.STRING()) {
useCaseName = this.extractString(ctx.STRING().getText());
useCaseId = this.generateId(useCaseName);
}
if (useCaseId && useCaseName) {
this.processUseCaseStatement(useCaseId, useCaseName, undefined, classes);
}
};
// System boundary type statement
exitSystemBoundaryTypeStatement = (ctx: any) => {
const boundaryName = ctx.systemBoundaryName();
let boundaryId = '';
if (boundaryName) {
if (boundaryName.IDENTIFIER()) {
boundaryId = boundaryName.IDENTIFIER().getText();
} else if (boundaryName.STRING()) {
boundaryId = this.generateId(this.extractString(boundaryName.STRING().getText()));
}
}
const typeContent = ctx.systemBoundaryTypeContent();
if (typeContent) {
const properties = typeContent.systemBoundaryTypeProperty();
const props = Array.isArray(properties) ? properties : [properties];
for (const prop of props) {
const type = prop.systemBoundaryType();
if (type) {
let typeValue: 'package' | 'rect' = 'rect';
if (type.PACKAGE()) {
typeValue = 'package';
} else if (type.RECT()) {
typeValue = 'rect';
}
this.processSystemBoundaryType(boundaryId, typeValue);
}
}
}
};
// Direction statement
exitDirectionStatement = (ctx: any) => {
const direction = ctx.direction();
if (direction) {
let directionText = '';
if (direction.TB()) {
directionText = 'TB';
} else if (direction.TD()) {
directionText = 'TD';
} else if (direction.BT()) {
directionText = 'BT';
} else if (direction.RL()) {
directionText = 'RL';
} else if (direction.LR()) {
directionText = 'LR';
}
this.processDirectionStatement(directionText);
}
};
// Class definition statement
exitClassDefStatement = (ctx: any) => {
let classId = '';
if (ctx.IDENTIFIER()) {
classId = ctx.IDENTIFIER().getText();
}
const styles: string[] = [];
const stylesOpt = ctx.stylesOpt();
if (stylesOpt) {
this.collectStyles(stylesOpt, styles);
}
this.processClassDefStatement(classId, styles);
};
// Class statement
exitClassStatement = (ctx: any) => {
const nodeList = ctx.nodeList();
const nodeIds: string[] = [];
if (nodeList) {
const identifiers = nodeList.IDENTIFIER();
const ids = Array.isArray(identifiers) ? identifiers : [identifiers];
for (const id of ids) {
nodeIds.push(id.getText());
}
}
let classId = '';
const identifiers = ctx.IDENTIFIER();
if (identifiers) {
const ids = Array.isArray(identifiers) ? identifiers : [identifiers];
if (ids.length > 0) {
classId = ids[ids.length - 1].getText();
}
}
this.processClassStatement(nodeIds, classId);
};
// Style statement
exitStyleStatement = (ctx: any) => {
let nodeId = '';
if (ctx.IDENTIFIER()) {
nodeId = ctx.IDENTIFIER().getText();
}
const styles: string[] = [];
const stylesOpt = ctx.stylesOpt();
if (stylesOpt) {
this.collectStyles(stylesOpt, styles);
}
this.processStyleStatement(nodeId, styles);
};
// Usecase statement
exitUsecaseStatement = (ctx: any) => {
const entityName = ctx.entityName();
if (entityName) {
const useCaseId = this.extractEntityName(entityName);
this.processUseCaseStatement(useCaseId, useCaseId);
}
};
// Helper methods
private extractMetadata(ctx: any): Record<string, string> {
const metadata: Record<string, string> = {};
const content = ctx.metadataContent();
if (content) {
const properties = content.metadataProperty();
const props = Array.isArray(properties) ? properties : [properties];
for (const prop of props) {
const strings = prop.STRING();
if (strings && strings.length >= 2) {
const key = this.extractString(strings[0].getText());
const value = this.extractString(strings[1].getText());
metadata[key] = value;
}
}
}
return metadata;
}
private extractEntityName(ctx: any): string {
if (ctx.nodeIdWithLabel()) {
const nodeId = ctx.nodeIdWithLabel();
if (nodeId.IDENTIFIER()) {
return nodeId.IDENTIFIER().getText();
}
}
if (ctx.IDENTIFIER()) {
const identifiers = ctx.IDENTIFIER();
if (Array.isArray(identifiers) && identifiers.length >= 2) {
return identifiers[0].getText();
}
return identifiers.getText ? identifiers.getText() : identifiers[0].getText();
}
if (ctx.STRING()) {
const strings = ctx.STRING();
const text = strings.getText ? strings.getText() : strings[0].getText();
return this.extractString(text);
}
return '';
}
private extractActorDeclaration(ctx: any): string {
const actorName = ctx.actorName();
if (actorName) {
if (actorName.IDENTIFIER()) {
return actorName.IDENTIFIER().getText();
} else if (actorName.STRING()) {
return this.extractString(actorName.STRING().getText());
}
}
return '';
}
private extractArrow(ctx: any): { type: number; label?: string } {
let arrowText = '';
let label: string | undefined;
if (ctx.labeledArrow()) {
const labeledArrow = ctx.labeledArrow();
const edgeLabel = labeledArrow.edgeLabel();
if (edgeLabel) {
if (edgeLabel.IDENTIFIER()) {
label = edgeLabel.IDENTIFIER().getText();
} else if (edgeLabel.STRING()) {
label = this.extractString(edgeLabel.STRING().getText());
}
}
if (labeledArrow.SOLID_ARROW()) {
arrowText = '-->';
} else if (labeledArrow.BACK_ARROW()) {
arrowText = '<--';
} else if (labeledArrow.CIRCLE_ARROW()) {
arrowText = '--o';
} else if (labeledArrow.CROSS_ARROW()) {
arrowText = '--x';
} else if (labeledArrow.CIRCLE_ARROW_REVERSED()) {
arrowText = 'o--';
} else if (labeledArrow.CROSS_ARROW_REVERSED()) {
arrowText = 'x--';
} else {
arrowText = '--';
}
} else {
if (ctx.SOLID_ARROW()) {
arrowText = '-->';
} else if (ctx.BACK_ARROW()) {
arrowText = '<--';
} else if (ctx.LINE_SOLID()) {
arrowText = '--';
} else if (ctx.CIRCLE_ARROW()) {
arrowText = '--o';
} else if (ctx.CROSS_ARROW()) {
arrowText = '--x';
} else if (ctx.CIRCLE_ARROW_REVERSED()) {
arrowText = 'o--';
} else if (ctx.CROSS_ARROW_REVERSED()) {
arrowText = 'x--';
}
}
return {
type: this.parseArrowType(arrowText),
label,
};
}
private collectStyles(ctx: any, styles: string[]): void {
if (!ctx) {
return;
}
const styleComponents = this.getAllStyleComponents(ctx);
for (const component of styleComponents) {
styles.push(component.getText());
}
}
private getAllStyleComponents(ctx: any): any[] {
const components: any[] = [];
if (ctx.style) {
const styleCtx = ctx.style();
if (styleCtx) {
this.collectStyleComponents(styleCtx, components);
}
}
if (ctx.stylesOpt) {
const stylesOptList = Array.isArray(ctx.stylesOpt()) ? ctx.stylesOpt() : [ctx.stylesOpt()];
for (const opt of stylesOptList) {
if (opt) {
this.collectStyleComponents(opt, components);
}
}
}
return components;
}
private collectStyleComponents(ctx: any, components: any[]): void {
if (!ctx) {
return;
}
if (ctx.styleComponent) {
const comp = ctx.styleComponent();
if (comp) {
components.push(comp);
}
}
if (ctx.style) {
const styleCtx = ctx.style();
if (styleCtx) {
this.collectStyleComponents(styleCtx, components);
}
}
}
}

View File

@@ -1,210 +0,0 @@
parser grammar UsecaseParser;
options {
tokenVocab = UsecaseLexer;
}
// Entry point
start: USECASE NEWLINE* statement* EOF;
// Statement types
statement
: actorStatement
| relationshipStatement
| systemBoundaryStatement
| systemBoundaryTypeStatement
| directionStatement
| classDefStatement
| classStatement
| styleStatement
| usecaseStatement
| NEWLINE
;
// Usecase statement (standalone entity)
usecaseStatement
: entityName NEWLINE*
;
// Actor statement
actorStatement
: ACTOR actorList NEWLINE*
;
actorList
: actorName (COMMA actorName)*
;
actorName
: (IDENTIFIER | STRING) metadata?
;
metadata
: AT LBRACE metadataContent RBRACE
;
metadataContent
: metadataProperty (COMMA metadataProperty)*
;
metadataProperty
: STRING COLON STRING
;
// Relationship statement
relationshipStatement
: entityName arrow entityName NEWLINE*
| actorDeclaration arrow entityName NEWLINE*
;
// System boundary statement
systemBoundaryStatement
: SYSTEM_BOUNDARY systemBoundaryName NEWLINE* systemBoundaryContent* END NEWLINE*
;
systemBoundaryName
: IDENTIFIER
| STRING
;
systemBoundaryContent
: usecaseInBoundary NEWLINE*
| NEWLINE
;
usecaseInBoundary
: usecaseWithClass
| IDENTIFIER
| STRING
;
usecaseWithClass
: IDENTIFIER CLASS_SEPARATOR IDENTIFIER
| STRING CLASS_SEPARATOR IDENTIFIER
;
// System boundary type statement
systemBoundaryTypeStatement
: systemBoundaryName AT LBRACE systemBoundaryTypeContent RBRACE NEWLINE*
;
systemBoundaryTypeContent
: systemBoundaryTypeProperty (COMMA systemBoundaryTypeProperty)*
;
systemBoundaryTypeProperty
: TYPE COLON systemBoundaryType
;
systemBoundaryType
: PACKAGE
| RECT
;
// Entity name (node reference)
entityName
: IDENTIFIER CLASS_SEPARATOR IDENTIFIER
| STRING CLASS_SEPARATOR IDENTIFIER
| IDENTIFIER
| STRING
| nodeIdWithLabel
;
// Actor declaration (inline)
actorDeclaration
: ACTOR actorName
;
// Node with label
nodeIdWithLabel
: IDENTIFIER LPAREN nodeLabel RPAREN
;
nodeLabel
: IDENTIFIER
| STRING
| nodeLabel IDENTIFIER
| nodeLabel STRING
;
// Arrow types
arrow
: SOLID_ARROW
| BACK_ARROW
| LINE_SOLID
| CIRCLE_ARROW
| CROSS_ARROW
| CIRCLE_ARROW_REVERSED
| CROSS_ARROW_REVERSED
| labeledArrow
;
labeledArrow
: LINE_SOLID edgeLabel SOLID_ARROW
| BACK_ARROW edgeLabel LINE_SOLID
| LINE_SOLID edgeLabel LINE_SOLID
| LINE_SOLID edgeLabel CIRCLE_ARROW
| LINE_SOLID edgeLabel CROSS_ARROW
| CIRCLE_ARROW_REVERSED edgeLabel LINE_SOLID
| CROSS_ARROW_REVERSED edgeLabel LINE_SOLID
;
edgeLabel
: IDENTIFIER
| STRING
;
// Direction statement
directionStatement
: DIRECTION direction NEWLINE*
;
direction
: TB
| TD
| BT
| RL
| LR
;
// Class definition statement
classDefStatement
: CLASS_DEF IDENTIFIER stylesOpt NEWLINE*
;
stylesOpt
: style
| stylesOpt COMMA style
;
style
: styleComponent
| style styleComponent
;
styleComponent
: IDENTIFIER
| NUMBER
| HASH_COLOR
| COLON
| STRING
| DASH
| DOT
| PERCENT
;
// Class statement
classStatement
: CLASS nodeList IDENTIFIER NEWLINE*
;
// Style statement
styleStatement
: STYLE IDENTIFIER stylesOpt NEWLINE*
;
// Node list
nodeList
: IDENTIFIER (COMMA IDENTIFIER)*
;

View File

@@ -1,292 +0,0 @@
import type {
UsecaseDB,
Actor,
UseCase,
SystemBoundary,
Relationship,
ClassDef,
ArrowType,
} from '../../usecaseTypes.js';
import { ARROW_TYPE } from '../../usecaseTypes.js';
import { log } from '../../../../logger.js';
/**
* Core shared logic for both Listener and Visitor patterns
* Contains all the proven parsing logic for usecase diagrams
*/
export class UsecaseParserCore {
protected db: UsecaseDB;
protected relationshipCounter = 0;
protected currentSystemBoundary: string | null = null;
protected currentSystemBoundaryUseCases: string[] = [];
constructor(db: UsecaseDB) {
this.db = db;
}
/**
* Browser-safe environment variable access
*/
protected getEnvVar(name: string): string | undefined {
try {
if (typeof process !== 'undefined' && process.env) {
return process.env[name];
}
} catch (_e) {
// process is not defined in browser
}
// Browser fallback
if (typeof window !== 'undefined' && (window as any).MERMAID_CONFIG) {
return (window as any).MERMAID_CONFIG[name];
}
return undefined;
}
/**
* Process actor statement
*/
protected processActorStatement(
actorId: string,
actorName: string,
metadata?: Record<string, string>
): void {
const actor: Actor = {
id: actorId,
name: actorName,
metadata,
};
this.db.addActor(actor);
log.debug(`Processed actor: ${actorId} (${actorName})`);
}
/**
* Process use case statement
*/
protected processUseCaseStatement(
useCaseId: string,
useCaseName: string,
nodeId?: string,
classes?: string[]
): void {
const useCase: UseCase = {
id: useCaseId,
name: useCaseName,
nodeId,
classes,
systemBoundary: this.currentSystemBoundary ?? undefined,
};
this.db.addUseCase(useCase);
// Add to current system boundary if we're inside one
if (this.currentSystemBoundary) {
this.currentSystemBoundaryUseCases.push(useCaseId);
}
log.debug(`Processed use case: ${useCaseId} (${useCaseName})`);
}
/**
* Process relationship statement
*/
protected processRelationship(from: string, to: string, arrowType: number, label?: string): void {
// Generate IDs for checking if entities exist
const fromId = this.generateId(from);
const toId = this.generateId(to);
// Ensure entities exist - if they're not actors, create them as use cases
if (!this.db.getActor(fromId) && !this.db.getUseCase(fromId)) {
this.db.addUseCase({ id: fromId, name: from });
log.debug(`Auto-created use case: ${fromId} (${from})`);
}
if (!this.db.getActor(toId) && !this.db.getUseCase(toId)) {
this.db.addUseCase({ id: toId, name: to });
log.debug(`Auto-created use case: ${toId} (${to})`);
}
const relationshipId = `rel_${this.relationshipCounter++}`;
// Determine relationship type based on arrow type and label
let type: 'association' | 'include' | 'extend' = 'association';
if (label) {
const lowerLabel = label.toLowerCase();
if (lowerLabel.includes('include')) {
type = 'include';
} else if (lowerLabel.includes('extend')) {
type = 'extend';
}
}
const relationship: Relationship = {
id: relationshipId,
from: fromId,
to: toId,
type,
arrowType: arrowType as ArrowType,
label,
};
this.db.addRelationship(relationship);
log.debug(`Processed relationship: ${fromId} -> ${toId} (${type})`);
}
/**
* Process system boundary start
*/
protected processSystemBoundaryStart(boundaryId: string, boundaryName: string): void {
this.currentSystemBoundary = boundaryId;
this.currentSystemBoundaryUseCases = [];
log.debug(`Started system boundary: ${boundaryId} (${boundaryName})`);
}
/**
* Process system boundary end
*/
protected processSystemBoundaryEnd(): void {
if (this.currentSystemBoundary) {
const systemBoundary: SystemBoundary = {
id: this.currentSystemBoundary,
name: this.currentSystemBoundary,
useCases: [...this.currentSystemBoundaryUseCases],
};
this.db.addSystemBoundary(systemBoundary);
log.debug(`Ended system boundary: ${this.currentSystemBoundary}`);
this.currentSystemBoundary = null;
this.currentSystemBoundaryUseCases = [];
}
}
/**
* Process system boundary type
*/
protected processSystemBoundaryType(boundaryId: string, type: 'package' | 'rect'): void {
const boundary = this.db.getSystemBoundary(boundaryId);
if (boundary) {
boundary.type = type;
log.debug(`Set system boundary type: ${boundaryId} -> ${type}`);
}
}
/**
* Process direction statement
*/
protected processDirectionStatement(direction: string): void {
const normalizedDirection = this.normalizeDirection(direction);
this.db.setDirection(normalizedDirection as any);
log.debug(`Set direction: ${normalizedDirection}`);
}
/**
* Normalize direction
*/
protected normalizeDirection(dir: string): string {
switch (dir) {
case 'TD':
return 'TB';
default:
return dir;
}
}
/**
* Process class definition statement
*/
protected processClassDefStatement(classId: string, styles: string[]): void {
const classDef: ClassDef = {
id: classId,
styles,
};
this.db.addClassDef(classDef);
log.debug(`Processed class definition: ${classId}`);
}
/**
* Process class statement (apply class to nodes)
*/
protected processClassStatement(nodeIds: string[], classId: string): void {
for (const nodeId of nodeIds) {
const useCase = this.db.getUseCase(nodeId);
if (useCase) {
if (!useCase.classes) {
useCase.classes = [];
}
if (!useCase.classes.includes(classId)) {
useCase.classes.push(classId);
}
log.debug(`Applied class ${classId} to use case ${nodeId}`);
}
}
}
/**
* Process style statement (apply styles directly to node)
*/
protected processStyleStatement(nodeId: string, styles: string[]): void {
const useCase = this.db.getUseCase(nodeId);
if (useCase) {
useCase.styles = styles;
log.debug(`Applied styles to use case ${nodeId}`);
}
const actor = this.db.getActor(nodeId);
if (actor) {
actor.styles = styles;
log.debug(`Applied styles to actor ${nodeId}`);
}
}
/**
* Extract text from string (remove quotes)
*/
protected extractString(text: string): string {
if (!text) {
return '';
}
// Remove surrounding quotes
if (
(text.startsWith('"') && text.endsWith('"')) ||
(text.startsWith("'") && text.endsWith("'"))
) {
return text.slice(1, -1);
}
return text;
}
/**
* Parse arrow type from token
*/
protected parseArrowType(arrowText: string): number {
switch (arrowText) {
case '-->':
return ARROW_TYPE.SOLID_ARROW;
case '<--':
return ARROW_TYPE.BACK_ARROW;
case '--':
return ARROW_TYPE.LINE_SOLID;
case '--o':
return ARROW_TYPE.CIRCLE_ARROW;
case '--x':
return ARROW_TYPE.CROSS_ARROW;
case 'o--':
return ARROW_TYPE.CIRCLE_ARROW_REVERSED;
case 'x--':
return ARROW_TYPE.CROSS_ARROW_REVERSED;
default:
return ARROW_TYPE.SOLID_ARROW;
}
}
/**
* Generate unique ID from name
*/
protected generateId(name: string): string {
return name.replace(/\W/g, '_');
}
}

View File

@@ -1,533 +0,0 @@
import { UsecaseParserCore } from './UsecaseParserCore.js';
import { log } from '../../../../logger.js';
import type { UsecaseDB } from '../../usecaseTypes.js';
/**
* Visitor implementation that builds the usecase model
* Uses the same core logic as the Listener for consistency
*/
export class UsecaseVisitor extends UsecaseParserCore {
private visitCount = 0;
constructor(db: UsecaseDB) {
super(db);
if (this.getEnvVar('ANTLR_DEBUG') === 'true') {
log.debug('🎯 UsecaseVisitor: Constructor called');
}
}
// Default visitor methods
visit(tree: any): any {
const shouldLog = this.getEnvVar('ANTLR_DEBUG') === 'true';
this.visitCount++;
if (shouldLog) {
log.debug(`🔍 UsecaseVisitor: Visiting node type: ${tree.constructor.name}`);
}
let result;
try {
result = tree.accept(this);
if (shouldLog) {
log.debug(`✅ UsecaseVisitor: Successfully visited ${tree.constructor.name}`);
}
} catch (error) {
log.error(`❌ UsecaseVisitor: Error visiting ${tree.constructor.name}:`, error);
throw error;
}
return result;
}
visitChildren(node: any): any {
if (!node) {
return null;
}
let result = null;
const n = node.getChildCount();
for (let i = 0; i < n; i++) {
const child = node.getChild(i);
if (child) {
const childResult = child.accept(this);
if (childResult !== null) {
result = childResult;
}
}
}
return result;
}
visitTerminal(_node: any): any {
return null;
}
visitErrorNode(_node: any): any {
log.error('❌ UsecaseVisitor: Error node encountered');
return null;
}
// Start rule
visitStart(ctx: any): any {
return this.visitChildren(ctx);
}
// Statement rule
visitStatement(ctx: any): any {
return this.visitChildren(ctx);
}
// Actor statement
visitActorStatement(ctx: any): any {
const actorList = ctx.actorList();
if (actorList) {
this.visitActorList(actorList);
}
return null;
}
visitActorList(ctx: any): any {
const actorNames = ctx.actorName();
if (actorNames) {
const names = Array.isArray(actorNames) ? actorNames : [actorNames];
for (const actorName of names) {
this.visitActorName(actorName);
}
}
return null;
}
visitActorName(ctx: any): any {
let actorName = '';
const identifier = ctx.IDENTIFIER();
if (identifier) {
actorName = identifier.getText();
} else {
const stringToken = ctx.STRING();
if (stringToken) {
actorName = this.extractString(stringToken.getText());
}
}
const actorId = this.generateId(actorName);
// Process metadata if present
let metadata: Record<string, string> | undefined;
const metadataCtx = ctx.metadata();
if (metadataCtx) {
metadata = this.visitMetadata(metadataCtx);
}
this.processActorStatement(actorId, actorName, metadata);
return null;
}
visitMetadata(ctx: any): Record<string, string> {
const metadata: Record<string, string> = {};
const content = ctx.metadataContent();
if (content) {
const properties = content.metadataProperty();
const props = Array.isArray(properties) ? properties : [properties];
for (const prop of props) {
const strings = prop.STRING();
if (strings && strings.length >= 2) {
const key = this.extractString(strings[0].getText());
const value = this.extractString(strings[1].getText());
metadata[key] = value;
}
}
}
return metadata;
}
// Relationship statement
visitRelationshipStatement(ctx: any): any {
let from = '';
let to = '';
let arrowType = 0;
let label: string | undefined;
// Get entity names
const entityNames = ctx.entityName();
if (entityNames && entityNames.length >= 2) {
from = this.visitEntityName(entityNames[0]);
to = this.visitEntityName(entityNames[1]);
} else if (ctx.actorDeclaration()) {
from = this.visitActorDeclaration(ctx.actorDeclaration());
if (entityNames && entityNames.length >= 1) {
to = this.visitEntityName(entityNames[0]);
}
}
// Get arrow type
const arrow = ctx.arrow();
if (arrow) {
const arrowResult = this.visitArrow(arrow);
arrowType = arrowResult.type;
label = arrowResult.label;
}
this.processRelationship(from, to, arrowType, label);
return null;
}
visitEntityName(ctx: any): string {
if (!ctx) {
return '';
}
const nodeIdWithLabel = ctx.nodeIdWithLabel();
if (nodeIdWithLabel) {
return this.visitNodeIdWithLabel(nodeIdWithLabel);
}
const identifiers = ctx.IDENTIFIER();
if (identifiers) {
if (Array.isArray(identifiers) && identifiers.length >= 2) {
// Has class separator (:::)
return identifiers[0].getText();
} else if (Array.isArray(identifiers) && identifiers.length === 1) {
return identifiers[0].getText();
}
}
const stringToken = ctx.STRING();
if (stringToken) {
return this.extractString(stringToken.getText());
}
return '';
}
visitActorDeclaration(ctx: any): string {
const actorName = ctx.actorName();
if (actorName) {
return this.visitActorName(actorName);
}
return '';
}
visitNodeIdWithLabel(ctx: any): string {
if (ctx.IDENTIFIER()) {
return ctx.IDENTIFIER().getText();
}
return '';
}
visitArrow(ctx: any): { type: number; label?: string } {
let arrowText = '';
let label: string | undefined;
if (ctx.labeledArrow()) {
const labeledArrow = ctx.labeledArrow();
const edgeLabel = labeledArrow.edgeLabel();
if (edgeLabel) {
if (edgeLabel.IDENTIFIER()) {
label = edgeLabel.IDENTIFIER().getText();
} else if (edgeLabel.STRING()) {
label = this.extractString(edgeLabel.STRING().getText());
}
}
// Determine arrow type from labeled arrow structure
if (labeledArrow.SOLID_ARROW()) {
arrowText = '-->';
} else if (labeledArrow.BACK_ARROW()) {
arrowText = '<--';
} else if (labeledArrow.CIRCLE_ARROW()) {
arrowText = '--o';
} else if (labeledArrow.CROSS_ARROW()) {
arrowText = '--x';
} else if (labeledArrow.CIRCLE_ARROW_REVERSED()) {
arrowText = 'o--';
} else if (labeledArrow.CROSS_ARROW_REVERSED()) {
arrowText = 'x--';
} else {
arrowText = '--';
}
} else {
// Simple arrow
if (ctx.SOLID_ARROW()) {
arrowText = '-->';
} else if (ctx.BACK_ARROW()) {
arrowText = '<--';
} else if (ctx.LINE_SOLID()) {
arrowText = '--';
} else if (ctx.CIRCLE_ARROW()) {
arrowText = '--o';
} else if (ctx.CROSS_ARROW()) {
arrowText = '--x';
} else if (ctx.CIRCLE_ARROW_REVERSED()) {
arrowText = 'o--';
} else if (ctx.CROSS_ARROW_REVERSED()) {
arrowText = 'x--';
}
}
return {
type: this.parseArrowType(arrowText),
label,
};
}
// System boundary statement
visitSystemBoundaryStatement(ctx: any): any {
const boundaryName = ctx.systemBoundaryName();
let boundaryId = '';
let boundaryNameText = '';
if (boundaryName) {
if (boundaryName.IDENTIFIER()) {
boundaryNameText = boundaryName.IDENTIFIER().getText();
} else if (boundaryName.STRING()) {
boundaryNameText = this.extractString(boundaryName.STRING().getText());
}
boundaryId = this.generateId(boundaryNameText);
}
this.processSystemBoundaryStart(boundaryId, boundaryNameText);
// Visit boundary content
const contents = ctx.systemBoundaryContent();
if (contents) {
const contentList = Array.isArray(contents) ? contents : [contents];
for (const content of contentList) {
this.visitSystemBoundaryContent(content);
}
}
this.processSystemBoundaryEnd();
return null;
}
visitSystemBoundaryContent(ctx: any): any {
const usecaseInBoundary = ctx.usecaseInBoundary();
if (usecaseInBoundary) {
this.visitUsecaseInBoundary(usecaseInBoundary);
}
return null;
}
visitUsecaseInBoundary(ctx: any): any {
let useCaseId = '';
let useCaseName = '';
let classes: string[] | undefined;
if (ctx.usecaseWithClass()) {
const withClass = ctx.usecaseWithClass();
if (withClass.IDENTIFIER()) {
const identifiers = withClass.IDENTIFIER();
if (Array.isArray(identifiers) && identifiers.length >= 2) {
useCaseId = identifiers[0].getText();
useCaseName = useCaseId;
classes = [identifiers[1].getText()];
}
} else if (withClass.STRING()) {
useCaseName = this.extractString(withClass.STRING().getText());
useCaseId = this.generateId(useCaseName);
const identifiers = withClass.IDENTIFIER();
if (identifiers) {
classes = [identifiers.getText()];
}
}
} else if (ctx.IDENTIFIER()) {
useCaseId = ctx.IDENTIFIER().getText();
useCaseName = useCaseId;
} else if (ctx.STRING()) {
useCaseName = this.extractString(ctx.STRING().getText());
useCaseId = this.generateId(useCaseName);
}
if (useCaseId && useCaseName) {
this.processUseCaseStatement(useCaseId, useCaseName, undefined, classes);
}
return null;
}
// System boundary type statement
visitSystemBoundaryTypeStatement(ctx: any): any {
const boundaryName = ctx.systemBoundaryName();
let boundaryId = '';
if (boundaryName) {
if (boundaryName.IDENTIFIER()) {
boundaryId = boundaryName.IDENTIFIER().getText();
} else if (boundaryName.STRING()) {
boundaryId = this.generateId(this.extractString(boundaryName.STRING().getText()));
}
}
const typeContent = ctx.systemBoundaryTypeContent();
if (typeContent) {
const properties = typeContent.systemBoundaryTypeProperty();
const props = Array.isArray(properties) ? properties : [properties];
for (const prop of props) {
const type = prop.systemBoundaryType();
if (type) {
let typeValue: 'package' | 'rect' = 'rect';
if (type.PACKAGE()) {
typeValue = 'package';
} else if (type.RECT()) {
typeValue = 'rect';
}
this.processSystemBoundaryType(boundaryId, typeValue);
}
}
}
return null;
}
// Direction statement
visitDirectionStatement(ctx: any): any {
const direction = ctx.direction();
if (direction) {
let directionText = '';
if (direction.TB()) {
directionText = 'TB';
} else if (direction.TD()) {
directionText = 'TD';
} else if (direction.BT()) {
directionText = 'BT';
} else if (direction.RL()) {
directionText = 'RL';
} else if (direction.LR()) {
directionText = 'LR';
}
this.processDirectionStatement(directionText);
}
return null;
}
// Class definition statement
visitClassDefStatement(ctx: any): any {
let classId = '';
if (ctx.IDENTIFIER()) {
classId = ctx.IDENTIFIER().getText();
}
const styles: string[] = [];
const stylesOpt = ctx.stylesOpt();
if (stylesOpt) {
this.collectStyles(stylesOpt, styles);
}
this.processClassDefStatement(classId, styles);
return null;
}
// Class statement
visitClassStatement(ctx: any): any {
const nodeList = ctx.nodeList();
const nodeIds: string[] = [];
if (nodeList) {
const identifiers = nodeList.IDENTIFIER();
const ids = Array.isArray(identifiers) ? identifiers : [identifiers];
for (const id of ids) {
nodeIds.push(id.getText());
}
}
let classId = '';
const identifiers = ctx.IDENTIFIER();
if (identifiers) {
const ids = Array.isArray(identifiers) ? identifiers : [identifiers];
if (ids.length > 0) {
classId = ids[ids.length - 1].getText();
}
}
this.processClassStatement(nodeIds, classId);
return null;
}
// Style statement
visitStyleStatement(ctx: any): any {
let nodeId = '';
if (ctx.IDENTIFIER()) {
nodeId = ctx.IDENTIFIER().getText();
}
const styles: string[] = [];
const stylesOpt = ctx.stylesOpt();
if (stylesOpt) {
this.collectStyles(stylesOpt, styles);
}
this.processStyleStatement(nodeId, styles);
return null;
}
// Usecase statement
visitUsecaseStatement(ctx: any): any {
const entityName = ctx.entityName();
if (entityName) {
const useCaseId = this.visitEntityName(entityName);
this.processUseCaseStatement(useCaseId, useCaseId);
}
return null;
}
// Helper method to collect styles
private collectStyles(ctx: any, styles: string[]): void {
if (!ctx) {
return;
}
// Visit all style components
const styleComponents = this.getAllStyleComponents(ctx);
for (const component of styleComponents) {
styles.push(component.getText());
}
}
private getAllStyleComponents(ctx: any): any[] {
const components: any[] = [];
if (ctx.style) {
const styleCtx = ctx.style();
if (styleCtx) {
this.collectStyleComponents(styleCtx, components);
}
}
if (ctx.stylesOpt) {
const stylesOptList = Array.isArray(ctx.stylesOpt()) ? ctx.stylesOpt() : [ctx.stylesOpt()];
for (const opt of stylesOptList) {
if (opt) {
this.collectStyleComponents(opt, components);
}
}
}
return components;
}
private collectStyleComponents(ctx: any, components: any[]): void {
if (!ctx) {
return;
}
if (ctx.styleComponent) {
const comp = ctx.styleComponent();
if (comp) {
components.push(comp);
}
}
if (ctx.style) {
const styleCtx = ctx.style();
if (styleCtx) {
this.collectStyleComponents(styleCtx, components);
}
}
}
}

View File

@@ -1,181 +0,0 @@
/**
* ANTLR-based Usecase Diagram Parser
*
* This is a proper ANTLR implementation using antlr-ng generated parser code.
* It provides the same interface as the existing parser for 100% compatibility.
*
* Follows the same structure as flowchart and sequence ANTLR parsers with both
* listener and visitor pattern support.
*/
import { CharStream, CommonTokenStream, ParseTreeWalker } from 'antlr4ng';
import { UsecaseLexer } from './generated/UsecaseLexer.js';
import { UsecaseParser } from './generated/UsecaseParser.js';
import { UsecaseListener } from './UsecaseListener.js';
import { UsecaseVisitor } from './UsecaseVisitor.js';
import { UsecaseErrorListener } from './UsecaseErrorListener.js';
import type { UsecaseDB } from '../../usecaseTypes.js';
import { log } from '../../../../logger.js';
/**
* Main ANTLR parser class that provides the same interface as the existing parser
*/
export class ANTLRUsecaseParser {
yy: UsecaseDB | null;
constructor() {
this.yy = null;
}
/**
* Parse usecase diagram input using ANTLR
*
* @param input - The usecase diagram text to parse
* @returns The database instance populated with parsed data
*/
parse(input: string): UsecaseDB {
if (!this.yy) {
throw new Error('Usecase ANTLR parser missing yy (database).');
}
const startTime = performance.now();
// Get environment variable helper
const getEnvVar = (name: string): string | undefined => {
try {
if (typeof process !== 'undefined' && process.env) {
return process.env[name];
}
} catch (_e) {
// process is not defined in browser
}
// Browser fallback
if (typeof window !== 'undefined' && (window as any).MERMAID_CONFIG) {
return (window as any).MERMAID_CONFIG[name];
}
return undefined;
};
const shouldLog = getEnvVar('ANTLR_DEBUG') === 'true';
if (shouldLog) {
log.debug('🎯 ANTLR Usecase Parser: Starting parse');
log.debug(`📝 Input length: ${input.length} characters`);
}
try {
// Reset database state
if (this.yy.clear) {
this.yy.clear();
}
// Create input stream and lexer
const inputStream = CharStream.fromString(input);
const lexer = new UsecaseLexer(inputStream);
// Add custom error listener to lexer
const lexerErrorListener = new UsecaseErrorListener();
lexer.removeErrorListeners();
lexer.addErrorListener(lexerErrorListener);
const tokenStream = new CommonTokenStream(lexer);
// Create parser
const parser = new UsecaseParser(tokenStream);
// Add custom error listener to parser
const parserErrorListener = new UsecaseErrorListener();
parser.removeErrorListeners();
parser.addErrorListener(parserErrorListener);
// Generate parse tree
if (shouldLog) {
log.debug('🌳 ANTLR Usecase Parser: Starting parse tree generation');
}
const tree = parser.start();
// Check for syntax errors
if (lexerErrorListener.hasErrors()) {
throw lexerErrorListener.createDetailedError();
}
if (parserErrorListener.hasErrors()) {
throw parserErrorListener.createDetailedError();
}
if (shouldLog) {
log.debug('✅ ANTLR Usecase Parser: Parse tree generated successfully');
}
// Check if we should use Visitor or Listener pattern
// Default to Visitor pattern (true) unless explicitly set to false
const useVisitorPattern = getEnvVar('USE_ANTLR_VISITOR') !== 'false';
if (shouldLog) {
log.debug('🔧 Usecase Parser: Pattern =', useVisitorPattern ? 'Visitor' : 'Listener');
}
if (useVisitorPattern) {
const visitor = new UsecaseVisitor(this.yy);
try {
visitor.visit(tree);
if (shouldLog) {
log.debug('✅ ANTLR Usecase Parser: Visitor completed successfully');
}
} catch (error) {
log.error(
'❌ ANTLR Usecase Parser: Visitor failed:',
error instanceof Error ? error.message : String(error)
);
log.error(
'❌ ANTLR Usecase Parser: Visitor stack:',
error instanceof Error ? error.stack : undefined
);
throw error;
}
} else {
const listener = new UsecaseListener(this.yy);
try {
ParseTreeWalker.DEFAULT.walk(listener, tree);
if (shouldLog) {
log.debug('✅ ANTLR Usecase Parser: Listener completed successfully');
}
} catch (error) {
log.error(
'❌ ANTLR Usecase Parser: Listener failed:',
error instanceof Error ? error.message : String(error)
);
log.error(
'❌ ANTLR Usecase Parser: Listener stack:',
error instanceof Error ? error.stack : undefined
);
throw error;
}
}
const totalTime = performance.now() - startTime;
if (shouldLog) {
log.debug(`⏱️ Total parse time: ${totalTime.toFixed(2)}ms`);
log.debug('✅ ANTLR Usecase Parser: Parse completed successfully');
}
return this.yy;
} catch (error) {
const totalTime = performance.now() - startTime;
log.error(`❌ ANTLR usecase parsing error after ${totalTime.toFixed(2)}ms:`, error);
log.error('📝 Input that caused error (first 500 chars):', input.substring(0, 500));
throw error;
}
}
// Provide the same interface as existing parser
setYY(yy: UsecaseDB) {
this.yy = yy;
}
}
// Export for compatibility with existing code
export const parser = new ANTLRUsecaseParser();
export default parser;

View File

@@ -1,87 +0,0 @@
const getStyles = (options: any) =>
`
.actor {
stroke: ${options.primaryColor};
fill: ${options.primaryColor};
}
.actor-label {
fill: ${options.primaryTextColor};
font-family: ${options.fontFamily};
font-size: 14px;
font-weight: normal;
}
.usecase-actor-shape line {
stroke: ${options.actorBorder};
fill: ${options.actorBkg};
}
.usecase-actor-shape circle, line {
stroke: ${options.actorBorder};
fill: ${options.actorBkg};
stroke-width: 2px;
}
.usecase {
stroke: ${options.primaryColor};
fill: ${options.primaryColor};
}
.usecase-label {
fill: ${options.primaryTextColor};
font-family: ${options.fontFamily};
font-size: 12px;
font-weight: normal;
}
/* Ellipse shape styling for use cases */
.usecase-element ellipse {
fill: ${options.mainBkg ?? '#ffffff'};
stroke: ${options.primaryColor};
stroke-width: 2px;
}
.usecase-element .label {
fill: ${options.primaryTextColor};
font-family: ${options.fontFamily};
font-size: 12px;
font-weight: normal;
text-anchor: middle;
dominant-baseline: central;
}
/* General ellipse styling */
.node ellipse {
fill: ${options.mainBkg ?? '#ffffff'};
stroke: ${options.nodeBorder ?? options.primaryColor};
stroke-width: 1px;
}
.relationship {
stroke: ${options.lineColor};
fill: none;
}
& .marker {
fill: ${options.lineColor};
stroke: ${options.lineColor};
}
.relationship-label {
fill: ${options.primaryTextColor};
font-family: ${options.fontFamily};
font-size: 10px;
font-weight: normal;
}
.nodeLabel, .edgeLabel {
color: ${options.classText};
}
.system-boundary {
fill: ${options.clusterBkg};
stroke: ${options.clusterBorder};
stroke-width: 1px;
}
`;
export default getStyles;

View File

@@ -1,501 +0,0 @@
import { vi, describe, it, expect, beforeEach, beforeAll } from 'vitest';
import { Diagram } from '../../Diagram.js';
import { addDiagrams } from '../../diagram-api/diagram-orchestration.js';
import { db } from './usecaseDb.js';
beforeAll(async () => {
// Is required to load the useCase diagram
await Diagram.fromText('usecase\n actor TestActor');
});
/**
* UseCase diagrams require a basic d3 mock for rendering
*/
vi.mock('d3', () => {
const NewD3 = function (this: any) {
function returnThis(this: any) {
return this;
}
return {
append: function () {
return NewD3();
},
lower: returnThis,
attr: returnThis,
style: returnThis,
text: returnThis,
getBBox: function () {
return {
height: 10,
width: 20,
};
},
};
};
return {
select: function () {
return new (NewD3 as any)();
},
selectAll: function () {
return new (NewD3 as any)();
},
// TODO: In d3 these are CurveFactory types, not strings
curveBasis: 'basis',
curveBasisClosed: 'basisClosed',
curveBasisOpen: 'basisOpen',
curveBumpX: 'bumpX',
curveBumpY: 'bumpY',
curveBundle: 'bundle',
curveCardinalClosed: 'cardinalClosed',
curveCardinalOpen: 'cardinalOpen',
curveCardinal: 'cardinal',
curveCatmullRomClosed: 'catmullRomClosed',
curveCatmullRomOpen: 'catmullRomOpen',
curveCatmullRom: 'catmullRom',
curveLinear: 'linear',
curveLinearClosed: 'linearClosed',
curveMonotoneX: 'monotoneX',
curveMonotoneY: 'monotoneY',
curveNatural: 'natural',
curveStep: 'step',
curveStepAfter: 'stepAfter',
curveStepBefore: 'stepBefore',
};
});
// -------------------------------
addDiagrams();
describe('UseCase diagram with ANTLR parser', () => {
beforeEach(() => {
db.clear();
});
describe('when parsing basic actors', () => {
it('should parse a single actor', async () => {
const diagram = await Diagram.fromText(
`usecase
actor User`
);
expect(diagram).toBeDefined();
expect(diagram.type).toBe('usecase');
const actors = db.getActors();
expect(actors.size).toBe(1);
expect(actors.has('User')).toBe(true);
expect(actors.get('User')?.name).toBe('User');
});
it('should parse multiple actors', async () => {
await Diagram.fromText(
`usecase
actor User
actor Admin
actor Guest`
);
const actors = db.getActors();
expect(actors.size).toBe(3);
expect(actors.has('User')).toBe(true);
expect(actors.has('Admin')).toBe(true);
expect(actors.has('Guest')).toBe(true);
});
it('should parse actor with simple name', async () => {
await Diagram.fromText(
`usecase
actor SystemUser`
);
const actors = db.getActors();
expect(actors.size).toBe(1);
expect(actors.has('SystemUser')).toBe(true);
});
});
describe('when parsing use cases', () => {
it('should parse use cases from relationships', async () => {
await Diagram.fromText(
`usecase
actor User
User --> Login`
);
const useCases = db.getUseCases();
expect(useCases.size).toBe(1);
expect(useCases.has('Login')).toBe(true);
});
it('should parse multiple use cases from relationships', async () => {
await Diagram.fromText(
`usecase
actor User
User --> Login
User --> Logout
User --> Register`
);
const useCases = db.getUseCases();
expect(useCases.size).toBe(3);
expect(useCases.has('Login')).toBe(true);
expect(useCases.has('Logout')).toBe(true);
expect(useCases.has('Register')).toBe(true);
});
it('should parse use case from relationship', async () => {
await Diagram.fromText(
`usecase
actor User
User --> UserLoginProcess`
);
const useCases = db.getUseCases();
expect(useCases.size).toBe(1);
expect(useCases.has('UserLoginProcess')).toBe(true);
});
it('should parse use cases with quoted names', async () => {
await Diagram.fromText(
`usecase
actor "Customer Service"
actor "System Administrator"
"Customer Service" --> "Handle Tickets"
"System Administrator" --> "Manage System"`
);
const actors = db.getActors();
expect(actors.size).toBe(2);
// IDs are generated with underscores replacing spaces
expect(actors.has('Customer_Service')).toBe(true);
expect(actors.has('System_Administrator')).toBe(true);
// But names should preserve the original text
expect(actors.get('Customer_Service')?.name).toBe('Customer Service');
expect(actors.get('System_Administrator')?.name).toBe('System Administrator');
const useCases = db.getUseCases();
expect(useCases.size).toBe(2);
expect(useCases.has('Handle_Tickets')).toBe(true);
expect(useCases.has('Manage_System')).toBe(true);
expect(useCases.get('Handle_Tickets')?.name).toBe('Handle Tickets');
expect(useCases.get('Manage_System')?.name).toBe('Manage System');
});
});
describe('when parsing relationships', () => {
it('should parse actor to use case relationship', async () => {
await Diagram.fromText(
`usecase
actor User
User --> Login`
);
const relationships = db.getRelationships();
expect(relationships.length).toBe(1);
expect(relationships[0].from).toBe('User');
expect(relationships[0].to).toBe('Login');
expect(relationships[0].type).toBe('association');
});
it('should parse multiple relationships', async () => {
await Diagram.fromText(
`usecase
actor User
User --> Login
User --> Logout`
);
const relationships = db.getRelationships();
expect(relationships.length).toBe(2);
expect(relationships[0].from).toBe('User');
expect(relationships[0].to).toBe('Login');
expect(relationships[1].from).toBe('User');
expect(relationships[1].to).toBe('Logout');
});
it('should parse relationship with label', async () => {
await Diagram.fromText(
`usecase
actor Developer
Developer --important--> WriteCode`
);
const relationships = db.getRelationships();
expect(relationships.length).toBe(1);
expect(relationships[0].label).toBe('important');
});
it('should parse different arrow types', async () => {
await Diagram.fromText(
`usecase
actor User
actor Admin
User --> Login
Admin <-- Logout
User -- ViewData`
);
const relationships = db.getRelationships();
expect(relationships.length).toBe(3);
});
});
describe('when parsing system boundaries', () => {
it('should parse a system boundary', async () => {
await Diagram.fromText(
`usecase
actor Admin, User
systemBoundary "Authentication"
Login
Logout
end
Admin --> Login
User --> Login`
);
const boundaries = db.getSystemBoundaries();
expect(boundaries.size).toBeGreaterThan(0);
});
it('should parse use cases within system boundary', async () => {
await Diagram.fromText(
`usecase
actor User
systemBoundary "Authentication System"
Login
Logout
end
User --> Login`
);
const useCases = db.getUseCases();
expect(useCases.size).toBe(2);
expect(useCases.has('Login')).toBe(true);
expect(useCases.has('Logout')).toBe(true);
});
});
describe('when parsing direction', () => {
it('should handle TB direction', async () => {
await Diagram.fromText(
`usecase
direction TB
actor User`
);
expect(db.getDirection()).toBe('TB');
});
it('should handle LR direction', async () => {
await Diagram.fromText(
`usecase
direction LR
actor User`
);
expect(db.getDirection()).toBe('LR');
});
it('should normalize TD to TB', async () => {
await Diagram.fromText(
`usecase
direction TD
actor User`
);
expect(db.getDirection()).toBe('TB');
});
});
describe('when parsing actor metadata', () => {
it('should parse actor with metadata', async () => {
await Diagram.fromText(
`usecase
actor User@{ "type" : "primary", "icon" : "user" }
User --> Login`
);
const actors = db.getActors();
expect(actors.size).toBe(1);
const user = actors.get('User');
expect(user).toBeDefined();
expect(user?.metadata).toBeDefined();
});
it('should parse multiple actors with different metadata', async () => {
await Diagram.fromText(
`usecase
actor User@{ "type" : "primary", "icon" : "user" }
actor Admin@{ "type" : "secondary", "icon" : "admin" }
User --> Login
Admin --> ManageUsers`
);
const actors = db.getActors();
expect(actors.size).toBe(2);
});
});
describe('when parsing complex diagrams', () => {
it('should parse a complete authentication system', async () => {
await Diagram.fromText(
`usecase
actor User
actor Admin
systemBoundary "Authentication System"
Login
Logout
Register
ResetPassword
end
User --> Login
User --> Register
User --> Logout
Admin --> Login`
);
const actors = db.getActors();
const useCases = db.getUseCases();
const relationships = db.getRelationships();
expect(actors.size).toBe(2);
expect(useCases.size).toBe(4);
expect(relationships.length).toBe(4);
});
it('should parse diagram with multiple arrow types', async () => {
await Diagram.fromText(
`usecase
actor User
actor Admin
User --> Login
Admin <-- Logout
User -- ViewData`
);
const relationships = db.getRelationships();
expect(relationships.length).toBe(3);
});
it('should handle use case creation from relationships', async () => {
await Diagram.fromText(
`usecase
actor Developer
Developer --> LoginSystem
Developer --> Authentication`
);
const useCases = db.getUseCases();
expect(useCases.size).toBe(2);
expect(useCases.has('LoginSystem')).toBe(true);
expect(useCases.has('Authentication')).toBe(true);
});
});
describe('when parsing class definitions', () => {
it('should handle classDef', async () => {
await Diagram.fromText(
`usecase
actor User
User --> Login
classDef important fill:#f96,stroke:#333,stroke-width:4px
class Login important`
);
const classDefs = db.getClassDefs();
expect(classDefs.size).toBeGreaterThan(0);
});
});
describe('database methods', () => {
it('should clear all data', async () => {
await Diagram.fromText(
`usecase
actor User
User --> Login`
);
expect(db.getActors().size).toBe(1);
expect(db.getUseCases().size).toBe(1);
expect(db.getRelationships().length).toBe(1);
db.clear();
expect(db.getActors().size).toBe(0);
expect(db.getUseCases().size).toBe(0);
expect(db.getRelationships().length).toBe(0);
});
it('should get specific actor by id', async () => {
await Diagram.fromText(
`usecase
actor User
actor Admin`
);
const user = db.getActor('User');
expect(user).toBeDefined();
expect(user?.id).toBe('User');
expect(user?.name).toBe('User');
});
it('should get specific use case by id', async () => {
await Diagram.fromText(
`usecase
actor User
User --> Login
User --> Logout`
);
const login = db.getUseCase('Login');
expect(login).toBeDefined();
expect(login?.id).toBe('Login');
expect(login?.name).toBe('Login');
});
it('should return undefined for non-existent actor', () => {
const actor = db.getActor('NonExistent');
expect(actor).toBeUndefined();
});
it('should return undefined for non-existent use case', () => {
const useCase = db.getUseCase('NonExistent');
expect(useCase).toBeUndefined();
});
});
describe('getData method', () => {
it('should convert diagram data to LayoutData format', async () => {
await Diagram.fromText(
`usecase
actor User
User --> Login`
);
const data = db.getData();
expect(data).toBeDefined();
expect(data.nodes).toBeDefined();
expect(data.edges).toBeDefined();
expect(data.nodes.length).toBe(2);
expect(data.edges.length).toBe(1);
expect(data.type).toBe('usecase');
});
it('should include direction in layout data', async () => {
await Diagram.fromText(
`usecase
direction LR
actor User`
);
const data = db.getData();
expect(data.direction).toBe('LR');
});
});
});

View File

@@ -1,397 +0,0 @@
import { log } from '../../logger.js';
import {
setAccTitle,
getAccTitle,
setDiagramTitle,
getDiagramTitle,
getAccDescription,
setAccDescription,
clear as commonClear,
} from '../common/commonDb.js';
import type {
UsecaseFields,
UsecaseDB,
Actor,
UseCase,
SystemBoundary,
Relationship,
ActorMetadata,
Direction,
ClassDef,
} from './usecaseTypes.js';
import { DEFAULT_DIRECTION, ARROW_TYPE } from './usecaseTypes.js';
import type { RequiredDeep } from 'type-fest';
import type { UsecaseDiagramConfig } from '../../config.type.js';
import DEFAULT_CONFIG from '../../defaultConfig.js';
import { getConfig as getGlobalConfig } from '../../diagram-api/diagramAPI.js';
import type { LayoutData, Node, ClusterNode, Edge } from '../../rendering-util/types.js';
export const DEFAULT_USECASE_CONFIG: Required<UsecaseDiagramConfig> = DEFAULT_CONFIG.usecase;
export const DEFAULT_USECASE_DB: RequiredDeep<UsecaseFields> = {
actors: new Map(),
useCases: new Map(),
systemBoundaries: new Map(),
relationships: [],
classDefs: new Map(),
direction: DEFAULT_DIRECTION,
config: DEFAULT_USECASE_CONFIG,
} as const;
let actors = new Map<string, Actor>();
let useCases = new Map<string, UseCase>();
let systemBoundaries = new Map<string, SystemBoundary>();
let relationships: Relationship[] = [];
let classDefs = new Map<string, ClassDef>();
let direction: Direction = DEFAULT_DIRECTION;
const config: Required<UsecaseDiagramConfig> = structuredClone(DEFAULT_USECASE_CONFIG);
const getConfig = (): Required<UsecaseDiagramConfig> => structuredClone(config);
const clear = (): void => {
actors = new Map();
useCases = new Map();
systemBoundaries = new Map();
relationships = [];
classDefs = new Map();
direction = DEFAULT_DIRECTION;
commonClear();
};
// Actor management
const addActor = (actor: Actor): void => {
if (!actor.id || !actor.name) {
throw new Error(
`Invalid actor: Actor must have both id and name. Received: ${JSON.stringify(actor)}`
);
}
if (!actors.has(actor.id)) {
actors.set(actor.id, actor);
log.debug(`Added actor: ${actor.id} (${actor.name})`);
} else {
log.debug(`Actor ${actor.id} already exists`);
}
};
const getActors = (): Map<string, Actor> => actors;
const getActor = (id: string): Actor | undefined => actors.get(id);
// UseCase management
const addUseCase = (useCase: UseCase): void => {
if (!useCase.id || !useCase.name) {
throw new Error(
`Invalid use case: Use case must have both id and name. Received: ${JSON.stringify(useCase)}`
);
}
if (!useCases.has(useCase.id)) {
useCases.set(useCase.id, useCase);
log.debug(`Added use case: ${useCase.id} (${useCase.name})`);
} else {
log.debug(`Use case ${useCase.id} already exists`);
}
};
const getUseCases = (): Map<string, UseCase> => useCases;
const getUseCase = (id: string): UseCase | undefined => useCases.get(id);
// SystemBoundary management
const addSystemBoundary = (systemBoundary: SystemBoundary): void => {
if (!systemBoundary.id || !systemBoundary.name) {
throw new Error(
`Invalid system boundary: System boundary must have both id and name. Received: ${JSON.stringify(systemBoundary)}`
);
}
if (!systemBoundaries.has(systemBoundary.id)) {
systemBoundaries.set(systemBoundary.id, systemBoundary);
log.debug(`Added system boundary: ${systemBoundary.name}`);
} else {
log.debug(`System boundary ${systemBoundary.id} already exists`);
}
};
const getSystemBoundaries = (): Map<string, SystemBoundary> => systemBoundaries;
const getSystemBoundary = (id: string): SystemBoundary | undefined => systemBoundaries.get(id);
// Relationship management
const addRelationship = (relationship: Relationship): void => {
// Validate relationship structure
if (!relationship.id || !relationship.from || !relationship.to) {
throw new Error(
`Invalid relationship: Relationship must have id, from, and to fields. Received: ${JSON.stringify(relationship)}`
);
}
if (!relationship.type) {
throw new Error(
`Invalid relationship: Relationship must have a type. Received: ${JSON.stringify(relationship)}`
);
}
// Validate relationship type
const validTypes = ['association', 'include', 'extend'];
if (!validTypes.includes(relationship.type)) {
throw new Error(
`Invalid relationship type: ${relationship.type}. Valid types are: ${validTypes.join(', ')}`
);
}
// Validate arrow type if present
if (relationship.arrowType !== undefined) {
const validArrowTypes = [0, 1, 2, 3, 4, 5, 6]; // SOLID_ARROW, BACK_ARROW, LINE_SOLID, CIRCLE_ARROW, CROSS_ARROW
if (!validArrowTypes.includes(relationship.arrowType)) {
throw new Error(
`Invalid arrow type: ${relationship.arrowType}. Valid arrow types are: ${validArrowTypes.join(', ')}`
);
}
}
relationships.push(relationship);
log.debug(
`Added relationship: ${relationship.from} -> ${relationship.to} (${relationship.type})`
);
};
const getRelationships = (): Relationship[] => relationships;
// ClassDef management
const addClassDef = (classDef: ClassDef): void => {
if (!classDef.id) {
throw new Error(
`Invalid classDef: ClassDef must have an id. Received: ${JSON.stringify(classDef)}`
);
}
classDefs.set(classDef.id, classDef);
log.debug(`Added classDef: ${classDef.id}`);
};
const getClassDefs = (): Map<string, ClassDef> => classDefs;
const getClassDef = (id: string): ClassDef | undefined => classDefs.get(id);
/**
* Get compiled styles from class definitions
* Similar to flowchart's getCompiledStyles method
*/
const getCompiledStyles = (classNames: string[]): string[] => {
let compiledStyles: string[] = [];
for (const className of classNames) {
const cssClass = classDefs.get(className);
if (cssClass?.styles) {
compiledStyles = [...compiledStyles, ...(cssClass.styles ?? [])].map((s) => s.trim());
}
}
return compiledStyles;
};
// Direction management
const setDirection = (dir: Direction): void => {
// Normalize TD to TB (same as flowchart)
if (dir === 'TD') {
direction = 'TB';
} else {
direction = dir;
}
log.debug('Direction set to:', direction);
};
const getDirection = (): Direction => direction;
// Convert usecase diagram data to LayoutData format for unified rendering
const getData = (): LayoutData => {
const globalConfig = getGlobalConfig();
const nodes: Node[] = [];
const edges: Edge[] = [];
// Convert actors to nodes
for (const actor of actors.values()) {
const classesArray = ['default', 'usecase-actor'];
const cssCompiledStyles = getCompiledStyles(classesArray);
// Determine which shape to use based on whether actor has an icon
const actorShape = actor.metadata?.icon ? 'usecaseActorIcon' : 'usecaseActor';
const node: Node = {
id: actor.id,
label: actor.name,
description: actor.description ? [actor.description] : undefined,
shape: actorShape, // Use icon shape if icon is present, otherwise stick figure
isGroup: false,
padding: 10,
look: globalConfig.look,
// Add metadata as data attributes for styling
cssClasses: `usecase-actor ${
actor.metadata && Object.keys(actor.metadata).length > 0
? Object.entries(actor.metadata)
.map(([key, value]) => `actor-${key}-${value}`)
.join(' ')
: ''
}`.trim(),
cssStyles: actor.styles ?? [], // Direct styles
cssCompiledStyles, // Compiled styles from class definitions
// Pass actor metadata to the shape handler
metadata: actor.metadata,
} as Node & { metadata?: ActorMetadata };
nodes.push(node);
}
// Convert use cases to nodes
for (const useCase of useCases.values()) {
// Build CSS classes string
let cssClasses = 'usecase-element';
const classesArray = ['default', 'usecase-element'];
if (useCase.classes && useCase.classes.length > 0) {
cssClasses += ' ' + useCase.classes.join(' ');
classesArray.push(...useCase.classes);
}
// Get compiled styles from class definitions
const cssCompiledStyles = getCompiledStyles(classesArray);
const node: Node = {
id: useCase.id,
label: useCase.name,
description: useCase.description ? [useCase.description] : undefined,
shape: 'ellipse', // Use ellipse shape for use cases
isGroup: false,
padding: 10,
look: globalConfig.look,
cssClasses,
cssStyles: useCase.styles ?? [], // Direct styles
cssCompiledStyles, // Compiled styles from class definitions
// If use case belongs to a system boundary, set parentId
...(useCase.systemBoundary && { parentId: useCase.systemBoundary }),
};
nodes.push(node);
}
// Convert system boundaries to group nodes
for (const boundary of systemBoundaries.values()) {
const classesArray = [
'default',
'system-boundary',
`system-boundary-${boundary.type ?? 'rect'}`,
];
const cssCompiledStyles = getCompiledStyles(classesArray);
const node: ClusterNode & { boundaryType?: string } = {
id: boundary.id,
label: boundary.name,
shape: 'usecaseSystemBoundary', // Use custom usecase system boundary cluster shape
isGroup: true, // System boundaries are clusters (containers for other nodes)
padding: 20,
look: globalConfig.look,
cssClasses: `system-boundary system-boundary-${boundary.type ?? 'rect'}`,
cssStyles: boundary.styles ?? [], // Direct styles
cssCompiledStyles, // Compiled styles from class definitions
// Pass boundary type to the shape handler
boundaryType: boundary.type,
};
nodes.push(node);
}
// Convert relationships to edges
relationships.forEach((relationship, index) => {
// Determine arrow types based on relationship.arrowType
let arrowTypeEnd = 'none';
let arrowTypeStart = 'none';
switch (relationship.arrowType) {
case ARROW_TYPE.SOLID_ARROW: // -->
arrowTypeEnd = 'arrow_point';
break;
case ARROW_TYPE.BACK_ARROW: // <--
arrowTypeStart = 'arrow_point';
break;
case ARROW_TYPE.CIRCLE_ARROW: // --o
arrowTypeEnd = 'arrow_circle';
break;
case ARROW_TYPE.CROSS_ARROW: // --x
arrowTypeEnd = 'arrow_cross';
break;
case ARROW_TYPE.CIRCLE_ARROW_REVERSED: // o--
arrowTypeStart = 'arrow_circle';
break;
case ARROW_TYPE.CROSS_ARROW_REVERSED: // x--
arrowTypeStart = 'arrow_cross';
break;
case ARROW_TYPE.LINE_SOLID: // --
// Both remain 'none'
break;
}
const edge: Edge = {
id: relationship.id || `edge-${index}`,
start: relationship.from,
end: relationship.to,
source: relationship.from,
target: relationship.to,
label: relationship.label,
labelpos: 'c', // Center label position for proper dagre layout
type: relationship.type,
arrowTypeEnd,
arrowTypeStart,
classes: `relationship relationship-${relationship.type}`,
look: globalConfig.look,
thickness: 'normal',
pattern: 'solid',
};
edges.push(edge);
});
return {
nodes,
edges,
config: globalConfig,
// Additional properties that layout algorithms might expect
type: 'usecase',
layoutAlgorithm: 'dagre', // Default layout algorithm
direction: getDirection(), // Use the current direction setting
nodeSpacing: 50, // Default node spacing
rankSpacing: 50, // Default rank spacing
markers: ['arrow_point'], // Arrow point markers used in usecase diagrams
};
};
export const db: UsecaseDB = {
getConfig,
clear,
setDiagramTitle,
getDiagramTitle,
setAccTitle,
getAccTitle,
setAccDescription,
getAccDescription,
addActor,
getActors,
getActor,
addUseCase,
getUseCases,
getUseCase,
addSystemBoundary,
getSystemBoundaries,
getSystemBoundary,
addRelationship,
getRelationships,
addClassDef,
getClassDefs,
getClassDef,
// Direction management
setDirection,
getDirection,
// Add getData method for unified rendering
getData,
};

View File

@@ -1,22 +0,0 @@
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'usecase';
const detector: DiagramDetector = (txt) => {
return /^\s*usecase/.test(txt);
};
const loader: DiagramLoader = async () => {
const { diagram } = await import('./usecaseDiagram.js');
return { id, diagram };
};
export const usecase: ExternalDiagramDefinition = {
id,
detector,
loader,
};

View File

@@ -1,12 +0,0 @@
import type { DiagramDefinition } from '../../diagram-api/types.js';
import { parser } from './usecaseParser.js';
import { db } from './usecaseDb.js';
import { renderer } from './usecaseRenderer.js';
import styles from './styles.js';
export const diagram: DiagramDefinition = {
parser,
db,
renderer,
styles,
};

View File

@@ -1,58 +0,0 @@
// Import local ANTLR parser
import { log } from '../../logger.js';
import type { ParserDefinition } from '../../diagram-api/types.js';
import { db } from './usecaseDb.js';
// Import local ANTLR parser implementation
import antlrParser from './parser/antlr/antlr-parser.js';
/**
* Parse usecase diagram using local ANTLR parser
*/
const parseUsecaseWithLocalAntlr = (input: string) => {
// Set the database instance
antlrParser.yy = db;
// Parse and return the populated database
return antlrParser.parse(input);
};
export const parser: ParserDefinition = {
parse: (input: string): void => {
log.debug('Parsing usecase diagram with local ANTLR parser:', input);
try {
// Use local ANTLR parser
parseUsecaseWithLocalAntlr(input);
log.debug('ANTLR parsing completed successfully');
} catch (error) {
log.error('Error parsing usecase diagram:', error);
// Check if it's a UsecaseParseError from our ANTLR parser
if (
error &&
typeof error === 'object' &&
'name' in error &&
error.name === 'UsecaseParseError'
) {
// Re-throw the detailed error for better error reporting
throw error;
}
// For other errors, wrap them in a generic error
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
const wrappedError = new Error(`Failed to parse usecase diagram: ${errorMessage}`);
// Add hash property for consistency with other diagram types
(wrappedError as any).hash = {
text: input.split('\n')[0] || '',
token: 'unknown',
line: '1',
loc: { first_line: 1, last_line: 1, first_column: 1, last_column: 1 },
expected: ['valid usecase syntax'],
};
throw wrappedError;
}
},
};

View File

@@ -1,48 +0,0 @@
import type { DrawDefinition } from '../../diagram-api/types.js';
import { log } from '../../logger.js';
import { getDiagramElement } from '../../rendering-util/insertElementsForSize.js';
import { getRegisteredLayoutAlgorithm, render } from '../../rendering-util/render.js';
import { setupViewPortForSVG } from '../../rendering-util/setupViewPortForSVG.js';
import { getConfig } from '../../diagram-api/diagramAPI.js';
import utils from '../../utils.js';
import type { UsecaseDB } from './usecaseTypes.js';
/**
* Main draw function using unified rendering system
*/
const draw: DrawDefinition = async (_text, id, _version, diag) => {
log.info('Drawing usecase diagram (unified)', id);
const { securityLevel, usecase: conf, layout } = getConfig();
// The getData method provided in all supported diagrams is used to extract the data from the parsed structure
// into the Layout data format
const usecaseDb = diag.db as UsecaseDB;
const data4Layout = usecaseDb.getData();
// Create the root SVG - the element is the div containing the SVG element
const svg = getDiagramElement(id, securityLevel);
data4Layout.type = diag.type;
data4Layout.layoutAlgorithm = getRegisteredLayoutAlgorithm(layout);
data4Layout.nodeSpacing = 50; // Default node spacing
data4Layout.rankSpacing = 50; // Default rank spacing
data4Layout.markers = ['point', 'circle', 'cross']; // Support point, circle, and cross markers
data4Layout.diagramId = id;
log.debug('Usecase layout data:', data4Layout);
// Use the unified rendering system
await render(data4Layout, svg);
const padding = 8;
utils.insertTitle(
svg,
'usecaseDiagramTitleText',
0, // Default title top margin
usecaseDb.getDiagramTitle?.() ?? ''
);
setupViewPortForSVG(svg, padding, 'usecaseDiagram', conf?.useMaxWidth ?? false);
};
export const renderer = { draw };

View File

@@ -1,40 +0,0 @@
const getStyles = (options: any) =>
`
.actor {
stroke: ${options.primaryColor};
fill: ${options.primaryColor};
}
.actor-label {
fill: ${options.primaryTextColor};
font-family: ${options.fontFamily};
font-size: 14px;
font-weight: normal;
}
.usecase {
stroke: ${options.primaryColor};
fill: ${options.primaryColor};
}
.usecase-label {
fill: ${options.primaryTextColor};
font-family: ${options.fontFamily};
font-size: 12px;
font-weight: normal;
}
.relationship {
stroke: ${options.primaryColor};
fill: ${options.primaryColor};
}
.relationship-label {
fill: ${options.primaryTextColor};
font-family: ${options.fontFamily};
font-size: 10px;
font-weight: normal;
}
`;
export default getStyles;

Some files were not shown because too many files have changed in this diff Show More