1use std::path::Path;
6
7use walkdir::WalkDir;
8
9use super::{WorkerConfig, WorkerInfo, WorkerType};
10
11pub struct WorkerDetector {
13 config:WorkerConfig,
14}
15
16impl WorkerDetector {
17 pub fn new(config:WorkerConfig) -> Self { Self { config } }
18
19 pub fn detect_workers(&self, root_dir:&Path) -> Vec<WorkerInfo> {
21 let mut workers = Vec::new();
22
23 for entry in WalkDir::new(root_dir).follow_links(true).into_iter().filter_map(|e| e.ok()) {
24 let path = entry.path();
25
26 if self.is_worker_file(path) {
27 if let Some(worker_info) = self.create_worker_info(path) {
28 workers.push(worker_info);
29 }
30 }
31 }
32
33 workers
34 }
35
36 pub fn is_worker_file(&self, path:&Path) -> bool {
38 if !path.is_file() {
39 return false;
40 }
41
42 let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
43
44 let worker_patterns = [
46 ".worker.ts",
47 ".worker.js",
48 ".worker.tsx",
49 ".worker.jsx",
50 "-worker.ts",
51 "-worker.js",
52 "worker.ts",
53 "worker.js",
54 "SharedWorker.ts",
55 "SharedWorker.js",
56 ];
57
58 for pattern in worker_patterns {
59 if file_name.ends_with(pattern) {
60 return true;
61 }
62 }
63
64 if let Ok(content) = std::fs::read_to_string(path) {
66 return self.contains_worker_marker(&content);
67 }
68
69 false
70 }
71
72 fn create_worker_info(&self, path:&Path) -> Option<WorkerInfo> {
74 let file_name = path.file_name()?.to_str()?;
75
76 let worker_type = if file_name.contains("SharedWorker") || file_name.contains("shared") {
77 WorkerType::Classic
79 } else {
80 self.config.worker_type
81 };
82
83 let is_shared = file_name.contains("SharedWorker") || file_name.contains("shared");
84
85 let source_path = path.to_string_lossy().to_string();
86 let name = path.file_stem()?.to_str()?.replace(".worker", "").replace("-worker", "");
87
88 let output_path = Path::new(&self.config.output_dir)
89 .join(format!("{}.js", name))
90 .to_string_lossy()
91 .to_string();
92
93 Some(WorkerInfo { source_path, output_path, name, worker_type, dependencies:Vec::new(), is_shared })
94 }
95
96 fn contains_worker_marker(&self, content:&str) -> bool {
98 let markers = [
99 "new Worker(",
100 "new SharedWorker(",
101 "self.onmessage",
102 "self.postMessage",
103 "importScripts(",
104 "// @worker",
105 "//worker",
106 ];
107
108 for marker in markers {
109 if content.contains(marker) {
110 return true;
111 }
112 }
113
114 false
115 }
116
117 pub fn extract_dependencies(&self, path:&Path) -> Vec<String> {
119 let mut deps = Vec::new();
120
121 if let Ok(content) = std::fs::read_to_string(path) {
122 for line in content.lines() {
124 let trimmed = line.trim();
125
126 if trimmed.starts_with("import ") {
128 if let Some(from_start) = trimmed.find("from") {
129 let import_part = &trimmed[from_start + 4..];
130 if let Some(path_start) = import_part.find('"') {
131 let path_end = import_part[path_start + 1..].find('"');
132 if let Some(end) = path_end {
133 let import_path = &import_part[path_start + 1..path_start + 1 + end];
134 deps.push(import_path.to_string());
135 }
136 }
137 }
138 }
139
140 if trimmed.starts_with("importScripts(") {
142 if let Some(paren_start) = trimmed.find('(') {
143 let paren_content = &trimmed[paren_start + 1..];
144 if let Some(paren_end) = paren_content.find(')') {
145 let scripts = &paren_content[..paren_end];
146 for script in scripts.split(',') {
147 let script = script.trim().trim_matches('"').trim_matches('\'');
148 if !script.is_empty() {
149 deps.push(script.to_string());
150 }
151 }
152 }
153 }
154 }
155 }
156 }
157
158 deps
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use std::fs;
165
166 use tempfile::TempDir;
167
168 use super::*;
169
170 #[test]
171 fn test_worker_detection_by_name() {
172 let config = WorkerConfig::new();
173 let detector = WorkerDetector::new(config);
174
175 assert!(detector.is_worker_file(Path::new("test.worker.ts")));
176 assert!(detector.is_worker_file(Path::new("my-worker.js")));
177 assert!(detector.is_worker_file(Path::new("SharedWorker.ts")));
178 assert!(!detector.is_worker_file(Path::new("regular.ts")));
179 }
180
181 #[test]
182 fn test_worker_detection_by_content() {
183 let config = WorkerConfig::new();
184 let detector = WorkerDetector::new(config);
185
186 let content = r#"
187 self.onmessage = function(e) {
188 self.postMessage(e.data);
189 };
190 "#;
191
192 assert!(detector.contains_worker_marker(content));
193 }
194
195 #[test]
196 fn test_dependency_extraction() {
197 let config = WorkerConfig::new();
198 let detector = WorkerDetector::new(config);
199
200 let path = Path::new("test.worker.ts");
201 let _deps = detector.extract_dependencies(path);
203 }
204}