import { statSync, watch, type FSWatcher } from 'node:fs'; import { basename, dirname } from 'node:path'; export type Log = (message: string) => void; /** Calls back once a directory tree has been quiet for the given time after a change. */ export function watchTree(directory: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined { let timer: NodeJS.Timeout | undefined; try { const watcher = watch(directory, { recursive: true }, () => { clearTimeout(timer); timer = setTimeout(onChange, quietMs); }); watcher.on('error', (error) => log(`stopped watching ${directory}: ${error.message}`)); watcher.on('close', () => clearTimeout(timer)); return watcher; } catch (error) { log(`cannot watch ${directory}: ${(error as Error).message}`); return undefined; } } /** * Watches a single file through its directory, because editors and atomic * writes replace files, which would end a watch on the old one. This also * notices a file that does not exist yet. */ export function watchFile(file: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined { let timer: NodeJS.Timeout | undefined; try { const watcher = watch(dirname(file), (_event, name) => { if (name !== basename(file)) return; clearTimeout(timer); timer = setTimeout(onChange, quietMs); }); watcher.on('error', (error) => log(`stopped watching ${file}: ${error.message}`)); watcher.on('close', () => clearTimeout(timer)); return watcher; } catch (error) { log(`cannot watch ${file}: ${(error as Error).message}`); return undefined; } } /** Watches a directory tree, or a file when the path is not a directory. */ export function watchPath(path: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined { let directory = false; try { directory = statSync(path).isDirectory(); } catch { /* A missing path is watched like a file, so its creation counts as a change. */ } return directory ? watchTree(path, quietMs, onChange, log) : watchFile(path, quietMs, onChange, log); }