| 1 | import * as fs from "fs"; |
| 2 | import * as path from "path"; |
| 3 | |
| 4 | import { FILE_IGNORE_PATTERNS } from "./filePatterns.js"; |
| 5 | |
| 6 | interface FileWatcherOptions { |
| 7 | ignore?: string[]; |
| 8 | debounceMs?: number; |
| 9 | maxDepth?: number; |
| 10 | } |
| 11 | |
| 12 | export class FileWatcher { |
| 13 | private watchers: fs.FSWatcher[] = []; |
| 14 | private callbacks: Set<() => void> = new Set(); |
| 15 | private debounceTimer: NodeJS.Timeout | null = null; |
| 16 | private options: Required<FileWatcherOptions>; |
| 17 | private watchedDirs: Set<string> = new Set(); |
| 18 | private isInitializing: boolean = false; |
| 19 | private lastErrorCode: string | null = null; |
| 20 | |
| 21 | constructor(options: FileWatcherOptions = {}) { |
| 22 | this.options = { |
| 23 | ignore: [...FILE_IGNORE_PATTERNS, ...(options.ignore || [])], |
| 24 | debounceMs: options.debounceMs || 1000, |
| 25 | maxDepth: options.maxDepth || 10, |
| 26 | }; |
| 27 | } |
| 28 | |
| 29 | private shouldIgnorePath(filePath: string): boolean { |
| 30 | const normalizedPath = path.normalize(filePath).replace(/\\/g, "/"); |
| 31 | |
| 32 | return this.options.ignore.some((pattern) => { |
| 33 | if (pattern.startsWith("**/")) { |
| 34 | const suffix = pattern.slice(3); |
| 35 | if (suffix.endsWith("/**")) { |
| 36 | // Directory pattern like **/node_modules/** |
| 37 | const dirName = suffix.slice(0, -3); |
| 38 | return ( |
| 39 | normalizedPath.includes(`/${dirName}/`) || |
| 40 | normalizedPath.endsWith(`/${dirName}`) || |
| 41 | normalizedPath === dirName |
| 42 | ); |
| 43 | } else if (suffix.startsWith("*")) { |
| 44 | // File pattern like **/*.tmp |
| 45 | const extension = suffix.slice(1); // Remove the '*' to get the extension |
| 46 | return normalizedPath.endsWith(extension); |
| 47 | } else { |
| 48 | // File pattern like **/package.json |
| 49 | return ( |
| 50 | normalizedPath.endsWith(`/${suffix}`) || |
| 51 | normalizedPath.endsWith(suffix) |
| 52 | ); |
| 53 | } |
| 54 | } |
| 55 | return normalizedPath.includes(pattern); |
| 56 | }); |
| 57 | } |
| 58 | |
| 59 | private triggerCallbacks(): void { |
| 60 | // Don't trigger callbacks during initialization |
| 61 | if (this.isInitializing) { |
| 62 | return; |
| 63 | } |
| 64 | |
| 65 | if (this.debounceTimer) { |
| 66 | clearTimeout(this.debounceTimer); |
| 67 | } |
| 68 | |
| 69 | this.debounceTimer = setTimeout(() => { |
| 70 | this.callbacks.forEach((callback) => { |
| 71 | try { |
| 72 | callback(); |
| 73 | } catch (error) { |
| 74 | console.error("Error in file watcher callback:", error); |
| 75 | } |
| 76 | }); |
| 77 | }, this.options.debounceMs); |
| 78 | } |
| 79 | |
| 80 | private handleFileChange = ( |
| 81 | eventType: string, |
| 82 | filename: string | null, |
| 83 | dirPath: string, |
| 84 | depth: number, |
| 85 | ): void => { |
| 86 | if (!filename) return; |
| 87 | |
| 88 | const fullPath = path.join(dirPath, filename); |
| 89 | |
| 90 | // Skip if path should be ignored |
| 91 | if (this.shouldIgnorePath(fullPath)) { |
| 92 | return; |
| 93 | } |
| 94 | |
| 95 | // Check if it's a directory and we should watch it |
| 96 | if (eventType === "rename") { |
| 97 | this.handleNewDirectory(fullPath, depth); |
| 98 | } |
| 99 | |
| 100 | this.triggerCallbacks(); |
| 101 | }; |
| 102 | |
| 103 | private handleNewDirectory(fullPath: string, depth: number): void { |
| 104 | try { |
| 105 | const stats = fs.statSync(fullPath); |
| 106 | if (stats.isDirectory() && depth < this.options.maxDepth) { |
| 107 | // New directory created, start watching it |
| 108 | this.watchDirectory(fullPath, depth + 1); |
| 109 | } |
| 110 | } catch { |
| 111 | // File/directory was deleted or not accessible |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | private setupWatcher(dirPath: string, depth: number): void { |
| 116 | try { |
| 117 | const watcher = fs.watch( |
| 118 | dirPath, |
| 119 | { persistent: false }, |
| 120 | (eventType, filename) => { |
| 121 | this.handleFileChange(eventType, filename, dirPath, depth); |
| 122 | }, |
| 123 | ); |
| 124 | |
| 125 | watcher.on("error", (error: any) => { |
| 126 | this.lastErrorCode = error?.code || null; |
| 127 | console.error(`File watcher error for ${dirPath}:`, error); |
| 128 | }); |
| 129 | |
| 130 | this.watchers.push(watcher); |
| 131 | } catch (error: any) { |
| 132 | // Gracefully handle environments that restrict fs.watch (e.g., low descriptor limits) |
| 133 | this.lastErrorCode = error?.code || null; |
| 134 | console.error(`Failed to create watcher for ${dirPath}:`, error); |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | private watchSubdirectories(dirPath: string, depth: number): void { |
| 139 | try { |
| 140 | const entries = fs.readdirSync(dirPath); |
| 141 | for (const entry of entries) { |
| 142 | const entryPath = path.join(dirPath, entry); |
| 143 | if (this.shouldIgnorePath(entryPath)) { |
| 144 | continue; |
| 145 | } |
| 146 | |
| 147 | try { |
| 148 | const stats = fs.statSync(entryPath); |
| 149 | if (stats.isDirectory()) { |
| 150 | this.watchDirectory(entryPath, depth + 1); |
| 151 | } |
| 152 | } catch { |
| 153 | // Skip inaccessible entries |
| 154 | } |
| 155 | } |
| 156 | } catch { |
| 157 | // Skip if can't read directory |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | private watchDirectory(dirPath: string, depth: number = 0): void { |
| 162 | if ( |
| 163 | depth > this.options.maxDepth || |
| 164 | this.shouldIgnorePath(dirPath) || |
| 165 | this.watchedDirs.has(dirPath) |
| 166 | ) { |
| 167 | return; |
| 168 | } |
| 169 | |
| 170 | try { |
| 171 | // Check if directory exists and is accessible |
| 172 | const stats = fs.statSync(dirPath); |
| 173 | if (!stats.isDirectory()) { |
| 174 | return; |
| 175 | } |
| 176 | |
| 177 | this.watchedDirs.add(dirPath); |
| 178 | this.setupWatcher(dirPath, depth); |
| 179 | this.watchSubdirectories(dirPath, depth); |
| 180 | } catch (error) { |
| 181 | console.error(`Failed to watch directory ${dirPath}:`, error); |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | public startWatching(rootPath: string = process.cwd()): void { |
| 186 | this.stopWatching(); |
| 187 | this.isInitializing = true; |
| 188 | this.watchDirectory(rootPath); |
| 189 | |
| 190 | // Allow a small delay for initial file system events to settle |
| 191 | // before enabling callbacks |
| 192 | setTimeout(() => { |
| 193 | this.isInitializing = false; |
| 194 | }, 50); |
| 195 | } |
| 196 | |
| 197 | public stopWatching(): void { |
| 198 | this.isInitializing = false; |
| 199 | this.watchers.forEach((watcher) => { |
| 200 | try { |
| 201 | watcher.close(); |
| 202 | } catch (error) { |
| 203 | console.error("Error closing file watcher:", error); |
| 204 | } |
| 205 | }); |
| 206 | this.watchers = []; |
| 207 | this.watchedDirs.clear(); |
| 208 | |
| 209 | if (this.debounceTimer) { |
| 210 | clearTimeout(this.debounceTimer); |
| 211 | this.debounceTimer = null; |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | public onChange(callback: () => void): () => void { |
| 216 | this.callbacks.add(callback); |
| 217 | |
| 218 | // Return unsubscribe function |
| 219 | return () => { |
| 220 | this.callbacks.delete(callback); |
| 221 | }; |
| 222 | } |
| 223 | |
| 224 | public destroy(): void { |
| 225 | this.stopWatching(); |
| 226 | this.callbacks.clear(); |
| 227 | } |
| 228 | |
| 229 | // Expose watcher health for tests and diagnostics |
| 230 | public isActive(): boolean { |
| 231 | return this.watchers.length > 0; |
| 232 | } |
| 233 | |
| 234 | public getLastErrorCode(): string | null { |
| 235 | return this.lastErrorCode; |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | // Singleton instance for the entire application |
| 240 | let globalFileWatcher: FileWatcher | null = null; |
| 241 | |
| 242 | export function getFileWatcher(): FileWatcher { |
| 243 | if (!globalFileWatcher) { |
| 244 | globalFileWatcher = new FileWatcher({ |
| 245 | debounceMs: 1000, // 1 second debounce |
| 246 | maxDepth: 10, |
| 247 | }); |
| 248 | } |
| 249 | return globalFileWatcher; |
| 250 | } |
| 251 | |
| 252 | export function startFileWatching(): void { |
| 253 | const watcher = getFileWatcher(); |
| 254 | watcher.startWatching(); |
| 255 | } |
| 256 | |
| 257 | export function stopFileWatching(): void { |
| 258 | if (globalFileWatcher) { |
| 259 | globalFileWatcher.destroy(); |
| 260 | globalFileWatcher = null; |
| 261 | } |
| 262 | } |