UNPKG

2.42 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.WatchManager = void 0;
4const events_1 = require("events");
5class WatchEventEmitter extends events_1.EventEmitter {
6 constructor(dirWatchers, watchPath, watcherId) {
7 super();
8 this.dirWatchers = dirWatchers;
9 this.watchPath = watchPath;
10 this.watcherId = watcherId;
11 }
12 close() {
13 const dirWatcher = this.dirWatchers.get(this.watchPath);
14 dirWatcher.eventEmitters.delete(this.watcherId);
15 if (dirWatcher.eventEmitters.size === 0) {
16 this.dirWatchers.delete(this.watchPath);
17 }
18 }
19}
20class WatchManager extends events_1.EventEmitter {
21 constructor() {
22 super(...arguments);
23 this.dirWatchers = new Map();
24 this.lastWatcherId = 0;
25 }
26 registerWatcher(watchPath, dirList, callback) {
27 let dirWatcher = this.dirWatchers.get(watchPath);
28 if (!dirWatcher) {
29 dirWatcher = { eventEmitters: new Map(), dirEntries: dirList };
30 this.dirWatchers.set(watchPath, dirWatcher);
31 }
32 const watcherId = this.lastWatcherId++;
33 const watchEventEmitter = new WatchEventEmitter(this.dirWatchers, watchPath, watcherId);
34 dirWatcher.eventEmitters.set(watcherId, watchEventEmitter);
35 watchEventEmitter.on(`rename`, (filename) => callback(`rename`, filename));
36 return watchEventEmitter;
37 }
38 notifyWatchers(resolvePath) {
39 for (const [watchPath, dirWatcher] of this.dirWatchers) {
40 const newDirEntries = resolvePath(watchPath).dirList || new Set();
41 // Difference between new and old directory contents
42 const dirEntryDiff = new Set();
43 for (const entry of newDirEntries) {
44 if (!dirWatcher.dirEntries.has(entry)) {
45 dirEntryDiff.add(entry);
46 }
47 }
48 for (const entry of dirWatcher.dirEntries) {
49 if (!newDirEntries.has(entry)) {
50 dirEntryDiff.add(entry);
51 }
52 }
53 for (const entry of dirEntryDiff) {
54 for (const watchEventEmitter of dirWatcher.eventEmitters.values()) {
55 watchEventEmitter.emit(`rename`, entry);
56 }
57 }
58 dirWatcher.dirEntries = newDirEntries;
59 }
60 }
61}
62exports.WatchManager = WatchManager;