@yarnpkg/pnpify
Version:
63 lines (62 loc) • 2.42 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.WatchManager = void 0;
const events_1 = require("events");
class WatchEventEmitter extends events_1.EventEmitter {
constructor(dirWatchers, watchPath, watcherId) {
super();
this.dirWatchers = dirWatchers;
this.watchPath = watchPath;
this.watcherId = watcherId;
}
close() {
const dirWatcher = this.dirWatchers.get(this.watchPath);
dirWatcher.eventEmitters.delete(this.watcherId);
if (dirWatcher.eventEmitters.size === 0) {
this.dirWatchers.delete(this.watchPath);
}
}
}
class WatchManager extends events_1.EventEmitter {
constructor() {
super(...arguments);
this.dirWatchers = new Map();
this.lastWatcherId = 0;
}
registerWatcher(watchPath, dirList, callback) {
let dirWatcher = this.dirWatchers.get(watchPath);
if (!dirWatcher) {
dirWatcher = { eventEmitters: new Map(), dirEntries: dirList };
this.dirWatchers.set(watchPath, dirWatcher);
}
const watcherId = this.lastWatcherId++;
const watchEventEmitter = new WatchEventEmitter(this.dirWatchers, watchPath, watcherId);
dirWatcher.eventEmitters.set(watcherId, watchEventEmitter);
watchEventEmitter.on(`rename`, (filename) => callback(`rename`, filename));
return watchEventEmitter;
}
notifyWatchers(resolvePath) {
for (const [watchPath, dirWatcher] of this.dirWatchers) {
const newDirEntries = resolvePath(watchPath).dirList || new Set();
// Difference between new and old directory contents
const dirEntryDiff = new Set();
for (const entry of newDirEntries) {
if (!dirWatcher.dirEntries.has(entry)) {
dirEntryDiff.add(entry);
}
}
for (const entry of dirWatcher.dirEntries) {
if (!newDirEntries.has(entry)) {
dirEntryDiff.add(entry);
}
}
for (const entry of dirEntryDiff) {
for (const watchEventEmitter of dirWatcher.eventEmitters.values()) {
watchEventEmitter.emit(`rename`, entry);
}
}
dirWatcher.dirEntries = newDirEntries;
}
}
}
exports.WatchManager = WatchManager;
;