This commit is contained in:
Philipp Kunz 2024-04-18 21:12:37 +02:00
commit 78abae13b7
76 changed files with 8565 additions and 0 deletions

16
.gitignore vendored Normal file
View File

@ -0,0 +1,16 @@
*~
*.err
*.log
._*
.cache
.fseventsd
.DocumentRevisions*
.DS_Store
.TemporaryItems
.Trashes
Thumbs.db
dist
node_modules
package-lock.json
__TREES__

13
dist_ts/constants.d.ts vendored Normal file
View File

@ -0,0 +1,13 @@
/// <reference types="node" resolution-mode="require"/>
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 };

17
dist_ts/constants.js Normal file
View File

@ -0,0 +1,17 @@
/* 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 };
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uc3RhbnRzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvY29uc3RhbnRzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUNBLFlBQVk7QUFFWixPQUFPLEVBQUUsTUFBTSxTQUFTLENBQUM7QUFFekIsVUFBVTtBQUVWLE1BQU0sUUFBUSxHQUFHLEdBQUcsQ0FBQztBQUVyQixNQUFNLEtBQUssR0FBRyxFQUFFLENBQUM7QUFFakIsTUFBTSxLQUFLLEdBQUcsVUFBVSxDQUFDO0FBRXpCLE1BQU0sUUFBUSxHQUFHLEVBQUUsQ0FBQyxRQUFRLEVBQUcsQ0FBQztBQUVoQyxNQUFNLFFBQVEsR0FBRyxDQUFFLFFBQVEsS0FBSyxPQUFPLENBQUUsQ0FBQztBQUUxQyxNQUFNLE1BQU0sR0FBRyxDQUFFLFFBQVEsS0FBSyxRQUFRLENBQUUsQ0FBQztBQUV6QyxNQUFNLFVBQVUsR0FBRyxDQUFFLFFBQVEsS0FBSyxPQUFPLENBQUUsQ0FBQztBQUU1QyxNQUFNLG9CQUFvQixHQUFHLE1BQU0sSUFBSSxVQUFVLENBQUM7QUFFbEQsTUFBTSxnQkFBZ0IsR0FBRyxJQUFJLENBQUM7QUFFOUIsTUFBTSxlQUFlLEdBQUcsS0FBSyxDQUFDO0FBRTlCLE1BQU0sY0FBYyxHQUFHLElBQUksQ0FBQztBQUU1QixZQUFZO0FBRVosT0FBTyxFQUFDLFFBQVEsRUFBRSxLQUFLLEVBQUUsS0FBSyxFQUFFLG9CQUFvQixFQUFFLFFBQVEsRUFBRSxNQUFNLEVBQUUsVUFBVSxFQUFFLFFBQVEsRUFBRSxnQkFBZ0IsRUFBRSxlQUFlLEVBQUUsY0FBYyxFQUFDLENBQUMifQ==

7
dist_ts/dettle/debounce.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
import type { FN, Debounced } from './types.js';
declare const debounce: <Args extends unknown[]>(fn: FN<Args, unknown>, wait?: number, options?: {
leading?: boolean;
trailing?: boolean;
maxWait?: number;
}) => Debounced<Args>;
export default debounce;

View File

@ -0,0 +1,92 @@
/* IMPORT */
/* MAIN */
const debounce = (fn, wait = 1, options) => {
/* VARIABLES */
wait = Math.max(1, wait);
const leading = options?.leading ?? false;
const trailing = options?.trailing ?? true;
const maxWait = Math.max(options?.maxWait ?? Infinity, wait);
let args;
let timeout;
let timestampCall = 0;
let timestampInvoke = 0;
/* HELPERS */
const getInstantData = () => {
const timestamp = Date.now();
const elapsedCall = timestamp - timestampCall;
const elapsedInvoke = timestamp - timestampInvoke;
const isInvoke = (elapsedCall >= wait || elapsedInvoke >= maxWait);
return [timestamp, isInvoke];
};
const invoke = (timestamp) => {
timestampInvoke = timestamp;
if (!args)
return; // This should never happen
const _args = args;
args = undefined;
fn.apply(undefined, _args);
};
const onCancel = () => {
resetTimeout(0);
};
const onFlush = () => {
if (!timeout)
return;
onCancel();
invoke(Date.now());
};
const onLeading = (timestamp) => {
timestampInvoke = timestamp;
if (leading)
return invoke(timestamp);
};
const onTrailing = (timestamp) => {
if (trailing && args)
return invoke(timestamp);
args = undefined;
};
const onTimeout = () => {
timeout = undefined;
const [timestamp, isInvoking] = getInstantData();
if (isInvoking)
return onTrailing(timestamp);
return updateTimeout(timestamp);
};
const updateTimeout = (timestamp) => {
const elapsedCall = timestamp - timestampCall;
const elapsedInvoke = timestamp - timestampInvoke;
const remainingCall = wait - elapsedCall;
const remainingInvoke = maxWait - elapsedInvoke;
const ms = Math.min(remainingCall, remainingInvoke);
return resetTimeout(ms);
};
const resetTimeout = (ms) => {
if (timeout)
clearTimeout(timeout);
if (ms <= 0)
return;
timeout = setTimeout(onTimeout, ms);
};
/* DEBOUNCED */
const debounced = (...argsLatest) => {
const [timestamp, isInvoking] = getInstantData();
const hadTimeout = !!timeout;
args = argsLatest;
timestampCall = timestamp;
if (isInvoking || !timeout)
resetTimeout(wait);
if (isInvoking) {
if (!hadTimeout)
return onLeading(timestamp);
return invoke(timestamp);
}
};
/* DEBOUNCED UTILITIES */
debounced.cancel = onCancel;
debounced.flush = onFlush;
/* RETURN */
return debounced;
};
/* EXPORT */
export default debounce;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVib3VuY2UuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi90cy9kZXR0bGUvZGVib3VuY2UudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsWUFBWTtBQUlaLFVBQVU7QUFFVixNQUFNLFFBQVEsR0FBRyxDQUEyQixFQUFxQixFQUFFLE9BQWUsQ0FBQyxFQUFFLE9BQXFFLEVBQW9CLEVBQUU7SUFFOUssZUFBZTtJQUVmLElBQUksR0FBRyxJQUFJLENBQUMsR0FBRyxDQUFHLENBQUMsRUFBRSxJQUFJLENBQUUsQ0FBQztJQUU1QixNQUFNLE9BQU8sR0FBRyxPQUFPLEVBQUUsT0FBTyxJQUFJLEtBQUssQ0FBQztJQUMxQyxNQUFNLFFBQVEsR0FBRyxPQUFPLEVBQUUsUUFBUSxJQUFJLElBQUksQ0FBQztJQUMzQyxNQUFNLE9BQU8sR0FBRyxJQUFJLENBQUMsR0FBRyxDQUFHLE9BQU8sRUFBRSxPQUFPLElBQUksUUFBUSxFQUFFLElBQUksQ0FBRSxDQUFDO0lBRWhFLElBQUksSUFBc0IsQ0FBQztJQUMzQixJQUFJLE9BQWtELENBQUM7SUFDdkQsSUFBSSxhQUFhLEdBQUcsQ0FBQyxDQUFDO0lBQ3RCLElBQUksZUFBZSxHQUFHLENBQUMsQ0FBQztJQUV4QixhQUFhO0lBRWIsTUFBTSxjQUFjLEdBQUcsR0FBc0IsRUFBRTtRQUU3QyxNQUFNLFNBQVMsR0FBRyxJQUFJLENBQUMsR0FBRyxFQUFHLENBQUM7UUFDOUIsTUFBTSxXQUFXLEdBQUcsU0FBUyxHQUFHLGFBQWEsQ0FBQztRQUM5QyxNQUFNLGFBQWEsR0FBRyxTQUFTLEdBQUcsZUFBZSxDQUFDO1FBQ2xELE1BQU0sUUFBUSxHQUFHLENBQUUsV0FBVyxJQUFJLElBQUksSUFBSSxhQUFhLElBQUksT0FBTyxDQUFFLENBQUM7UUFFckUsT0FBTyxDQUFDLFNBQVMsRUFBRSxRQUFRLENBQUMsQ0FBQztJQUUvQixDQUFDLENBQUM7SUFFRixNQUFNLE1BQU0sR0FBRyxDQUFFLFNBQWlCLEVBQVMsRUFBRTtRQUUzQyxlQUFlLEdBQUcsU0FBUyxDQUFDO1FBRTVCLElBQUssQ0FBQyxJQUFJO1lBQUcsT0FBTyxDQUFDLDJCQUEyQjtRQUVoRCxNQUFNLEtBQUssR0FBRyxJQUFJLENBQUM7UUFFbkIsSUFBSSxHQUFHLFNBQVMsQ0FBQztRQUVqQixFQUFFLENBQUMsS0FBSyxDQUFHLFNBQVMsRUFBRSxLQUFLLENBQUUsQ0FBQztJQUVoQyxDQUFDLENBQUM7SUFFRixNQUFNLFFBQVEsR0FBRyxHQUFTLEVBQUU7UUFFMUIsWUFBWSxDQUFHLENBQUMsQ0FBRSxDQUFDO0lBRXJCLENBQUMsQ0FBQztJQUVGLE1BQU0sT0FBTyxHQUFHLEdBQVMsRUFBRTtRQUV6QixJQUFLLENBQUMsT0FBTztZQUFHLE9BQU87UUFFdkIsUUFBUSxFQUFHLENBQUM7UUFFWixNQUFNLENBQUcsSUFBSSxDQUFDLEdBQUcsRUFBRyxDQUFFLENBQUM7SUFFekIsQ0FBQyxDQUFDO0lBRUYsTUFBTSxTQUFTLEdBQUcsQ0FBRSxTQUFpQixFQUFTLEVBQUU7UUFFOUMsZUFBZSxHQUFHLFNBQVMsQ0FBQztRQUU1QixJQUFLLE9BQU87WUFBRyxPQUFPLE1BQU0sQ0FBRyxTQUFTLENBQUUsQ0FBQztJQUU3QyxDQUFDLENBQUM7SUFFRixNQUFNLFVBQVUsR0FBRyxDQUFFLFNBQWlCLEVBQVMsRUFBRTtRQUUvQyxJQUFLLFFBQVEsSUFBSSxJQUFJO1lBQUcsT0FBTyxNQUFNLENBQUcsU0FBUyxDQUFFLENBQUM7UUFFcEQsSUFBSSxHQUFHLFNBQVMsQ0FBQztJQUVuQixDQUFDLENBQUM7SUFFRixNQUFNLFNBQVMsR0FBRyxHQUFTLEVBQUU7UUFFM0IsT0FBTyxHQUFHLFNBQVMsQ0FBQztRQUVwQixNQUFNLENBQUMsU0FBUyxFQUFFLFVBQVUsQ0FBQyxHQUFHLGNBQWMsRUFBRyxDQUFDO1FBRWxELElBQUssVUFBVTtZQUFHLE9BQU8sVUFBVSxDQUFHLFNBQVMsQ0FBRSxDQUFDO1FBRWxELE9BQU8sYUFBYSxDQUFHLFNBQVMsQ0FBRSxDQUFDO0lBRXJDLENBQUMsQ0FBQztJQUVGLE1BQU0sYUFBYSxHQUFHLENBQUUsU0FBaUIsRUFBUyxFQUFFO1FBRWxELE1BQU0sV0FBVyxHQUFHLFNBQVMsR0FBRyxhQUFhLENBQUM7UUFDOUMsTUFBTSxhQUFhLEdBQUcsU0FBUyxHQUFHLGVBQWUsQ0FBQztRQUNsRCxNQUFNLGFBQWEsR0FBRyxJQUFJLEdBQUcsV0FBVyxDQUFDO1FBQ3pDLE1BQU0sZUFBZSxHQUFHLE9BQU8sR0FBRyxhQUFhLENBQUM7UUFDaEQsTUFBTSxFQUFFLEdBQUcsSUFBSSxDQUFDLEdBQUcsQ0FBRyxhQUFhLEVBQUUsZUFBZSxDQUFFLENBQUM7UUFFdkQsT0FBTyxZQUFZLENBQUcsRUFBRSxDQUFFLENBQUM7SUFFN0IsQ0FBQyxDQUFDO0lBRUYsTUFBTSxZQUFZLEdBQUcsQ0FBRSxFQUFVLEVBQVMsRUFBRTtRQUUxQyxJQUFLLE9BQU87WUFBRyxZQUFZLENBQUcsT0FBTyxDQUFFLENBQUM7UUFFeEMsSUFBSyxFQUFFLElBQUksQ0FBQztZQUFHLE9BQU87UUFFdEIsT0FBTyxHQUFHLFVBQVUsQ0FBRyxTQUFTLEVBQUUsRUFBRSxDQUFFLENBQUM7SUFFekMsQ0FBQyxDQUFDO0lBRUYsZUFBZTtJQUVmLE1BQU0sU0FBUyxHQUFHLENBQUUsR0FBRyxVQUFnQixFQUFTLEVBQUU7UUFFaEQsTUFBTSxDQUFDLFNBQVMsRUFBRSxVQUFVLENBQUMsR0FBRyxjQUFjLEVBQUcsQ0FBQztRQUNsRCxNQUFNLFVBQVUsR0FBRyxDQUFDLENBQUMsT0FBTyxDQUFDO1FBRTdCLElBQUksR0FBRyxVQUFVLENBQUM7UUFDbEIsYUFBYSxHQUFHLFNBQVMsQ0FBQztRQUUxQixJQUFLLFVBQVUsSUFBSSxDQUFDLE9BQU87WUFBRyxZQUFZLENBQUcsSUFBSSxDQUFFLENBQUM7UUFFcEQsSUFBSyxVQUFVLEVBQUcsQ0FBQztZQUVqQixJQUFLLENBQUMsVUFBVTtnQkFBRyxPQUFPLFNBQVMsQ0FBRyxTQUFTLENBQUUsQ0FBQztZQUVsRCxPQUFPLE1BQU0sQ0FBRyxTQUFTLENBQUUsQ0FBQztRQUU5QixDQUFDO0lBRUgsQ0FBQyxDQUFDO0lBRUYseUJBQXlCO0lBRXpCLFNBQVMsQ0FBQyxNQUFNLEdBQUcsUUFBUSxDQUFDO0lBRTVCLFNBQVMsQ0FBQyxLQUFLLEdBQUcsT0FBTyxDQUFDO0lBRTFCLFlBQVk7SUFFWixPQUFPLFNBQVMsQ0FBQztBQUVuQixDQUFDLENBQUM7QUFFRixZQUFZO0FBRVosZUFBZSxRQUFRLENBQUMifQ==

3
dist_ts/dettle/index.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
import debounce from './debounce.js';
import throttle from './throttle.js';
export { debounce, throttle };

6
dist_ts/dettle/index.js Normal file
View File

@ -0,0 +1,6 @@
/* IMPORT */
import debounce from './debounce.js';
import throttle from './throttle.js';
/* EXPORT */
export { debounce, throttle };
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi90cy9kZXR0bGUvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsWUFBWTtBQUVaLE9BQU8sUUFBUSxNQUFNLGVBQWUsQ0FBQztBQUNyQyxPQUFPLFFBQVEsTUFBTSxlQUFlLENBQUM7QUFFckMsWUFBWTtBQUVaLE9BQU8sRUFBQyxRQUFRLEVBQUUsUUFBUSxFQUFDLENBQUMifQ==

6
dist_ts/dettle/throttle.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
import type { FN, Throttled } from './types.js';
declare const throttle: <Args extends unknown[]>(fn: FN<Args, unknown>, wait?: number, options?: {
leading?: boolean;
trailing?: boolean;
}) => Throttled<Args>;
export default throttle;

View File

@ -0,0 +1,13 @@
/* IMPORT */
import debounce from './debounce.js';
/* MAIN */
const throttle = (fn, wait = 1, options) => {
return debounce(fn, wait, {
maxWait: wait,
leading: options?.leading ?? true,
trailing: options?.trailing ?? true
});
};
/* EXPORT */
export default throttle;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGhyb3R0bGUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi90cy9kZXR0bGUvdGhyb3R0bGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsWUFBWTtBQUVaLE9BQU8sUUFBUSxNQUFNLGVBQWUsQ0FBQztBQUdyQyxVQUFVO0FBRVYsTUFBTSxRQUFRLEdBQUcsQ0FBMkIsRUFBcUIsRUFBRSxPQUFlLENBQUMsRUFBRSxPQUFtRCxFQUFvQixFQUFFO0lBRTVKLE9BQU8sUUFBUSxDQUFHLEVBQUUsRUFBRSxJQUFJLEVBQUU7UUFDMUIsT0FBTyxFQUFFLElBQUk7UUFDYixPQUFPLEVBQUUsT0FBTyxFQUFFLE9BQU8sSUFBSSxJQUFJO1FBQ2pDLFFBQVEsRUFBRSxPQUFPLEVBQUUsUUFBUSxJQUFJLElBQUk7S0FDcEMsQ0FBQyxDQUFDO0FBRUwsQ0FBQyxDQUFDO0FBRUYsWUFBWTtBQUVaLGVBQWUsUUFBUSxDQUFDIn0=

11
dist_ts/dettle/types.d.ts vendored Normal file
View File

@ -0,0 +1,11 @@
type Callback = () => void;
type FN<Args extends unknown[], Return> = (...args: Args) => Return;
type Debounced<Args extends unknown[]> = FN<Args, void> & {
cancel: Callback;
flush: Callback;
};
type Throttled<Args extends unknown[]> = FN<Args, void> & {
cancel: Callback;
flush: Callback;
};
export type { Callback, FN, Debounced, Throttled };

3
dist_ts/dettle/types.js Normal file
View File

@ -0,0 +1,3 @@
/* MAIN */
export {};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZXMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi90cy9kZXR0bGUvdHlwZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsVUFBVSJ9

28
dist_ts/enums.d.ts 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 };

36
dist_ts/enums.js Normal file
View File

@ -0,0 +1,36 @@
/* 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 };
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW51bXMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy9lbnVtcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFDQSxVQUFVO0FBRVYsSUFBVyxRQUdWO0FBSEQsV0FBVyxRQUFRO0lBQ2pCLHFDQUFPLENBQUE7SUFDUCx1Q0FBUSxDQUFBO0FBQ1YsQ0FBQyxFQUhVLFFBQVEsS0FBUixRQUFRLFFBR2xCO0FBRUQsSUFBVyxhQUdWO0FBSEQsV0FBVyxhQUFhO0lBQ3RCLGtDQUFpQixDQUFBO0lBQ2pCLGtDQUFpQixDQUFBO0FBQ25CLENBQUMsRUFIVSxhQUFhLEtBQWIsYUFBYSxRQUd2QjtBQUVELElBQVcsY0FHVjtBQUhELFdBQVcsY0FBYztJQUN2QixtQ0FBaUIsQ0FBQTtJQUNqQixpQ0FBZSxDQUFBO0FBQ2pCLENBQUMsRUFIVSxjQUFjLEtBQWQsY0FBYyxRQUd4QjtBQUVELElBQVcsV0FRVjtBQVJELFdBQVcsV0FBVztJQUNwQiwwQkFBVyxDQUFBO0lBQ1gsaUNBQWtCLENBQUE7SUFDbEIsZ0NBQWlCLENBQUE7SUFDakIsZ0NBQWlCLENBQUE7SUFDakIsdUNBQXdCLENBQUE7SUFDeEIsZ0NBQWlCLENBQUE7SUFDakIsdUNBQXdCLENBQUE7QUFDMUIsQ0FBQyxFQVJVLFdBQVcsS0FBWCxXQUFXLFFBUXJCO0FBRUQsSUFBVyxZQUtWO0FBTEQsV0FBVyxZQUFZO0lBQ3JCLDJCQUFXLENBQUE7SUFDWCwrQkFBZSxDQUFBO0lBQ2YsK0JBQWUsQ0FBQTtJQUNmLCtCQUFlLENBQUE7QUFDakIsQ0FBQyxFQUxVLFlBQVksS0FBWixZQUFZLFFBS3RCO0FBRUQsWUFBWTtBQUVaLE9BQU8sRUFBQyxRQUFRLEVBQUUsYUFBYSxFQUFFLGNBQWMsRUFBRSxXQUFXLEVBQUUsWUFBWSxFQUFDLENBQUMifQ==

10
dist_ts/lazy_map_set.d.ts 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;

82
dist_ts/lazy_map_set.js Normal file
View File

@ -0,0 +1,82 @@
/* 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;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibGF6eV9tYXBfc2V0LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvbGF6eV9tYXBfc2V0LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUNBLFlBQVk7QUFFWixPQUFPLEtBQUssTUFBTSxZQUFZLENBQUM7QUFFL0IsVUFBVTtBQUVWLGlEQUFpRDtBQUVqRCxNQUFNLFVBQVU7SUFBaEI7UUFFRSxlQUFlO1FBRVAsUUFBRyxHQUF1QixJQUFJLEdBQUcsRUFBRyxDQUFDO0lBOEgvQyxDQUFDO0lBNUhDLFNBQVM7SUFFVCxLQUFLO1FBRUgsSUFBSSxDQUFDLEdBQUcsQ0FBQyxLQUFLLEVBQUcsQ0FBQztJQUVwQixDQUFDO0lBRUQsTUFBTSxDQUFHLEdBQU0sRUFBRSxLQUFTO1FBRXhCLElBQUssS0FBSyxDQUFDLElBQUksQ0FBQyxXQUFXLENBQUcsS0FBSyxDQUFFLEVBQUcsQ0FBQztZQUV2QyxPQUFPLElBQUksQ0FBQyxHQUFHLENBQUMsTUFBTSxDQUFHLEdBQUcsQ0FBRSxDQUFDO1FBRWpDLENBQUM7YUFBTSxJQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFHLEdBQUcsQ0FBRSxFQUFHLENBQUM7WUFFbEMsTUFBTSxNQUFNLEdBQUcsSUFBSSxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUcsR0FBRyxDQUFFLENBQUM7WUFFcEMsSUFBSyxLQUFLLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBRyxNQUFNLENBQUUsRUFBRyxDQUFDO2dCQUVsQyxNQUFNLE9BQU8sR0FBRyxNQUFNLENBQUMsTUFBTSxDQUFHLEtBQUssQ0FBRSxDQUFDO2dCQUV4QyxJQUFLLENBQUMsTUFBTSxDQUFDLElBQUksRUFBRyxDQUFDO29CQUVuQixJQUFJLENBQUMsR0FBRyxDQUFDLE1BQU0sQ0FBRyxHQUFHLENBQUUsQ0FBQztnQkFFMUIsQ0FBQztnQkFFRCxPQUFPLE9BQU8sQ0FBQztZQUVqQixDQUFDO2lCQUFNLElBQUssTUFBTSxLQUFLLEtBQUssRUFBRyxDQUFDO2dCQUU5QixJQUFJLENBQUMsR0FBRyxDQUFDLE1BQU0sQ0FBRyxHQUFHLENBQUUsQ0FBQztnQkFFeEIsT0FBTyxJQUFJLENBQUM7WUFFZCxDQUFDO1FBRUgsQ0FBQztRQUVELE9BQU8sS0FBSyxDQUFDO0lBRWYsQ0FBQztJQUVELElBQUksQ0FBRyxHQUFNLEVBQUUsUUFBaUM7UUFFOUMsSUFBSyxJQUFJLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBRyxHQUFHLENBQUUsRUFBRyxDQUFDO1lBRTNCLE1BQU0sTUFBTSxHQUFHLElBQUksQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFHLEdBQUcsQ0FBRSxDQUFDO1lBRXBDLElBQUssS0FBSyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUcsTUFBTSxDQUFFLEVBQUcsQ0FBQztnQkFFbEMsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFHLE1BQU0sQ0FBRSxDQUFDLElBQUksQ0FBRyxRQUFRLENBQUUsQ0FBQztZQUVqRCxDQUFDO2lCQUFNLElBQUssUUFBUSxDQUFHLE1BQU8sQ0FBRSxFQUFHLENBQUMsQ0FBQyxLQUFLO2dCQUV4QyxPQUFPLE1BQU0sQ0FBQztZQUVoQixDQUFDO1FBRUgsQ0FBQztRQUVELE9BQU8sU0FBUyxDQUFDO0lBRW5CLENBQUM7SUFFRCxHQUFHLENBQUcsR0FBTTtRQUVWLE9BQU8sSUFBSSxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUcsR0FBRyxDQUFFLENBQUM7SUFFOUIsQ0FBQztJQUVELEdBQUcsQ0FBRyxHQUFNLEVBQUUsS0FBUztRQUVyQixJQUFLLEtBQUssQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFHLEtBQUssQ0FBRSxFQUFHLENBQUM7WUFFdkMsT0FBTyxJQUFJLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBRyxHQUFHLENBQUUsQ0FBQztRQUU5QixDQUFDO2FBQU0sSUFBSyxJQUFJLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBRyxHQUFHLENBQUUsRUFBRyxDQUFDO1lBRWxDLE1BQU0sTUFBTSxHQUFHLElBQUksQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFHLEdBQUcsQ0FBRSxDQUFDO1lBRXBDLElBQUssS0FBSyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUcsTUFBTSxDQUFFLEVBQUcsQ0FBQztnQkFFbEMsT0FBTyxNQUFNLENBQUMsR0FBRyxDQUFHLEtBQUssQ0FBRSxDQUFDO1lBRTlCLENBQUM7aUJBQU0sQ0FBQztnQkFFTixPQUFPLENBQUUsTUFBTSxLQUFLLEtBQUssQ0FBRSxDQUFDO1lBRTlCLENBQUM7UUFFSCxDQUFDO1FBRUQsT0FBTyxLQUFLLENBQUM7SUFFZixDQUFDO0lBRUQsR0FBRyxDQUFHLEdBQU0sRUFBRSxLQUFRO1FBRXBCLElBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUcsR0FBRyxDQUFFLEVBQUcsQ0FBQztZQUUzQixNQUFNLE1BQU0sR0FBRyxJQUFJLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBRyxHQUFHLENBQUUsQ0FBQztZQUVwQyxJQUFLLEtBQUssQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFHLE1BQU0sQ0FBRSxFQUFHLENBQUM7Z0JBRWxDLE1BQU0sQ0FBQyxHQUFHLENBQUcsS0FBSyxDQUFFLENBQUM7WUFFdkIsQ0FBQztpQkFBTSxJQUFLLE1BQU0sS0FBSyxLQUFLLEVBQUcsQ0FBQztnQkFFOUIsSUFBSSxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUcsR0FBRyxFQUFFLElBQUksR0FBRyxDQUFFLENBQUUsTUFBTyxFQUFFLEtBQUssQ0FBRSxDQUFDLENBQUUsQ0FBQyxDQUFDLEtBQUs7WUFFM0QsQ0FBQztRQUVILENBQUM7YUFBTSxDQUFDO1lBRU4sSUFBSSxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUcsR0FBRyxFQUFFLEtBQUssQ0FBRSxDQUFDO1FBRTlCLENBQUM7UUFFRCxPQUFPLElBQUksQ0FBQztJQUVkLENBQUM7Q0FFRjtBQUVELFlBQVk7QUFFWixlQUFlLFVBQVUsQ0FBQyJ9

View File

@ -0,0 +1,2 @@
declare const NOOP: () => void;
export { NOOP };

View File

@ -0,0 +1,5 @@
/* MAIN */
const NOOP = () => { };
/* EXPORT */
export { NOOP };
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uc3RhbnRzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vdHMvcHJvbWlzZS1tYWtlLW5ha2VkL2NvbnN0YW50cy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFDQSxVQUFVO0FBRVYsTUFBTSxJQUFJLEdBQUcsR0FBUyxFQUFFLEdBQUUsQ0FBQyxDQUFDO0FBRTVCLFlBQVk7QUFFWixPQUFPLEVBQUMsSUFBSSxFQUFDLENBQUMifQ==

6
dist_ts/promise-make-naked/index.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
import type { Result } from './types.js';
declare const makeNakedPromise: {
<T>(): Result<T>;
wrap<T_1>(fn: (result: Result<T_1>) => void): Promise<T_1>;
};
export default makeNakedPromise;

View File

@ -0,0 +1,32 @@
/* IMPORT */
import { NOOP } from './constants.js';
/* MAIN */
const makeNakedPromise = () => {
let resolve = NOOP;
let reject = NOOP;
let resolved = false;
let rejected = false;
const promise = new Promise((res, rej) => {
resolve = value => {
resolved = true;
return res(value);
};
reject = value => {
rejected = true;
return rej(value);
};
});
const isPending = () => !resolved && !rejected;
const isResolved = () => resolved;
const isRejected = () => rejected;
return { promise, resolve, reject, isPending, isResolved, isRejected };
};
/* UTILITIES */
makeNakedPromise.wrap = async (fn) => {
const result = makeNakedPromise();
await fn(result);
return result.promise;
};
/* EXPORT */
export default makeNakedPromise;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi90cy9wcm9taXNlLW1ha2UtbmFrZWQvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsWUFBWTtBQUVaLE9BQU8sRUFBQyxJQUFJLEVBQUMsTUFBTSxnQkFBZ0IsQ0FBQztBQUdwQyxVQUFVO0FBRVYsTUFBTSxnQkFBZ0IsR0FBRyxHQUFrQixFQUFFO0lBRTNDLElBQUksT0FBTyxHQUFzQixJQUFJLENBQUM7SUFDdEMsSUFBSSxNQUFNLEdBQWtCLElBQUksQ0FBQztJQUVqQyxJQUFJLFFBQVEsR0FBRyxLQUFLLENBQUM7SUFDckIsSUFBSSxRQUFRLEdBQUcsS0FBSyxDQUFDO0lBRXJCLE1BQU0sT0FBTyxHQUFHLElBQUksT0FBTyxDQUFNLENBQUUsR0FBRyxFQUFFLEdBQUcsRUFBUyxFQUFFO1FBRXBELE9BQU8sR0FBRyxLQUFLLENBQUMsRUFBRTtZQUNoQixRQUFRLEdBQUcsSUFBSSxDQUFDO1lBQ2hCLE9BQU8sR0FBRyxDQUFHLEtBQUssQ0FBRSxDQUFDO1FBQ3ZCLENBQUMsQ0FBQztRQUVGLE1BQU0sR0FBRyxLQUFLLENBQUMsRUFBRTtZQUNmLFFBQVEsR0FBRyxJQUFJLENBQUM7WUFDaEIsT0FBTyxHQUFHLENBQUcsS0FBSyxDQUFFLENBQUM7UUFDdkIsQ0FBQyxDQUFDO0lBRUosQ0FBQyxDQUFDLENBQUM7SUFFSCxNQUFNLFNBQVMsR0FBRyxHQUFZLEVBQUUsQ0FBQyxDQUFDLFFBQVEsSUFBSSxDQUFDLFFBQVEsQ0FBQztJQUN4RCxNQUFNLFVBQVUsR0FBRyxHQUFZLEVBQUUsQ0FBQyxRQUFRLENBQUM7SUFDM0MsTUFBTSxVQUFVLEdBQUcsR0FBWSxFQUFFLENBQUMsUUFBUSxDQUFDO0lBRTNDLE9BQU8sRUFBQyxPQUFPLEVBQUUsT0FBTyxFQUFFLE1BQU0sRUFBRSxTQUFTLEVBQUUsVUFBVSxFQUFFLFVBQVUsRUFBQyxDQUFDO0FBRXZFLENBQUMsQ0FBQztBQUVGLGVBQWU7QUFFZixnQkFBZ0IsQ0FBQyxJQUFJLEdBQUcsS0FBSyxFQUFPLEVBQWlDLEVBQWUsRUFBRTtJQUVwRixNQUFNLE1BQU0sR0FBRyxnQkFBZ0IsRUFBTSxDQUFDO0lBRXRDLE1BQU0sRUFBRSxDQUFHLE1BQU0sQ0FBRSxDQUFDO0lBRXBCLE9BQU8sTUFBTSxDQUFDLE9BQU8sQ0FBQztBQUV4QixDQUFDLENBQUM7QUFFRixZQUFZO0FBRVosZUFBZSxnQkFBZ0IsQ0FBQyJ9

11
dist_ts/promise-make-naked/types.d.ts vendored Normal file
View File

@ -0,0 +1,11 @@
type PromiseResolve<T> = (value: T | PromiseLike<T>) => void;
type PromiseReject = (reason?: unknown) => void;
type Result<T> = {
promise: Promise<T>;
resolve: PromiseResolve<T>;
reject: PromiseReject;
isPending: () => boolean;
isResolved: () => boolean;
isRejected: () => boolean;
};
export type { PromiseResolve, PromiseReject, Result };

View File

@ -0,0 +1,3 @@
/* MAIN */
export {};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZXMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi90cy9wcm9taXNlLW1ha2UtbmFrZWQvdHlwZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsVUFBVSJ9

3
dist_ts/tiny-readdir/index.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
import type { Options, Result } from './types.js';
declare const readdir: (rootPath: string, options?: Options) => Promise<Result>;
export default readdir;

File diff suppressed because one or more lines are too long

28
dist_ts/tiny-readdir/types.d.ts vendored Normal file
View File

@ -0,0 +1,28 @@
type Callback = () => void;
type Options = {
depth?: number;
limit?: number;
followSymlinks?: boolean;
ignore?: ((targetPath: string) => boolean) | RegExp;
signal?: {
aborted: boolean;
};
};
type ResultDirectory = {
directories: string[];
directoriesNames: Set<string>;
directoriesNamesToPaths: Record<string, string[]>;
files: string[];
filesNames: Set<string>;
filesNamesToPaths: Record<string, string[]>;
symlinks: string[];
symlinksNames: Set<string>;
symlinksNamesToPaths: Record<string, string[]>;
};
type ResultDirectories = {
[path: string]: ResultDirectory;
};
type Result = ResultDirectory & {
map: ResultDirectories;
};
export type { Callback, Options, ResultDirectory, ResultDirectories, Result };

View File

@ -0,0 +1,3 @@
/* HELPERS */
export {};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZXMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi90cy90aW55LXJlYWRkaXIvdHlwZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsYUFBYSJ9

8
dist_ts/tiny-readdir/utils.d.ts vendored Normal file
View File

@ -0,0 +1,8 @@
import type { Callback } from './types.js';
declare const isFunction: (value: unknown) => value is Function;
declare const makeCounterPromise: () => {
promise: Promise<void>;
increment: Callback;
decrement: Callback;
};
export { isFunction, makeCounterPromise };

View File

@ -0,0 +1,23 @@
/* IMPORT */
import makeNakedPromise from '../promise-make-naked/index.js';
/* MAIN */
const isFunction = (value) => {
return (typeof value === 'function');
};
const makeCounterPromise = () => {
const { promise, resolve } = makeNakedPromise();
let counter = 0;
const increment = () => {
counter += 1;
};
const decrement = () => {
counter -= 1;
if (counter)
return;
resolve();
};
return { promise, increment, decrement };
};
/* EXPORT */
export { isFunction, makeCounterPromise };
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbHMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi90cy90aW55LXJlYWRkaXIvdXRpbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsWUFBWTtBQUVaLE9BQU8sZ0JBQWdCLE1BQU0sZ0NBQWdDLENBQUM7QUFHOUQsVUFBVTtBQUVWLE1BQU0sVUFBVSxHQUFHLENBQUUsS0FBYyxFQUFzQixFQUFFO0lBRXpELE9BQU8sQ0FBRSxPQUFPLEtBQUssS0FBSyxVQUFVLENBQUUsQ0FBQztBQUV6QyxDQUFDLENBQUM7QUFFRixNQUFNLGtCQUFrQixHQUFHLEdBQXlFLEVBQUU7SUFFcEcsTUFBTSxFQUFDLE9BQU8sRUFBRSxPQUFPLEVBQUMsR0FBRyxnQkFBZ0IsRUFBUyxDQUFDO0lBRXJELElBQUksT0FBTyxHQUFHLENBQUMsQ0FBQztJQUVoQixNQUFNLFNBQVMsR0FBRyxHQUFTLEVBQUU7UUFFM0IsT0FBTyxJQUFJLENBQUMsQ0FBQztJQUVmLENBQUMsQ0FBQztJQUVGLE1BQU0sU0FBUyxHQUFHLEdBQVMsRUFBRTtRQUUzQixPQUFPLElBQUksQ0FBQyxDQUFDO1FBRWIsSUFBSyxPQUFPO1lBQUcsT0FBTztRQUV0QixPQUFPLEVBQUcsQ0FBQztJQUViLENBQUMsQ0FBQztJQUVGLE9BQU8sRUFBRSxPQUFPLEVBQUUsU0FBUyxFQUFFLFNBQVMsRUFBRSxDQUFDO0FBRTNDLENBQUMsQ0FBQztBQUVGLFlBQVk7QUFFWixPQUFPLEVBQUMsVUFBVSxFQUFFLGtCQUFrQixFQUFDLENBQUMifQ==

77
dist_ts/types.d.ts vendored Normal file
View File

@ -0,0 +1,77 @@
/// <reference types="node" resolution-mode="require"/>
import type { FSWatcher, BigIntStats } from 'node:fs';
import type { FSTargetEvent, TargetEvent } from './enums.js';
import type WatcherStats from './watcher_stats.js';
type ResultDirectory = {
directories: string[];
directoriesNames: Set<string>;
directoriesNamesToPaths: Record<string, string[]>;
files: string[];
filesNames: Set<string>;
filesNamesToPaths: Record<string, string[]>;
symlinks: string[];
symlinksNames: Set<string>;
symlinksNamesToPaths: Record<string, string[]>;
};
type ResultDirectories = {
[path: string]: ResultDirectory;
};
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 };

3
dist_ts/types.js Normal file
View File

@ -0,0 +1,3 @@
/* IMPORT */
export {};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZXMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy90eXBlcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFDQSxZQUFZIn0=

41
dist_ts/utils.d.ts vendored Normal file
View File

@ -0,0 +1,41 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import type { Callback, Ignore, ReaddirMap, Stats } from './types.js';
declare const Utils: {
lang: {
debounce: <Args extends unknown[]>(fn: import("./dettle/types.js").FN<Args, unknown>, wait?: number, options?: {
leading?: boolean;
trailing?: boolean;
maxWait?: number;
}) => import("./dettle/types.js").Debounced<Args>;
attempt: <T>(fn: () => T) => Error | T;
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;
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;

121
dist_ts/utils.js Normal file

File diff suppressed because one or more lines are too long

55
dist_ts/watcher.d.ts vendored Normal file
View File

@ -0,0 +1,55 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import { EventEmitter } from 'node:events';
import { TargetEvent } from './enums.js';
import WatcherHandler from './watcher_handler.js';
import WatcherLocker from './watcher_locker.js';
import WatcherPoller from './watcher_poller.js';
import type { Callback, Disposer, Handler, Ignore, Path, PollerConfig, SubwatcherConfig, WatcherOptions, WatcherConfig } from './types.js';
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;

397
dist_ts/watcher.js Normal file

File diff suppressed because one or more lines are too long

36
dist_ts/watcher_handler.d.ts vendored Normal file
View File

@ -0,0 +1,36 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import { FSTargetEvent } from './enums.js';
import type Watcher from './watcher.js';
import type { Event, FSWatcher, Handler, HandlerBatched, Path, WatcherOptions, WatcherConfig } from './types.js';
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;

249
dist_ts/watcher_handler.js Normal file

File diff suppressed because one or more lines are too long

32
dist_ts/watcher_locker.d.ts vendored Normal file
View File

@ -0,0 +1,32 @@
import { TargetEvent } from './enums.js';
import type Watcher from './watcher.js';
import type { Path, LocksAdd, LocksUnlink, LocksPair, LockConfig } from './types.js';
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;

140
dist_ts/watcher_locker.js Normal file

File diff suppressed because one or more lines are too long

12
dist_ts/watcher_locks_resolver.d.ts vendored Normal file
View File

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

View File

@ -0,0 +1,43 @@
/* 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;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoid2F0Y2hlcl9sb2Nrc19yZXNvbHZlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3RzL3dhdGNoZXJfbG9ja3NfcmVzb2x2ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsVUFBVTtBQUVWLCtFQUErRTtBQUMvRSxvREFBb0Q7QUFFcEQsTUFBTSxvQkFBb0IsR0FBRztJQUUzQixlQUFlO0lBRWYsUUFBUSxFQUFFLEdBQUc7SUFDYixVQUFVLEVBQUUsU0FBdUM7SUFDbkQsR0FBRyxFQUFFLElBQUksR0FBRyxFQUFxQjtJQUVqQyxtQkFBbUI7SUFFbkIsSUFBSSxFQUFFLEdBQVMsRUFBRTtRQUVmLElBQUssb0JBQW9CLENBQUMsVUFBVTtZQUFHLE9BQU87UUFFOUMsb0JBQW9CLENBQUMsVUFBVSxHQUFHLFdBQVcsQ0FBRyxvQkFBb0IsQ0FBQyxPQUFPLEVBQUUsb0JBQW9CLENBQUMsUUFBUSxDQUFFLENBQUM7SUFFaEgsQ0FBQztJQUVELEtBQUssRUFBRSxHQUFTLEVBQUU7UUFFaEIsSUFBSyxDQUFDLG9CQUFvQixDQUFDLFVBQVU7WUFBRyxPQUFPO1FBRS9DLGFBQWEsQ0FBRyxvQkFBb0IsQ0FBQyxVQUFVLENBQUUsQ0FBQztRQUVsRCxPQUFPLG9CQUFvQixDQUFDLFVBQVUsQ0FBQztJQUV6QyxDQUFDO0lBRUQsU0FBUztJQUVULEdBQUcsRUFBRSxDQUFFLEVBQVksRUFBRSxPQUFlLEVBQVMsRUFBRTtRQUU3QyxvQkFBb0IsQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFHLEVBQUUsRUFBRSxJQUFJLENBQUMsR0FBRyxFQUFHLEdBQUcsT0FBTyxDQUFFLENBQUM7UUFFM0Qsb0JBQW9CLENBQUMsSUFBSSxFQUFHLENBQUM7SUFFL0IsQ0FBQztJQUVELE1BQU0sRUFBRSxDQUFFLEVBQVksRUFBUyxFQUFFO1FBRS9CLG9CQUFvQixDQUFDLEdBQUcsQ0FBQyxNQUFNLENBQUcsRUFBRSxDQUFFLENBQUM7SUFFekMsQ0FBQztJQUVELE9BQU8sRUFBRSxHQUFTLEVBQUU7UUFFbEIsSUFBSyxDQUFDLG9CQUFvQixDQUFDLEdBQUcsQ0FBQyxJQUFJO1lBQUcsT0FBTyxvQkFBb0IsQ0FBQyxLQUFLLEVBQUcsQ0FBQztRQUUzRSxNQUFNLEdBQUcsR0FBRyxJQUFJLENBQUMsR0FBRyxFQUFHLENBQUM7UUFFeEIsS0FBTSxNQUFNLENBQUMsRUFBRSxFQUFFLFNBQVMsQ0FBQyxJQUFJLG9CQUFvQixDQUFDLEdBQUcsRUFBRyxDQUFDO1lBRXpELElBQUssU0FBUyxJQUFJLEdBQUc7Z0JBQUcsU0FBUyxDQUFDLDBDQUEwQztZQUU1RSxvQkFBb0IsQ0FBQyxNQUFNLENBQUcsRUFBRSxDQUFFLENBQUM7WUFFbkMsRUFBRSxFQUFHLENBQUM7UUFFUixDQUFDO0lBRUgsQ0FBQztDQUVGLENBQUM7QUFFRixZQUFZO0FBRVosZUFBZSxvQkFBb0IsQ0FBQyJ9

17
dist_ts/watcher_poller.d.ts vendored Normal file
View File

@ -0,0 +1,17 @@
import { FileType, TargetEvent } from './enums.js';
import LazyMapSet from './lazy_map_set.js';
import WatcherStats from './watcher_stats.js';
import type { INO, Path } from './types.js';
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;

117
dist_ts/watcher_poller.js Normal file

File diff suppressed because one or more lines are too long

17
dist_ts/watcher_stats.d.ts vendored Normal file
View File

@ -0,0 +1,17 @@
import type { INO, Stats } from './types.js';
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;

30
dist_ts/watcher_stats.js Normal file
View File

@ -0,0 +1,30 @@
/* 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;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoid2F0Y2hlcl9zdGF0cy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3RzL3dhdGNoZXJfc3RhdHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsWUFBWTtBQUlaLFVBQVU7QUFFVixnRkFBZ0Y7QUFFaEYsTUFBTSxZQUFZO0lBY2hCLGlCQUFpQjtJQUVqQixZQUFjLEtBQVk7UUFFeEIsSUFBSSxDQUFDLEdBQUcsR0FBRyxDQUFFLEtBQUssQ0FBQyxHQUFHLElBQUksTUFBTSxDQUFDLGdCQUFnQixDQUFFLENBQUMsQ0FBQyxDQUFDLE1BQU0sQ0FBRyxLQUFLLENBQUMsR0FBRyxDQUFFLENBQUMsQ0FBQyxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUM7UUFDdkYsSUFBSSxDQUFDLElBQUksR0FBRyxNQUFNLENBQUcsS0FBSyxDQUFDLElBQUksQ0FBRSxDQUFDO1FBQ2xDLElBQUksQ0FBQyxPQUFPLEdBQUcsTUFBTSxDQUFHLEtBQUssQ0FBQyxPQUFPLENBQUUsQ0FBQztRQUN4QyxJQUFJLENBQUMsT0FBTyxHQUFHLE1BQU0sQ0FBRyxLQUFLLENBQUMsT0FBTyxDQUFFLENBQUM7UUFDeEMsSUFBSSxDQUFDLE9BQU8sR0FBRyxNQUFNLENBQUcsS0FBSyxDQUFDLE9BQU8sQ0FBRSxDQUFDO1FBQ3hDLElBQUksQ0FBQyxXQUFXLEdBQUcsTUFBTSxDQUFHLEtBQUssQ0FBQyxXQUFXLENBQUUsQ0FBQztRQUNoRCxJQUFJLENBQUMsT0FBTyxHQUFHLEtBQUssQ0FBQyxNQUFNLEVBQUcsQ0FBQztRQUMvQixJQUFJLENBQUMsWUFBWSxHQUFHLEtBQUssQ0FBQyxXQUFXLEVBQUcsQ0FBQztRQUN6QyxJQUFJLENBQUMsZUFBZSxHQUFHLEtBQUssQ0FBQyxjQUFjLEVBQUcsQ0FBQztJQUVqRCxDQUFDO0lBRUQsU0FBUztJQUVULE1BQU07UUFFSixPQUFPLElBQUksQ0FBQyxPQUFPLENBQUM7SUFFdEIsQ0FBQztJQUVELFdBQVc7UUFFVCxPQUFPLElBQUksQ0FBQyxZQUFZLENBQUM7SUFFM0IsQ0FBQztJQUVELGNBQWM7UUFFWixPQUFPLElBQUksQ0FBQyxlQUFlLENBQUM7SUFFOUIsQ0FBQztDQUVGO0FBRUQsWUFBWTtBQUVaLGVBQWUsWUFBWSxDQUFDIn0=

21
license 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.

5
npmextra.json Normal file
View File

@ -0,0 +1,5 @@
{
"tsdoc": {
"legal": "The licenses of the original packages apply."
}
}

26
package.json Executable file
View File

@ -0,0 +1,26 @@
{
"name": "@tempfix/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.0",
"type": "module",
"main": "dist_ts/watcher.js",
"exports": "./dist_ts/watcher.js",
"types": "./dist_ts/watcher.d.ts",
"scripts": {},
"keywords": [
"fs",
"file",
"system",
"filesystem",
"watch",
"watcher"
],
"dependencies": {
"stubborn-fs": "^1.2.5"
},
"devDependencies": {
"@git.zone/tsbuild": "^2.1.72",
"@types/node": "^20.4.6"
}
}

921
pnpm-lock.yaml Normal file
View File

@ -0,0 +1,921 @@
lockfileVersion: '6.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
dependencies:
stubborn-fs:
specifier: ^1.2.5
version: 1.2.5
devDependencies:
'@git.zone/tsbuild':
specifier: ^2.1.72
version: 2.1.72
'@types/node':
specifier: ^20.4.6
version: 20.11.8
packages:
/@apiglobal/typedrequest-interfaces@2.0.1:
resolution: {integrity: sha512-Oi7pNU4vKo5UvcCJmqkH43Us237Ws/Pp/WDYnwnonRnTmIMd+6QjNfN/gXcPnP6tbamk8r8Xzcz9mgnSDM2ysw==}
dev: true
/@git.zone/tsbuild@2.1.72:
resolution: {integrity: sha512-rVWM98chNjkt8pXdF5knGErZjM3GPnRXZYHVGECptxNvvhTol2DliM1OP8k3p3X5UOwEPV2sQVe//XzXs3BcUw==}
hasBin: true
dependencies:
'@push.rocks/early': 4.0.4
'@push.rocks/smartcli': 4.0.8
'@push.rocks/smartdelay': 3.0.5
'@push.rocks/smartfile': 11.0.4
'@push.rocks/smartlog': 3.0.3
'@push.rocks/smartpath': 5.0.11
'@push.rocks/smartpromise': 4.0.3
typescript: 5.3.3
dev: true
/@isaacs/cliui@8.0.2:
resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}
engines: {node: '>=12'}
dependencies:
string-width: 5.1.2
string-width-cjs: /string-width@4.2.3
strip-ansi: 7.1.0
strip-ansi-cjs: /strip-ansi@6.0.1
wrap-ansi: 8.1.0
wrap-ansi-cjs: /wrap-ansi@7.0.0
dev: true
/@pkgjs/parseargs@0.11.0:
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
requiresBuild: true
dev: true
optional: true
/@push.rocks/consolecolor@2.0.1:
resolution: {integrity: sha512-iQx+sjxmvhRXjnv8aMiaZu125ZWfyZKSylCvKUNjVrdhkmP2uPy2VWsvyRBS4UiieYHTY/i+HpQiFv4QZV2/Fg==}
dependencies:
ansi-256-colors: 1.1.0
dev: true
/@push.rocks/early@4.0.4:
resolution: {integrity: sha512-ak6/vqZ1PlFV08fSFQ6UwiBrr+K6IsfieZWWzT7eex1Ls6GvWEi8wZ3REFDPJq/qckNLWSgEy0EsqzRtltkaCA==}
dependencies:
'@push.rocks/consolecolor': 2.0.1
'@push.rocks/smartpromise': 4.0.3
dev: true
/@push.rocks/isounique@1.0.5:
resolution: {integrity: sha512-Z0BVqZZOCif1THTbIKWMgg0wxCzt9CyBtBBqQJiZ+jJ0KlQFrQHNHrPt81/LXe/L4x0cxWsn0bpL6W5DNSvNLw==}
dev: true
/@push.rocks/lik@6.0.12:
resolution: {integrity: sha512-/vzlOZ26gCmXZz67LeM2hJ+aNM49Jxvf3FKxLMXHhJwffd3LcV96MYbMfKzKR/za/bh5Itf3a6UjLL5mmN6Pew==}
dependencies:
'@push.rocks/smartdelay': 3.0.5
'@push.rocks/smartmatch': 2.0.0
'@push.rocks/smartpromise': 4.0.3
'@push.rocks/smartrx': 3.0.7
'@push.rocks/smarttime': 4.0.6
'@types/minimatch': 5.1.2
'@types/symbol-tree': 3.2.5
symbol-tree: 3.2.4
dev: true
/@push.rocks/smartcli@4.0.8:
resolution: {integrity: sha512-B4F3nqq7ko8tev1wxGdFnh/zSDDP8Q9LpEOb3wTf0jayyhYetFQ7n6zi4J9fhXYBKPkJSyQEBoOfRmgJyeLHkA==}
dependencies:
'@push.rocks/lik': 6.0.12
'@push.rocks/smartlog': 3.0.3
'@push.rocks/smartparam': 1.1.10
'@push.rocks/smartpromise': 4.0.3
'@push.rocks/smartrx': 3.0.7
yargs-parser: 21.1.1
dev: true
/@push.rocks/smartdelay@3.0.5:
resolution: {integrity: sha512-mUuI7kj2f7ztjpic96FvRIlf2RsKBa5arw81AHNsndbxO6asRcxuWL8dTVxouEIK8YsBUlj0AsrCkHhMbLQdHw==}
dependencies:
'@push.rocks/smartpromise': 4.0.3
dev: true
/@push.rocks/smartenv@5.0.12:
resolution: {integrity: sha512-tDEFwywzq0FNzRYc9qY2dRl2pgQuZG0G2/yml2RLWZWSW+Fn1EHshnKOGHz8o77W7zvu4hTgQQX42r/JY5XHTg==}
dependencies:
'@push.rocks/smartpromise': 4.0.3
dev: true
/@push.rocks/smartfile-interfaces@1.0.7:
resolution: {integrity: sha512-MeOl/200UOvSO4Pgq/DVFiBVZpL9gjOBQM+4XYNjSxda8c6VBvchHAntaFLQUlO8U1ckNaP9i+nMO4O4/0ymyw==}
dev: true
/@push.rocks/smartfile@11.0.4:
resolution: {integrity: sha512-NXAyqYE5zNUJ9Mu/t2oWUKu21CRUI4Dvlm56rKBSczCq5xeC7EwmamTzL3Nyn6Tmu1jBpYktYL4zIx17JJOB7w==}
dependencies:
'@push.rocks/lik': 6.0.12
'@push.rocks/smartdelay': 3.0.5
'@push.rocks/smartfile-interfaces': 1.0.7
'@push.rocks/smarthash': 3.0.4
'@push.rocks/smartjson': 5.0.10
'@push.rocks/smartmime': 1.0.6
'@push.rocks/smartpath': 5.0.11
'@push.rocks/smartpromise': 4.0.3
'@push.rocks/smartrequest': 2.0.21
'@push.rocks/smartstream': 3.0.30
'@types/fs-extra': 11.0.4
'@types/glob': 8.1.0
'@types/js-yaml': 4.0.9
fs-extra: 11.2.0
glob: 10.3.10
js-yaml: 4.1.0
dev: true
/@push.rocks/smarthash@3.0.4:
resolution: {integrity: sha512-HJ/fSx41jm0CvSaqMLa6b2nuNK5rHAqAeAq3dAB7Sq9BCPm2M0J5ZVDTzEAH8pS91XYniUiwuE0jwPERNn9hmw==}
dependencies:
'@push.rocks/smartjson': 5.0.10
'@push.rocks/smartpromise': 4.0.3
'@types/through2': 2.0.41
through2: 4.0.2
dev: true
/@push.rocks/smartjson@5.0.10:
resolution: {integrity: sha512-yuntSMGZ+XNHMrbS9RxotaD+eOgoNTcuDoWsttis+N3Mkc9DIam0pt/ER4NU8TgfMmhT/hKwQH+3DJceDzntoA==}
dependencies:
'@push.rocks/smartstring': 4.0.13
'@types/buffer-json': 2.0.3
buffer-json: 2.0.0
fast-json-stable-stringify: 2.1.0
lodash.clonedeep: 4.5.0
dev: true
/@push.rocks/smartlog-interfaces@3.0.0:
resolution: {integrity: sha512-dfRqiSolGQwaF9gWmkixWOoXZxcWBjK3u6A1CpcfhCbVr2VSUMIrZ5t74/DgdfedsTrhDqoD0NGezsMXF2pFHQ==}
dependencies:
'@apiglobal/typedrequest-interfaces': 2.0.1
dev: true
/@push.rocks/smartlog@3.0.3:
resolution: {integrity: sha512-E4UUSdbrf0TdSqI7LrUa3jgYQGKT6+ybSHuRcopFDt0W2/tBpY+/vPyAApJIa8iGFKJoi3oSTgYJbK90SwQwKg==}
dependencies:
'@push.rocks/isounique': 1.0.5
'@push.rocks/smartlog-interfaces': 3.0.0
dev: true
/@push.rocks/smartmatch@2.0.0:
resolution: {integrity: sha512-MBzP++1yNIBeox71X6VxpIgZ8m4bXnJpZJ4nWVH6IWpmO38MXTu4X0QF8tQnyT4LFcwvc9iiWaD15cstHa7Mmw==}
dependencies:
matcher: 5.0.0
dev: true
/@push.rocks/smartmime@1.0.6:
resolution: {integrity: sha512-PHd+I4UcsnOATNg8wjDsSAmmJ4CwQFrQCNzd0HSJMs4ZpiK3Ya91almd6GLpDPU370U4HFh4FaPF4eEAI6vkJQ==}
dependencies:
'@types/mime-types': 2.1.4
mime-types: 2.1.35
dev: true
/@push.rocks/smartparam@1.1.10:
resolution: {integrity: sha512-2WDAUtc7GH+E0QszsiuXRdLPnJ/edlS2zPtFgfNpA0LJ8tJ5J9lyx6zhM39k4rKzKtK7bnjWHDb2tHE9zaOBYw==}
deprecated: deprecated in favour of @push.rocks/smartobject
dependencies:
'@push.rocks/smartpromise': 4.0.3
minimatch: 9.0.3
dev: true
/@push.rocks/smartpath@5.0.11:
resolution: {integrity: sha512-dqdd7KTby0AdaWYC9gVoHDTUIixFhEvo+mmdaTdNshZsfHNkm/EDV25dA+9gJ8/yoyuCYmrwmByNYy9a+xFUeQ==}
dev: true
/@push.rocks/smartpromise@4.0.3:
resolution: {integrity: sha512-z3lIso4/6KK3c6NFTVGZ7AOBsGURf8ha3qQtX/OxjZFk5dqS//8PLd0XqghVdIaUlRGmJ7Sfds/efZERWn1tAg==}
dev: true
/@push.rocks/smartrequest@2.0.21:
resolution: {integrity: sha512-btk9GbiMNxNcEgJEqTq9qMFJ/6ua6oG4q49v+8ujKAXU50vFn1WQ/H0VAyeu9LMa5GCcRwUhNNDdwpLVGVbrBg==}
dependencies:
'@push.rocks/smartpromise': 4.0.3
'@push.rocks/smarturl': 3.0.7
agentkeepalive: 4.5.0
form-data: 4.0.0
dev: true
/@push.rocks/smartrx@3.0.7:
resolution: {integrity: sha512-qCWy0s3RLAgGSnaw/Gu0BNaJ59CsI6RK5OJDCCqxc7P2X/S755vuLtnAR5/0dEjdhCHXHX9ytPZx+o9g/CNiyA==}
dependencies:
'@push.rocks/smartpromise': 4.0.3
rxjs: 7.8.1
dev: true
/@push.rocks/smartstream@3.0.30:
resolution: {integrity: sha512-+izraXkILJJIy99PzP2LYahaW+g/35bTi/UxD7FeuOYbTaigode6Q3swvs0nrK6yu+A9x6RfoWV4JAJjd3Y87g==}
dependencies:
'@push.rocks/lik': 6.0.12
'@push.rocks/smartpromise': 4.0.3
'@push.rocks/smartrx': 3.0.7
dev: true
/@push.rocks/smartstring@4.0.13:
resolution: {integrity: sha512-iEAch6fYC+VijBYWFfRif5Wj5KxdUgC2Xnn0NNgDFrBmI14HsECcPbZ0YdESawRVD27pLYYZJCCbu/M/Llo1kg==}
dependencies:
'@push.rocks/isounique': 1.0.5
'@push.rocks/smartenv': 5.0.12
'@types/randomatic': 3.1.5
buffer: 6.0.3
crypto-random-string: 5.0.0
js-base64: 3.7.6
normalize-newline: 4.1.0
randomatic: 3.1.1
strip-indent: 4.0.0
url: 0.11.3
dev: true
/@push.rocks/smarttime@4.0.6:
resolution: {integrity: sha512-1whOow0YJw/TbN758TedRRxApoZbsvyxCVpoGjXh7DE/fEEgs7RCr4vVF5jYpyXNQuNMLpKJcTsSfyQ6RvH4Aw==}
dependencies:
'@push.rocks/lik': 6.0.12
'@push.rocks/smartdelay': 3.0.5
'@push.rocks/smartpromise': 4.0.3
croner: 7.0.5
dayjs: 1.11.10
is-nan: 1.3.2
pretty-ms: 8.0.0
dev: true
/@push.rocks/smarturl@3.0.7:
resolution: {integrity: sha512-nx4EWjQD9JeO7QVbOsxd1PFeDQYoSQOOOYCZ+r7QWXHLJG52iYzgvJDCQyX6p705HDkYMJWozW2ZzhR22qLKbw==}
dev: true
/@types/buffer-json@2.0.3:
resolution: {integrity: sha512-ItD4UfF3Q5jA+PEV6ZUWEHvlWaXJbd0rpuBKOIrEebM053FHaJddKsgUf0vy7nLSTs44nqFj3Mh8J3TiT0xv4g==}
dev: true
/@types/fs-extra@11.0.4:
resolution: {integrity: sha512-yTbItCNreRooED33qjunPthRcSjERP1r4MqCZc7wv0u2sUkzTFp45tgUfS5+r7FrZPdmCCNflLhVSP/o+SemsQ==}
dependencies:
'@types/jsonfile': 6.1.4
'@types/node': 20.11.8
dev: true
/@types/glob@8.1.0:
resolution: {integrity: sha512-IO+MJPVhoqz+28h1qLAcBEH2+xHMK6MTyHJc7MTnnYb6wsoLR29POVGJ7LycmVXIqyy/4/2ShP5sUwTXuOwb/w==}
dependencies:
'@types/minimatch': 5.1.2
'@types/node': 20.11.8
dev: true
/@types/js-yaml@4.0.9:
resolution: {integrity: sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==}
dev: true
/@types/jsonfile@6.1.4:
resolution: {integrity: sha512-D5qGUYwjvnNNextdU59/+fI+spnwtTFmyQP0h+PfIOSkNfpU6AOICUOkm4i0OnSk+NyjdPJrxCDro0sJsWlRpQ==}
dependencies:
'@types/node': 20.11.8
dev: true
/@types/mime-types@2.1.4:
resolution: {integrity: sha512-lfU4b34HOri+kAY5UheuFMWPDOI+OPceBSHZKp69gEyTL/mmJ4cnU6Y/rlme3UL3GyOn6Y42hyIEw0/q8sWx5w==}
dev: true
/@types/minimatch@5.1.2:
resolution: {integrity: sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA==}
dev: true
/@types/node@20.11.8:
resolution: {integrity: sha512-i7omyekpPTNdv4Jb/Rgqg0RU8YqLcNsI12quKSDkRXNfx7Wxdm6HhK1awT3xTgEkgxPn3bvnSpiEAc7a7Lpyow==}
dependencies:
undici-types: 5.26.5
dev: true
/@types/randomatic@3.1.5:
resolution: {integrity: sha512-VCwCTw6qh1pRRw+5rNTAwqPmf6A+hdrkdM7dBpZVmhl7g+em3ONXlYK/bWPVKqVGMWgP0d1bog8Vc/X6zRwRRQ==}
dev: true
/@types/symbol-tree@3.2.5:
resolution: {integrity: sha512-zXnnyENt1TYQcS21MkPaJCVjfcPq7p7yc5mo5JACuumXp6sly5jnlS0IokHd+xmmuCbx6V7JqkMBpswR+nZAcw==}
dev: true
/@types/through2@2.0.41:
resolution: {integrity: sha512-ryQ0tidWkb1O1JuYvWKyMLYEtOWDqF5mHerJzKz/gQpoAaJq2l/dsMPBF0B5BNVT34rbARYJ5/tsZwLfUi2kwQ==}
dependencies:
'@types/node': 20.11.8
dev: true
/agentkeepalive@4.5.0:
resolution: {integrity: sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==}
engines: {node: '>= 8.0.0'}
dependencies:
humanize-ms: 1.2.1
dev: true
/ansi-256-colors@1.1.0:
resolution: {integrity: sha1-kQ3lDvzHwJ49gvL4er1rcAwYgYo=}
engines: {node: '>=0.10.0'}
dev: true
/ansi-regex@5.0.1:
resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}
engines: {node: '>=8'}
dev: true
/ansi-regex@6.0.1:
resolution: {integrity: sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==}
engines: {node: '>=12'}
dev: true
/ansi-styles@4.3.0:
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
engines: {node: '>=8'}
dependencies:
color-convert: 2.0.1
dev: true
/ansi-styles@6.2.1:
resolution: {integrity: sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==}
engines: {node: '>=12'}
dev: true
/argparse@2.0.1:
resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
dev: true
/asynckit@0.4.0:
resolution: {integrity: sha1-x57Zf380y48robyXkLzDZkdLS3k=}
dev: true
/balanced-match@1.0.2:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
dev: true
/base64-js@1.5.1:
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
dev: true
/brace-expansion@2.0.1:
resolution: {integrity: sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==}
dependencies:
balanced-match: 1.0.2
dev: true
/buffer-json@2.0.0:
resolution: {integrity: sha512-+jjPFVqyfF1esi9fvfUs3NqM0pH1ziZ36VP4hmA/y/Ssfo/5w5xHKfTw9BwQjoJ1w/oVtpLomqwUHKdefGyuHw==}
dev: true
/buffer@6.0.3:
resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==}
dependencies:
base64-js: 1.5.1
ieee754: 1.2.1
dev: true
/call-bind@1.0.5:
resolution: {integrity: sha512-C3nQxfFZxFRVoJoGKKI8y3MOEo129NQ+FgQ08iye+Mk4zNZZGdjfs06bVTr+DBSlA66Q2VEcMki/cUCP4SercQ==}
dependencies:
function-bind: 1.1.2
get-intrinsic: 1.2.2
set-function-length: 1.2.0
dev: true
/color-convert@2.0.1:
resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
engines: {node: '>=7.0.0'}
dependencies:
color-name: 1.1.4
dev: true
/color-name@1.1.4:
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
dev: true
/combined-stream@1.0.8:
resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
engines: {node: '>= 0.8'}
dependencies:
delayed-stream: 1.0.0
dev: true
/croner@7.0.5:
resolution: {integrity: sha512-15HLCD7iXnMe5km54yc4LN5BH+Cg9uCQvbkJ0acHxFffE29w3Uvgb9s/l310UCVUgMwGSBNw9BAHsEb5uMgj1g==}
engines: {node: '>=6.0'}
dev: true
/cross-spawn@7.0.3:
resolution: {integrity: sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==}
engines: {node: '>= 8'}
dependencies:
path-key: 3.1.1
shebang-command: 2.0.0
which: 2.0.2
dev: true
/crypto-random-string@5.0.0:
resolution: {integrity: sha512-KWjTXWwxFd6a94m5CdRGW/t82Tr8DoBc9dNnPCAbFI1EBweN6v1tv8y4Y1m7ndkp/nkIBRxUxAzpaBnR2k3bcQ==}
engines: {node: '>=14.16'}
dependencies:
type-fest: 2.19.0
dev: true
/dayjs@1.11.10:
resolution: {integrity: sha512-vjAczensTgRcqDERK0SR2XMwsF/tSvnvlv6VcF2GIhg6Sx4yOIt/irsr1RDJsKiIyBzJDpCoXiWWq28MqH2cnQ==}
dev: true
/define-data-property@1.1.1:
resolution: {integrity: sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==}
engines: {node: '>= 0.4'}
dependencies:
get-intrinsic: 1.2.2
gopd: 1.0.1
has-property-descriptors: 1.0.1
dev: true
/define-properties@1.2.1:
resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}
engines: {node: '>= 0.4'}
dependencies:
define-data-property: 1.1.1
has-property-descriptors: 1.0.1
object-keys: 1.1.1
dev: true
/delayed-stream@1.0.0:
resolution: {integrity: sha1-3zrhmayt+31ECqrgsp4icrJOxhk=}
engines: {node: '>=0.4.0'}
dev: true
/eastasianwidth@0.2.0:
resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
dev: true
/emoji-regex@8.0.0:
resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
dev: true
/emoji-regex@9.2.2:
resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}
dev: true
/escape-string-regexp@5.0.0:
resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==}
engines: {node: '>=12'}
dev: true
/fast-json-stable-stringify@2.1.0:
resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==}
dev: true
/foreground-child@3.1.1:
resolution: {integrity: sha512-TMKDUnIte6bfb5nWv7V/caI169OHgvwjb7V4WkeUvbQQdjr5rWKqHFiKWb/fcOwB+CzBT+qbWjvj+DVwRskpIg==}
engines: {node: '>=14'}
dependencies:
cross-spawn: 7.0.3
signal-exit: 4.1.0
dev: true
/form-data@4.0.0:
resolution: {integrity: sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==}
engines: {node: '>= 6'}
dependencies:
asynckit: 0.4.0
combined-stream: 1.0.8
mime-types: 2.1.35
dev: true
/fs-extra@11.2.0:
resolution: {integrity: sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==}
engines: {node: '>=14.14'}
dependencies:
graceful-fs: 4.2.11
jsonfile: 6.1.0
universalify: 2.0.1
dev: true
/function-bind@1.1.2:
resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}
dev: true
/get-intrinsic@1.2.2:
resolution: {integrity: sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==}
dependencies:
function-bind: 1.1.2
has-proto: 1.0.1
has-symbols: 1.0.3
hasown: 2.0.0
dev: true
/glob@10.3.10:
resolution: {integrity: sha512-fa46+tv1Ak0UPK1TOy/pZrIybNNt4HCv7SDzwyfiOZkvZLEbjsZkJBPtDHVshZjbecAoAGSC20MjLDG/qr679g==}
engines: {node: '>=16 || 14 >=14.17'}
hasBin: true
dependencies:
foreground-child: 3.1.1
jackspeak: 2.3.6
minimatch: 9.0.3
minipass: 7.0.4
path-scurry: 1.10.1
dev: true
/gopd@1.0.1:
resolution: {integrity: sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==}
dependencies:
get-intrinsic: 1.2.2
dev: true
/graceful-fs@4.2.11:
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
dev: true
/has-property-descriptors@1.0.1:
resolution: {integrity: sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==}
dependencies:
get-intrinsic: 1.2.2
dev: true
/has-proto@1.0.1:
resolution: {integrity: sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==}
engines: {node: '>= 0.4'}
dev: true
/has-symbols@1.0.3:
resolution: {integrity: sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==}
engines: {node: '>= 0.4'}
dev: true
/hasown@2.0.0:
resolution: {integrity: sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==}
engines: {node: '>= 0.4'}
dependencies:
function-bind: 1.1.2
dev: true
/humanize-ms@1.2.1:
resolution: {integrity: sha1-xG4xWaKT9riW2ikxbYtv6Lt5u+0=}
dependencies:
ms: 2.1.3
dev: true
/ieee754@1.2.1:
resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==}
dev: true
/inherits@2.0.4:
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
dev: true
/is-fullwidth-code-point@3.0.0:
resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}
engines: {node: '>=8'}
dev: true
/is-nan@1.3.2:
resolution: {integrity: sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w==}
engines: {node: '>= 0.4'}
dependencies:
call-bind: 1.0.5
define-properties: 1.2.1
dev: true
/is-number@4.0.0:
resolution: {integrity: sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==}
engines: {node: '>=0.10.0'}
dev: true
/isexe@2.0.0:
resolution: {integrity: sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=}
dev: true
/jackspeak@2.3.6:
resolution: {integrity: sha512-N3yCS/NegsOBokc8GAdM8UcmfsKiSS8cipheD/nivzr700H+nsMOxJjQnvwOcRYVuFkdH0wGUvW2WbXGmrZGbQ==}
engines: {node: '>=14'}
dependencies:
'@isaacs/cliui': 8.0.2
optionalDependencies:
'@pkgjs/parseargs': 0.11.0
dev: true
/js-base64@3.7.6:
resolution: {integrity: sha512-NPrWuHFxFUknr1KqJRDgUQPexQF0uIJWjeT+2KjEePhitQxQEx5EJBG1lVn5/hc8aLycTpXrDOgPQ6Zq+EDiTA==}
dev: true
/js-yaml@4.1.0:
resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==}
hasBin: true
dependencies:
argparse: 2.0.1
dev: true
/jsonfile@6.1.0:
resolution: {integrity: sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==}
dependencies:
universalify: 2.0.1
optionalDependencies:
graceful-fs: 4.2.11
dev: true
/kind-of@6.0.3:
resolution: {integrity: sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==}
engines: {node: '>=0.10.0'}
dev: true
/lodash.clonedeep@4.5.0:
resolution: {integrity: sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=}
dev: true
/lru-cache@10.2.0:
resolution: {integrity: sha512-2bIM8x+VAf6JT4bKAljS1qUWgMsqZRPGJS6FSahIMPVvctcNhyVp7AJu7quxOW9jwkryBReKZY5tY5JYv2n/7Q==}
engines: {node: 14 || >=16.14}
dev: true
/matcher@5.0.0:
resolution: {integrity: sha512-s2EMBOWtXFc8dgqvoAzKJXxNHibcdJMV0gwqKUaw9E2JBJuGUK7DrNKrA6g/i+v72TT16+6sVm5mS3thaMLQUw==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
dependencies:
escape-string-regexp: 5.0.0
dev: true
/math-random@1.0.4:
resolution: {integrity: sha512-rUxjysqif/BZQH2yhd5Aaq7vXMSx9NdEsQcyA07uEzIvxgI7zIr33gGsh+RU0/XjmQpCW7RsVof1vlkvQVCK5A==}
dev: true
/mime-db@1.52.0:
resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}
engines: {node: '>= 0.6'}
dev: true
/mime-types@2.1.35:
resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}
engines: {node: '>= 0.6'}
dependencies:
mime-db: 1.52.0
dev: true
/min-indent@1.0.1:
resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}
engines: {node: '>=4'}
dev: true
/minimatch@9.0.3:
resolution: {integrity: sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==}
engines: {node: '>=16 || 14 >=14.17'}
dependencies:
brace-expansion: 2.0.1
dev: true
/minipass@7.0.4:
resolution: {integrity: sha512-jYofLM5Dam9279rdkWzqHozUo4ybjdZmCsDHePy5V/PbBcVMiSZR97gmAy45aqi8CK1lG2ECd356FU86avfwUQ==}
engines: {node: '>=16 || 14 >=14.17'}
dev: true
/ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
dev: true
/normalize-newline@4.1.0:
resolution: {integrity: sha512-ff4jKqMI8Xl50/4Mms/9jPobzAV/UK+kXG2XJ/7AqOmxIx8mqfqTIHYxuAnEgJ2AQeBbLnlbmZ5+38Y9A0w/YA==}
engines: {node: '>=12'}
dependencies:
replace-buffer: 1.2.1
dev: true
/object-inspect@1.13.1:
resolution: {integrity: sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==}
dev: true
/object-keys@1.1.1:
resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}
engines: {node: '>= 0.4'}
dev: true
/parse-ms@3.0.0:
resolution: {integrity: sha512-Tpb8Z7r7XbbtBTrM9UhpkzzaMrqA2VXMT3YChzYltwV3P3pM6t8wl7TvpMnSTosz1aQAdVib7kdoys7vYOPerw==}
engines: {node: '>=12'}
dev: true
/path-key@3.1.1:
resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
engines: {node: '>=8'}
dev: true
/path-scurry@1.10.1:
resolution: {integrity: sha512-MkhCqzzBEpPvxxQ71Md0b1Kk51W01lrYvlMzSUaIzNsODdd7mqhiimSZlr+VegAz5Z6Vzt9Xg2ttE//XBhH3EQ==}
engines: {node: '>=16 || 14 >=14.17'}
dependencies:
lru-cache: 10.2.0
minipass: 7.0.4
dev: true
/pretty-ms@8.0.0:
resolution: {integrity: sha512-ASJqOugUF1bbzI35STMBUpZqdfYKlJugy6JBziGi2EE+AL5JPJGSzvpeVXojxrr0ViUYoToUjb5kjSEGf7Y83Q==}
engines: {node: '>=14.16'}
dependencies:
parse-ms: 3.0.0
dev: true
/punycode@1.4.1:
resolution: {integrity: sha1-wNWmOycYgArY4esPpSachN1BhF4=}
dev: true
/qs@6.11.2:
resolution: {integrity: sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==}
engines: {node: '>=0.6'}
dependencies:
side-channel: 1.0.4
dev: true
/randomatic@3.1.1:
resolution: {integrity: sha512-TuDE5KxZ0J461RVjrJZCJc+J+zCkTb1MbH9AQUq68sMhOMcy9jLcb3BrZKgp9q9Ncltdg4QVqWrH02W2EFFVYw==}
engines: {node: '>= 0.10.0'}
dependencies:
is-number: 4.0.0
kind-of: 6.0.3
math-random: 1.0.4
dev: true
/readable-stream@3.6.2:
resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}
engines: {node: '>= 6'}
dependencies:
inherits: 2.0.4
string_decoder: 1.3.0
util-deprecate: 1.0.2
dev: true
/replace-buffer@1.2.1:
resolution: {integrity: sha512-ly3OKwKu+3T55DjP5PjIMzxgz9lFx6dQnBmAIxryZyRKl8f22juy12ShOyuq8WrQE5UlFOseZgQZDua0iF9DHw==}
engines: {node: '>=4'}
dev: true
/rxjs@7.8.1:
resolution: {integrity: sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==}
dependencies:
tslib: 2.6.2
dev: true
/safe-buffer@5.2.1:
resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}
dev: true
/set-function-length@1.2.0:
resolution: {integrity: sha512-4DBHDoyHlM1IRPGYcoxexgh67y4ueR53FKV1yyxwFMY7aCqcN/38M1+SwZ/qJQ8iLv7+ck385ot4CcisOAPT9w==}
engines: {node: '>= 0.4'}
dependencies:
define-data-property: 1.1.1
function-bind: 1.1.2
get-intrinsic: 1.2.2
gopd: 1.0.1
has-property-descriptors: 1.0.1
dev: true
/shebang-command@2.0.0:
resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}
engines: {node: '>=8'}
dependencies:
shebang-regex: 3.0.0
dev: true
/shebang-regex@3.0.0:
resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}
engines: {node: '>=8'}
dev: true
/side-channel@1.0.4:
resolution: {integrity: sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==}
dependencies:
call-bind: 1.0.5
get-intrinsic: 1.2.2
object-inspect: 1.13.1
dev: true
/signal-exit@4.1.0:
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
engines: {node: '>=14'}
dev: true
/string-width@4.2.3:
resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}
engines: {node: '>=8'}
dependencies:
emoji-regex: 8.0.0
is-fullwidth-code-point: 3.0.0
strip-ansi: 6.0.1
dev: true
/string-width@5.1.2:
resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==}
engines: {node: '>=12'}
dependencies:
eastasianwidth: 0.2.0
emoji-regex: 9.2.2
strip-ansi: 7.1.0
dev: true
/string_decoder@1.3.0:
resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}
dependencies:
safe-buffer: 5.2.1
dev: true
/strip-ansi@6.0.1:
resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
engines: {node: '>=8'}
dependencies:
ansi-regex: 5.0.1
dev: true
/strip-ansi@7.1.0:
resolution: {integrity: sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==}
engines: {node: '>=12'}
dependencies:
ansi-regex: 6.0.1
dev: true
/strip-indent@4.0.0:
resolution: {integrity: sha512-mnVSV2l+Zv6BLpSD/8V87CW/y9EmmbYzGCIavsnsI6/nwn26DwffM/yztm30Z/I2DY9wdS3vXVCMnHDgZaVNoA==}
engines: {node: '>=12'}
dependencies:
min-indent: 1.0.1
dev: true
/stubborn-fs@1.2.5:
resolution: {integrity: sha512-H2N9c26eXjzL/S/K+i/RHHcFanE74dptvvjM8iwzwbVcWY/zjBbgRqF3K0DY4+OD+uTTASTBvDoxPDaPN02D7g==}
dev: false
/symbol-tree@3.2.4:
resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
dev: true
/through2@4.0.2:
resolution: {integrity: sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==}
dependencies:
readable-stream: 3.6.2
dev: true
/tslib@2.6.2:
resolution: {integrity: sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==}
dev: true
/type-fest@2.19.0:
resolution: {integrity: sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==}
engines: {node: '>=12.20'}
dev: true
/typescript@5.3.3:
resolution: {integrity: sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==}
engines: {node: '>=14.17'}
hasBin: true
dev: true
/undici-types@5.26.5:
resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==}
dev: true
/universalify@2.0.1:
resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}
engines: {node: '>= 10.0.0'}
dev: true
/url@0.11.3:
resolution: {integrity: sha512-6hxOLGfZASQK/cijlZnZJTq8OXAkt/3YGfQX45vvMYXpZoo8NdWZcY73K108Jf759lS1Bv/8wXnHDTSz17dSRw==}
dependencies:
punycode: 1.4.1
qs: 6.11.2
dev: true
/util-deprecate@1.0.2:
resolution: {integrity: sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=}
dev: true
/which@2.0.2:
resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}
engines: {node: '>= 8'}
hasBin: true
dependencies:
isexe: 2.0.0
dev: true
/wrap-ansi@7.0.0:
resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}
engines: {node: '>=10'}
dependencies:
ansi-styles: 4.3.0
string-width: 4.2.3
strip-ansi: 6.0.1
dev: true
/wrap-ansi@8.1.0:
resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==}
engines: {node: '>=12'}
dependencies:
ansi-styles: 6.2.1
string-width: 5.1.2
strip-ansi: 7.1.0
dev: true
/yargs-parser@21.1.1:
resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
engines: {node: '>=12'}
dev: true

242
readme.md 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 not supported under Linux, so if you need to support Linux at all you are out of luck already.
- Even if you only need to support macOS or Windows, 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 with to make Watcher, and providing some good ideas for how to write good tests for it.
## License
MIT © Fabio Spampinato

167
test/hooks.js 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
test/index.js Normal file

File diff suppressed because it is too large Load Diff

112
test/tree.js 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;

32
ts/constants.ts 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};

152
ts/dettle/debounce.ts Normal file
View File

@ -0,0 +1,152 @@
/* IMPORT */
import type {FN, Debounced} from './types.js';
/* MAIN */
const debounce = <Args extends unknown[]> ( fn: FN<Args, unknown>, wait: number = 1, options?: { leading?: boolean, trailing?: boolean, maxWait?: number } ): Debounced<Args> => {
/* VARIABLES */
wait = Math.max ( 1, wait );
const leading = options?.leading ?? false;
const trailing = options?.trailing ?? true;
const maxWait = Math.max ( options?.maxWait ?? Infinity, wait );
let args: Args | undefined;
let timeout: ReturnType<typeof setTimeout> | undefined;
let timestampCall = 0;
let timestampInvoke = 0;
/* HELPERS */
const getInstantData = (): [number, boolean] => {
const timestamp = Date.now ();
const elapsedCall = timestamp - timestampCall;
const elapsedInvoke = timestamp - timestampInvoke;
const isInvoke = ( elapsedCall >= wait || elapsedInvoke >= maxWait );
return [timestamp, isInvoke];
};
const invoke = ( timestamp: number ): void => {
timestampInvoke = timestamp;
if ( !args ) return; // This should never happen
const _args = args;
args = undefined;
fn.apply ( undefined, _args );
};
const onCancel = (): void => {
resetTimeout ( 0 );
};
const onFlush = (): void => {
if ( !timeout ) return;
onCancel ();
invoke ( Date.now () );
};
const onLeading = ( timestamp: number ): void => {
timestampInvoke = timestamp;
if ( leading ) return invoke ( timestamp );
};
const onTrailing = ( timestamp: number ): void => {
if ( trailing && args ) return invoke ( timestamp );
args = undefined;
};
const onTimeout = (): void => {
timeout = undefined;
const [timestamp, isInvoking] = getInstantData ();
if ( isInvoking ) return onTrailing ( timestamp );
return updateTimeout ( timestamp );
};
const updateTimeout = ( timestamp: number ): void => {
const elapsedCall = timestamp - timestampCall;
const elapsedInvoke = timestamp - timestampInvoke;
const remainingCall = wait - elapsedCall;
const remainingInvoke = maxWait - elapsedInvoke;
const ms = Math.min ( remainingCall, remainingInvoke );
return resetTimeout ( ms );
};
const resetTimeout = ( ms: number ): void => {
if ( timeout ) clearTimeout ( timeout );
if ( ms <= 0 ) return;
timeout = setTimeout ( onTimeout, ms );
};
/* DEBOUNCED */
const debounced = ( ...argsLatest: Args ): void => {
const [timestamp, isInvoking] = getInstantData ();
const hadTimeout = !!timeout;
args = argsLatest;
timestampCall = timestamp;
if ( isInvoking || !timeout ) resetTimeout ( wait );
if ( isInvoking ) {
if ( !hadTimeout ) return onLeading ( timestamp );
return invoke ( timestamp );
}
};
/* DEBOUNCED UTILITIES */
debounced.cancel = onCancel;
debounced.flush = onFlush;
/* RETURN */
return debounced;
};
/* EXPORT */
export default debounce;

9
ts/dettle/index.ts Executable file
View File

@ -0,0 +1,9 @@
/* IMPORT */
import debounce from './debounce.js';
import throttle from './throttle.js';
/* EXPORT */
export {debounce, throttle};

21
ts/dettle/license Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2023-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.

21
ts/dettle/throttle.ts Normal file
View File

@ -0,0 +1,21 @@
/* IMPORT */
import debounce from './debounce.js';
import type {FN, Throttled} from './types.js';
/* MAIN */
const throttle = <Args extends unknown[]> ( fn: FN<Args, unknown>, wait: number = 1, options?: { leading?: boolean, trailing?: boolean } ): Throttled<Args> => {
return debounce ( fn, wait, {
maxWait: wait,
leading: options?.leading ?? true,
trailing: options?.trailing ?? true
});
};
/* EXPORT */
export default throttle;

14
ts/dettle/types.ts Normal file
View File

@ -0,0 +1,14 @@
/* MAIN */
type Callback = () => void;
type FN<Args extends unknown[], Return> = ( ...args: Args ) => Return;
type Debounced<Args extends unknown[]> = FN<Args, void> & { cancel: Callback, flush: Callback };
type Throttled<Args extends unknown[]> = FN<Args, void> & { cancel: Callback, flush: Callback };
/* EXPORT */
export type {Callback, FN, Debounced, Throttled};

38
ts/enums.ts 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
ts/lazy_map_set.ts Normal file
View File

@ -0,0 +1,144 @@
/* IMPORT */
import Utils from './utils.js';
/* 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;

View File

@ -0,0 +1,8 @@
/* MAIN */
const NOOP = (): void => {};
/* EXPORT */
export {NOOP};

53
ts/promise-make-naked/index.ts Executable file
View File

@ -0,0 +1,53 @@
/* IMPORT */
import {NOOP} from './constants.js';
import type {PromiseResolve, PromiseReject, Result} from './types.js';
/* MAIN */
const makeNakedPromise = <T> (): Result<T> => {
let resolve: PromiseResolve<T> = NOOP;
let reject: PromiseReject = NOOP;
let resolved = false;
let rejected = false;
const promise = new Promise<T> ( ( res, rej ): void => {
resolve = value => {
resolved = true;
return res ( value );
};
reject = value => {
rejected = true;
return rej ( value );
};
});
const isPending = (): boolean => !resolved && !rejected;
const isResolved = (): boolean => resolved;
const isRejected = (): boolean => rejected;
return {promise, resolve, reject, isPending, isResolved, isRejected};
};
/* UTILITIES */
makeNakedPromise.wrap = async <T> ( fn: ( result: Result<T> ) => void ): Promise<T> => {
const result = makeNakedPromise<T> ();
await fn ( result );
return result.promise;
};
/* EXPORT */
export default makeNakedPromise;

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2021-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.

View File

@ -0,0 +1,19 @@
/* MAIN */
type PromiseResolve <T> = ( value: T | PromiseLike<T> ) => void;
type PromiseReject = ( reason?: unknown ) => void;
type Result <T> = {
promise: Promise<T>,
resolve: PromiseResolve<T>,
reject: PromiseReject,
isPending: () => boolean,
isResolved: () => boolean,
isRejected: () => boolean
};
/* EXPORT */
export type {PromiseResolve, PromiseReject, Result};

246
ts/tiny-readdir/index.ts Executable file
View File

@ -0,0 +1,246 @@
/* IMPORT */
import fs from 'node:fs';
import path from 'node:path';
import {isFunction, makeCounterPromise} from './utils.js';
import type {Options, ResultDirectory, ResultDirectories, Result} from './types.js';
/* MAIN */
//TODO: Streamline the type of dirnmaps
const readdir = ( rootPath: string, options?: Options ): Promise<Result> => {
const followSymlinks = options?.followSymlinks ?? false;
const maxDepth = options?.depth ?? Infinity;
const maxPaths = options?.limit ?? Infinity;
const ignore = options?.ignore ?? (() => false);
const isIgnored = isFunction ( ignore ) ? ignore : ( targetPath: string ) => ignore.test ( targetPath );
const signal = options?.signal ?? { aborted: false };
const directories: string[] = [];
const directoriesNames: Set<string> = new Set ();
const directoriesNamesToPaths: Record<string, string[]> = {};
const files: string[] = [];
const filesNames: Set<string> = new Set ();
const filesNamesToPaths: Record<string, string[]> = {};
const symlinks: string[] = [];
const symlinksNames: Set<string> = new Set ();
const symlinksNamesToPaths: Record<string, string[]> = {};
const map: ResultDirectories = {};
const visited = new Set<string> ();
const resultEmpty: Result = { directories: [], directoriesNames: new Set (), directoriesNamesToPaths: {}, files: [], filesNames: new Set (), filesNamesToPaths: {}, symlinks: [], symlinksNames: new Set (), symlinksNamesToPaths: {}, map: {} };
const result: Result = { directories, directoriesNames, directoriesNamesToPaths, files, filesNames, filesNamesToPaths, symlinks, symlinksNames, symlinksNamesToPaths, map };
const {promise, increment, decrement} = makeCounterPromise ();
let foundPaths = 0;
const handleDirectory = ( dirmap: ResultDirectory, subPath: string, name: string, depth: number ): void => {
if ( visited.has ( subPath ) ) return;
if ( foundPaths >= maxPaths ) return;
foundPaths += 1;
dirmap.directories.push ( subPath );
dirmap.directoriesNames.add ( name );
// dirmap.directoriesNamesToPaths.propertyIsEnumerable(name) || ( dirmap.directoriesNamesToPaths[name] = [] );
// dirmap.directoriesNamesToPaths[name].push ( subPath );
directories.push ( subPath );
directoriesNames.add ( name );
directoriesNamesToPaths.propertyIsEnumerable(name) || ( directoriesNamesToPaths[name] = [] );
directoriesNamesToPaths[name].push ( subPath );
visited.add ( subPath );
if ( depth >= maxDepth ) return;
if ( foundPaths >= maxPaths ) return;
populateResultFromPath ( subPath, depth + 1 );
};
const handleFile = ( dirmap: ResultDirectory, subPath: string, name: string ): void => {
if ( visited.has ( subPath ) ) return;
if ( foundPaths >= maxPaths ) return;
foundPaths += 1;
dirmap.files.push ( subPath );
dirmap.filesNames.add ( name );
// dirmap.filesNamesToPaths.propertyIsEnumerable(name) || ( dirmap.filesNamesToPaths[name] = [] );
// dirmap.filesNamesToPaths[name].push ( subPath );
files.push ( subPath );
filesNames.add ( name );
filesNamesToPaths.propertyIsEnumerable(name) || ( filesNamesToPaths[name] = [] );
filesNamesToPaths[name].push ( subPath );
visited.add ( subPath );
};
const handleSymlink = ( dirmap: ResultDirectory, subPath: string, name: string, depth: number ): void => {
if ( visited.has ( subPath ) ) return;
if ( foundPaths >= maxPaths ) return;
foundPaths += 1;
dirmap.symlinks.push ( subPath );
dirmap.symlinksNames.add ( name );
// dirmap.symlinksNamesToPaths.propertyIsEnumerable(name) || ( dirmap.symlinksNamesToPaths[name] = [] );
// dirmap.symlinksNamesToPaths[name].push ( subPath );
symlinks.push ( subPath );
symlinksNames.add ( name );
symlinksNamesToPaths.propertyIsEnumerable(name) || ( symlinksNamesToPaths[name] = [] );
symlinksNamesToPaths[name].push ( subPath );
visited.add ( subPath );
if ( !followSymlinks ) return;
if ( depth >= maxDepth ) return;
if ( foundPaths >= maxPaths ) return;
populateResultFromSymlink ( subPath, depth + 1 );
};
const handleStat = ( dirmap: ResultDirectory, rootPath: string, name: string, stat: fs.Stats, depth: number ): void => {
if ( signal.aborted ) return;
if ( isIgnored ( rootPath ) ) return;
if ( stat.isDirectory () ) {
handleDirectory ( dirmap, rootPath, name, depth );
} else if ( stat.isFile () ) {
handleFile ( dirmap, rootPath, name );
} else if ( stat.isSymbolicLink () ) {
handleSymlink ( dirmap, rootPath, name, depth );
}
};
const handleDirent = ( dirmap: ResultDirectory, rootPath: string, dirent: fs.Dirent, depth: number ): void => {
if ( signal.aborted ) return;
const separator = ( rootPath === path.sep ) ? '' : path.sep;
const name = dirent.name;
const subPath = `${rootPath}${separator}${name}`;
if ( isIgnored ( subPath ) ) return;
if ( dirent.isDirectory () ) {
handleDirectory ( dirmap, subPath, name, depth );
} else if ( dirent.isFile () ) {
handleFile ( dirmap, subPath, name );
} else if ( dirent.isSymbolicLink () ) {
handleSymlink ( dirmap, subPath, name, depth );
}
};
const handleDirents = ( dirmap: ResultDirectory, rootPath: string, dirents: fs.Dirent[], depth: number ): void => {
for ( let i = 0, l = dirents.length; i < l; i++ ) {
handleDirent ( dirmap, rootPath, dirents[i], depth );
}
};
const populateResultFromPath = ( rootPath: string, depth: number ): void => {
if ( signal.aborted ) return;
if ( depth > maxDepth ) return;
if ( foundPaths >= maxPaths ) return;
increment ();
fs.readdir ( rootPath, { withFileTypes: true }, ( error, dirents ) => {
if ( error ) return decrement ();
if ( signal.aborted ) return decrement ();
if ( !dirents.length ) return decrement ();
const dirmap = map[rootPath] = { directories: [], directoriesNames: new Set (), directoriesNamesToPaths: {}, files: [], filesNames: new Set (), filesNamesToPaths: {}, symlinks: [], symlinksNames: new Set (), symlinksNamesToPaths: {} };
handleDirents ( dirmap, rootPath, dirents, depth );
decrement ();
});
};
const populateResultFromSymlink = async ( rootPath: string, depth: number ): Promise<void> => {
increment ();
fs.realpath ( rootPath, ( error, realPath ) => {
if ( error ) return decrement ();
if ( signal.aborted ) return decrement ();
fs.stat ( realPath, async ( error, stat ) => {
if ( error ) return decrement ();
if ( signal.aborted ) return decrement ();
const name = path.basename ( realPath );
const dirmap = map[rootPath] = { directories: [], directoriesNames: new Set (), directoriesNamesToPaths: {}, files: [], filesNames: new Set (), filesNamesToPaths: {}, symlinks: [], symlinksNames: new Set (), symlinksNamesToPaths: {} };
handleStat ( dirmap, realPath, name, stat, depth );
decrement ();
});
});
};
const getResult = async ( rootPath: string, depth: number = 1 ): Promise<Result> => {
rootPath = path.normalize ( rootPath );
visited.add ( rootPath );
populateResultFromPath ( rootPath, depth );
await promise;
if ( signal.aborted ) return resultEmpty;
return result;
};
return getResult ( rootPath );
};
/* EXPORT */
export default readdir;

21
ts/tiny-readdir/license 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.

38
ts/tiny-readdir/types.ts Normal file
View File

@ -0,0 +1,38 @@
/* HELPERS */
type Callback = () => void;
/* MAIN */
type Options = {
depth?: number,
limit?: number,
followSymlinks?: boolean,
ignore?: (( targetPath: string ) => boolean) | RegExp,
signal?: { aborted: boolean }
};
type ResultDirectory = {
directories: string[],
directoriesNames: Set<string>,
directoriesNamesToPaths: Record<string, string[]>,
files: string[],
filesNames: Set<string>,
filesNamesToPaths: Record<string, string[]>,
symlinks: string[],
symlinksNames: Set<string>,
symlinksNamesToPaths: Record<string, string[]>
};
type ResultDirectories = {
[path: string]: ResultDirectory
};
type Result = ResultDirectory & {
map: ResultDirectories
};
/* EXPORT */
export type {Callback, Options, ResultDirectory, ResultDirectories, Result};

43
ts/tiny-readdir/utils.ts Normal file
View File

@ -0,0 +1,43 @@
/* IMPORT */
import makeNakedPromise from '../promise-make-naked/index.js';
import type {Callback} from './types.js';
/* MAIN */
const isFunction = ( value: unknown ): value is Function => {
return ( typeof value === 'function' );
};
const makeCounterPromise = (): { promise: Promise<void>, increment: Callback, decrement: Callback } => {
const {promise, resolve} = makeNakedPromise<void> ();
let counter = 0;
const increment = (): void => {
counter += 1;
};
const decrement = (): void => {
counter -= 1;
if ( counter ) return;
resolve ();
};
return { promise, increment, decrement };
};
/* EXPORT */
export {isFunction, makeCounterPromise};

104
ts/types.ts Normal file
View File

@ -0,0 +1,104 @@
/* IMPORT */
import type {FSWatcher, BigIntStats} from 'node:fs';
import type {FSTargetEvent, TargetEvent} from './enums.js';
import type WatcherStats from './watcher_stats.js';
type ResultDirectory = {
directories: string[];
directoriesNames: Set<string>;
directoriesNamesToPaths: Record<string, string[]>;
files: string[];
filesNames: Set<string>;
filesNamesToPaths: Record<string, string[]>;
symlinks: string[];
symlinksNames: Set<string>;
symlinksNamesToPaths: Record<string, string[]>;
};
type ResultDirectories = {
[path: string]: ResultDirectory;
};
/* 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
ts/utils.ts Normal file
View File

@ -0,0 +1,208 @@
/* IMPORT */
import { debounce } from './dettle/index.js';
import fs from 'node:fs';
import path from 'node:path';
import sfs from 'stubborn-fs';
import readdir from './tiny-readdir/index.js';
import {POLLING_TIMEOUT} from './constants.js';
import type {Callback, Ignore, ReaddirMap, Stats} from './types.js';
/* 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
ts/watcher.ts 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.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';
import type {Callback, Disposer, Handler, Ignore, Path, PollerConfig, SubwatcherConfig, WatcherOptions, WatcherConfig} from './types.js';
/* 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
ts/watcher_handler.ts 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.js';
import {FSTargetEvent, FSWatcherEvent, TargetEvent} from './enums.js';
import Utils from './utils.js';
import type Watcher from './watcher.js';
import type {Event, FSWatcher, Handler, HandlerBatched, Path, WatcherOptions, WatcherConfig} from './types.js';
/* 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
ts/watcher_locker.ts Normal file
View File

@ -0,0 +1,202 @@
/* 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';
import type Watcher from './watcher.js';
import type {Path, LocksAdd, LocksUnlink, LocksPair, LockConfig} from './types.js';
/* 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;

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
ts/watcher_poller.ts Normal file
View File

@ -0,0 +1,193 @@
/* 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';
import type {INO, Path} from './types.js';
/* 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
ts/watcher_stats.ts Normal file
View File

@ -0,0 +1,64 @@
/* IMPORT */
import type {INO, Stats} from './types.js';
/* 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;

14
tsconfig.json Executable file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}