@rslib/core 0.20.0 → 0.20.1

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.
@@ -0,0 +1,1467 @@
1
+ /*! LICENSE: chokidar.js.LICENSE.txt */
2
+ import { EventEmitter } from "node:events";
3
+ import { stat as external_node_fs_stat, unwatchFile, watch, watchFile } from "node:fs";
4
+ import { lstat, open as promises_open, readdir, realpath as promises_realpath, stat as promises_stat } from "node:fs/promises";
5
+ import { basename as external_node_path_basename, dirname as external_node_path_dirname, extname, isAbsolute, join, normalize, relative as external_node_path_relative, resolve as external_node_path_resolve, sep } from "node:path";
6
+ import { Readable } from "node:stream";
7
+ import { type as external_node_os_type } from "node:os";
8
+ const EntryTypes = {
9
+ FILE_TYPE: 'files',
10
+ DIR_TYPE: 'directories',
11
+ FILE_DIR_TYPE: 'files_directories',
12
+ EVERYTHING_TYPE: 'all'
13
+ };
14
+ const defaultOptions = {
15
+ root: '.',
16
+ fileFilter: (_entryInfo)=>true,
17
+ directoryFilter: (_entryInfo)=>true,
18
+ type: EntryTypes.FILE_TYPE,
19
+ lstat: false,
20
+ depth: 2147483648,
21
+ alwaysStat: false,
22
+ highWaterMark: 4096
23
+ };
24
+ Object.freeze(defaultOptions);
25
+ const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
26
+ const NORMAL_FLOW_ERRORS = new Set([
27
+ 'ENOENT',
28
+ 'EPERM',
29
+ 'EACCES',
30
+ 'ELOOP',
31
+ RECURSIVE_ERROR_CODE
32
+ ]);
33
+ const ALL_TYPES = [
34
+ EntryTypes.DIR_TYPE,
35
+ EntryTypes.EVERYTHING_TYPE,
36
+ EntryTypes.FILE_DIR_TYPE,
37
+ EntryTypes.FILE_TYPE
38
+ ];
39
+ const DIR_TYPES = new Set([
40
+ EntryTypes.DIR_TYPE,
41
+ EntryTypes.EVERYTHING_TYPE,
42
+ EntryTypes.FILE_DIR_TYPE
43
+ ]);
44
+ const FILE_TYPES = new Set([
45
+ EntryTypes.EVERYTHING_TYPE,
46
+ EntryTypes.FILE_DIR_TYPE,
47
+ EntryTypes.FILE_TYPE
48
+ ]);
49
+ const isNormalFlowError = (error)=>NORMAL_FLOW_ERRORS.has(error.code);
50
+ const wantBigintFsStats = 'win32' === process.platform;
51
+ const emptyFn = (_entryInfo)=>true;
52
+ const normalizeFilter = (filter)=>{
53
+ if (void 0 === filter) return emptyFn;
54
+ if ('function' == typeof filter) return filter;
55
+ if ('string' == typeof filter) {
56
+ const fl = filter.trim();
57
+ return (entry)=>entry.basename === fl;
58
+ }
59
+ if (Array.isArray(filter)) {
60
+ const trItems = filter.map((item)=>item.trim());
61
+ return (entry)=>trItems.some((f)=>entry.basename === f);
62
+ }
63
+ return emptyFn;
64
+ };
65
+ class ReaddirpStream extends Readable {
66
+ parents;
67
+ reading;
68
+ parent;
69
+ _stat;
70
+ _maxDepth;
71
+ _wantsDir;
72
+ _wantsFile;
73
+ _wantsEverything;
74
+ _root;
75
+ _isDirent;
76
+ _statsProp;
77
+ _rdOptions;
78
+ _fileFilter;
79
+ _directoryFilter;
80
+ constructor(options = {}){
81
+ super({
82
+ objectMode: true,
83
+ autoDestroy: true,
84
+ highWaterMark: options.highWaterMark
85
+ });
86
+ const opts = {
87
+ ...defaultOptions,
88
+ ...options
89
+ };
90
+ const { root, type } = opts;
91
+ this._fileFilter = normalizeFilter(opts.fileFilter);
92
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
93
+ const statMethod = opts.lstat ? lstat : promises_stat;
94
+ if (wantBigintFsStats) this._stat = (path)=>statMethod(path, {
95
+ bigint: true
96
+ });
97
+ else this._stat = statMethod;
98
+ this._maxDepth = null != opts.depth && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;
99
+ this._wantsDir = type ? DIR_TYPES.has(type) : false;
100
+ this._wantsFile = type ? FILE_TYPES.has(type) : false;
101
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
102
+ this._root = external_node_path_resolve(root);
103
+ this._isDirent = !opts.alwaysStat;
104
+ this._statsProp = this._isDirent ? 'dirent' : 'stats';
105
+ this._rdOptions = {
106
+ encoding: 'utf8',
107
+ withFileTypes: this._isDirent
108
+ };
109
+ this.parents = [
110
+ this._exploreDir(root, 1)
111
+ ];
112
+ this.reading = false;
113
+ this.parent = void 0;
114
+ }
115
+ async _read(batch) {
116
+ if (this.reading) return;
117
+ this.reading = true;
118
+ try {
119
+ while(!this.destroyed && batch > 0){
120
+ const par = this.parent;
121
+ const fil = par && par.files;
122
+ if (fil && fil.length > 0) {
123
+ const { path, depth } = par;
124
+ const slice = fil.splice(0, batch).map((dirent)=>this._formatEntry(dirent, path));
125
+ const awaited = await Promise.all(slice);
126
+ for (const entry of awaited){
127
+ if (!entry) continue;
128
+ if (this.destroyed) return;
129
+ const entryType = await this._getEntryType(entry);
130
+ if ('directory' === entryType && this._directoryFilter(entry)) {
131
+ if (depth <= this._maxDepth) this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
132
+ if (this._wantsDir) {
133
+ this.push(entry);
134
+ batch--;
135
+ }
136
+ } else if (('file' === entryType || this._includeAsFile(entry)) && this._fileFilter(entry)) {
137
+ if (this._wantsFile) {
138
+ this.push(entry);
139
+ batch--;
140
+ }
141
+ }
142
+ }
143
+ } else {
144
+ const parent = this.parents.pop();
145
+ if (!parent) {
146
+ this.push(null);
147
+ break;
148
+ }
149
+ this.parent = await parent;
150
+ if (this.destroyed) return;
151
+ }
152
+ }
153
+ } catch (error) {
154
+ this.destroy(error);
155
+ } finally{
156
+ this.reading = false;
157
+ }
158
+ }
159
+ async _exploreDir(path, depth) {
160
+ let files;
161
+ try {
162
+ files = await readdir(path, this._rdOptions);
163
+ } catch (error) {
164
+ this._onError(error);
165
+ }
166
+ return {
167
+ files,
168
+ depth,
169
+ path
170
+ };
171
+ }
172
+ async _formatEntry(dirent, path) {
173
+ let entry;
174
+ const basename = this._isDirent ? dirent.name : dirent;
175
+ try {
176
+ const fullPath = external_node_path_resolve(join(path, basename));
177
+ entry = {
178
+ path: external_node_path_relative(this._root, fullPath),
179
+ fullPath,
180
+ basename
181
+ };
182
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
183
+ } catch (err) {
184
+ this._onError(err);
185
+ return;
186
+ }
187
+ return entry;
188
+ }
189
+ _onError(err) {
190
+ if (isNormalFlowError(err) && !this.destroyed) this.emit('warn', err);
191
+ else this.destroy(err);
192
+ }
193
+ async _getEntryType(entry) {
194
+ if (!entry && this._statsProp in entry) return '';
195
+ const stats = entry[this._statsProp];
196
+ if (stats.isFile()) return 'file';
197
+ if (stats.isDirectory()) return 'directory';
198
+ if (stats && stats.isSymbolicLink()) {
199
+ const full = entry.fullPath;
200
+ try {
201
+ const entryRealPath = await promises_realpath(full);
202
+ const entryRealPathStats = await lstat(entryRealPath);
203
+ if (entryRealPathStats.isFile()) return 'file';
204
+ if (entryRealPathStats.isDirectory()) {
205
+ const len = entryRealPath.length;
206
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === sep) {
207
+ const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
208
+ recursiveError.code = RECURSIVE_ERROR_CODE;
209
+ return this._onError(recursiveError);
210
+ }
211
+ return 'directory';
212
+ }
213
+ } catch (error) {
214
+ this._onError(error);
215
+ return '';
216
+ }
217
+ }
218
+ }
219
+ _includeAsFile(entry) {
220
+ const stats = entry && entry[this._statsProp];
221
+ return stats && this._wantsEverything && !stats.isDirectory();
222
+ }
223
+ }
224
+ function readdirp(root, options = {}) {
225
+ let type = options.entryType || options.type;
226
+ if ('both' === type) type = EntryTypes.FILE_DIR_TYPE;
227
+ if (type) options.type = type;
228
+ if (root) {
229
+ if ('string' != typeof root) throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
230
+ else if (type && !ALL_TYPES.includes(type)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
231
+ } else throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
232
+ options.root = root;
233
+ return new ReaddirpStream(options);
234
+ }
235
+ const STR_DATA = 'data';
236
+ const STR_END = 'end';
237
+ const STR_CLOSE = 'close';
238
+ const EMPTY_FN = ()=>{};
239
+ const pl = process.platform;
240
+ const isWindows = 'win32' === pl;
241
+ const isMacos = 'darwin' === pl;
242
+ const isLinux = 'linux' === pl;
243
+ const isFreeBSD = 'freebsd' === pl;
244
+ const isIBMi = 'OS400' === external_node_os_type();
245
+ const EVENTS = {
246
+ ALL: 'all',
247
+ READY: 'ready',
248
+ ADD: 'add',
249
+ CHANGE: 'change',
250
+ ADD_DIR: 'addDir',
251
+ UNLINK: 'unlink',
252
+ UNLINK_DIR: 'unlinkDir',
253
+ RAW: 'raw',
254
+ ERROR: 'error'
255
+ };
256
+ const EV = EVENTS;
257
+ const THROTTLE_MODE_WATCH = 'watch';
258
+ const statMethods = {
259
+ lstat: lstat,
260
+ stat: promises_stat
261
+ };
262
+ const KEY_LISTENERS = 'listeners';
263
+ const KEY_ERR = 'errHandlers';
264
+ const KEY_RAW = 'rawEmitters';
265
+ const HANDLER_KEYS = [
266
+ KEY_LISTENERS,
267
+ KEY_ERR,
268
+ KEY_RAW
269
+ ];
270
+ const binaryExtensions = new Set([
271
+ '3dm',
272
+ '3ds',
273
+ '3g2',
274
+ '3gp',
275
+ '7z',
276
+ 'a',
277
+ 'aac',
278
+ 'adp',
279
+ 'afdesign',
280
+ 'afphoto',
281
+ 'afpub',
282
+ 'ai',
283
+ 'aif',
284
+ 'aiff',
285
+ 'alz',
286
+ 'ape',
287
+ 'apk',
288
+ 'appimage',
289
+ 'ar',
290
+ 'arj',
291
+ 'asf',
292
+ 'au',
293
+ 'avi',
294
+ 'bak',
295
+ 'baml',
296
+ 'bh',
297
+ 'bin',
298
+ 'bk',
299
+ 'bmp',
300
+ 'btif',
301
+ 'bz2',
302
+ 'bzip2',
303
+ 'cab',
304
+ 'caf',
305
+ 'cgm',
306
+ 'class',
307
+ 'cmx',
308
+ 'cpio',
309
+ 'cr2',
310
+ 'cur',
311
+ 'dat',
312
+ 'dcm',
313
+ 'deb',
314
+ 'dex',
315
+ 'djvu',
316
+ 'dll',
317
+ 'dmg',
318
+ 'dng',
319
+ 'doc',
320
+ 'docm',
321
+ 'docx',
322
+ 'dot',
323
+ 'dotm',
324
+ 'dra',
325
+ 'DS_Store',
326
+ 'dsk',
327
+ 'dts',
328
+ 'dtshd',
329
+ 'dvb',
330
+ 'dwg',
331
+ 'dxf',
332
+ 'ecelp4800',
333
+ 'ecelp7470',
334
+ 'ecelp9600',
335
+ 'egg',
336
+ 'eol',
337
+ 'eot',
338
+ 'epub',
339
+ 'exe',
340
+ 'f4v',
341
+ 'fbs',
342
+ 'fh',
343
+ 'fla',
344
+ 'flac',
345
+ 'flatpak',
346
+ 'fli',
347
+ 'flv',
348
+ 'fpx',
349
+ 'fst',
350
+ 'fvt',
351
+ 'g3',
352
+ 'gh',
353
+ 'gif',
354
+ 'graffle',
355
+ 'gz',
356
+ 'gzip',
357
+ 'h261',
358
+ 'h263',
359
+ 'h264',
360
+ 'icns',
361
+ 'ico',
362
+ 'ief',
363
+ 'img',
364
+ 'ipa',
365
+ 'iso',
366
+ 'jar',
367
+ 'jpeg',
368
+ 'jpg',
369
+ 'jpgv',
370
+ 'jpm',
371
+ 'jxr',
372
+ 'key',
373
+ 'ktx',
374
+ 'lha',
375
+ 'lib',
376
+ 'lvp',
377
+ 'lz',
378
+ 'lzh',
379
+ 'lzma',
380
+ 'lzo',
381
+ 'm3u',
382
+ 'm4a',
383
+ 'm4v',
384
+ 'mar',
385
+ 'mdi',
386
+ 'mht',
387
+ 'mid',
388
+ 'midi',
389
+ 'mj2',
390
+ 'mka',
391
+ 'mkv',
392
+ 'mmr',
393
+ 'mng',
394
+ 'mobi',
395
+ 'mov',
396
+ 'movie',
397
+ 'mp3',
398
+ 'mp4',
399
+ 'mp4a',
400
+ 'mpeg',
401
+ 'mpg',
402
+ 'mpga',
403
+ 'mxu',
404
+ 'nef',
405
+ 'npx',
406
+ 'numbers',
407
+ 'nupkg',
408
+ 'o',
409
+ 'odp',
410
+ 'ods',
411
+ 'odt',
412
+ 'oga',
413
+ 'ogg',
414
+ 'ogv',
415
+ 'otf',
416
+ 'ott',
417
+ 'pages',
418
+ 'pbm',
419
+ 'pcx',
420
+ 'pdb',
421
+ 'pdf',
422
+ 'pea',
423
+ 'pgm',
424
+ 'pic',
425
+ 'png',
426
+ 'pnm',
427
+ 'pot',
428
+ 'potm',
429
+ 'potx',
430
+ 'ppa',
431
+ 'ppam',
432
+ 'ppm',
433
+ 'pps',
434
+ 'ppsm',
435
+ 'ppsx',
436
+ 'ppt',
437
+ 'pptm',
438
+ 'pptx',
439
+ 'psd',
440
+ 'pya',
441
+ 'pyc',
442
+ 'pyo',
443
+ 'pyv',
444
+ 'qt',
445
+ 'rar',
446
+ 'ras',
447
+ 'raw',
448
+ 'resources',
449
+ 'rgb',
450
+ 'rip',
451
+ 'rlc',
452
+ 'rmf',
453
+ 'rmvb',
454
+ 'rpm',
455
+ 'rtf',
456
+ 'rz',
457
+ 's3m',
458
+ 's7z',
459
+ 'scpt',
460
+ 'sgi',
461
+ 'shar',
462
+ 'snap',
463
+ 'sil',
464
+ 'sketch',
465
+ 'slk',
466
+ 'smv',
467
+ 'snk',
468
+ 'so',
469
+ 'stl',
470
+ 'suo',
471
+ 'sub',
472
+ 'swf',
473
+ 'tar',
474
+ 'tbz',
475
+ 'tbz2',
476
+ 'tga',
477
+ 'tgz',
478
+ 'thmx',
479
+ 'tif',
480
+ 'tiff',
481
+ 'tlz',
482
+ 'ttc',
483
+ 'ttf',
484
+ 'txz',
485
+ 'udf',
486
+ 'uvh',
487
+ 'uvi',
488
+ 'uvm',
489
+ 'uvp',
490
+ 'uvs',
491
+ 'uvu',
492
+ 'viv',
493
+ 'vob',
494
+ 'war',
495
+ 'wav',
496
+ 'wax',
497
+ 'wbmp',
498
+ 'wdp',
499
+ 'weba',
500
+ 'webm',
501
+ 'webp',
502
+ 'whl',
503
+ 'wim',
504
+ 'wm',
505
+ 'wma',
506
+ 'wmv',
507
+ 'wmx',
508
+ 'woff',
509
+ 'woff2',
510
+ 'wrm',
511
+ 'wvx',
512
+ 'xbm',
513
+ 'xif',
514
+ 'xla',
515
+ 'xlam',
516
+ 'xls',
517
+ 'xlsb',
518
+ 'xlsm',
519
+ 'xlsx',
520
+ 'xlt',
521
+ 'xltm',
522
+ 'xltx',
523
+ 'xm',
524
+ 'xmind',
525
+ 'xpi',
526
+ 'xpm',
527
+ 'xwd',
528
+ 'xz',
529
+ 'z',
530
+ 'zip',
531
+ 'zipx'
532
+ ]);
533
+ const isBinaryPath = (filePath)=>binaryExtensions.has(extname(filePath).slice(1).toLowerCase());
534
+ const foreach = (val, fn)=>{
535
+ if (val instanceof Set) val.forEach(fn);
536
+ else fn(val);
537
+ };
538
+ const addAndConvert = (main, prop, item)=>{
539
+ let container = main[prop];
540
+ if (!(container instanceof Set)) main[prop] = container = new Set([
541
+ container
542
+ ]);
543
+ container.add(item);
544
+ };
545
+ const clearItem = (cont)=>(key)=>{
546
+ const set = cont[key];
547
+ if (set instanceof Set) set.clear();
548
+ else delete cont[key];
549
+ };
550
+ const delFromSet = (main, prop, item)=>{
551
+ const container = main[prop];
552
+ if (container instanceof Set) container.delete(item);
553
+ else if (container === item) delete main[prop];
554
+ };
555
+ const isEmptySet = (val)=>val instanceof Set ? 0 === val.size : !val;
556
+ const FsWatchInstances = new Map();
557
+ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
558
+ const handleEvent = (rawEvent, evPath)=>{
559
+ listener(path);
560
+ emitRaw(rawEvent, evPath, {
561
+ watchedPath: path
562
+ });
563
+ if (evPath && path !== evPath) fsWatchBroadcast(external_node_path_resolve(path, evPath), KEY_LISTENERS, join(path, evPath));
564
+ };
565
+ try {
566
+ return watch(path, {
567
+ persistent: options.persistent
568
+ }, handleEvent);
569
+ } catch (error) {
570
+ errHandler(error);
571
+ return;
572
+ }
573
+ }
574
+ const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3)=>{
575
+ const cont = FsWatchInstances.get(fullPath);
576
+ if (!cont) return;
577
+ foreach(cont[listenerType], (listener)=>{
578
+ listener(val1, val2, val3);
579
+ });
580
+ };
581
+ const setFsWatchListener = (path, fullPath, options, handlers)=>{
582
+ const { listener, errHandler, rawEmitter } = handlers;
583
+ let cont = FsWatchInstances.get(fullPath);
584
+ let watcher;
585
+ if (!options.persistent) {
586
+ watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
587
+ if (!watcher) return;
588
+ return watcher.close.bind(watcher);
589
+ }
590
+ if (cont) {
591
+ addAndConvert(cont, KEY_LISTENERS, listener);
592
+ addAndConvert(cont, KEY_ERR, errHandler);
593
+ addAndConvert(cont, KEY_RAW, rawEmitter);
594
+ } else {
595
+ watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
596
+ if (!watcher) return;
597
+ watcher.on(EV.ERROR, async (error)=>{
598
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
599
+ if (cont) cont.watcherUnusable = true;
600
+ if (isWindows && 'EPERM' === error.code) try {
601
+ const fd = await promises_open(path, 'r');
602
+ await fd.close();
603
+ broadcastErr(error);
604
+ } catch (err) {}
605
+ else broadcastErr(error);
606
+ });
607
+ cont = {
608
+ listeners: listener,
609
+ errHandlers: errHandler,
610
+ rawEmitters: rawEmitter,
611
+ watcher
612
+ };
613
+ FsWatchInstances.set(fullPath, cont);
614
+ }
615
+ return ()=>{
616
+ delFromSet(cont, KEY_LISTENERS, listener);
617
+ delFromSet(cont, KEY_ERR, errHandler);
618
+ delFromSet(cont, KEY_RAW, rawEmitter);
619
+ if (isEmptySet(cont.listeners)) {
620
+ cont.watcher.close();
621
+ FsWatchInstances.delete(fullPath);
622
+ HANDLER_KEYS.forEach(clearItem(cont));
623
+ cont.watcher = void 0;
624
+ Object.freeze(cont);
625
+ }
626
+ };
627
+ };
628
+ const FsWatchFileInstances = new Map();
629
+ const setFsWatchFileListener = (path, fullPath, options, handlers)=>{
630
+ const { listener, rawEmitter } = handlers;
631
+ let cont = FsWatchFileInstances.get(fullPath);
632
+ const copts = cont && cont.options;
633
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
634
+ unwatchFile(fullPath);
635
+ cont = void 0;
636
+ }
637
+ if (cont) {
638
+ addAndConvert(cont, KEY_LISTENERS, listener);
639
+ addAndConvert(cont, KEY_RAW, rawEmitter);
640
+ } else {
641
+ cont = {
642
+ listeners: listener,
643
+ rawEmitters: rawEmitter,
644
+ options,
645
+ watcher: watchFile(fullPath, options, (curr, prev)=>{
646
+ foreach(cont.rawEmitters, (rawEmitter)=>{
647
+ rawEmitter(EV.CHANGE, fullPath, {
648
+ curr,
649
+ prev
650
+ });
651
+ });
652
+ const currmtime = curr.mtimeMs;
653
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || 0 === currmtime) foreach(cont.listeners, (listener)=>listener(path, curr));
654
+ })
655
+ };
656
+ FsWatchFileInstances.set(fullPath, cont);
657
+ }
658
+ return ()=>{
659
+ delFromSet(cont, KEY_LISTENERS, listener);
660
+ delFromSet(cont, KEY_RAW, rawEmitter);
661
+ if (isEmptySet(cont.listeners)) {
662
+ FsWatchFileInstances.delete(fullPath);
663
+ unwatchFile(fullPath);
664
+ cont.options = cont.watcher = void 0;
665
+ Object.freeze(cont);
666
+ }
667
+ };
668
+ };
669
+ class NodeFsHandler {
670
+ fsw;
671
+ _boundHandleError;
672
+ constructor(fsW){
673
+ this.fsw = fsW;
674
+ this._boundHandleError = (error)=>fsW._handleError(error);
675
+ }
676
+ _watchWithNodeFs(path, listener) {
677
+ const opts = this.fsw.options;
678
+ const directory = external_node_path_dirname(path);
679
+ const basename = external_node_path_basename(path);
680
+ const parent = this.fsw._getWatchedDir(directory);
681
+ parent.add(basename);
682
+ const absolutePath = external_node_path_resolve(path);
683
+ const options = {
684
+ persistent: opts.persistent
685
+ };
686
+ if (!listener) listener = EMPTY_FN;
687
+ let closer;
688
+ if (opts.usePolling) {
689
+ const enableBin = opts.interval !== opts.binaryInterval;
690
+ options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
691
+ closer = setFsWatchFileListener(path, absolutePath, options, {
692
+ listener,
693
+ rawEmitter: this.fsw._emitRaw
694
+ });
695
+ } else closer = setFsWatchListener(path, absolutePath, options, {
696
+ listener,
697
+ errHandler: this._boundHandleError,
698
+ rawEmitter: this.fsw._emitRaw
699
+ });
700
+ return closer;
701
+ }
702
+ _handleFile(file, stats, initialAdd) {
703
+ if (this.fsw.closed) return;
704
+ const dirname = external_node_path_dirname(file);
705
+ const basename = external_node_path_basename(file);
706
+ const parent = this.fsw._getWatchedDir(dirname);
707
+ let prevStats = stats;
708
+ if (parent.has(basename)) return;
709
+ const listener = async (path, newStats)=>{
710
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
711
+ if (newStats && 0 !== newStats.mtimeMs) {
712
+ if (parent.has(basename)) {
713
+ const at = newStats.atimeMs;
714
+ const mt = newStats.mtimeMs;
715
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats);
716
+ prevStats = newStats;
717
+ }
718
+ } else try {
719
+ const newStats = await promises_stat(file);
720
+ if (this.fsw.closed) return;
721
+ const at = newStats.atimeMs;
722
+ const mt = newStats.mtimeMs;
723
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats);
724
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {
725
+ this.fsw._closeFile(path);
726
+ prevStats = newStats;
727
+ const closer = this._watchWithNodeFs(file, listener);
728
+ if (closer) this.fsw._addPathCloser(path, closer);
729
+ } else prevStats = newStats;
730
+ } catch (error) {
731
+ this.fsw._remove(dirname, basename);
732
+ }
733
+ };
734
+ const closer = this._watchWithNodeFs(file, listener);
735
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
736
+ if (!this.fsw._throttle(EV.ADD, file, 0)) return;
737
+ this.fsw._emit(EV.ADD, file, stats);
738
+ }
739
+ return closer;
740
+ }
741
+ async _handleSymlink(entry, directory, path, item) {
742
+ if (this.fsw.closed) return;
743
+ const full = entry.fullPath;
744
+ const dir = this.fsw._getWatchedDir(directory);
745
+ if (!this.fsw.options.followSymlinks) {
746
+ this.fsw._incrReadyCount();
747
+ let linkPath;
748
+ try {
749
+ linkPath = await promises_realpath(path);
750
+ } catch (e) {
751
+ this.fsw._emitReady();
752
+ return true;
753
+ }
754
+ if (this.fsw.closed) return;
755
+ if (dir.has(item)) {
756
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
757
+ this.fsw._symlinkPaths.set(full, linkPath);
758
+ this.fsw._emit(EV.CHANGE, path, entry.stats);
759
+ }
760
+ } else {
761
+ dir.add(item);
762
+ this.fsw._symlinkPaths.set(full, linkPath);
763
+ this.fsw._emit(EV.ADD, path, entry.stats);
764
+ }
765
+ this.fsw._emitReady();
766
+ return true;
767
+ }
768
+ if (this.fsw._symlinkPaths.has(full)) return true;
769
+ this.fsw._symlinkPaths.set(full, true);
770
+ }
771
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
772
+ directory = join(directory, '');
773
+ const throttleKey = target ? `${directory}:${target}` : directory;
774
+ throttler = this.fsw._throttle('readdir', throttleKey, 1000);
775
+ if (!throttler) return;
776
+ const previous = this.fsw._getWatchedDir(wh.path);
777
+ const current = new Set();
778
+ let stream = this.fsw._readdirp(directory, {
779
+ fileFilter: (entry)=>wh.filterPath(entry),
780
+ directoryFilter: (entry)=>wh.filterDir(entry)
781
+ });
782
+ if (!stream) return;
783
+ stream.on(STR_DATA, async (entry)=>{
784
+ if (this.fsw.closed) {
785
+ stream = void 0;
786
+ return;
787
+ }
788
+ const item = entry.path;
789
+ let path = join(directory, item);
790
+ current.add(item);
791
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) return;
792
+ if (this.fsw.closed) {
793
+ stream = void 0;
794
+ return;
795
+ }
796
+ if (item === target || !target && !previous.has(item)) {
797
+ this.fsw._incrReadyCount();
798
+ path = join(dir, external_node_path_relative(dir, path));
799
+ this._addToNodeFs(path, initialAdd, wh, depth + 1);
800
+ }
801
+ }).on(EV.ERROR, this._boundHandleError);
802
+ return new Promise((resolve, reject)=>{
803
+ if (!stream) return reject();
804
+ stream.once(STR_END, ()=>{
805
+ if (this.fsw.closed) {
806
+ stream = void 0;
807
+ return;
808
+ }
809
+ const wasThrottled = throttler ? throttler.clear() : false;
810
+ resolve(void 0);
811
+ previous.getChildren().filter((item)=>item !== directory && !current.has(item)).forEach((item)=>{
812
+ this.fsw._remove(directory, item);
813
+ });
814
+ stream = void 0;
815
+ if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
816
+ });
817
+ });
818
+ }
819
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
820
+ const parentDir = this.fsw._getWatchedDir(external_node_path_dirname(dir));
821
+ const tracked = parentDir.has(external_node_path_basename(dir));
822
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) this.fsw._emit(EV.ADD_DIR, dir, stats);
823
+ parentDir.add(external_node_path_basename(dir));
824
+ this.fsw._getWatchedDir(dir);
825
+ let throttler;
826
+ let closer;
827
+ const oDepth = this.fsw.options.depth;
828
+ if ((null == oDepth || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
829
+ if (!target) {
830
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
831
+ if (this.fsw.closed) return;
832
+ }
833
+ closer = this._watchWithNodeFs(dir, (dirPath, stats)=>{
834
+ if (stats && 0 === stats.mtimeMs) return;
835
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
836
+ });
837
+ }
838
+ return closer;
839
+ }
840
+ async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
841
+ const ready = this.fsw._emitReady;
842
+ if (this.fsw._isIgnored(path) || this.fsw.closed) {
843
+ ready();
844
+ return false;
845
+ }
846
+ const wh = this.fsw._getWatchHelpers(path);
847
+ if (priorWh) {
848
+ wh.filterPath = (entry)=>priorWh.filterPath(entry);
849
+ wh.filterDir = (entry)=>priorWh.filterDir(entry);
850
+ }
851
+ try {
852
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
853
+ if (this.fsw.closed) return;
854
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
855
+ ready();
856
+ return false;
857
+ }
858
+ const follow = this.fsw.options.followSymlinks;
859
+ let closer;
860
+ if (stats.isDirectory()) {
861
+ const absPath = external_node_path_resolve(path);
862
+ const targetPath = follow ? await promises_realpath(path) : path;
863
+ if (this.fsw.closed) return;
864
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
865
+ if (this.fsw.closed) return;
866
+ if (absPath !== targetPath && void 0 !== targetPath) this.fsw._symlinkPaths.set(absPath, targetPath);
867
+ } else if (stats.isSymbolicLink()) {
868
+ const targetPath = follow ? await promises_realpath(path) : path;
869
+ if (this.fsw.closed) return;
870
+ const parent = external_node_path_dirname(wh.watchPath);
871
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
872
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
873
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
874
+ if (this.fsw.closed) return;
875
+ if (void 0 !== targetPath) this.fsw._symlinkPaths.set(external_node_path_resolve(path), targetPath);
876
+ } else closer = this._handleFile(wh.watchPath, stats, initialAdd);
877
+ ready();
878
+ if (closer) this.fsw._addPathCloser(path, closer);
879
+ return false;
880
+ } catch (error) {
881
+ if (this.fsw._handleError(error)) {
882
+ ready();
883
+ return path;
884
+ }
885
+ }
886
+ }
887
+ }
888
+ /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */ const SLASH = '/';
889
+ const SLASH_SLASH = '//';
890
+ const ONE_DOT = '.';
891
+ const TWO_DOTS = '..';
892
+ const STRING_TYPE = 'string';
893
+ const BACK_SLASH_RE = /\\/g;
894
+ const DOUBLE_SLASH_RE = /\/\//g;
895
+ const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
896
+ const REPLACER_RE = /^\.[/\\]/;
897
+ function arrify(item) {
898
+ return Array.isArray(item) ? item : [
899
+ item
900
+ ];
901
+ }
902
+ const isMatcherObject = (matcher)=>'object' == typeof matcher && null !== matcher && !(matcher instanceof RegExp);
903
+ function createPattern(matcher) {
904
+ if ('function' == typeof matcher) return matcher;
905
+ if ('string' == typeof matcher) return (string)=>matcher === string;
906
+ if (matcher instanceof RegExp) return (string)=>matcher.test(string);
907
+ if ('object' == typeof matcher && null !== matcher) return (string)=>{
908
+ if (matcher.path === string) return true;
909
+ if (matcher.recursive) {
910
+ const relative = external_node_path_relative(matcher.path, string);
911
+ if (!relative) return false;
912
+ return !relative.startsWith('..') && !isAbsolute(relative);
913
+ }
914
+ return false;
915
+ };
916
+ return ()=>false;
917
+ }
918
+ function normalizePath(path) {
919
+ if ('string' != typeof path) throw new Error('string expected');
920
+ path = normalize(path);
921
+ path = path.replace(/\\/g, '/');
922
+ let prepend = false;
923
+ if (path.startsWith('//')) prepend = true;
924
+ path = path.replace(DOUBLE_SLASH_RE, '/');
925
+ if (prepend) path = '/' + path;
926
+ return path;
927
+ }
928
+ function matchPatterns(patterns, testString, stats) {
929
+ const path = normalizePath(testString);
930
+ for(let index = 0; index < patterns.length; index++){
931
+ const pattern = patterns[index];
932
+ if (pattern(path, stats)) return true;
933
+ }
934
+ return false;
935
+ }
936
+ function anymatch(matchers, testString) {
937
+ if (null == matchers) throw new TypeError('anymatch: specify first argument');
938
+ const matchersArray = arrify(matchers);
939
+ const patterns = matchersArray.map((matcher)=>createPattern(matcher));
940
+ if (null == testString) return (testString, stats)=>matchPatterns(patterns, testString, stats);
941
+ return matchPatterns(patterns, testString);
942
+ }
943
+ const unifyPaths = (paths_)=>{
944
+ const paths = arrify(paths_).flat();
945
+ if (!paths.every((p)=>typeof p === STRING_TYPE)) throw new TypeError(`Non-string provided as watch path: ${paths}`);
946
+ return paths.map(normalizePathToUnix);
947
+ };
948
+ const toUnix = (string)=>{
949
+ let str = string.replace(BACK_SLASH_RE, SLASH);
950
+ let prepend = false;
951
+ if (str.startsWith(SLASH_SLASH)) prepend = true;
952
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
953
+ if (prepend) str = SLASH + str;
954
+ return str;
955
+ };
956
+ const normalizePathToUnix = (path)=>toUnix(normalize(toUnix(path)));
957
+ const normalizeIgnored = (cwd = '')=>(path)=>{
958
+ if ('string' == typeof path) return normalizePathToUnix(isAbsolute(path) ? path : join(cwd, path));
959
+ return path;
960
+ };
961
+ const getAbsolutePath = (path, cwd)=>{
962
+ if (isAbsolute(path)) return path;
963
+ return join(cwd, path);
964
+ };
965
+ const EMPTY_SET = Object.freeze(new Set());
966
+ class DirEntry {
967
+ path;
968
+ _removeWatcher;
969
+ items;
970
+ constructor(dir, removeWatcher){
971
+ this.path = dir;
972
+ this._removeWatcher = removeWatcher;
973
+ this.items = new Set();
974
+ }
975
+ add(item) {
976
+ const { items } = this;
977
+ if (!items) return;
978
+ if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
979
+ }
980
+ async remove(item) {
981
+ const { items } = this;
982
+ if (!items) return;
983
+ items.delete(item);
984
+ if (items.size > 0) return;
985
+ const dir = this.path;
986
+ try {
987
+ await readdir(dir);
988
+ } catch (err) {
989
+ if (this._removeWatcher) this._removeWatcher(external_node_path_dirname(dir), external_node_path_basename(dir));
990
+ }
991
+ }
992
+ has(item) {
993
+ const { items } = this;
994
+ if (!items) return;
995
+ return items.has(item);
996
+ }
997
+ getChildren() {
998
+ const { items } = this;
999
+ if (!items) return [];
1000
+ return [
1001
+ ...items.values()
1002
+ ];
1003
+ }
1004
+ dispose() {
1005
+ this.items.clear();
1006
+ this.path = '';
1007
+ this._removeWatcher = EMPTY_FN;
1008
+ this.items = EMPTY_SET;
1009
+ Object.freeze(this);
1010
+ }
1011
+ }
1012
+ const STAT_METHOD_F = 'stat';
1013
+ const STAT_METHOD_L = 'lstat';
1014
+ class WatchHelper {
1015
+ fsw;
1016
+ path;
1017
+ watchPath;
1018
+ fullWatchPath;
1019
+ dirParts;
1020
+ followSymlinks;
1021
+ statMethod;
1022
+ constructor(path, follow, fsw){
1023
+ this.fsw = fsw;
1024
+ const watchPath = path;
1025
+ this.path = path = path.replace(REPLACER_RE, '');
1026
+ this.watchPath = watchPath;
1027
+ this.fullWatchPath = external_node_path_resolve(watchPath);
1028
+ this.dirParts = [];
1029
+ this.dirParts.forEach((parts)=>{
1030
+ if (parts.length > 1) parts.pop();
1031
+ });
1032
+ this.followSymlinks = follow;
1033
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
1034
+ }
1035
+ entryPath(entry) {
1036
+ return join(this.watchPath, external_node_path_relative(this.watchPath, entry.fullPath));
1037
+ }
1038
+ filterPath(entry) {
1039
+ const { stats } = entry;
1040
+ if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
1041
+ const resolvedPath = this.entryPath(entry);
1042
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
1043
+ }
1044
+ filterDir(entry) {
1045
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
1046
+ }
1047
+ }
1048
+ class FSWatcher extends EventEmitter {
1049
+ closed;
1050
+ options;
1051
+ _closers;
1052
+ _ignoredPaths;
1053
+ _throttled;
1054
+ _streams;
1055
+ _symlinkPaths;
1056
+ _watched;
1057
+ _pendingWrites;
1058
+ _pendingUnlinks;
1059
+ _readyCount;
1060
+ _emitReady;
1061
+ _closePromise;
1062
+ _userIgnored;
1063
+ _readyEmitted;
1064
+ _emitRaw;
1065
+ _boundRemove;
1066
+ _nodeFsHandler;
1067
+ constructor(_opts = {}){
1068
+ super();
1069
+ this.closed = false;
1070
+ this._closers = new Map();
1071
+ this._ignoredPaths = new Set();
1072
+ this._throttled = new Map();
1073
+ this._streams = new Set();
1074
+ this._symlinkPaths = new Map();
1075
+ this._watched = new Map();
1076
+ this._pendingWrites = new Map();
1077
+ this._pendingUnlinks = new Map();
1078
+ this._readyCount = 0;
1079
+ this._readyEmitted = false;
1080
+ const awf = _opts.awaitWriteFinish;
1081
+ const DEF_AWF = {
1082
+ stabilityThreshold: 2000,
1083
+ pollInterval: 100
1084
+ };
1085
+ const opts = {
1086
+ persistent: true,
1087
+ ignoreInitial: false,
1088
+ ignorePermissionErrors: false,
1089
+ interval: 100,
1090
+ binaryInterval: 300,
1091
+ followSymlinks: true,
1092
+ usePolling: false,
1093
+ atomic: true,
1094
+ ..._opts,
1095
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
1096
+ awaitWriteFinish: true === awf ? DEF_AWF : 'object' == typeof awf ? {
1097
+ ...DEF_AWF,
1098
+ ...awf
1099
+ } : false
1100
+ };
1101
+ if (isIBMi) opts.usePolling = true;
1102
+ if (void 0 === opts.atomic) opts.atomic = !opts.usePolling;
1103
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
1104
+ if (void 0 !== envPoll) {
1105
+ const envLower = envPoll.toLowerCase();
1106
+ if ('false' === envLower || '0' === envLower) opts.usePolling = false;
1107
+ else if ('true' === envLower || '1' === envLower) opts.usePolling = true;
1108
+ else opts.usePolling = !!envLower;
1109
+ }
1110
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
1111
+ if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
1112
+ let readyCalls = 0;
1113
+ this._emitReady = ()=>{
1114
+ readyCalls++;
1115
+ if (readyCalls >= this._readyCount) {
1116
+ this._emitReady = EMPTY_FN;
1117
+ this._readyEmitted = true;
1118
+ process.nextTick(()=>this.emit(EVENTS.READY));
1119
+ }
1120
+ };
1121
+ this._emitRaw = (...args)=>this.emit(EVENTS.RAW, ...args);
1122
+ this._boundRemove = this._remove.bind(this);
1123
+ this.options = opts;
1124
+ this._nodeFsHandler = new NodeFsHandler(this);
1125
+ Object.freeze(opts);
1126
+ }
1127
+ _addIgnoredPath(matcher) {
1128
+ if (isMatcherObject(matcher)) {
1129
+ for (const ignored of this._ignoredPaths)if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) return;
1130
+ }
1131
+ this._ignoredPaths.add(matcher);
1132
+ }
1133
+ _removeIgnoredPath(matcher) {
1134
+ this._ignoredPaths.delete(matcher);
1135
+ if ('string' == typeof matcher) {
1136
+ for (const ignored of this._ignoredPaths)if (isMatcherObject(ignored) && ignored.path === matcher) this._ignoredPaths.delete(ignored);
1137
+ }
1138
+ }
1139
+ add(paths_, _origAdd, _internal) {
1140
+ const { cwd } = this.options;
1141
+ this.closed = false;
1142
+ this._closePromise = void 0;
1143
+ let paths = unifyPaths(paths_);
1144
+ if (cwd) paths = paths.map((path)=>{
1145
+ const absPath = getAbsolutePath(path, cwd);
1146
+ return absPath;
1147
+ });
1148
+ paths.forEach((path)=>{
1149
+ this._removeIgnoredPath(path);
1150
+ });
1151
+ this._userIgnored = void 0;
1152
+ if (!this._readyCount) this._readyCount = 0;
1153
+ this._readyCount += paths.length;
1154
+ Promise.all(paths.map(async (path)=>{
1155
+ const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, void 0, 0, _origAdd);
1156
+ if (res) this._emitReady();
1157
+ return res;
1158
+ })).then((results)=>{
1159
+ if (this.closed) return;
1160
+ results.forEach((item)=>{
1161
+ if (item) this.add(external_node_path_dirname(item), external_node_path_basename(_origAdd || item));
1162
+ });
1163
+ });
1164
+ return this;
1165
+ }
1166
+ unwatch(paths_) {
1167
+ if (this.closed) return this;
1168
+ const paths = unifyPaths(paths_);
1169
+ const { cwd } = this.options;
1170
+ paths.forEach((path)=>{
1171
+ if (!isAbsolute(path) && !this._closers.has(path)) {
1172
+ if (cwd) path = join(cwd, path);
1173
+ path = external_node_path_resolve(path);
1174
+ }
1175
+ this._closePath(path);
1176
+ this._addIgnoredPath(path);
1177
+ if (this._watched.has(path)) this._addIgnoredPath({
1178
+ path,
1179
+ recursive: true
1180
+ });
1181
+ this._userIgnored = void 0;
1182
+ });
1183
+ return this;
1184
+ }
1185
+ close() {
1186
+ if (this._closePromise) return this._closePromise;
1187
+ this.closed = true;
1188
+ this.removeAllListeners();
1189
+ const closers = [];
1190
+ this._closers.forEach((closerList)=>closerList.forEach((closer)=>{
1191
+ const promise = closer();
1192
+ if (promise instanceof Promise) closers.push(promise);
1193
+ }));
1194
+ this._streams.forEach((stream)=>stream.destroy());
1195
+ this._userIgnored = void 0;
1196
+ this._readyCount = 0;
1197
+ this._readyEmitted = false;
1198
+ this._watched.forEach((dirent)=>dirent.dispose());
1199
+ this._closers.clear();
1200
+ this._watched.clear();
1201
+ this._streams.clear();
1202
+ this._symlinkPaths.clear();
1203
+ this._throttled.clear();
1204
+ this._closePromise = closers.length ? Promise.all(closers).then(()=>void 0) : Promise.resolve();
1205
+ return this._closePromise;
1206
+ }
1207
+ getWatched() {
1208
+ const watchList = {};
1209
+ this._watched.forEach((entry, dir)=>{
1210
+ const key = this.options.cwd ? external_node_path_relative(this.options.cwd, dir) : dir;
1211
+ const index = key || ONE_DOT;
1212
+ watchList[index] = entry.getChildren().sort();
1213
+ });
1214
+ return watchList;
1215
+ }
1216
+ emitWithAll(event, args) {
1217
+ this.emit(event, ...args);
1218
+ if (event !== EVENTS.ERROR) this.emit(EVENTS.ALL, event, ...args);
1219
+ }
1220
+ async _emit(event, path, stats) {
1221
+ if (this.closed) return;
1222
+ const opts = this.options;
1223
+ if (isWindows) path = normalize(path);
1224
+ if (opts.cwd) path = external_node_path_relative(opts.cwd, path);
1225
+ const args = [
1226
+ path
1227
+ ];
1228
+ if (null != stats) args.push(stats);
1229
+ const awf = opts.awaitWriteFinish;
1230
+ let pw;
1231
+ if (awf && (pw = this._pendingWrites.get(path))) {
1232
+ pw.lastChange = new Date();
1233
+ return this;
1234
+ }
1235
+ if (opts.atomic) {
1236
+ if (event === EVENTS.UNLINK) {
1237
+ this._pendingUnlinks.set(path, [
1238
+ event,
1239
+ ...args
1240
+ ]);
1241
+ setTimeout(()=>{
1242
+ this._pendingUnlinks.forEach((entry, path)=>{
1243
+ this.emit(...entry);
1244
+ this.emit(EVENTS.ALL, ...entry);
1245
+ this._pendingUnlinks.delete(path);
1246
+ });
1247
+ }, 'number' == typeof opts.atomic ? opts.atomic : 100);
1248
+ return this;
1249
+ }
1250
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path)) {
1251
+ event = EVENTS.CHANGE;
1252
+ this._pendingUnlinks.delete(path);
1253
+ }
1254
+ }
1255
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
1256
+ const awfEmit = (err, stats)=>{
1257
+ if (err) {
1258
+ event = EVENTS.ERROR;
1259
+ args[0] = err;
1260
+ this.emitWithAll(event, args);
1261
+ } else if (stats) {
1262
+ if (args.length > 1) args[1] = stats;
1263
+ else args.push(stats);
1264
+ this.emitWithAll(event, args);
1265
+ }
1266
+ };
1267
+ this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
1268
+ return this;
1269
+ }
1270
+ if (event === EVENTS.CHANGE) {
1271
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path, 50);
1272
+ if (isThrottled) return this;
1273
+ }
1274
+ if (opts.alwaysStat && void 0 === stats && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
1275
+ const fullPath = opts.cwd ? join(opts.cwd, path) : path;
1276
+ let stats;
1277
+ try {
1278
+ stats = await promises_stat(fullPath);
1279
+ } catch (err) {}
1280
+ if (!stats || this.closed) return;
1281
+ args.push(stats);
1282
+ }
1283
+ this.emitWithAll(event, args);
1284
+ return this;
1285
+ }
1286
+ _handleError(error) {
1287
+ const code = error && error.code;
1288
+ if (error && 'ENOENT' !== code && 'ENOTDIR' !== code && (!this.options.ignorePermissionErrors || 'EPERM' !== code && 'EACCES' !== code)) this.emit(EVENTS.ERROR, error);
1289
+ return error || this.closed;
1290
+ }
1291
+ _throttle(actionType, path, timeout) {
1292
+ if (!this._throttled.has(actionType)) this._throttled.set(actionType, new Map());
1293
+ const action = this._throttled.get(actionType);
1294
+ if (!action) throw new Error('invalid throttle');
1295
+ const actionPath = action.get(path);
1296
+ if (actionPath) {
1297
+ actionPath.count++;
1298
+ return false;
1299
+ }
1300
+ let timeoutObject;
1301
+ const clear = ()=>{
1302
+ const item = action.get(path);
1303
+ const count = item ? item.count : 0;
1304
+ action.delete(path);
1305
+ clearTimeout(timeoutObject);
1306
+ if (item) clearTimeout(item.timeoutObject);
1307
+ return count;
1308
+ };
1309
+ timeoutObject = setTimeout(clear, timeout);
1310
+ const thr = {
1311
+ timeoutObject,
1312
+ clear,
1313
+ count: 0
1314
+ };
1315
+ action.set(path, thr);
1316
+ return thr;
1317
+ }
1318
+ _incrReadyCount() {
1319
+ return this._readyCount++;
1320
+ }
1321
+ _awaitWriteFinish(path, threshold, event, awfEmit) {
1322
+ const awf = this.options.awaitWriteFinish;
1323
+ if ('object' != typeof awf) return;
1324
+ const pollInterval = awf.pollInterval;
1325
+ let timeoutHandler;
1326
+ let fullPath = path;
1327
+ if (this.options.cwd && !isAbsolute(path)) fullPath = join(this.options.cwd, path);
1328
+ const now = new Date();
1329
+ const writes = this._pendingWrites;
1330
+ function awaitWriteFinishFn(prevStat) {
1331
+ external_node_fs_stat(fullPath, (err, curStat)=>{
1332
+ if (err || !writes.has(path)) {
1333
+ if (err && 'ENOENT' !== err.code) awfEmit(err);
1334
+ return;
1335
+ }
1336
+ const now = Number(new Date());
1337
+ if (prevStat && curStat.size !== prevStat.size) writes.get(path).lastChange = now;
1338
+ const pw = writes.get(path);
1339
+ const df = now - pw.lastChange;
1340
+ if (df >= threshold) {
1341
+ writes.delete(path);
1342
+ awfEmit(void 0, curStat);
1343
+ } else timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
1344
+ });
1345
+ }
1346
+ if (!writes.has(path)) {
1347
+ writes.set(path, {
1348
+ lastChange: now,
1349
+ cancelWait: ()=>{
1350
+ writes.delete(path);
1351
+ clearTimeout(timeoutHandler);
1352
+ return event;
1353
+ }
1354
+ });
1355
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
1356
+ }
1357
+ }
1358
+ _isIgnored(path, stats) {
1359
+ if (this.options.atomic && DOT_RE.test(path)) return true;
1360
+ if (!this._userIgnored) {
1361
+ const { cwd } = this.options;
1362
+ const ign = this.options.ignored;
1363
+ const ignored = (ign || []).map(normalizeIgnored(cwd));
1364
+ const ignoredPaths = [
1365
+ ...this._ignoredPaths
1366
+ ];
1367
+ const list = [
1368
+ ...ignoredPaths.map(normalizeIgnored(cwd)),
1369
+ ...ignored
1370
+ ];
1371
+ this._userIgnored = anymatch(list, void 0);
1372
+ }
1373
+ return this._userIgnored(path, stats);
1374
+ }
1375
+ _isntIgnored(path, stat) {
1376
+ return !this._isIgnored(path, stat);
1377
+ }
1378
+ _getWatchHelpers(path) {
1379
+ return new WatchHelper(path, this.options.followSymlinks, this);
1380
+ }
1381
+ _getWatchedDir(directory) {
1382
+ const dir = external_node_path_resolve(directory);
1383
+ if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
1384
+ return this._watched.get(dir);
1385
+ }
1386
+ _hasReadPermissions(stats) {
1387
+ if (this.options.ignorePermissionErrors) return true;
1388
+ return Boolean(256 & Number(stats.mode));
1389
+ }
1390
+ _remove(directory, item, isDirectory) {
1391
+ const path = join(directory, item);
1392
+ const fullPath = external_node_path_resolve(path);
1393
+ isDirectory = null != isDirectory ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
1394
+ if (!this._throttle('remove', path, 100)) return;
1395
+ if (!isDirectory && 1 === this._watched.size) this.add(directory, item, true);
1396
+ const wp = this._getWatchedDir(path);
1397
+ const nestedDirectoryChildren = wp.getChildren();
1398
+ nestedDirectoryChildren.forEach((nested)=>this._remove(path, nested));
1399
+ const parent = this._getWatchedDir(directory);
1400
+ const wasTracked = parent.has(item);
1401
+ parent.remove(item);
1402
+ if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath);
1403
+ let relPath = path;
1404
+ if (this.options.cwd) relPath = external_node_path_relative(this.options.cwd, path);
1405
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
1406
+ const event = this._pendingWrites.get(relPath).cancelWait();
1407
+ if (event === EVENTS.ADD) return;
1408
+ }
1409
+ this._watched.delete(path);
1410
+ this._watched.delete(fullPath);
1411
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
1412
+ if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
1413
+ this._closePath(path);
1414
+ }
1415
+ _closePath(path) {
1416
+ this._closeFile(path);
1417
+ const dir = external_node_path_dirname(path);
1418
+ this._getWatchedDir(dir).remove(external_node_path_basename(path));
1419
+ }
1420
+ _closeFile(path) {
1421
+ const closers = this._closers.get(path);
1422
+ if (!closers) return;
1423
+ closers.forEach((closer)=>closer());
1424
+ this._closers.delete(path);
1425
+ }
1426
+ _addPathCloser(path, closer) {
1427
+ if (!closer) return;
1428
+ let list = this._closers.get(path);
1429
+ if (!list) {
1430
+ list = [];
1431
+ this._closers.set(path, list);
1432
+ }
1433
+ list.push(closer);
1434
+ }
1435
+ _readdirp(root, opts) {
1436
+ if (this.closed) return;
1437
+ const options = {
1438
+ type: EVENTS.ALL,
1439
+ alwaysStat: true,
1440
+ lstat: true,
1441
+ ...opts,
1442
+ depth: 0
1443
+ };
1444
+ let stream = readdirp(root, options);
1445
+ this._streams.add(stream);
1446
+ stream.once(STR_CLOSE, ()=>{
1447
+ stream = void 0;
1448
+ });
1449
+ stream.once(STR_END, ()=>{
1450
+ if (stream) {
1451
+ this._streams.delete(stream);
1452
+ stream = void 0;
1453
+ }
1454
+ });
1455
+ return stream;
1456
+ }
1457
+ }
1458
+ function chokidar_watch(paths, options = {}) {
1459
+ const watcher = new FSWatcher(options);
1460
+ watcher.add(paths);
1461
+ return watcher;
1462
+ }
1463
+ const chokidar = {
1464
+ watch: chokidar_watch,
1465
+ FSWatcher: FSWatcher
1466
+ };
1467
+ export default chokidar;