frontendmap 0.1.3

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
use anyhow::Result;
use regex::Regex;
use std::fs;
use std::path::Path;
use crate::model::{Route, Framework};

pub fn scan_routes(root: &Path, framework: &Framework) -> Result<Vec<Route>> {
    let mut routes = Vec::new();
    
    // Scan for various router patterns
    scan_react_router(root, &mut routes)?;
    scan_vue_router(root, &mut routes)?;
    scan_angular_router(root, &mut routes)?;
    scan_svelte_router(root, &mut routes)?;
    
    // Only scan file-based routes for frameworks that use them
    match framework {
        Framework::Next => scan_next_pages(root, &mut routes)?,
        Framework::Nuxt => scan_nuxt_pages(root, &mut routes)?,
        Framework::SvelteKit => scan_sveltekit_routes(root, &mut routes)?,
        _ => {} // React/Vue/Angular/Svelte don't use file-based routing by default
    }
    
    Ok(routes)
}

fn scan_react_router(root: &Path, routes: &mut Vec<Route>) -> Result<()> {
    let walker = ignore::WalkBuilder::new(root)
        .hidden(false)
        .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();
    
    // Pattern for React Router v6: <Route path="/xxx" element={<Component />} />
    let route_v6_re = Regex::new(r#"<Route\s+[^>]*path\s*=\s*["']([^"']+)["'][^>]*element\s*=\s*\{<(\w+)"#).expect("invalid regex pattern");
    // Pattern for route config objects: { path: '/xxx', element: <Component /> }
    let config_re = Regex::new(r#"\{\s*path\s*:\s*["']([^"']+)["']\s*,\s*element\s*:\s*(?:<)?(\w+)"#).expect("invalid regex pattern");
    // Pattern for createBrowserRouter: { path: '/xxx', element: <Component /> }
    let browser_router_re = Regex::new(r#"\{\s*path\s*:\s*["']([^"']+)["']\s*,\s*element\s*:\s*<(\w+)"#).expect("invalid regex pattern");
    // Pattern for import statements (to skip)
    let import_re = Regex::new(r#"^\s*import\s"#).expect("invalid regex pattern");
    
    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();
        // Skip test files
        if is_test_file(path) {
            continue;
        }
        
        let content = match fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        
        let lines: Vec<&str> = content.lines().collect();
        
        for (line_num, line) in lines.iter().enumerate() {
            // Skip import lines
            if import_re.is_match(line) {
                continue;
            }
            
            if let Some(caps) = route_v6_re.captures(line) {
                routes.push(Route {
                    path: caps[1].to_string(),
                    component: caps[2].to_string(),
                    file: path.to_path_buf(),
                    line: line_num + 1,
                });
            } else if let Some(caps) = config_re.captures(line) {
                routes.push(Route {
                    path: caps[1].to_string(),
                    component: caps[2].to_string(),
                    file: path.to_path_buf(),
                    line: line_num + 1,
                });
            } else if let Some(caps) = browser_router_re.captures(line) {
                routes.push(Route {
                    path: caps[1].to_string(),
                    component: caps[2].to_string(),
                    file: path.to_path_buf(),
                    line: line_num + 1,
                });
            }
        }
    }
    
    Ok(())
}

fn is_test_file(path: &Path) -> bool {
    let path_str = path.to_string_lossy();
    if path_str.contains("/__tests__/") || path_str.contains("\\__tests\\") {
        return true;
    }
    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 scan_vue_router(root: &Path, routes: &mut Vec<Route>) -> Result<()> {
    let walker = ignore::WalkBuilder::new(root)
        .hidden(false)
        .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();
    
    // Pattern for Vue Router array config (multiline)
    let path_re = Regex::new(r#"path\s*:\s*["']([^"']+)["']"#).expect("invalid regex pattern");
    let name_re = Regex::new(r#"name\s*:\s*["'](\w+)["']"#).expect("invalid regex pattern");
    let import_re = Regex::new(r#"import\(['"]([^'"]+)['"]\)"#).expect("invalid regex pattern");
    // Pattern for component reference: component: ComponentName
    let component_re = Regex::new(r#"component\s*:\s*(\w+)"#).expect("invalid regex pattern");
    
    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();
        // Skip test files
        if is_test_file(path) {
            continue;
        }
        
        let path = entry.path();
        let content = match fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        
        let lines: Vec<&str> = content.lines().collect();
        
        let mut i = 0;
        while i < lines.len() {
            let line = lines[i];
            
            if let Some(path_caps) = path_re.captures(line) {
                let route_path = path_caps[1].to_string();
                let mut route_name = String::new();
                let mut component_name = String::new();
                
                // Look for name and import/component in nearby lines
                let search_end = (i + 10).min(lines.len());
                for j in i..search_end {
                    let nearby = lines[j];
                    
                    if route_name.is_empty() {
                        if let Some(name_caps) = name_re.captures(nearby) {
                            route_name = name_caps[1].to_string();
                        }
                    }
                    
                    if component_name.is_empty() {
                        // Try lazy import first
                        if let Some(import_caps) = import_re.captures(nearby) {
                            let import_path = import_caps[1].to_string();
                            component_name = import_path.rsplit('/').next()
                                .unwrap_or(&route_name)
                                .replace(".vue", "")
                                .replace(".ts", "")
                                .replace(".js", "");
                        }
                        // Try component reference
                        else if let Some(comp_caps) = component_re.captures(nearby) {
                            component_name = comp_caps[1].to_string();
                        }
                    }
                    
                    if !route_name.is_empty() && !component_name.is_empty() {
                        break;
                    }
                }
                
                if component_name.is_empty() {
                    component_name = route_name.clone();
                }
                
                if !route_path.is_empty() && !component_name.is_empty() {
                    routes.push(Route {
                        path: route_path,
                        component: component_name,
                        file: path.to_path_buf(),
                        line: i + 1,
                    });
                }
            }
            
            i += 1;
        }
    }
    
    Ok(())
}

fn scan_angular_router(root: &Path, routes: &mut Vec<Route>) -> Result<()> {
    let walker = ignore::WalkBuilder::new(root)
        .hidden(false)
        .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();
    
    // Pattern for Angular routes: { path: 'xxx', component: XxxComponent }
    let route_re = Regex::new(r#"\{\s*path\s*:\s*['"]([^'"]+)['"]\s*,\s*component\s*:\s*(\w+)"#).expect("invalid regex pattern");
    
    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();
        // Skip test files
        if is_test_file(path) {
            continue;
        }
        
        let path = entry.path();
        let content = match fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        
        let lines: Vec<&str> = content.lines().collect();
        
        for (line_num, line) in lines.iter().enumerate() {
            if let Some(caps) = route_re.captures(line) {
                routes.push(Route {
                    path: caps[1].to_string(),
                    component: caps[2].to_string(),
                    file: path.to_path_buf(),
                    line: line_num + 1,
                });
            }
        }
    }
    
    Ok(())
}

fn scan_svelte_router(root: &Path, routes: &mut Vec<Route>) -> Result<()> {
    // Svelte uses file-based routing, handled by scan_sveltekit_routes
    Ok(())
}

fn scan_next_pages(root: &Path, routes: &mut Vec<Route>) -> Result<()> {
    let pages_dirs = vec![
        root.join("pages"),
        root.join("src").join("pages"),
        root.join("app"),
        root.join("src").join("app"),
    ];
    
    for dir in &pages_dirs {
        if dir.exists() {
            scan_directory_routes(dir, root, routes, "next")?;
        }
    }
    
    Ok(())
}

fn scan_nuxt_pages(root: &Path, routes: &mut Vec<Route>) -> Result<()> {
    let pages_dirs = vec![
        root.join("pages"),
        root.join("src").join("pages"),
    ];
    
    for dir in &pages_dirs {
        if dir.exists() {
            scan_directory_routes(dir, root, routes, "nuxt")?;
        }
    }
    
    Ok(())
}

fn scan_sveltekit_routes(root: &Path, routes: &mut Vec<Route>) -> Result<()> {
    let routes_dir = root.join("src").join("routes");
    if routes_dir.exists() {
        scan_directory_routes(&routes_dir, root, routes, "sveltekit")?;
    }
    
    Ok(())
}

fn scan_directory_routes(dir: &Path, root: &Path, routes: &mut Vec<Route>, framework: &str) -> Result<()> {
    let walker = ignore::WalkBuilder::new(dir)
        .hidden(false)
        .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();
        let relative = path.strip_prefix(root).unwrap_or(path);
        
        // Skip non-page files
        let filename = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
        if filename.starts_with('_') || filename.starts_with('.') {
            continue;
        }
        
        // Skip test files
        if is_test_file(path) {
            continue;
        }
        
        // Check for valid page extensions
        if let Some(ext) = path.extension() {
            let ext = ext.to_string_lossy().to_lowercase();
            if !matches!(ext.as_str(), "tsx" | "jsx" | "ts" | "js" | "vue" | "svelte") {
                continue;
            }
        } else {
            continue;
        }
        
        // Convert file path to route path
        let route_path = file_to_route_path(relative, framework);
        
        // Extract component name from filename
        let component_name = path.file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("default")
            .to_string();
        
        routes.push(Route {
            path: route_path,
            component: component_name,
            file: path.to_path_buf(),
            line: 1,
        });
    }
    
    Ok(())
}

fn file_to_route_path(relative: &Path, framework: &str) -> String {
    let mut parts = Vec::new();
    
    for component in relative.components() {
        let part = component.as_os_str().to_string_lossy();
        
        // Skip file extension
        if part.contains('.') {
            let name = part.rsplit('.').next().unwrap_or(&part);
            if name != "index" {
                parts.push(name.to_string());
            }
        } else {
            parts.push(part.to_string());
        }
    }
    
    // Handle dynamic routes based on framework
    let path = parts.join("/");
    let path = match framework {
        "next" | "nuxt" | "sveltekit" => {
            // [id] -> :id, [...slug] -> *slug
            let dynamic_re = Regex::new(r"\[(\w+)\]").expect("invalid regex pattern");
            let catch_all_re = Regex::new(r"\[\.\.\.(\w+)\]").expect("invalid regex pattern");
            let path = dynamic_re.replace_all(&path, ":$1").to_string();
            catch_all_re.replace_all(&path, "*$1").to_string()
        }
        _ => path,
    };
    
    if path.is_empty() {
        "/".to_string()
    } else {
        format!("/{}", path)
    }
}