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