Layout von Websiten mit Bootstrap und Foundation
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. 'use strict';
  2. const { EventEmitter } = require('events');
  3. const fs = require('fs');
  4. const sysPath = require('path');
  5. const { promisify } = require('util');
  6. const readdirp = require('readdirp');
  7. const anymatch = require('anymatch').default;
  8. const globParent = require('glob-parent');
  9. const isGlob = require('is-glob');
  10. const braces = require('braces');
  11. const normalizePath = require('normalize-path');
  12. const NodeFsHandler = require('./lib/nodefs-handler');
  13. const FsEventsHandler = require('./lib/fsevents-handler');
  14. const {
  15. EV_ALL,
  16. EV_READY,
  17. EV_ADD,
  18. EV_CHANGE,
  19. EV_UNLINK,
  20. EV_ADD_DIR,
  21. EV_UNLINK_DIR,
  22. EV_RAW,
  23. EV_ERROR,
  24. STR_CLOSE,
  25. STR_END,
  26. BACK_SLASH_RE,
  27. DOUBLE_SLASH_RE,
  28. SLASH_OR_BACK_SLASH_RE,
  29. DOT_RE,
  30. REPLACER_RE,
  31. SLASH,
  32. BRACE_START,
  33. BANG,
  34. ONE_DOT,
  35. TWO_DOTS,
  36. GLOBSTAR,
  37. SLASH_GLOBSTAR,
  38. ANYMATCH_OPTS,
  39. STRING_TYPE,
  40. FUNCTION_TYPE,
  41. EMPTY_STR,
  42. EMPTY_FN,
  43. isWindows,
  44. isMacos
  45. } = require('./lib/constants');
  46. const stat = promisify(fs.stat);
  47. const readdir = promisify(fs.readdir);
  48. /**
  49. * @typedef {String} Path
  50. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  51. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  52. */
  53. /**
  54. *
  55. * @typedef {Object} WatchHelpers
  56. * @property {Boolean} followSymlinks
  57. * @property {'stat'|'lstat'} statMethod
  58. * @property {Path} path
  59. * @property {Path} watchPath
  60. * @property {Function} entryPath
  61. * @property {Boolean} hasGlob
  62. * @property {Object} globFilter
  63. * @property {Function} filterPath
  64. * @property {Function} filterDir
  65. */
  66. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  67. const flatten = (list, result = []) => {
  68. list.forEach(item => {
  69. if (Array.isArray(item)) {
  70. flatten(item, result);
  71. } else {
  72. result.push(item);
  73. }
  74. });
  75. return result;
  76. };
  77. const unifyPaths = (paths_) => {
  78. /**
  79. * @type {Array<String>}
  80. */
  81. const paths = flatten(arrify(paths_));
  82. if (!paths.every(p => typeof p === STRING_TYPE)) {
  83. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  84. }
  85. return paths.map(normalizePathToUnix);
  86. };
  87. const toUnix = (string) => {
  88. let str = string.replace(BACK_SLASH_RE, SLASH);
  89. while (str.match(DOUBLE_SLASH_RE)) {
  90. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  91. }
  92. return str;
  93. };
  94. // Our version of upath.normalize
  95. // TODO: this is not equal to path-normalize module - investigate why
  96. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  97. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  98. if (typeof path !== STRING_TYPE) return path;
  99. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  100. };
  101. const getAbsolutePath = (path, cwd) => {
  102. if (sysPath.isAbsolute(path)) {
  103. return path;
  104. }
  105. if (path.startsWith(BANG)) {
  106. return BANG + sysPath.join(cwd, path.slice(1));
  107. }
  108. return sysPath.join(cwd, path);
  109. };
  110. const undef = (opts, key) => opts[key] === undefined;
  111. /**
  112. * Directory entry.
  113. * @property {Path} path
  114. * @property {Set<Path>} items
  115. */
  116. class DirEntry {
  117. /**
  118. * @param {Path} dir
  119. * @param {Function} removeWatcher
  120. */
  121. constructor(dir, removeWatcher) {
  122. this.path = dir;
  123. this._removeWatcher = removeWatcher;
  124. /** @type {Set<Path>} */
  125. this.items = new Set();
  126. }
  127. add(item) {
  128. const {items} = this;
  129. if (!items) return;
  130. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  131. }
  132. async remove(item) {
  133. const {items} = this;
  134. if (!items) return;
  135. items.delete(item);
  136. if (items.size > 0) return;
  137. const dir = this.path;
  138. try {
  139. await readdir(dir);
  140. } catch (err) {
  141. if (this._removeWatcher) {
  142. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  143. }
  144. }
  145. }
  146. has(item) {
  147. const {items} = this;
  148. if (!items) return;
  149. return items.has(item);
  150. }
  151. /**
  152. * @returns {Array<String>}
  153. */
  154. getChildren() {
  155. const {items} = this;
  156. if (!items) return;
  157. return [...items.values()];
  158. }
  159. dispose() {
  160. this.items.clear();
  161. delete this.path;
  162. delete this._removeWatcher;
  163. delete this.items;
  164. Object.freeze(this);
  165. }
  166. }
  167. const STAT_METHOD_F = 'stat';
  168. const STAT_METHOD_L = 'lstat';
  169. class WatchHelper {
  170. constructor(path, watchPath, follow, fsw) {
  171. this.fsw = fsw;
  172. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  173. this.watchPath = watchPath;
  174. this.fullWatchPath = sysPath.resolve(watchPath);
  175. this.hasGlob = watchPath !== path;
  176. /** @type {object|boolean} */
  177. if (path === EMPTY_STR) this.hasGlob = false;
  178. this.globSymlink = this.hasGlob && follow ? undefined : false;
  179. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  180. this.dirParts = this.getDirParts(path);
  181. this.dirParts.forEach((parts) => {
  182. if (parts.length > 1) parts.pop();
  183. });
  184. this.followSymlinks = follow;
  185. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  186. }
  187. checkGlobSymlink(entry) {
  188. // only need to resolve once
  189. // first entry should always have entry.parentDir === EMPTY_STR
  190. if (this.globSymlink === undefined) {
  191. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  192. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  193. }
  194. if (this.globSymlink) {
  195. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  196. }
  197. return entry.fullPath;
  198. }
  199. entryPath(entry) {
  200. return sysPath.join(this.watchPath,
  201. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  202. );
  203. }
  204. filterPath(entry) {
  205. const {stats} = entry;
  206. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  207. const resolvedPath = this.entryPath(entry);
  208. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  209. this.globFilter(resolvedPath) : true;
  210. return matchesGlob &&
  211. this.fsw._isntIgnored(resolvedPath, stats) &&
  212. this.fsw._hasReadPermissions(stats);
  213. }
  214. getDirParts(path) {
  215. if (!this.hasGlob) return [];
  216. const parts = [];
  217. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  218. expandedPath.forEach((path) => {
  219. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  220. });
  221. return parts;
  222. }
  223. filterDir(entry) {
  224. if (this.hasGlob) {
  225. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  226. let globstar = false;
  227. this.unmatchedGlob = !this.dirParts.some((parts) => {
  228. return parts.every((part, i) => {
  229. if (part === GLOBSTAR) globstar = true;
  230. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  231. });
  232. });
  233. }
  234. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  235. }
  236. }
  237. /**
  238. * Watches files & directories for changes. Emitted events:
  239. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  240. *
  241. * new FSWatcher()
  242. * .add(directories)
  243. * .on('add', path => log('File', path, 'was added'))
  244. */
  245. class FSWatcher extends EventEmitter {
  246. // Not indenting methods for history sake; for now.
  247. constructor(_opts) {
  248. super();
  249. const opts = {};
  250. if (_opts) Object.assign(opts, _opts); // for frozen objects
  251. /** @type {Map<String, DirEntry>} */
  252. this._watched = new Map();
  253. /** @type {Map<String, Array>} */
  254. this._closers = new Map();
  255. /** @type {Set<String>} */
  256. this._ignoredPaths = new Set();
  257. /** @type {Map<ThrottleType, Map>} */
  258. this._throttled = new Map();
  259. /** @type {Map<Path, String|Boolean>} */
  260. this._symlinkPaths = new Map();
  261. this._streams = new Set();
  262. this.closed = false;
  263. // Set up default options.
  264. if (undef(opts, 'persistent')) opts.persistent = true;
  265. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  266. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  267. if (undef(opts, 'interval')) opts.interval = 100;
  268. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  269. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  270. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  271. // Enable fsevents on OS X when polling isn't explicitly enabled.
  272. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  273. // If we can't use fsevents, ensure the options reflect it's disabled.
  274. const canUseFsEvents = FsEventsHandler.canUse();
  275. if (!canUseFsEvents) opts.useFsEvents = false;
  276. // Use polling on Mac if not using fsevents.
  277. // Other platforms use non-polling fs_watch.
  278. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  279. opts.usePolling = isMacos;
  280. }
  281. // Global override (useful for end-developers that need to force polling for all
  282. // instances of chokidar, regardless of usage/dependency depth)
  283. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  284. if (envPoll !== undefined) {
  285. const envLower = envPoll.toLowerCase();
  286. if (envLower === 'false' || envLower === '0') {
  287. opts.usePolling = false;
  288. } else if (envLower === 'true' || envLower === '1') {
  289. opts.usePolling = true;
  290. } else {
  291. opts.usePolling = !!envLower;
  292. }
  293. }
  294. const envInterval = process.env.CHOKIDAR_INTERVAL;
  295. if (envInterval) {
  296. opts.interval = Number.parseInt(envInterval, 10);
  297. }
  298. // Editor atomic write normalization enabled by default with fs.watch
  299. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  300. if (opts.atomic) this._pendingUnlinks = new Map();
  301. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  302. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  303. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  304. const awf = opts.awaitWriteFinish;
  305. if (awf) {
  306. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  307. if (!awf.pollInterval) awf.pollInterval = 100;
  308. this._pendingWrites = new Map();
  309. }
  310. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  311. let readyCalls = 0;
  312. this._emitReady = () => {
  313. readyCalls++;
  314. if (readyCalls >= this._readyCount) {
  315. this._emitReady = EMPTY_FN;
  316. this._readyEmitted = true;
  317. // use process.nextTick to allow time for listener to be bound
  318. process.nextTick(() => this.emit(EV_READY));
  319. }
  320. };
  321. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  322. this._readyEmitted = false;
  323. this.options = opts;
  324. // Initialize with proper watcher.
  325. if (opts.useFsEvents) {
  326. this._fsEventsHandler = new FsEventsHandler(this);
  327. } else {
  328. this._nodeFsHandler = new NodeFsHandler(this);
  329. }
  330. // You’re frozen when your heart’s not open.
  331. Object.freeze(opts);
  332. }
  333. // Public methods
  334. /**
  335. * Adds paths to be watched on an existing FSWatcher instance
  336. * @param {Path|Array<Path>} paths_
  337. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  338. * @param {Boolean=} _internal private; indicates a non-user add
  339. * @returns {FSWatcher} for chaining
  340. */
  341. add(paths_, _origAdd, _internal) {
  342. const {cwd, disableGlobbing} = this.options;
  343. this.closed = false;
  344. let paths = unifyPaths(paths_);
  345. if (cwd) {
  346. paths = paths.map((path) => {
  347. const absPath = getAbsolutePath(path, cwd);
  348. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  349. if (disableGlobbing || !isGlob(path)) {
  350. return absPath;
  351. }
  352. return normalizePath(absPath);
  353. });
  354. }
  355. // set aside negated glob strings
  356. paths = paths.filter((path) => {
  357. if (path.startsWith(BANG)) {
  358. this._ignoredPaths.add(path.slice(1));
  359. return false;
  360. }
  361. // if a path is being added that was previously ignored, stop ignoring it
  362. this._ignoredPaths.delete(path);
  363. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  364. // reset the cached userIgnored anymatch fn
  365. // to make ignoredPaths changes effective
  366. this._userIgnored = undefined;
  367. return true;
  368. });
  369. if (this.options.useFsEvents && this._fsEventsHandler) {
  370. if (!this._readyCount) this._readyCount = paths.length;
  371. if (this.options.persistent) this._readyCount *= 2;
  372. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  373. } else {
  374. if (!this._readyCount) this._readyCount = 0;
  375. this._readyCount += paths.length;
  376. Promise.all(
  377. paths.map(async path => {
  378. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  379. if (res) this._emitReady();
  380. return res;
  381. })
  382. ).then(results => {
  383. if (this.closed) return;
  384. results.filter(item => item).forEach(item => {
  385. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  386. });
  387. });
  388. }
  389. return this;
  390. }
  391. /**
  392. * Close watchers or start ignoring events from specified paths.
  393. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  394. * @returns {FSWatcher} for chaining
  395. */
  396. unwatch(paths_) {
  397. if (this.closed) return this;
  398. const paths = unifyPaths(paths_);
  399. const {cwd} = this.options;
  400. paths.forEach((path) => {
  401. // convert to absolute path unless relative path already matches
  402. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  403. if (cwd) path = sysPath.join(cwd, path);
  404. path = sysPath.resolve(path);
  405. }
  406. this._closePath(path);
  407. this._ignoredPaths.add(path);
  408. if (this._watched.has(path)) {
  409. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  410. }
  411. // reset the cached userIgnored anymatch fn
  412. // to make ignoredPaths changes effective
  413. this._userIgnored = undefined;
  414. });
  415. return this;
  416. }
  417. /**
  418. * Close watchers and remove all listeners from watched paths.
  419. * @returns {Promise<void>}.
  420. */
  421. close() {
  422. if (this.closed) return this._closePromise;
  423. this.closed = true;
  424. // Memory management.
  425. this.removeAllListeners();
  426. const closers = [];
  427. this._closers.forEach(closerList => closerList.forEach(closer => {
  428. const promise = closer();
  429. if (promise instanceof Promise) closers.push(promise);
  430. }));
  431. this._streams.forEach(stream => stream.destroy());
  432. this._userIgnored = undefined;
  433. this._readyCount = 0;
  434. this._readyEmitted = false;
  435. this._watched.forEach(dirent => dirent.dispose());
  436. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  437. this[`_${key}`].clear();
  438. });
  439. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  440. return this._closePromise;
  441. }
  442. /**
  443. * Expose list of watched paths
  444. * @returns {Object} for chaining
  445. */
  446. getWatched() {
  447. const watchList = {};
  448. this._watched.forEach((entry, dir) => {
  449. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  450. watchList[key || ONE_DOT] = entry.getChildren().sort();
  451. });
  452. return watchList;
  453. }
  454. emitWithAll(event, args) {
  455. this.emit(...args);
  456. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  457. }
  458. // Common helpers
  459. // --------------
  460. /**
  461. * Normalize and emit events.
  462. * Calling _emit DOES NOT MEAN emit() would be called!
  463. * @param {EventName} event Type of event
  464. * @param {Path} path File or directory path
  465. * @param {*=} val1 arguments to be passed with event
  466. * @param {*=} val2
  467. * @param {*=} val3
  468. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  469. */
  470. async _emit(event, path, val1, val2, val3) {
  471. if (this.closed) return;
  472. const opts = this.options;
  473. if (isWindows) path = sysPath.normalize(path);
  474. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  475. /** @type Array<any> */
  476. const args = [event, path];
  477. if (val3 !== undefined) args.push(val1, val2, val3);
  478. else if (val2 !== undefined) args.push(val1, val2);
  479. else if (val1 !== undefined) args.push(val1);
  480. const awf = opts.awaitWriteFinish;
  481. let pw;
  482. if (awf && (pw = this._pendingWrites.get(path))) {
  483. pw.lastChange = new Date();
  484. return this;
  485. }
  486. if (opts.atomic) {
  487. if (event === EV_UNLINK) {
  488. this._pendingUnlinks.set(path, args);
  489. setTimeout(() => {
  490. this._pendingUnlinks.forEach((entry, path) => {
  491. this.emit(...entry);
  492. this.emit(EV_ALL, ...entry);
  493. this._pendingUnlinks.delete(path);
  494. });
  495. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  496. return this;
  497. }
  498. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  499. event = args[0] = EV_CHANGE;
  500. this._pendingUnlinks.delete(path);
  501. }
  502. }
  503. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  504. const awfEmit = (err, stats) => {
  505. if (err) {
  506. event = args[0] = EV_ERROR;
  507. args[1] = err;
  508. this.emitWithAll(event, args);
  509. } else if (stats) {
  510. // if stats doesn't exist the file must have been deleted
  511. if (args.length > 2) {
  512. args[2] = stats;
  513. } else {
  514. args.push(stats);
  515. }
  516. this.emitWithAll(event, args);
  517. }
  518. };
  519. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  520. return this;
  521. }
  522. if (event === EV_CHANGE) {
  523. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  524. if (isThrottled) return this;
  525. }
  526. if (opts.alwaysStat && val1 === undefined &&
  527. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  528. ) {
  529. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  530. let stats;
  531. try {
  532. stats = await stat(fullPath);
  533. } catch (err) {}
  534. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  535. if (!stats || this.closed) return;
  536. args.push(stats);
  537. }
  538. this.emitWithAll(event, args);
  539. return this;
  540. }
  541. /**
  542. * Common handler for errors
  543. * @param {Error} error
  544. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  545. */
  546. _handleError(error) {
  547. const code = error && error.code;
  548. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  549. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  550. ) {
  551. this.emit(EV_ERROR, error);
  552. }
  553. return error || this.closed;
  554. }
  555. /**
  556. * Helper utility for throttling
  557. * @param {ThrottleType} actionType type being throttled
  558. * @param {Path} path being acted upon
  559. * @param {Number} timeout duration of time to suppress duplicate actions
  560. * @returns {Object|false} tracking object or false if action should be suppressed
  561. */
  562. _throttle(actionType, path, timeout) {
  563. if (!this._throttled.has(actionType)) {
  564. this._throttled.set(actionType, new Map());
  565. }
  566. /** @type {Map<Path, Object>} */
  567. const action = this._throttled.get(actionType);
  568. /** @type {Object} */
  569. const actionPath = action.get(path);
  570. if (actionPath) {
  571. actionPath.count++;
  572. return false;
  573. }
  574. let timeoutObject;
  575. const clear = () => {
  576. const item = action.get(path);
  577. const count = item ? item.count : 0;
  578. action.delete(path);
  579. clearTimeout(timeoutObject);
  580. if (item) clearTimeout(item.timeoutObject);
  581. return count;
  582. };
  583. timeoutObject = setTimeout(clear, timeout);
  584. const thr = {timeoutObject, clear, count: 0};
  585. action.set(path, thr);
  586. return thr;
  587. }
  588. _incrReadyCount() {
  589. return this._readyCount++;
  590. }
  591. /**
  592. * Awaits write operation to finish.
  593. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  594. * @param {Path} path being acted upon
  595. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  596. * @param {EventName} event
  597. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  598. */
  599. _awaitWriteFinish(path, threshold, event, awfEmit) {
  600. let timeoutHandler;
  601. let fullPath = path;
  602. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  603. fullPath = sysPath.join(this.options.cwd, path);
  604. }
  605. const now = new Date();
  606. const awaitWriteFinish = (prevStat) => {
  607. fs.stat(fullPath, (err, curStat) => {
  608. if (err || !this._pendingWrites.has(path)) {
  609. if (err && err.code !== 'ENOENT') awfEmit(err);
  610. return;
  611. }
  612. const now = Number(new Date());
  613. if (prevStat && curStat.size !== prevStat.size) {
  614. this._pendingWrites.get(path).lastChange = now;
  615. }
  616. const pw = this._pendingWrites.get(path);
  617. const df = now - pw.lastChange;
  618. if (df >= threshold) {
  619. this._pendingWrites.delete(path);
  620. awfEmit(undefined, curStat);
  621. } else {
  622. timeoutHandler = setTimeout(
  623. awaitWriteFinish,
  624. this.options.awaitWriteFinish.pollInterval,
  625. curStat
  626. );
  627. }
  628. });
  629. };
  630. if (!this._pendingWrites.has(path)) {
  631. this._pendingWrites.set(path, {
  632. lastChange: now,
  633. cancelWait: () => {
  634. this._pendingWrites.delete(path);
  635. clearTimeout(timeoutHandler);
  636. return event;
  637. }
  638. });
  639. timeoutHandler = setTimeout(
  640. awaitWriteFinish,
  641. this.options.awaitWriteFinish.pollInterval
  642. );
  643. }
  644. }
  645. _getGlobIgnored() {
  646. return [...this._ignoredPaths.values()];
  647. }
  648. /**
  649. * Determines whether user has asked to ignore this path.
  650. * @param {Path} path filepath or dir
  651. * @param {fs.Stats=} stats result of fs.stat
  652. * @returns {Boolean}
  653. */
  654. _isIgnored(path, stats) {
  655. if (this.options.atomic && DOT_RE.test(path)) return true;
  656. if (!this._userIgnored) {
  657. const {cwd} = this.options;
  658. const ign = this.options.ignored;
  659. const ignored = ign && ign.map(normalizeIgnored(cwd));
  660. const paths = arrify(ignored)
  661. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  662. .map((path) => path + SLASH_GLOBSTAR);
  663. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  664. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  665. }
  666. return this._userIgnored([path, stats]);
  667. }
  668. _isntIgnored(path, stat) {
  669. return !this._isIgnored(path, stat);
  670. }
  671. /**
  672. * Provides a set of common helpers and properties relating to symlink and glob handling.
  673. * @param {Path} path file, directory, or glob pattern being watched
  674. * @param {Number=} depth at any depth > 0, this isn't a glob
  675. * @returns {WatchHelper} object containing helpers for this path
  676. */
  677. _getWatchHelpers(path, depth) {
  678. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  679. const follow = this.options.followSymlinks;
  680. return new WatchHelper(path, watchPath, follow, this);
  681. }
  682. // Directory helpers
  683. // -----------------
  684. /**
  685. * Provides directory tracking objects
  686. * @param {String} directory path of the directory
  687. * @returns {DirEntry} the directory's tracking object
  688. */
  689. _getWatchedDir(directory) {
  690. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  691. const dir = sysPath.resolve(directory);
  692. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  693. return this._watched.get(dir);
  694. }
  695. // File helpers
  696. // ------------
  697. /**
  698. * Check for read permissions.
  699. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  700. * @param {fs.Stats} stats - object, result of fs_stat
  701. * @returns {Boolean} indicates whether the file can be read
  702. */
  703. _hasReadPermissions(stats) {
  704. if (this.options.ignorePermissionErrors) return true;
  705. // stats.mode may be bigint
  706. const md = stats && Number.parseInt(stats.mode, 10);
  707. const st = md & 0o777;
  708. const it = Number.parseInt(st.toString(8)[0], 10);
  709. return Boolean(4 & it);
  710. }
  711. /**
  712. * Handles emitting unlink events for
  713. * files and directories, and via recursion, for
  714. * files and directories within directories that are unlinked
  715. * @param {String} directory within which the following item is located
  716. * @param {String} item base path of item/directory
  717. * @returns {void}
  718. */
  719. _remove(directory, item, isDirectory) {
  720. // if what is being deleted is a directory, get that directory's paths
  721. // for recursive deleting and cleaning of watched object
  722. // if it is not a directory, nestedDirectoryChildren will be empty array
  723. const path = sysPath.join(directory, item);
  724. const fullPath = sysPath.resolve(path);
  725. isDirectory = isDirectory != null
  726. ? isDirectory
  727. : this._watched.has(path) || this._watched.has(fullPath);
  728. // prevent duplicate handling in case of arriving here nearly simultaneously
  729. // via multiple paths (such as _handleFile and _handleDir)
  730. if (!this._throttle('remove', path, 100)) return;
  731. // if the only watched file is removed, watch for its return
  732. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  733. this.add(directory, item, true);
  734. }
  735. // This will create a new entry in the watched object in either case
  736. // so we got to do the directory check beforehand
  737. const wp = this._getWatchedDir(path);
  738. const nestedDirectoryChildren = wp.getChildren();
  739. // Recursively remove children directories / files.
  740. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  741. // Check if item was on the watched list and remove it
  742. const parent = this._getWatchedDir(directory);
  743. const wasTracked = parent.has(item);
  744. parent.remove(item);
  745. // If we wait for this file to be fully written, cancel the wait.
  746. let relPath = path;
  747. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  748. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  749. const event = this._pendingWrites.get(relPath).cancelWait();
  750. if (event === EV_ADD) return;
  751. }
  752. // The Entry will either be a directory that just got removed
  753. // or a bogus entry to a file, in either case we have to remove it
  754. this._watched.delete(path);
  755. this._watched.delete(fullPath);
  756. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  757. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  758. // Avoid conflicts if we later create another file with the same name
  759. if (!this.options.useFsEvents) {
  760. this._closePath(path);
  761. }
  762. }
  763. /**
  764. *
  765. * @param {Path} path
  766. */
  767. _closePath(path) {
  768. const closers = this._closers.get(path);
  769. if (!closers) return;
  770. closers.forEach(closer => closer());
  771. this._closers.delete(path);
  772. const dir = sysPath.dirname(path);
  773. this._getWatchedDir(dir).remove(sysPath.basename(path));
  774. }
  775. /**
  776. *
  777. * @param {Path} path
  778. * @param {Function} closer
  779. */
  780. _addPathCloser(path, closer) {
  781. if (!closer) return;
  782. let list = this._closers.get(path);
  783. if (!list) {
  784. list = [];
  785. this._closers.set(path, list);
  786. }
  787. list.push(closer);
  788. }
  789. _readdirp(root, opts) {
  790. if (this.closed) return;
  791. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  792. let stream = readdirp(root, options);
  793. this._streams.add(stream);
  794. stream.once(STR_CLOSE, () => {
  795. stream = undefined;
  796. });
  797. stream.once(STR_END, () => {
  798. if (stream) {
  799. this._streams.delete(stream);
  800. stream = undefined;
  801. }
  802. });
  803. return stream;
  804. }
  805. }
  806. // Export FSWatcher class
  807. exports.FSWatcher = FSWatcher;
  808. /**
  809. * Instantiates watcher with paths to be tracked.
  810. * @param {String|Array<String>} paths file/directory paths and/or globs
  811. * @param {Object=} options chokidar opts
  812. * @returns an instance of FSWatcher for chaining.
  813. */
  814. const watch = (paths, options) => {
  815. const watcher = new FSWatcher(options);
  816. watcher.add(paths);
  817. return watcher;
  818. };
  819. exports.watch = watch;