@lvce-editor/file-watcher-process 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1576 -6
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -1,5 +1,13 @@
1
1
  import { VError } from '@lvce-editor/verror';
2
2
  import * as fs from 'node:fs/promises';
3
+ import { lstat, stat, readdir, realpath } from 'node:fs/promises';
4
+ import { unwatchFile, watchFile as watchFile$1, watch as watch$1, stat as stat$2 } from 'fs';
5
+ import { realpath as realpath$1, stat as stat$1, lstat as lstat$1, open, readdir as readdir$1 } from 'fs/promises';
6
+ import { EventEmitter } from 'events';
7
+ import * as sysPath from 'path';
8
+ import { Readable } from 'node:stream';
9
+ import { resolve, join, relative, sep } from 'node:path';
10
+ import { type } from 'os';
3
11
  import { ElectronMessagePortRpcClient, ElectronUtilityProcessRpcClient, NodeWorkerRpcClient, NodeForkedProcessRpcClient } from '@lvce-editor/rpc';
4
12
 
5
13
  const SharedProcess = 1;
@@ -35,15 +43,1577 @@ const watchFile = async path => {
35
43
  await watchInternal(path, {}, callback);
36
44
  };
37
45
 
46
+ const EntryTypes = {
47
+ FILE_TYPE: 'files',
48
+ DIR_TYPE: 'directories',
49
+ FILE_DIR_TYPE: 'files_directories',
50
+ EVERYTHING_TYPE: 'all'
51
+ };
52
+ const defaultOptions = {
53
+ root: '.',
54
+ fileFilter: _entryInfo => true,
55
+ directoryFilter: _entryInfo => true,
56
+ type: EntryTypes.FILE_TYPE,
57
+ lstat: false,
58
+ depth: 2147483648,
59
+ alwaysStat: false,
60
+ highWaterMark: 4096
61
+ };
62
+ Object.freeze(defaultOptions);
63
+ const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
64
+ const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
65
+ const ALL_TYPES = [EntryTypes.DIR_TYPE, EntryTypes.EVERYTHING_TYPE, EntryTypes.FILE_DIR_TYPE, EntryTypes.FILE_TYPE];
66
+ const DIR_TYPES = new Set([EntryTypes.DIR_TYPE, EntryTypes.EVERYTHING_TYPE, EntryTypes.FILE_DIR_TYPE]);
67
+ const FILE_TYPES = new Set([EntryTypes.EVERYTHING_TYPE, EntryTypes.FILE_DIR_TYPE, EntryTypes.FILE_TYPE]);
68
+ const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
69
+ const wantBigintFsStats = process.platform === 'win32';
70
+ const emptyFn = _entryInfo => true;
71
+ const normalizeFilter = filter => {
72
+ if (filter === undefined) return emptyFn;
73
+ if (typeof filter === 'function') return filter;
74
+ if (typeof filter === 'string') {
75
+ const fl = filter.trim();
76
+ return entry => entry.basename === fl;
77
+ }
78
+ if (Array.isArray(filter)) {
79
+ const trItems = filter.map(item => item.trim());
80
+ return entry => trItems.some(f => entry.basename === f);
81
+ }
82
+ return emptyFn;
83
+ };
84
+ /** Readable readdir stream, emitting new files as they're being listed. */
85
+ class ReaddirpStream extends Readable {
86
+ constructor(options = {}) {
87
+ super({
88
+ objectMode: true,
89
+ autoDestroy: true,
90
+ highWaterMark: options.highWaterMark
91
+ });
92
+ const opts = {
93
+ ...defaultOptions,
94
+ ...options
95
+ };
96
+ const {
97
+ root,
98
+ type
99
+ } = opts;
100
+ this._fileFilter = normalizeFilter(opts.fileFilter);
101
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
102
+ const statMethod = opts.lstat ? lstat : stat;
103
+ // Use bigint stats if it's windows and stat() supports options (node 10+).
104
+ if (wantBigintFsStats) {
105
+ this._stat = path => statMethod(path, {
106
+ bigint: true
107
+ });
108
+ } else {
109
+ this._stat = statMethod;
110
+ }
111
+ this._maxDepth = opts.depth ?? defaultOptions.depth;
112
+ this._wantsDir = type ? DIR_TYPES.has(type) : false;
113
+ this._wantsFile = type ? FILE_TYPES.has(type) : false;
114
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
115
+ this._root = resolve(root);
116
+ this._isDirent = !opts.alwaysStat;
117
+ this._statsProp = this._isDirent ? 'dirent' : 'stats';
118
+ this._rdOptions = {
119
+ encoding: 'utf8',
120
+ withFileTypes: this._isDirent
121
+ };
122
+ // Launch stream with one parent, the root dir.
123
+ this.parents = [this._exploreDir(root, 1)];
124
+ this.reading = false;
125
+ this.parent = undefined;
126
+ }
127
+ async _read(batch) {
128
+ if (this.reading) return;
129
+ this.reading = true;
130
+ try {
131
+ while (!this.destroyed && batch > 0) {
132
+ const par = this.parent;
133
+ const fil = par && par.files;
134
+ if (fil && fil.length > 0) {
135
+ const {
136
+ path,
137
+ depth
138
+ } = par;
139
+ const slice = fil.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
140
+ const awaited = await Promise.all(slice);
141
+ for (const entry of awaited) {
142
+ if (!entry) {
143
+ batch--;
144
+ return;
145
+ }
146
+ if (this.destroyed) return;
147
+ const entryType = await this._getEntryType(entry);
148
+ if (entryType === 'directory' && this._directoryFilter(entry)) {
149
+ if (depth <= this._maxDepth) {
150
+ this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
151
+ }
152
+ if (this._wantsDir) {
153
+ this.push(entry);
154
+ batch--;
155
+ }
156
+ } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
157
+ if (this._wantsFile) {
158
+ this.push(entry);
159
+ batch--;
160
+ }
161
+ }
162
+ }
163
+ } else {
164
+ const parent = this.parents.pop();
165
+ if (!parent) {
166
+ this.push(null);
167
+ break;
168
+ }
169
+ this.parent = await parent;
170
+ if (this.destroyed) return;
171
+ }
172
+ }
173
+ } catch (error) {
174
+ this.destroy(error);
175
+ } finally {
176
+ this.reading = false;
177
+ }
178
+ }
179
+ async _exploreDir(path, depth) {
180
+ let files;
181
+ try {
182
+ files = await readdir(path, this._rdOptions);
183
+ } catch (error) {
184
+ this._onError(error);
185
+ }
186
+ return {
187
+ files,
188
+ depth,
189
+ path
190
+ };
191
+ }
192
+ async _formatEntry(dirent, path) {
193
+ let entry;
194
+ const basename = this._isDirent ? dirent.name : dirent;
195
+ try {
196
+ const fullPath = resolve(join(path, basename));
197
+ entry = {
198
+ path: relative(this._root, fullPath),
199
+ fullPath,
200
+ basename
201
+ };
202
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
203
+ } catch (err) {
204
+ this._onError(err);
205
+ return;
206
+ }
207
+ return entry;
208
+ }
209
+ _onError(err) {
210
+ if (isNormalFlowError(err) && !this.destroyed) {
211
+ this.emit('warn', err);
212
+ } else {
213
+ this.destroy(err);
214
+ }
215
+ }
216
+ async _getEntryType(entry) {
217
+ // entry may be undefined, because a warning or an error were emitted
218
+ // and the statsProp is undefined
219
+ if (!entry && this._statsProp in entry) {
220
+ return '';
221
+ }
222
+ const stats = entry[this._statsProp];
223
+ if (stats.isFile()) return 'file';
224
+ if (stats.isDirectory()) return 'directory';
225
+ if (stats && stats.isSymbolicLink()) {
226
+ const full = entry.fullPath;
227
+ try {
228
+ const entryRealPath = await realpath(full);
229
+ const entryRealPathStats = await lstat(entryRealPath);
230
+ if (entryRealPathStats.isFile()) {
231
+ return 'file';
232
+ }
233
+ if (entryRealPathStats.isDirectory()) {
234
+ const len = entryRealPath.length;
235
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === sep) {
236
+ const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
237
+ // @ts-ignore
238
+ recursiveError.code = RECURSIVE_ERROR_CODE;
239
+ return this._onError(recursiveError);
240
+ }
241
+ return 'directory';
242
+ }
243
+ } catch (error) {
244
+ this._onError(error);
245
+ return '';
246
+ }
247
+ }
248
+ }
249
+ _includeAsFile(entry) {
250
+ const stats = entry && entry[this._statsProp];
251
+ return stats && this._wantsEverything && !stats.isDirectory();
252
+ }
253
+ }
254
+ /**
255
+ * Streaming version: Reads all files and directories in given root recursively.
256
+ * Consumes ~constant small amount of RAM.
257
+ * @param root Root directory
258
+ * @param options Options to specify root (start directory), filters and recursion depth
259
+ */
260
+ function readdirp(root, options = {}) {
261
+ // @ts-ignore
262
+ let type = options.entryType || options.type;
263
+ if (type === 'both') type = EntryTypes.FILE_DIR_TYPE; // backwards-compatibility
264
+ if (type) options.type = type;
265
+ if (!root) {
266
+ throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
267
+ } else if (typeof root !== 'string') {
268
+ throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
269
+ } else if (type && !ALL_TYPES.includes(type)) {
270
+ throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
271
+ }
272
+ options.root = root;
273
+ return new ReaddirpStream(options);
274
+ }
275
+
276
+ const STR_DATA = 'data';
277
+ const STR_END = 'end';
278
+ const STR_CLOSE = 'close';
279
+ const EMPTY_FN = () => {};
280
+ const pl = process.platform;
281
+ const isWindows = pl === 'win32';
282
+ const isMacos = pl === 'darwin';
283
+ const isLinux = pl === 'linux';
284
+ const isFreeBSD = pl === 'freebsd';
285
+ const isIBMi = type() === 'OS400';
286
+ const EVENTS = {
287
+ ALL: 'all',
288
+ READY: 'ready',
289
+ ADD: 'add',
290
+ CHANGE: 'change',
291
+ ADD_DIR: 'addDir',
292
+ UNLINK: 'unlink',
293
+ UNLINK_DIR: 'unlinkDir',
294
+ RAW: 'raw',
295
+ ERROR: 'error'
296
+ };
297
+ const EV = EVENTS;
298
+ const THROTTLE_MODE_WATCH = 'watch';
299
+ const statMethods = {
300
+ lstat: lstat$1,
301
+ stat: stat$1
302
+ };
303
+ const KEY_LISTENERS = 'listeners';
304
+ const KEY_ERR = 'errHandlers';
305
+ const KEY_RAW = 'rawEmitters';
306
+ const HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
307
+ // prettier-ignore
308
+ const binaryExtensions = new Set(['3dm', '3ds', '3g2', '3gp', '7z', 'a', 'aac', 'adp', 'afdesign', 'afphoto', 'afpub', 'ai', 'aif', 'aiff', 'alz', 'ape', 'apk', 'appimage', 'ar', 'arj', 'asf', 'au', 'avi', 'bak', 'baml', 'bh', 'bin', 'bk', 'bmp', 'btif', 'bz2', 'bzip2', 'cab', 'caf', 'cgm', 'class', 'cmx', 'cpio', 'cr2', 'cur', 'dat', 'dcm', 'deb', 'dex', 'djvu', 'dll', 'dmg', 'dng', 'doc', 'docm', 'docx', 'dot', 'dotm', 'dra', 'DS_Store', 'dsk', 'dts', 'dtshd', 'dvb', 'dwg', 'dxf', 'ecelp4800', 'ecelp7470', 'ecelp9600', 'egg', 'eol', 'eot', 'epub', 'exe', 'f4v', 'fbs', 'fh', 'fla', 'flac', 'flatpak', 'fli', 'flv', 'fpx', 'fst', 'fvt', 'g3', 'gh', 'gif', 'graffle', 'gz', 'gzip', 'h261', 'h263', 'h264', 'icns', 'ico', 'ief', 'img', 'ipa', 'iso', 'jar', 'jpeg', 'jpg', 'jpgv', 'jpm', 'jxr', 'key', 'ktx', 'lha', 'lib', 'lvp', 'lz', 'lzh', 'lzma', 'lzo', 'm3u', 'm4a', 'm4v', 'mar', 'mdi', 'mht', 'mid', 'midi', 'mj2', 'mka', 'mkv', 'mmr', 'mng', 'mobi', 'mov', 'movie', 'mp3', 'mp4', 'mp4a', 'mpeg', 'mpg', 'mpga', 'mxu', 'nef', 'npx', 'numbers', 'nupkg', 'o', 'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'otf', 'ott', 'pages', 'pbm', 'pcx', 'pdb', 'pdf', 'pea', 'pgm', 'pic', 'png', 'pnm', 'pot', 'potm', 'potx', 'ppa', 'ppam', 'ppm', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx', 'psd', 'pya', 'pyc', 'pyo', 'pyv', 'qt', 'rar', 'ras', 'raw', 'resources', 'rgb', 'rip', 'rlc', 'rmf', 'rmvb', 'rpm', 'rtf', 'rz', 's3m', 's7z', 'scpt', 'sgi', 'shar', 'snap', 'sil', 'sketch', 'slk', 'smv', 'snk', 'so', 'stl', 'suo', 'sub', 'swf', 'tar', 'tbz', 'tbz2', 'tga', 'tgz', 'thmx', 'tif', 'tiff', 'tlz', 'ttc', 'ttf', 'txz', 'udf', 'uvh', 'uvi', 'uvm', 'uvp', 'uvs', 'uvu', 'viv', 'vob', 'war', 'wav', 'wax', 'wbmp', 'wdp', 'weba', 'webm', 'webp', 'whl', 'wim', 'wm', 'wma', 'wmv', 'wmx', 'woff', 'woff2', 'wrm', 'wvx', 'xbm', 'xif', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx', 'xm', 'xmind', 'xpi', 'xpm', 'xwd', 'xz', 'z', 'zip', 'zipx']);
309
+ const isBinaryPath = filePath => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase());
310
+ // TODO: emit errors properly. Example: EMFILE on Macos.
311
+ const foreach = (val, fn) => {
312
+ if (val instanceof Set) {
313
+ val.forEach(fn);
314
+ } else {
315
+ fn(val);
316
+ }
317
+ };
318
+ const addAndConvert = (main, prop, item) => {
319
+ let container = main[prop];
320
+ if (!(container instanceof Set)) {
321
+ main[prop] = container = new Set([container]);
322
+ }
323
+ container.add(item);
324
+ };
325
+ const clearItem = cont => key => {
326
+ const set = cont[key];
327
+ if (set instanceof Set) {
328
+ set.clear();
329
+ } else {
330
+ delete cont[key];
331
+ }
332
+ };
333
+ const delFromSet = (main, prop, item) => {
334
+ const container = main[prop];
335
+ if (container instanceof Set) {
336
+ container.delete(item);
337
+ } else if (container === item) {
338
+ delete main[prop];
339
+ }
340
+ };
341
+ const isEmptySet = val => val instanceof Set ? val.size === 0 : !val;
342
+ const FsWatchInstances = new Map();
343
+ /**
344
+ * Instantiates the fs_watch interface
345
+ * @param path to be watched
346
+ * @param options to be passed to fs_watch
347
+ * @param listener main event handler
348
+ * @param errHandler emits info about errors
349
+ * @param emitRaw emits raw event data
350
+ * @returns {NativeFsWatcher}
351
+ */
352
+ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
353
+ const handleEvent = (rawEvent, evPath) => {
354
+ listener(path);
355
+ emitRaw(rawEvent, evPath, {
356
+ watchedPath: path
357
+ });
358
+ // emit based on events occurring for files from a directory's watcher in
359
+ // case the file's watcher misses it (and rely on throttling to de-dupe)
360
+ if (evPath && path !== evPath) {
361
+ fsWatchBroadcast(sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath));
362
+ }
363
+ };
364
+ try {
365
+ return watch$1(path, {
366
+ persistent: options.persistent
367
+ }, handleEvent);
368
+ } catch (error) {
369
+ errHandler(error);
370
+ return undefined;
371
+ }
372
+ }
373
+ /**
374
+ * Helper for passing fs_watch event data to a collection of listeners
375
+ * @param fullPath absolute path bound to fs_watch instance
376
+ */
377
+ const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
378
+ const cont = FsWatchInstances.get(fullPath);
379
+ if (!cont) return;
380
+ foreach(cont[listenerType], listener => {
381
+ listener(val1, val2, val3);
382
+ });
383
+ };
384
+ /**
385
+ * Instantiates the fs_watch interface or binds listeners
386
+ * to an existing one covering the same file system entry
387
+ * @param path
388
+ * @param fullPath absolute path
389
+ * @param options to be passed to fs_watch
390
+ * @param handlers container for event listener functions
391
+ */
392
+ const setFsWatchListener = (path, fullPath, options, handlers) => {
393
+ const {
394
+ listener,
395
+ errHandler,
396
+ rawEmitter
397
+ } = handlers;
398
+ let cont = FsWatchInstances.get(fullPath);
399
+ let watcher;
400
+ if (!options.persistent) {
401
+ watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
402
+ if (!watcher) return;
403
+ return watcher.close.bind(watcher);
404
+ }
405
+ if (cont) {
406
+ addAndConvert(cont, KEY_LISTENERS, listener);
407
+ addAndConvert(cont, KEY_ERR, errHandler);
408
+ addAndConvert(cont, KEY_RAW, rawEmitter);
409
+ } else {
410
+ watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler,
411
+ // no need to use broadcast here
412
+ fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
413
+ if (!watcher) return;
414
+ watcher.on(EV.ERROR, async error => {
415
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
416
+ if (cont) cont.watcherUnusable = true; // documented since Node 10.4.1
417
+ // Workaround for https://github.com/joyent/node/issues/4337
418
+ if (isWindows && error.code === 'EPERM') {
419
+ try {
420
+ const fd = await open(path, 'r');
421
+ await fd.close();
422
+ broadcastErr(error);
423
+ } catch (err) {
424
+ // do nothing
425
+ }
426
+ } else {
427
+ broadcastErr(error);
428
+ }
429
+ });
430
+ cont = {
431
+ listeners: listener,
432
+ errHandlers: errHandler,
433
+ rawEmitters: rawEmitter,
434
+ watcher
435
+ };
436
+ FsWatchInstances.set(fullPath, cont);
437
+ }
438
+ // const index = cont.listeners.indexOf(listener);
439
+ // removes this instance's listeners and closes the underlying fs_watch
440
+ // instance if there are no more listeners left
441
+ return () => {
442
+ delFromSet(cont, KEY_LISTENERS, listener);
443
+ delFromSet(cont, KEY_ERR, errHandler);
444
+ delFromSet(cont, KEY_RAW, rawEmitter);
445
+ if (isEmptySet(cont.listeners)) {
446
+ // Check to protect against issue gh-730.
447
+ // if (cont.watcherUnusable) {
448
+ cont.watcher.close();
449
+ // }
450
+ FsWatchInstances.delete(fullPath);
451
+ HANDLER_KEYS.forEach(clearItem(cont));
452
+ // @ts-ignore
453
+ cont.watcher = undefined;
454
+ Object.freeze(cont);
455
+ }
456
+ };
457
+ };
458
+ // fs_watchFile helpers
459
+ // object to hold per-process fs_watchFile instances
460
+ // (may be shared across chokidar FSWatcher instances)
461
+ const FsWatchFileInstances = new Map();
462
+ /**
463
+ * Instantiates the fs_watchFile interface or binds listeners
464
+ * to an existing one covering the same file system entry
465
+ * @param path to be watched
466
+ * @param fullPath absolute path
467
+ * @param options options to be passed to fs_watchFile
468
+ * @param handlers container for event listener functions
469
+ * @returns closer
470
+ */
471
+ const setFsWatchFileListener = (path, fullPath, options, handlers) => {
472
+ const {
473
+ listener,
474
+ rawEmitter
475
+ } = handlers;
476
+ let cont = FsWatchFileInstances.get(fullPath);
477
+ // let listeners = new Set();
478
+ // let rawEmitters = new Set();
479
+ const copts = cont && cont.options;
480
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
481
+ // "Upgrade" the watcher to persistence or a quicker interval.
482
+ // This creates some unlikely edge case issues if the user mixes
483
+ // settings in a very weird way, but solving for those cases
484
+ // doesn't seem worthwhile for the added complexity.
485
+ // listeners = cont.listeners;
486
+ // rawEmitters = cont.rawEmitters;
487
+ unwatchFile(fullPath);
488
+ cont = undefined;
489
+ }
490
+ if (cont) {
491
+ addAndConvert(cont, KEY_LISTENERS, listener);
492
+ addAndConvert(cont, KEY_RAW, rawEmitter);
493
+ } else {
494
+ // TODO
495
+ // listeners.add(listener);
496
+ // rawEmitters.add(rawEmitter);
497
+ cont = {
498
+ listeners: listener,
499
+ rawEmitters: rawEmitter,
500
+ options,
501
+ watcher: watchFile$1(fullPath, options, (curr, prev) => {
502
+ foreach(cont.rawEmitters, rawEmitter => {
503
+ rawEmitter(EV.CHANGE, fullPath, {
504
+ curr,
505
+ prev
506
+ });
507
+ });
508
+ const currmtime = curr.mtimeMs;
509
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
510
+ foreach(cont.listeners, listener => listener(path, curr));
511
+ }
512
+ })
513
+ };
514
+ FsWatchFileInstances.set(fullPath, cont);
515
+ }
516
+ // const index = cont.listeners.indexOf(listener);
517
+ // Removes this instance's listeners and closes the underlying fs_watchFile
518
+ // instance if there are no more listeners left.
519
+ return () => {
520
+ delFromSet(cont, KEY_LISTENERS, listener);
521
+ delFromSet(cont, KEY_RAW, rawEmitter);
522
+ if (isEmptySet(cont.listeners)) {
523
+ FsWatchFileInstances.delete(fullPath);
524
+ unwatchFile(fullPath);
525
+ cont.options = cont.watcher = undefined;
526
+ Object.freeze(cont);
527
+ }
528
+ };
529
+ };
530
+ /**
531
+ * @mixin
532
+ */
533
+ class NodeFsHandler {
534
+ constructor(fsW) {
535
+ this.fsw = fsW;
536
+ this._boundHandleError = error => fsW._handleError(error);
537
+ }
538
+ /**
539
+ * Watch file for changes with fs_watchFile or fs_watch.
540
+ * @param path to file or dir
541
+ * @param listener on fs change
542
+ * @returns closer for the watcher instance
543
+ */
544
+ _watchWithNodeFs(path, listener) {
545
+ const opts = this.fsw.options;
546
+ const directory = sysPath.dirname(path);
547
+ const basename = sysPath.basename(path);
548
+ const parent = this.fsw._getWatchedDir(directory);
549
+ parent.add(basename);
550
+ const absolutePath = sysPath.resolve(path);
551
+ const options = {
552
+ persistent: opts.persistent
553
+ };
554
+ if (!listener) listener = EMPTY_FN;
555
+ let closer;
556
+ if (opts.usePolling) {
557
+ const enableBin = opts.interval !== opts.binaryInterval;
558
+ options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
559
+ closer = setFsWatchFileListener(path, absolutePath, options, {
560
+ listener,
561
+ rawEmitter: this.fsw._emitRaw
562
+ });
563
+ } else {
564
+ closer = setFsWatchListener(path, absolutePath, options, {
565
+ listener,
566
+ errHandler: this._boundHandleError,
567
+ rawEmitter: this.fsw._emitRaw
568
+ });
569
+ }
570
+ return closer;
571
+ }
572
+ /**
573
+ * Watch a file and emit add event if warranted.
574
+ * @returns closer for the watcher instance
575
+ */
576
+ _handleFile(file, stats, initialAdd) {
577
+ if (this.fsw.closed) {
578
+ return;
579
+ }
580
+ const dirname = sysPath.dirname(file);
581
+ const basename = sysPath.basename(file);
582
+ const parent = this.fsw._getWatchedDir(dirname);
583
+ // stats is always present
584
+ let prevStats = stats;
585
+ // if the file is already being watched, do nothing
586
+ if (parent.has(basename)) return;
587
+ const listener = async (path, newStats) => {
588
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
589
+ if (!newStats || newStats.mtimeMs === 0) {
590
+ try {
591
+ const newStats = await stat$1(file);
592
+ if (this.fsw.closed) return;
593
+ // Check that change event was not fired because of changed only accessTime.
594
+ const at = newStats.atimeMs;
595
+ const mt = newStats.mtimeMs;
596
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
597
+ this.fsw._emit(EV.CHANGE, file, newStats);
598
+ }
599
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {
600
+ this.fsw._closeFile(path);
601
+ prevStats = newStats;
602
+ const closer = this._watchWithNodeFs(file, listener);
603
+ if (closer) this.fsw._addPathCloser(path, closer);
604
+ } else {
605
+ prevStats = newStats;
606
+ }
607
+ } catch (error) {
608
+ // Fix issues where mtime is null but file is still present
609
+ this.fsw._remove(dirname, basename);
610
+ }
611
+ // add is about to be emitted if file not already tracked in parent
612
+ } else if (parent.has(basename)) {
613
+ // Check that change event was not fired because of changed only accessTime.
614
+ const at = newStats.atimeMs;
615
+ const mt = newStats.mtimeMs;
616
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
617
+ this.fsw._emit(EV.CHANGE, file, newStats);
618
+ }
619
+ prevStats = newStats;
620
+ }
621
+ };
622
+ // kick off the watcher
623
+ const closer = this._watchWithNodeFs(file, listener);
624
+ // emit an add event if we're supposed to
625
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
626
+ if (!this.fsw._throttle(EV.ADD, file, 0)) return;
627
+ this.fsw._emit(EV.ADD, file, stats);
628
+ }
629
+ return closer;
630
+ }
631
+ /**
632
+ * Handle symlinks encountered while reading a dir.
633
+ * @param entry returned by readdirp
634
+ * @param directory path of dir being read
635
+ * @param path of this item
636
+ * @param item basename of this item
637
+ * @returns true if no more processing is needed for this entry.
638
+ */
639
+ async _handleSymlink(entry, directory, path, item) {
640
+ if (this.fsw.closed) {
641
+ return;
642
+ }
643
+ const full = entry.fullPath;
644
+ const dir = this.fsw._getWatchedDir(directory);
645
+ if (!this.fsw.options.followSymlinks) {
646
+ // watch symlink directly (don't follow) and detect changes
647
+ this.fsw._incrReadyCount();
648
+ let linkPath;
649
+ try {
650
+ linkPath = await realpath$1(path);
651
+ } catch (e) {
652
+ this.fsw._emitReady();
653
+ return true;
654
+ }
655
+ if (this.fsw.closed) return;
656
+ if (dir.has(item)) {
657
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
658
+ this.fsw._symlinkPaths.set(full, linkPath);
659
+ this.fsw._emit(EV.CHANGE, path, entry.stats);
660
+ }
661
+ } else {
662
+ dir.add(item);
663
+ this.fsw._symlinkPaths.set(full, linkPath);
664
+ this.fsw._emit(EV.ADD, path, entry.stats);
665
+ }
666
+ this.fsw._emitReady();
667
+ return true;
668
+ }
669
+ // don't follow the same symlink more than once
670
+ if (this.fsw._symlinkPaths.has(full)) {
671
+ return true;
672
+ }
673
+ this.fsw._symlinkPaths.set(full, true);
674
+ }
675
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
676
+ // Normalize the directory name on Windows
677
+ directory = sysPath.join(directory, '');
678
+ throttler = this.fsw._throttle('readdir', directory, 1000);
679
+ if (!throttler) return;
680
+ const previous = this.fsw._getWatchedDir(wh.path);
681
+ const current = new Set();
682
+ let stream = this.fsw._readdirp(directory, {
683
+ fileFilter: entry => wh.filterPath(entry),
684
+ directoryFilter: entry => wh.filterDir(entry)
685
+ });
686
+ if (!stream) return;
687
+ stream.on(STR_DATA, async entry => {
688
+ if (this.fsw.closed) {
689
+ stream = undefined;
690
+ return;
691
+ }
692
+ const item = entry.path;
693
+ let path = sysPath.join(directory, item);
694
+ current.add(item);
695
+ if (entry.stats.isSymbolicLink() && (await this._handleSymlink(entry, directory, path, item))) {
696
+ return;
697
+ }
698
+ if (this.fsw.closed) {
699
+ stream = undefined;
700
+ return;
701
+ }
702
+ // Files that present in current directory snapshot
703
+ // but absent in previous are added to watch list and
704
+ // emit `add` event.
705
+ if (item === target || !target && !previous.has(item)) {
706
+ this.fsw._incrReadyCount();
707
+ // ensure relativeness of path is preserved in case of watcher reuse
708
+ path = sysPath.join(dir, sysPath.relative(dir, path));
709
+ this._addToNodeFs(path, initialAdd, wh, depth + 1);
710
+ }
711
+ }).on(EV.ERROR, this._boundHandleError);
712
+ return new Promise((resolve, reject) => {
713
+ if (!stream) return reject();
714
+ stream.once(STR_END, () => {
715
+ if (this.fsw.closed) {
716
+ stream = undefined;
717
+ return;
718
+ }
719
+ const wasThrottled = throttler ? throttler.clear() : false;
720
+ resolve(undefined);
721
+ // Files that absent in current directory snapshot
722
+ // but present in previous emit `remove` event
723
+ // and are removed from @watched[directory].
724
+ previous.getChildren().filter(item => {
725
+ return item !== directory && !current.has(item);
726
+ }).forEach(item => {
727
+ this.fsw._remove(directory, item);
728
+ });
729
+ stream = undefined;
730
+ // one more time for any missed in case changes came in extremely quickly
731
+ if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
732
+ });
733
+ });
734
+ }
735
+ /**
736
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
737
+ * @param dir fs path
738
+ * @param stats
739
+ * @param initialAdd
740
+ * @param depth relative to user-supplied path
741
+ * @param target child path targeted for watch
742
+ * @param wh Common watch helpers for this path
743
+ * @param realpath
744
+ * @returns closer for the watcher instance.
745
+ */
746
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
747
+ const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
748
+ const tracked = parentDir.has(sysPath.basename(dir));
749
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
750
+ this.fsw._emit(EV.ADD_DIR, dir, stats);
751
+ }
752
+ // ensure dir is tracked (harmless if redundant)
753
+ parentDir.add(sysPath.basename(dir));
754
+ this.fsw._getWatchedDir(dir);
755
+ let throttler;
756
+ let closer;
757
+ const oDepth = this.fsw.options.depth;
758
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
759
+ if (!target) {
760
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
761
+ if (this.fsw.closed) return;
762
+ }
763
+ closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
764
+ // if current directory is removed, do nothing
765
+ if (stats && stats.mtimeMs === 0) return;
766
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
767
+ });
768
+ }
769
+ return closer;
770
+ }
771
+ /**
772
+ * Handle added file, directory, or glob pattern.
773
+ * Delegates call to _handleFile / _handleDir after checks.
774
+ * @param path to file or ir
775
+ * @param initialAdd was the file added at watch instantiation?
776
+ * @param priorWh depth relative to user-supplied path
777
+ * @param depth Child path actually targeted for watch
778
+ * @param target Child path actually targeted for watch
779
+ */
780
+ async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
781
+ const ready = this.fsw._emitReady;
782
+ if (this.fsw._isIgnored(path) || this.fsw.closed) {
783
+ ready();
784
+ return false;
785
+ }
786
+ const wh = this.fsw._getWatchHelpers(path);
787
+ if (priorWh) {
788
+ wh.filterPath = entry => priorWh.filterPath(entry);
789
+ wh.filterDir = entry => priorWh.filterDir(entry);
790
+ }
791
+ // evaluate what is at the path we're being asked to watch
792
+ try {
793
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
794
+ if (this.fsw.closed) return;
795
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
796
+ ready();
797
+ return false;
798
+ }
799
+ const follow = this.fsw.options.followSymlinks;
800
+ let closer;
801
+ if (stats.isDirectory()) {
802
+ const absPath = sysPath.resolve(path);
803
+ const targetPath = follow ? await realpath$1(path) : path;
804
+ if (this.fsw.closed) return;
805
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
806
+ if (this.fsw.closed) return;
807
+ // preserve this symlink's target path
808
+ if (absPath !== targetPath && targetPath !== undefined) {
809
+ this.fsw._symlinkPaths.set(absPath, targetPath);
810
+ }
811
+ } else if (stats.isSymbolicLink()) {
812
+ const targetPath = follow ? await realpath$1(path) : path;
813
+ if (this.fsw.closed) return;
814
+ const parent = sysPath.dirname(wh.watchPath);
815
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
816
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
817
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
818
+ if (this.fsw.closed) return;
819
+ // preserve this symlink's target path
820
+ if (targetPath !== undefined) {
821
+ this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
822
+ }
823
+ } else {
824
+ closer = this._handleFile(wh.watchPath, stats, initialAdd);
825
+ }
826
+ ready();
827
+ if (closer) this.fsw._addPathCloser(path, closer);
828
+ return false;
829
+ } catch (error) {
830
+ if (this.fsw._handleError(error)) {
831
+ ready();
832
+ return path;
833
+ }
834
+ }
835
+ }
836
+ }
837
+
838
+ /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
839
+ const SLASH = '/';
840
+ const SLASH_SLASH = '//';
841
+ const ONE_DOT = '.';
842
+ const TWO_DOTS = '..';
843
+ const STRING_TYPE = 'string';
844
+ const BACK_SLASH_RE = /\\/g;
845
+ const DOUBLE_SLASH_RE = /\/\//;
846
+ const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
847
+ const REPLACER_RE = /^\.[/\\]/;
848
+ function arrify(item) {
849
+ return Array.isArray(item) ? item : [item];
850
+ }
851
+ const isMatcherObject = matcher => typeof matcher === 'object' && matcher !== null && !(matcher instanceof RegExp);
852
+ function createPattern(matcher) {
853
+ if (typeof matcher === 'function') return matcher;
854
+ if (typeof matcher === 'string') return string => matcher === string;
855
+ if (matcher instanceof RegExp) return string => matcher.test(string);
856
+ if (typeof matcher === 'object' && matcher !== null) {
857
+ return string => {
858
+ if (matcher.path === string) return true;
859
+ if (matcher.recursive) {
860
+ const relative = sysPath.relative(matcher.path, string);
861
+ if (!relative) {
862
+ return false;
863
+ }
864
+ return !relative.startsWith('..') && !sysPath.isAbsolute(relative);
865
+ }
866
+ return false;
867
+ };
868
+ }
869
+ return () => false;
870
+ }
871
+ function normalizePath(path) {
872
+ if (typeof path !== 'string') throw new Error('string expected');
873
+ path = sysPath.normalize(path);
874
+ path = path.replace(/\\/g, '/');
875
+ let prepend = false;
876
+ if (path.startsWith('//')) prepend = true;
877
+ const DOUBLE_SLASH_RE = /\/\//;
878
+ while (path.match(DOUBLE_SLASH_RE)) path = path.replace(DOUBLE_SLASH_RE, '/');
879
+ if (prepend) path = '/' + path;
880
+ return path;
881
+ }
882
+ function matchPatterns(patterns, testString, stats) {
883
+ const path = normalizePath(testString);
884
+ for (let index = 0; index < patterns.length; index++) {
885
+ const pattern = patterns[index];
886
+ if (pattern(path, stats)) {
887
+ return true;
888
+ }
889
+ }
890
+ return false;
891
+ }
892
+ function anymatch(matchers, testString) {
893
+ if (matchers == null) {
894
+ throw new TypeError('anymatch: specify first argument');
895
+ }
896
+ // Early cache for matchers.
897
+ const matchersArray = arrify(matchers);
898
+ const patterns = matchersArray.map(matcher => createPattern(matcher));
899
+ {
900
+ return (testString, stats) => {
901
+ return matchPatterns(patterns, testString, stats);
902
+ };
903
+ }
904
+ }
905
+ const unifyPaths = paths_ => {
906
+ const paths = arrify(paths_).flat();
907
+ if (!paths.every(p => typeof p === STRING_TYPE)) {
908
+ throw new TypeError(`Non-string provided as watch path: ${paths}`);
909
+ }
910
+ return paths.map(normalizePathToUnix);
911
+ };
912
+ // If SLASH_SLASH occurs at the beginning of path, it is not replaced
913
+ // because "//StoragePC/DrivePool/Movies" is a valid network path
914
+ const toUnix = string => {
915
+ let str = string.replace(BACK_SLASH_RE, SLASH);
916
+ let prepend = false;
917
+ if (str.startsWith(SLASH_SLASH)) {
918
+ prepend = true;
919
+ }
920
+ while (str.match(DOUBLE_SLASH_RE)) {
921
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
922
+ }
923
+ if (prepend) {
924
+ str = SLASH + str;
925
+ }
926
+ return str;
927
+ };
928
+ // Our version of upath.normalize
929
+ // TODO: this is not equal to path-normalize module - investigate why
930
+ const normalizePathToUnix = path => toUnix(sysPath.normalize(toUnix(path)));
931
+ // TODO: refactor
932
+ const normalizeIgnored = (cwd = '') => path => {
933
+ if (typeof path === 'string') {
934
+ return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
935
+ } else {
936
+ return path;
937
+ }
938
+ };
939
+ const getAbsolutePath = (path, cwd) => {
940
+ if (sysPath.isAbsolute(path)) {
941
+ return path;
942
+ }
943
+ return sysPath.join(cwd, path);
944
+ };
945
+ const EMPTY_SET = Object.freeze(new Set());
946
+ /**
947
+ * Directory entry.
948
+ */
949
+ class DirEntry {
950
+ constructor(dir, removeWatcher) {
951
+ this.path = dir;
952
+ this._removeWatcher = removeWatcher;
953
+ this.items = new Set();
954
+ }
955
+ add(item) {
956
+ const {
957
+ items
958
+ } = this;
959
+ if (!items) return;
960
+ if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
961
+ }
962
+ async remove(item) {
963
+ const {
964
+ items
965
+ } = this;
966
+ if (!items) return;
967
+ items.delete(item);
968
+ if (items.size > 0) return;
969
+ const dir = this.path;
970
+ try {
971
+ await readdir$1(dir);
972
+ } catch (err) {
973
+ if (this._removeWatcher) {
974
+ this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
975
+ }
976
+ }
977
+ }
978
+ has(item) {
979
+ const {
980
+ items
981
+ } = this;
982
+ if (!items) return;
983
+ return items.has(item);
984
+ }
985
+ getChildren() {
986
+ const {
987
+ items
988
+ } = this;
989
+ if (!items) return [];
990
+ return [...items.values()];
991
+ }
992
+ dispose() {
993
+ this.items.clear();
994
+ this.path = '';
995
+ this._removeWatcher = EMPTY_FN;
996
+ this.items = EMPTY_SET;
997
+ Object.freeze(this);
998
+ }
999
+ }
1000
+ const STAT_METHOD_F = 'stat';
1001
+ const STAT_METHOD_L = 'lstat';
1002
+ class WatchHelper {
1003
+ constructor(path, follow, fsw) {
1004
+ this.fsw = fsw;
1005
+ const watchPath = path;
1006
+ this.path = path = path.replace(REPLACER_RE, '');
1007
+ this.watchPath = watchPath;
1008
+ this.fullWatchPath = sysPath.resolve(watchPath);
1009
+ this.dirParts = [];
1010
+ this.dirParts.forEach(parts => {
1011
+ if (parts.length > 1) parts.pop();
1012
+ });
1013
+ this.followSymlinks = follow;
1014
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
1015
+ }
1016
+ entryPath(entry) {
1017
+ return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, entry.fullPath));
1018
+ }
1019
+ filterPath(entry) {
1020
+ const {
1021
+ stats
1022
+ } = entry;
1023
+ if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
1024
+ const resolvedPath = this.entryPath(entry);
1025
+ // TODO: what if stats is undefined? remove !
1026
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
1027
+ }
1028
+ filterDir(entry) {
1029
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
1030
+ }
1031
+ }
1032
+ /**
1033
+ * Watches files & directories for changes. Emitted events:
1034
+ * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
1035
+ *
1036
+ * new FSWatcher()
1037
+ * .add(directories)
1038
+ * .on('add', path => log('File', path, 'was added'))
1039
+ */
1040
+ class FSWatcher extends EventEmitter {
1041
+ // Not indenting methods for history sake; for now.
1042
+ constructor(_opts = {}) {
1043
+ super();
1044
+ this.closed = false;
1045
+ this._closers = new Map();
1046
+ this._ignoredPaths = new Set();
1047
+ this._throttled = new Map();
1048
+ this._streams = new Set();
1049
+ this._symlinkPaths = new Map();
1050
+ this._watched = new Map();
1051
+ this._pendingWrites = new Map();
1052
+ this._pendingUnlinks = new Map();
1053
+ this._readyCount = 0;
1054
+ this._readyEmitted = false;
1055
+ const awf = _opts.awaitWriteFinish;
1056
+ const DEF_AWF = {
1057
+ stabilityThreshold: 2000,
1058
+ pollInterval: 100
1059
+ };
1060
+ const opts = {
1061
+ // Defaults
1062
+ persistent: true,
1063
+ ignoreInitial: false,
1064
+ ignorePermissionErrors: false,
1065
+ interval: 100,
1066
+ binaryInterval: 300,
1067
+ followSymlinks: true,
1068
+ usePolling: false,
1069
+ // useAsync: false,
1070
+ atomic: true,
1071
+ // NOTE: overwritten later (depends on usePolling)
1072
+ ..._opts,
1073
+ // Change format
1074
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
1075
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === 'object' ? {
1076
+ ...DEF_AWF,
1077
+ ...awf
1078
+ } : false
1079
+ };
1080
+ // Always default to polling on IBM i because fs.watch() is not available on IBM i.
1081
+ if (isIBMi) opts.usePolling = true;
1082
+ // Editor atomic write normalization enabled by default with fs.watch
1083
+ if (opts.atomic === undefined) opts.atomic = !opts.usePolling;
1084
+ // opts.atomic = typeof _opts.atomic === 'number' ? _opts.atomic : 100;
1085
+ // Global override. Useful for developers, who need to force polling for all
1086
+ // instances of chokidar, regardless of usage / dependency depth
1087
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
1088
+ if (envPoll !== undefined) {
1089
+ const envLower = envPoll.toLowerCase();
1090
+ if (envLower === 'false' || envLower === '0') opts.usePolling = false;else if (envLower === 'true' || envLower === '1') opts.usePolling = true;else opts.usePolling = !!envLower;
1091
+ }
1092
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
1093
+ if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
1094
+ // This is done to emit ready only once, but each 'add' will increase that?
1095
+ let readyCalls = 0;
1096
+ this._emitReady = () => {
1097
+ readyCalls++;
1098
+ if (readyCalls >= this._readyCount) {
1099
+ this._emitReady = EMPTY_FN;
1100
+ this._readyEmitted = true;
1101
+ // use process.nextTick to allow time for listener to be bound
1102
+ process.nextTick(() => this.emit(EVENTS.READY));
1103
+ }
1104
+ };
1105
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
1106
+ this._boundRemove = this._remove.bind(this);
1107
+ this.options = opts;
1108
+ this._nodeFsHandler = new NodeFsHandler(this);
1109
+ // You’re frozen when your heart’s not open.
1110
+ Object.freeze(opts);
1111
+ }
1112
+ _addIgnoredPath(matcher) {
1113
+ if (isMatcherObject(matcher)) {
1114
+ // return early if we already have a deeply equal matcher object
1115
+ for (const ignored of this._ignoredPaths) {
1116
+ if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
1117
+ return;
1118
+ }
1119
+ }
1120
+ }
1121
+ this._ignoredPaths.add(matcher);
1122
+ }
1123
+ _removeIgnoredPath(matcher) {
1124
+ this._ignoredPaths.delete(matcher);
1125
+ // now find any matcher objects with the matcher as path
1126
+ if (typeof matcher === 'string') {
1127
+ for (const ignored of this._ignoredPaths) {
1128
+ // TODO (43081j): make this more efficient.
1129
+ // probably just make a `this._ignoredDirectories` or some
1130
+ // such thing.
1131
+ if (isMatcherObject(ignored) && ignored.path === matcher) {
1132
+ this._ignoredPaths.delete(ignored);
1133
+ }
1134
+ }
1135
+ }
1136
+ }
1137
+ // Public methods
1138
+ /**
1139
+ * Adds paths to be watched on an existing FSWatcher instance.
1140
+ * @param paths_ file or file list. Other arguments are unused
1141
+ */
1142
+ add(paths_, _origAdd, _internal) {
1143
+ const {
1144
+ cwd
1145
+ } = this.options;
1146
+ this.closed = false;
1147
+ this._closePromise = undefined;
1148
+ let paths = unifyPaths(paths_);
1149
+ if (cwd) {
1150
+ paths = paths.map(path => {
1151
+ const absPath = getAbsolutePath(path, cwd);
1152
+ // Check `path` instead of `absPath` because the cwd portion can't be a glob
1153
+ return absPath;
1154
+ });
1155
+ }
1156
+ paths.forEach(path => {
1157
+ this._removeIgnoredPath(path);
1158
+ });
1159
+ this._userIgnored = undefined;
1160
+ if (!this._readyCount) this._readyCount = 0;
1161
+ this._readyCount += paths.length;
1162
+ Promise.all(paths.map(async path => {
1163
+ const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, undefined, 0, _origAdd);
1164
+ if (res) this._emitReady();
1165
+ return res;
1166
+ })).then(results => {
1167
+ if (this.closed) return;
1168
+ results.forEach(item => {
1169
+ if (item) this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
1170
+ });
1171
+ });
1172
+ return this;
1173
+ }
1174
+ /**
1175
+ * Close watchers or start ignoring events from specified paths.
1176
+ */
1177
+ unwatch(paths_) {
1178
+ if (this.closed) return this;
1179
+ const paths = unifyPaths(paths_);
1180
+ const {
1181
+ cwd
1182
+ } = this.options;
1183
+ paths.forEach(path => {
1184
+ // convert to absolute path unless relative path already matches
1185
+ if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
1186
+ if (cwd) path = sysPath.join(cwd, path);
1187
+ path = sysPath.resolve(path);
1188
+ }
1189
+ this._closePath(path);
1190
+ this._addIgnoredPath(path);
1191
+ if (this._watched.has(path)) {
1192
+ this._addIgnoredPath({
1193
+ path,
1194
+ recursive: true
1195
+ });
1196
+ }
1197
+ // reset the cached userIgnored anymatch fn
1198
+ // to make ignoredPaths changes effective
1199
+ this._userIgnored = undefined;
1200
+ });
1201
+ return this;
1202
+ }
1203
+ /**
1204
+ * Close watchers and remove all listeners from watched paths.
1205
+ */
1206
+ close() {
1207
+ if (this._closePromise) {
1208
+ return this._closePromise;
1209
+ }
1210
+ this.closed = true;
1211
+ // Memory management.
1212
+ this.removeAllListeners();
1213
+ const closers = [];
1214
+ this._closers.forEach(closerList => closerList.forEach(closer => {
1215
+ const promise = closer();
1216
+ if (promise instanceof Promise) closers.push(promise);
1217
+ }));
1218
+ this._streams.forEach(stream => stream.destroy());
1219
+ this._userIgnored = undefined;
1220
+ this._readyCount = 0;
1221
+ this._readyEmitted = false;
1222
+ this._watched.forEach(dirent => dirent.dispose());
1223
+ this._closers.clear();
1224
+ this._watched.clear();
1225
+ this._streams.clear();
1226
+ this._symlinkPaths.clear();
1227
+ this._throttled.clear();
1228
+ this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
1229
+ return this._closePromise;
1230
+ }
1231
+ /**
1232
+ * Expose list of watched paths
1233
+ * @returns for chaining
1234
+ */
1235
+ getWatched() {
1236
+ const watchList = {};
1237
+ this._watched.forEach((entry, dir) => {
1238
+ const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
1239
+ const index = key || ONE_DOT;
1240
+ watchList[index] = entry.getChildren().sort();
1241
+ });
1242
+ return watchList;
1243
+ }
1244
+ emitWithAll(event, args) {
1245
+ this.emit(event, ...args);
1246
+ if (event !== EVENTS.ERROR) this.emit(EVENTS.ALL, event, ...args);
1247
+ }
1248
+ // Common helpers
1249
+ // --------------
1250
+ /**
1251
+ * Normalize and emit events.
1252
+ * Calling _emit DOES NOT MEAN emit() would be called!
1253
+ * @param event Type of event
1254
+ * @param path File or directory path
1255
+ * @param stats arguments to be passed with event
1256
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1257
+ */
1258
+ async _emit(event, path, stats) {
1259
+ if (this.closed) return;
1260
+ const opts = this.options;
1261
+ if (isWindows) path = sysPath.normalize(path);
1262
+ if (opts.cwd) path = sysPath.relative(opts.cwd, path);
1263
+ const args = [path];
1264
+ if (stats != null) args.push(stats);
1265
+ const awf = opts.awaitWriteFinish;
1266
+ let pw;
1267
+ if (awf && (pw = this._pendingWrites.get(path))) {
1268
+ pw.lastChange = new Date();
1269
+ return this;
1270
+ }
1271
+ if (opts.atomic) {
1272
+ if (event === EVENTS.UNLINK) {
1273
+ this._pendingUnlinks.set(path, [event, ...args]);
1274
+ setTimeout(() => {
1275
+ this._pendingUnlinks.forEach((entry, path) => {
1276
+ this.emit(...entry);
1277
+ this.emit(EVENTS.ALL, ...entry);
1278
+ this._pendingUnlinks.delete(path);
1279
+ });
1280
+ }, typeof opts.atomic === 'number' ? opts.atomic : 100);
1281
+ return this;
1282
+ }
1283
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path)) {
1284
+ event = EVENTS.CHANGE;
1285
+ this._pendingUnlinks.delete(path);
1286
+ }
1287
+ }
1288
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
1289
+ const awfEmit = (err, stats) => {
1290
+ if (err) {
1291
+ event = EVENTS.ERROR;
1292
+ args[0] = err;
1293
+ this.emitWithAll(event, args);
1294
+ } else if (stats) {
1295
+ // if stats doesn't exist the file must have been deleted
1296
+ if (args.length > 1) {
1297
+ args[1] = stats;
1298
+ } else {
1299
+ args.push(stats);
1300
+ }
1301
+ this.emitWithAll(event, args);
1302
+ }
1303
+ };
1304
+ this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
1305
+ return this;
1306
+ }
1307
+ if (event === EVENTS.CHANGE) {
1308
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path, 50);
1309
+ if (isThrottled) return this;
1310
+ }
1311
+ if (opts.alwaysStat && stats === undefined && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
1312
+ const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
1313
+ let stats;
1314
+ try {
1315
+ stats = await stat$1(fullPath);
1316
+ } catch (err) {
1317
+ // do nothing
1318
+ }
1319
+ // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
1320
+ if (!stats || this.closed) return;
1321
+ args.push(stats);
1322
+ }
1323
+ this.emitWithAll(event, args);
1324
+ return this;
1325
+ }
1326
+ /**
1327
+ * Common handler for errors
1328
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1329
+ */
1330
+ _handleError(error) {
1331
+ const code = error && error.code;
1332
+ if (error && code !== 'ENOENT' && code !== 'ENOTDIR' && (!this.options.ignorePermissionErrors || code !== 'EPERM' && code !== 'EACCES')) {
1333
+ this.emit(EVENTS.ERROR, error);
1334
+ }
1335
+ return error || this.closed;
1336
+ }
1337
+ /**
1338
+ * Helper utility for throttling
1339
+ * @param actionType type being throttled
1340
+ * @param path being acted upon
1341
+ * @param timeout duration of time to suppress duplicate actions
1342
+ * @returns tracking object or false if action should be suppressed
1343
+ */
1344
+ _throttle(actionType, path, timeout) {
1345
+ if (!this._throttled.has(actionType)) {
1346
+ this._throttled.set(actionType, new Map());
1347
+ }
1348
+ const action = this._throttled.get(actionType);
1349
+ if (!action) throw new Error('invalid throttle');
1350
+ const actionPath = action.get(path);
1351
+ if (actionPath) {
1352
+ actionPath.count++;
1353
+ return false;
1354
+ }
1355
+ // eslint-disable-next-line prefer-const
1356
+ let timeoutObject;
1357
+ const clear = () => {
1358
+ const item = action.get(path);
1359
+ const count = item ? item.count : 0;
1360
+ action.delete(path);
1361
+ clearTimeout(timeoutObject);
1362
+ if (item) clearTimeout(item.timeoutObject);
1363
+ return count;
1364
+ };
1365
+ timeoutObject = setTimeout(clear, timeout);
1366
+ const thr = {
1367
+ timeoutObject,
1368
+ clear,
1369
+ count: 0
1370
+ };
1371
+ action.set(path, thr);
1372
+ return thr;
1373
+ }
1374
+ _incrReadyCount() {
1375
+ return this._readyCount++;
1376
+ }
1377
+ /**
1378
+ * Awaits write operation to finish.
1379
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
1380
+ * @param path being acted upon
1381
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
1382
+ * @param event
1383
+ * @param awfEmit Callback to be called when ready for event to be emitted.
1384
+ */
1385
+ _awaitWriteFinish(path, threshold, event, awfEmit) {
1386
+ const awf = this.options.awaitWriteFinish;
1387
+ if (typeof awf !== 'object') return;
1388
+ const pollInterval = awf.pollInterval;
1389
+ let timeoutHandler;
1390
+ let fullPath = path;
1391
+ if (this.options.cwd && !sysPath.isAbsolute(path)) {
1392
+ fullPath = sysPath.join(this.options.cwd, path);
1393
+ }
1394
+ const now = new Date();
1395
+ const writes = this._pendingWrites;
1396
+ function awaitWriteFinishFn(prevStat) {
1397
+ stat$2(fullPath, (err, curStat) => {
1398
+ if (err || !writes.has(path)) {
1399
+ if (err && err.code !== 'ENOENT') awfEmit(err);
1400
+ return;
1401
+ }
1402
+ const now = Number(new Date());
1403
+ if (prevStat && curStat.size !== prevStat.size) {
1404
+ writes.get(path).lastChange = now;
1405
+ }
1406
+ const pw = writes.get(path);
1407
+ const df = now - pw.lastChange;
1408
+ if (df >= threshold) {
1409
+ writes.delete(path);
1410
+ awfEmit(undefined, curStat);
1411
+ } else {
1412
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
1413
+ }
1414
+ });
1415
+ }
1416
+ if (!writes.has(path)) {
1417
+ writes.set(path, {
1418
+ lastChange: now,
1419
+ cancelWait: () => {
1420
+ writes.delete(path);
1421
+ clearTimeout(timeoutHandler);
1422
+ return event;
1423
+ }
1424
+ });
1425
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
1426
+ }
1427
+ }
1428
+ /**
1429
+ * Determines whether user has asked to ignore this path.
1430
+ */
1431
+ _isIgnored(path, stats) {
1432
+ if (this.options.atomic && DOT_RE.test(path)) return true;
1433
+ if (!this._userIgnored) {
1434
+ const {
1435
+ cwd
1436
+ } = this.options;
1437
+ const ign = this.options.ignored;
1438
+ const ignored = (ign || []).map(normalizeIgnored(cwd));
1439
+ const ignoredPaths = [...this._ignoredPaths];
1440
+ const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
1441
+ this._userIgnored = anymatch(list);
1442
+ }
1443
+ return this._userIgnored(path, stats);
1444
+ }
1445
+ _isntIgnored(path, stat) {
1446
+ return !this._isIgnored(path, stat);
1447
+ }
1448
+ /**
1449
+ * Provides a set of common helpers and properties relating to symlink handling.
1450
+ * @param path file or directory pattern being watched
1451
+ */
1452
+ _getWatchHelpers(path) {
1453
+ return new WatchHelper(path, this.options.followSymlinks, this);
1454
+ }
1455
+ // Directory helpers
1456
+ // -----------------
1457
+ /**
1458
+ * Provides directory tracking objects
1459
+ * @param directory path of the directory
1460
+ */
1461
+ _getWatchedDir(directory) {
1462
+ const dir = sysPath.resolve(directory);
1463
+ if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
1464
+ return this._watched.get(dir);
1465
+ }
1466
+ // File helpers
1467
+ // ------------
1468
+ /**
1469
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
1470
+ */
1471
+ _hasReadPermissions(stats) {
1472
+ if (this.options.ignorePermissionErrors) return true;
1473
+ return Boolean(Number(stats.mode) & 0o400);
1474
+ }
1475
+ /**
1476
+ * Handles emitting unlink events for
1477
+ * files and directories, and via recursion, for
1478
+ * files and directories within directories that are unlinked
1479
+ * @param directory within which the following item is located
1480
+ * @param item base path of item/directory
1481
+ */
1482
+ _remove(directory, item, isDirectory) {
1483
+ // if what is being deleted is a directory, get that directory's paths
1484
+ // for recursive deleting and cleaning of watched object
1485
+ // if it is not a directory, nestedDirectoryChildren will be empty array
1486
+ const path = sysPath.join(directory, item);
1487
+ const fullPath = sysPath.resolve(path);
1488
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
1489
+ // prevent duplicate handling in case of arriving here nearly simultaneously
1490
+ // via multiple paths (such as _handleFile and _handleDir)
1491
+ if (!this._throttle('remove', path, 100)) return;
1492
+ // if the only watched file is removed, watch for its return
1493
+ if (!isDirectory && this._watched.size === 1) {
1494
+ this.add(directory, item, true);
1495
+ }
1496
+ // This will create a new entry in the watched object in either case
1497
+ // so we got to do the directory check beforehand
1498
+ const wp = this._getWatchedDir(path);
1499
+ const nestedDirectoryChildren = wp.getChildren();
1500
+ // Recursively remove children directories / files.
1501
+ nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
1502
+ // Check if item was on the watched list and remove it
1503
+ const parent = this._getWatchedDir(directory);
1504
+ const wasTracked = parent.has(item);
1505
+ parent.remove(item);
1506
+ // Fixes issue #1042 -> Relative paths were detected and added as symlinks
1507
+ // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
1508
+ // but never removed from the map in case the path was deleted.
1509
+ // This leads to an incorrect state if the path was recreated:
1510
+ // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
1511
+ if (this._symlinkPaths.has(fullPath)) {
1512
+ this._symlinkPaths.delete(fullPath);
1513
+ }
1514
+ // If we wait for this file to be fully written, cancel the wait.
1515
+ let relPath = path;
1516
+ if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
1517
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
1518
+ const event = this._pendingWrites.get(relPath).cancelWait();
1519
+ if (event === EVENTS.ADD) return;
1520
+ }
1521
+ // The Entry will either be a directory that just got removed
1522
+ // or a bogus entry to a file, in either case we have to remove it
1523
+ this._watched.delete(path);
1524
+ this._watched.delete(fullPath);
1525
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
1526
+ if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
1527
+ // Avoid conflicts if we later create another file with the same name
1528
+ this._closePath(path);
1529
+ }
1530
+ /**
1531
+ * Closes all watchers for a path
1532
+ */
1533
+ _closePath(path) {
1534
+ this._closeFile(path);
1535
+ const dir = sysPath.dirname(path);
1536
+ this._getWatchedDir(dir).remove(sysPath.basename(path));
1537
+ }
1538
+ /**
1539
+ * Closes only file-specific watchers
1540
+ */
1541
+ _closeFile(path) {
1542
+ const closers = this._closers.get(path);
1543
+ if (!closers) return;
1544
+ closers.forEach(closer => closer());
1545
+ this._closers.delete(path);
1546
+ }
1547
+ _addPathCloser(path, closer) {
1548
+ if (!closer) return;
1549
+ let list = this._closers.get(path);
1550
+ if (!list) {
1551
+ list = [];
1552
+ this._closers.set(path, list);
1553
+ }
1554
+ list.push(closer);
1555
+ }
1556
+ _readdirp(root, opts) {
1557
+ if (this.closed) return;
1558
+ const options = {
1559
+ type: EVENTS.ALL,
1560
+ alwaysStat: true,
1561
+ lstat: true,
1562
+ ...opts,
1563
+ depth: 0
1564
+ };
1565
+ let stream = readdirp(root, options);
1566
+ this._streams.add(stream);
1567
+ stream.once(STR_CLOSE, () => {
1568
+ stream = undefined;
1569
+ });
1570
+ stream.once(STR_END, () => {
1571
+ if (stream) {
1572
+ this._streams.delete(stream);
1573
+ stream = undefined;
1574
+ }
1575
+ });
1576
+ return stream;
1577
+ }
1578
+ }
1579
+ /**
1580
+ * Instantiates watcher with paths to be tracked.
1581
+ * @param paths file / directory paths
1582
+ * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others
1583
+ * @returns an instance of FSWatcher for chaining.
1584
+ * @example
1585
+ * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
1586
+ * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
1587
+ */
1588
+ function watch(paths, options = {}) {
1589
+ const watcher = new FSWatcher(options);
1590
+ watcher.add(paths);
1591
+ return watcher;
1592
+ }
1593
+
1594
+ const normalizeEvent = (eventName, path) => {
1595
+ return {
1596
+ eventName,
1597
+ path
1598
+ };
1599
+ };
1600
+
38
1601
  const watchFolder = async path => {
39
- const callback = async event => {
1602
+ const callBackInternal = async (eventName, path, stats) => {
1603
+ const event = normalizeEvent(eventName, path);
40
1604
  await invoke('FileWatcher.handleChange', event);
41
1605
  };
42
- // TODO maybe there can be a way to wait for the watcher to be created
43
- // but not wait until all watch events have been fired
44
- void watchInternal(path, {
45
- recursive: true
46
- }, callback);
1606
+ const callback = (eventName, path, stats) => {
1607
+ void callBackInternal(eventName, path);
1608
+ };
1609
+ const watcher = watch(path);
1610
+ watcher.on('all', callback);
1611
+ const {
1612
+ resolve,
1613
+ promise
1614
+ } = Promise.withResolvers();
1615
+ watcher.on('ready', resolve);
1616
+ await promise;
47
1617
  };
48
1618
 
49
1619
  const commandMap = {