import { statSync } from 'node:fs' import { dirname, isAbsolute, relative, resolve } from 'node:path' import type { AsyncSubscription } from '@parcel/watcher' import type { Driver, SourceChange } from '@pandacss/compiler' export type WatchEvent = SourceChange export interface WatchBatch { source: WatchEvent[] config: WatchEvent[] } export interface ProjectWatchOptions { driver: Driver cwd: string outdir: string | (() => string) debounceMs?: number onStatus?(message: string): void onError?(error: unknown): void onSourceChange(events: WatchEvent[]): Promise | void onConfigChange(events: WatchEvent[]): Promise | void // Full rebuild used to recover from a dropped-events signal (see the subscribe // handler below). Defaults to `onSourceChange([])`, which re-reads from disk for // the default `build`/`lib` commands; commands whose incremental `onSourceChange` // skips a re-parse (`cssgen`, `analyze`) override this to force a full re-scan. onRescan?(): Promise | void } export function formatWatchError(error: unknown): string { if (error instanceof Error) return error.stack ?? error.message return String(error) } // `@parcel/watcher` relays a macOS FSEvents backpressure condition — its user- or // kernel-side event buffer overflowed and the OS coalesced the backlog — as a // *recoverable* subscribe-callback error whose message contains "must be // re-scanned" (the three variants live in @parcel/watcher's FSEventsBackend.cc). // Per Apple's FSEvents contract (`kFSEventStreamEventFlagMustScanSubDirs`) the // correct response is to re-scan, not to treat the watch as broken. export function isFsEventsRescanError(error: unknown): boolean { return error instanceof Error && error.message.includes('must be re-scanned') } export function normalizeParcelEvent(event: { type: string; path: string }): WatchEvent | undefined { if (event.type === 'create') return { kind: 'add', path: event.path } if (event.type === 'update') return { kind: 'change', path: event.path } if (event.type === 'delete') return { kind: 'unlink', path: event.path } return undefined } export function createEventDebouncer(callback: (events: T[]) => void | Promise, delay = 50) { let timer: ReturnType | undefined let pending: T[] = [] const flush = async () => { if (timer) clearTimeout(timer) timer = undefined if (pending.length === 0) return const events = pending pending = [] await callback(events) } return { push(events: T[]) { pending.push(...events) if (timer) clearTimeout(timer) timer = setTimeout(() => void flush(), delay) }, flush, close() { if (timer) clearTimeout(timer) timer = undefined pending = [] }, } } export async function handleWatchBatch( driver: Pick, batch: WatchBatch, ): Promise { if (batch.config.length > 0) { const diff = await driver.reload() if (!diff.hasChanged) return } if (batch.source.length > 0) { driver.applyChanges(batch.source) } } export async function startProjectWatch(options: ProjectWatchOptions): Promise<() => Promise> { // Native watcher — only load when a command actually enters watch mode. const parcelWatcher = await import('@parcel/watcher') const targets = options.driver.watchTargets() const configFiles = new Set(targets.config.map((path) => resolve(options.cwd, path))) const configDirs = new Set([...configFiles].map((path) => dirname(path))) const sourceDirs = new Set(targets.dirs.map((dir) => resolve(options.cwd, dir))) const watchableConfigDirs = new Set([...configDirs].filter(isWatchableDirectory)) const watchableSourceDirs = new Set([...sourceDirs].filter(isWatchableDirectory)) const debounceMs = options.debounceMs ?? 0 let serialGate: Promise = Promise.resolve() const currentOutdir = () => (typeof options.outdir === 'function' ? options.outdir() : options.outdir) const runSerialized = (task: () => Promise): Promise => { // Rebuilds must not overlap; each batch waits for the previous one to settle. serialGate = serialGate.then(task).catch((error) => { options.onStatus?.('watch: rebuild failed') options.onError?.(error) }) return serialGate } // Recovery for a dropped-events signal: a full rebuild that must re-read the // filesystem, since the specific missed paths are unknown. Defaults to // `onSourceChange([])`; commands with an incremental `onSourceChange` pass an // explicit `onRescan` that re-parses from disk. const rescan = (): Promise => Promise.resolve(options.onRescan ? options.onRescan() : options.onSourceChange([])) const debouncer = createEventDebouncer(async (events) => { const batch = splitEvents(events, options.driver) await runSerialized(async () => { options.onStatus?.(formatWatchChange(options.cwd, batch)) options.onStatus?.(formatWatchRebuildStart(batch)) if (batch.config.length > 0) { await options.onConfigChange(batch.config) options.onStatus?.(formatWatchRebuildSuccess(batch)) return } if (batch.source.length > 0) { await options.onSourceChange(batch.source) options.onStatus?.(formatWatchRebuildSuccess(batch)) } }) }, debounceMs) const subscriptions: AsyncSubscription[] = [] const subscribe = async (dir: string, filter?: (event: WatchEvent) => boolean) => { const subscription = await parcelWatcher.subscribe( dir, (error, events) => { if (error) { // Rethrowing here escapes into @parcel/watcher's native callback as an // uncaught exception and kills the watch process. A dropped-events // signal is recoverable — the OS is asking us to re-scan — so run a // full rebuild through the serial gate instead of crashing. Anything // else is a genuine watcher failure and keeps the original throw. if (isFsEventsRescanError(error)) { options.onStatus?.('watch: dropped events, re-scanning') void runSerialized(rescan) return } throw error } const normalized = events .map((event) => normalizeParcelEvent(event)) .filter((event): event is WatchEvent => !!event) .filter((event) => !isOutputEvent(options.cwd, currentOutdir(), event)) .filter((event) => !filter || filter(event)) if (normalized.length > 0) debouncer.push(normalized) }, { ignore: ['**/node_modules/**', '**/.git/**', '**/.DS_Store', `${currentOutdir()}/**`] }, ) subscriptions.push(subscription) } await Promise.all([ ...[...watchableSourceDirs].map((dir) => subscribe(dir)), ...[...watchableConfigDirs].map((dir) => subscribe(dir, (event) => options.driver.isConfigFile(event.path))), ]) options.onStatus?.( formatWatchReady({ sourceDirs: watchableSourceDirs.size, configFiles: configFiles.size + (options.driver.configPath ? 1 : 0), debounceMs, outdir: currentOutdir(), }), ) let stopped = false const stop = async () => { if (stopped) return stopped = true debouncer.close() await Promise.all(subscriptions.map((subscription) => subscription.unsubscribe())) // Tests and embedded callers may start multiple watchers in one process. process.off('SIGINT', exit) process.off('SIGTERM', exit) options.onStatus?.('watch: stopped') } const exit = () => { void stop().finally(() => process.exit(0)) } process.once('SIGINT', exit) process.once('SIGTERM', exit) return stop } export function formatWatchReady(summary: { sourceDirs: number configFiles: number debounceMs: number outdir: string }): string { return `watch: ready (${summary.sourceDirs} source dirs, ${summary.configFiles} config files, debounce ${summary.debounceMs}ms, outdir ${summary.outdir})` } export function formatWatchRebuildStart(batch: WatchBatch): string { return `watch: rebuilding (${batch.source.length} source, ${batch.config.length} config)` } export function formatWatchRebuildSuccess(batch: WatchBatch): string { if (batch.config.length > 0) return 'watch: config reloaded' return `watch: rebuilt ${batch.source.length} source events` } export function formatWatchChange(cwd: string, batch: WatchBatch): string { if (batch.config.length > 0) return formatWatchChangeKind(cwd, 'config', batch.config) return formatWatchChangeKind(cwd, 'source', batch.source) } export function isOutputEvent(cwd: string, outdir: string, event: WatchEvent): boolean { const outputDir = resolve(cwd, outdir) const target = resolve(cwd, event.path) const path = relative(outputDir, target) return path === '' || (!!path && !path.startsWith('..') && !isAbsolute(path)) } export function isWatchableDirectory(path: string): boolean { try { return statSync(path).isDirectory() } catch { return false } } function splitEvents(events: WatchEvent[], driver: Pick): WatchBatch { const batch: WatchBatch = { source: [], config: [] } for (const event of events) { if (driver.isConfigFile(event.path)) batch.config.push(event) else batch.source.push(event) } return batch } function formatWatchChangeKind(cwd: string, kind: 'config' | 'source', events: WatchEvent[]): string { if (events.length === 1) return `watch: ${kind} changed ${formatWatchPath(cwd, events[0]!.path)}` return `watch: ${events.length} ${kind} files changed` } function formatWatchPath(cwd: string, path: string): string { const absolute = isAbsolute(path) ? path : resolve(cwd, path) const formatted = relative(cwd, absolute) return formatted && !formatted.startsWith('..') && !isAbsolute(formatted) ? formatted : path }