-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerateRepomap.ts
executable file
·1106 lines (995 loc) · 33.1 KB
/
generateRepomap.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* generateRepomap.ts
* Visualizes TypeScript codebases as Mermaid diagrams with AI-powered analysis
*
* Core Features:
* - Generates visual repository maps from TypeScript codebases
* - Supports feature integration planning with AI assistance
* - Creates role-based diagrams with automatic styling
* - Implements font size scaling based on file complexity
* - Supports incremental updates with --no-repomix option
*
* Process Flow:
* 1. XML Generation: Analyze codebase structure using repomix
* 2. Data Parsing: Convert XML to structured format using Gemini
* 3. Diagram Creation: Generate Mermaid diagram using Claude
* 4. Feature Planning: (Optional) Visualize proposed features
*
* Dependencies:
* - repomix: Codebase analysis and XML generation
* - OpenRouter API: AI model access (Gemini, Claude)
* - Mermaid: Diagram rendering
*
* Usage:
* generateRepomap [directory] [--add "feature request"] [--no-repomix]
*
* Options:
* directory Target directory (defaults to current)
* --add Add a proposed feature to the diagram
* --no-repomix Skip repomix analysis, use existing files
*
* Environment:
* LLM_API_KEY OpenRouter API key (required)
*
* @author George Stephens
* @license MIT
*/
//----------------------------------------
// Core Dependencies
//----------------------------------------
import { execSync } from "child_process";
import * as fs from "fs";
import * as path from "path";
import * as dotenv from "dotenv";
import * as os from "os";
import { z } from "zod";
import { BaseChatModel } from "@langchain/core/language_models/chat_models";
import { ChatMessage, BaseMessage } from "@langchain/core/messages";
//----------------------------------------
// Model Configuration
//----------------------------------------
/**
* XML Parsing Model (Steps 1-2)
* Gemini model optimized for structured data extraction
*/
const XML_PARSING_MODEL = "google/gemini-flash-1.5-8b";
/**
* Diagram Generation Model (Step 3)
* Claude model for intelligent diagram creation and code understanding
*/
const DIAGRAM_GENERATION_MODEL = "anthropic/claude-3.5-sonnet:beta";
/**
* Feature Planning Model (Step 4)
* Claude model for architectural analysis and feature integration
*/
const FEATURE_PLANNING_MODEL = "anthropic/claude-3.5-sonnet:beta";
//----------------------------------------
// Type Definitions
//----------------------------------------
/**
* IntermediateData Interface
* Structured format for codebase representation between XML and Mermaid
*/
interface IntermediateData {
files: {
path: string;
imports: string[];
exports: string[];
relationships: { type: string; target: string }[];
}[];
directories: string[];
}
//----------------------------------------
// OpenRouter Integration
//----------------------------------------
/**
* OpenRouterChatModel
* Custom LangChain implementation for OpenRouter API
*
* Features:
* - Automatic retries with exponential backoff
* - Request timeout handling (default: 5 minutes)
* - JSON response parsing with markdown cleanup
* - Detailed error handling and reporting
*/
export class OpenRouterChatModel extends BaseChatModel {
private apiKey: string;
private model: string;
private siteUrl: string;
private siteName: string;
private maxRetries: number;
private timeout: number;
constructor(config: {
apiKey: string;
model?: string;
siteUrl?: string;
siteName?: string;
maxRetries?: number;
timeout?: number;
}) {
super({});
this.apiKey = config.apiKey;
this.model = config.model || "google/gemini-2.0-flash-exp:free";
this.siteUrl = config.siteUrl || "https://github.com/George5562/Repomap";
this.siteName = config.siteName || "RepoMap";
this.maxRetries = config.maxRetries || 3;
this.timeout = config.timeout || 300000;
}
_llmType(): string {
return "openrouter";
}
bindTools(tools: any[], kwargs?: any): any {
return this;
}
private async makeRequest(
messages: BaseMessage[],
attempt: number = 1
): Promise<any> {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
const response = await fetch(
"https://openrouter.ai/api/v1/chat/completions",
{
method: "POST",
headers: {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
"HTTP-Referer": this.siteUrl,
"X-Title": this.siteName,
},
body: JSON.stringify({
model: this.model,
messages: messages.map((m) => ({
role: m._getType() === "human" ? "user" : m._getType(),
content: m.content,
})),
}),
signal: controller.signal,
}
);
clearTimeout(timeoutId);
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`OpenRouter API error: ${response.statusText}\n${errorText}`
);
}
const result = await response.json();
if (
!result.choices ||
!result.choices.length ||
!result.choices[0].message
) {
throw new Error("Invalid response format from OpenRouter API");
}
return result;
} catch (error) {
if (attempt < this.maxRetries) {
console.log(
`\n⚠️ attempt ${attempt} failed, retrying in ${
attempt * 2
} seconds...`
);
await new Promise((resolve) => setTimeout(resolve, attempt * 2000));
return this.makeRequest(messages, attempt + 1);
}
throw error;
}
}
async _generate(messages: BaseMessage[]): Promise<any> {
try {
const result = await this.makeRequest(messages);
const content = result.choices[0].message.content;
let parsedContent = content;
if (typeof content === "string") {
try {
// Remove markdown code block markers if present
const cleanContent = content.replace(/```json\n?|\n?```/g, "").trim();
parsedContent = JSON.parse(cleanContent);
} catch (e) {
// If not valid JSON, use as is
parsedContent = { diagram: content };
}
}
return {
generations: [
{
text:
typeof parsedContent === "object"
? JSON.stringify(parsedContent)
: parsedContent,
message: new ChatMessage({
content:
typeof parsedContent === "object"
? JSON.stringify(parsedContent)
: parsedContent,
role: result.choices[0].message.role || "assistant",
}),
},
],
};
} catch (error) {
console.error("\n❌ API error details:", error);
throw error;
}
}
}
//----------------------------------------
// Visual Style Configuration
//----------------------------------------
/**
* Role Definitions
* Maps file types to visual representations in the diagram
*/
const ROLE_DEFINITIONS = [
{ role: "page", shape: "rectangle", color: "#d0ebff" }, // UI/routing files
{ role: "component", shape: "stadium", color: "#d3f9d8" }, // Reusable UI elements
{ role: "service", shape: "circle", color: "#ffe8cc" }, // Business logic
{ role: "config", shape: "triangle", color: "#ffe3e3" }, // Configuration files
];
/**
* Relationship Types
* Defines valid connection types between nodes
*/
const RELATIONSHIP_VERBS = [
"uses", // General dependency
"calls", // Function/method invocation
"renders", // Component rendering
"fetches from", // Data retrieval
"provides data to", // Data provision
];
/**
* Font Size Configuration
* Scales node text based on file complexity
*/
const MIN_LINES = 100; // Files ≤100 lines: 10px
const MAX_LINES = 500; // Files ≥500 lines: 20px
const MIN_FONT = 10;
const MAX_FONT = 20;
/**
* Global Configuration Paths
*/
const HOME_DIR = os.homedir();
const GLOBAL_CONFIG_DIR = path.join(HOME_DIR, ".config", "generateRepomap");
const GLOBAL_CONFIG_FILE = path.join(GLOBAL_CONFIG_DIR, ".env");
//----------------------------------------
// CLI Help Documentation
//----------------------------------------
function printHelp() {
console.log(`
usage:
generateRepomap [directory] [--add "feature request"] [--no-repomix]
examples:
generateRepomap ./src
generateRepomap ./src --add "add a search feature for listings"
generateRepomap ./src --no-repomix --add "add another feature"
if no directory is specified, uses current directory.
if --no-repomix is specified, we skip running repomix and rely on previously generated files.
`);
}
//----------------------------------------
// API Key Management
//----------------------------------------
/**
* getApiKey
* Retrieves OpenRouter API key from available sources
*
* Search Order:
* 1. Environment variable
* 2. Local .env file
* 3. Global config file
*
* @returns API key if found
* @throws Error if no API key is found
*/
function getApiKey(): string {
try {
if (process.env.LLM_API_KEY) return process.env.LLM_API_KEY;
const localEnv = dotenv.config();
if (localEnv.parsed?.LLM_API_KEY) return localEnv.parsed.LLM_API_KEY;
if (fs.existsSync(GLOBAL_CONFIG_FILE)) {
const globalEnvResult = dotenv.config({
path: GLOBAL_CONFIG_FILE,
override: true,
});
if (globalEnvResult.error)
throw new Error(
`error reading global config: ${globalEnvResult.error.message}`
);
if (process.env.LLM_API_KEY) return process.env.LLM_API_KEY;
}
console.error("\n❌ API key not found.");
console.error(
"please set LLM_API_KEY via env var, local .env, or global config."
);
process.exit(1);
} catch (error) {
console.error(
"\n❌ error reading config:",
error instanceof Error ? error.message : String(error)
);
process.exit(1);
}
}
//----------------------------------------
// File System Operations
//----------------------------------------
/**
* runRepomix
* Executes repomix analysis on target directory
*/
function runRepomix(targetDir: string, outputFile: string) {
console.log("\n🔍 Step 1: Running repomix analysis...");
try {
execSync(`npx repomix analyze "${targetDir}" -o "${outputFile}"`, {
stdio: "inherit",
});
console.log("✅ XML generation complete");
} catch (error) {
console.error("\n❌ Error in Step 1 - XML generation:", error);
throw error;
}
}
/**
* prepareOutputDirectory
* Creates output directory if needed
*/
function prepareOutputDirectory(outputDir: string) {
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
}
//----------------------------------------
// Schema Definitions
//----------------------------------------
/**
* Mermaid Diagram Schema
* Validates diagram output format
*/
const diagramSchema = z.object({
diagram: z.string().describe("mermaid diagram starting with 'flowchart TB'"),
});
/**
* Feature Changes Schema
* Validates proposed feature modifications
*/
const changesSchema = z.object({
newNodes: z.array(
z.object({
id: z.string(),
label: z.string(),
role: z.enum(
ROLE_DEFINITIONS.map((r) => r.role) as [string, ...string[]]
),
})
),
newEdges: z.array(
z.object({
from: z.string(),
to: z.string(),
relationship: z.string(),
proposed: z.boolean(),
})
),
explanation: z
.string()
.describe("A verbose, human-readable explanation of the proposed changes"),
});
//----------------------------------------
// Diagram Generation
//----------------------------------------
/**
* constructXmlParsingPrompt
* Creates prompt for XML to JSON conversion
*
* Guides model to:
* 1. Extract file metadata
* 2. Identify dependencies
* 3. Map relationships
* 4. Maintain structure
*/
function constructXmlParsingPrompt(xmlContent: string): string {
return `
Given the repository structure in XML format, transform it into a JSON object that captures the following:
---
### 1. File Roles
Assign a **one-word role** for each file based on its functional purpose:
| **Role** | **Definition** | **Examples** |
|-----------------|----------------------------------------------------------------|----------------------------------|
| \`Page\` | Files that define routes or pages. | \`Home.tsx\`, \`listing/route.ts\` |
| \`Component\` | UI components and reusable visual elements. | \`Button.tsx\`, \`Header.tsx\` |
| \`Service\` | Files providing logic, utilities, or external integrations. | \`apiService.ts\`, \`dbConnect.ts\` |
| \`Config\` | Files that store configuration, constants, or static content. | \`apiConfig.ts\`, \`strings.ts\` |
| \`Context\` | Context providers or custom hooks for state management. | \`AuthContext.tsx\`, \`useFilters.ts\`|
| \`Model\` | Data models or interfaces. | \`listings.ts\`, \`users.ts\` |
Each file must include its **role** in the JSON output.
---
### 2. Relationships
Analyze the relationships between files by parsing **import/export** statements. For each file, list its relationships in the style:
\`\`\`json
{
"filePath": "path/to/file.ts",
"role": "RoleName",
"relationships": [
{
"type": "RelationshipType",
"target": "path/to/targetFile",
"details": "Additional Details (e.g., function, type, interface)"
}
]
}
\`\`\`
**Table of Relationships**:
| **Relationship Type** | **Condition** | **Details** |
|------------------------|-----------------------------------------------------------|---------------------------------|
| \`imports\` | File imports another file. | Include specific imports (functions, types, components). |
| \`renders\` | File imports a component or UI element. | Specify component name. |
| \`uses\` | File imports a service, utility, or hook. | Function/service name. |
| \`configures\` | File imports a configuration or constant. | Constant name or file. |
| \`exports\` | File exports functions, components, types, or interfaces. | Specify export name and type. |
| \`depends_on\` | Logical dependency not captured through direct imports. | High-level functional linkage. |
---
### 3. File Path
For each file, include the **full file path** as provided in the XML input. Paths must be normalized to their absolute form.
---
### Final JSON Structure
The output JSON should follow this structure:
\`\`\`json
{
"files": [
{
"filePath": "path/to/file.ts",
"role": "Component",
"relationships": [
{
"type": "imports",
"target": "path/to/service.ts",
"details": "apiService function"
},
{
"type": "renders",
"target": "path/to/Header.tsx",
"details": "Header component"
}
]
},
{
"filePath": "path/to/config/apiConfig.ts",
"role": "Config",
"relationships": []
}
]
}
\`\`\`
---
### Requirements for the LLM
1. Parse the XML input to extract:
- File paths.
- Import/export statements for each file.
2. Identify what is being imported/exported within each file.
3. Assign one of the pre-defined **roles** to each file based on its content.
4. Derive all relationships (e.g., \`imports\`, \`renders\`, \`configures\`) for each file.
5. Normalize and include the file path in absolute form.
Ensure the output is **clean, formatted JSON** with no missing details.
XML Content:
${xmlContent}`;
}
/**
* parseXmlToUnstructuredMap
* Converts repomix XML to IntermediateData format
*
* @param content Raw XML from repomix
* @returns Structured codebase representation
*/
async function parseXmlToUnstructuredMap(
content: string
): Promise<IntermediateData> {
console.log("\n📊 Step 2/4: Parsing XML structure");
const apiKey = getApiKey();
try {
const response = await fetch(
"https://openrouter.ai/api/v1/chat/completions",
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"HTTP-Referer": "https://github.com/George5562/Repomap",
"X-Title": "RepoMap",
},
body: JSON.stringify({
model: XML_PARSING_MODEL,
response_format: { type: "json_object" },
messages: [
{
role: "system",
content: `You are a code analysis assistant that extracts structured information from codebase content.
Your responses should always be valid JSON objects in the following format:
{
"files": [
{
"path": "string",
"imports": ["string"],
"exports": ["string"],
"relationships": [
{
"type": "string (uses|renders|fetches from|provides data to)",
"target": "string (normalized path)"
}
]
}
],
"directories": ["string"]
}
Important:
1. Ensure all relative imports are normalized to absolute paths
2. Every import should have a corresponding relationship
3. Use appropriate relationship types based on what is being imported
4. Return ONLY valid JSON, no markdown or additional text`,
},
{
role: "user",
content: constructXmlParsingPrompt(content),
},
],
}),
}
);
if (!response.ok) {
throw new Error(`API error: ${response.statusText}`);
}
const result = await response.json();
if (!result.choices?.[0]?.message?.content) {
throw new Error("Invalid API response format");
}
let parsed;
const rawContent = result.choices[0].message.content;
try {
// First try: direct JSON parse
parsed =
typeof rawContent === "object" ? rawContent : JSON.parse(rawContent);
} catch (e) {
try {
// Second try: clean up markdown and comments
const cleaned = rawContent
.replace(/```json\n?|\n?```/g, "")
.replace(/\/\/.+/g, "") // Remove single line comments
.replace(/\/\*[\s\S]*?\*\//g, "") // Remove multi-line comments
.trim();
parsed = JSON.parse(cleaned);
} catch (e2) {
// Last resort: aggressive cleanup
const aggressive = rawContent
.replace(/```[\s\S]*?```/g, "") // Remove all code blocks
.replace(/[^\x20-\x7E]/g, "") // Remove non-printable characters
.replace(/\/\/.+/g, "") // Remove comments
.replace(/\/\*[\s\S]*?\*\//g, "") // Remove multi-line comments
.replace(/,(\s*[}\]])/g, "$1") // Remove trailing commas
.replace(/\s+/g, " ") // Normalize whitespace
.replace(/([{,]\s*)([a-zA-Z0-9_]+):/g, '$1"$2":') // Quote unquoted keys
.trim();
// Find the first { and last }, take only that substring
const start = aggressive.indexOf("{");
const end = aggressive.lastIndexOf("}") + 1;
if (start >= 0 && end > start) {
const jsonStr = aggressive.substring(start, end);
parsed = JSON.parse(jsonStr);
} else {
throw new Error("Could not find valid JSON structure in response");
}
}
}
// Basic structure validation
if (!parsed.files || !Array.isArray(parsed.files)) {
parsed = {
files: [],
directories: [],
};
}
// Ensure each file has the required properties
parsed.files = parsed.files.map((file: any) => ({
path: file.path || "",
imports: Array.isArray(file.imports) ? file.imports : [],
exports: Array.isArray(file.exports) ? file.exports : [],
relationships: Array.isArray(file.relationships)
? file.relationships
: [],
}));
// Ensure directories is an array
if (!Array.isArray(parsed.directories)) {
parsed.directories = [];
}
return parsed as IntermediateData;
} catch (error) {
console.error("⚠️ XML parsing failed, returning empty structure");
return {
files: [],
directories: [],
};
}
}
/**
* generateMermaidDiagram
* Creates Mermaid diagram from IntermediateData
*
* @param structureData Parsed codebase structure
* @returns Mermaid diagram syntax
*/
async function generateMermaidDiagram(
structureData: IntermediateData
): Promise<string> {
console.log("\n🎨 Step 3/4: Generating diagram");
const apiKey = getApiKey();
try {
const response = await fetch(
"https://openrouter.ai/api/v1/chat/completions",
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"HTTP-Referer": "https://github.com/George5562/Repomap",
"X-Title": "RepoMap",
},
body: JSON.stringify({
model: DIAGRAM_GENERATION_MODEL,
messages: [
{
role: "system",
content: `You are a diagram generation assistant that creates Mermaid flowcharts from codebase structures.
Your responses must always start with 'flowchart TB' and use correct Mermaid syntax.
### Class Definitions:
Define these styles for the roles:
classDef page fill:#d0ebff,stroke:#333,stroke-width:1px,color:#fff,shape:rect;
classDef component fill:#d3f9d8,stroke:#333,stroke-width:1px,color:#fff,shape:round;
classDef service fill:#ffe8cc,stroke:#333,stroke-width:1px,color:#fff,shape:diamond;
classDef config fill:#ffe3e3,stroke:#333,stroke-width:1px,color:#fff,shape:parallelogram;
classDef model fill:#f8f9fa,stroke:#333,stroke-width:1px,color:#333,shape:ellipse;
classDef context fill:#fef9c3,stroke:#333,stroke-width:1px,color:#333,shape:hexagon;
### Relationship Rules:
- Use the 'imports' relationship only to avoid duplication.
- Format the arrow text as follows:
**type:** followed by the details of the relationship.
Example:
listing.ts -- **imports:** apiService function --> nextauth.ts
`,
},
{
role: "user",
content: `Create a Mermaid flowchart from this codebase structure:
${JSON.stringify(structureData, null, 2)}
### Instructions:
1. Start the diagram with 'flowchart TB'.
2. Group related nodes into subgraphs based on their directory structure.
3. Use the appropriate classDef styles for each node based on its role:
- Page → class: page
- Component → class: component
- Service → class: service
- Config → class: config
- Model → class: model
- Context → class: context
4. Map the relationships using arrows with proper labels:
- Arrow text must include the bold **type:** followed by 'details'.
- Example: listing.ts -- **imports:** apiService function --> nextauth.ts
5. Escape node names containing square brackets (e.g., replace \[...\] with \\[...\\]) to avoid Mermaid syntax errors.
6. Ensure the diagram is clean and maintainable. **Return ONLY the Mermaid diagram syntax.**`,
},
],
}),
}
);
const data = await response.json();
const diagram = data.choices?.[0]?.message?.content;
if (diagram) {
return diagram;
} else {
throw new Error("No Mermaid diagram generated.");
}
} catch (error) {
console.error("Error generating Mermaid diagram:", error);
throw error;
}
}
//----------------------------------------
// Feature Planning
//----------------------------------------
/**
* getProposedChanges
* Plans changes for requested feature
*/
async function getProposedChanges(
structureData: IntermediateData,
featureRequest: string
): Promise<any> {
console.log("\n🎯 Planning feature changes...");
const apiKey = getApiKey();
const model = new OpenRouterChatModel({
apiKey,
model: FEATURE_PLANNING_MODEL,
siteUrl: "https://github.com/George5562/repomap",
siteName: "RepoMap",
});
const structuredModel = model.withStructuredOutput(changesSchema);
return await structuredModel.invoke(
constructFeaturePrompt(structureData, featureRequest)
);
}
/**
* integrateChangesIntoDiagram
* Integrates proposed changes into existing diagram
*/
async function integrateChangesIntoDiagram(
baseDiagram: string,
changes: any
): Promise<string> {
console.log("\n🔄 Integrating changes into diagram...");
const apiKey = getApiKey();
const model = new OpenRouterChatModel({
apiKey,
model: FEATURE_PLANNING_MODEL,
siteUrl: "https://github.com/George5562/repomap",
siteName: "RepoMap",
});
const structuredModel = model.withStructuredOutput(diagramSchema);
return (
await structuredModel.invoke(
constructIntegrationPrompt(baseDiagram, changes)
)
).diagram;
}
/**
* constructFeaturePrompt
* Creates prompt for feature planning
*/
function constructFeaturePrompt(
structureData: IntermediateData,
featureRequest: string
): string {
return `
analyze this TypeScript codebase and propose changes for the requested feature.
suggest new components and their relationships while maintaining existing architecture.
feature request: "${featureRequest}"
current structure:
${JSON.stringify(structureData, null, 2)}
instructions:
1. analyze the current codebase structure
2. propose new components needed for the feature
3. define relationships between new and existing components
4. use available roles: ${ROLE_DEFINITIONS.map((r) => r.role).join(", ")}
5. use relationship types: ${RELATIONSHIP_VERBS.join(", ")}
`;
}
/**
* constructIntegrationPrompt
* Creates prompt for integrating changes
*/
function constructIntegrationPrompt(baseDiagram: string, changes: any): string {
return `
integrate these proposed changes into the existing mermaid diagram.
maintain consistent styling and structure while adding new components.
base diagram:
${baseDiagram}
proposed changes:
${JSON.stringify(changes, null, 2)}
instructions:
1. preserve existing diagram structure and styling
2. add new nodes with correct shapes and colors
3. integrate new relationships
4. maintain flowchart TB direction
5. ensure all style definitions are preserved
`;
}
/**
* planAndVisualizeFeature
* Plans and visualizes new feature additions
*
* @param structureData Current codebase structure
* @param featureRequest Requested feature description
* @param baseDiagram Existing Mermaid diagram
* @returns Updated diagram with new features
*/
async function planAndVisualizeFeature(
structureData: IntermediateData,
featureRequest: string,
baseDiagram: string
): Promise<string> {
console.log("\n✨ Step 4/4: Planning feature");
const changes = await getProposedChanges(structureData, featureRequest);
const updatedDiagram = await integrateChangesIntoDiagram(
baseDiagram,
changes
);
return updatedDiagram;
}
//----------------------------------------
// File Operations
//----------------------------------------
/**
* saveDiagram
* Writes Mermaid diagram to file
*/
function saveDiagram(mermaidSyntax: string, mermaidFile: string): void {
fs.writeFileSync(mermaidFile, mermaidSyntax, { flag: "w" });
console.log(`✅ Saved: ${path.basename(mermaidFile)}`);
}
/**
* sanitizeFeatureName
* Converts feature request to valid filename
*/
function sanitizeFeatureName(featureRequest: string): string {
return featureRequest
.toLowerCase()
.replace(/[^a-z0-9]+/g, "_")
.replace(/^_+|_+$/g, "");
}
function applyFontSizeScaling(
diagram: string,
lineCountMap: Map<string, number>
): string {
const lines = diagram.split("\n");
const nodeRegex = /^(\s*)([a-zA-Z0-9_]+)\((\[?"?([^\"]+)"?\]?)\)/;
const newLines: string[] = [];
for (const line of lines) {
newLines.push(line);
const match = nodeRegex.exec(line);
if (match) {
const nodeId = match[2];
const filename = match[4];
const linesCount = lineCountMap.get(filename);
if (linesCount !== undefined) {
const fontSize = calculateFontSize(linesCount);
newLines.push(`style ${nodeId} font-size:${fontSize}px;`);
}
}
}
return newLines.join("\n");
}
//----------------------------------------
// Line Count Processing
//----------------------------------------
/**
* parseLineCountsFromRepomix
* Extracts line counts from repomix output
*/
function parseLineCountsFromRepomix(repofile: string): Map<string, number> {
const content = fs.readFileSync(repofile, "utf8");
const lineCountMap = new Map<string, number>();
const fileRegex = /<file path="([^"]+)">([\s\S]*?)<\/file>/g;
let match;
while ((match = fileRegex.exec(content)) !== null) {
const filePath = match[1];
const fileContent = match[2];
let maxLine = 0;
const lineMatches = fileContent.matchAll(/^(\d+):/gm);
for (const lm of lineMatches) {
const num = parseInt(lm[1], 10);
if (num > maxLine) maxLine = num;
}
const filename = path.basename(filePath);
lineCountMap.set(filename, maxLine);
}
return lineCountMap;
}
/**
* Calculates font size based on line count
* Rules:
* - Files ≤ MIN_LINES get MIN_FONT size
* - Files ≥ MAX_LINES get MAX_FONT size
* - Files in between get proportionally scaled size
*/
function calculateFontSize(lines: number): number {
if (lines <= MIN_LINES) return MIN_FONT;
if (lines >= MAX_LINES) return MAX_FONT;
const ratio = (lines - MIN_LINES) / (MAX_LINES - MIN_LINES);
return MIN_FONT + ratio * (MAX_FONT - MIN_FONT);
}
//----------------------------------------
// Main Program Flow
//----------------------------------------
/**
* Main function orchestrating the four-step process:
- * 1. Generate XML with repomix
- * 2. Parse to IntermediateData using Gemini
- * 3. Create Mermaid diagram using Claude
- * 4. (Optional) Add feature visualization
- */
async function generateRepomap() {
const args = process.argv.slice(2);
if (args.includes("--help")) {