1use std::collections::{HashMap, HashSet};
9use std::path::Path;
10
11pub fn sanitize_module_name(raw: &str) -> String {
14 let mut result = String::new();
15 for ch in raw.chars() {
16 if ch.is_ascii_alphanumeric() || ch == '_' {
17 result.push(ch);
18 } else {
19 result.push_str(&format!("_u{:04x}", ch as u32));
20 }
21 }
22 if result.is_empty() {
23 result.push_str("_unnamed");
24 }
25 if !result.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') {
26 result.insert(0, '_');
27 }
28 result
29}
30
31pub fn strip_imports_extract_exports(src: &str) -> (String, HashSet<String>) {
36 let mut result = String::with_capacity(src.len());
37 let mut exports = HashSet::new();
38
39 for line in src.lines() {
40 let trimmed = line.trim();
41
42 if trimmed.starts_with("import ") {
44 continue;
45 }
46
47 if let Some(rest) = trimmed.strip_prefix("export ") {
49 if let Some(after) = rest.strip_prefix("function ") {
50 if let Some(paren) = after.find('(') {
51 exports.insert(after[..paren].trim().to_string());
52 }
53 result.push_str(rest);
55 } else if let Some(after) = rest.strip_prefix("async function ") {
56 if let Some(paren) = after.find('(') {
57 exports.insert(after[..paren].trim().to_string());
58 }
59 result.push_str(rest);
60 } else if rest.starts_with("const ") || rest.starts_with("let ") || rest.starts_with("var ") {
61 let kw_len = if rest.starts_with("const ") { 6 } else { 4 };
62 if let Some(eq) = rest[kw_len..].find('=') {
63 let name = rest[kw_len..kw_len + eq].trim();
64 exports.insert(name.to_string());
65 }
66 result.push_str(rest);
67 } else if let Some(after_class) = rest.strip_prefix("class ") {
68 if let Some(br) = after_class.find([' ', '{']) {
69 exports.insert(after_class[..br].trim().to_string());
70 }
71 result.push_str(rest);
72 } else if let Some(after_default) = rest.strip_prefix("default ") {
73 if let Some(after_fn) = after_default.strip_prefix("function ") {
75 if let Some(paren) = after_fn.find('(') {
76 let name = after_fn[..paren].trim();
77 if !name.is_empty() {
78 exports.insert(name.to_string());
79 }
80 }
81 } else if let Some(after_class) = after_default.strip_prefix("class ")
82 && let Some(br) = after_class.find([' ', '{'])
83 {
84 exports.insert(after_class[..br].trim().to_string());
85 }
86 result.push_str(after_default);
87 } else if rest.starts_with('{') {
88 if let Some(braces) = rest.strip_prefix('{')
90 .and_then(|s| s.strip_suffix('}'))
91 .or_else(|| rest.strip_prefix('{').and_then(|s| {
92 s.find('}').map(|i| &s[..i])
94 }))
95 {
96 for name in braces.split(',') {
97 let name = name.trim();
98 if let Some(alias) = name.strip_prefix("as ") {
100 let alias = alias.trim();
101 if !alias.is_empty() {
102 exports.insert(alias.to_string());
103 }
104 } else if !name.is_empty() && !name.starts_with("as ") {
105 exports.insert(name.to_string());
106 }
107 }
108 }
109 continue;
110 } else {
111 continue;
113 }
114 result.push('\n');
115 } else {
116 result.push_str(line);
117 result.push('\n');
118 }
119 }
120
121 (result, exports)
122}
123
124fn sanitize_name(filename: &str) -> String {
126 let stem = filename.strip_suffix(".js").unwrap_or(filename);
127 sanitize_module_name(stem)
128}
129
130#[derive(Debug, Clone)]
132pub struct FileGroup {
133 pub core_name: String,
135 pub core_file: String,
137 pub members: Vec<String>,
139 pub name_map: HashMap<String, String>,
141 pub imported_names: HashMap<String, Vec<(String, String)>>,
144}
145
146pub fn analyze_groups(in_dir: &str) -> (Vec<FileGroup>, String) {
152 let in_path = Path::new(in_dir);
153
154 let js_files: Vec<String> = std::fs::read_dir(in_path)
156 .unwrap_or_else(|e| panic!("Cannot read in_dir '{}': {}", in_dir, e))
157 .filter_map(|entry| {
158 let entry = entry.ok()?;
159 let path = entry.path();
160 if path.extension()? == "js" {
161 Some(path.file_name()?.to_string_lossy().to_string())
162 } else {
163 None
164 }
165 })
166 .collect();
167
168 let mut imports: HashMap<String, Vec<String>> = HashMap::new();
170 let mut imported_names: HashMap<String, Vec<(String, String)>> = HashMap::new();
171 let mut sanitzed: HashMap<String, String> = HashMap::new();
172
173 for file in &js_files {
174 let src = std::fs::read_to_string(in_path.join(file))
175 .unwrap_or_else(|e| panic!("Cannot read '{}': {}", file, e));
176 let (file_imports, _exports, _decls, file_imported_names) = extract_imports(&src, file);
177 imports.insert(file.clone(), file_imports);
178 imported_names.insert(file.clone(), file_imported_names);
179 sanitzed.insert(file.clone(), sanitize_name(file));
180 }
181
182 let mut imported_by: HashMap<String, Vec<String>> = HashMap::new();
184 for (importer, deps) in &imports {
185 for dep in deps {
186 imported_by
187 .entry(dep.clone())
188 .or_default()
189 .push(importer.clone());
190 }
191 }
192
193 let core_files: Vec<String> = js_files
195 .iter()
196 .filter(|f| {
197 imported_by
198 .get(*f)
199 .is_none_or(|importers| importers.is_empty())
200 })
201 .cloned()
202 .collect();
203
204 let mut groups: Vec<FileGroup> = Vec::new();
206 for core in &core_files {
207 let members = transitive_deps(core, &imports);
208 let core_name = sanitzed.get(core).cloned().unwrap_or_else(|| {
209 sanitize_name(core)
210 });
211 let name_map = sanitzed.clone();
212
213 groups.push(FileGroup {
214 core_name: core_name.clone(),
215 core_file: core.clone(),
216 members,
217 name_map,
218 imported_names: imported_names.clone(),
219 });
220 }
221
222 let groups_json = serde_json::to_string_pretty(&groups_to_json(&groups))
224 .expect("Failed to serialize groups.json");
225
226 (groups, groups_json)
227}
228
229fn transitive_deps(
231 file: &str,
232 imports: &HashMap<String, Vec<String>>,
233) -> Vec<String> {
234 let mut visited: HashSet<String> = HashSet::new();
235 let mut stack: Vec<String> = vec![file.to_string()];
236 let mut result: Vec<String> = Vec::new();
237
238 while let Some(cur) = stack.pop() {
240 if !visited.insert(cur.clone()) {
241 continue;
242 }
243 result.push(cur.clone());
244 if let Some(deps) = imports.get(&cur) {
245 for dep in deps {
246 if !visited.contains(dep.as_str()) {
247 stack.push(dep.clone());
248 }
249 }
250 }
251 }
252 result.reverse();
253 result
254}
255
256type ImportMeta = (Vec<String>, Vec<String>, Vec<String>, Vec<(String, String)>);
258
259fn extract_imports(
265 src: &str,
266 _filename: &str,
267) -> ImportMeta {
268 let mut imported_files: Vec<String> = Vec::new();
270 let mut exported_names: Vec<String> = Vec::new();
271 let mut declarations: Vec<String> = Vec::new();
272 let mut imported_names: Vec<(String, String)> = Vec::new();
273
274 for line in src.lines() {
275 let trimmed = line.trim();
276
277 if trimmed.starts_with("import ")
279 && let Some(from_idx) = trimmed.find(" from ") {
280 let specifier = &trimmed[from_idx + 6..];
282 let specifier = specifier.trim();
283 let path_str = if let Some(stripped) = specifier.strip_prefix('\'') {
284 stripped.find('\'').map(|end| &stripped[..end])
285 } else if let Some(stripped) = specifier.strip_prefix('"') {
286 stripped.find('"').map(|end| &stripped[..end])
287 } else {
288 None
289 };
290
291 let source_filename = path_str
292 .and_then(path_to_filename);
293
294 if let Some(ref sf) = source_filename {
295 imported_files.push(sf.clone());
296 }
297
298 let import_clause = &trimmed["import ".len()..from_idx].trim();
300 if let Some(brace_open) = import_clause.find('{')
301 && let Some(brace_close) = import_clause[brace_open..].find('}')
302 {
303 let names_str = &import_clause[brace_open + 1..brace_open + brace_close];
304 for name in names_str.split(',') {
305 let name = name.trim();
306 if !name.is_empty()
307 && let Some(ref sf) = source_filename
308 {
309 imported_names.push((name.to_string(), sf.clone()));
310 }
311 }
312 }
313 }
314
315 if let Some(rest) = trimmed.strip_prefix("export ") {
317 if let Some(after) = rest.strip_prefix("function ") {
318 if let Some(name_end) = after.find('(') {
319 exported_names.push(after[..name_end].trim().to_string());
320 }
321 } else if rest.starts_with("const ") || rest.starts_with("let ") || rest.starts_with("var ") {
322 let after = &rest[6..];
324 if let Some(eq) = after.find('=') {
325 let name = after[..eq].trim();
326 exported_names.push(name.to_string());
327 }
328 } else if let Some(after) = rest.strip_prefix("class ") {
329 if let Some(name_end) = after.find([' ', '{']) {
330 exported_names.push(after[..name_end].trim().to_string());
331 }
332 } else if rest.starts_with("async function ")
333 && let Some(name_end) = rest[16..].find('(') {
334 exported_names.push(rest[16..16 + name_end].trim().to_string());
335 }
336 }
337
338 if trimmed.starts_with("function ") && !trimmed.starts_with("//")
340 && let Some(name_end) = trimmed[9..].find('(') {
341 declarations.push(trimmed[9..9 + name_end].trim().to_string());
342 }
343 if (trimmed.starts_with("const ") || trimmed.starts_with("let ") || trimmed.starts_with("var "))
344 && !trimmed.contains("export ")
345 {
346 let prefix = if trimmed.starts_with("const ") { 6 } else { 4 };
347 let after = &trimmed[prefix..];
348 if let Some(eq) = after.find('=') {
349 let name = after[..eq].trim();
350 declarations.push(name.to_string());
351 }
352 }
353 }
354
355 imported_files.sort();
357 imported_files.dedup();
358 imported_names.sort();
359 imported_names.dedup();
360
361 (imported_files, exported_names, declarations, imported_names)
362}
363
364fn path_to_filename(path: &str) -> Option<String> {
366 let fname = Path::new(path).file_name()?.to_string_lossy().to_string();
367 if fname.ends_with(".js") {
368 Some(fname)
369 } else {
370 Some(format!("{}.js", fname))
371 }
372}
373
374fn groups_to_json(groups: &[FileGroup]) -> serde_json::Value {
376 let entries: Vec<serde_json::Value> = groups
377 .iter()
378 .map(|g| {
379 serde_json::json!({
380 "name": g.core_name,
381 "core_file": g.core_file,
382 "member_count": g.members.len(),
383 "members": g.members,
384 })
385 })
386 .collect();
387 serde_json::Value::Array(entries)
388}