UNPKG

8.06 kBTypeScriptView Raw
1/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
2import { Stats } from 'fs';
3import { EventEmitter } from 'events';
4import { ReaddirpStream, ReaddirpOptions, EntryInfo } from 'readdirp';
5import { NodeFsHandler, EventName, Path, EVENTS as EV, WatchHandlers } from './handler.js';
6type AWF = {
7 stabilityThreshold: number;
8 pollInterval: number;
9};
10type BasicOpts = {
11 persistent: boolean;
12 ignoreInitial: boolean;
13 followSymlinks: boolean;
14 cwd?: string;
15 usePolling: boolean;
16 interval: number;
17 binaryInterval: number;
18 alwaysStat?: boolean;
19 depth?: number;
20 ignorePermissionErrors: boolean;
21 atomic: boolean | number;
22};
23export type Throttler = {
24 timeoutObject: NodeJS.Timeout;
25 clear: () => void;
26 count: number;
27};
28export type ChokidarOptions = Partial<BasicOpts & {
29 ignored: Matcher | Matcher[];
30 awaitWriteFinish: boolean | Partial<AWF>;
31}>;
32export type FSWInstanceOptions = BasicOpts & {
33 ignored: Matcher[];
34 awaitWriteFinish: false | AWF;
35};
36export type ThrottleType = 'readdir' | 'watch' | 'add' | 'remove' | 'change';
37export type EmitArgs = [path: Path, stats?: Stats];
38export type EmitErrorArgs = [error: Error, stats?: Stats];
39export type EmitArgsWithName = [event: EventName, ...EmitArgs];
40export type MatchFunction = (val: string, stats?: Stats) => boolean;
41export interface MatcherObject {
42 path: string;
43 recursive?: boolean;
44}
45export type Matcher = string | RegExp | MatchFunction | MatcherObject;
46/**
47 * Directory entry.
48 */
49declare class DirEntry {
50 path: Path;
51 _removeWatcher: (dir: string, base: string) => void;
52 items: Set<Path>;
53 constructor(dir: Path, removeWatcher: (dir: string, base: string) => void);
54 add(item: string): void;
55 remove(item: string): Promise<void>;
56 has(item: string): boolean | undefined;
57 getChildren(): string[];
58 dispose(): void;
59}
60export declare class WatchHelper {
61 fsw: FSWatcher;
62 path: string;
63 watchPath: string;
64 fullWatchPath: string;
65 dirParts: string[][];
66 followSymlinks: boolean;
67 statMethod: 'stat' | 'lstat';
68 constructor(path: string, follow: boolean, fsw: FSWatcher);
69 entryPath(entry: EntryInfo): Path;
70 filterPath(entry: EntryInfo): boolean;
71 filterDir(entry: EntryInfo): boolean;
72}
73export interface FSWatcherKnownEventMap {
74 [EV.READY]: [];
75 [EV.RAW]: Parameters<WatchHandlers['rawEmitter']>;
76 [EV.ERROR]: Parameters<WatchHandlers['errHandler']>;
77 [EV.ALL]: [event: EventName, ...EmitArgs];
78}
79export type FSWatcherEventMap = FSWatcherKnownEventMap & {
80 [k in Exclude<EventName, keyof FSWatcherKnownEventMap>]: EmitArgs;
81};
82/**
83 * Watches files & directories for changes. Emitted events:
84 * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
85 *
86 * new FSWatcher()
87 * .add(directories)
88 * .on('add', path => log('File', path, 'was added'))
89 */
90export declare class FSWatcher extends EventEmitter<FSWatcherEventMap> {
91 closed: boolean;
92 options: FSWInstanceOptions;
93 _closers: Map<string, Array<any>>;
94 _ignoredPaths: Set<Matcher>;
95 _throttled: Map<ThrottleType, Map<any, any>>;
96 _streams: Set<ReaddirpStream>;
97 _symlinkPaths: Map<Path, string | boolean>;
98 _watched: Map<string, DirEntry>;
99 _pendingWrites: Map<string, any>;
100 _pendingUnlinks: Map<string, EmitArgsWithName>;
101 _readyCount: number;
102 _emitReady: () => void;
103 _closePromise?: Promise<void>;
104 _userIgnored?: MatchFunction;
105 _readyEmitted: boolean;
106 _emitRaw: WatchHandlers['rawEmitter'];
107 _boundRemove: (dir: string, item: string) => void;
108 _nodeFsHandler: NodeFsHandler;
109 constructor(_opts?: ChokidarOptions);
110 _addIgnoredPath(matcher: Matcher): void;
111 _removeIgnoredPath(matcher: Matcher): void;
112 /**
113 * Adds paths to be watched on an existing FSWatcher instance.
114 * @param paths_ file or file list. Other arguments are unused
115 */
116 add(paths_: Path | Path[], _origAdd?: string, _internal?: boolean): FSWatcher;
117 /**
118 * Close watchers or start ignoring events from specified paths.
119 */
120 unwatch(paths_: Path | Path[]): FSWatcher;
121 /**
122 * Close watchers and remove all listeners from watched paths.
123 */
124 close(): Promise<void>;
125 /**
126 * Expose list of watched paths
127 * @returns for chaining
128 */
129 getWatched(): Record<string, string[]>;
130 emitWithAll(event: EventName, args: EmitArgs): void;
131 /**
132 * Normalize and emit events.
133 * Calling _emit DOES NOT MEAN emit() would be called!
134 * @param event Type of event
135 * @param path File or directory path
136 * @param stats arguments to be passed with event
137 * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
138 */
139 _emit(event: EventName, path: Path, stats?: Stats): Promise<this | undefined>;
140 /**
141 * Common handler for errors
142 * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
143 */
144 _handleError(error: Error): Error | boolean;
145 /**
146 * Helper utility for throttling
147 * @param actionType type being throttled
148 * @param path being acted upon
149 * @param timeout duration of time to suppress duplicate actions
150 * @returns tracking object or false if action should be suppressed
151 */
152 _throttle(actionType: ThrottleType, path: Path, timeout: number): Throttler | false;
153 _incrReadyCount(): number;
154 /**
155 * Awaits write operation to finish.
156 * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
157 * @param path being acted upon
158 * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
159 * @param event
160 * @param awfEmit Callback to be called when ready for event to be emitted.
161 */
162 _awaitWriteFinish(path: Path, threshold: number, event: EventName, awfEmit: (err?: Error, stat?: Stats) => void): void;
163 /**
164 * Determines whether user has asked to ignore this path.
165 */
166 _isIgnored(path: Path, stats?: Stats): boolean;
167 _isntIgnored(path: Path, stat?: Stats): boolean;
168 /**
169 * Provides a set of common helpers and properties relating to symlink handling.
170 * @param path file or directory pattern being watched
171 */
172 _getWatchHelpers(path: Path): WatchHelper;
173 /**
174 * Provides directory tracking objects
175 * @param directory path of the directory
176 */
177 _getWatchedDir(directory: string): DirEntry;
178 /**
179 * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
180 */
181 _hasReadPermissions(stats: Stats): boolean;
182 /**
183 * Handles emitting unlink events for
184 * files and directories, and via recursion, for
185 * files and directories within directories that are unlinked
186 * @param directory within which the following item is located
187 * @param item base path of item/directory
188 */
189 _remove(directory: string, item: string, isDirectory?: boolean): void;
190 /**
191 * Closes all watchers for a path
192 */
193 _closePath(path: Path): void;
194 /**
195 * Closes only file-specific watchers
196 */
197 _closeFile(path: Path): void;
198 _addPathCloser(path: Path, closer: () => void): void;
199 _readdirp(root: Path, opts?: Partial<ReaddirpOptions>): ReaddirpStream | undefined;
200}
201/**
202 * Instantiates watcher with paths to be tracked.
203 * @param paths file / directory paths
204 * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others
205 * @returns an instance of FSWatcher for chaining.
206 * @example
207 * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
208 * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
209 */
210export declare function watch(paths: string | string[], options?: ChokidarOptions): FSWatcher;
211declare const _default: {
212 watch: typeof watch;
213 FSWatcher: typeof FSWatcher;
214};
215export default _default;