run npm install to generate a package lock

This commit is contained in:
sashinexists
2024-12-07 13:18:31 +11:00
parent e7d08a91b5
commit 23437d228e
2501 changed files with 290663 additions and 0 deletions

10
node_modules/watcher/.editorconfig generated vendored Normal file
View File

@@ -0,0 +1,10 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true

27
node_modules/watcher/.github/workflows/node.js.yml generated vendored Normal file
View File

@@ -0,0 +1,27 @@
name: Test
on:
push:
branches: ["master"]
pull_request:
branches: ["master"]
jobs:
test:
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [16.x, 18.x]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm run clean
- run: npm run compile
- run: npm run test

52
node_modules/watcher/changelog.md generated vendored Normal file
View File

@@ -0,0 +1,52 @@
### Version 2.3.1
- Readme: updated with new Node recursive developments (#37)
- Updated some dependencies
### Version 2.3.0
- Replaced ripstat with stubborn-fs directly, for simplicity
### Version 2.2.2
- Updated "dettle", to ensure debounce delays of 0 are handled properly
### Version 2.2.1
- Replaced "debounce" with "dettle"
### Version 2.2.0
- Added support for ignoring paths with a regex
### Version 2.1.0
- Readme: added a mention about a high renameTimeout value
- Updated dependencies
- Exposed the "limit" option from "tiny-readdir"
- Ensuring relative paths can be watched too
- CI: ignoring Node v14
- Added support for detecting case-sensitive renames in case-insensitive filesystems
### Version 2.0.0
- Added 4 more tests regarding empty directories
- Added a test using "touch" specifically
- Added a GH CI workflow
- Updated test workflow
- Fixed an issue where not all internal watchers were being disposed of on close
- Switched to ESM
### Version 1.2.0
- Added support for passing a readdir map, in order to potentially deduplicate away the potential initial scan the library needs
### Version 1.1.2
- Deleted repo-level github funding.yml
- Using "ripstat" for retrieving stats objects faster
### Version 1.1.1
- Aborting directories scans immediately when closing the watcher
- Ensuring the thread doesnt get clogged during recursive directory scanning
### Version 1.1.0
- Node v12 is the minimum version supported
- Storing stripped-down stats objects in 50+% less memory
- Handling change events more reliably
- Ensuring the "depth" option is handled properly when native recursion is unavailable
- New option: "native", it allows for disabling the native recursive watcher
### Version 1.0.0
- Initial commit

13
node_modules/watcher/dist/constants.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
/// <reference types="node" />
declare const DEBOUNCE = 300;
declare const DEPTH = 20;
declare const LIMIT = 10000000;
declare const PLATFORM: NodeJS.Platform;
declare const IS_LINUX: boolean;
declare const IS_MAC: boolean;
declare const IS_WINDOWS: boolean;
declare const HAS_NATIVE_RECURSION: boolean;
declare const POLLING_INTERVAL = 3000;
declare const POLLING_TIMEOUT = 20000;
declare const RENAME_TIMEOUT = 1250;
export { DEBOUNCE, DEPTH, LIMIT, HAS_NATIVE_RECURSION, IS_LINUX, IS_MAC, IS_WINDOWS, PLATFORM, POLLING_INTERVAL, POLLING_TIMEOUT, RENAME_TIMEOUT };

16
node_modules/watcher/dist/constants.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
/* IMPORT */
import os from 'node:os';
/* MAIN */
const DEBOUNCE = 300;
const DEPTH = 20;
const LIMIT = 10000000;
const PLATFORM = os.platform();
const IS_LINUX = (PLATFORM === 'linux');
const IS_MAC = (PLATFORM === 'darwin');
const IS_WINDOWS = (PLATFORM === 'win32');
const HAS_NATIVE_RECURSION = IS_MAC || IS_WINDOWS;
const POLLING_INTERVAL = 3000;
const POLLING_TIMEOUT = 20000;
const RENAME_TIMEOUT = 1250;
/* EXPORT */
export { DEBOUNCE, DEPTH, LIMIT, HAS_NATIVE_RECURSION, IS_LINUX, IS_MAC, IS_WINDOWS, PLATFORM, POLLING_INTERVAL, POLLING_TIMEOUT, RENAME_TIMEOUT };

28
node_modules/watcher/dist/enums.d.ts generated vendored Normal file
View File

@@ -0,0 +1,28 @@
declare const enum FileType {
DIR = 1,
FILE = 2
}
declare const enum FSTargetEvent {
CHANGE = "change",
RENAME = "rename"
}
declare const enum FSWatcherEvent {
CHANGE = "change",
ERROR = "error"
}
declare const enum TargetEvent {
ADD = "add",
ADD_DIR = "addDir",
CHANGE = "change",
RENAME = "rename",
RENAME_DIR = "renameDir",
UNLINK = "unlink",
UNLINK_DIR = "unlinkDir"
}
declare const enum WatcherEvent {
ALL = "all",
CLOSE = "close",
ERROR = "error",
READY = "ready"
}
export { FileType, FSTargetEvent, FSWatcherEvent, TargetEvent, WatcherEvent };

35
node_modules/watcher/dist/enums.js generated vendored Normal file
View File

@@ -0,0 +1,35 @@
/* MAIN */
var FileType;
(function (FileType) {
FileType[FileType["DIR"] = 1] = "DIR";
FileType[FileType["FILE"] = 2] = "FILE";
})(FileType || (FileType = {}));
var FSTargetEvent;
(function (FSTargetEvent) {
FSTargetEvent["CHANGE"] = "change";
FSTargetEvent["RENAME"] = "rename";
})(FSTargetEvent || (FSTargetEvent = {}));
var FSWatcherEvent;
(function (FSWatcherEvent) {
FSWatcherEvent["CHANGE"] = "change";
FSWatcherEvent["ERROR"] = "error";
})(FSWatcherEvent || (FSWatcherEvent = {}));
var TargetEvent;
(function (TargetEvent) {
TargetEvent["ADD"] = "add";
TargetEvent["ADD_DIR"] = "addDir";
TargetEvent["CHANGE"] = "change";
TargetEvent["RENAME"] = "rename";
TargetEvent["RENAME_DIR"] = "renameDir";
TargetEvent["UNLINK"] = "unlink";
TargetEvent["UNLINK_DIR"] = "unlinkDir";
})(TargetEvent || (TargetEvent = {}));
var WatcherEvent;
(function (WatcherEvent) {
WatcherEvent["ALL"] = "all";
WatcherEvent["CLOSE"] = "close";
WatcherEvent["ERROR"] = "error";
WatcherEvent["READY"] = "ready";
})(WatcherEvent || (WatcherEvent = {}));
/* EXPORT */
export { FileType, FSTargetEvent, FSWatcherEvent, TargetEvent, WatcherEvent };

10
node_modules/watcher/dist/lazy_map_set.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
declare class LazyMapSet<K, V> {
private map;
clear(): void;
delete(key: K, value?: V): boolean;
find(key: K, iterator: (value: V) => boolean): V | undefined;
get(key: K): Set<V> | V | undefined;
has(key: K, value?: V): boolean;
set(key: K, value: V): this;
}
export default LazyMapSet;

81
node_modules/watcher/dist/lazy_map_set.js generated vendored Normal file
View File

@@ -0,0 +1,81 @@
/* IMPORT */
import Utils from './utils.js';
/* MAIN */
//TODO: Maybe publish this as a standalone module
class LazyMapSet {
constructor() {
/* VARIABLES */
this.map = new Map();
}
/* API */
clear() {
this.map.clear();
}
delete(key, value) {
if (Utils.lang.isUndefined(value)) {
return this.map.delete(key);
}
else if (this.map.has(key)) {
const values = this.map.get(key);
if (Utils.lang.isSet(values)) {
const deleted = values.delete(value);
if (!values.size) {
this.map.delete(key);
}
return deleted;
}
else if (values === value) {
this.map.delete(key);
return true;
}
}
return false;
}
find(key, iterator) {
if (this.map.has(key)) {
const values = this.map.get(key);
if (Utils.lang.isSet(values)) {
return Array.from(values).find(iterator);
}
else if (iterator(values)) { //TSC
return values;
}
}
return undefined;
}
get(key) {
return this.map.get(key);
}
has(key, value) {
if (Utils.lang.isUndefined(value)) {
return this.map.has(key);
}
else if (this.map.has(key)) {
const values = this.map.get(key);
if (Utils.lang.isSet(values)) {
return values.has(value);
}
else {
return (values === value);
}
}
return false;
}
set(key, value) {
if (this.map.has(key)) {
const values = this.map.get(key);
if (Utils.lang.isSet(values)) {
values.add(value);
}
else if (values !== value) {
this.map.set(key, new Set([values, value])); //TSC
}
}
else {
this.map.set(key, value);
}
return this;
}
}
/* EXPORT */
export default LazyMapSet;

64
node_modules/watcher/dist/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,64 @@
/// <reference types="node" />
import type { FSWatcher, BigIntStats } from 'node:fs';
import type { ResultDirectories } from 'tiny-readdir';
import type { FSTargetEvent, TargetEvent } from './enums';
import type WatcherStats from './watcher_stats';
type Callback = () => void;
type Disposer = () => void;
type Event = [TargetEvent, Path, Path?];
type FSHandler = (event?: FSTargetEvent, targetName?: string) => void;
type Handler = (event: TargetEvent, targetPath: Path, targetPathNext?: Path) => void;
type HandlerBatched = (event?: FSTargetEvent, targetPath?: Path, isInitial?: boolean) => Promise<void>;
type Ignore = ((targetPath: Path) => boolean) | RegExp;
type INO = bigint | number;
type Path = string;
type ReaddirMap = ResultDirectories;
type Stats = BigIntStats;
type LocksAdd = Map<INO, () => void>;
type LocksUnlink = Map<INO, () => Path>;
type LocksPair = {
add: LocksAdd;
unlink: LocksUnlink;
};
type LockConfig = {
ino?: INO;
targetPath: Path;
locks: LocksPair;
events: {
add: TargetEvent.ADD | TargetEvent.ADD_DIR;
change?: TargetEvent.CHANGE;
rename: TargetEvent.RENAME | TargetEvent.RENAME_DIR;
unlink: TargetEvent.UNLINK | TargetEvent.UNLINK_DIR;
};
};
type PollerConfig = {
options: WatcherOptions;
targetPath: Path;
};
type SubwatcherConfig = {
options: WatcherOptions;
targetPath: Path;
};
type WatcherConfig = {
handler: Handler;
watcher: FSWatcher;
options: WatcherOptions;
folderPath: Path;
filePath?: Path;
};
type WatcherOptions = {
debounce?: number;
depth?: number;
limit?: number;
ignore?: Ignore;
ignoreInitial?: boolean;
native?: boolean;
persistent?: boolean;
pollingInterval?: number;
pollingTimeout?: number;
readdirMap?: ReaddirMap;
recursive?: boolean;
renameDetection?: boolean;
renameTimeout?: number;
};
export type { Callback, Disposer, Event, FSHandler, FSWatcher, Handler, HandlerBatched, Ignore, INO, Path, ReaddirMap, Stats, LocksAdd, LocksUnlink, LocksPair, LockConfig, PollerConfig, SubwatcherConfig, WatcherConfig, WatcherOptions, WatcherStats };

2
node_modules/watcher/dist/types.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
/* IMPORT */
export {};

37
node_modules/watcher/dist/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1,37 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import type { Callback, Ignore, ReaddirMap, Stats } from './types';
declare const Utils: {
lang: {
debounce: <Args extends unknown[]>(fn: import("dettle/dist/types").FN<Args, unknown>, wait?: number | undefined, options?: import("dettle/dist/types").DebounceOptions | undefined) => import("dettle/dist/types").Debounced<Args>;
attempt: <T>(fn: () => T) => T | Error;
castArray: <T_1>(x: T_1 | T_1[]) => T_1[];
castError: (exception: unknown) => Error;
defer: (callback: Callback) => NodeJS.Timeout;
isArray: (value: unknown) => value is unknown[];
isError: (value: unknown) => value is Error;
isFunction: (value: unknown) => value is Function;
isNaN: (value: unknown) => value is number;
isNumber: (value: unknown) => value is number;
isPrimitive: (value: unknown) => value is string | number | bigint | boolean | symbol | null | undefined;
isShallowEqual: (x: any, y: any) => boolean;
isSet: (value: unknown) => value is Set<unknown>;
isString: (value: unknown) => value is string;
isUndefined: (value: unknown) => value is undefined;
noop: () => undefined;
uniq: <T_2>(arr: T_2[]) => T_2[];
};
fs: {
getDepth: (targetPath: string) => number;
getRealPath: (targetPath: string, native?: boolean) => string | undefined;
isSubPath: (targetPath: string, subPath: string) => boolean;
poll: (targetPath: string, timeout?: number) => Promise<Stats | undefined>;
readdir: (rootPath: string, ignore?: Ignore, depth?: number, limit?: number, signal?: {
aborted: boolean;
}, readdirMap?: ReaddirMap) => Promise<[string[], string[]]>;
};
};
export default Utils;

120
node_modules/watcher/dist/utils.js generated vendored Normal file
View File

@@ -0,0 +1,120 @@
/* IMPORT */
import { debounce } from 'dettle';
import fs from 'node:fs';
import path from 'node:path';
import sfs from 'stubborn-fs';
import readdir from 'tiny-readdir';
import { POLLING_TIMEOUT } from './constants.js';
/* MAIN */
const Utils = {
/* LANG API */
lang: {
debounce,
attempt: (fn) => {
try {
return fn();
}
catch (error) {
return Utils.lang.castError(error);
}
},
castArray: (x) => {
return Utils.lang.isArray(x) ? x : [x];
},
castError: (exception) => {
if (Utils.lang.isError(exception))
return exception;
if (Utils.lang.isString(exception))
return new Error(exception);
return new Error('Unknown error');
},
defer: (callback) => {
return setTimeout(callback, 0);
},
isArray: (value) => {
return Array.isArray(value);
},
isError: (value) => {
return value instanceof Error;
},
isFunction: (value) => {
return typeof value === 'function';
},
isNaN: (value) => {
return Number.isNaN(value);
},
isNumber: (value) => {
return typeof value === 'number';
},
isPrimitive: (value) => {
if (value === null)
return true;
const type = typeof value;
return type !== 'object' && type !== 'function';
},
isShallowEqual: (x, y) => {
if (x === y)
return true;
if (Utils.lang.isNaN(x))
return Utils.lang.isNaN(y);
if (Utils.lang.isPrimitive(x) || Utils.lang.isPrimitive(y))
return x === y;
for (const i in x)
if (!(i in y))
return false;
for (const i in y)
if (x[i] !== y[i])
return false;
return true;
},
isSet: (value) => {
return value instanceof Set;
},
isString: (value) => {
return typeof value === 'string';
},
isUndefined: (value) => {
return value === undefined;
},
noop: () => {
return;
},
uniq: (arr) => {
if (arr.length < 2)
return arr;
return Array.from(new Set(arr));
}
},
/* FS API */
fs: {
getDepth: (targetPath) => {
return Math.max(0, targetPath.split(path.sep).length - 1);
},
getRealPath: (targetPath, native) => {
try {
return native ? fs.realpathSync.native(targetPath) : fs.realpathSync(targetPath);
}
catch {
return;
}
},
isSubPath: (targetPath, subPath) => {
return (subPath.startsWith(targetPath) && subPath[targetPath.length] === path.sep && (subPath.length - targetPath.length) > path.sep.length);
},
poll: (targetPath, timeout = POLLING_TIMEOUT) => {
return sfs.retry.stat(timeout)(targetPath, { bigint: true }).catch(Utils.lang.noop);
},
readdir: async (rootPath, ignore, depth = Infinity, limit = Infinity, signal, readdirMap) => {
if (readdirMap && depth === 1 && rootPath in readdirMap) { // Reusing cached data
const result = readdirMap[rootPath];
return [result.directories, result.files];
}
else { // Retrieving fresh data
const result = await readdir(rootPath, { depth, limit, ignore, signal });
return [result.directories, result.files];
}
}
}
};
/* EXPORT */
export default Utils;

55
node_modules/watcher/dist/watcher.d.ts generated vendored Normal file
View File

@@ -0,0 +1,55 @@
/// <reference types="node" />
/// <reference types="node" />
import { EventEmitter } from 'node:events';
import { TargetEvent } from './enums';
import WatcherHandler from './watcher_handler';
import WatcherLocker from './watcher_locker';
import WatcherPoller from './watcher_poller';
import type { Callback, Disposer, Handler, Ignore, Path, PollerConfig, SubwatcherConfig, WatcherOptions, WatcherConfig } from './types';
declare class Watcher extends EventEmitter {
_closed: boolean;
_ready: boolean;
_closeAborter: AbortController;
_closeSignal: {
aborted: boolean;
};
_closeWait: Promise<void>;
_readyWait: Promise<void>;
_locker: WatcherLocker;
_roots: Set<Path>;
_poller: WatcherPoller;
_pollers: Set<PollerConfig>;
_subwatchers: Set<SubwatcherConfig>;
_watchers: Record<Path, WatcherConfig[]>;
_watchersLock: Promise<void>;
_watchersRestorable: Record<Path, WatcherConfig>;
_watchersRestoreTimeout?: NodeJS.Timeout;
constructor(target?: Path[] | Path | Handler, options?: WatcherOptions | Handler, handler?: Handler);
isClosed(): boolean;
isIgnored(targetPath: Path, ignore?: Ignore): boolean;
isReady(): boolean;
close(): boolean;
error(exception: unknown): boolean;
event(event: TargetEvent, targetPath: Path, targetPathNext?: Path): boolean;
ready(): boolean;
pollerExists(targetPath: Path, options: WatcherOptions): boolean;
subwatcherExists(targetPath: Path, options: WatcherOptions): boolean;
watchersClose(folderPath?: Path, filePath?: Path, recursive?: boolean): void;
watchersLock(callback: Callback): Promise<void>;
watchersRestore(): void;
watcherAdd(config: WatcherConfig, baseWatcherHandler?: WatcherHandler): Promise<WatcherHandler>;
watcherClose(config: WatcherConfig): void;
watcherExists(folderPath: Path, options: WatcherOptions, handler: Handler, filePath?: Path): boolean;
watchDirectories(foldersPaths: Path[], options: WatcherOptions, handler: Handler, filePath?: Path, baseWatcherHandler?: WatcherHandler): Promise<WatcherHandler | undefined>;
watchDirectory(folderPath: Path, options: WatcherOptions, handler: Handler, filePath?: Path, baseWatcherHandler?: WatcherHandler): Promise<void>;
watchFileOnce(filePath: Path, options: WatcherOptions, callback: Callback): Promise<void>;
watchFile(filePath: Path, options: WatcherOptions, handler: Handler): Promise<void>;
watchPollingOnce(targetPath: Path, options: WatcherOptions, callback: Callback): Promise<void>;
watchPolling(targetPath: Path, options: WatcherOptions, callback: Callback): Promise<Disposer>;
watchUnknownChild(targetPath: Path, options: WatcherOptions, handler: Handler): Promise<void>;
watchUnknownTarget(targetPath: Path, options: WatcherOptions, handler: Handler): Promise<void>;
watchPaths(targetPaths: Path[], options: WatcherOptions, handler: Handler): Promise<void>;
watchPath(targetPath: Path, options: WatcherOptions, handler: Handler): Promise<void>;
watch(target?: Path[] | Path | Handler, options?: WatcherOptions | Handler, handler?: Handler): Promise<void>;
}
export default Watcher;

396
node_modules/watcher/dist/watcher.js generated vendored Normal file
View File

@@ -0,0 +1,396 @@
/* IMPORT */
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import path from 'node:path';
import { DEPTH, LIMIT, HAS_NATIVE_RECURSION, POLLING_INTERVAL } from './constants.js';
import { TargetEvent, WatcherEvent } from './enums.js';
import Utils from './utils.js';
import WatcherHandler from './watcher_handler.js';
import WatcherLocker from './watcher_locker.js';
import WatcherPoller from './watcher_poller.js';
/* MAIN */
class Watcher extends EventEmitter {
/* CONSTRUCTOR */
constructor(target, options, handler) {
super();
this._closed = false;
this._ready = false;
this._closeAborter = new AbortController();
this._closeSignal = this._closeAborter.signal;
this.on(WatcherEvent.CLOSE, () => this._closeAborter.abort());
this._closeWait = new Promise(resolve => this.on(WatcherEvent.CLOSE, resolve));
this._readyWait = new Promise(resolve => this.on(WatcherEvent.READY, resolve));
this._locker = new WatcherLocker(this);
this._roots = new Set();
this._poller = new WatcherPoller();
this._pollers = new Set();
this._subwatchers = new Set();
this._watchers = {};
this._watchersLock = Promise.resolve();
this._watchersRestorable = {};
this.watch(target, options, handler);
}
/* API */
isClosed() {
return this._closed;
}
isIgnored(targetPath, ignore) {
return !!ignore && (Utils.lang.isFunction(ignore) ? !!ignore(targetPath) : ignore.test(targetPath));
}
isReady() {
return this._ready;
}
close() {
this._locker.reset();
this._poller.reset();
this._roots.clear();
this.watchersClose();
if (this.isClosed())
return false;
this._closed = true;
return this.emit(WatcherEvent.CLOSE);
}
error(exception) {
if (this.isClosed())
return false;
const error = Utils.lang.castError(exception);
return this.emit(WatcherEvent.ERROR, error);
}
event(event, targetPath, targetPathNext) {
if (this.isClosed())
return false;
this.emit(WatcherEvent.ALL, event, targetPath, targetPathNext);
return this.emit(event, targetPath, targetPathNext);
}
ready() {
if (this.isClosed() || this.isReady())
return false;
this._ready = true;
return this.emit(WatcherEvent.READY);
}
pollerExists(targetPath, options) {
for (const poller of this._pollers) {
if (poller.targetPath !== targetPath)
continue;
if (!Utils.lang.isShallowEqual(poller.options, options))
continue;
return true;
}
return false;
}
subwatcherExists(targetPath, options) {
for (const subwatcher of this._subwatchers) {
if (subwatcher.targetPath !== targetPath)
continue;
if (!Utils.lang.isShallowEqual(subwatcher.options, options))
continue;
return true;
}
return false;
}
watchersClose(folderPath, filePath, recursive = true) {
if (!folderPath) {
for (const folderPath in this._watchers) {
this.watchersClose(folderPath, filePath, false);
}
}
else {
const configs = this._watchers[folderPath];
if (configs) {
for (const config of [...configs]) { // It's important to clone the array, as items will be deleted from it also
if (filePath && config.filePath !== filePath)
continue;
this.watcherClose(config);
}
}
if (recursive) {
for (const folderPathOther in this._watchers) {
if (!Utils.fs.isSubPath(folderPath, folderPathOther))
continue;
this.watchersClose(folderPathOther, filePath, false);
}
}
}
}
watchersLock(callback) {
return this._watchersLock.then(() => {
return this._watchersLock = new Promise(async (resolve) => {
await callback();
resolve();
});
});
}
watchersRestore() {
delete this._watchersRestoreTimeout;
const watchers = Object.entries(this._watchersRestorable);
this._watchersRestorable = {};
for (const [targetPath, config] of watchers) {
this.watchPath(targetPath, config.options, config.handler);
}
}
async watcherAdd(config, baseWatcherHandler) {
const { folderPath } = config;
const configs = this._watchers[folderPath] = (this._watchers[folderPath] || []);
configs.push(config);
const watcherHandler = new WatcherHandler(this, config, baseWatcherHandler);
await watcherHandler.init();
return watcherHandler;
}
watcherClose(config) {
config.watcher.close();
const configs = this._watchers[config.folderPath];
if (configs) {
const index = configs.indexOf(config);
configs.splice(index, 1);
if (!configs.length) {
delete this._watchers[config.folderPath];
}
}
const rootPath = config.filePath || config.folderPath;
const isRoot = this._roots.has(rootPath);
if (isRoot) {
this._watchersRestorable[rootPath] = config;
if (!this._watchersRestoreTimeout) {
this._watchersRestoreTimeout = Utils.lang.defer(() => this.watchersRestore());
}
}
}
watcherExists(folderPath, options, handler, filePath) {
const configsSibling = this._watchers[folderPath];
if (!!configsSibling?.find(config => config.handler === handler && (!config.filePath || config.filePath === filePath) && config.options.ignore === options.ignore && !!config.options.native === !!options.native && (!options.recursive || config.options.recursive)))
return true;
let folderAncestorPath = path.dirname(folderPath);
for (let depth = 1; depth < Infinity; depth++) {
const configsAncestor = this._watchers[folderAncestorPath];
if (!!configsAncestor?.find(config => (depth === 1 || (config.options.recursive && depth <= (config.options.depth ?? DEPTH))) && config.handler === handler && (!config.filePath || config.filePath === filePath) && config.options.ignore === options.ignore && !!config.options.native === !!options.native && (!options.recursive || (config.options.recursive && (HAS_NATIVE_RECURSION && config.options.native !== false)))))
return true;
if (!HAS_NATIVE_RECURSION)
break; // No other ancestor will possibly be found
const folderAncestorPathNext = path.dirname(folderPath);
if (folderAncestorPath === folderAncestorPathNext)
break;
folderAncestorPath = folderAncestorPathNext;
}
return false;
}
async watchDirectories(foldersPaths, options, handler, filePath, baseWatcherHandler) {
if (this.isClosed())
return;
foldersPaths = Utils.lang.uniq(foldersPaths).sort();
let watcherHandlerLast;
for (const folderPath of foldersPaths) {
if (this.isIgnored(folderPath, options.ignore))
continue;
if (this.watcherExists(folderPath, options, handler, filePath))
continue;
try {
const watcherOptions = (!options.recursive || (HAS_NATIVE_RECURSION && options.native !== false)) ? options : { ...options, recursive: false }; // Ensuring recursion is explicitly disabled if not available
const watcher = fs.watch(folderPath, watcherOptions);
const watcherConfig = { watcher, handler, options, folderPath, filePath };
const watcherHandler = watcherHandlerLast = await this.watcherAdd(watcherConfig, baseWatcherHandler);
const isRoot = this._roots.has(filePath || folderPath);
if (isRoot) {
const parentOptions = { ...options, ignoreInitial: true, recursive: false }; // Ensuring only the parent folder is being watched
const parentFolderPath = path.dirname(folderPath);
const parentFilePath = folderPath;
await this.watchDirectories([parentFolderPath], parentOptions, handler, parentFilePath, watcherHandler);
//TODO: Watch parents recursively with the following code, which requires other things to be changed too though
// while ( true ) {
// await this.watchDirectories ( [parentFolderPath], parentOptions, handler, parentFilePath, watcherHandler );
// const parentFolderPathNext = path.dirname ( parentFolderPath );
// if ( parentFolderPath === parentFolderPathNext ) break;
// parentFilePath = parentFolderPath;
// parentFolderPath = parentFolderPathNext;
// }
}
}
catch (error) {
this.error(error);
}
}
return watcherHandlerLast;
}
async watchDirectory(folderPath, options, handler, filePath, baseWatcherHandler) {
if (this.isClosed())
return;
if (this.isIgnored(folderPath, options.ignore))
return;
if (!options.recursive || (HAS_NATIVE_RECURSION && options.native !== false)) {
return this.watchersLock(() => {
return this.watchDirectories([folderPath], options, handler, filePath, baseWatcherHandler);
});
}
else {
options = { ...options, recursive: true }; // Ensuring recursion is explicitly enabled
const depth = options.depth ?? DEPTH;
const limit = options.limit ?? LIMIT;
const [folderSubPaths] = await Utils.fs.readdir(folderPath, options.ignore, depth, limit, this._closeSignal, options.readdirMap);
return this.watchersLock(async () => {
const watcherHandler = await this.watchDirectories([folderPath], options, handler, filePath, baseWatcherHandler);
if (folderSubPaths.length) {
const folderPathDepth = Utils.fs.getDepth(folderPath);
for (const folderSubPath of folderSubPaths) {
const folderSubPathDepth = Utils.fs.getDepth(folderSubPath);
const subDepth = Math.max(0, depth - (folderSubPathDepth - folderPathDepth));
const subOptions = { ...options, depth: subDepth }; // Updating the maximum depth to account for depth of the sub path
await this.watchDirectories([folderSubPath], subOptions, handler, filePath, baseWatcherHandler || watcherHandler);
}
}
});
}
}
async watchFileOnce(filePath, options, callback) {
if (this.isClosed())
return;
options = { ...options, ignoreInitial: false }; // Ensuring initial events are detected too
if (this.subwatcherExists(filePath, options))
return;
const config = { targetPath: filePath, options };
const handler = (event, targetPath) => {
if (targetPath !== filePath)
return;
stop();
callback();
};
const watcher = new Watcher(handler);
const start = () => {
this._subwatchers.add(config);
this.on(WatcherEvent.CLOSE, stop); // Ensuring the subwatcher is stopped on close
watcher.watchFile(filePath, options, handler);
};
const stop = () => {
this._subwatchers.delete(config);
this.removeListener(WatcherEvent.CLOSE, stop); // Ensuring there are no leftover listeners
watcher.close();
};
return start();
}
async watchFile(filePath, options, handler) {
if (this.isClosed())
return;
if (this.isIgnored(filePath, options.ignore))
return;
options = { ...options, recursive: false }; // Ensuring recursion is explicitly disabled
const folderPath = path.dirname(filePath);
return this.watchDirectory(folderPath, options, handler, filePath);
}
async watchPollingOnce(targetPath, options, callback) {
if (this.isClosed())
return;
let isDone = false;
const poller = new WatcherPoller();
const disposer = await this.watchPolling(targetPath, options, async () => {
if (isDone)
return;
const events = await poller.update(targetPath, options.pollingTimeout);
if (!events.length)
return; // Nothing actually changed, skipping
if (isDone)
return; // Another async callback has done the work already, skipping
isDone = true;
disposer();
callback();
});
}
async watchPolling(targetPath, options, callback) {
if (this.isClosed())
return Utils.lang.noop;
if (this.pollerExists(targetPath, options))
return Utils.lang.noop;
const watcherOptions = { ...options, interval: options.pollingInterval ?? POLLING_INTERVAL }; // Ensuring a default interval is set
const config = { targetPath, options };
const start = () => {
this._pollers.add(config);
this.on(WatcherEvent.CLOSE, stop); // Ensuring polling is stopped on close
fs.watchFile(targetPath, watcherOptions, callback);
};
const stop = () => {
this._pollers.delete(config);
this.removeListener(WatcherEvent.CLOSE, stop); // Ensuring there are no leftover listeners
fs.unwatchFile(targetPath, callback);
};
Utils.lang.attempt(start);
return () => Utils.lang.attempt(stop);
}
async watchUnknownChild(targetPath, options, handler) {
if (this.isClosed())
return;
const watch = () => this.watchPath(targetPath, options, handler);
return this.watchFileOnce(targetPath, options, watch);
}
async watchUnknownTarget(targetPath, options, handler) {
if (this.isClosed())
return;
const watch = () => this.watchPath(targetPath, options, handler);
return this.watchPollingOnce(targetPath, options, watch);
}
async watchPaths(targetPaths, options, handler) {
if (this.isClosed())
return;
targetPaths = Utils.lang.uniq(targetPaths).sort();
const isParallelizable = targetPaths.every((targetPath, index) => targetPaths.every((t, i) => i === index || !Utils.fs.isSubPath(targetPath, t))); // All paths are about separate subtrees, so we can start watching in parallel safely //TODO: Find parallelizable chunks rather than using an all or nothing approach
if (isParallelizable) { // Watching in parallel
await Promise.all(targetPaths.map(targetPath => {
return this.watchPath(targetPath, options, handler);
}));
}
else { // Watching serially
for (const targetPath of targetPaths) {
await this.watchPath(targetPath, options, handler);
}
}
}
async watchPath(targetPath, options, handler) {
if (this.isClosed())
return;
targetPath = path.resolve(targetPath);
if (this.isIgnored(targetPath, options.ignore))
return;
const stats = await Utils.fs.poll(targetPath, options.pollingTimeout);
if (!stats) {
const parentPath = path.dirname(targetPath);
const parentStats = await Utils.fs.poll(parentPath, options.pollingTimeout);
if (parentStats?.isDirectory()) {
return this.watchUnknownChild(targetPath, options, handler);
}
else {
return this.watchUnknownTarget(targetPath, options, handler);
}
}
else if (stats.isFile()) {
return this.watchFile(targetPath, options, handler);
}
else if (stats.isDirectory()) {
return this.watchDirectory(targetPath, options, handler);
}
else {
this.error(`"${targetPath}" is not supported`);
}
}
async watch(target, options, handler = Utils.lang.noop) {
if (Utils.lang.isFunction(target))
return this.watch([], {}, target);
if (Utils.lang.isUndefined(target))
return this.watch([], options, handler);
if (Utils.lang.isFunction(options))
return this.watch(target, {}, options);
if (Utils.lang.isUndefined(options))
return this.watch(target, {}, handler);
if (this.isClosed())
return;
if (this.isReady())
options.readdirMap = undefined; // Only usable before initialization
const targetPaths = Utils.lang.castArray(target);
targetPaths.forEach(targetPath => this._roots.add(targetPath));
await this.watchPaths(targetPaths, options, handler);
if (this.isClosed())
return;
if (handler !== Utils.lang.noop) {
this.on(WatcherEvent.ALL, handler);
}
options.readdirMap = undefined; // Only usable before initialization
this.ready();
}
}
/* EXPORT */
export default Watcher;

36
node_modules/watcher/dist/watcher_handler.d.ts generated vendored Normal file
View File

@@ -0,0 +1,36 @@
/// <reference types="node" />
/// <reference types="node" />
import { FSTargetEvent } from './enums';
import type Watcher from './watcher';
import type { Event, FSWatcher, Handler, HandlerBatched, Path, WatcherOptions, WatcherConfig } from './types';
declare class WatcherHandler {
base?: WatcherHandler;
watcher: Watcher;
handler: Handler;
handlerBatched: HandlerBatched;
fswatcher: FSWatcher;
options: WatcherOptions;
folderPath: Path;
filePath?: Path;
constructor(watcher: Watcher, config: WatcherConfig, base?: WatcherHandler);
_isSubRoot(targetPath: Path): boolean;
_makeHandlerBatched(delay?: number): (event: FSTargetEvent, targetPath?: Path, isInitial?: boolean) => Promise<void>;
eventsDeduplicate(events: Event[]): Event[];
eventsPopulate(targetPaths: Path[], events?: Event[], isInitial?: boolean): Promise<Event[]>;
eventsPopulateAddDir(targetPaths: Path[], targetPath: Path, events?: Event[], isInitial?: boolean): Promise<Event[]>;
eventsPopulateUnlinkDir(targetPaths: Path[], targetPath: Path, events?: Event[], isInitial?: boolean): Promise<Event[]>;
onTargetAdd(targetPath: Path): void;
onTargetAddDir(targetPath: Path): void;
onTargetChange(targetPath: Path): void;
onTargetUnlink(targetPath: Path): void;
onTargetUnlinkDir(targetPath: Path): void;
onTargetEvent(event: Event): void;
onTargetEvents(events: Event[]): void;
onWatcherEvent(event?: FSTargetEvent, targetPath?: Path, isInitial?: boolean): Promise<void>;
onWatcherChange(event?: FSTargetEvent, targetName?: string | null): void;
onWatcherError(error: NodeJS.ErrnoException): void;
init(): Promise<void>;
initWatcherEvents(): Promise<void>;
initInitialEvents(): Promise<void>;
}
export default WatcherHandler;

248
node_modules/watcher/dist/watcher_handler.js generated vendored Normal file
View File

@@ -0,0 +1,248 @@
/* IMPORT */
import path from 'node:path';
import { DEBOUNCE, DEPTH, LIMIT, HAS_NATIVE_RECURSION, IS_WINDOWS } from './constants.js';
import { FSTargetEvent, FSWatcherEvent, TargetEvent } from './enums.js';
import Utils from './utils.js';
/* MAIN */
class WatcherHandler {
/* CONSTRUCTOR */
constructor(watcher, config, base) {
this.base = base;
this.watcher = watcher;
this.handler = config.handler;
this.fswatcher = config.watcher;
this.options = config.options;
this.folderPath = config.folderPath;
this.filePath = config.filePath;
this.handlerBatched = this.base ? this.base.onWatcherEvent.bind(this.base) : this._makeHandlerBatched(this.options.debounce); //UGLY
}
/* HELPERS */
_isSubRoot(targetPath) {
if (this.filePath) {
return targetPath === this.filePath;
}
else {
return targetPath === this.folderPath || Utils.fs.isSubPath(this.folderPath, targetPath);
}
}
_makeHandlerBatched(delay = DEBOUNCE) {
return (() => {
let lock = this.watcher._readyWait; // ~Ensuring no two flushes are active in parallel, or before the watcher is ready
let initials = [];
let regulars = new Set();
const flush = async (initials, regulars) => {
const initialEvents = this.options.ignoreInitial ? [] : initials;
const regularEvents = await this.eventsPopulate([...regulars]);
const events = this.eventsDeduplicate([...initialEvents, ...regularEvents]);
this.onTargetEvents(events);
};
const flushDebounced = Utils.lang.debounce(() => {
if (this.watcher.isClosed())
return;
lock = flush(initials, regulars);
initials = [];
regulars = new Set();
}, delay);
return async (event, targetPath = '', isInitial = false) => {
if (isInitial) { // Poll immediately
await this.eventsPopulate([targetPath], initials, true);
}
else { // Poll later
regulars.add(targetPath);
}
lock.then(flushDebounced);
};
})();
}
/* EVENT HELPERS */
eventsDeduplicate(events) {
if (events.length < 2)
return events;
const targetsEventPrev = {};
return events.reduce((acc, event) => {
const [targetEvent, targetPath] = event;
const targetEventPrev = targetsEventPrev[targetPath];
if (targetEvent === targetEventPrev)
return acc; // Same event, ignoring
if (targetEvent === TargetEvent.CHANGE && targetEventPrev === TargetEvent.ADD)
return acc; // "change" after "add", ignoring
targetsEventPrev[targetPath] = targetEvent;
acc.push(event);
return acc;
}, []);
}
async eventsPopulate(targetPaths, events = [], isInitial = false) {
await Promise.all(targetPaths.map(async (targetPath) => {
const targetEvents = await this.watcher._poller.update(targetPath, this.options.pollingTimeout);
await Promise.all(targetEvents.map(async (event) => {
events.push([event, targetPath]);
if (event === TargetEvent.ADD_DIR) {
await this.eventsPopulateAddDir(targetPaths, targetPath, events, isInitial);
}
else if (event === TargetEvent.UNLINK_DIR) {
await this.eventsPopulateUnlinkDir(targetPaths, targetPath, events, isInitial);
}
}));
}));
return events;
}
;
async eventsPopulateAddDir(targetPaths, targetPath, events = [], isInitial = false) {
if (isInitial)
return events;
const depth = this.options.recursive ? this.options.depth ?? DEPTH : Math.min(1, this.options.depth ?? DEPTH);
const limit = this.options.limit ?? LIMIT;
const [directories, files] = await Utils.fs.readdir(targetPath, this.options.ignore, depth, limit, this.watcher._closeSignal);
const targetSubPaths = [...directories, ...files];
await Promise.all(targetSubPaths.map(targetSubPath => {
if (this.watcher.isIgnored(targetSubPath, this.options.ignore))
return;
if (targetPaths.includes(targetSubPath))
return;
return this.eventsPopulate([targetSubPath], events, true);
}));
return events;
}
async eventsPopulateUnlinkDir(targetPaths, targetPath, events = [], isInitial = false) {
if (isInitial)
return events;
for (const folderPathOther of this.watcher._poller.stats.keys()) {
if (!Utils.fs.isSubPath(targetPath, folderPathOther))
continue;
if (targetPaths.includes(folderPathOther))
continue;
await this.eventsPopulate([folderPathOther], events, true);
}
return events;
}
/* EVENT HANDLERS */
onTargetAdd(targetPath) {
if (this._isSubRoot(targetPath)) {
if (this.options.renameDetection) {
this.watcher._locker.getLockTargetAdd(targetPath, this.options.renameTimeout);
}
else {
this.watcher.event(TargetEvent.ADD, targetPath);
}
}
}
onTargetAddDir(targetPath) {
if (targetPath !== this.folderPath && this.options.recursive && (!HAS_NATIVE_RECURSION && this.options.native !== false)) {
this.watcher.watchDirectory(targetPath, this.options, this.handler, undefined, this.base || this);
}
if (this._isSubRoot(targetPath)) {
if (this.options.renameDetection) {
this.watcher._locker.getLockTargetAddDir(targetPath, this.options.renameTimeout);
}
else {
this.watcher.event(TargetEvent.ADD_DIR, targetPath);
}
}
}
onTargetChange(targetPath) {
if (this._isSubRoot(targetPath)) {
this.watcher.event(TargetEvent.CHANGE, targetPath);
}
}
onTargetUnlink(targetPath) {
this.watcher.watchersClose(path.dirname(targetPath), targetPath, false);
if (this._isSubRoot(targetPath)) {
if (this.options.renameDetection) {
this.watcher._locker.getLockTargetUnlink(targetPath, this.options.renameTimeout);
}
else {
this.watcher.event(TargetEvent.UNLINK, targetPath);
}
}
}
onTargetUnlinkDir(targetPath) {
this.watcher.watchersClose(path.dirname(targetPath), targetPath, false);
this.watcher.watchersClose(targetPath);
if (this._isSubRoot(targetPath)) {
if (this.options.renameDetection) {
this.watcher._locker.getLockTargetUnlinkDir(targetPath, this.options.renameTimeout);
}
else {
this.watcher.event(TargetEvent.UNLINK_DIR, targetPath);
}
}
}
onTargetEvent(event) {
const [targetEvent, targetPath] = event;
if (targetEvent === TargetEvent.ADD) {
this.onTargetAdd(targetPath);
}
else if (targetEvent === TargetEvent.ADD_DIR) {
this.onTargetAddDir(targetPath);
}
else if (targetEvent === TargetEvent.CHANGE) {
this.onTargetChange(targetPath);
}
else if (targetEvent === TargetEvent.UNLINK) {
this.onTargetUnlink(targetPath);
}
else if (targetEvent === TargetEvent.UNLINK_DIR) {
this.onTargetUnlinkDir(targetPath);
}
}
onTargetEvents(events) {
for (const event of events) {
this.onTargetEvent(event);
}
}
onWatcherEvent(event, targetPath, isInitial = false) {
return this.handlerBatched(event, targetPath, isInitial);
}
onWatcherChange(event = FSTargetEvent.CHANGE, targetName) {
if (this.watcher.isClosed())
return;
const targetPath = path.resolve(this.folderPath, targetName || '');
if (this.filePath && targetPath !== this.folderPath && targetPath !== this.filePath)
return;
if (this.watcher.isIgnored(targetPath, this.options.ignore))
return;
this.onWatcherEvent(event, targetPath);
}
onWatcherError(error) {
if (IS_WINDOWS && error.code === 'EPERM') { // This may happen when a folder is deleted
this.onWatcherChange(FSTargetEvent.CHANGE, '');
}
else {
this.watcher.error(error);
}
}
/* API */
async init() {
await this.initWatcherEvents();
await this.initInitialEvents();
}
async initWatcherEvents() {
const onChange = this.onWatcherChange.bind(this);
this.fswatcher.on(FSWatcherEvent.CHANGE, onChange);
const onError = this.onWatcherError.bind(this);
this.fswatcher.on(FSWatcherEvent.ERROR, onError);
}
async initInitialEvents() {
const isInitial = !this.watcher.isReady(); // "isInitial" => is ignorable via the "ignoreInitial" option
if (this.filePath) { // Single initial path
if (this.watcher._poller.stats.has(this.filePath))
return; // Already polled
await this.onWatcherEvent(FSTargetEvent.CHANGE, this.filePath, isInitial);
}
else { // Multiple initial paths
const depth = this.options.recursive && (HAS_NATIVE_RECURSION && this.options.native !== false) ? this.options.depth ?? DEPTH : Math.min(1, this.options.depth ?? DEPTH);
const limit = this.options.limit ?? LIMIT;
const [directories, files] = await Utils.fs.readdir(this.folderPath, this.options.ignore, depth, limit, this.watcher._closeSignal, this.options.readdirMap);
const targetPaths = [this.folderPath, ...directories, ...files];
await Promise.all(targetPaths.map(targetPath => {
if (this.watcher._poller.stats.has(targetPath))
return; // Already polled
if (this.watcher.isIgnored(targetPath, this.options.ignore))
return;
return this.onWatcherEvent(FSTargetEvent.CHANGE, targetPath, isInitial);
}));
}
}
}
/* EXPORT */
export default WatcherHandler;

32
node_modules/watcher/dist/watcher_locker.d.ts generated vendored Normal file
View File

@@ -0,0 +1,32 @@
import { TargetEvent } from './enums';
import type Watcher from './watcher';
import type { Path, LocksAdd, LocksUnlink, LocksPair, LockConfig } from './types';
declare class WatcherLocker {
_locksAdd: LocksAdd;
_locksAddDir: LocksAdd;
_locksUnlink: LocksUnlink;
_locksUnlinkDir: LocksUnlink;
_locksDir: LocksPair;
_locksFile: LocksPair;
_watcher: Watcher;
static DIR_EVENTS: {
readonly add: TargetEvent.ADD_DIR;
readonly rename: TargetEvent.RENAME_DIR;
readonly unlink: TargetEvent.UNLINK_DIR;
};
static FILE_EVENTS: {
readonly add: TargetEvent.ADD;
readonly change: TargetEvent.CHANGE;
readonly rename: TargetEvent.RENAME;
readonly unlink: TargetEvent.UNLINK;
};
constructor(watcher: Watcher);
getLockAdd(config: LockConfig, timeout?: number): void;
getLockUnlink(config: LockConfig, timeout?: number): void;
getLockTargetAdd(targetPath: Path, timeout?: number): void;
getLockTargetAddDir(targetPath: Path, timeout?: number): void;
getLockTargetUnlink(targetPath: Path, timeout?: number): void;
getLockTargetUnlinkDir(targetPath: Path, timeout?: number): void;
reset(): void;
}
export default WatcherLocker;

139
node_modules/watcher/dist/watcher_locker.js generated vendored Normal file
View File

@@ -0,0 +1,139 @@
/* IMPORT */
import { RENAME_TIMEOUT } from './constants.js';
import { FileType, TargetEvent } from './enums.js';
import Utils from './utils.js';
import WatcherLocksResolver from './watcher_locks_resolver.js';
/* MAIN */
//TODO: Use a better name for this thing, maybe "RenameDetector"
class WatcherLocker {
/* CONSTRUCTOR */
constructor(watcher) {
this._watcher = watcher;
this.reset();
}
/* API */
getLockAdd(config, timeout = RENAME_TIMEOUT) {
const { ino, targetPath, events, locks } = config;
const emit = () => {
const otherPath = this._watcher._poller.paths.find(ino || -1, path => path !== targetPath); // Maybe this is actually a rename in a case-insensitive filesystem
if (otherPath && otherPath !== targetPath) {
if (Utils.fs.getRealPath(targetPath, true) === otherPath)
return; //TODO: This seems a little too special-casey
this._watcher.event(events.rename, otherPath, targetPath);
}
else {
this._watcher.event(events.add, targetPath);
}
};
if (!ino)
return emit();
const cleanup = () => {
locks.add.delete(ino);
WatcherLocksResolver.remove(free);
};
const free = () => {
cleanup();
emit();
};
WatcherLocksResolver.add(free, timeout);
const resolve = () => {
const unlink = locks.unlink.get(ino);
if (!unlink)
return; // No matching "unlink" lock found, skipping
cleanup();
const targetPathPrev = unlink();
if (targetPath === targetPathPrev) {
if (events.change) {
if (this._watcher._poller.stats.has(targetPath)) {
this._watcher.event(events.change, targetPath);
}
}
}
else {
this._watcher.event(events.rename, targetPathPrev, targetPath);
}
};
locks.add.set(ino, resolve);
resolve();
}
getLockUnlink(config, timeout = RENAME_TIMEOUT) {
const { ino, targetPath, events, locks } = config;
const emit = () => {
this._watcher.event(events.unlink, targetPath);
};
if (!ino)
return emit();
const cleanup = () => {
locks.unlink.delete(ino);
WatcherLocksResolver.remove(free);
};
const free = () => {
cleanup();
emit();
};
WatcherLocksResolver.add(free, timeout);
const overridden = () => {
cleanup();
return targetPath;
};
locks.unlink.set(ino, overridden);
locks.add.get(ino)?.();
}
getLockTargetAdd(targetPath, timeout) {
const ino = this._watcher._poller.getIno(targetPath, TargetEvent.ADD, FileType.FILE);
return this.getLockAdd({
ino,
targetPath,
events: WatcherLocker.FILE_EVENTS,
locks: this._locksFile
}, timeout);
}
getLockTargetAddDir(targetPath, timeout) {
const ino = this._watcher._poller.getIno(targetPath, TargetEvent.ADD_DIR, FileType.DIR);
return this.getLockAdd({
ino,
targetPath,
events: WatcherLocker.DIR_EVENTS,
locks: this._locksDir
}, timeout);
}
getLockTargetUnlink(targetPath, timeout) {
const ino = this._watcher._poller.getIno(targetPath, TargetEvent.UNLINK, FileType.FILE);
return this.getLockUnlink({
ino,
targetPath,
events: WatcherLocker.FILE_EVENTS,
locks: this._locksFile
}, timeout);
}
getLockTargetUnlinkDir(targetPath, timeout) {
const ino = this._watcher._poller.getIno(targetPath, TargetEvent.UNLINK_DIR, FileType.DIR);
return this.getLockUnlink({
ino,
targetPath,
events: WatcherLocker.DIR_EVENTS,
locks: this._locksDir
}, timeout);
}
reset() {
this._locksAdd = new Map();
this._locksAddDir = new Map();
this._locksUnlink = new Map();
this._locksUnlinkDir = new Map();
this._locksDir = { add: this._locksAddDir, unlink: this._locksUnlinkDir };
this._locksFile = { add: this._locksAdd, unlink: this._locksUnlink };
}
}
WatcherLocker.DIR_EVENTS = {
add: TargetEvent.ADD_DIR,
rename: TargetEvent.RENAME_DIR,
unlink: TargetEvent.UNLINK_DIR
};
WatcherLocker.FILE_EVENTS = {
add: TargetEvent.ADD,
change: TargetEvent.CHANGE,
rename: TargetEvent.RENAME,
unlink: TargetEvent.UNLINK
};
/* EXPORT */
export default WatcherLocker;

12
node_modules/watcher/dist/watcher_locks_resolver.d.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
/// <reference types="node" />
declare const WatcherLocksResolver: {
interval: number;
intervalId: NodeJS.Timeout | undefined;
fns: Map<Function, number>;
init: () => void;
reset: () => void;
add: (fn: Function, timeout: number) => void;
remove: (fn: Function) => void;
resolve: () => void;
};
export default WatcherLocksResolver;

42
node_modules/watcher/dist/watcher_locks_resolver.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
/* MAIN */
// Registering a single interval scales much better than registering N timeouts
// Timeouts are respected within the interval margin
const WatcherLocksResolver = {
/* VARIABLES */
interval: 100,
intervalId: undefined,
fns: new Map(),
/* LIFECYCLE API */
init: () => {
if (WatcherLocksResolver.intervalId)
return;
WatcherLocksResolver.intervalId = setInterval(WatcherLocksResolver.resolve, WatcherLocksResolver.interval);
},
reset: () => {
if (!WatcherLocksResolver.intervalId)
return;
clearInterval(WatcherLocksResolver.intervalId);
delete WatcherLocksResolver.intervalId;
},
/* API */
add: (fn, timeout) => {
WatcherLocksResolver.fns.set(fn, Date.now() + timeout);
WatcherLocksResolver.init();
},
remove: (fn) => {
WatcherLocksResolver.fns.delete(fn);
},
resolve: () => {
if (!WatcherLocksResolver.fns.size)
return WatcherLocksResolver.reset();
const now = Date.now();
for (const [fn, timestamp] of WatcherLocksResolver.fns) {
if (timestamp >= now)
continue; // We should still wait some more for this
WatcherLocksResolver.remove(fn);
fn();
}
}
};
/* EXPORT */
export default WatcherLocksResolver;

17
node_modules/watcher/dist/watcher_poller.d.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import { FileType, TargetEvent } from './enums';
import LazyMapSet from './lazy_map_set';
import WatcherStats from './watcher_stats';
import type { INO, Path } from './types';
declare class WatcherPoller {
inos: Partial<Record<TargetEvent, Record<Path, [INO, FileType]>>>;
paths: LazyMapSet<INO, Path>;
stats: Map<Path, WatcherStats>;
getIno(targetPath: Path, event: TargetEvent, type?: FileType): INO | undefined;
getStats(targetPath: Path): WatcherStats | undefined;
poll(targetPath: Path, timeout?: number): Promise<WatcherStats | undefined>;
reset(): void;
update(targetPath: Path, timeout?: number): Promise<TargetEvent[]>;
updateIno(targetPath: Path, event: TargetEvent, stats: WatcherStats): void;
updateStats(targetPath: Path, stats?: WatcherStats): void;
}
export default WatcherPoller;

116
node_modules/watcher/dist/watcher_poller.js generated vendored Normal file
View File

@@ -0,0 +1,116 @@
/* IMPORT */
import { FileType, TargetEvent } from './enums.js';
import LazyMapSet from './lazy_map_set.js';
import Utils from './utils.js';
import WatcherStats from './watcher_stats.js';
/* MAIN */
class WatcherPoller {
constructor() {
/* VARIABLES */
this.inos = {};
this.paths = new LazyMapSet();
this.stats = new Map();
}
/* API */
getIno(targetPath, event, type) {
const inos = this.inos[event];
if (!inos)
return;
const ino = inos[targetPath];
if (!ino)
return;
if (type && ino[1] !== type)
return;
return ino[0];
}
getStats(targetPath) {
return this.stats.get(targetPath);
}
async poll(targetPath, timeout) {
const stats = await Utils.fs.poll(targetPath, timeout);
if (!stats)
return;
const isSupported = stats.isFile() || stats.isDirectory();
if (!isSupported)
return;
return new WatcherStats(stats);
}
reset() {
this.inos = {};
this.paths = new LazyMapSet();
this.stats = new Map();
}
async update(targetPath, timeout) {
const prev = this.getStats(targetPath);
const next = await this.poll(targetPath, timeout);
this.updateStats(targetPath, next);
if (!prev && next) {
if (next.isFile()) {
this.updateIno(targetPath, TargetEvent.ADD, next);
return [TargetEvent.ADD];
}
if (next.isDirectory()) {
this.updateIno(targetPath, TargetEvent.ADD_DIR, next);
return [TargetEvent.ADD_DIR];
}
}
else if (prev && !next) {
if (prev.isFile()) {
this.updateIno(targetPath, TargetEvent.UNLINK, prev);
return [TargetEvent.UNLINK];
}
if (prev.isDirectory()) {
this.updateIno(targetPath, TargetEvent.UNLINK_DIR, prev);
return [TargetEvent.UNLINK_DIR];
}
}
else if (prev && next) {
if (prev.isFile()) {
if (next.isFile()) {
if (prev.ino === next.ino && !prev.size && !next.size)
return []; // Same path, same content and same file, nothing actually changed
this.updateIno(targetPath, TargetEvent.CHANGE, next);
return [TargetEvent.CHANGE];
}
if (next.isDirectory()) {
this.updateIno(targetPath, TargetEvent.UNLINK, prev);
this.updateIno(targetPath, TargetEvent.ADD_DIR, next);
return [TargetEvent.UNLINK, TargetEvent.ADD_DIR];
}
}
else if (prev.isDirectory()) {
if (next.isFile()) {
this.updateIno(targetPath, TargetEvent.UNLINK_DIR, prev);
this.updateIno(targetPath, TargetEvent.ADD, next);
return [TargetEvent.UNLINK_DIR, TargetEvent.ADD];
}
if (next.isDirectory()) {
if (prev.ino === next.ino)
return []; // Same path and same directory, nothing actually changed
this.updateIno(targetPath, TargetEvent.UNLINK_DIR, prev);
this.updateIno(targetPath, TargetEvent.ADD_DIR, next);
return [TargetEvent.UNLINK_DIR, TargetEvent.ADD_DIR];
}
}
}
return [];
}
updateIno(targetPath, event, stats) {
const inos = this.inos[event] = this.inos[event] || (this.inos[event] = {});
const type = stats.isFile() ? FileType.FILE : FileType.DIR;
inos[targetPath] = [stats.ino, type];
}
updateStats(targetPath, stats) {
if (stats) {
this.paths.set(stats.ino, targetPath);
this.stats.set(targetPath, stats);
}
else {
const ino = this.stats.get(targetPath)?.ino || -1;
this.paths.delete(ino, targetPath);
this.stats.delete(targetPath);
}
}
}
/* EXPORT */
export default WatcherPoller;

17
node_modules/watcher/dist/watcher_stats.d.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import type { INO, Stats } from './types';
declare class WatcherStats {
ino: INO;
size: number;
atimeMs: number;
mtimeMs: number;
ctimeMs: number;
birthtimeMs: number;
_isFile: boolean;
_isDirectory: boolean;
_isSymbolicLink: boolean;
constructor(stats: Stats);
isFile(): boolean;
isDirectory(): boolean;
isSymbolicLink(): boolean;
}
export default WatcherStats;

29
node_modules/watcher/dist/watcher_stats.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
/* IMPORT */
/* MAIN */
// An more memory-efficient representation of the useful subset of stats objects
class WatcherStats {
/* CONSTRUCTOR */
constructor(stats) {
this.ino = (stats.ino <= Number.MAX_SAFE_INTEGER) ? Number(stats.ino) : stats.ino;
this.size = Number(stats.size);
this.atimeMs = Number(stats.atimeMs);
this.mtimeMs = Number(stats.mtimeMs);
this.ctimeMs = Number(stats.ctimeMs);
this.birthtimeMs = Number(stats.birthtimeMs);
this._isFile = stats.isFile();
this._isDirectory = stats.isDirectory();
this._isSymbolicLink = stats.isSymbolicLink();
}
/* API */
isFile() {
return this._isFile;
}
isDirectory() {
return this._isDirectory;
}
isSymbolicLink() {
return this._isSymbolicLink;
}
}
/* EXPORT */
export default WatcherStats;

21
node_modules/watcher/license generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020-present Fabio Spampinato
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

37
node_modules/watcher/package.json generated vendored Executable file
View File

@@ -0,0 +1,37 @@
{
"name": "watcher",
"repository": "github:fabiospampinato/watcher",
"description": "The file system watcher that strives for perfection, with no native dependencies and optional rename detection support.",
"version": "2.3.1",
"type": "module",
"main": "dist/watcher.js",
"exports": "./dist/watcher.js",
"types": "./dist/watcher.d.ts",
"scripts": {
"clean": "tsex clean",
"compile": "tsex compile",
"compile:watch": "tsex compile --watch",
"test": "tsex test",
"test:watch": "tsex test --watch",
"prepublishOnly": "tsex prepare"
},
"keywords": [
"fs",
"file",
"system",
"filesystem",
"watch",
"watcher"
],
"dependencies": {
"dettle": "^1.0.2",
"stubborn-fs": "^1.2.5",
"tiny-readdir": "^2.7.2"
},
"devDependencies": {
"@types/node": "^20.4.6",
"fava": "^0.2.0",
"tsex": "^3.0.0",
"typescript": "^5.1.6"
}
}

242
node_modules/watcher/readme.md generated vendored Normal file
View File

@@ -0,0 +1,242 @@
# Watcher
The file system watcher that strives for perfection, with no native dependencies and optional rename detection support.
## Features
- **Reliable**: This library aims to handle all issues that may possibly arise when dealing with the file system, including some the most popular alternatives don't handle, like EMFILE errors.
- **Rename detection**: This library can optionally detect when files and directories are renamed, which allows you to provide a better experience to your users in some cases.
- **Performant**: Native recursive watching is used when available (macOS and Windows), and it's efficiently manually performed otherwise.
- **No native dependencies**: Native dependencies can be painful to work with, this library uses 0 of them.
- **No bloat**: Many alternative watchers ship with potentially useless and expensive features, like support for globbing, this library aims to be much leaner while still exposing the right abstractions that allow you to use globbing if you want to.
- **TypeScript-ready**: This library is written in TypeScript, so types aren't an afterthought but come with the library.
## Comparison
You are probably currently using one of the following alternatives for file system watching, here's how they compare against Watcher:
- `fs.watch`: Node's built-in `fs.watch` function is essentially garbage and you never want to use it directly.
- Cons:
- Recursive watching is only supported starting in Node v19.1.0 on Linux.
- Even if you only need to support environments where native recursive watching is provided, the events provided by `fs.watch` are completely useless as they tell you nothing about what actually happened in the file system, so you'll have to poll the file system on your own anyway.
- There are many things that `fs.watch` doesn't take care of, for example watching non-existent paths is just not supported and EMFILE errors are not handled.
- [`chokidar`](https://github.com/paulmillr/chokidar): this is the most popular file system watcher available, while it may be good enough in some cases it's not perfect.
- Cons:
- It requires a native dependency for efficient recursive watching under macOS, and native dependencies can be a pain to work with.
- It doesn't watch recursively efficiently under Windows, Watcher on the other hand is built upon Node's native recursive watching capabilities for Windows.
- It can't detect renames.
- If you don't need features like globbing then chokidar will bloat your app bundles unnecessarely.
- EMFILE errors are not handled properly, so if you are watching enough files chokidar will eventually just give up on them.
- It's not very actively maintened, Watcher on the other hand strives for having 0 bugs, if you can find some we'll fix them ASAP.
- Pros:
- It supports handling symlinks.
- It has some built-in support for handling temporary files written to disk while perfoming an atomic write, although ignoring them in Watcher is pretty trivial too, you can ignore them via the `ignore` option.
- It can more reliably watch network attached paths, although that will lead to performance issues when watching ~lots of files.
- It's more battle tested, although Watcher has a more comprehensive test suite and is used in production too (for example in [Notable](https://github.com/notable/notable), which was using `chokidar` before).
- [`node-watch`](https://github.com/yuanchuan/node-watch): in some ways this library is similar to Watcher, but much less mature.
- Cons:
- No initial events can be emitted when starting watching.
- Only the "update" or "remove" events are emitted, which tell you nothing about whether each event refers to a file or a directory, or whether a file got added or modified.
- "add" and "unlink" events are not provided in some cases, like for files inside an added/deleted folder.
- Watching non-existent paths is not supported.
- It can't detect renames.
- [`nsfw`](https://github.com/Axosoft/nsfw): this is a lesser known but pretty good watcher, although it comes with some major drawbacks.
- Cons:
- It's based on native dependencies, which can be a pain to work with, especially considering that prebuild binaries are not provided so you have to build them yourself.
- It's not very customizable, so for example instructing the watcher to ignore some paths is not possible.
- Everything being native makes it more difficult to contribute a PR or a test to it.
- It's not very actively maintained.
- Pros:
- It adds next to 0 overhead to the rest of your app, as the watching is performed in a separate process and events are emitted in batches.
- "`perfection`": if there was a "perfect" file system watcher, it would compare like this against Watcher (i.e. this is pretty much what's currently missing in Watcher):
- Pros:
- It would support symlinks, Watcher doesn't handle them just yet.
- It would watch all parent directories of the watched roots, for unlink detection when those parents get unlinked, Watcher currently also watches only up-to 1 level parents, which is more than what most other watchers do though.
- It would provide some simple and efficient APIs for adding and removing paths to watch from/to a watcher instance, Watcher currently only has some internal APIs that could be used for that but they are not production-ready yet, although closing a watcher and making a new one with the updated paths to watch works well enough in most cases.
- It would add next to 0 overhead to the rest of your app, currenly Watcher adds some overhead to your app, but if that's significant for your use cases we would consider that to be a bug. You could potentially already spawn a separate process and do the file system watching there yourself too.
- Potentially there are some more edge cases that should be handled too, if you know about them or can find any bug in Watcher just open an issue and we'll fix it ASAP.
## Install
```sh
npm install --save watcher
```
## Options
The following options are provided, you can use them to customize watching to your needs:
- `debounce`: amount of milliseconds to debounce event emission for.
- by default this is set to `300`.
- the higher this is the more duplicate events will be ignored automatically.
- `depth`: maximum depth to watch files at.
- by default this is set to `20`.
- this is useful for avoiding watching directories that are absurdly deep, that would probably waste resources.
- `limit`: maximum number of paths to prod.
- by default this is set to `10_000_000`.
- this is useful as a safe guard in cases where for example the user decided to watch `/`, perhaps by mistake.
- `ignore`: optional function (or regex) that if returns `true` for a path it will cause that path and all its descendants to not be watched at all.
- by default this is not set, so all paths are watched.
- setting an `ignore` function can be very important for performance, you should probably ignore folders like `.git` and temporary files like those used when writing atomically to disk.
- if you need globbing you'll just have to match the path passed to `ignore` against a glob with a globbing library of your choosing.
- `ignoreInitial`: whether events for the initial scan should be ignored or not.
- by default this is set to `false`, so initial events are emitted.
- `native`: whether to use the native recursive watcher if available and needed.
- by default this is set to `true`.
- the native recursive watcher is only available under macOS and Windows.
- when the native recursive watcher is used the `depth` option is ignored.
- setting it to `false` can have a positive performance impact if you want to watch recursively a potentially very deep directory with a low `depth` value.
- `persistent`: whether to keep the Node process running as long as the watcher is not closed.
- by default this is set to `false`.
- `pollingInterval`: polling is used as a last resort measure when watching non-existent paths inside non-existent directories, this controls how often polling is performed, in milliseconds.
- by default this is set to `3000`.
- you can set it to a lower value to make the app detect events much more quickly, but don't set it too low if you are watching many paths that require polling as polling is expensive.
- `pollingTimeout`: sometimes polling will fail, for example if there are too many file descriptors currently open, usually eventually polling will succeed after a few tries though, this controls the amount of milliseconds the library should keep retrying for.
- by default this is set to `20000`.
- `recursive`: whether to watch recursively or not.
- by default this is set to `false`.
- this is supported under all OS'.
- this is implemented natively by Node itself under macOS and Windows.
- `renameDetection`: whether the library should attempt to detect renames and emit `rename`/`renameDir` events.
- by default this is set to `false`.
- rename detection may cause a delayed event emission, because the library may have to wait some more time for it.
- if disabled, the raw underlying `add`/`addDir` and `unlink`/`unlinkDir` events will be emitted instead after a rename.
- if enabled, the library will check if each pair of `add`/`unlink` or `addDir`/`unlinkDir` events are actually `rename` or `renameDir` events respectively, so it will wait for both of those events to be emitted.
- rename detection is fairly reliable, but it is fundamentally dependent on how long the file system takes to emit the underlying raw events, if it takes longer than the set rename timeout the app won't detect the rename and will instead emit the underlying raw events.
- `renameTimeout`: amount of milliseconds to wait for a potential `rename`/`renameDir` event to be detected.
- by default this is set to `1250`.
- the higher this value is the more reliably renames will be detected, but don't set this too high, or the emission of some events could be delayed by that amount.
- the higher this value is the longer the library will take to emit `add`/`addDir`/`unlink`/`unlinkDir` events.
## Usage
Watcher returns an `EventEmitter` instance, so all the methods inherited from that are supported, and the API is largely event-driven.
The following events are emitted:
- Watcher events:
- `error`: Emitted whenever an error occurs.
- `ready`: Emitted after the Watcher has finished instantiating itself. No events are emitted before this events, expect potentially for the `error` event.
- `close`: Emitted when the watcher gets explicitly closed and all its watching operations are stopped. No further events will be emitted after this event.
- `all`: Emitted right before a file system event is about to get emitted.
- File system events:
- `add`: Emitted when a new file is added.
- `addDir`: Emitted when a new directory is added.
- `change`: Emitted when an existing file gets changed, maybe its content changed, maybe its metadata changed.
- `rename`: Emitted when a file gets renamed. This is only emitted when `renameDetection` is enabled.
- `renameDir`: Emitted when a directory gets renamed. This is only emitted when `renameDetection` is enabled.
- `unlink`: Emitted when a file gets removed from the watched tree.
- `unlinkDir`: Emitted when a directory gets removed from the watched tree.
Basically it you have used [`chokidar`](https://github.com/paulmillr/chokidar) in the past Watcher emits pretty much the same exact events, except that it can also emit `rename`/`renameDir` events, it doesn't provide `stats` objects but only paths, and in general it exposes a similar API surface, so switching from (or to) `chokidar` should be easy.
The following interface is provided:
```ts
type Roots = string[] | string;
type TargetEvent = 'add' | 'addDir' | 'change' | 'rename' | 'renameDir' | 'unlink' | 'unlinkDir';
type WatcherEvent = 'all' | 'close' | 'error' | 'ready';
type Event = TargetEvent | WatcherEvent;
type Options = {
debounce?: number,
depth?: number,
ignore?: (( targetPath: Path ) => boolean) | RegExp,
ignoreInitial?: boolean,
native?: boolean,
persistent?: boolean,
pollingInterval?: number,
pollingTimeout?: number,
recursive?: boolean,
renameDetection?: boolean,
renameTimeout?: number
};
class Watcher {
constructor ( roots: Roots, options?: Options, handler?: Handler ): this;
on ( event: Event, handler: Function ): this;
close (): void;
}
```
You would use the library like this:
```ts
import Watcher from 'watcher';
// Watching a single path
const watcher = new Watcher ( '/foo/bar' );
// Watching multiple paths
const watcher = new Watcher ( ['/foo/bar', '/baz/qux'] );
// Passing some options
const watcher = new Watcher ( '/foo/bar', { renameDetection: true } );
// Passing an "all" handler directly
const watcher = new Watcher ( '/foo/bar', {}, ( event, targetPath, targetPathNext ) => {} );
// Attaching the "all" handler manually
const watcher = new Watcher ( '/foo/bar' );
watcher.on ( 'all', ( event, targetPath, targetPathNext ) => { // This is what the library does internally when you pass it a handler directly
console.log ( event ); // => could be any target event: 'add', 'addDir', 'change', 'rename', 'renameDir', 'unlink' or 'unlinkDir'
console.log ( targetPath ); // => the file system path where the event took place, this is always provided
console.log ( targetPathNext ); // => the file system path "targetPath" got renamed to, this is only provided on 'rename'/'renameDir' events
});
// Listening to individual events manually
const watcher = new Watcher ( '/foo/bar' );
watcher.on ( 'error', error => {
console.log ( error instanceof Error ); // => true, "Error" instances are always provided on "error"
});
watcher.on ( 'ready', () => {
// The app just finished instantiation and may soon emit some events
});
watcher.on ( 'close', () => {
// The app just stopped watching and will not emit any further events
});
watcher.on ( 'all', ( event, targetPath, targetPathNext ) => {
console.log ( event ); // => could be any target event: 'add', 'addDir', 'change', 'rename', 'renameDir', 'unlink' or 'unlinkDir'
console.log ( targetPath ); // => the file system path where the event took place, this is always provided
console.log ( targetPathNext ); // => the file system path "targetPath" got renamed to, this is only provided on 'rename'/'renameDir' events
});
watcher.on ( 'add', filePath => {
console.log ( filePath ); // "filePath" just got created, or discovered by the watcher if this is an initial event
});
watcher.on ( 'addDir', directoryPath => {
console.log ( directoryPath ); // "directoryPath" just got created, or discovered by the watcher if this is an initial event
});
watcher.on ( 'change', filePath => {
console.log ( filePath ); // "filePath" just got modified
});
watcher.on ( 'rename', ( filePath, filePathNext ) => {
console.log ( filePath, filePathNext ); // "filePath" got renamed to "filePathNext"
});
watcher.on ( 'renameDir', ( directoryPath, directoryPathNext ) => {
console.log ( directoryPath, directoryPathNext ); // "directoryPath" got renamed to "directoryPathNext"
});
watcher.on ( 'unlink', filePath => {
console.log ( filePath ); // "filePath" got deleted, or at least moved outside the watched tree
});
watcher.on ( 'unlinkDir', directoryPath => {
console.log ( directoryPath ); // "directoryPath" got deleted, or at least moved outside the watched tree
});
// Closing the watcher once you are done with it
watcher.close ();
// Updating watched roots by closing a watcher and opening an updated one
watcher.close ();
watcher = new Watcher ( /* Updated options... */ );
```
## Thanks
- [`chokidar`](https://github.com/paulmillr/chokidar): for providing me a largely good-enough file system watcher for a long time.
- [`node-watch`](https://github.com/yuanchuan/node-watch): for providing a good base from which to make Watcher, and providing some good ideas for how to write good tests for it.
## License
MIT © Fabio Spampinato

32
node_modules/watcher/src/constants.ts generated vendored Normal file
View File

@@ -0,0 +1,32 @@
/* IMPORT */
import os from 'node:os';
/* MAIN */
const DEBOUNCE = 300;
const DEPTH = 20;
const LIMIT = 10_000_000;
const PLATFORM = os.platform ();
const IS_LINUX = ( PLATFORM === 'linux' );
const IS_MAC = ( PLATFORM === 'darwin' );
const IS_WINDOWS = ( PLATFORM === 'win32' );
const HAS_NATIVE_RECURSION = IS_MAC || IS_WINDOWS;
const POLLING_INTERVAL = 3000;
const POLLING_TIMEOUT = 20000;
const RENAME_TIMEOUT = 1250;
/* EXPORT */
export {DEBOUNCE, DEPTH, LIMIT, HAS_NATIVE_RECURSION, IS_LINUX, IS_MAC, IS_WINDOWS, PLATFORM, POLLING_INTERVAL, POLLING_TIMEOUT, RENAME_TIMEOUT};

38
node_modules/watcher/src/enums.ts generated vendored Normal file
View File

@@ -0,0 +1,38 @@
/* MAIN */
const enum FileType {
DIR = 1,
FILE = 2
}
const enum FSTargetEvent {
CHANGE = 'change',
RENAME = 'rename'
}
const enum FSWatcherEvent {
CHANGE = 'change',
ERROR = 'error'
}
const enum TargetEvent {
ADD = 'add',
ADD_DIR = 'addDir',
CHANGE = 'change',
RENAME = 'rename',
RENAME_DIR = 'renameDir',
UNLINK = 'unlink',
UNLINK_DIR = 'unlinkDir'
}
const enum WatcherEvent {
ALL = 'all',
CLOSE = 'close',
ERROR = 'error',
READY = 'ready'
}
/* EXPORT */
export {FileType, FSTargetEvent, FSWatcherEvent, TargetEvent, WatcherEvent};

144
node_modules/watcher/src/lazy_map_set.ts generated vendored Normal file
View File

@@ -0,0 +1,144 @@
/* IMPORT */
import Utils from './utils';
/* MAIN */
//TODO: Maybe publish this as a standalone module
class LazyMapSet<K, V> {
/* VARIABLES */
private map: Map<K, Set<V> | V> = new Map ();
/* API */
clear (): void {
this.map.clear ();
}
delete ( key: K, value?: V ): boolean {
if ( Utils.lang.isUndefined ( value ) ) {
return this.map.delete ( key );
} else if ( this.map.has ( key ) ) {
const values = this.map.get ( key );
if ( Utils.lang.isSet ( values ) ) {
const deleted = values.delete ( value );
if ( !values.size ) {
this.map.delete ( key );
}
return deleted;
} else if ( values === value ) {
this.map.delete ( key );
return true;
}
}
return false;
}
find ( key: K, iterator: ( value: V ) => boolean ): V | undefined {
if ( this.map.has ( key ) ) {
const values = this.map.get ( key );
if ( Utils.lang.isSet ( values ) ) {
return Array.from ( values ).find ( iterator );
} else if ( iterator ( values! ) ) { //TSC
return values;
}
}
return undefined;
}
get ( key: K ): Set<V> | V | undefined {
return this.map.get ( key );
}
has ( key: K, value?: V ): boolean {
if ( Utils.lang.isUndefined ( value ) ) {
return this.map.has ( key );
} else if ( this.map.has ( key ) ) {
const values = this.map.get ( key );
if ( Utils.lang.isSet ( values ) ) {
return values.has ( value );
} else {
return ( values === value );
}
}
return false;
}
set ( key: K, value: V ): this {
if ( this.map.has ( key ) ) {
const values = this.map.get ( key );
if ( Utils.lang.isSet ( values ) ) {
values.add ( value );
} else if ( values !== value ) {
this.map.set ( key, new Set ([ values!, value ]) ); //TSC
}
} else {
this.map.set ( key, value );
}
return this;
}
}
/* EXPORT */
export default LazyMapSet;

90
node_modules/watcher/src/types.ts generated vendored Normal file
View File

@@ -0,0 +1,90 @@
/* IMPORT */
import type {FSWatcher, BigIntStats} from 'node:fs';
import type {ResultDirectories} from 'tiny-readdir';
import type {FSTargetEvent, TargetEvent} from './enums';
import type WatcherStats from './watcher_stats';
/* MAIN */
type Callback = () => void;
type Disposer = () => void;
type Event = [TargetEvent, Path, Path?];
type FSHandler = ( event?: FSTargetEvent, targetName?: string ) => void;
type Handler = ( event: TargetEvent, targetPath: Path, targetPathNext?: Path ) => void;
type HandlerBatched = ( event?: FSTargetEvent, targetPath?: Path, isInitial?: boolean ) => Promise<void>;
type Ignore = (( targetPath: Path ) => boolean) | RegExp;
type INO = bigint | number;
type Path = string;
type ReaddirMap = ResultDirectories;
type Stats = BigIntStats;
type LocksAdd = Map<INO, () => void>;
type LocksUnlink = Map<INO, () => Path>;
type LocksPair = {
add: LocksAdd,
unlink: LocksUnlink
};
type LockConfig = {
ino?: INO,
targetPath: Path,
locks: LocksPair,
events: {
add: TargetEvent.ADD | TargetEvent.ADD_DIR,
change?: TargetEvent.CHANGE,
rename: TargetEvent.RENAME | TargetEvent.RENAME_DIR,
unlink: TargetEvent.UNLINK | TargetEvent.UNLINK_DIR
}
};
type PollerConfig = {
options: WatcherOptions,
targetPath: Path
};
type SubwatcherConfig = {
options: WatcherOptions,
targetPath: Path
};
type WatcherConfig = {
handler: Handler,
watcher: FSWatcher,
options: WatcherOptions,
folderPath: Path,
filePath?: Path
};
type WatcherOptions = {
debounce?: number,
depth?: number, //FIXME: Not respected when events are detected and native recursion is available, but setting a maximum depth is mostly relevant for the non-native implemention
limit?: number, //FIXME: Not respected for newly added directories, but hard to keep track of everything and not has important
ignore?: Ignore,
ignoreInitial?: boolean,
native?: boolean,
persistent?: boolean,
pollingInterval?: number,
pollingTimeout?: number,
readdirMap?: ReaddirMap,
recursive?: boolean,
renameDetection?: boolean,
renameTimeout?: number //TODO: Having a timeout for these sorts of things isn't exactly reliable, but what's the better option?
};
/* EXPORT */
export type {Callback, Disposer, Event, FSHandler, FSWatcher, Handler, HandlerBatched, Ignore, INO, Path, ReaddirMap, Stats, LocksAdd, LocksUnlink, LocksPair, LockConfig, PollerConfig, SubwatcherConfig, WatcherConfig, WatcherOptions, WatcherStats};

208
node_modules/watcher/src/utils.ts generated vendored Normal file
View File

@@ -0,0 +1,208 @@
/* IMPORT */
import {debounce} from 'dettle';
import fs from 'node:fs';
import path from 'node:path';
import sfs from 'stubborn-fs';
import readdir from 'tiny-readdir';
import {POLLING_TIMEOUT} from './constants';
import type {Callback, Ignore, ReaddirMap, Stats} from './types';
/* MAIN */
const Utils = {
/* LANG API */
lang: { //TODO: Import all these utilities from "nanodash" instead
debounce,
attempt: <T> ( fn: () => T ): T | Error => {
try {
return fn ();
} catch ( error: unknown ) {
return Utils.lang.castError ( error );
}
},
castArray: <T> ( x: T | T[] ): T[] => {
return Utils.lang.isArray ( x ) ? x : [x];
},
castError: ( exception: unknown ): Error => {
if ( Utils.lang.isError ( exception ) ) return exception;
if ( Utils.lang.isString ( exception ) ) return new Error ( exception );
return new Error ( 'Unknown error' );
},
defer: ( callback: Callback ): NodeJS.Timeout => {
return setTimeout ( callback, 0 );
},
isArray: ( value: unknown ): value is unknown[] => {
return Array.isArray ( value );
},
isError: ( value: unknown ): value is Error => {
return value instanceof Error;
},
isFunction: ( value: unknown ): value is Function => {
return typeof value === 'function';
},
isNaN: ( value: unknown ): value is number => {
return Number.isNaN ( value );
},
isNumber: ( value: unknown ): value is number => {
return typeof value === 'number';
},
isPrimitive: ( value: unknown ): value is bigint | symbol | string | number | boolean | null | undefined => {
if ( value === null ) return true;
const type = typeof value;
return type !== 'object' && type !== 'function';
},
isShallowEqual: ( x: any, y: any ): boolean => {
if ( x === y ) return true;
if ( Utils.lang.isNaN ( x ) ) return Utils.lang.isNaN ( y );
if ( Utils.lang.isPrimitive ( x ) || Utils.lang.isPrimitive ( y ) ) return x === y;
for ( const i in x ) if ( !( i in y ) ) return false;
for ( const i in y ) if ( x[i] !== y[i] ) return false;
return true;
},
isSet: ( value: unknown ): value is Set<unknown> => {
return value instanceof Set;
},
isString: ( value: unknown ): value is string => {
return typeof value === 'string';
},
isUndefined: ( value: unknown ): value is undefined => {
return value === undefined;
},
noop: (): undefined => {
return;
},
uniq: <T> ( arr: T[] ): T[] => {
if ( arr.length < 2 ) return arr;
return Array.from ( new Set ( arr ) );
}
},
/* FS API */
fs: {
getDepth: ( targetPath: string ): number => {
return Math.max ( 0, targetPath.split ( path.sep ).length - 1 );
},
getRealPath: ( targetPath: string, native?: boolean ): string | undefined => {
try {
return native ? fs.realpathSync.native ( targetPath ) : fs.realpathSync ( targetPath );
} catch {
return;
}
},
isSubPath: ( targetPath: string, subPath: string ): boolean => {
return ( subPath.startsWith ( targetPath ) && subPath[targetPath.length] === path.sep && ( subPath.length - targetPath.length ) > path.sep.length );
},
poll: ( targetPath: string, timeout: number = POLLING_TIMEOUT ): Promise<Stats | undefined> => {
return sfs.retry.stat ( timeout )( targetPath, { bigint: true } ).catch ( Utils.lang.noop );
},
readdir: async ( rootPath: string, ignore?: Ignore, depth: number = Infinity, limit: number = Infinity, signal?: { aborted: boolean }, readdirMap?: ReaddirMap ): Promise<[string[], string[]]> => {
if ( readdirMap && depth === 1 && rootPath in readdirMap ) { // Reusing cached data
const result = readdirMap[rootPath];
return [result.directories, result.files];
} else { // Retrieving fresh data
const result = await readdir ( rootPath, { depth, limit, ignore, signal } );
return [result.directories, result.files];
}
}
}
};
/* EXPORT */
export default Utils;

655
node_modules/watcher/src/watcher.ts generated vendored Normal file
View File

@@ -0,0 +1,655 @@
/* IMPORT */
import {EventEmitter} from 'node:events';
import fs from 'node:fs';
import path from 'node:path';
import {DEPTH, LIMIT, HAS_NATIVE_RECURSION, POLLING_INTERVAL} from './constants';
import {TargetEvent, WatcherEvent} from './enums';
import Utils from './utils';
import WatcherHandler from './watcher_handler';
import WatcherLocker from './watcher_locker';
import WatcherPoller from './watcher_poller';
import type {Callback, Disposer, Handler, Ignore, Path, PollerConfig, SubwatcherConfig, WatcherOptions, WatcherConfig} from './types';
/* MAIN */
class Watcher extends EventEmitter {
/* VARIABLES */
_closed: boolean;
_ready: boolean;
_closeAborter: AbortController;
_closeSignal: { aborted: boolean };
_closeWait: Promise<void>;
_readyWait: Promise<void>;
_locker: WatcherLocker;
_roots: Set<Path>;
_poller: WatcherPoller;
_pollers: Set<PollerConfig>;
_subwatchers: Set<SubwatcherConfig>;
_watchers: Record<Path, WatcherConfig[]>;
_watchersLock: Promise<void>;
_watchersRestorable: Record<Path, WatcherConfig>;
_watchersRestoreTimeout?: NodeJS.Timeout;
/* CONSTRUCTOR */
constructor ( target?: Path[] | Path | Handler, options?: WatcherOptions | Handler, handler?: Handler ) {
super ();
this._closed = false;
this._ready = false;
this._closeAborter = new AbortController ();
this._closeSignal = this._closeAborter.signal;
this.on ( WatcherEvent.CLOSE, () => this._closeAborter.abort () );
this._closeWait = new Promise ( resolve => this.on ( WatcherEvent.CLOSE, resolve ) );
this._readyWait = new Promise ( resolve => this.on ( WatcherEvent.READY, resolve ) );
this._locker = new WatcherLocker ( this );
this._roots = new Set ();
this._poller = new WatcherPoller ();
this._pollers = new Set ();
this._subwatchers = new Set ();
this._watchers = {};
this._watchersLock = Promise.resolve ();
this._watchersRestorable = {};
this.watch ( target, options, handler );
}
/* API */
isClosed (): boolean {
return this._closed;
}
isIgnored ( targetPath: Path, ignore?: Ignore ): boolean {
return !!ignore && ( Utils.lang.isFunction ( ignore ) ? !!ignore ( targetPath ) : ignore.test ( targetPath ) );
}
isReady (): boolean {
return this._ready;
}
close (): boolean {
this._locker.reset ();
this._poller.reset ();
this._roots.clear ();
this.watchersClose ();
if ( this.isClosed () ) return false;
this._closed = true;
return this.emit ( WatcherEvent.CLOSE );
}
error ( exception: unknown ): boolean {
if ( this.isClosed () ) return false;
const error = Utils.lang.castError ( exception );
return this.emit ( WatcherEvent.ERROR, error );
}
event ( event: TargetEvent, targetPath: Path, targetPathNext?: Path ): boolean {
if ( this.isClosed () ) return false;
this.emit ( WatcherEvent.ALL, event, targetPath, targetPathNext );
return this.emit ( event, targetPath, targetPathNext );
}
ready (): boolean {
if ( this.isClosed () || this.isReady () ) return false;
this._ready = true;
return this.emit ( WatcherEvent.READY );
}
pollerExists ( targetPath: Path, options: WatcherOptions ): boolean { //FIXME: This doesn't actually allow for multiple pollers to the same paths, but potentially in the future the same path could be polled with different callbacks to be called, which this doesn't currently allow for
for ( const poller of this._pollers ) {
if ( poller.targetPath !== targetPath ) continue;
if ( !Utils.lang.isShallowEqual ( poller.options, options ) ) continue;
return true;
}
return false;
}
subwatcherExists ( targetPath: Path, options: WatcherOptions ): boolean { //FIXME: This doesn't actually allow for multiple subwatchers to the same paths, but potentially in the future the same path could be subwatched with different callbacks to be called, which this doesn't currently allow for
for ( const subwatcher of this._subwatchers ) {
if ( subwatcher.targetPath !== targetPath ) continue;
if ( !Utils.lang.isShallowEqual ( subwatcher.options, options ) ) continue;
return true;
}
return false;
}
watchersClose ( folderPath?: Path, filePath?: Path, recursive: boolean = true ): void {
if ( !folderPath ) {
for ( const folderPath in this._watchers ) {
this.watchersClose ( folderPath, filePath, false );
}
} else {
const configs = this._watchers[folderPath];
if ( configs ) {
for ( const config of [...configs] ) { // It's important to clone the array, as items will be deleted from it also
if ( filePath && config.filePath !== filePath ) continue;
this.watcherClose ( config );
}
}
if ( recursive ) {
for ( const folderPathOther in this._watchers ) {
if ( !Utils.fs.isSubPath ( folderPath, folderPathOther ) ) continue;
this.watchersClose ( folderPathOther, filePath, false );
}
}
}
}
watchersLock ( callback: Callback ): Promise<void> {
return this._watchersLock.then ( () => {
return this._watchersLock = new Promise ( async resolve => {
await callback ();
resolve ();
});
});
}
watchersRestore (): void {
delete this._watchersRestoreTimeout;
const watchers = Object.entries ( this._watchersRestorable );
this._watchersRestorable = {};
for ( const [targetPath, config] of watchers ) {
this.watchPath ( targetPath, config.options, config.handler );
}
}
async watcherAdd ( config: WatcherConfig, baseWatcherHandler?: WatcherHandler ): Promise<WatcherHandler> {
const {folderPath} = config;
const configs = this._watchers[folderPath] = ( this._watchers[folderPath] || [] );
configs.push ( config );
const watcherHandler = new WatcherHandler ( this, config, baseWatcherHandler );
await watcherHandler.init ();
return watcherHandler;
}
watcherClose ( config: WatcherConfig ): void {
config.watcher.close ();
const configs = this._watchers[config.folderPath];
if ( configs ) {
const index = configs.indexOf ( config );
configs.splice ( index, 1 );
if ( !configs.length ) {
delete this._watchers[config.folderPath];
}
}
const rootPath = config.filePath || config.folderPath;
const isRoot = this._roots.has ( rootPath );
if ( isRoot ) {
this._watchersRestorable[rootPath] = config;
if ( !this._watchersRestoreTimeout ) {
this._watchersRestoreTimeout = Utils.lang.defer ( () => this.watchersRestore () );
}
}
}
watcherExists ( folderPath: Path, options: WatcherOptions, handler: Handler, filePath?: Path ): boolean {
const configsSibling = this._watchers[folderPath];
if ( !!configsSibling?.find ( config => config.handler === handler && ( !config.filePath || config.filePath === filePath ) && config.options.ignore === options.ignore && !!config.options.native === !!options.native && ( !options.recursive || config.options.recursive ) ) ) return true;
let folderAncestorPath = path.dirname ( folderPath );
for ( let depth = 1; depth < Infinity; depth++ ) {
const configsAncestor = this._watchers[folderAncestorPath];
if ( !!configsAncestor?.find ( config => ( depth === 1 || ( config.options.recursive && depth <= ( config.options.depth ?? DEPTH ) ) ) && config.handler === handler && ( !config.filePath || config.filePath === filePath ) && config.options.ignore === options.ignore && !!config.options.native === !!options.native && ( !options.recursive || ( config.options.recursive && ( HAS_NATIVE_RECURSION && config.options.native !== false ) ) ) ) ) return true;
if ( !HAS_NATIVE_RECURSION ) break; // No other ancestor will possibly be found
const folderAncestorPathNext = path.dirname ( folderPath );
if ( folderAncestorPath === folderAncestorPathNext ) break;
folderAncestorPath = folderAncestorPathNext;
}
return false;
}
async watchDirectories ( foldersPaths: Path[], options: WatcherOptions, handler: Handler, filePath?: Path, baseWatcherHandler?: WatcherHandler ): Promise<WatcherHandler | undefined> {
if ( this.isClosed () ) return;
foldersPaths = Utils.lang.uniq ( foldersPaths ).sort ();
let watcherHandlerLast: WatcherHandler | undefined;
for ( const folderPath of foldersPaths ) {
if ( this.isIgnored ( folderPath, options.ignore ) ) continue;
if ( this.watcherExists ( folderPath, options, handler, filePath ) ) continue;
try {
const watcherOptions = ( !options.recursive || ( HAS_NATIVE_RECURSION && options.native !== false ) ) ? options : { ...options, recursive: false }; // Ensuring recursion is explicitly disabled if not available
const watcher = fs.watch ( folderPath, watcherOptions );
const watcherConfig: WatcherConfig = { watcher, handler, options, folderPath, filePath };
const watcherHandler = watcherHandlerLast = await this.watcherAdd ( watcherConfig, baseWatcherHandler );
const isRoot = this._roots.has ( filePath || folderPath );
if ( isRoot ) {
const parentOptions: WatcherOptions = { ...options, ignoreInitial: true, recursive: false }; // Ensuring only the parent folder is being watched
const parentFolderPath = path.dirname ( folderPath );
const parentFilePath = folderPath;
await this.watchDirectories ( [parentFolderPath], parentOptions, handler, parentFilePath, watcherHandler );
//TODO: Watch parents recursively with the following code, which requires other things to be changed too though
// while ( true ) {
// await this.watchDirectories ( [parentFolderPath], parentOptions, handler, parentFilePath, watcherHandler );
// const parentFolderPathNext = path.dirname ( parentFolderPath );
// if ( parentFolderPath === parentFolderPathNext ) break;
// parentFilePath = parentFolderPath;
// parentFolderPath = parentFolderPathNext;
// }
}
} catch ( error: unknown ) {
this.error ( error );
}
}
return watcherHandlerLast;
}
async watchDirectory ( folderPath: Path, options: WatcherOptions, handler: Handler, filePath?: Path, baseWatcherHandler?: WatcherHandler ): Promise<void> {
if ( this.isClosed () ) return;
if ( this.isIgnored ( folderPath, options.ignore ) ) return;
if ( !options.recursive || ( HAS_NATIVE_RECURSION && options.native !== false ) ) {
return this.watchersLock ( () => {
return this.watchDirectories ( [folderPath], options, handler, filePath, baseWatcherHandler );
});
} else {
options = { ...options, recursive: true }; // Ensuring recursion is explicitly enabled
const depth = options.depth ?? DEPTH;
const limit = options.limit ?? LIMIT;
const [folderSubPaths] = await Utils.fs.readdir ( folderPath, options.ignore, depth, limit, this._closeSignal, options.readdirMap );
return this.watchersLock ( async () => {
const watcherHandler = await this.watchDirectories ( [folderPath], options, handler, filePath, baseWatcherHandler );
if ( folderSubPaths.length ) {
const folderPathDepth = Utils.fs.getDepth ( folderPath );
for ( const folderSubPath of folderSubPaths ) {
const folderSubPathDepth = Utils.fs.getDepth ( folderSubPath );
const subDepth = Math.max ( 0, depth - ( folderSubPathDepth - folderPathDepth ) );
const subOptions = { ...options, depth: subDepth }; // Updating the maximum depth to account for depth of the sub path
await this.watchDirectories ( [folderSubPath], subOptions, handler, filePath, baseWatcherHandler || watcherHandler );
}
}
});
}
}
async watchFileOnce ( filePath: Path, options: WatcherOptions, callback: Callback ): Promise<void> {
if ( this.isClosed () ) return;
options = { ...options, ignoreInitial: false }; // Ensuring initial events are detected too
if ( this.subwatcherExists ( filePath, options ) ) return;
const config: SubwatcherConfig = { targetPath: filePath, options };
const handler = ( event: TargetEvent, targetPath: Path ) => {
if ( targetPath !== filePath ) return;
stop ();
callback ();
};
const watcher = new Watcher ( handler );
const start = (): void => {
this._subwatchers.add ( config );
this.on ( WatcherEvent.CLOSE, stop ); // Ensuring the subwatcher is stopped on close
watcher.watchFile ( filePath, options, handler );
};
const stop = (): void => {
this._subwatchers.delete ( config );
this.removeListener ( WatcherEvent.CLOSE, stop ); // Ensuring there are no leftover listeners
watcher.close ();
};
return start ();
}
async watchFile ( filePath: Path, options: WatcherOptions, handler: Handler ): Promise<void> {
if ( this.isClosed () ) return;
if ( this.isIgnored ( filePath, options.ignore ) ) return;
options = { ...options, recursive: false }; // Ensuring recursion is explicitly disabled
const folderPath = path.dirname ( filePath );
return this.watchDirectory ( folderPath, options, handler, filePath );
}
async watchPollingOnce ( targetPath: Path, options: WatcherOptions, callback: Callback ): Promise<void> {
if ( this.isClosed () ) return;
let isDone = false;
const poller = new WatcherPoller ();
const disposer = await this.watchPolling ( targetPath, options, async () => {
if ( isDone ) return;
const events = await poller.update ( targetPath, options.pollingTimeout );
if ( !events.length ) return; // Nothing actually changed, skipping
if ( isDone ) return; // Another async callback has done the work already, skipping
isDone = true;
disposer ();
callback ();
});
}
async watchPolling ( targetPath: Path, options: WatcherOptions, callback: Callback ): Promise<Disposer> {
if ( this.isClosed () ) return Utils.lang.noop;
if ( this.pollerExists ( targetPath, options ) ) return Utils.lang.noop;
const watcherOptions = { ...options, interval: options.pollingInterval ?? POLLING_INTERVAL }; // Ensuring a default interval is set
const config: PollerConfig = { targetPath, options };
const start = (): void => {
this._pollers.add ( config );
this.on ( WatcherEvent.CLOSE, stop ); // Ensuring polling is stopped on close
fs.watchFile ( targetPath, watcherOptions, callback );
};
const stop = (): void => {
this._pollers.delete ( config );
this.removeListener ( WatcherEvent.CLOSE, stop ); // Ensuring there are no leftover listeners
fs.unwatchFile ( targetPath, callback );
};
Utils.lang.attempt ( start );
return () => Utils.lang.attempt ( stop );
}
async watchUnknownChild ( targetPath: Path, options: WatcherOptions, handler: Handler ): Promise<void> {
if ( this.isClosed () ) return;
const watch = () => this.watchPath ( targetPath, options, handler );
return this.watchFileOnce ( targetPath, options, watch );
}
async watchUnknownTarget ( targetPath: Path, options: WatcherOptions, handler: Handler ): Promise<void> {
if ( this.isClosed () ) return;
const watch = () => this.watchPath ( targetPath, options, handler );
return this.watchPollingOnce ( targetPath, options, watch );
}
async watchPaths ( targetPaths: Path[], options: WatcherOptions, handler: Handler ): Promise<void> {
if ( this.isClosed () ) return;
targetPaths = Utils.lang.uniq ( targetPaths ).sort ();
const isParallelizable = targetPaths.every ( ( targetPath, index ) => targetPaths.every ( ( t, i ) => i === index || !Utils.fs.isSubPath ( targetPath, t ) ) ); // All paths are about separate subtrees, so we can start watching in parallel safely //TODO: Find parallelizable chunks rather than using an all or nothing approach
if ( isParallelizable ) { // Watching in parallel
await Promise.all ( targetPaths.map ( targetPath => {
return this.watchPath ( targetPath, options, handler );
}));
} else { // Watching serially
for ( const targetPath of targetPaths ) {
await this.watchPath ( targetPath, options, handler );
}
}
}
async watchPath ( targetPath: Path, options: WatcherOptions, handler: Handler ): Promise<void> {
if ( this.isClosed () ) return;
targetPath = path.resolve ( targetPath );
if ( this.isIgnored ( targetPath, options.ignore ) ) return;
const stats = await Utils.fs.poll ( targetPath, options.pollingTimeout );
if ( !stats ) {
const parentPath = path.dirname ( targetPath );
const parentStats = await Utils.fs.poll ( parentPath, options.pollingTimeout );
if ( parentStats?.isDirectory () ) {
return this.watchUnknownChild ( targetPath, options, handler );
} else {
return this.watchUnknownTarget ( targetPath, options, handler );
}
} else if ( stats.isFile () ) {
return this.watchFile ( targetPath, options, handler );
} else if ( stats.isDirectory () ) {
return this.watchDirectory ( targetPath, options, handler );
} else {
this.error ( `"${targetPath}" is not supported` );
}
}
async watch ( target?: Path[] | Path | Handler, options?: WatcherOptions | Handler, handler: Handler = Utils.lang.noop ): Promise<void> {
if ( Utils.lang.isFunction ( target ) ) return this.watch ( [], {}, target );
if ( Utils.lang.isUndefined ( target ) ) return this.watch ( [], options, handler );
if ( Utils.lang.isFunction ( options ) ) return this.watch ( target, {}, options );
if ( Utils.lang.isUndefined ( options ) ) return this.watch ( target, {}, handler );
if ( this.isClosed () ) return;
if ( this.isReady () ) options.readdirMap = undefined; // Only usable before initialization
const targetPaths = Utils.lang.castArray ( target );
targetPaths.forEach ( targetPath => this._roots.add ( targetPath ) );
await this.watchPaths ( targetPaths, options, handler );
if ( this.isClosed () ) return;
if ( handler !== Utils.lang.noop ) {
this.on ( WatcherEvent.ALL, handler );
}
options.readdirMap = undefined; // Only usable before initialization
this.ready ();
}
}
/* EXPORT */
export default Watcher;

427
node_modules/watcher/src/watcher_handler.ts generated vendored Normal file
View File

@@ -0,0 +1,427 @@
/* IMPORT */
import path from 'node:path';
import {DEBOUNCE, DEPTH, LIMIT, HAS_NATIVE_RECURSION, IS_WINDOWS} from './constants';
import {FSTargetEvent, FSWatcherEvent, TargetEvent} from './enums';
import Utils from './utils';
import type Watcher from './watcher';
import type {Event, FSWatcher, Handler, HandlerBatched, Path, WatcherOptions, WatcherConfig} from './types';
/* MAIN */
class WatcherHandler {
/* VARIABLES */
base?: WatcherHandler;
watcher: Watcher;
handler: Handler;
handlerBatched: HandlerBatched;
fswatcher: FSWatcher;
options: WatcherOptions;
folderPath: Path;
filePath?: Path;
/* CONSTRUCTOR */
constructor ( watcher: Watcher, config: WatcherConfig, base?: WatcherHandler ) {
this.base = base;
this.watcher = watcher;
this.handler = config.handler;
this.fswatcher = config.watcher;
this.options = config.options;
this.folderPath = config.folderPath;
this.filePath = config.filePath;
this.handlerBatched = this.base ? this.base.onWatcherEvent.bind ( this.base ) : this._makeHandlerBatched ( this.options.debounce ); //UGLY
}
/* HELPERS */
_isSubRoot ( targetPath: Path ): boolean { // Only events inside the watched root are emitted
if ( this.filePath ) {
return targetPath === this.filePath;
} else {
return targetPath === this.folderPath || Utils.fs.isSubPath ( this.folderPath, targetPath );
}
}
_makeHandlerBatched ( delay: number = DEBOUNCE ) {
return (() => {
let lock = this.watcher._readyWait; // ~Ensuring no two flushes are active in parallel, or before the watcher is ready
let initials: Event[] = [];
let regulars: Set<Path> = new Set ();
const flush = async ( initials: Event[], regulars: Set<Path> ): Promise<void> => {
const initialEvents = this.options.ignoreInitial ? [] : initials;
const regularEvents = await this.eventsPopulate ([ ...regulars ]);
const events = this.eventsDeduplicate ([ ...initialEvents, ...regularEvents ]);
this.onTargetEvents ( events );
};
const flushDebounced = Utils.lang.debounce ( () => {
if ( this.watcher.isClosed () ) return;
lock = flush ( initials, regulars );
initials = [];
regulars = new Set ();
}, delay );
return async ( event: FSTargetEvent, targetPath: Path = '', isInitial: boolean = false ): Promise<void> => {
if ( isInitial ) { // Poll immediately
await this.eventsPopulate ( [targetPath], initials, true );
} else { // Poll later
regulars.add ( targetPath );
}
lock.then ( flushDebounced );
};
})();
}
/* EVENT HELPERS */
eventsDeduplicate ( events: Event[] ): Event[] {
if ( events.length < 2 ) return events;
const targetsEventPrev: Record<Path, TargetEvent> = {};
return events.reduce<Event[]> ( ( acc, event ) => {
const [targetEvent, targetPath] = event;
const targetEventPrev = targetsEventPrev[targetPath];
if ( targetEvent === targetEventPrev ) return acc; // Same event, ignoring
if ( targetEvent === TargetEvent.CHANGE && targetEventPrev === TargetEvent.ADD ) return acc; // "change" after "add", ignoring
targetsEventPrev[targetPath] = targetEvent;
acc.push ( event );
return acc;
}, [] );
}
async eventsPopulate ( targetPaths: Path[], events: Event[] = [], isInitial: boolean = false ): Promise<Event[]> {
await Promise.all ( targetPaths.map ( async targetPath => {
const targetEvents = await this.watcher._poller.update ( targetPath, this.options.pollingTimeout );
await Promise.all ( targetEvents.map ( async event => {
events.push ([ event, targetPath ]);
if ( event === TargetEvent.ADD_DIR ) {
await this.eventsPopulateAddDir ( targetPaths, targetPath, events, isInitial );
} else if ( event === TargetEvent.UNLINK_DIR ) {
await this.eventsPopulateUnlinkDir ( targetPaths, targetPath, events, isInitial );
}
}));
}));
return events;
};
async eventsPopulateAddDir ( targetPaths: Path[], targetPath: Path, events: Event[] = [], isInitial: boolean = false ): Promise<Event[]> {
if ( isInitial ) return events;
const depth = this.options.recursive ? this.options.depth ?? DEPTH : Math.min ( 1, this.options.depth ?? DEPTH );
const limit = this.options.limit ?? LIMIT;
const [directories, files] = await Utils.fs.readdir ( targetPath, this.options.ignore, depth, limit, this.watcher._closeSignal );
const targetSubPaths = [...directories, ...files];
await Promise.all ( targetSubPaths.map ( targetSubPath => {
if ( this.watcher.isIgnored ( targetSubPath, this.options.ignore ) ) return;
if ( targetPaths.includes ( targetSubPath ) ) return;
return this.eventsPopulate ( [targetSubPath], events, true );
}));
return events;
}
async eventsPopulateUnlinkDir ( targetPaths: Path[], targetPath: Path, events: Event[] = [], isInitial: boolean = false ): Promise<Event[]> {
if ( isInitial ) return events;
for ( const folderPathOther of this.watcher._poller.stats.keys () ) {
if ( !Utils.fs.isSubPath ( targetPath, folderPathOther ) ) continue;
if ( targetPaths.includes ( folderPathOther ) ) continue;
await this.eventsPopulate ( [folderPathOther], events, true );
}
return events;
}
/* EVENT HANDLERS */
onTargetAdd ( targetPath: Path ): void {
if ( this._isSubRoot ( targetPath ) ) {
if ( this.options.renameDetection ) {
this.watcher._locker.getLockTargetAdd ( targetPath, this.options.renameTimeout );
} else {
this.watcher.event ( TargetEvent.ADD, targetPath );
}
}
}
onTargetAddDir ( targetPath: Path ): void {
if ( targetPath !== this.folderPath && this.options.recursive && ( !HAS_NATIVE_RECURSION && this.options.native !== false ) ) {
this.watcher.watchDirectory ( targetPath, this.options, this.handler, undefined, this.base || this );
}
if ( this._isSubRoot ( targetPath ) ) {
if ( this.options.renameDetection ) {
this.watcher._locker.getLockTargetAddDir ( targetPath, this.options.renameTimeout );
} else {
this.watcher.event ( TargetEvent.ADD_DIR, targetPath );
}
}
}
onTargetChange ( targetPath: Path ): void {
if ( this._isSubRoot ( targetPath ) ) {
this.watcher.event ( TargetEvent.CHANGE, targetPath );
}
}
onTargetUnlink ( targetPath: Path ): void {
this.watcher.watchersClose ( path.dirname ( targetPath ), targetPath, false );
if ( this._isSubRoot ( targetPath ) ) {
if ( this.options.renameDetection ) {
this.watcher._locker.getLockTargetUnlink ( targetPath, this.options.renameTimeout );
} else {
this.watcher.event ( TargetEvent.UNLINK, targetPath );
}
}
}
onTargetUnlinkDir ( targetPath: Path ): void {
this.watcher.watchersClose ( path.dirname ( targetPath ), targetPath, false );
this.watcher.watchersClose ( targetPath );
if ( this._isSubRoot ( targetPath ) ) {
if ( this.options.renameDetection ) {
this.watcher._locker.getLockTargetUnlinkDir ( targetPath, this.options.renameTimeout );
} else {
this.watcher.event ( TargetEvent.UNLINK_DIR, targetPath );
}
}
}
onTargetEvent ( event: Event ): void {
const [targetEvent, targetPath] = event;
if ( targetEvent === TargetEvent.ADD ) {
this.onTargetAdd ( targetPath );
} else if ( targetEvent === TargetEvent.ADD_DIR ) {
this.onTargetAddDir ( targetPath );
} else if ( targetEvent === TargetEvent.CHANGE ) {
this.onTargetChange ( targetPath );
} else if ( targetEvent === TargetEvent.UNLINK ) {
this.onTargetUnlink ( targetPath );
} else if ( targetEvent === TargetEvent.UNLINK_DIR ) {
this.onTargetUnlinkDir ( targetPath );
}
}
onTargetEvents ( events: Event[] ): void {
for ( const event of events ) {
this.onTargetEvent ( event );
}
}
onWatcherEvent ( event?: FSTargetEvent, targetPath?: Path, isInitial: boolean = false ): Promise<void> {
return this.handlerBatched ( event, targetPath, isInitial );
}
onWatcherChange ( event: FSTargetEvent = FSTargetEvent.CHANGE, targetName?: string | null ): void {
if ( this.watcher.isClosed () ) return;
const targetPath = path.resolve ( this.folderPath, targetName || '' );
if ( this.filePath && targetPath !== this.folderPath && targetPath !== this.filePath ) return;
if ( this.watcher.isIgnored ( targetPath, this.options.ignore ) ) return;
this.onWatcherEvent ( event, targetPath );
}
onWatcherError ( error: NodeJS.ErrnoException ): void {
if ( IS_WINDOWS && error.code === 'EPERM' ) { // This may happen when a folder is deleted
this.onWatcherChange ( FSTargetEvent.CHANGE, '' );
} else {
this.watcher.error ( error );
}
}
/* API */
async init (): Promise<void> {
await this.initWatcherEvents ();
await this.initInitialEvents ();
}
async initWatcherEvents (): Promise<void> {
const onChange = this.onWatcherChange.bind ( this );
this.fswatcher.on ( FSWatcherEvent.CHANGE, onChange );
const onError = this.onWatcherError.bind ( this );
this.fswatcher.on ( FSWatcherEvent.ERROR, onError );
}
async initInitialEvents (): Promise<void> {
const isInitial = !this.watcher.isReady (); // "isInitial" => is ignorable via the "ignoreInitial" option
if ( this.filePath ) { // Single initial path
if ( this.watcher._poller.stats.has ( this.filePath ) ) return; // Already polled
await this.onWatcherEvent ( FSTargetEvent.CHANGE, this.filePath, isInitial );
} else { // Multiple initial paths
const depth = this.options.recursive && ( HAS_NATIVE_RECURSION && this.options.native !== false ) ? this.options.depth ?? DEPTH : Math.min ( 1, this.options.depth ?? DEPTH );
const limit = this.options.limit ?? LIMIT;
const [directories, files] = await Utils.fs.readdir ( this.folderPath, this.options.ignore, depth, limit, this.watcher._closeSignal, this.options.readdirMap );
const targetPaths = [this.folderPath, ...directories, ...files];
await Promise.all ( targetPaths.map ( targetPath => {
if ( this.watcher._poller.stats.has ( targetPath ) ) return; // Already polled
if ( this.watcher.isIgnored ( targetPath, this.options.ignore ) ) return;
return this.onWatcherEvent ( FSTargetEvent.CHANGE, targetPath, isInitial );
}));
}
}
}
/* EXPORT */
export default WatcherHandler;

202
node_modules/watcher/src/watcher_locker.ts generated vendored Normal file
View File

@@ -0,0 +1,202 @@
/* IMPORT */
import {RENAME_TIMEOUT} from './constants';
import {FileType, TargetEvent} from './enums';
import Utils from './utils';
import WatcherLocksResolver from './watcher_locks_resolver';
import type Watcher from './watcher';
import type {Path, LocksAdd, LocksUnlink, LocksPair, LockConfig} from './types';
/* MAIN */
//TODO: Use a better name for this thing, maybe "RenameDetector"
class WatcherLocker {
/* VARIABLES */
_locksAdd!: LocksAdd;
_locksAddDir!: LocksAdd;
_locksUnlink!: LocksUnlink;
_locksUnlinkDir!: LocksUnlink;
_locksDir!: LocksPair;
_locksFile!: LocksPair;
_watcher: Watcher;
static DIR_EVENTS = <const> {
add: TargetEvent.ADD_DIR,
rename: TargetEvent.RENAME_DIR,
unlink: TargetEvent.UNLINK_DIR
};
static FILE_EVENTS = <const> {
add: TargetEvent.ADD,
change: TargetEvent.CHANGE,
rename: TargetEvent.RENAME,
unlink: TargetEvent.UNLINK
};
/* CONSTRUCTOR */
constructor ( watcher: Watcher ) {
this._watcher = watcher;
this.reset ();
}
/* API */
getLockAdd ( config: LockConfig, timeout: number = RENAME_TIMEOUT ): void {
const {ino, targetPath, events, locks} = config;
const emit = (): void => {
const otherPath = this._watcher._poller.paths.find ( ino || -1, path => path !== targetPath ); // Maybe this is actually a rename in a case-insensitive filesystem
if ( otherPath && otherPath !== targetPath ) {
if ( Utils.fs.getRealPath ( targetPath, true ) === otherPath ) return; //TODO: This seems a little too special-casey
this._watcher.event ( events.rename, otherPath, targetPath );
} else {
this._watcher.event ( events.add, targetPath );
}
};
if ( !ino ) return emit ();
const cleanup = (): void => {
locks.add.delete ( ino );
WatcherLocksResolver.remove ( free );
};
const free = (): void => {
cleanup ();
emit ();
};
WatcherLocksResolver.add ( free, timeout );
const resolve = (): void => {
const unlink = locks.unlink.get ( ino );
if ( !unlink ) return; // No matching "unlink" lock found, skipping
cleanup ();
const targetPathPrev = unlink ();
if ( targetPath === targetPathPrev ) {
if ( events.change ) {
if ( this._watcher._poller.stats.has ( targetPath ) ) {
this._watcher.event ( events.change, targetPath );
}
}
} else {
this._watcher.event ( events.rename, targetPathPrev, targetPath );
}
};
locks.add.set ( ino, resolve );
resolve ();
}
getLockUnlink ( config: LockConfig, timeout: number = RENAME_TIMEOUT ): void {
const {ino, targetPath, events, locks} = config;
const emit = (): void => {
this._watcher.event ( events.unlink, targetPath );
};
if ( !ino ) return emit ();
const cleanup = (): void => {
locks.unlink.delete ( ino );
WatcherLocksResolver.remove ( free );
};
const free = (): void => {
cleanup ();
emit ();
};
WatcherLocksResolver.add ( free, timeout );
const overridden = (): Path => {
cleanup ();
return targetPath;
};
locks.unlink.set ( ino, overridden );
locks.add.get ( ino )?.();
}
getLockTargetAdd ( targetPath: Path, timeout?: number ): void {
const ino = this._watcher._poller.getIno ( targetPath, TargetEvent.ADD, FileType.FILE );
return this.getLockAdd ({
ino,
targetPath,
events: WatcherLocker.FILE_EVENTS,
locks: this._locksFile
}, timeout );
}
getLockTargetAddDir ( targetPath: Path, timeout?: number ): void {
const ino = this._watcher._poller.getIno ( targetPath, TargetEvent.ADD_DIR, FileType.DIR );
return this.getLockAdd ({
ino,
targetPath,
events: WatcherLocker.DIR_EVENTS,
locks: this._locksDir
}, timeout );
}
getLockTargetUnlink ( targetPath: Path, timeout?: number ): void {
const ino = this._watcher._poller.getIno ( targetPath, TargetEvent.UNLINK, FileType.FILE );
return this.getLockUnlink ({
ino,
targetPath,
events: WatcherLocker.FILE_EVENTS,
locks: this._locksFile
}, timeout );
}
getLockTargetUnlinkDir ( targetPath: Path, timeout?: number ): void {
const ino = this._watcher._poller.getIno ( targetPath, TargetEvent.UNLINK_DIR, FileType.DIR );
return this.getLockUnlink ({
ino,
targetPath,
events: WatcherLocker.DIR_EVENTS,
locks: this._locksDir
}, timeout );
}
reset (): void {
this._locksAdd = new Map ();
this._locksAddDir = new Map ();
this._locksUnlink = new Map ();
this._locksUnlinkDir = new Map ();
this._locksDir = { add: this._locksAddDir, unlink: this._locksUnlinkDir };
this._locksFile = { add: this._locksAdd, unlink: this._locksUnlink };
}
}
/* EXPORT */
export default WatcherLocker;

73
node_modules/watcher/src/watcher_locks_resolver.ts generated vendored Normal file
View File

@@ -0,0 +1,73 @@
/* MAIN */
// Registering a single interval scales much better than registering N timeouts
// Timeouts are respected within the interval margin
const WatcherLocksResolver = {
/* VARIABLES */
interval: 100,
intervalId: undefined as NodeJS.Timeout | undefined,
fns: new Map<Function, number> (),
/* LIFECYCLE API */
init: (): void => {
if ( WatcherLocksResolver.intervalId ) return;
WatcherLocksResolver.intervalId = setInterval ( WatcherLocksResolver.resolve, WatcherLocksResolver.interval );
},
reset: (): void => {
if ( !WatcherLocksResolver.intervalId ) return;
clearInterval ( WatcherLocksResolver.intervalId );
delete WatcherLocksResolver.intervalId;
},
/* API */
add: ( fn: Function, timeout: number ): void => {
WatcherLocksResolver.fns.set ( fn, Date.now () + timeout );
WatcherLocksResolver.init ();
},
remove: ( fn: Function ): void => {
WatcherLocksResolver.fns.delete ( fn );
},
resolve: (): void => {
if ( !WatcherLocksResolver.fns.size ) return WatcherLocksResolver.reset ();
const now = Date.now ();
for ( const [fn, timestamp] of WatcherLocksResolver.fns ) {
if ( timestamp >= now ) continue; // We should still wait some more for this
WatcherLocksResolver.remove ( fn );
fn ();
}
}
};
/* EXPORT */
export default WatcherLocksResolver;

193
node_modules/watcher/src/watcher_poller.ts generated vendored Normal file
View File

@@ -0,0 +1,193 @@
/* IMPORT */
import {FileType, TargetEvent} from './enums';
import LazyMapSet from './lazy_map_set';
import Utils from './utils';
import WatcherStats from './watcher_stats';
import type {INO, Path} from './types';
/* MAIN */
class WatcherPoller {
/* VARIABLES */
inos: Partial<Record<TargetEvent, Record<Path, [INO, FileType]>>> = {};
paths: LazyMapSet<INO, Path> = new LazyMapSet ();
stats: Map<Path, WatcherStats> = new Map ();
/* API */
getIno ( targetPath: Path, event: TargetEvent, type?: FileType ): INO | undefined {
const inos = this.inos[event];
if ( !inos ) return;
const ino = inos[targetPath];
if ( !ino ) return;
if ( type && ino[1] !== type ) return;
return ino[0];
}
getStats ( targetPath: Path ): WatcherStats | undefined {
return this.stats.get ( targetPath );
}
async poll ( targetPath: Path, timeout?: number ): Promise<WatcherStats | undefined> {
const stats = await Utils.fs.poll ( targetPath, timeout );
if ( !stats ) return;
const isSupported = stats.isFile () || stats.isDirectory ();
if ( !isSupported ) return;
return new WatcherStats ( stats );
}
reset (): void {
this.inos = {};
this.paths = new LazyMapSet ();
this.stats = new Map ();
}
async update ( targetPath: Path, timeout?: number ): Promise<TargetEvent[]> {
const prev = this.getStats ( targetPath );
const next = await this.poll ( targetPath, timeout );
this.updateStats ( targetPath, next );
if ( !prev && next ) {
if ( next.isFile () ) {
this.updateIno ( targetPath, TargetEvent.ADD, next );
return [TargetEvent.ADD];
}
if ( next.isDirectory () ) {
this.updateIno ( targetPath, TargetEvent.ADD_DIR, next );
return [TargetEvent.ADD_DIR];
}
} else if ( prev && !next ) {
if ( prev.isFile () ) {
this.updateIno ( targetPath, TargetEvent.UNLINK, prev );
return [TargetEvent.UNLINK];
}
if ( prev.isDirectory () ) {
this.updateIno ( targetPath, TargetEvent.UNLINK_DIR, prev );
return [TargetEvent.UNLINK_DIR];
}
} else if ( prev && next ) {
if ( prev.isFile () ) {
if ( next.isFile () ) {
if ( prev.ino === next.ino && !prev.size && !next.size ) return []; // Same path, same content and same file, nothing actually changed
this.updateIno ( targetPath, TargetEvent.CHANGE, next );
return [TargetEvent.CHANGE];
}
if ( next.isDirectory () ) {
this.updateIno ( targetPath, TargetEvent.UNLINK, prev );
this.updateIno ( targetPath, TargetEvent.ADD_DIR, next );
return [TargetEvent.UNLINK, TargetEvent.ADD_DIR];
}
} else if ( prev.isDirectory () ) {
if ( next.isFile () ) {
this.updateIno ( targetPath, TargetEvent.UNLINK_DIR, prev );
this.updateIno ( targetPath, TargetEvent.ADD, next );
return [TargetEvent.UNLINK_DIR, TargetEvent.ADD];
}
if ( next.isDirectory () ) {
if ( prev.ino === next.ino ) return []; // Same path and same directory, nothing actually changed
this.updateIno ( targetPath, TargetEvent.UNLINK_DIR, prev );
this.updateIno ( targetPath, TargetEvent.ADD_DIR, next );
return [TargetEvent.UNLINK_DIR, TargetEvent.ADD_DIR];
}
}
}
return [];
}
updateIno ( targetPath: Path, event: TargetEvent, stats: WatcherStats ): void {
const inos = this.inos[event] = this.inos[event] || ( this.inos[event] = {} );
const type = stats.isFile () ? FileType.FILE : FileType.DIR;
inos[targetPath] = [stats.ino, type];
}
updateStats ( targetPath: Path, stats?: WatcherStats ): void {
if ( stats ) {
this.paths.set ( stats.ino, targetPath );
this.stats.set ( targetPath, stats );
} else {
const ino = this.stats.get ( targetPath )?.ino || -1;
this.paths.delete ( ino, targetPath );
this.stats.delete ( targetPath );
}
}
}
/* EXPORT */
export default WatcherPoller;

64
node_modules/watcher/src/watcher_stats.ts generated vendored Normal file
View File

@@ -0,0 +1,64 @@
/* IMPORT */
import type {INO, Stats} from './types';
/* MAIN */
// An more memory-efficient representation of the useful subset of stats objects
class WatcherStats {
/* VARIABLES */
ino: INO;
size: number;
atimeMs: number;
mtimeMs: number;
ctimeMs: number;
birthtimeMs: number;
_isFile: boolean;
_isDirectory: boolean;
_isSymbolicLink: boolean;
/* CONSTRUCTOR */
constructor ( stats: Stats ) {
this.ino = ( stats.ino <= Number.MAX_SAFE_INTEGER ) ? Number ( stats.ino ) : stats.ino;
this.size = Number ( stats.size );
this.atimeMs = Number ( stats.atimeMs );
this.mtimeMs = Number ( stats.mtimeMs );
this.ctimeMs = Number ( stats.ctimeMs );
this.birthtimeMs = Number ( stats.birthtimeMs );
this._isFile = stats.isFile ();
this._isDirectory = stats.isDirectory ();
this._isSymbolicLink = stats.isSymbolicLink ();
}
/* API */
isFile (): boolean {
return this._isFile;
}
isDirectory (): boolean {
return this._isDirectory;
}
isSymbolicLink (): boolean {
return this._isSymbolicLink;
}
}
/* EXPORT */
export default WatcherStats;

167
node_modules/watcher/test/hooks.js generated vendored Normal file
View File

@@ -0,0 +1,167 @@
/* IMPORT */
import fs from 'node:fs';
import {setTimeout as delay} from 'node:timers/promises';
import Watcher from '../dist/watcher.js';
import Tree from './tree.js';
/* HELPERS */
let TREES = [];
/* MAIN */
//TODO: Use actual hooks, once those get fixed in "fava"
const before = async () => {
if ( fs.existsSync ( Tree.ROOT ) ) {
fs.rmdirSync ( Tree.ROOT, { recursive: true } );
}
TREES = await Promise.all ( Array ( 190 ).fill ().map ( async ( _, i ) => {
const tree = new Tree ( i );
await tree.build ();
return tree;
}));
await delay ( 5000 ); // Giving the filesystem enough time to chill
};
const beforeEach = t => {
const isEqual = ( a, b ) => JSON.stringify ( a ) === JSON.stringify ( b );
const prettyprint = value => JSON.stringify ( value, undefined, 2 );
t.context.normalizePaths = paths => {
return paths.map ( path => {
return Array.isArray ( path ) ? t.context.normalizePaths ( path ) : t.context.tree.path ( path );
});
};
t.context.hasWatchObjects = ( pollersNr, subwatchersNr, watchersNr ) => {
t.is ( t.context.watcher._pollers.size, pollersNr, 'pollers number' );
t.is ( t.context.watcher._subwatchers.size, subwatchersNr, 'subwatchers number' );
t.is ( Object.keys ( t.context.watcher._watchers ).map ( key => t.context.watcher._watchers[key] ).flat ().length, watchersNr, 'watchers number' );
};
t.context.deepEqualUnordered = ( a, b ) => {
t.is ( a.length, b.length );
t.true ( a.every ( item => {
const index = b.findIndex ( itemOther => isEqual ( item, itemOther ) );
if ( index === -1 ) return false;
b.splice ( index, 1 );
return true;
}), prettyprint ( [a, b] ) );
};
t.context.deepEqualUnorderedTuples = ( [a1, b1], [a2, b2] ) => {
t.is ( a1.length, b1.length );
t.is ( a1.length, a2.length );
t.is ( b1.length, b2.length );
t.true ( a1.every ( ( item, itemIndex ) => {
for ( let i = 0, l = a2.length; i < l; i++ ) {
if ( !isEqual ( item, a2[i] ) ) continue;
if ( !isEqual ( b1[itemIndex], b2[i] ) ) continue;
a1.splice ( itemIndex, 1 );
b1.splice ( itemIndex, 1 );
a2.splice ( i, 1 );
b2.splice ( i, 1 );
return true;
}
return false;
}), prettyprint ( [[a1, b1], [a2, b2]] ) );
};
t.context.deepEqualChanges = changes => {
t.deepEqual ( t.context.changes, t.context.normalizePaths ( changes ) );
};
t.context.deepEqualUnorderedChanges = changes => {
t.context.deepEqualUnordered ( t.context.changes, t.context.normalizePaths ( changes ) );
};
t.context.deepEqualResults = ( events, changes ) => {
t.deepEqual ( t.context.events, events );
t.deepEqual ( t.context.changes, t.context.normalizePaths ( changes ) );
t.context.watchReset ();
};
t.context.deepEqualUnorderedResults = ( events, changes ) => {
t.context.deepEqualUnorderedTuples ( [t.context.events, t.context.changes], [events, t.context.normalizePaths ( changes )] );
t.context.watchReset ();
};
t.context.watch = ( target, options = {}, handler = () => {}, filterer = () => true ) => {
const targets = t.context.normalizePaths ( Array.isArray ( target ) ? target : [target] );
t.context.events = [];
t.context.changes = [];
t.context.watcher = new Watcher ( targets, options, ( event, targetPath, targetPathNext ) => {
if ( !filterer ( event, targetPath ) ) return;
const change = targetPathNext ? [targetPath, targetPathNext] : targetPath;
t.context.events.push ( event );
t.context.changes.push ( change );
handler ( event, change );
});
};
t.context.watchForDirs = ( target, options, handler ) => {
const isDirEvent = event => event.endsWith ( 'Dir' );
t.context.watch ( target, options, handler, isDirEvent );
};
t.context.watchForFiles = ( target, options, handler ) => {
const isFileEvent = event => !event.endsWith ( 'Dir' );
t.context.watch ( target, options, handler, isFileEvent );
};
t.context.watchReset = () => {
t.context.events.length = 0;
t.context.changes.length = 0;
};
t.context.wait = {};
t.context.wait.close = () => {
return t.context.watcher._closeWait;
};
t.context.wait.ready = () => {
return t.context.watcher._readyWait;
};
t.context.wait.time = () => delay ( 1000 );
t.context.wait.longtime = () => delay ( 2000 );
t.context.wait.longlongtime = () => delay ( 3000 );
t.context.tree = TREES.pop ();
};
const afterEach = t => {
t.context.watcher.close ();
};
const withContext = fn => {
return async t => {
await beforeEach ( t );
await fn ( t );
await afterEach ( t );
};
};
/* EXPORT */
export {before, beforeEach, afterEach, withContext};

2218
node_modules/watcher/test/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

112
node_modules/watcher/test/tree.js generated vendored Normal file
View File

@@ -0,0 +1,112 @@
/* IMPORT */
import fs from 'node:fs';
import path, { dirname } from 'node:path';
import process from 'node:process';
/* MAIN */
class Tree {
static ROOT = path.join ( process.cwd (), 'test', '__TREES__' );
static BLUEPRINT = [
'home/a/file1',
'home/a/file2',
'home/b/file1',
'home/b/file2',
'home/e/sub/file1',
'home/e/file1',
'home/e/file2',
'home/shallow/1/2/file1',
'home/shallow/1/2/file2',
'home/deep/1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/21/22/23/file1',
'home/deep/1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/21/22/23/file2',
'home/empty/'
];
constructor ( id ) {
this.root = path.join ( Tree.ROOT, String ( id ) );
}
build () {
Tree.BLUEPRINT.forEach ( path => {
if ( path.endsWith ( '/' ) ) {
fs.mkdirSync ( this.path ( path ), { recursive: true } );
} else {
fs.mkdirSync ( dirname ( this.path ( path ) ), { recursive: true } );
fs.writeFileSync ( this.path ( path ), '' );
}
});
}
copy ( path1, path2, delay = 0 ) {
setTimeout ( () => {
fs.cpSync ( this.path ( path1 ), this.path ( path2 ), { recursive: true } );
}, delay );
}
modify ( path, delay = 0 ) {
setTimeout ( () => {
fs.appendFileSync ( this.path ( path ), 'content' );
}, delay );
}
newDir ( path, delay = 0 ) {
setTimeout ( () => {
fs.mkdirSync ( this.path ( path ), { recursive: true } );
}, delay );
}
newDirs ( path, count ) {
return Array ( count ).fill ().map ( ( _, nr ) => {
const id = 'newdir_' + nr;
const dpath = this.path ( path, id );
fs.mkdirSync ( dpath, { recursive: true } );
return dpath;
});
}
newFile ( path, delay = 0 ) {
setTimeout ( () => {
fs.mkdirSync ( dirname ( this.path ( path ) ), { recursive: true } );
fs.writeFileSync ( this.path ( path ), '' );
}, delay );
}
newFiles ( path, count ) {
return Array ( count ).fill ().map ( ( _, nr ) => {
const id = 'newfile_' + nr;
const fpath = this.path ( path, id );
fs.mkdirSync ( dirname ( fpath ), { recursive: true } );
fs.writeFileSync ( fpath, '' );
return fpath;
});
}
path ( ...paths ) {
if ( paths[0].startsWith ( 'home' ) ) {
return path.join ( this.root, ...paths ).replace ( /\/$/, '' );
} else {
return path.join ( ...paths ).replace ( /\/$/, '' );
}
}
remove ( path, delay = 0 ) {
setTimeout ( () => {
fs.rmSync ( this.path ( path ), { recursive: true } );
}, delay );
}
rename ( path1, path2, delay = 0 ) {
setTimeout ( () => {
fs.renameSync ( this.path ( path1 ), this.path ( path2 ) );
}, delay );
}
}
/* EXPORT */
export default Tree;

6
node_modules/watcher/tsconfig.json generated vendored Executable file
View File

@@ -0,0 +1,6 @@
{
"extends": "tsex/tsconfig.json",
"compilerOptions": {
"noUnusedParameters": false
}
}