forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwatcher.js
More file actions
688 lines (612 loc) · 17.4 KB
/
watcher.js
File metadata and controls
688 lines (612 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
'use strict';
const {
ArrayPrototypePush,
ObjectAssign,
Promise,
PromiseResolve,
SafeMap,
SafeSet,
SymbolAsyncIterator,
} = primordials;
const { AbortError } = require('internal/errors');
const { Buffer } = require('buffer');
const { EventEmitter } = require('events');
const { basename, join } = require('path');
const {
setInterval,
clearInterval,
} = require('timers');
/**
* VFSWatcher - Polling-based file/directory watcher for VFS.
* Emits 'change' events when the file content or stats change.
* Compatible with fs.watch() return value interface.
*/
class VFSWatcher extends EventEmitter {
#vfs;
#path;
#interval;
#timer = null;
#lastStats;
#closed = false;
#persistent;
#recursive;
#encoding;
#trackedFiles;
#signal;
#abortHandler = null;
/**
* @param {VirtualProvider} provider The VFS provider
* @param {string} path The path to watch (provider-relative)
* @param {object} [options] Options
* @param {number} [options.interval] Polling interval in ms (default: 100)
* @param {boolean} [options.persistent] Keep process alive (default: true)
* @param {boolean} [options.recursive] Watch subdirectories (default: false)
* @param {AbortSignal} [options.signal] AbortSignal for cancellation
*/
constructor(provider, path, options = {}) {
super();
this.#vfs = provider;
this.#path = path;
this.#interval = options.interval ?? 100;
this.#persistent = options.persistent !== false;
this.#recursive = options.recursive === true;
this.#encoding = options.encoding;
this.#trackedFiles = new SafeMap(); // path -> { stats, relativePath }
this.#signal = options.signal;
// Handle AbortSignal
if (this.#signal) {
if (this.#signal.aborted) {
this.close();
return;
}
this.#abortHandler = () => this.close();
this.#signal.addEventListener('abort', this.#abortHandler, { once: true });
}
// Get initial stats
this.#lastStats = this.#getStats();
// If watching a directory, build file list
if (this.#lastStats?.isDirectory()) {
if (this.#recursive) {
this.#buildFileList(this.#path, '');
} else {
this.#buildChildList(this.#path);
}
}
// Start polling
this.#startPolling();
}
/**
* Encodes a filename according to the watcher's encoding option.
* @param {string} filename The filename to encode
* @returns {string|Buffer} The encoded filename
*/
#encodeFilename(filename) {
if (this.#encoding === 'buffer') {
return Buffer.from(filename);
}
return filename;
}
/**
* Gets stats for the watched path.
* @returns {Stats|null} The stats or null if file doesn't exist
*/
#getStats() {
try {
return this.#vfs.statSync(this.#path);
} catch {
return null;
}
}
/**
* Starts the polling timer.
*/
#startPolling() {
if (this.#closed) return;
this.#timer = setInterval(() => this.#poll(), this.#interval);
// If not persistent, unref the timer to allow process to exit
if (!this.#persistent && this.#timer.unref) {
this.#timer.unref();
}
}
/**
* Polls for changes.
*/
#poll() {
if (this.#closed) return;
// For directory watching, poll tracked children
if (this.#lastStats?.isDirectory()) {
this.#pollDirectory();
return;
}
// For single file watching
const newStats = this.#getStats();
if (this.#statsChanged(this.#lastStats, newStats)) {
const eventType = this.#determineEventType(this.#lastStats, newStats);
const filename = this.#encodeFilename(basename(this.#path));
this.emit('change', eventType, filename);
}
this.#lastStats = newStats;
}
/**
* Polls directory children for changes, detecting new and deleted files.
*/
#pollDirectory() {
// Rescan for new files
if (this.#recursive) {
this.#rescanRecursive(this.#path, '');
} else {
this.#rescanChildren(this.#path);
}
// Check tracked files for changes/deletions
for (const { 0: filePath, 1: info } of this.#trackedFiles) {
const newStats = this.#getStatsFor(filePath);
if (newStats === null && info.stats !== null) {
// File was deleted
this.emit('change', 'rename', this.#encodeFilename(info.relativePath));
this.#trackedFiles.delete(filePath);
} else if (this.#statsChanged(info.stats, newStats)) {
const eventType = this.#determineEventType(info.stats, newStats);
this.emit('change', eventType, this.#encodeFilename(info.relativePath));
info.stats = newStats;
}
}
}
/**
* Rescans direct children for new entries.
* @param {string} dirPath The directory path
*/
#rescanChildren(dirPath) {
try {
const entries = this.#vfs.readdirSync(dirPath);
for (const name of entries) {
const fullPath = join(dirPath, name);
if (!this.#trackedFiles.has(fullPath)) {
const stats = this.#getStatsFor(fullPath);
this.#trackedFiles.set(fullPath, {
stats,
relativePath: name,
});
this.emit('change', 'rename', this.#encodeFilename(name));
}
}
} catch {
// Directory might not exist or be readable
}
}
/**
* Recursively rescans for new entries.
* @param {string} dirPath The directory path
* @param {string} relativePath The relative path from watched root
*/
#rescanRecursive(dirPath, relativePath) {
try {
const entries = this.#vfs.readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(dirPath, entry.name);
const relPath = relativePath ?
join(relativePath, entry.name) : entry.name;
if (entry.isDirectory()) {
this.#rescanRecursive(fullPath, relPath);
} else if (!this.#trackedFiles.has(fullPath)) {
const stats = this.#getStatsFor(fullPath);
this.#trackedFiles.set(fullPath, {
stats,
relativePath: relPath,
});
this.emit('change', 'rename', this.#encodeFilename(relPath));
}
}
} catch {
// Directory might not exist or be readable
}
}
/**
* Gets stats for a specific path.
* @param {string} filePath The file path
* @returns {Stats|null}
*/
#getStatsFor(filePath) {
try {
return this.#vfs.statSync(filePath);
} catch {
return null;
}
}
/**
* Builds the list of files to track for recursive watching.
* @param {string} dirPath The directory path
* @param {string} relativePath The relative path from the watched root
*/
#buildFileList(dirPath, relativePath) {
try {
const entries = this.#vfs.readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(dirPath, entry.name);
const relPath = relativePath ? join(relativePath, entry.name) : entry.name;
if (entry.isDirectory()) {
// Recurse into subdirectory
this.#buildFileList(fullPath, relPath);
} else {
// Track the file
const stats = this.#getStatsFor(fullPath);
this.#trackedFiles.set(fullPath, {
stats,
relativePath: relPath,
});
}
}
} catch {
// Directory might not exist or be readable
}
}
/**
* Builds a list of direct children to track for non-recursive watching.
* @param {string} dirPath The directory path
*/
#buildChildList(dirPath) {
try {
const entries = this.#vfs.readdirSync(dirPath);
for (const name of entries) {
const fullPath = join(dirPath, name);
const stats = this.#getStatsFor(fullPath);
this.#trackedFiles.set(fullPath, {
stats,
relativePath: name,
});
}
} catch {
// Directory might not exist or be readable
}
}
/**
* Checks if stats have changed.
* @param {Stats|null} oldStats Previous stats
* @param {Stats|null} newStats Current stats
* @returns {boolean} True if stats changed
*/
#statsChanged(oldStats, newStats) {
// File created or deleted
if ((oldStats === null) !== (newStats === null)) {
return true;
}
// Both null - no change
if (oldStats === null && newStats === null) {
return false;
}
// Compare mtime and size
if (oldStats.mtimeMs !== newStats.mtimeMs) {
return true;
}
if (oldStats.size !== newStats.size) {
return true;
}
return false;
}
/**
* Determines the event type based on stats change.
* @param {Stats|null} oldStats Previous stats
* @param {Stats|null} newStats Current stats
* @returns {string} 'rename' or 'change'
*/
#determineEventType(oldStats, newStats) {
// File was created or deleted
if ((oldStats === null) !== (newStats === null)) {
return 'rename';
}
// Content changed
return 'change';
}
/**
* Closes the watcher and stops polling.
*/
close() {
if (this.#closed) return;
this.#closed = true;
if (this.#timer) {
clearInterval(this.#timer);
this.#timer = null;
}
// Clear tracked files
this.#trackedFiles.clear();
// Remove abort handler
if (this.#signal && this.#abortHandler) {
this.#signal.removeEventListener('abort', this.#abortHandler);
}
this.emit('close');
}
/**
* Alias for close() - compatibility with FSWatcher.
* @returns {this}
*/
unref() {
this.#timer?.unref?.();
return this;
}
/**
* Makes the timer keep the process alive - compatibility with FSWatcher.
* @returns {this}
*/
ref() {
this.#timer?.ref?.();
return this;
}
}
/**
* VFSStatWatcher - Polling-based stat watcher for VFS.
* Emits 'change' events with current and previous stats.
* Compatible with fs.watchFile() return value interface.
*/
class VFSStatWatcher extends EventEmitter {
#vfs;
#path;
#interval;
#persistent;
#bigint;
#closed = false;
#timer = null;
#lastStats;
#listeners;
/**
* @param {VirtualProvider} provider The VFS provider
* @param {string} path The path to watch (provider-relative)
* @param {object} [options] Options
* @param {number} [options.interval] Polling interval in ms (default: 5007)
* @param {boolean} [options.persistent] Keep process alive (default: true)
*/
constructor(provider, path, options = {}) {
super();
this.#vfs = provider;
this.#path = path;
this.#interval = options.interval ?? 5007;
this.#persistent = options.persistent !== false;
this.#bigint = options.bigint === true;
this.#listeners = new SafeSet();
// Get initial stats
this.#lastStats = this.#getStats();
// Start polling
this.#startPolling();
}
/**
* Gets stats for the watched path.
* @returns {Stats} The stats (with zeroed values if file doesn't exist)
*/
#getStats() {
try {
return this.#vfs.statSync(this.#path, { bigint: this.#bigint });
} catch {
// Return a zeroed stats object for non-existent files
// This matches Node.js behavior
return this.#createZeroStats();
}
}
/**
* Creates a zeroed stats object for non-existent files.
* @returns {object} Zeroed stats
*/
#createZeroStats() {
const { createZeroStats } = require('internal/vfs/stats');
return createZeroStats({ bigint: this.#bigint });
}
/**
* Starts the polling timer.
*/
#startPolling() {
if (this.#closed) return;
this.#timer = setInterval(() => this.#poll(), this.#interval);
// If not persistent, unref the timer to allow process to exit
if (!this.#persistent && this.#timer.unref) {
this.#timer.unref();
}
}
/**
* Polls for changes.
*/
#poll() {
if (this.#closed) return;
const newStats = this.#getStats();
if (this.#statsChanged(this.#lastStats, newStats)) {
const prevStats = this.#lastStats;
this.#lastStats = newStats;
this.emit('change', newStats, prevStats);
}
}
/**
* Checks if stats have changed.
* @param {Stats} oldStats Previous stats
* @param {Stats} newStats Current stats
* @returns {boolean} True if stats changed
*/
#statsChanged(oldStats, newStats) {
// Compare mtime and ctime
if (oldStats.mtimeMs !== newStats.mtimeMs) {
return true;
}
if (oldStats.ctimeMs !== newStats.ctimeMs) {
return true;
}
if (oldStats.size !== newStats.size) {
return true;
}
return false;
}
/**
* Adds a listener for the given event.
* Tracks 'change' listeners for internal bookkeeping.
* @param {string} event The event name
* @param {Function} listener The listener function
* @returns {this}
*/
addListener(event, listener) {
if (event === 'change') {
this.#listeners.add(listener);
}
super.addListener(event, listener);
return this;
}
/**
* Removes a listener for the given event.
* @param {string} event The event name
* @param {Function} listener The listener function
* @returns {this}
*/
removeListener(event, listener) {
if (event === 'change') {
this.#listeners.delete(listener);
}
super.removeListener(event, listener);
return this;
}
/**
* Removes all listeners for an event.
* Overrides EventEmitter to also clear internal #listeners tracking.
* @param {string} eventName The event name
* @returns {this}
*/
removeAllListeners(eventName) {
if (eventName === 'change') {
this.#listeners.clear();
}
super.removeAllListeners(eventName);
return this;
}
/**
* Returns true if there are no listeners.
* @returns {boolean}
*/
hasNoListeners() {
return this.#listeners.size === 0;
}
/**
* Stops the watcher.
*/
stop() {
if (this.#closed) return;
this.#closed = true;
if (this.#timer) {
clearInterval(this.#timer);
this.#timer = null;
}
this.emit('stop');
}
/**
* Makes the timer not keep the process alive.
* @returns {this}
*/
unref() {
this.#timer?.unref?.();
return this;
}
/**
* Makes the timer keep the process alive.
* @returns {this}
*/
ref() {
this.#timer?.ref?.();
return this;
}
}
/**
* VFSWatchAsyncIterable - Async iterable wrapper for VFSWatcher.
* Compatible with fs.promises.watch() return value interface.
*/
const kMaxPendingEvents = 1024;
class VFSWatchAsyncIterable {
#watcher;
#closed = false;
#pendingEvents = [];
#pendingResolvers = [];
/**
* @param {VirtualProvider} provider The VFS provider
* @param {string} path The path to watch (provider-relative)
* @param {object} [options] Options
*/
constructor(provider, path, options = {}) {
// Strip signal from options passed to VFSWatcher — we handle abort
// at the iterable level to reject pending next() with AbortError
// instead of resolving with done:true via the 'close' event.
const signal = options.signal;
const watcherOptions = ObjectAssign({ __proto__: null }, options);
delete watcherOptions.signal;
this.#watcher = new VFSWatcher(provider, path, watcherOptions);
this.#watcher.on('change', (eventType, filename) => {
const event = { eventType, filename };
if (this.#pendingResolvers.length > 0) {
const { resolve } = this.#pendingResolvers.shift();
resolve({ value: event, done: false });
} else if (this.#pendingEvents.length < kMaxPendingEvents) {
ArrayPrototypePush(this.#pendingEvents, event);
}
// Drop events when queue is full to prevent unbounded memory growth
});
this.#watcher.on('close', () => {
this.#closed = true;
// Resolve any pending iterators
while (this.#pendingResolvers.length > 0) {
const { resolve } = this.#pendingResolvers.shift();
resolve({ value: undefined, done: true });
}
});
// Handle abort signal — reject pending next() with AbortError
if (signal) {
const onAbort = () => {
this.#closed = true;
const err = new AbortError(undefined, { cause: signal.reason });
while (this.#pendingResolvers.length > 0) {
const { reject } = this.#pendingResolvers.shift();
reject(err);
}
this.#watcher.close();
};
if (signal.aborted) {
onAbort();
} else {
signal.addEventListener('abort', onAbort, { once: true });
}
}
}
/**
* Returns the async iterator.
* @returns {AsyncIterator}
*/
[SymbolAsyncIterator]() {
return this;
}
/**
* Gets the next event.
* @returns {Promise<IteratorResult>}
*/
next() {
if (this.#closed) {
return PromiseResolve({ value: undefined, done: true });
}
if (this.#pendingEvents.length > 0) {
const event = this.#pendingEvents.shift();
return PromiseResolve({ value: event, done: false });
}
return new Promise((resolve, reject) => {
ArrayPrototypePush(this.#pendingResolvers, { resolve, reject });
});
}
/**
* Closes the iterator and underlying watcher.
* @returns {Promise<IteratorResult>}
*/
return() {
this.#watcher.close();
return PromiseResolve({ value: undefined, done: true });
}
/**
* Handles iterator throw.
* @param {Error} error The error to throw
* @returns {Promise<IteratorResult>}
*/
throw(error) {
this.#watcher.close();
return PromiseResolve({ value: undefined, done: true });
}
}
module.exports = {
VFSWatcher,
VFSStatWatcher,
VFSWatchAsyncIterable,
};