archrip 0.2.9 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/install/slash-commands.d.ts +2 -0
  2. package/dist/install/slash-commands.d.ts.map +1 -1
  3. package/dist/install/slash-commands.js +23 -18
  4. package/dist/install/slash-commands.js.map +1 -1
  5. package/dist/schema/architecture.schema.json +0 -1
  6. package/dist/templates/slash-commands/{claude → shared}/archrip-scan.md +9 -9
  7. package/dist/utils/layout.js +3 -2
  8. package/dist/utils/layout.js.map +1 -1
  9. package/dist/utils/layout.spec.js +28 -0
  10. package/dist/utils/layout.spec.js.map +1 -1
  11. package/dist/utils/validate.d.ts +0 -1
  12. package/dist/utils/validate.d.ts.map +1 -1
  13. package/dist/utils/validate.js +0 -3
  14. package/dist/utils/validate.js.map +1 -1
  15. package/dist/utils/validate.spec.js +0 -27
  16. package/dist/utils/validate.spec.js.map +1 -1
  17. package/dist/viewer-template/package.json +0 -1
  18. package/dist/viewer-template/src/App.tsx +6 -11
  19. package/dist/viewer-template/src/components/DetailPanel.tsx +1 -79
  20. package/dist/viewer-template/src/data/loader.ts +1 -14
  21. package/dist/viewer-template/src/hooks/useArchitecture.ts +1 -3
  22. package/dist/viewer-template/src/hooks/useUseCaseFilter.ts +1 -8
  23. package/dist/viewer-template/src/index.css +6 -0
  24. package/dist/viewer-template/src/types.ts +4 -63
  25. package/package.json +1 -1
  26. package/dist/templates/slash-commands/codex/archrip-scan.md +0 -222
  27. package/dist/templates/slash-commands/codex/archrip-update.md +0 -39
  28. package/dist/templates/slash-commands/gemini/archrip-scan.md +0 -222
  29. package/dist/templates/slash-commands/gemini/archrip-update.md +0 -39
  30. package/dist/viewer-template/src/components/DepthFilter.tsx +0 -43
  31. package/dist/viewer-template/src/components/nodes/GroupNode.tsx +0 -62
  32. package/dist/viewer-template/src/hooks/useDepthFilter.ts +0 -192
  33. package/dist/viewer-template/src/utils/layout.ts +0 -229
  34. /package/dist/templates/slash-commands/{claude → shared}/archrip-update.md +0 -0
@@ -1,222 +0,0 @@
1
- ---
2
- description: Scan codebase and generate architecture diagram data
3
- ---
4
-
5
- # archrip scan — Analyze codebase architecture
6
-
7
- Analyze the current codebase and generate `.archrip/architecture.json`.
8
-
9
- **Language rule:** Respond in the same language as the user's message or `$ARGUMENTS`. If no user text is available, detect the project's primary language from README/docs and match it. The `architecture.json` fields (labels, descriptions) should also use that language.
10
-
11
- ## Phase 1: Project Discovery
12
- 1. Read top-level files (package.json, composer.json, go.mod, Cargo.toml, pom.xml, pyproject.toml, etc.)
13
- 2. Identify language, framework, source root
14
- 3. List directory structure (2 levels deep)
15
- 4. Auto-detect `sourceUrl`: Run `git remote get-url origin` and convert to browse URL:
16
- - `git@github.com:org/repo.git` → `https://github.com/org/repo/blob/main/{filePath}`
17
- - `https://github.com/org/repo.git` → `https://github.com/org/repo/blob/main/{filePath}`
18
- - `git@gitlab.com:org/repo.git` → `https://gitlab.com/org/repo/-/blob/main/{filePath}`
19
- - If no git remote, leave empty (ask in Phase 7)
20
-
21
- ## Phase 2: Documentation Discovery
22
- Read existing documentation to understand architecture context:
23
- 1. Check for: README.md, CLAUDE.md, docs/, doc/, wiki/, ARCHITECTURE.md, CONTRIBUTING.md, ADR/
24
- 2. For each document, extract and take notes on:
25
- - **Business context**: What problem does this system solve? Who are the users?
26
- - **Component responsibilities**: What each module/service does and why it exists
27
- - **Design decisions & constraints**: Why certain patterns/libraries were chosen, known limitations
28
- - **Data flow**: How data moves through the system (request lifecycle, event flow, etc.)
29
- - **External integrations**: What external services are used, why, and how
30
- - **Non-functional requirements**: SLAs, performance targets, security policies
31
- - **Deployment & infrastructure**: Hosting, CI/CD, environment details
32
- 3. Keep these notes — you will use them in Phase 4 to write rich node/edge descriptions and metadata
33
-
34
- ## Phase 3: Layer Identification
35
- Assign each component a `layer` integer. The rule: **higher layer = closer to domain core (more stable, fewer external dependencies). Lower layer = closer to external world (more volatile, I/O-bound).**
36
-
37
- Both layouts use this value — dagre places higher layers lower on screen, concentric places them at the center.
38
-
39
- **Reference mappings** (layer numbers in parentheses — adapt to actual project structure):
40
-
41
- MVC / Layered:
42
- - Laravel: External(0) → Controllers(1) → Services(2) → Domain(3)
43
- - Rails: External(0) → Controllers(1) → Services(2) → Domain(3)
44
- - Django: External(0) → Views(1) → Serializers(2) → Services(3) → Domain(4)
45
- - Spring Boot: External(0) → Controllers(1) → Services(2) → Repositories(3) → Domain(4)
46
- - NestJS: External(0) → Controllers(1) → Services(2) → Repositories(3) → Domain(4)
47
- - Next.js App Router: External(0) → Route Handlers/Pages(1) → Components(2) → Hooks/Services(3) → Data Access(4)
48
- - FastAPI: External(0) → Routers(1) → Services(2) → Repositories(3) → Domain(4)
49
-
50
- DDD / Clean Architecture / Hexagonal (use `"layout": "concentric"`):
51
- - Generic: External(0) → Adapters(1) [Controllers, DB impl, API clients] → Application Services(2) → Ports(3) [domain-defined interfaces] → Domain(4)
52
- - Go (Hex): External(0) → Adapters(1) [Handlers, Repositories] → Use Cases(2) → Ports(3) → Domain(4)
53
- - Flutter (Clean): External(0) → Data Sources(1) → Repositories(2) → Use Cases(3) → Domain(4)
54
- - Note: Ports are interfaces **defined by the domain** — they belong near domain core, not at the adapter layer. Adapters implement/use Ports from the outside.
55
-
56
- CQRS / Event-Driven:
57
- - CQRS: External(0) → Command Handlers / Query Handlers(1) → Application Services(2) → Domain(3). Command and Query sides share the same layer structure but separate models
58
- - Event Sourcing: External(0) → Command Handlers(1) → Event Store(2) → Projections(3) → Read Models(4)
59
- - Event-Driven (Motia, Temporal, etc.): External(0) → API Steps(1) → Event Steps(2) → Services(3) → Domain(4)
60
-
61
- Serverless / Microservices:
62
- - SST/Lambda: External(0) → API Gateway(1) → Lambda Handlers(2) → Services(3) → Domain(4)
63
- - Microservices: External(0) → Gateway/BFF(1) → Service Boundaries(2) → Internal Services(3) → Shared Domain(4)
64
-
65
- Modular Monolith:
66
- - Generic: External(0) → Module APIs(1) [public interfaces] → Module Internal Services(2) → Shared Kernel / Domain(3)
67
-
68
- For unlisted frameworks: group by directory responsibility and apply the abstract rule above.
69
-
70
- ## Phase 4: Read Key Files
71
- For each layer, read representative files to extract:
72
- - Component names and purposes
73
- - Dependencies (imports, injections)
74
- - Public methods/routes
75
- - Database schemas (from migrations or model definitions)
76
-
77
- **Enrich descriptions from documentation:** Cross-reference code with your Phase 2 notes.
78
- For each component, compose a `description` (1-3 sentences) that covers:
79
- - **What**: Its responsibility (from code analysis)
80
- - **Why**: Business context or design rationale (from docs)
81
- - **How**: Key implementation details, constraints, or patterns worth noting
82
-
83
- A good description tells the reader something they cannot see from the label alone.
84
- - BAD: "User service" (just echoes the label)
85
- - GOOD: "Handles user registration, login, and profile management. Uses JWT for session tokens with 24h expiry. Password hashing via bcrypt (cost=12)."
86
-
87
- Also identify metadata candidates:
88
- - SLA/performance notes → `metadata` with `type: "list"`
89
- - Related doc links → `metadata` with `type: "link"`
90
- - Infrastructure details (Lambda ARN, DB engine, etc.) → `metadata` with `type: "code"` or `"text"`
91
-
92
- **Do NOT read every file.** Focus on entry points, core logic, interfaces, and data models.
93
-
94
- ## Phase 5: Map Relationships
95
- For each component, identify:
96
- - What it depends on (imports, constructor injection)
97
- - What depends on it
98
- - External service connections
99
-
100
- **Connectivity check:** After mapping, verify every node has at least one edge. If a node is orphaned:
101
- - DTOs/entities → connect to the service or adapter that references them
102
- - External services → connect to the adapter/controller that integrates with them
103
- - Models → connect to the adapter/repository that queries them
104
-
105
- ## Phase 6: Identify Use Cases
106
- Group related components into user-facing features.
107
-
108
- ## Phase 7: Draft Review — STOP and ask the developer
109
-
110
- **IMPORTANT: Do NOT proceed to Phase 8 until the developer responds. You MUST stop here and wait for input.**
111
-
112
- Present a summary of what you found:
113
- - **Documents read**: List all docs you read in Phase 2 (e.g., README.md, CLAUDE.md, docs/architecture.md)
114
- - List of discovered nodes (grouped by layer/category)
115
- - List of discovered use cases
116
- - External services found
117
-
118
- Then ask:
119
- - Are there other documents you should read? (e.g., docs/, wiki/, design docs)
120
- - Are there missing components, external services, or use cases?
121
- - Should anything be excluded?
122
- - `sourceUrl` auto-detected as: `<detected-url>` — correct? (If not detected, ask for the `sourceUrl` template, e.g., `https://github.com/org/repo/blob/main/{filePath}`)
123
-
124
- End your message with: **"Please review and reply with corrections, or type 'go' to generate."**
125
-
126
- **Do NOT write architecture.json yet. Wait for the developer to respond.**
127
-
128
- If the developer replies with corrections, apply them and present the updated summary. Repeat until they say "go" / "ok" / "skip".
129
-
130
- ## Phase 8: Generate architecture.json
131
- Only run this phase AFTER the developer has approved the draft in Phase 7.
132
-
133
- Create `.archrip/` directory if it doesn't exist, then write the complete `.archrip/architecture.json` following the schema, incorporating developer feedback.
134
-
135
- After writing the file:
136
- 1. Run `npx archrip serve` in the terminal — it auto-builds and opens the browser. **Do NOT run `npx archrip build` separately or open the browser manually** (serve handles everything).
137
- 2. Tell the developer: Run `/archrip-update` to make further adjustments (add/remove nodes, fix relationships, etc.)
138
-
139
- ### Required structure (use EXACTLY these field names)
140
-
141
- ```json
142
- {
143
- "version": "1.0",
144
- "project": { "name": "...", "sourceUrl": "https://github.com/org/repo/blob/main/{filePath}" },
145
- "nodes": [
146
- { "id": "ctrl-users", "category": "controller", "label": "UsersController", "layer": 1, "filePath": "src/controllers/users.ts", "useCases": ["uc-user-mgmt"] }
147
- ],
148
- "edges": [
149
- { "source": "ctrl-users", "target": "svc-users", "type": "dependency" }
150
- ],
151
- "useCases": [
152
- { "id": "uc-user-mgmt", "name": "User Management", "nodeIds": ["ctrl-users", "svc-users"] }
153
- ]
154
- }
155
- ```
156
-
157
- **Critical field names — do NOT use alternatives:**
158
- - Node: `id`, `category`, `label` (NOT name), `layer` — all required
159
- - Edge: `source`, `target` (NOT from/to) — all required
160
- - UseCase: `id`, `name`, `nodeIds` — all required
161
-
162
- ### Node Rules
163
- - `id`: kebab-case, prefixed by category abbreviation (ctrl-, svc-, port-, adpt-, model-, db-, ext-, job-, dto-)
164
- - `layer`: non-negative integer. **Higher = closer to domain core / more stable. Lower = closer to external world / more volatile.** Dagre (TB) places higher layers lower on screen; concentric places them at center. Use as many layers as the architecture requires (typically 3-6). Example for DDD: 0=external, 1=adapters (controllers + infra), 2=app services, 3=ports, 4=domain. Example for MVC: 0=external, 1=controllers, 2=services, 3=domain.
165
- - `category`: one of controller, service, port, adapter, model, database, external, job, dto (or custom). Use `model` for domain entities/value objects (core business logic). Use `database` for DB tables, migrations, ORMs, and infrastructure persistence.
166
- - `label`: display name for the node
167
- - `description`: 1-3 sentences explaining responsibility + business context. Do NOT just echo the label. Cross-reference documentation for richer context (see Description Guidelines below)
168
- - `filePath`: relative from project root
169
- - `depth` (optional): 0=overview, 1=structure, 2=detail. Auto-inferred from `layer` if omitted: with 3+ unique layers, lowest → 0, middle → 1, highest → 2. With 1-2 layers, all nodes get depth 0 (always visible).
170
- - `useCases`: array of use case IDs this node participates in
171
- - `metadata` (optional): array of `{ label, value, type? }` entries for supplementary info (AWS ARNs, doc links, SLA notes, etc.). `type` is `text` (default), `code`, `link`, or `list`. `value` is a string, or `string[]` when `type` is `list`. Example:
172
- ```json
173
- "metadata": [
174
- { "label": "Lambda ARN", "value": "arn:aws:lambda:ap-northeast-1:123:function:auth", "type": "code" },
175
- { "label": "API Docs", "value": "https://docs.example.com/auth", "type": "link" },
176
- { "label": "SLA", "value": ["99.9% uptime", "p95 < 200ms"], "type": "list" }
177
- ]
178
- ```
179
-
180
- ### Edge Rules
181
- - `source`: source node id
182
- - `target`: target node id
183
- - `type`: dependency | implements | relation
184
- - `description` (optional): human-readable description of the edge's purpose
185
- - `metadata` (optional): same format as node metadata — array of `{ label, value, type? }` entries
186
- - Only include significant architectural dependencies (not utility imports)
187
- - **Every node MUST have at least one edge.** If a node has no obvious dependency, connect it with a `relation` edge to the component that uses or contains it.
188
-
189
- ### Layout Selection
190
- - DDD / Clean Architecture / Hexagonal / Onion Architecture → add `"layout": "concentric"` to `project`
191
- - MVC / standard layered → `"layout": "dagre"` (default, can be omitted)
192
-
193
- ### Description Guidelines
194
-
195
- #### Node `description`
196
- Write 1-3 sentences that explain responsibility AND business context.
197
- Cross-reference project documentation (README, CLAUDE.md, docs/) for richer context.
198
- - BAD: "User service" (just echoes the label)
199
- - BAD: "Handles users" (too vague)
200
- - GOOD: "Handles user registration, authentication, and profile management. Uses JWT for session tokens; password hashing via bcrypt. Rate-limited to 10 req/s per IP."
201
-
202
- #### Edge `description`
203
- Explain WHY the dependency exists, not just THAT it exists.
204
- - BAD: "calls" / "depends on"
205
- - GOOD: "Delegates payment processing via Stripe SDK; retries on timeout (3x with exponential backoff)"
206
-
207
- #### `metadata` for supplementary details
208
- Use `metadata` to capture information from docs that doesn't fit in `description`:
209
- ```json
210
- "metadata": [
211
- { "label": "SLA", "value": ["99.9% uptime", "p95 < 200ms"], "type": "list" },
212
- { "label": "Design Doc", "value": "https://...", "type": "link" },
213
- { "label": "Infrastructure", "value": "Lambda + DynamoDB (on-demand)", "type": "text" },
214
- { "label": "Rate Limit", "value": "10 req/s per IP", "type": "text" }
215
- ]
216
- ```
217
-
218
- ### Schema Rules
219
- - Include table schema only when migration files or model annotations are available
220
- - Reference from node data using schema key name
221
-
222
- $ARGUMENTS
@@ -1,39 +0,0 @@
1
- ---
2
- description: Update or refine the architecture diagram
3
- ---
4
-
5
- # archrip update — Update architecture diagram
6
-
7
- Read `.archrip/architecture.json` and update it.
8
-
9
- ## Mode 1: Auto-detect from git diff (no arguments)
10
-
11
- If `$ARGUMENTS` is empty:
12
-
13
- 1. Run `git diff --name-only HEAD~10` to find changed files
14
- 2. Read the current `.archrip/architecture.json`
15
- 3. For each changed file:
16
- - New component? → Add node + edges
17
- - Removed component? → Remove node + edges + use case references
18
- - Changed dependencies? → Update edges
19
- 4. Preserve existing node IDs for unchanged components
20
- 5. Write updated `.archrip/architecture.json`
21
-
22
- ## Mode 2: Apply requested changes (with arguments)
23
-
24
- If `$ARGUMENTS` is provided, apply the user's requested changes:
25
- - Add/remove/modify nodes
26
- - Fix relationships
27
- - Add/modify use cases
28
- - Adjust layer assignments
29
- - Add database schemas
30
- - Add/modify metadata entries
31
- - Improve descriptions
32
-
33
- Write the updated `.archrip/architecture.json`.
34
-
35
- ## After Update
36
-
37
- After writing the file, run `npx archrip serve` in the terminal to rebuild and preview the updated diagram.
38
-
39
- $ARGUMENTS
@@ -1,43 +0,0 @@
1
- import { DEPTH_LEVELS } from '../types.ts';
2
- import type { DepthLevel } from '../types.ts';
3
-
4
- interface DepthFilterProps {
5
- depthLevel: DepthLevel;
6
- onSelect: (level: DepthLevel) => void;
7
- }
8
-
9
- export function DepthFilter({ depthLevel, onSelect }: DepthFilterProps) {
10
- return (
11
- <div
12
- className="rounded-lg p-3 w-64 border"
13
- style={{
14
- background: 'var(--color-surface-primary)',
15
- borderColor: 'var(--color-border-primary)',
16
- boxShadow: 'var(--shadow-panel)',
17
- }}
18
- >
19
- <h3
20
- className="text-xs font-semibold uppercase tracking-wider mb-2"
21
- style={{ color: 'var(--color-content-tertiary)' }}
22
- >
23
- Depth
24
- </h3>
25
- <div className="flex gap-1">
26
- {DEPTH_LEVELS.map(({ level, label }) => (
27
- <button
28
- key={level}
29
- onClick={() => onSelect(level)}
30
- className="flex-1 text-xs py-1.5 px-2 rounded font-medium transition-colors cursor-pointer"
31
- style={
32
- depthLevel === level
33
- ? { background: 'var(--color-interactive-primary)', color: 'var(--color-content-inverse)' }
34
- : { background: 'var(--color-surface-secondary)', color: 'var(--color-content-secondary)' }
35
- }
36
- >
37
- {label}
38
- </button>
39
- ))}
40
- </div>
41
- </div>
42
- );
43
- }
@@ -1,62 +0,0 @@
1
- import { Handle, Position } from '@xyflow/react';
2
- import type { NodeProps } from '@xyflow/react';
3
- import type { ArchFlowNode } from '../../types.ts';
4
- import { getCategoryColors, getCategoryIcon } from '../../types.ts';
5
-
6
- export function GroupNode({ data, selected }: NodeProps<ArchFlowNode>) {
7
- const d = data;
8
- const colors = getCategoryColors(d.category);
9
- const icon = getCategoryIcon(d.category);
10
-
11
- return (
12
- <>
13
- <Handle type="target" position={Position.Top} style={{ background: colors.border }} />
14
- <div
15
- style={{
16
- background: colors.bg,
17
- border: `2px dashed ${selected ? 'var(--color-border-focus)' : colors.border}`,
18
- borderRadius: 12,
19
- padding: '8px 12px',
20
- minWidth: 160,
21
- maxWidth: 220,
22
- cursor: 'pointer',
23
- boxShadow: selected ? 'var(--shadow-node-selected)' : 'var(--shadow-node)',
24
- transition: 'box-shadow 0.15s, border-color 0.15s',
25
- position: 'relative',
26
- }}
27
- >
28
- {/* Count badge */}
29
- {d.memberCount != null && (
30
- <div
31
- style={{
32
- position: 'absolute',
33
- top: -8,
34
- right: -8,
35
- background: colors.border,
36
- color: '#fff',
37
- fontSize: 10,
38
- fontWeight: 700,
39
- width: 20,
40
- height: 20,
41
- borderRadius: '50%',
42
- display: 'flex',
43
- alignItems: 'center',
44
- justifyContent: 'center',
45
- lineHeight: 1,
46
- }}
47
- >
48
- {d.memberCount}
49
- </div>
50
- )}
51
-
52
- <div style={{ fontSize: 11, color: colors.text, opacity: 0.7, marginBottom: 2 }}>
53
- {icon} {d.category.toUpperCase()}
54
- </div>
55
- <div style={{ fontSize: 13, fontWeight: 600, color: colors.text, lineHeight: 1.3, wordBreak: 'break-word' }}>
56
- {d.label}
57
- </div>
58
- </div>
59
- <Handle type="source" position={Position.Bottom} style={{ background: colors.border }} />
60
- </>
61
- );
62
- }
@@ -1,192 +0,0 @@
1
- import { useMemo } from 'react';
2
- import { useQueryState, parseAsInteger } from 'nuqs';
3
- import type { Edge } from '@xyflow/react';
4
-
5
- import type { ArchFlowNode, ArchNodeData, DepthLevel, MemberNodeSummary } from '../types.ts';
6
- import { getCategoryLabel } from '../types.ts';
7
- import { computeLayout, NODE_WIDTH, NODE_HEIGHT, GROUP_NODE_WIDTH, GROUP_NODE_HEIGHT } from '../utils/layout.ts';
8
-
9
- function clampDepth(value: number): DepthLevel {
10
- if (value <= 0) return 0;
11
- if (value >= 2) return 2;
12
- return 1;
13
- }
14
-
15
- export function useDepthFilter(
16
- nodes: ArchFlowNode[],
17
- edges: Edge[],
18
- layoutType: 'dagre' | 'concentric',
19
- ) {
20
- const [rawDepth, setRawDepth] = useQueryState('depth', parseAsInteger.withDefault(2).withOptions({ history: 'replace' }));
21
- const depthLevel = clampDepth(rawDepth);
22
-
23
- const setDepthLevel = (level: DepthLevel) => {
24
- void setRawDepth(level);
25
- };
26
-
27
- const { visibleNodes, visibleEdges } = useMemo(() => {
28
- // depth=2 (Detail): pass-through, no merging
29
- if (depthLevel === 2) {
30
- return { visibleNodes: nodes, visibleEdges: edges };
31
- }
32
-
33
- // Split nodes into kept (visible at this depth) and mergeable (to be grouped)
34
- const kept: ArchFlowNode[] = [];
35
- const mergeable: ArchFlowNode[] = [];
36
-
37
- for (const node of nodes) {
38
- if (node.data.depth <= depthLevel) {
39
- kept.push(node);
40
- } else {
41
- mergeable.push(node);
42
- }
43
- }
44
-
45
- // Group mergeable nodes by category
46
- const categoryGroups = new Map<string, ArchFlowNode[]>();
47
- for (const node of mergeable) {
48
- const cat = node.data.category;
49
- const group = categoryGroups.get(cat);
50
- if (group) {
51
- group.push(node);
52
- } else {
53
- categoryGroups.set(cat, [node]);
54
- }
55
- }
56
-
57
- // Build nodeToGroup mapping & create group nodes
58
- const nodeToGroup = new Map<string, string>();
59
- const groupNodes: ArchFlowNode[] = [];
60
-
61
- for (const [category, groupMembers] of categoryGroups) {
62
- if (groupMembers.length === 1) {
63
- // Singleton: keep as-is, no grouping
64
- kept.push(groupMembers[0]!);
65
- continue;
66
- }
67
-
68
- const groupId = `__group_${category}`;
69
-
70
- // Map all member IDs to the group ID
71
- for (const member of groupMembers) {
72
- nodeToGroup.set(member.id, groupId);
73
- }
74
-
75
- // Collect member summaries
76
- const memberNodes: MemberNodeSummary[] = groupMembers.map((m) => ({
77
- id: m.id,
78
- label: m.data.label,
79
- description: m.data.description,
80
- filePath: m.data.filePath,
81
- sourceUrl: m.data.sourceUrl,
82
- }));
83
-
84
- // Merge useCases from all members
85
- const useCasesSet = new Set<string>();
86
- for (const m of groupMembers) {
87
- for (const uc of m.data.useCases) {
88
- useCasesSet.add(uc);
89
- }
90
- }
91
-
92
- // Use the most common layer from members for layout
93
- const layerCounts = new Map<number, number>();
94
- for (const m of groupMembers) {
95
- const l = m.data.layer ?? 0;
96
- layerCounts.set(l, (layerCounts.get(l) ?? 0) + 1);
97
- }
98
- let bestLayer = 0;
99
- let bestCount = 0;
100
- for (const [l, c] of layerCounts) {
101
- if (c > bestCount) {
102
- bestLayer = l;
103
- bestCount = c;
104
- }
105
- }
106
-
107
- const label = `${getCategoryLabel(category)} (${groupMembers.length})`;
108
-
109
- const data: ArchNodeData = {
110
- label,
111
- category,
112
- depth: 0,
113
- description: `${groupMembers.length} ${getCategoryLabel(category).toLowerCase()} nodes`,
114
- filePath: '',
115
- sourceUrl: '',
116
- layer: bestLayer,
117
- useCases: [...useCasesSet],
118
- isGroup: true,
119
- memberCount: groupMembers.length,
120
- memberNodes,
121
- };
122
-
123
- groupNodes.push({
124
- id: groupId,
125
- type: 'groupNode',
126
- position: { x: 0, y: 0 }, // will be computed by layout
127
- data,
128
- });
129
- }
130
-
131
- // Combine kept + group nodes
132
- const allNodes = [...kept, ...groupNodes];
133
-
134
- // Remap edges
135
- const edgeSet = new Set<string>();
136
- const remappedEdges: Edge[] = [];
137
-
138
- for (const edge of edges) {
139
- const source = nodeToGroup.get(edge.source) ?? edge.source;
140
- const target = nodeToGroup.get(edge.target) ?? edge.target;
141
-
142
- // Skip self-loops (same group)
143
- if (source === target) continue;
144
-
145
- // Skip if either endpoint doesn't exist in allNodes
146
- const sourceExists = allNodes.some((n) => n.id === source);
147
- const targetExists = allNodes.some((n) => n.id === target);
148
- if (!sourceExists || !targetExists) continue;
149
-
150
- // Deduplicate by (source, target)
151
- const key = `${source}->${target}`;
152
- if (edgeSet.has(key)) continue;
153
- edgeSet.add(key);
154
-
155
- remappedEdges.push({
156
- ...edge,
157
- id: key,
158
- source,
159
- target,
160
- });
161
- }
162
-
163
- // Compute layout for merged graph
164
- const layoutNodes = allNodes.map((n) => ({
165
- id: n.id,
166
- width: n.data.isGroup ? GROUP_NODE_WIDTH : NODE_WIDTH,
167
- height: n.data.isGroup ? GROUP_NODE_HEIGHT : NODE_HEIGHT,
168
- layer: n.data.layer,
169
- category: n.data.category,
170
- }));
171
-
172
- const layoutEdges = remappedEdges.map((e) => ({
173
- source: e.source,
174
- target: e.target,
175
- }));
176
-
177
- const positions = computeLayout(layoutNodes, layoutEdges, layoutType);
178
-
179
- // Apply computed positions
180
- const positionedNodes: ArchFlowNode[] = allNodes.map((node) => {
181
- const pos = positions.get(node.id);
182
- if (pos) {
183
- return { ...node, position: { x: pos.x, y: pos.y } };
184
- }
185
- return node;
186
- });
187
-
188
- return { visibleNodes: positionedNodes, visibleEdges: remappedEdges };
189
- }, [nodes, edges, depthLevel, layoutType]);
190
-
191
- return { depthLevel, setDepthLevel, visibleNodes, visibleEdges };
192
- }