frontendmap 0.1.4

Frontend project satellite map — index, query, and navigate your web project
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
use anyhow::Result;
use regex::Regex;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use crate::model::{Component, ComponentKind, Prop};

pub fn scan_components(root: &Path) -> Result<Vec<Component>> {
    let mut components = Vec::new();
    let mut file_components: HashMap<PathBuf, Vec<String>> = HashMap::new();
    
    // Walk through all JS/TS/JSX/TSX/Vue/Svelte files
    let walker = ignore::WalkBuilder::new(root)
        .hidden(true)
        .git_ignore(true)
        .add_custom_ignore_filename(".gitignore")
        .filter_entry(|e| {
            if e.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
                let name = e.file_name().to_string_lossy();
                !matches!(name.as_ref(), "node_modules" | "dist" | "build" | ".next" | ".nuxt" | ".svelte-kit" | ".git" | ".svn" | "vendor" | "coverage" | "__pycache__" | ".cache")
            } else {
                true
            }
        })
        .build();
    
    for entry in walker {
        let entry = match entry {
            Ok(e) => e,
            Err(_) => continue,
        };
        
        if !entry.file_type().map(|ft| ft.is_file()).unwrap_or(false) {
            continue;
        }
        
        let path = entry.path();
        if !is_component_file(path) {
            continue;
        }
        
        let content = match fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        
        let file_comps = extract_components(path, &content);
        for comp in file_comps {
            file_components.entry(path.to_path_buf()).or_default().push(comp.name.clone());
            components.push(comp);
        }
    }
    
    // Build reference relationships
    build_references(&mut components, root);
    
    Ok(components)
}

fn is_component_file(path: &Path) -> bool {
    // Skip test files
    if is_test_file(path) {
        return false;
    }
    
    if let Some(ext) = path.extension() {
        let ext = ext.to_string_lossy().to_lowercase();
        matches!(ext.as_str(), "jsx" | "tsx" | "vue" | "svelte" | "astro")
    } else {
        // Also check .js/.ts files that might contain components
        if let Some(ext) = path.extension() {
            let ext = ext.to_string_lossy().to_lowercase();
            if matches!(ext.as_str(), "js" | "ts") {
                // Check if filename starts with uppercase (component convention)
                if let Some(name) = path.file_stem() {
                    let name = name.to_string_lossy();
                    return name.chars().next().map(|c| c.is_uppercase()).unwrap_or(false);
                }
            }
        }
        false
    }
}

fn is_test_file(path: &Path) -> bool {
    let path_str = path.to_string_lossy();
    // Skip __tests__ directories
    if path_str.contains("/__tests__/") || path_str.contains("\\__tests\\") {
        return true;
    }
    // Skip .test.* and .spec.* files
    if let Some(name) = path.file_stem() {
        let name = name.to_string_lossy();
        if name.ends_with(".test") || name.ends_with(".spec") {
            return true;
        }
    }
    false
}


fn extract_components(file_path: &Path, content: &str) -> Vec<Component> {
    let mut components = Vec::new();
    
    // Check file extension to determine extraction method
    if let Some(ext) = file_path.extension() {
        let ext = ext.to_string_lossy().to_lowercase();
        match ext.as_str() {
            "vue" => return extract_vue_components(file_path, content),
            "svelte" => return extract_svelte_components(file_path, content),
            "astro" => return extract_astro_components(file_path, content),
            _ => {} // Continue with JS/TS extraction
        }
    }
    
    // JS/TS component extraction patterns (pre-compiled)
    let patterns: Vec<(Regex, ComponentKind)> = vec![
        // Pattern 1: export default function ComponentName
        (Regex::new(r"export\s+default\s+(?:async\s+)?function\s+(\w+)").expect("invalid regex pattern"), ComponentKind::Function),
        // Pattern 2: export const ComponentName = () =>
        (Regex::new(r"export\s+const\s+(\w+)\s*=\s*(?:\([^)]*\)|[a-zA-Z_]\w*)\s*=>").expect("invalid regex pattern"), ComponentKind::Arrow),
        // Pattern 3: export function ComponentName
        (Regex::new(r"export\s+(?:async\s+)?function\s+(\w+)").expect("invalid regex pattern"), ComponentKind::Function),
        // Pattern 4: export default ComponentName (for class components)
        (Regex::new(r"export\s+default\s+class\s+(\w+)").expect("invalid regex pattern"), ComponentKind::Class),
        // Pattern 5: export class ComponentName
        (Regex::new(r"export\s+class\s+(\w+)").expect("invalid regex pattern"), ComponentKind::Class),
        // Pattern 6: const ComponentName = () => ... export default ComponentName
        (Regex::new(r"const\s+(\w+)\s*=\s*(?:\([^)]*\)|[a-zA-Z_]\w*)\s*=>").expect("invalid regex pattern"), ComponentKind::Arrow),
        // Pattern 7: function ComponentName() { ... } export default ComponentName
        (Regex::new(r"(?:async\s+)?function\s+(\w+)\s*\(").expect("invalid regex pattern"), ComponentKind::Function),
    ];
    
    let lines: Vec<&str> = content.lines().collect();
    let mut seen_names: std::collections::HashSet<String> = std::collections::HashSet::new();
    
    for (line_num, line) in lines.iter().enumerate() {
        let line = line.trim();
        
        for (re, kind) in &patterns {
            if let Some(caps) = re.captures(line) {
                let name = caps[1].to_string();
                if is_component_name(&name) && !seen_names.contains(&name) {
                    seen_names.insert(name.clone());
                    let props = extract_js_props(content, &name);
                    components.push(Component {
                        name,
                        file: file_path.to_path_buf(),
                        kind: kind.clone(),
                        props,
                        used_by: Vec::new(),
                        uses: Vec::new(),
                        line: line_num + 1,
                    });
                }
            }
        }
    }
    
    components
}

fn extract_vue_components(file_path: &Path, content: &str) -> Vec<Component> {
    let mut components = Vec::new();
    
    // Vue component name is the filename (without extension)
    let name = file_path.file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("Unknown")
        .to_string();
    
    // Skip non-component files
    if name.starts_with('_') || name == "index" {
        // For index files, use parent directory name
        if name == "index" {
            if let Some(parent) = file_path.parent() {
                let parent_name = parent.file_name()
                    .and_then(|s| s.to_str())
                    .unwrap_or("Unknown")
                    .to_string();
                let props = extract_vue_props(content);
                let script_line = find_script_line(content);
                
                components.push(Component {
                    name: parent_name,
                    file: file_path.to_path_buf(),
                    kind: ComponentKind::Function,
                    props,
                    used_by: Vec::new(),
                    uses: Vec::new(),
                    line: script_line,
                });
            }
        }
        return components;
    }
    
    let props = extract_vue_props(content);
    let script_line = find_script_line(content);
    
    components.push(Component {
        name,
        file: file_path.to_path_buf(),
        kind: ComponentKind::Function,
        props,
        used_by: Vec::new(),
        uses: Vec::new(),
        line: script_line,
    });
    
    components
}

fn extract_svelte_components(file_path: &Path, content: &str) -> Vec<Component> {
    let mut components = Vec::new();
    
    // Svelte component name is the filename
    let name = file_path.file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("Unknown")
        .to_string();
    
    // Extract props from export let
    let props = extract_svelte_props(content);
    let script_line = find_script_line(content);
    
    components.push(Component {
        name,
        file: file_path.to_path_buf(),
        kind: ComponentKind::Function,
        props,
        used_by: Vec::new(),
        uses: Vec::new(),
        line: script_line,
    });
    
    components
}

fn extract_astro_components(file_path: &Path, content: &str) -> Vec<Component> {
    let mut components = Vec::new();
    
    // Astro component name is the filename
    let name = file_path.file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("Unknown")
        .to_string();
    
    // Extract props from Astro interface
    let props = extract_astro_props(content);
    let script_line = find_script_line(content);
    
    components.push(Component {
        name,
        file: file_path.to_path_buf(),
        kind: ComponentKind::Function,
        props,
        used_by: Vec::new(),
        uses: Vec::new(),
        line: script_line,
    });
    
    components
}

fn find_script_line(content: &str) -> usize {
    let script_re = Regex::new(r"<script").expect("invalid regex pattern");
    content.lines().enumerate()
        .find(|(_, l)| script_re.is_match(l))
        .map(|(i, _)| i + 1)
        .unwrap_or(1)
}

fn is_component_name(name: &str) -> bool {
    // Component names should start with uppercase
    // Skip common non-component exports
    let skip_names = ["default", "props", "emits", "setup", "data", "methods", "computed", "watch"];
    if skip_names.contains(&name) {
        return false;
    }
    // Skip UPPER_CASE constants (e.g., NAV_LINK_CLASS, API_URL)
    if name.chars().all(|c| c.is_uppercase() || c == '_' || c.is_numeric()) {
        return false;
    }
    name.chars().next().map(|c| c.is_uppercase()).unwrap_or(false)
}

fn extract_js_props(content: &str, component_name: &str) -> Vec<Prop> {
    let mut props = Vec::new();
    
    // Pattern 1: function Component({ prop1, prop2 })
    let destructure_re = Regex::new(&format!(r"{}\s*\(\s*\{{([^}}]*)\}}", regex::escape(component_name))).expect("invalid regex pattern");
    
    // Pattern 2: function Component(props: { prop1: type1, prop2: type2 })
    let type_re = Regex::new(&format!(r"{}\s*\(\s*(?:props|\{{[^}}]*\}})\s*:\s*\{{([^}}]*)\}}", regex::escape(component_name))).expect("invalid regex pattern");
    
    // Pattern 3: interface Props { ... } or type Props = { ... }
    let interface_re = Regex::new(r"(?:interface|type)\s+(?:Props|IProps)\s*(?:=\s*)?\{([^}]+)\}").expect("invalid regex pattern");
    
    if let Some(caps) = destructure_re.captures(content) {
        let props_str = &caps[1];
        for prop in props_str.split(',') {
            let prop = prop.trim();
            if !prop.is_empty() {
                let parts: Vec<&str> = prop.split(':').collect();
                let name = parts[0].trim().to_string();
                let type_annotation = if parts.len() > 1 {
                    Some(parts[1].trim().to_string())
                } else {
                    None
                };
                props.push(Prop {
                    name,
                    type_annotation,
                    required: true,
                });
            }
        }
    } else if let Some(caps) = type_re.captures(content) {
        let props_str = &caps[1];
        for prop in props_str.split(',') {
            let prop = prop.trim();
            if !prop.is_empty() {
                let parts: Vec<&str> = prop.split(':').collect();
                let name = parts[0].trim().trim_matches('?').to_string();
                let type_annotation = if parts.len() > 1 {
                    Some(parts[1].trim().to_string())
                } else {
                    None
                };
                let required = !prop.contains('?');
                props.push(Prop {
                    name,
                    type_annotation,
                    required,
                });
            }
        }
    } else if let Some(caps) = interface_re.captures(content) {
        let props_str = &caps[1];
        for prop in props_str.split('\n') {
            let prop = prop.trim().trim_end_matches(';');
            if !prop.is_empty() && !prop.starts_with("//") {
                let parts: Vec<&str> = prop.split(':').collect();
                if parts.len() >= 2 {
                    let name = parts[0].trim().trim_matches('?').to_string();
                    let type_annotation = Some(parts[1].trim().to_string());
                    let required = !prop.contains('?');
                    props.push(Prop {
                        name,
                        type_annotation,
                        required,
                    });
                }
            }
        }
    }
    
    props
}

fn extract_vue_props(content: &str) -> Vec<Prop> {
    let mut props = Vec::new();
    
    // Pattern 1: defineProps<{ prop1: type1, prop2: type2 }>()
    let type_props_re = Regex::new(r"defineProps\s*<\s*\{([^}]+)\}\s*>").expect("invalid regex pattern");
    // Pattern 2: defineProps({ prop1: type, prop2: type })
    let obj_props_re = Regex::new(r"defineProps\s*\(\s*\{([^}]+)\}\s*\)").expect("invalid regex pattern");
    // Pattern 3: props: { prop1: type, prop2: type } (Options API)
    let options_re = Regex::new(r"props\s*:\s*\{([^}]+)\}").expect("invalid regex pattern");
    
    if let Some(caps) = type_props_re.captures(content) {
        let props_str = &caps[1];
        for prop in props_str.split(',') {
            let prop = prop.trim();
            if !prop.is_empty() {
                let parts: Vec<&str> = prop.split(':').collect();
                let name = parts[0].trim().trim_matches('?').to_string();
                let type_annotation = if parts.len() > 1 {
                    Some(parts[1].trim().to_string())
                } else {
                    None
                };
                let required = !prop.contains('?');
                props.push(Prop {
                    name,
                    type_annotation,
                    required,
                });
            }
        }
    } else if let Some(caps) = obj_props_re.captures(content) {
        let props_str = &caps[1];
        for prop in props_str.split(',') {
            let prop = prop.trim();
            if !prop.is_empty() {
                let parts: Vec<&str> = prop.split(':').collect();
                let name = parts[0].trim().to_string();
                let type_annotation = if parts.len() > 1 {
                    Some(parts[1].trim().to_string())
                } else {
                    None
                };
                props.push(Prop {
                    name,
                    type_annotation,
                    required: true,
                });
            }
        }
    } else if let Some(caps) = options_re.captures(content) {
        let props_str = &caps[1];
        for prop in props_str.split(',') {
            let prop = prop.trim();
            if !prop.is_empty() {
                let parts: Vec<&str> = prop.split(':').collect();
                let name = parts[0].trim().to_string();
                let type_annotation = if parts.len() > 1 {
                    Some(parts[1].trim().to_string())
                } else {
                    None
                };
                props.push(Prop {
                    name,
                    type_annotation,
                    required: true,
                });
            }
        }
    }
    
    props
}

fn extract_svelte_props(content: &str) -> Vec<Prop> {
    let mut props = Vec::new();
    
    // Svelte props: export let prop1, export let prop2: type
    let prop_re = Regex::new(r"export\s+let\s+(\w+)(?:\s*:\s*(\w+))?").expect("invalid regex pattern");
    
    for caps in prop_re.captures_iter(content) {
        let name = caps[1].to_string();
        let type_annotation = caps.get(2).map(|m| m.as_str().to_string());
        props.push(Prop {
            name,
            type_annotation,
            required: true,
        });
    }
    
    props
}

fn extract_astro_props(content: &str) -> Vec<Prop> {
    let mut props = Vec::new();
    
    // Astro props: interface Props { prop1: type1, prop2: type2 }
    let interface_re = Regex::new(r"interface\s+Props\s*\{([^}]+)\}").expect("invalid regex pattern");
    
    if let Some(caps) = interface_re.captures(content) {
        let props_str = &caps[1];
        for prop in props_str.split('\n') {
            let prop = prop.trim().trim_end_matches(';');
            if !prop.is_empty() && !prop.starts_with("//") {
                let parts: Vec<&str> = prop.split(':').collect();
                if parts.len() >= 2 {
                    let name = parts[0].trim().trim_matches('?').to_string();
                    let type_annotation = Some(parts[1].trim().to_string());
                    let required = !prop.contains('?');
                    props.push(Prop {
                        name,
                        type_annotation,
                        required,
                    });
                }
            }
        }
    }
    
    props
}

fn build_references(components: &mut Vec<Component>, root: &Path) {
    let component_names: Vec<String> = components.iter().map(|c| c.name.clone()).collect();
    
    // Walk through all files to find references
    let walker = ignore::WalkBuilder::new(root)
        .hidden(true)
        .git_ignore(true)
        .add_custom_ignore_filename(".gitignore")
        .filter_entry(|e| {
            if e.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
                let name = e.file_name().to_string_lossy();
                !matches!(name.as_ref(), "node_modules" | "dist" | "build" | ".next" | ".nuxt" | ".svelte-kit" | ".git" | ".svn" | "vendor" | "coverage" | "__pycache__" | ".cache")
            } else {
                true
            }
        })
        .build();
    
    // Pre-compile regex patterns for each component name
    let mut compiled_patterns: Vec<(Regex, Regex, Regex)> = Vec::with_capacity(component_names.len());
    for comp_name in &component_names {
        // Pattern 1: <ComponentName or <ComponentName>
        let jsx_re = Regex::new(&format!(r"<{}", regex::escape(comp_name))).expect("invalid regex pattern");
        // Pattern 2: import { ComponentName } from
        let import_re = Regex::new(&format!(r"import\s+.*{}\s+.*from", regex::escape(comp_name))).expect("invalid regex pattern");
        // Pattern 3: import ComponentName from
        let default_import_re = Regex::new(&format!(r"import\s+{}\s+from", regex::escape(comp_name))).expect("invalid regex pattern");
        compiled_patterns.push((jsx_re, import_re, default_import_re));
    }

    // Allowed source file extensions for reference tracking
    let source_extensions = ["js", "jsx", "ts", "tsx", "vue", "svelte", "astro"];

    // file -> set of component names it references
    let mut file_refs: HashMap<PathBuf, Vec<String>> = HashMap::new();
    
    for entry in walker {
        let entry = match entry {
            Ok(e) => e,
            Err(_) => continue,
        };
        
        if !entry.file_type().map(|ft| ft.is_file()).unwrap_or(false) {
            continue;
        }
        
        let path = entry.path();
        let content = match fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        
        // Skip test files for reference tracking
        if is_test_file(path) {
            continue;
        }

        // Skip non-source files
        let is_source = path.extension()
            .and_then(|e| e.to_str())
            .map(|ext| source_extensions.contains(&ext.to_lowercase().as_str()))
            .unwrap_or(false);
        if !is_source {
            continue;
        }
        
        // Check for component usage in JSX/Vue/Svelte
        for (idx, comp_name) in component_names.iter().enumerate() {
            let (ref jsx_re, ref import_re, ref default_import_re) = compiled_patterns[idx];

            if jsx_re.is_match(&content) || import_re.is_match(&content) || default_import_re.is_match(&content) {
                file_refs.entry(path.to_path_buf()).or_default().push(comp_name.clone());
            }
        }
    }
    
    // Build component name -> file mapping (clone to avoid borrow conflict)
    let comp_files: HashMap<String, PathBuf> = components.iter()
        .map(|c| (c.name.clone(), c.file.clone()))
        .collect();
    
    // Update components with references
    for comp in components.iter_mut() {
        let comp_path = comp.file.to_string_lossy().to_string();
        
        // used_by: other files that reference this component
        for (file_path, refs) in &file_refs {
            let file_str = file_path.to_string_lossy().to_string();
            if refs.contains(&comp.name) && file_str != comp_path {
                comp.used_by.push(file_path.clone());
            }
        }
        
        // uses: components referenced by this file
        if let Some(refs) = file_refs.get(&comp.file) {
            for ref_name in refs {
                if ref_name != &comp.name && comp_files.contains_key(ref_name) {
                    comp.uses.push(ref_name.clone());
                }
            }
        }
    }
}