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.

9297 lines
245 KiB

  1. /*
  2. @license
  3. Rollup.js v4.40.0
  4. Sat, 12 Apr 2025 08:39:04 GMT - commit 1f2d579ccd4b39f223fed14ac7d031a6c848cd80
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import { getAugmentedNamespace, fseventsImporter, getDefaultExportFromCjs, createFilter, rollupInternal } from './node-entry.js';
  9. import path from 'node:path';
  10. import process$1 from 'node:process';
  11. import require$$0$1 from 'path';
  12. import require$$2 from 'util';
  13. import require$$0$2 from 'fs';
  14. import require$$1 from 'stream';
  15. import require$$2$1 from 'os';
  16. import require$$0$3 from 'events';
  17. import { platform } from 'node:os';
  18. import './parseAst.js';
  19. import '../../native.js';
  20. import 'node:perf_hooks';
  21. import 'node:fs/promises';
  22. var chokidar$1 = {};
  23. var utils$2 = {};
  24. var constants$3;
  25. var hasRequiredConstants$3;
  26. function requireConstants$3 () {
  27. if (hasRequiredConstants$3) return constants$3;
  28. hasRequiredConstants$3 = 1;
  29. const path = require$$0$1;
  30. const WIN_SLASH = '\\\\/';
  31. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  32. /**
  33. * Posix glob regex
  34. */
  35. const DOT_LITERAL = '\\.';
  36. const PLUS_LITERAL = '\\+';
  37. const QMARK_LITERAL = '\\?';
  38. const SLASH_LITERAL = '\\/';
  39. const ONE_CHAR = '(?=.)';
  40. const QMARK = '[^/]';
  41. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  42. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  43. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  44. const NO_DOT = `(?!${DOT_LITERAL})`;
  45. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  46. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  47. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  48. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  49. const STAR = `${QMARK}*?`;
  50. const POSIX_CHARS = {
  51. DOT_LITERAL,
  52. PLUS_LITERAL,
  53. QMARK_LITERAL,
  54. SLASH_LITERAL,
  55. ONE_CHAR,
  56. QMARK,
  57. END_ANCHOR,
  58. DOTS_SLASH,
  59. NO_DOT,
  60. NO_DOTS,
  61. NO_DOT_SLASH,
  62. NO_DOTS_SLASH,
  63. QMARK_NO_DOT,
  64. STAR,
  65. START_ANCHOR
  66. };
  67. /**
  68. * Windows glob regex
  69. */
  70. const WINDOWS_CHARS = {
  71. ...POSIX_CHARS,
  72. SLASH_LITERAL: `[${WIN_SLASH}]`,
  73. QMARK: WIN_NO_SLASH,
  74. STAR: `${WIN_NO_SLASH}*?`,
  75. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  76. NO_DOT: `(?!${DOT_LITERAL})`,
  77. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  78. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  79. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  80. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  81. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  82. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  83. };
  84. /**
  85. * POSIX Bracket Regex
  86. */
  87. const POSIX_REGEX_SOURCE = {
  88. alnum: 'a-zA-Z0-9',
  89. alpha: 'a-zA-Z',
  90. ascii: '\\x00-\\x7F',
  91. blank: ' \\t',
  92. cntrl: '\\x00-\\x1F\\x7F',
  93. digit: '0-9',
  94. graph: '\\x21-\\x7E',
  95. lower: 'a-z',
  96. print: '\\x20-\\x7E ',
  97. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  98. space: ' \\t\\r\\n\\v\\f',
  99. upper: 'A-Z',
  100. word: 'A-Za-z0-9_',
  101. xdigit: 'A-Fa-f0-9'
  102. };
  103. constants$3 = {
  104. MAX_LENGTH: 1024 * 64,
  105. POSIX_REGEX_SOURCE,
  106. // regular expressions
  107. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  108. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  109. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  110. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  111. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  112. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  113. // Replace globs with equivalent patterns to reduce parsing time.
  114. REPLACEMENTS: {
  115. '***': '*',
  116. '**/**': '**',
  117. '**/**/**': '**'
  118. },
  119. // Digits
  120. CHAR_0: 48, /* 0 */
  121. CHAR_9: 57, /* 9 */
  122. // Alphabet chars.
  123. CHAR_UPPERCASE_A: 65, /* A */
  124. CHAR_LOWERCASE_A: 97, /* a */
  125. CHAR_UPPERCASE_Z: 90, /* Z */
  126. CHAR_LOWERCASE_Z: 122, /* z */
  127. CHAR_LEFT_PARENTHESES: 40, /* ( */
  128. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  129. CHAR_ASTERISK: 42, /* * */
  130. // Non-alphabetic chars.
  131. CHAR_AMPERSAND: 38, /* & */
  132. CHAR_AT: 64, /* @ */
  133. CHAR_BACKWARD_SLASH: 92, /* \ */
  134. CHAR_CARRIAGE_RETURN: 13, /* \r */
  135. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  136. CHAR_COLON: 58, /* : */
  137. CHAR_COMMA: 44, /* , */
  138. CHAR_DOT: 46, /* . */
  139. CHAR_DOUBLE_QUOTE: 34, /* " */
  140. CHAR_EQUAL: 61, /* = */
  141. CHAR_EXCLAMATION_MARK: 33, /* ! */
  142. CHAR_FORM_FEED: 12, /* \f */
  143. CHAR_FORWARD_SLASH: 47, /* / */
  144. CHAR_GRAVE_ACCENT: 96, /* ` */
  145. CHAR_HASH: 35, /* # */
  146. CHAR_HYPHEN_MINUS: 45, /* - */
  147. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  148. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  149. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  150. CHAR_LINE_FEED: 10, /* \n */
  151. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  152. CHAR_PERCENT: 37, /* % */
  153. CHAR_PLUS: 43, /* + */
  154. CHAR_QUESTION_MARK: 63, /* ? */
  155. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  156. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  157. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  158. CHAR_SEMICOLON: 59, /* ; */
  159. CHAR_SINGLE_QUOTE: 39, /* ' */
  160. CHAR_SPACE: 32, /* */
  161. CHAR_TAB: 9, /* \t */
  162. CHAR_UNDERSCORE: 95, /* _ */
  163. CHAR_VERTICAL_LINE: 124, /* | */
  164. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  165. SEP: path.sep,
  166. /**
  167. * Create EXTGLOB_CHARS
  168. */
  169. extglobChars(chars) {
  170. return {
  171. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  172. '?': { type: 'qmark', open: '(?:', close: ')?' },
  173. '+': { type: 'plus', open: '(?:', close: ')+' },
  174. '*': { type: 'star', open: '(?:', close: ')*' },
  175. '@': { type: 'at', open: '(?:', close: ')' }
  176. };
  177. },
  178. /**
  179. * Create GLOB_CHARS
  180. */
  181. globChars(win32) {
  182. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  183. }
  184. };
  185. return constants$3;
  186. }
  187. var hasRequiredUtils$2;
  188. function requireUtils$2 () {
  189. if (hasRequiredUtils$2) return utils$2;
  190. hasRequiredUtils$2 = 1;
  191. (function (exports) {
  192. const path = require$$0$1;
  193. const win32 = process.platform === 'win32';
  194. const {
  195. REGEX_BACKSLASH,
  196. REGEX_REMOVE_BACKSLASH,
  197. REGEX_SPECIAL_CHARS,
  198. REGEX_SPECIAL_CHARS_GLOBAL
  199. } = /*@__PURE__*/ requireConstants$3();
  200. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  201. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  202. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  203. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  204. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  205. exports.removeBackslashes = str => {
  206. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  207. return match === '\\' ? '' : match;
  208. });
  209. };
  210. exports.supportsLookbehinds = () => {
  211. const segs = process.version.slice(1).split('.').map(Number);
  212. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  213. return true;
  214. }
  215. return false;
  216. };
  217. exports.isWindows = options => {
  218. if (options && typeof options.windows === 'boolean') {
  219. return options.windows;
  220. }
  221. return win32 === true || path.sep === '\\';
  222. };
  223. exports.escapeLast = (input, char, lastIdx) => {
  224. const idx = input.lastIndexOf(char, lastIdx);
  225. if (idx === -1) return input;
  226. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  227. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  228. };
  229. exports.removePrefix = (input, state = {}) => {
  230. let output = input;
  231. if (output.startsWith('./')) {
  232. output = output.slice(2);
  233. state.prefix = './';
  234. }
  235. return output;
  236. };
  237. exports.wrapOutput = (input, state = {}, options = {}) => {
  238. const prepend = options.contains ? '' : '^';
  239. const append = options.contains ? '' : '$';
  240. let output = `${prepend}(?:${input})${append}`;
  241. if (state.negated === true) {
  242. output = `(?:^(?!${output}).*$)`;
  243. }
  244. return output;
  245. };
  246. } (utils$2));
  247. return utils$2;
  248. }
  249. var scan_1$1;
  250. var hasRequiredScan$1;
  251. function requireScan$1 () {
  252. if (hasRequiredScan$1) return scan_1$1;
  253. hasRequiredScan$1 = 1;
  254. const utils = /*@__PURE__*/ requireUtils$2();
  255. const {
  256. CHAR_ASTERISK, /* * */
  257. CHAR_AT, /* @ */
  258. CHAR_BACKWARD_SLASH, /* \ */
  259. CHAR_COMMA, /* , */
  260. CHAR_DOT, /* . */
  261. CHAR_EXCLAMATION_MARK, /* ! */
  262. CHAR_FORWARD_SLASH, /* / */
  263. CHAR_LEFT_CURLY_BRACE, /* { */
  264. CHAR_LEFT_PARENTHESES, /* ( */
  265. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  266. CHAR_PLUS, /* + */
  267. CHAR_QUESTION_MARK, /* ? */
  268. CHAR_RIGHT_CURLY_BRACE, /* } */
  269. CHAR_RIGHT_PARENTHESES, /* ) */
  270. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  271. } = /*@__PURE__*/ requireConstants$3();
  272. const isPathSeparator = code => {
  273. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  274. };
  275. const depth = token => {
  276. if (token.isPrefix !== true) {
  277. token.depth = token.isGlobstar ? Infinity : 1;
  278. }
  279. };
  280. /**
  281. * Quickly scans a glob pattern and returns an object with a handful of
  282. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  283. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  284. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  285. *
  286. * ```js
  287. * const pm = require('picomatch');
  288. * console.log(pm.scan('foo/bar/*.js'));
  289. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  290. * ```
  291. * @param {String} `str`
  292. * @param {Object} `options`
  293. * @return {Object} Returns an object with tokens and regex source string.
  294. * @api public
  295. */
  296. const scan = (input, options) => {
  297. const opts = options || {};
  298. const length = input.length - 1;
  299. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  300. const slashes = [];
  301. const tokens = [];
  302. const parts = [];
  303. let str = input;
  304. let index = -1;
  305. let start = 0;
  306. let lastIndex = 0;
  307. let isBrace = false;
  308. let isBracket = false;
  309. let isGlob = false;
  310. let isExtglob = false;
  311. let isGlobstar = false;
  312. let braceEscaped = false;
  313. let backslashes = false;
  314. let negated = false;
  315. let negatedExtglob = false;
  316. let finished = false;
  317. let braces = 0;
  318. let prev;
  319. let code;
  320. let token = { value: '', depth: 0, isGlob: false };
  321. const eos = () => index >= length;
  322. const peek = () => str.charCodeAt(index + 1);
  323. const advance = () => {
  324. prev = code;
  325. return str.charCodeAt(++index);
  326. };
  327. while (index < length) {
  328. code = advance();
  329. let next;
  330. if (code === CHAR_BACKWARD_SLASH) {
  331. backslashes = token.backslashes = true;
  332. code = advance();
  333. if (code === CHAR_LEFT_CURLY_BRACE) {
  334. braceEscaped = true;
  335. }
  336. continue;
  337. }
  338. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  339. braces++;
  340. while (eos() !== true && (code = advance())) {
  341. if (code === CHAR_BACKWARD_SLASH) {
  342. backslashes = token.backslashes = true;
  343. advance();
  344. continue;
  345. }
  346. if (code === CHAR_LEFT_CURLY_BRACE) {
  347. braces++;
  348. continue;
  349. }
  350. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  351. isBrace = token.isBrace = true;
  352. isGlob = token.isGlob = true;
  353. finished = true;
  354. if (scanToEnd === true) {
  355. continue;
  356. }
  357. break;
  358. }
  359. if (braceEscaped !== true && code === CHAR_COMMA) {
  360. isBrace = token.isBrace = true;
  361. isGlob = token.isGlob = true;
  362. finished = true;
  363. if (scanToEnd === true) {
  364. continue;
  365. }
  366. break;
  367. }
  368. if (code === CHAR_RIGHT_CURLY_BRACE) {
  369. braces--;
  370. if (braces === 0) {
  371. braceEscaped = false;
  372. isBrace = token.isBrace = true;
  373. finished = true;
  374. break;
  375. }
  376. }
  377. }
  378. if (scanToEnd === true) {
  379. continue;
  380. }
  381. break;
  382. }
  383. if (code === CHAR_FORWARD_SLASH) {
  384. slashes.push(index);
  385. tokens.push(token);
  386. token = { value: '', depth: 0, isGlob: false };
  387. if (finished === true) continue;
  388. if (prev === CHAR_DOT && index === (start + 1)) {
  389. start += 2;
  390. continue;
  391. }
  392. lastIndex = index + 1;
  393. continue;
  394. }
  395. if (opts.noext !== true) {
  396. const isExtglobChar = code === CHAR_PLUS
  397. || code === CHAR_AT
  398. || code === CHAR_ASTERISK
  399. || code === CHAR_QUESTION_MARK
  400. || code === CHAR_EXCLAMATION_MARK;
  401. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  402. isGlob = token.isGlob = true;
  403. isExtglob = token.isExtglob = true;
  404. finished = true;
  405. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  406. negatedExtglob = true;
  407. }
  408. if (scanToEnd === true) {
  409. while (eos() !== true && (code = advance())) {
  410. if (code === CHAR_BACKWARD_SLASH) {
  411. backslashes = token.backslashes = true;
  412. code = advance();
  413. continue;
  414. }
  415. if (code === CHAR_RIGHT_PARENTHESES) {
  416. isGlob = token.isGlob = true;
  417. finished = true;
  418. break;
  419. }
  420. }
  421. continue;
  422. }
  423. break;
  424. }
  425. }
  426. if (code === CHAR_ASTERISK) {
  427. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  428. isGlob = token.isGlob = true;
  429. finished = true;
  430. if (scanToEnd === true) {
  431. continue;
  432. }
  433. break;
  434. }
  435. if (code === CHAR_QUESTION_MARK) {
  436. isGlob = token.isGlob = true;
  437. finished = true;
  438. if (scanToEnd === true) {
  439. continue;
  440. }
  441. break;
  442. }
  443. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  444. while (eos() !== true && (next = advance())) {
  445. if (next === CHAR_BACKWARD_SLASH) {
  446. backslashes = token.backslashes = true;
  447. advance();
  448. continue;
  449. }
  450. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  451. isBracket = token.isBracket = true;
  452. isGlob = token.isGlob = true;
  453. finished = true;
  454. break;
  455. }
  456. }
  457. if (scanToEnd === true) {
  458. continue;
  459. }
  460. break;
  461. }
  462. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  463. negated = token.negated = true;
  464. start++;
  465. continue;
  466. }
  467. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  468. isGlob = token.isGlob = true;
  469. if (scanToEnd === true) {
  470. while (eos() !== true && (code = advance())) {
  471. if (code === CHAR_LEFT_PARENTHESES) {
  472. backslashes = token.backslashes = true;
  473. code = advance();
  474. continue;
  475. }
  476. if (code === CHAR_RIGHT_PARENTHESES) {
  477. finished = true;
  478. break;
  479. }
  480. }
  481. continue;
  482. }
  483. break;
  484. }
  485. if (isGlob === true) {
  486. finished = true;
  487. if (scanToEnd === true) {
  488. continue;
  489. }
  490. break;
  491. }
  492. }
  493. if (opts.noext === true) {
  494. isExtglob = false;
  495. isGlob = false;
  496. }
  497. let base = str;
  498. let prefix = '';
  499. let glob = '';
  500. if (start > 0) {
  501. prefix = str.slice(0, start);
  502. str = str.slice(start);
  503. lastIndex -= start;
  504. }
  505. if (base && isGlob === true && lastIndex > 0) {
  506. base = str.slice(0, lastIndex);
  507. glob = str.slice(lastIndex);
  508. } else if (isGlob === true) {
  509. base = '';
  510. glob = str;
  511. } else {
  512. base = str;
  513. }
  514. if (base && base !== '' && base !== '/' && base !== str) {
  515. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  516. base = base.slice(0, -1);
  517. }
  518. }
  519. if (opts.unescape === true) {
  520. if (glob) glob = utils.removeBackslashes(glob);
  521. if (base && backslashes === true) {
  522. base = utils.removeBackslashes(base);
  523. }
  524. }
  525. const state = {
  526. prefix,
  527. input,
  528. start,
  529. base,
  530. glob,
  531. isBrace,
  532. isBracket,
  533. isGlob,
  534. isExtglob,
  535. isGlobstar,
  536. negated,
  537. negatedExtglob
  538. };
  539. if (opts.tokens === true) {
  540. state.maxDepth = 0;
  541. if (!isPathSeparator(code)) {
  542. tokens.push(token);
  543. }
  544. state.tokens = tokens;
  545. }
  546. if (opts.parts === true || opts.tokens === true) {
  547. let prevIndex;
  548. for (let idx = 0; idx < slashes.length; idx++) {
  549. const n = prevIndex ? prevIndex + 1 : start;
  550. const i = slashes[idx];
  551. const value = input.slice(n, i);
  552. if (opts.tokens) {
  553. if (idx === 0 && start !== 0) {
  554. tokens[idx].isPrefix = true;
  555. tokens[idx].value = prefix;
  556. } else {
  557. tokens[idx].value = value;
  558. }
  559. depth(tokens[idx]);
  560. state.maxDepth += tokens[idx].depth;
  561. }
  562. if (idx !== 0 || value !== '') {
  563. parts.push(value);
  564. }
  565. prevIndex = i;
  566. }
  567. if (prevIndex && prevIndex + 1 < input.length) {
  568. const value = input.slice(prevIndex + 1);
  569. parts.push(value);
  570. if (opts.tokens) {
  571. tokens[tokens.length - 1].value = value;
  572. depth(tokens[tokens.length - 1]);
  573. state.maxDepth += tokens[tokens.length - 1].depth;
  574. }
  575. }
  576. state.slashes = slashes;
  577. state.parts = parts;
  578. }
  579. return state;
  580. };
  581. scan_1$1 = scan;
  582. return scan_1$1;
  583. }
  584. var parse_1$2;
  585. var hasRequiredParse$2;
  586. function requireParse$2 () {
  587. if (hasRequiredParse$2) return parse_1$2;
  588. hasRequiredParse$2 = 1;
  589. const constants = /*@__PURE__*/ requireConstants$3();
  590. const utils = /*@__PURE__*/ requireUtils$2();
  591. /**
  592. * Constants
  593. */
  594. const {
  595. MAX_LENGTH,
  596. POSIX_REGEX_SOURCE,
  597. REGEX_NON_SPECIAL_CHARS,
  598. REGEX_SPECIAL_CHARS_BACKREF,
  599. REPLACEMENTS
  600. } = constants;
  601. /**
  602. * Helpers
  603. */
  604. const expandRange = (args, options) => {
  605. if (typeof options.expandRange === 'function') {
  606. return options.expandRange(...args, options);
  607. }
  608. args.sort();
  609. const value = `[${args.join('-')}]`;
  610. return value;
  611. };
  612. /**
  613. * Create the message for a syntax error
  614. */
  615. const syntaxError = (type, char) => {
  616. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  617. };
  618. /**
  619. * Parse the given input string.
  620. * @param {String} input
  621. * @param {Object} options
  622. * @return {Object}
  623. */
  624. const parse = (input, options) => {
  625. if (typeof input !== 'string') {
  626. throw new TypeError('Expected a string');
  627. }
  628. input = REPLACEMENTS[input] || input;
  629. const opts = { ...options };
  630. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  631. let len = input.length;
  632. if (len > max) {
  633. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  634. }
  635. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  636. const tokens = [bos];
  637. const capture = opts.capture ? '' : '?:';
  638. const win32 = utils.isWindows(options);
  639. // create constants based on platform, for windows or posix
  640. const PLATFORM_CHARS = constants.globChars(win32);
  641. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  642. const {
  643. DOT_LITERAL,
  644. PLUS_LITERAL,
  645. SLASH_LITERAL,
  646. ONE_CHAR,
  647. DOTS_SLASH,
  648. NO_DOT,
  649. NO_DOT_SLASH,
  650. NO_DOTS_SLASH,
  651. QMARK,
  652. QMARK_NO_DOT,
  653. STAR,
  654. START_ANCHOR
  655. } = PLATFORM_CHARS;
  656. const globstar = opts => {
  657. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  658. };
  659. const nodot = opts.dot ? '' : NO_DOT;
  660. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  661. let star = opts.bash === true ? globstar(opts) : STAR;
  662. if (opts.capture) {
  663. star = `(${star})`;
  664. }
  665. // minimatch options support
  666. if (typeof opts.noext === 'boolean') {
  667. opts.noextglob = opts.noext;
  668. }
  669. const state = {
  670. input,
  671. index: -1,
  672. start: 0,
  673. dot: opts.dot === true,
  674. consumed: '',
  675. output: '',
  676. prefix: '',
  677. backtrack: false,
  678. negated: false,
  679. brackets: 0,
  680. braces: 0,
  681. parens: 0,
  682. quotes: 0,
  683. globstar: false,
  684. tokens
  685. };
  686. input = utils.removePrefix(input, state);
  687. len = input.length;
  688. const extglobs = [];
  689. const braces = [];
  690. const stack = [];
  691. let prev = bos;
  692. let value;
  693. /**
  694. * Tokenizing helpers
  695. */
  696. const eos = () => state.index === len - 1;
  697. const peek = state.peek = (n = 1) => input[state.index + n];
  698. const advance = state.advance = () => input[++state.index] || '';
  699. const remaining = () => input.slice(state.index + 1);
  700. const consume = (value = '', num = 0) => {
  701. state.consumed += value;
  702. state.index += num;
  703. };
  704. const append = token => {
  705. state.output += token.output != null ? token.output : token.value;
  706. consume(token.value);
  707. };
  708. const negate = () => {
  709. let count = 1;
  710. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  711. advance();
  712. state.start++;
  713. count++;
  714. }
  715. if (count % 2 === 0) {
  716. return false;
  717. }
  718. state.negated = true;
  719. state.start++;
  720. return true;
  721. };
  722. const increment = type => {
  723. state[type]++;
  724. stack.push(type);
  725. };
  726. const decrement = type => {
  727. state[type]--;
  728. stack.pop();
  729. };
  730. /**
  731. * Push tokens onto the tokens array. This helper speeds up
  732. * tokenizing by 1) helping us avoid backtracking as much as possible,
  733. * and 2) helping us avoid creating extra tokens when consecutive
  734. * characters are plain text. This improves performance and simplifies
  735. * lookbehinds.
  736. */
  737. const push = tok => {
  738. if (prev.type === 'globstar') {
  739. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  740. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  741. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  742. state.output = state.output.slice(0, -prev.output.length);
  743. prev.type = 'star';
  744. prev.value = '*';
  745. prev.output = star;
  746. state.output += prev.output;
  747. }
  748. }
  749. if (extglobs.length && tok.type !== 'paren') {
  750. extglobs[extglobs.length - 1].inner += tok.value;
  751. }
  752. if (tok.value || tok.output) append(tok);
  753. if (prev && prev.type === 'text' && tok.type === 'text') {
  754. prev.value += tok.value;
  755. prev.output = (prev.output || '') + tok.value;
  756. return;
  757. }
  758. tok.prev = prev;
  759. tokens.push(tok);
  760. prev = tok;
  761. };
  762. const extglobOpen = (type, value) => {
  763. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  764. token.prev = prev;
  765. token.parens = state.parens;
  766. token.output = state.output;
  767. const output = (opts.capture ? '(' : '') + token.open;
  768. increment('parens');
  769. push({ type, value, output: state.output ? '' : ONE_CHAR });
  770. push({ type: 'paren', extglob: true, value: advance(), output });
  771. extglobs.push(token);
  772. };
  773. const extglobClose = token => {
  774. let output = token.close + (opts.capture ? ')' : '');
  775. let rest;
  776. if (token.type === 'negate') {
  777. let extglobStar = star;
  778. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  779. extglobStar = globstar(opts);
  780. }
  781. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  782. output = token.close = `)$))${extglobStar}`;
  783. }
  784. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  785. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  786. // In this case, we need to parse the string and use it in the output of the original pattern.
  787. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  788. //
  789. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  790. const expression = parse(rest, { ...options, fastpaths: false }).output;
  791. output = token.close = `)${expression})${extglobStar})`;
  792. }
  793. if (token.prev.type === 'bos') {
  794. state.negatedExtglob = true;
  795. }
  796. }
  797. push({ type: 'paren', extglob: true, value, output });
  798. decrement('parens');
  799. };
  800. /**
  801. * Fast paths
  802. */
  803. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  804. let backslashes = false;
  805. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  806. if (first === '\\') {
  807. backslashes = true;
  808. return m;
  809. }
  810. if (first === '?') {
  811. if (esc) {
  812. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  813. }
  814. if (index === 0) {
  815. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  816. }
  817. return QMARK.repeat(chars.length);
  818. }
  819. if (first === '.') {
  820. return DOT_LITERAL.repeat(chars.length);
  821. }
  822. if (first === '*') {
  823. if (esc) {
  824. return esc + first + (rest ? star : '');
  825. }
  826. return star;
  827. }
  828. return esc ? m : `\\${m}`;
  829. });
  830. if (backslashes === true) {
  831. if (opts.unescape === true) {
  832. output = output.replace(/\\/g, '');
  833. } else {
  834. output = output.replace(/\\+/g, m => {
  835. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  836. });
  837. }
  838. }
  839. if (output === input && opts.contains === true) {
  840. state.output = input;
  841. return state;
  842. }
  843. state.output = utils.wrapOutput(output, state, options);
  844. return state;
  845. }
  846. /**
  847. * Tokenize input until we reach end-of-string
  848. */
  849. while (!eos()) {
  850. value = advance();
  851. if (value === '\u0000') {
  852. continue;
  853. }
  854. /**
  855. * Escaped characters
  856. */
  857. if (value === '\\') {
  858. const next = peek();
  859. if (next === '/' && opts.bash !== true) {
  860. continue;
  861. }
  862. if (next === '.' || next === ';') {
  863. continue;
  864. }
  865. if (!next) {
  866. value += '\\';
  867. push({ type: 'text', value });
  868. continue;
  869. }
  870. // collapse slashes to reduce potential for exploits
  871. const match = /^\\+/.exec(remaining());
  872. let slashes = 0;
  873. if (match && match[0].length > 2) {
  874. slashes = match[0].length;
  875. state.index += slashes;
  876. if (slashes % 2 !== 0) {
  877. value += '\\';
  878. }
  879. }
  880. if (opts.unescape === true) {
  881. value = advance();
  882. } else {
  883. value += advance();
  884. }
  885. if (state.brackets === 0) {
  886. push({ type: 'text', value });
  887. continue;
  888. }
  889. }
  890. /**
  891. * If we're inside a regex character class, continue
  892. * until we reach the closing bracket.
  893. */
  894. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  895. if (opts.posix !== false && value === ':') {
  896. const inner = prev.value.slice(1);
  897. if (inner.includes('[')) {
  898. prev.posix = true;
  899. if (inner.includes(':')) {
  900. const idx = prev.value.lastIndexOf('[');
  901. const pre = prev.value.slice(0, idx);
  902. const rest = prev.value.slice(idx + 2);
  903. const posix = POSIX_REGEX_SOURCE[rest];
  904. if (posix) {
  905. prev.value = pre + posix;
  906. state.backtrack = true;
  907. advance();
  908. if (!bos.output && tokens.indexOf(prev) === 1) {
  909. bos.output = ONE_CHAR;
  910. }
  911. continue;
  912. }
  913. }
  914. }
  915. }
  916. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  917. value = `\\${value}`;
  918. }
  919. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  920. value = `\\${value}`;
  921. }
  922. if (opts.posix === true && value === '!' && prev.value === '[') {
  923. value = '^';
  924. }
  925. prev.value += value;
  926. append({ value });
  927. continue;
  928. }
  929. /**
  930. * If we're inside a quoted string, continue
  931. * until we reach the closing double quote.
  932. */
  933. if (state.quotes === 1 && value !== '"') {
  934. value = utils.escapeRegex(value);
  935. prev.value += value;
  936. append({ value });
  937. continue;
  938. }
  939. /**
  940. * Double quotes
  941. */
  942. if (value === '"') {
  943. state.quotes = state.quotes === 1 ? 0 : 1;
  944. if (opts.keepQuotes === true) {
  945. push({ type: 'text', value });
  946. }
  947. continue;
  948. }
  949. /**
  950. * Parentheses
  951. */
  952. if (value === '(') {
  953. increment('parens');
  954. push({ type: 'paren', value });
  955. continue;
  956. }
  957. if (value === ')') {
  958. if (state.parens === 0 && opts.strictBrackets === true) {
  959. throw new SyntaxError(syntaxError('opening', '('));
  960. }
  961. const extglob = extglobs[extglobs.length - 1];
  962. if (extglob && state.parens === extglob.parens + 1) {
  963. extglobClose(extglobs.pop());
  964. continue;
  965. }
  966. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  967. decrement('parens');
  968. continue;
  969. }
  970. /**
  971. * Square brackets
  972. */
  973. if (value === '[') {
  974. if (opts.nobracket === true || !remaining().includes(']')) {
  975. if (opts.nobracket !== true && opts.strictBrackets === true) {
  976. throw new SyntaxError(syntaxError('closing', ']'));
  977. }
  978. value = `\\${value}`;
  979. } else {
  980. increment('brackets');
  981. }
  982. push({ type: 'bracket', value });
  983. continue;
  984. }
  985. if (value === ']') {
  986. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  987. push({ type: 'text', value, output: `\\${value}` });
  988. continue;
  989. }
  990. if (state.brackets === 0) {
  991. if (opts.strictBrackets === true) {
  992. throw new SyntaxError(syntaxError('opening', '['));
  993. }
  994. push({ type: 'text', value, output: `\\${value}` });
  995. continue;
  996. }
  997. decrement('brackets');
  998. const prevValue = prev.value.slice(1);
  999. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  1000. value = `/${value}`;
  1001. }
  1002. prev.value += value;
  1003. append({ value });
  1004. // when literal brackets are explicitly disabled
  1005. // assume we should match with a regex character class
  1006. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  1007. continue;
  1008. }
  1009. const escaped = utils.escapeRegex(prev.value);
  1010. state.output = state.output.slice(0, -prev.value.length);
  1011. // when literal brackets are explicitly enabled
  1012. // assume we should escape the brackets to match literal characters
  1013. if (opts.literalBrackets === true) {
  1014. state.output += escaped;
  1015. prev.value = escaped;
  1016. continue;
  1017. }
  1018. // when the user specifies nothing, try to match both
  1019. prev.value = `(${capture}${escaped}|${prev.value})`;
  1020. state.output += prev.value;
  1021. continue;
  1022. }
  1023. /**
  1024. * Braces
  1025. */
  1026. if (value === '{' && opts.nobrace !== true) {
  1027. increment('braces');
  1028. const open = {
  1029. type: 'brace',
  1030. value,
  1031. output: '(',
  1032. outputIndex: state.output.length,
  1033. tokensIndex: state.tokens.length
  1034. };
  1035. braces.push(open);
  1036. push(open);
  1037. continue;
  1038. }
  1039. if (value === '}') {
  1040. const brace = braces[braces.length - 1];
  1041. if (opts.nobrace === true || !brace) {
  1042. push({ type: 'text', value, output: value });
  1043. continue;
  1044. }
  1045. let output = ')';
  1046. if (brace.dots === true) {
  1047. const arr = tokens.slice();
  1048. const range = [];
  1049. for (let i = arr.length - 1; i >= 0; i--) {
  1050. tokens.pop();
  1051. if (arr[i].type === 'brace') {
  1052. break;
  1053. }
  1054. if (arr[i].type !== 'dots') {
  1055. range.unshift(arr[i].value);
  1056. }
  1057. }
  1058. output = expandRange(range, opts);
  1059. state.backtrack = true;
  1060. }
  1061. if (brace.comma !== true && brace.dots !== true) {
  1062. const out = state.output.slice(0, brace.outputIndex);
  1063. const toks = state.tokens.slice(brace.tokensIndex);
  1064. brace.value = brace.output = '\\{';
  1065. value = output = '\\}';
  1066. state.output = out;
  1067. for (const t of toks) {
  1068. state.output += (t.output || t.value);
  1069. }
  1070. }
  1071. push({ type: 'brace', value, output });
  1072. decrement('braces');
  1073. braces.pop();
  1074. continue;
  1075. }
  1076. /**
  1077. * Pipes
  1078. */
  1079. if (value === '|') {
  1080. if (extglobs.length > 0) {
  1081. extglobs[extglobs.length - 1].conditions++;
  1082. }
  1083. push({ type: 'text', value });
  1084. continue;
  1085. }
  1086. /**
  1087. * Commas
  1088. */
  1089. if (value === ',') {
  1090. let output = value;
  1091. const brace = braces[braces.length - 1];
  1092. if (brace && stack[stack.length - 1] === 'braces') {
  1093. brace.comma = true;
  1094. output = '|';
  1095. }
  1096. push({ type: 'comma', value, output });
  1097. continue;
  1098. }
  1099. /**
  1100. * Slashes
  1101. */
  1102. if (value === '/') {
  1103. // if the beginning of the glob is "./", advance the start
  1104. // to the current index, and don't add the "./" characters
  1105. // to the state. This greatly simplifies lookbehinds when
  1106. // checking for BOS characters like "!" and "." (not "./")
  1107. if (prev.type === 'dot' && state.index === state.start + 1) {
  1108. state.start = state.index + 1;
  1109. state.consumed = '';
  1110. state.output = '';
  1111. tokens.pop();
  1112. prev = bos; // reset "prev" to the first token
  1113. continue;
  1114. }
  1115. push({ type: 'slash', value, output: SLASH_LITERAL });
  1116. continue;
  1117. }
  1118. /**
  1119. * Dots
  1120. */
  1121. if (value === '.') {
  1122. if (state.braces > 0 && prev.type === 'dot') {
  1123. if (prev.value === '.') prev.output = DOT_LITERAL;
  1124. const brace = braces[braces.length - 1];
  1125. prev.type = 'dots';
  1126. prev.output += value;
  1127. prev.value += value;
  1128. brace.dots = true;
  1129. continue;
  1130. }
  1131. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  1132. push({ type: 'text', value, output: DOT_LITERAL });
  1133. continue;
  1134. }
  1135. push({ type: 'dot', value, output: DOT_LITERAL });
  1136. continue;
  1137. }
  1138. /**
  1139. * Question marks
  1140. */
  1141. if (value === '?') {
  1142. const isGroup = prev && prev.value === '(';
  1143. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1144. extglobOpen('qmark', value);
  1145. continue;
  1146. }
  1147. if (prev && prev.type === 'paren') {
  1148. const next = peek();
  1149. let output = value;
  1150. if (next === '<' && !utils.supportsLookbehinds()) {
  1151. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  1152. }
  1153. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  1154. output = `\\${value}`;
  1155. }
  1156. push({ type: 'text', value, output });
  1157. continue;
  1158. }
  1159. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  1160. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  1161. continue;
  1162. }
  1163. push({ type: 'qmark', value, output: QMARK });
  1164. continue;
  1165. }
  1166. /**
  1167. * Exclamation
  1168. */
  1169. if (value === '!') {
  1170. if (opts.noextglob !== true && peek() === '(') {
  1171. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  1172. extglobOpen('negate', value);
  1173. continue;
  1174. }
  1175. }
  1176. if (opts.nonegate !== true && state.index === 0) {
  1177. negate();
  1178. continue;
  1179. }
  1180. }
  1181. /**
  1182. * Plus
  1183. */
  1184. if (value === '+') {
  1185. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1186. extglobOpen('plus', value);
  1187. continue;
  1188. }
  1189. if ((prev && prev.value === '(') || opts.regex === false) {
  1190. push({ type: 'plus', value, output: PLUS_LITERAL });
  1191. continue;
  1192. }
  1193. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  1194. push({ type: 'plus', value });
  1195. continue;
  1196. }
  1197. push({ type: 'plus', value: PLUS_LITERAL });
  1198. continue;
  1199. }
  1200. /**
  1201. * Plain text
  1202. */
  1203. if (value === '@') {
  1204. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1205. push({ type: 'at', extglob: true, value, output: '' });
  1206. continue;
  1207. }
  1208. push({ type: 'text', value });
  1209. continue;
  1210. }
  1211. /**
  1212. * Plain text
  1213. */
  1214. if (value !== '*') {
  1215. if (value === '$' || value === '^') {
  1216. value = `\\${value}`;
  1217. }
  1218. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  1219. if (match) {
  1220. value += match[0];
  1221. state.index += match[0].length;
  1222. }
  1223. push({ type: 'text', value });
  1224. continue;
  1225. }
  1226. /**
  1227. * Stars
  1228. */
  1229. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  1230. prev.type = 'star';
  1231. prev.star = true;
  1232. prev.value += value;
  1233. prev.output = star;
  1234. state.backtrack = true;
  1235. state.globstar = true;
  1236. consume(value);
  1237. continue;
  1238. }
  1239. let rest = remaining();
  1240. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  1241. extglobOpen('star', value);
  1242. continue;
  1243. }
  1244. if (prev.type === 'star') {
  1245. if (opts.noglobstar === true) {
  1246. consume(value);
  1247. continue;
  1248. }
  1249. const prior = prev.prev;
  1250. const before = prior.prev;
  1251. const isStart = prior.type === 'slash' || prior.type === 'bos';
  1252. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  1253. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  1254. push({ type: 'star', value, output: '' });
  1255. continue;
  1256. }
  1257. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  1258. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  1259. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  1260. push({ type: 'star', value, output: '' });
  1261. continue;
  1262. }
  1263. // strip consecutive `/**/`
  1264. while (rest.slice(0, 3) === '/**') {
  1265. const after = input[state.index + 4];
  1266. if (after && after !== '/') {
  1267. break;
  1268. }
  1269. rest = rest.slice(3);
  1270. consume('/**', 3);
  1271. }
  1272. if (prior.type === 'bos' && eos()) {
  1273. prev.type = 'globstar';
  1274. prev.value += value;
  1275. prev.output = globstar(opts);
  1276. state.output = prev.output;
  1277. state.globstar = true;
  1278. consume(value);
  1279. continue;
  1280. }
  1281. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  1282. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  1283. prior.output = `(?:${prior.output}`;
  1284. prev.type = 'globstar';
  1285. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  1286. prev.value += value;
  1287. state.globstar = true;
  1288. state.output += prior.output + prev.output;
  1289. consume(value);
  1290. continue;
  1291. }
  1292. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  1293. const end = rest[1] !== void 0 ? '|$' : '';
  1294. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  1295. prior.output = `(?:${prior.output}`;
  1296. prev.type = 'globstar';
  1297. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  1298. prev.value += value;
  1299. state.output += prior.output + prev.output;
  1300. state.globstar = true;
  1301. consume(value + advance());
  1302. push({ type: 'slash', value: '/', output: '' });
  1303. continue;
  1304. }
  1305. if (prior.type === 'bos' && rest[0] === '/') {
  1306. prev.type = 'globstar';
  1307. prev.value += value;
  1308. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  1309. state.output = prev.output;
  1310. state.globstar = true;
  1311. consume(value + advance());
  1312. push({ type: 'slash', value: '/', output: '' });
  1313. continue;
  1314. }
  1315. // remove single star from output
  1316. state.output = state.output.slice(0, -prev.output.length);
  1317. // reset previous token to globstar
  1318. prev.type = 'globstar';
  1319. prev.output = globstar(opts);
  1320. prev.value += value;
  1321. // reset output with globstar
  1322. state.output += prev.output;
  1323. state.globstar = true;
  1324. consume(value);
  1325. continue;
  1326. }
  1327. const token = { type: 'star', value, output: star };
  1328. if (opts.bash === true) {
  1329. token.output = '.*?';
  1330. if (prev.type === 'bos' || prev.type === 'slash') {
  1331. token.output = nodot + token.output;
  1332. }
  1333. push(token);
  1334. continue;
  1335. }
  1336. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  1337. token.output = value;
  1338. push(token);
  1339. continue;
  1340. }
  1341. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  1342. if (prev.type === 'dot') {
  1343. state.output += NO_DOT_SLASH;
  1344. prev.output += NO_DOT_SLASH;
  1345. } else if (opts.dot === true) {
  1346. state.output += NO_DOTS_SLASH;
  1347. prev.output += NO_DOTS_SLASH;
  1348. } else {
  1349. state.output += nodot;
  1350. prev.output += nodot;
  1351. }
  1352. if (peek() !== '*') {
  1353. state.output += ONE_CHAR;
  1354. prev.output += ONE_CHAR;
  1355. }
  1356. }
  1357. push(token);
  1358. }
  1359. while (state.brackets > 0) {
  1360. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  1361. state.output = utils.escapeLast(state.output, '[');
  1362. decrement('brackets');
  1363. }
  1364. while (state.parens > 0) {
  1365. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  1366. state.output = utils.escapeLast(state.output, '(');
  1367. decrement('parens');
  1368. }
  1369. while (state.braces > 0) {
  1370. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  1371. state.output = utils.escapeLast(state.output, '{');
  1372. decrement('braces');
  1373. }
  1374. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  1375. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  1376. }
  1377. // rebuild the output if we had to backtrack at any point
  1378. if (state.backtrack === true) {
  1379. state.output = '';
  1380. for (const token of state.tokens) {
  1381. state.output += token.output != null ? token.output : token.value;
  1382. if (token.suffix) {
  1383. state.output += token.suffix;
  1384. }
  1385. }
  1386. }
  1387. return state;
  1388. };
  1389. /**
  1390. * Fast paths for creating regular expressions for common glob patterns.
  1391. * This can significantly speed up processing and has very little downside
  1392. * impact when none of the fast paths match.
  1393. */
  1394. parse.fastpaths = (input, options) => {
  1395. const opts = { ...options };
  1396. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  1397. const len = input.length;
  1398. if (len > max) {
  1399. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1400. }
  1401. input = REPLACEMENTS[input] || input;
  1402. const win32 = utils.isWindows(options);
  1403. // create constants based on platform, for windows or posix
  1404. const {
  1405. DOT_LITERAL,
  1406. SLASH_LITERAL,
  1407. ONE_CHAR,
  1408. DOTS_SLASH,
  1409. NO_DOT,
  1410. NO_DOTS,
  1411. NO_DOTS_SLASH,
  1412. STAR,
  1413. START_ANCHOR
  1414. } = constants.globChars(win32);
  1415. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  1416. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  1417. const capture = opts.capture ? '' : '?:';
  1418. const state = { negated: false, prefix: '' };
  1419. let star = opts.bash === true ? '.*?' : STAR;
  1420. if (opts.capture) {
  1421. star = `(${star})`;
  1422. }
  1423. const globstar = opts => {
  1424. if (opts.noglobstar === true) return star;
  1425. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1426. };
  1427. const create = str => {
  1428. switch (str) {
  1429. case '*':
  1430. return `${nodot}${ONE_CHAR}${star}`;
  1431. case '.*':
  1432. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  1433. case '*.*':
  1434. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  1435. case '*/*':
  1436. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  1437. case '**':
  1438. return nodot + globstar(opts);
  1439. case '**/*':
  1440. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  1441. case '**/*.*':
  1442. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  1443. case '**/.*':
  1444. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  1445. default: {
  1446. const match = /^(.*?)\.(\w+)$/.exec(str);
  1447. if (!match) return;
  1448. const source = create(match[1]);
  1449. if (!source) return;
  1450. return source + DOT_LITERAL + match[2];
  1451. }
  1452. }
  1453. };
  1454. const output = utils.removePrefix(input, state);
  1455. let source = create(output);
  1456. if (source && opts.strictSlashes !== true) {
  1457. source += `${SLASH_LITERAL}?`;
  1458. }
  1459. return source;
  1460. };
  1461. parse_1$2 = parse;
  1462. return parse_1$2;
  1463. }
  1464. var picomatch_1$1;
  1465. var hasRequiredPicomatch$3;
  1466. function requirePicomatch$3 () {
  1467. if (hasRequiredPicomatch$3) return picomatch_1$1;
  1468. hasRequiredPicomatch$3 = 1;
  1469. const path = require$$0$1;
  1470. const scan = /*@__PURE__*/ requireScan$1();
  1471. const parse = /*@__PURE__*/ requireParse$2();
  1472. const utils = /*@__PURE__*/ requireUtils$2();
  1473. const constants = /*@__PURE__*/ requireConstants$3();
  1474. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  1475. /**
  1476. * Creates a matcher function from one or more glob patterns. The
  1477. * returned function takes a string to match as its first argument,
  1478. * and returns true if the string is a match. The returned matcher
  1479. * function also takes a boolean as the second argument that, when true,
  1480. * returns an object with additional information.
  1481. *
  1482. * ```js
  1483. * const picomatch = require('picomatch');
  1484. * // picomatch(glob[, options]);
  1485. *
  1486. * const isMatch = picomatch('*.!(*a)');
  1487. * console.log(isMatch('a.a')); //=> false
  1488. * console.log(isMatch('a.b')); //=> true
  1489. * ```
  1490. * @name picomatch
  1491. * @param {String|Array} `globs` One or more glob patterns.
  1492. * @param {Object=} `options`
  1493. * @return {Function=} Returns a matcher function.
  1494. * @api public
  1495. */
  1496. const picomatch = (glob, options, returnState = false) => {
  1497. if (Array.isArray(glob)) {
  1498. const fns = glob.map(input => picomatch(input, options, returnState));
  1499. const arrayMatcher = str => {
  1500. for (const isMatch of fns) {
  1501. const state = isMatch(str);
  1502. if (state) return state;
  1503. }
  1504. return false;
  1505. };
  1506. return arrayMatcher;
  1507. }
  1508. const isState = isObject(glob) && glob.tokens && glob.input;
  1509. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  1510. throw new TypeError('Expected pattern to be a non-empty string');
  1511. }
  1512. const opts = options || {};
  1513. const posix = utils.isWindows(options);
  1514. const regex = isState
  1515. ? picomatch.compileRe(glob, options)
  1516. : picomatch.makeRe(glob, options, false, true);
  1517. const state = regex.state;
  1518. delete regex.state;
  1519. let isIgnored = () => false;
  1520. if (opts.ignore) {
  1521. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  1522. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  1523. }
  1524. const matcher = (input, returnObject = false) => {
  1525. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  1526. const result = { glob, state, regex, posix, input, output, match, isMatch };
  1527. if (typeof opts.onResult === 'function') {
  1528. opts.onResult(result);
  1529. }
  1530. if (isMatch === false) {
  1531. result.isMatch = false;
  1532. return returnObject ? result : false;
  1533. }
  1534. if (isIgnored(input)) {
  1535. if (typeof opts.onIgnore === 'function') {
  1536. opts.onIgnore(result);
  1537. }
  1538. result.isMatch = false;
  1539. return returnObject ? result : false;
  1540. }
  1541. if (typeof opts.onMatch === 'function') {
  1542. opts.onMatch(result);
  1543. }
  1544. return returnObject ? result : true;
  1545. };
  1546. if (returnState) {
  1547. matcher.state = state;
  1548. }
  1549. return matcher;
  1550. };
  1551. /**
  1552. * Test `input` with the given `regex`. This is used by the main
  1553. * `picomatch()` function to test the input string.
  1554. *
  1555. * ```js
  1556. * const picomatch = require('picomatch');
  1557. * // picomatch.test(input, regex[, options]);
  1558. *
  1559. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  1560. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  1561. * ```
  1562. * @param {String} `input` String to test.
  1563. * @param {RegExp} `regex`
  1564. * @return {Object} Returns an object with matching info.
  1565. * @api public
  1566. */
  1567. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  1568. if (typeof input !== 'string') {
  1569. throw new TypeError('Expected input to be a string');
  1570. }
  1571. if (input === '') {
  1572. return { isMatch: false, output: '' };
  1573. }
  1574. const opts = options || {};
  1575. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  1576. let match = input === glob;
  1577. let output = (match && format) ? format(input) : input;
  1578. if (match === false) {
  1579. output = format ? format(input) : input;
  1580. match = output === glob;
  1581. }
  1582. if (match === false || opts.capture === true) {
  1583. if (opts.matchBase === true || opts.basename === true) {
  1584. match = picomatch.matchBase(input, regex, options, posix);
  1585. } else {
  1586. match = regex.exec(output);
  1587. }
  1588. }
  1589. return { isMatch: Boolean(match), match, output };
  1590. };
  1591. /**
  1592. * Match the basename of a filepath.
  1593. *
  1594. * ```js
  1595. * const picomatch = require('picomatch');
  1596. * // picomatch.matchBase(input, glob[, options]);
  1597. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  1598. * ```
  1599. * @param {String} `input` String to test.
  1600. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  1601. * @return {Boolean}
  1602. * @api public
  1603. */
  1604. picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  1605. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  1606. return regex.test(path.basename(input));
  1607. };
  1608. /**
  1609. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  1610. *
  1611. * ```js
  1612. * const picomatch = require('picomatch');
  1613. * // picomatch.isMatch(string, patterns[, options]);
  1614. *
  1615. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  1616. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  1617. * ```
  1618. * @param {String|Array} str The string to test.
  1619. * @param {String|Array} patterns One or more glob patterns to use for matching.
  1620. * @param {Object} [options] See available [options](#options).
  1621. * @return {Boolean} Returns true if any patterns match `str`
  1622. * @api public
  1623. */
  1624. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  1625. /**
  1626. * Parse a glob pattern to create the source string for a regular
  1627. * expression.
  1628. *
  1629. * ```js
  1630. * const picomatch = require('picomatch');
  1631. * const result = picomatch.parse(pattern[, options]);
  1632. * ```
  1633. * @param {String} `pattern`
  1634. * @param {Object} `options`
  1635. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  1636. * @api public
  1637. */
  1638. picomatch.parse = (pattern, options) => {
  1639. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  1640. return parse(pattern, { ...options, fastpaths: false });
  1641. };
  1642. /**
  1643. * Scan a glob pattern to separate the pattern into segments.
  1644. *
  1645. * ```js
  1646. * const picomatch = require('picomatch');
  1647. * // picomatch.scan(input[, options]);
  1648. *
  1649. * const result = picomatch.scan('!./foo/*.js');
  1650. * console.log(result);
  1651. * { prefix: '!./',
  1652. * input: '!./foo/*.js',
  1653. * start: 3,
  1654. * base: 'foo',
  1655. * glob: '*.js',
  1656. * isBrace: false,
  1657. * isBracket: false,
  1658. * isGlob: true,
  1659. * isExtglob: false,
  1660. * isGlobstar: false,
  1661. * negated: true }
  1662. * ```
  1663. * @param {String} `input` Glob pattern to scan.
  1664. * @param {Object} `options`
  1665. * @return {Object} Returns an object with
  1666. * @api public
  1667. */
  1668. picomatch.scan = (input, options) => scan(input, options);
  1669. /**
  1670. * Compile a regular expression from the `state` object returned by the
  1671. * [parse()](#parse) method.
  1672. *
  1673. * @param {Object} `state`
  1674. * @param {Object} `options`
  1675. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  1676. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  1677. * @return {RegExp}
  1678. * @api public
  1679. */
  1680. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  1681. if (returnOutput === true) {
  1682. return state.output;
  1683. }
  1684. const opts = options || {};
  1685. const prepend = opts.contains ? '' : '^';
  1686. const append = opts.contains ? '' : '$';
  1687. let source = `${prepend}(?:${state.output})${append}`;
  1688. if (state && state.negated === true) {
  1689. source = `^(?!${source}).*$`;
  1690. }
  1691. const regex = picomatch.toRegex(source, options);
  1692. if (returnState === true) {
  1693. regex.state = state;
  1694. }
  1695. return regex;
  1696. };
  1697. /**
  1698. * Create a regular expression from a parsed glob pattern.
  1699. *
  1700. * ```js
  1701. * const picomatch = require('picomatch');
  1702. * const state = picomatch.parse('*.js');
  1703. * // picomatch.compileRe(state[, options]);
  1704. *
  1705. * console.log(picomatch.compileRe(state));
  1706. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  1707. * ```
  1708. * @param {String} `state` The object returned from the `.parse` method.
  1709. * @param {Object} `options`
  1710. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  1711. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  1712. * @return {RegExp} Returns a regex created from the given pattern.
  1713. * @api public
  1714. */
  1715. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  1716. if (!input || typeof input !== 'string') {
  1717. throw new TypeError('Expected a non-empty string');
  1718. }
  1719. let parsed = { negated: false, fastpaths: true };
  1720. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  1721. parsed.output = parse.fastpaths(input, options);
  1722. }
  1723. if (!parsed.output) {
  1724. parsed = parse(input, options);
  1725. }
  1726. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  1727. };
  1728. /**
  1729. * Create a regular expression from the given regex source string.
  1730. *
  1731. * ```js
  1732. * const picomatch = require('picomatch');
  1733. * // picomatch.toRegex(source[, options]);
  1734. *
  1735. * const { output } = picomatch.parse('*.js');
  1736. * console.log(picomatch.toRegex(output));
  1737. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  1738. * ```
  1739. * @param {String} `source` Regular expression source string.
  1740. * @param {Object} `options`
  1741. * @return {RegExp}
  1742. * @api public
  1743. */
  1744. picomatch.toRegex = (source, options) => {
  1745. try {
  1746. const opts = options || {};
  1747. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  1748. } catch (err) {
  1749. if (options && options.debug === true) throw err;
  1750. return /$^/;
  1751. }
  1752. };
  1753. /**
  1754. * Picomatch constants.
  1755. * @return {Object}
  1756. */
  1757. picomatch.constants = constants;
  1758. /**
  1759. * Expose "picomatch"
  1760. */
  1761. picomatch_1$1 = picomatch;
  1762. return picomatch_1$1;
  1763. }
  1764. var picomatch$1;
  1765. var hasRequiredPicomatch$2;
  1766. function requirePicomatch$2 () {
  1767. if (hasRequiredPicomatch$2) return picomatch$1;
  1768. hasRequiredPicomatch$2 = 1;
  1769. picomatch$1 = /*@__PURE__*/ requirePicomatch$3();
  1770. return picomatch$1;
  1771. }
  1772. var readdirp_1;
  1773. var hasRequiredReaddirp;
  1774. function requireReaddirp () {
  1775. if (hasRequiredReaddirp) return readdirp_1;
  1776. hasRequiredReaddirp = 1;
  1777. const fs = require$$0$2;
  1778. const { Readable } = require$$1;
  1779. const sysPath = require$$0$1;
  1780. const { promisify } = require$$2;
  1781. const picomatch = /*@__PURE__*/ requirePicomatch$2();
  1782. const readdir = promisify(fs.readdir);
  1783. const stat = promisify(fs.stat);
  1784. const lstat = promisify(fs.lstat);
  1785. const realpath = promisify(fs.realpath);
  1786. /**
  1787. * @typedef {Object} EntryInfo
  1788. * @property {String} path
  1789. * @property {String} fullPath
  1790. * @property {fs.Stats=} stats
  1791. * @property {fs.Dirent=} dirent
  1792. * @property {String} basename
  1793. */
  1794. const BANG = '!';
  1795. const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
  1796. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
  1797. const FILE_TYPE = 'files';
  1798. const DIR_TYPE = 'directories';
  1799. const FILE_DIR_TYPE = 'files_directories';
  1800. const EVERYTHING_TYPE = 'all';
  1801. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  1802. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  1803. const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
  1804. const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
  1805. const normalizeFilter = filter => {
  1806. if (filter === undefined) return;
  1807. if (typeof filter === 'function') return filter;
  1808. if (typeof filter === 'string') {
  1809. const glob = picomatch(filter.trim());
  1810. return entry => glob(entry.basename);
  1811. }
  1812. if (Array.isArray(filter)) {
  1813. const positive = [];
  1814. const negative = [];
  1815. for (const item of filter) {
  1816. const trimmed = item.trim();
  1817. if (trimmed.charAt(0) === BANG) {
  1818. negative.push(picomatch(trimmed.slice(1)));
  1819. } else {
  1820. positive.push(picomatch(trimmed));
  1821. }
  1822. }
  1823. if (negative.length > 0) {
  1824. if (positive.length > 0) {
  1825. return entry =>
  1826. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  1827. }
  1828. return entry => !negative.some(f => f(entry.basename));
  1829. }
  1830. return entry => positive.some(f => f(entry.basename));
  1831. }
  1832. };
  1833. class ReaddirpStream extends Readable {
  1834. static get defaultOptions() {
  1835. return {
  1836. root: '.',
  1837. /* eslint-disable no-unused-vars */
  1838. fileFilter: (path) => true,
  1839. directoryFilter: (path) => true,
  1840. /* eslint-enable no-unused-vars */
  1841. type: FILE_TYPE,
  1842. lstat: false,
  1843. depth: 2147483648,
  1844. alwaysStat: false
  1845. };
  1846. }
  1847. constructor(options = {}) {
  1848. super({
  1849. objectMode: true,
  1850. autoDestroy: true,
  1851. highWaterMark: options.highWaterMark || 4096
  1852. });
  1853. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  1854. const { root, type } = opts;
  1855. this._fileFilter = normalizeFilter(opts.fileFilter);
  1856. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  1857. const statMethod = opts.lstat ? lstat : stat;
  1858. // Use bigint stats if it's windows and stat() supports options (node 10+).
  1859. if (wantBigintFsStats) {
  1860. this._stat = path => statMethod(path, { bigint: true });
  1861. } else {
  1862. this._stat = statMethod;
  1863. }
  1864. this._maxDepth = opts.depth;
  1865. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  1866. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  1867. this._wantsEverything = type === EVERYTHING_TYPE;
  1868. this._root = sysPath.resolve(root);
  1869. this._isDirent = ('Dirent' in fs) && !opts.alwaysStat;
  1870. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  1871. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  1872. // Launch stream with one parent, the root dir.
  1873. this.parents = [this._exploreDir(root, 1)];
  1874. this.reading = false;
  1875. this.parent = undefined;
  1876. }
  1877. async _read(batch) {
  1878. if (this.reading) return;
  1879. this.reading = true;
  1880. try {
  1881. while (!this.destroyed && batch > 0) {
  1882. const { path, depth, files = [] } = this.parent || {};
  1883. if (files.length > 0) {
  1884. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  1885. for (const entry of await Promise.all(slice)) {
  1886. if (this.destroyed) return;
  1887. const entryType = await this._getEntryType(entry);
  1888. if (entryType === 'directory' && this._directoryFilter(entry)) {
  1889. if (depth <= this._maxDepth) {
  1890. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  1891. }
  1892. if (this._wantsDir) {
  1893. this.push(entry);
  1894. batch--;
  1895. }
  1896. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  1897. if (this._wantsFile) {
  1898. this.push(entry);
  1899. batch--;
  1900. }
  1901. }
  1902. }
  1903. } else {
  1904. const parent = this.parents.pop();
  1905. if (!parent) {
  1906. this.push(null);
  1907. break;
  1908. }
  1909. this.parent = await parent;
  1910. if (this.destroyed) return;
  1911. }
  1912. }
  1913. } catch (error) {
  1914. this.destroy(error);
  1915. } finally {
  1916. this.reading = false;
  1917. }
  1918. }
  1919. async _exploreDir(path, depth) {
  1920. let files;
  1921. try {
  1922. files = await readdir(path, this._rdOptions);
  1923. } catch (error) {
  1924. this._onError(error);
  1925. }
  1926. return { files, depth, path };
  1927. }
  1928. async _formatEntry(dirent, path) {
  1929. let entry;
  1930. try {
  1931. const basename = this._isDirent ? dirent.name : dirent;
  1932. const fullPath = sysPath.resolve(sysPath.join(path, basename));
  1933. entry = { path: sysPath.relative(this._root, fullPath), fullPath, basename };
  1934. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  1935. } catch (err) {
  1936. this._onError(err);
  1937. }
  1938. return entry;
  1939. }
  1940. _onError(err) {
  1941. if (isNormalFlowError(err) && !this.destroyed) {
  1942. this.emit('warn', err);
  1943. } else {
  1944. this.destroy(err);
  1945. }
  1946. }
  1947. async _getEntryType(entry) {
  1948. // entry may be undefined, because a warning or an error were emitted
  1949. // and the statsProp is undefined
  1950. const stats = entry && entry[this._statsProp];
  1951. if (!stats) {
  1952. return;
  1953. }
  1954. if (stats.isFile()) {
  1955. return 'file';
  1956. }
  1957. if (stats.isDirectory()) {
  1958. return 'directory';
  1959. }
  1960. if (stats && stats.isSymbolicLink()) {
  1961. const full = entry.fullPath;
  1962. try {
  1963. const entryRealPath = await realpath(full);
  1964. const entryRealPathStats = await lstat(entryRealPath);
  1965. if (entryRealPathStats.isFile()) {
  1966. return 'file';
  1967. }
  1968. if (entryRealPathStats.isDirectory()) {
  1969. const len = entryRealPath.length;
  1970. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath.sep) {
  1971. const recursiveError = new Error(
  1972. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  1973. );
  1974. recursiveError.code = RECURSIVE_ERROR_CODE;
  1975. return this._onError(recursiveError);
  1976. }
  1977. return 'directory';
  1978. }
  1979. } catch (error) {
  1980. this._onError(error);
  1981. }
  1982. }
  1983. }
  1984. _includeAsFile(entry) {
  1985. const stats = entry && entry[this._statsProp];
  1986. return stats && this._wantsEverything && !stats.isDirectory();
  1987. }
  1988. }
  1989. /**
  1990. * @typedef {Object} ReaddirpArguments
  1991. * @property {Function=} fileFilter
  1992. * @property {Function=} directoryFilter
  1993. * @property {String=} type
  1994. * @property {Number=} depth
  1995. * @property {String=} root
  1996. * @property {Boolean=} lstat
  1997. * @property {Boolean=} bigint
  1998. */
  1999. /**
  2000. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  2001. * @param {String} root Root directory
  2002. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  2003. */
  2004. const readdirp = (root, options = {}) => {
  2005. let type = options.entryType || options.type;
  2006. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  2007. if (type) options.type = type;
  2008. if (!root) {
  2009. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  2010. } else if (typeof root !== 'string') {
  2011. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  2012. } else if (type && !ALL_TYPES.includes(type)) {
  2013. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  2014. }
  2015. options.root = root;
  2016. return new ReaddirpStream(options);
  2017. };
  2018. const readdirpPromise = (root, options = {}) => {
  2019. return new Promise((resolve, reject) => {
  2020. const files = [];
  2021. readdirp(root, options)
  2022. .on('data', entry => files.push(entry))
  2023. .on('end', () => resolve(files))
  2024. .on('error', error => reject(error));
  2025. });
  2026. };
  2027. readdirp.promise = readdirpPromise;
  2028. readdirp.ReaddirpStream = ReaddirpStream;
  2029. readdirp.default = readdirp;
  2030. readdirp_1 = readdirp;
  2031. return readdirp_1;
  2032. }
  2033. var anymatch = {exports: {}};
  2034. var utils$1 = {};
  2035. var constants$2;
  2036. var hasRequiredConstants$2;
  2037. function requireConstants$2 () {
  2038. if (hasRequiredConstants$2) return constants$2;
  2039. hasRequiredConstants$2 = 1;
  2040. const path = require$$0$1;
  2041. const WIN_SLASH = '\\\\/';
  2042. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  2043. /**
  2044. * Posix glob regex
  2045. */
  2046. const DOT_LITERAL = '\\.';
  2047. const PLUS_LITERAL = '\\+';
  2048. const QMARK_LITERAL = '\\?';
  2049. const SLASH_LITERAL = '\\/';
  2050. const ONE_CHAR = '(?=.)';
  2051. const QMARK = '[^/]';
  2052. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  2053. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  2054. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  2055. const NO_DOT = `(?!${DOT_LITERAL})`;
  2056. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  2057. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  2058. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  2059. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  2060. const STAR = `${QMARK}*?`;
  2061. const POSIX_CHARS = {
  2062. DOT_LITERAL,
  2063. PLUS_LITERAL,
  2064. QMARK_LITERAL,
  2065. SLASH_LITERAL,
  2066. ONE_CHAR,
  2067. QMARK,
  2068. END_ANCHOR,
  2069. DOTS_SLASH,
  2070. NO_DOT,
  2071. NO_DOTS,
  2072. NO_DOT_SLASH,
  2073. NO_DOTS_SLASH,
  2074. QMARK_NO_DOT,
  2075. STAR,
  2076. START_ANCHOR
  2077. };
  2078. /**
  2079. * Windows glob regex
  2080. */
  2081. const WINDOWS_CHARS = {
  2082. ...POSIX_CHARS,
  2083. SLASH_LITERAL: `[${WIN_SLASH}]`,
  2084. QMARK: WIN_NO_SLASH,
  2085. STAR: `${WIN_NO_SLASH}*?`,
  2086. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  2087. NO_DOT: `(?!${DOT_LITERAL})`,
  2088. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2089. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  2090. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2091. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  2092. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  2093. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  2094. };
  2095. /**
  2096. * POSIX Bracket Regex
  2097. */
  2098. const POSIX_REGEX_SOURCE = {
  2099. alnum: 'a-zA-Z0-9',
  2100. alpha: 'a-zA-Z',
  2101. ascii: '\\x00-\\x7F',
  2102. blank: ' \\t',
  2103. cntrl: '\\x00-\\x1F\\x7F',
  2104. digit: '0-9',
  2105. graph: '\\x21-\\x7E',
  2106. lower: 'a-z',
  2107. print: '\\x20-\\x7E ',
  2108. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  2109. space: ' \\t\\r\\n\\v\\f',
  2110. upper: 'A-Z',
  2111. word: 'A-Za-z0-9_',
  2112. xdigit: 'A-Fa-f0-9'
  2113. };
  2114. constants$2 = {
  2115. MAX_LENGTH: 1024 * 64,
  2116. POSIX_REGEX_SOURCE,
  2117. // regular expressions
  2118. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  2119. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  2120. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  2121. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  2122. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  2123. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  2124. // Replace globs with equivalent patterns to reduce parsing time.
  2125. REPLACEMENTS: {
  2126. '***': '*',
  2127. '**/**': '**',
  2128. '**/**/**': '**'
  2129. },
  2130. // Digits
  2131. CHAR_0: 48, /* 0 */
  2132. CHAR_9: 57, /* 9 */
  2133. // Alphabet chars.
  2134. CHAR_UPPERCASE_A: 65, /* A */
  2135. CHAR_LOWERCASE_A: 97, /* a */
  2136. CHAR_UPPERCASE_Z: 90, /* Z */
  2137. CHAR_LOWERCASE_Z: 122, /* z */
  2138. CHAR_LEFT_PARENTHESES: 40, /* ( */
  2139. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  2140. CHAR_ASTERISK: 42, /* * */
  2141. // Non-alphabetic chars.
  2142. CHAR_AMPERSAND: 38, /* & */
  2143. CHAR_AT: 64, /* @ */
  2144. CHAR_BACKWARD_SLASH: 92, /* \ */
  2145. CHAR_CARRIAGE_RETURN: 13, /* \r */
  2146. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  2147. CHAR_COLON: 58, /* : */
  2148. CHAR_COMMA: 44, /* , */
  2149. CHAR_DOT: 46, /* . */
  2150. CHAR_DOUBLE_QUOTE: 34, /* " */
  2151. CHAR_EQUAL: 61, /* = */
  2152. CHAR_EXCLAMATION_MARK: 33, /* ! */
  2153. CHAR_FORM_FEED: 12, /* \f */
  2154. CHAR_FORWARD_SLASH: 47, /* / */
  2155. CHAR_GRAVE_ACCENT: 96, /* ` */
  2156. CHAR_HASH: 35, /* # */
  2157. CHAR_HYPHEN_MINUS: 45, /* - */
  2158. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  2159. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  2160. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  2161. CHAR_LINE_FEED: 10, /* \n */
  2162. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  2163. CHAR_PERCENT: 37, /* % */
  2164. CHAR_PLUS: 43, /* + */
  2165. CHAR_QUESTION_MARK: 63, /* ? */
  2166. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  2167. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  2168. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  2169. CHAR_SEMICOLON: 59, /* ; */
  2170. CHAR_SINGLE_QUOTE: 39, /* ' */
  2171. CHAR_SPACE: 32, /* */
  2172. CHAR_TAB: 9, /* \t */
  2173. CHAR_UNDERSCORE: 95, /* _ */
  2174. CHAR_VERTICAL_LINE: 124, /* | */
  2175. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  2176. SEP: path.sep,
  2177. /**
  2178. * Create EXTGLOB_CHARS
  2179. */
  2180. extglobChars(chars) {
  2181. return {
  2182. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  2183. '?': { type: 'qmark', open: '(?:', close: ')?' },
  2184. '+': { type: 'plus', open: '(?:', close: ')+' },
  2185. '*': { type: 'star', open: '(?:', close: ')*' },
  2186. '@': { type: 'at', open: '(?:', close: ')' }
  2187. };
  2188. },
  2189. /**
  2190. * Create GLOB_CHARS
  2191. */
  2192. globChars(win32) {
  2193. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  2194. }
  2195. };
  2196. return constants$2;
  2197. }
  2198. var hasRequiredUtils$1;
  2199. function requireUtils$1 () {
  2200. if (hasRequiredUtils$1) return utils$1;
  2201. hasRequiredUtils$1 = 1;
  2202. (function (exports) {
  2203. const path = require$$0$1;
  2204. const win32 = process.platform === 'win32';
  2205. const {
  2206. REGEX_BACKSLASH,
  2207. REGEX_REMOVE_BACKSLASH,
  2208. REGEX_SPECIAL_CHARS,
  2209. REGEX_SPECIAL_CHARS_GLOBAL
  2210. } = /*@__PURE__*/ requireConstants$2();
  2211. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  2212. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  2213. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  2214. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  2215. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  2216. exports.removeBackslashes = str => {
  2217. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  2218. return match === '\\' ? '' : match;
  2219. });
  2220. };
  2221. exports.supportsLookbehinds = () => {
  2222. const segs = process.version.slice(1).split('.').map(Number);
  2223. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  2224. return true;
  2225. }
  2226. return false;
  2227. };
  2228. exports.isWindows = options => {
  2229. if (options && typeof options.windows === 'boolean') {
  2230. return options.windows;
  2231. }
  2232. return win32 === true || path.sep === '\\';
  2233. };
  2234. exports.escapeLast = (input, char, lastIdx) => {
  2235. const idx = input.lastIndexOf(char, lastIdx);
  2236. if (idx === -1) return input;
  2237. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  2238. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  2239. };
  2240. exports.removePrefix = (input, state = {}) => {
  2241. let output = input;
  2242. if (output.startsWith('./')) {
  2243. output = output.slice(2);
  2244. state.prefix = './';
  2245. }
  2246. return output;
  2247. };
  2248. exports.wrapOutput = (input, state = {}, options = {}) => {
  2249. const prepend = options.contains ? '' : '^';
  2250. const append = options.contains ? '' : '$';
  2251. let output = `${prepend}(?:${input})${append}`;
  2252. if (state.negated === true) {
  2253. output = `(?:^(?!${output}).*$)`;
  2254. }
  2255. return output;
  2256. };
  2257. } (utils$1));
  2258. return utils$1;
  2259. }
  2260. var scan_1;
  2261. var hasRequiredScan;
  2262. function requireScan () {
  2263. if (hasRequiredScan) return scan_1;
  2264. hasRequiredScan = 1;
  2265. const utils = /*@__PURE__*/ requireUtils$1();
  2266. const {
  2267. CHAR_ASTERISK, /* * */
  2268. CHAR_AT, /* @ */
  2269. CHAR_BACKWARD_SLASH, /* \ */
  2270. CHAR_COMMA, /* , */
  2271. CHAR_DOT, /* . */
  2272. CHAR_EXCLAMATION_MARK, /* ! */
  2273. CHAR_FORWARD_SLASH, /* / */
  2274. CHAR_LEFT_CURLY_BRACE, /* { */
  2275. CHAR_LEFT_PARENTHESES, /* ( */
  2276. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  2277. CHAR_PLUS, /* + */
  2278. CHAR_QUESTION_MARK, /* ? */
  2279. CHAR_RIGHT_CURLY_BRACE, /* } */
  2280. CHAR_RIGHT_PARENTHESES, /* ) */
  2281. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  2282. } = /*@__PURE__*/ requireConstants$2();
  2283. const isPathSeparator = code => {
  2284. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  2285. };
  2286. const depth = token => {
  2287. if (token.isPrefix !== true) {
  2288. token.depth = token.isGlobstar ? Infinity : 1;
  2289. }
  2290. };
  2291. /**
  2292. * Quickly scans a glob pattern and returns an object with a handful of
  2293. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  2294. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  2295. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  2296. *
  2297. * ```js
  2298. * const pm = require('picomatch');
  2299. * console.log(pm.scan('foo/bar/*.js'));
  2300. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  2301. * ```
  2302. * @param {String} `str`
  2303. * @param {Object} `options`
  2304. * @return {Object} Returns an object with tokens and regex source string.
  2305. * @api public
  2306. */
  2307. const scan = (input, options) => {
  2308. const opts = options || {};
  2309. const length = input.length - 1;
  2310. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  2311. const slashes = [];
  2312. const tokens = [];
  2313. const parts = [];
  2314. let str = input;
  2315. let index = -1;
  2316. let start = 0;
  2317. let lastIndex = 0;
  2318. let isBrace = false;
  2319. let isBracket = false;
  2320. let isGlob = false;
  2321. let isExtglob = false;
  2322. let isGlobstar = false;
  2323. let braceEscaped = false;
  2324. let backslashes = false;
  2325. let negated = false;
  2326. let negatedExtglob = false;
  2327. let finished = false;
  2328. let braces = 0;
  2329. let prev;
  2330. let code;
  2331. let token = { value: '', depth: 0, isGlob: false };
  2332. const eos = () => index >= length;
  2333. const peek = () => str.charCodeAt(index + 1);
  2334. const advance = () => {
  2335. prev = code;
  2336. return str.charCodeAt(++index);
  2337. };
  2338. while (index < length) {
  2339. code = advance();
  2340. let next;
  2341. if (code === CHAR_BACKWARD_SLASH) {
  2342. backslashes = token.backslashes = true;
  2343. code = advance();
  2344. if (code === CHAR_LEFT_CURLY_BRACE) {
  2345. braceEscaped = true;
  2346. }
  2347. continue;
  2348. }
  2349. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  2350. braces++;
  2351. while (eos() !== true && (code = advance())) {
  2352. if (code === CHAR_BACKWARD_SLASH) {
  2353. backslashes = token.backslashes = true;
  2354. advance();
  2355. continue;
  2356. }
  2357. if (code === CHAR_LEFT_CURLY_BRACE) {
  2358. braces++;
  2359. continue;
  2360. }
  2361. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  2362. isBrace = token.isBrace = true;
  2363. isGlob = token.isGlob = true;
  2364. finished = true;
  2365. if (scanToEnd === true) {
  2366. continue;
  2367. }
  2368. break;
  2369. }
  2370. if (braceEscaped !== true && code === CHAR_COMMA) {
  2371. isBrace = token.isBrace = true;
  2372. isGlob = token.isGlob = true;
  2373. finished = true;
  2374. if (scanToEnd === true) {
  2375. continue;
  2376. }
  2377. break;
  2378. }
  2379. if (code === CHAR_RIGHT_CURLY_BRACE) {
  2380. braces--;
  2381. if (braces === 0) {
  2382. braceEscaped = false;
  2383. isBrace = token.isBrace = true;
  2384. finished = true;
  2385. break;
  2386. }
  2387. }
  2388. }
  2389. if (scanToEnd === true) {
  2390. continue;
  2391. }
  2392. break;
  2393. }
  2394. if (code === CHAR_FORWARD_SLASH) {
  2395. slashes.push(index);
  2396. tokens.push(token);
  2397. token = { value: '', depth: 0, isGlob: false };
  2398. if (finished === true) continue;
  2399. if (prev === CHAR_DOT && index === (start + 1)) {
  2400. start += 2;
  2401. continue;
  2402. }
  2403. lastIndex = index + 1;
  2404. continue;
  2405. }
  2406. if (opts.noext !== true) {
  2407. const isExtglobChar = code === CHAR_PLUS
  2408. || code === CHAR_AT
  2409. || code === CHAR_ASTERISK
  2410. || code === CHAR_QUESTION_MARK
  2411. || code === CHAR_EXCLAMATION_MARK;
  2412. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  2413. isGlob = token.isGlob = true;
  2414. isExtglob = token.isExtglob = true;
  2415. finished = true;
  2416. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  2417. negatedExtglob = true;
  2418. }
  2419. if (scanToEnd === true) {
  2420. while (eos() !== true && (code = advance())) {
  2421. if (code === CHAR_BACKWARD_SLASH) {
  2422. backslashes = token.backslashes = true;
  2423. code = advance();
  2424. continue;
  2425. }
  2426. if (code === CHAR_RIGHT_PARENTHESES) {
  2427. isGlob = token.isGlob = true;
  2428. finished = true;
  2429. break;
  2430. }
  2431. }
  2432. continue;
  2433. }
  2434. break;
  2435. }
  2436. }
  2437. if (code === CHAR_ASTERISK) {
  2438. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  2439. isGlob = token.isGlob = true;
  2440. finished = true;
  2441. if (scanToEnd === true) {
  2442. continue;
  2443. }
  2444. break;
  2445. }
  2446. if (code === CHAR_QUESTION_MARK) {
  2447. isGlob = token.isGlob = true;
  2448. finished = true;
  2449. if (scanToEnd === true) {
  2450. continue;
  2451. }
  2452. break;
  2453. }
  2454. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  2455. while (eos() !== true && (next = advance())) {
  2456. if (next === CHAR_BACKWARD_SLASH) {
  2457. backslashes = token.backslashes = true;
  2458. advance();
  2459. continue;
  2460. }
  2461. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  2462. isBracket = token.isBracket = true;
  2463. isGlob = token.isGlob = true;
  2464. finished = true;
  2465. break;
  2466. }
  2467. }
  2468. if (scanToEnd === true) {
  2469. continue;
  2470. }
  2471. break;
  2472. }
  2473. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  2474. negated = token.negated = true;
  2475. start++;
  2476. continue;
  2477. }
  2478. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  2479. isGlob = token.isGlob = true;
  2480. if (scanToEnd === true) {
  2481. while (eos() !== true && (code = advance())) {
  2482. if (code === CHAR_LEFT_PARENTHESES) {
  2483. backslashes = token.backslashes = true;
  2484. code = advance();
  2485. continue;
  2486. }
  2487. if (code === CHAR_RIGHT_PARENTHESES) {
  2488. finished = true;
  2489. break;
  2490. }
  2491. }
  2492. continue;
  2493. }
  2494. break;
  2495. }
  2496. if (isGlob === true) {
  2497. finished = true;
  2498. if (scanToEnd === true) {
  2499. continue;
  2500. }
  2501. break;
  2502. }
  2503. }
  2504. if (opts.noext === true) {
  2505. isExtglob = false;
  2506. isGlob = false;
  2507. }
  2508. let base = str;
  2509. let prefix = '';
  2510. let glob = '';
  2511. if (start > 0) {
  2512. prefix = str.slice(0, start);
  2513. str = str.slice(start);
  2514. lastIndex -= start;
  2515. }
  2516. if (base && isGlob === true && lastIndex > 0) {
  2517. base = str.slice(0, lastIndex);
  2518. glob = str.slice(lastIndex);
  2519. } else if (isGlob === true) {
  2520. base = '';
  2521. glob = str;
  2522. } else {
  2523. base = str;
  2524. }
  2525. if (base && base !== '' && base !== '/' && base !== str) {
  2526. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  2527. base = base.slice(0, -1);
  2528. }
  2529. }
  2530. if (opts.unescape === true) {
  2531. if (glob) glob = utils.removeBackslashes(glob);
  2532. if (base && backslashes === true) {
  2533. base = utils.removeBackslashes(base);
  2534. }
  2535. }
  2536. const state = {
  2537. prefix,
  2538. input,
  2539. start,
  2540. base,
  2541. glob,
  2542. isBrace,
  2543. isBracket,
  2544. isGlob,
  2545. isExtglob,
  2546. isGlobstar,
  2547. negated,
  2548. negatedExtglob
  2549. };
  2550. if (opts.tokens === true) {
  2551. state.maxDepth = 0;
  2552. if (!isPathSeparator(code)) {
  2553. tokens.push(token);
  2554. }
  2555. state.tokens = tokens;
  2556. }
  2557. if (opts.parts === true || opts.tokens === true) {
  2558. let prevIndex;
  2559. for (let idx = 0; idx < slashes.length; idx++) {
  2560. const n = prevIndex ? prevIndex + 1 : start;
  2561. const i = slashes[idx];
  2562. const value = input.slice(n, i);
  2563. if (opts.tokens) {
  2564. if (idx === 0 && start !== 0) {
  2565. tokens[idx].isPrefix = true;
  2566. tokens[idx].value = prefix;
  2567. } else {
  2568. tokens[idx].value = value;
  2569. }
  2570. depth(tokens[idx]);
  2571. state.maxDepth += tokens[idx].depth;
  2572. }
  2573. if (idx !== 0 || value !== '') {
  2574. parts.push(value);
  2575. }
  2576. prevIndex = i;
  2577. }
  2578. if (prevIndex && prevIndex + 1 < input.length) {
  2579. const value = input.slice(prevIndex + 1);
  2580. parts.push(value);
  2581. if (opts.tokens) {
  2582. tokens[tokens.length - 1].value = value;
  2583. depth(tokens[tokens.length - 1]);
  2584. state.maxDepth += tokens[tokens.length - 1].depth;
  2585. }
  2586. }
  2587. state.slashes = slashes;
  2588. state.parts = parts;
  2589. }
  2590. return state;
  2591. };
  2592. scan_1 = scan;
  2593. return scan_1;
  2594. }
  2595. var parse_1$1;
  2596. var hasRequiredParse$1;
  2597. function requireParse$1 () {
  2598. if (hasRequiredParse$1) return parse_1$1;
  2599. hasRequiredParse$1 = 1;
  2600. const constants = /*@__PURE__*/ requireConstants$2();
  2601. const utils = /*@__PURE__*/ requireUtils$1();
  2602. /**
  2603. * Constants
  2604. */
  2605. const {
  2606. MAX_LENGTH,
  2607. POSIX_REGEX_SOURCE,
  2608. REGEX_NON_SPECIAL_CHARS,
  2609. REGEX_SPECIAL_CHARS_BACKREF,
  2610. REPLACEMENTS
  2611. } = constants;
  2612. /**
  2613. * Helpers
  2614. */
  2615. const expandRange = (args, options) => {
  2616. if (typeof options.expandRange === 'function') {
  2617. return options.expandRange(...args, options);
  2618. }
  2619. args.sort();
  2620. const value = `[${args.join('-')}]`;
  2621. return value;
  2622. };
  2623. /**
  2624. * Create the message for a syntax error
  2625. */
  2626. const syntaxError = (type, char) => {
  2627. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  2628. };
  2629. /**
  2630. * Parse the given input string.
  2631. * @param {String} input
  2632. * @param {Object} options
  2633. * @return {Object}
  2634. */
  2635. const parse = (input, options) => {
  2636. if (typeof input !== 'string') {
  2637. throw new TypeError('Expected a string');
  2638. }
  2639. input = REPLACEMENTS[input] || input;
  2640. const opts = { ...options };
  2641. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2642. let len = input.length;
  2643. if (len > max) {
  2644. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2645. }
  2646. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  2647. const tokens = [bos];
  2648. const capture = opts.capture ? '' : '?:';
  2649. const win32 = utils.isWindows(options);
  2650. // create constants based on platform, for windows or posix
  2651. const PLATFORM_CHARS = constants.globChars(win32);
  2652. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  2653. const {
  2654. DOT_LITERAL,
  2655. PLUS_LITERAL,
  2656. SLASH_LITERAL,
  2657. ONE_CHAR,
  2658. DOTS_SLASH,
  2659. NO_DOT,
  2660. NO_DOT_SLASH,
  2661. NO_DOTS_SLASH,
  2662. QMARK,
  2663. QMARK_NO_DOT,
  2664. STAR,
  2665. START_ANCHOR
  2666. } = PLATFORM_CHARS;
  2667. const globstar = opts => {
  2668. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2669. };
  2670. const nodot = opts.dot ? '' : NO_DOT;
  2671. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  2672. let star = opts.bash === true ? globstar(opts) : STAR;
  2673. if (opts.capture) {
  2674. star = `(${star})`;
  2675. }
  2676. // minimatch options support
  2677. if (typeof opts.noext === 'boolean') {
  2678. opts.noextglob = opts.noext;
  2679. }
  2680. const state = {
  2681. input,
  2682. index: -1,
  2683. start: 0,
  2684. dot: opts.dot === true,
  2685. consumed: '',
  2686. output: '',
  2687. prefix: '',
  2688. backtrack: false,
  2689. negated: false,
  2690. brackets: 0,
  2691. braces: 0,
  2692. parens: 0,
  2693. quotes: 0,
  2694. globstar: false,
  2695. tokens
  2696. };
  2697. input = utils.removePrefix(input, state);
  2698. len = input.length;
  2699. const extglobs = [];
  2700. const braces = [];
  2701. const stack = [];
  2702. let prev = bos;
  2703. let value;
  2704. /**
  2705. * Tokenizing helpers
  2706. */
  2707. const eos = () => state.index === len - 1;
  2708. const peek = state.peek = (n = 1) => input[state.index + n];
  2709. const advance = state.advance = () => input[++state.index] || '';
  2710. const remaining = () => input.slice(state.index + 1);
  2711. const consume = (value = '', num = 0) => {
  2712. state.consumed += value;
  2713. state.index += num;
  2714. };
  2715. const append = token => {
  2716. state.output += token.output != null ? token.output : token.value;
  2717. consume(token.value);
  2718. };
  2719. const negate = () => {
  2720. let count = 1;
  2721. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  2722. advance();
  2723. state.start++;
  2724. count++;
  2725. }
  2726. if (count % 2 === 0) {
  2727. return false;
  2728. }
  2729. state.negated = true;
  2730. state.start++;
  2731. return true;
  2732. };
  2733. const increment = type => {
  2734. state[type]++;
  2735. stack.push(type);
  2736. };
  2737. const decrement = type => {
  2738. state[type]--;
  2739. stack.pop();
  2740. };
  2741. /**
  2742. * Push tokens onto the tokens array. This helper speeds up
  2743. * tokenizing by 1) helping us avoid backtracking as much as possible,
  2744. * and 2) helping us avoid creating extra tokens when consecutive
  2745. * characters are plain text. This improves performance and simplifies
  2746. * lookbehinds.
  2747. */
  2748. const push = tok => {
  2749. if (prev.type === 'globstar') {
  2750. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  2751. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  2752. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  2753. state.output = state.output.slice(0, -prev.output.length);
  2754. prev.type = 'star';
  2755. prev.value = '*';
  2756. prev.output = star;
  2757. state.output += prev.output;
  2758. }
  2759. }
  2760. if (extglobs.length && tok.type !== 'paren') {
  2761. extglobs[extglobs.length - 1].inner += tok.value;
  2762. }
  2763. if (tok.value || tok.output) append(tok);
  2764. if (prev && prev.type === 'text' && tok.type === 'text') {
  2765. prev.value += tok.value;
  2766. prev.output = (prev.output || '') + tok.value;
  2767. return;
  2768. }
  2769. tok.prev = prev;
  2770. tokens.push(tok);
  2771. prev = tok;
  2772. };
  2773. const extglobOpen = (type, value) => {
  2774. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  2775. token.prev = prev;
  2776. token.parens = state.parens;
  2777. token.output = state.output;
  2778. const output = (opts.capture ? '(' : '') + token.open;
  2779. increment('parens');
  2780. push({ type, value, output: state.output ? '' : ONE_CHAR });
  2781. push({ type: 'paren', extglob: true, value: advance(), output });
  2782. extglobs.push(token);
  2783. };
  2784. const extglobClose = token => {
  2785. let output = token.close + (opts.capture ? ')' : '');
  2786. let rest;
  2787. if (token.type === 'negate') {
  2788. let extglobStar = star;
  2789. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  2790. extglobStar = globstar(opts);
  2791. }
  2792. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  2793. output = token.close = `)$))${extglobStar}`;
  2794. }
  2795. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  2796. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  2797. // In this case, we need to parse the string and use it in the output of the original pattern.
  2798. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  2799. //
  2800. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  2801. const expression = parse(rest, { ...options, fastpaths: false }).output;
  2802. output = token.close = `)${expression})${extglobStar})`;
  2803. }
  2804. if (token.prev.type === 'bos') {
  2805. state.negatedExtglob = true;
  2806. }
  2807. }
  2808. push({ type: 'paren', extglob: true, value, output });
  2809. decrement('parens');
  2810. };
  2811. /**
  2812. * Fast paths
  2813. */
  2814. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  2815. let backslashes = false;
  2816. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  2817. if (first === '\\') {
  2818. backslashes = true;
  2819. return m;
  2820. }
  2821. if (first === '?') {
  2822. if (esc) {
  2823. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  2824. }
  2825. if (index === 0) {
  2826. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  2827. }
  2828. return QMARK.repeat(chars.length);
  2829. }
  2830. if (first === '.') {
  2831. return DOT_LITERAL.repeat(chars.length);
  2832. }
  2833. if (first === '*') {
  2834. if (esc) {
  2835. return esc + first + (rest ? star : '');
  2836. }
  2837. return star;
  2838. }
  2839. return esc ? m : `\\${m}`;
  2840. });
  2841. if (backslashes === true) {
  2842. if (opts.unescape === true) {
  2843. output = output.replace(/\\/g, '');
  2844. } else {
  2845. output = output.replace(/\\+/g, m => {
  2846. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  2847. });
  2848. }
  2849. }
  2850. if (output === input && opts.contains === true) {
  2851. state.output = input;
  2852. return state;
  2853. }
  2854. state.output = utils.wrapOutput(output, state, options);
  2855. return state;
  2856. }
  2857. /**
  2858. * Tokenize input until we reach end-of-string
  2859. */
  2860. while (!eos()) {
  2861. value = advance();
  2862. if (value === '\u0000') {
  2863. continue;
  2864. }
  2865. /**
  2866. * Escaped characters
  2867. */
  2868. if (value === '\\') {
  2869. const next = peek();
  2870. if (next === '/' && opts.bash !== true) {
  2871. continue;
  2872. }
  2873. if (next === '.' || next === ';') {
  2874. continue;
  2875. }
  2876. if (!next) {
  2877. value += '\\';
  2878. push({ type: 'text', value });
  2879. continue;
  2880. }
  2881. // collapse slashes to reduce potential for exploits
  2882. const match = /^\\+/.exec(remaining());
  2883. let slashes = 0;
  2884. if (match && match[0].length > 2) {
  2885. slashes = match[0].length;
  2886. state.index += slashes;
  2887. if (slashes % 2 !== 0) {
  2888. value += '\\';
  2889. }
  2890. }
  2891. if (opts.unescape === true) {
  2892. value = advance();
  2893. } else {
  2894. value += advance();
  2895. }
  2896. if (state.brackets === 0) {
  2897. push({ type: 'text', value });
  2898. continue;
  2899. }
  2900. }
  2901. /**
  2902. * If we're inside a regex character class, continue
  2903. * until we reach the closing bracket.
  2904. */
  2905. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  2906. if (opts.posix !== false && value === ':') {
  2907. const inner = prev.value.slice(1);
  2908. if (inner.includes('[')) {
  2909. prev.posix = true;
  2910. if (inner.includes(':')) {
  2911. const idx = prev.value.lastIndexOf('[');
  2912. const pre = prev.value.slice(0, idx);
  2913. const rest = prev.value.slice(idx + 2);
  2914. const posix = POSIX_REGEX_SOURCE[rest];
  2915. if (posix) {
  2916. prev.value = pre + posix;
  2917. state.backtrack = true;
  2918. advance();
  2919. if (!bos.output && tokens.indexOf(prev) === 1) {
  2920. bos.output = ONE_CHAR;
  2921. }
  2922. continue;
  2923. }
  2924. }
  2925. }
  2926. }
  2927. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  2928. value = `\\${value}`;
  2929. }
  2930. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  2931. value = `\\${value}`;
  2932. }
  2933. if (opts.posix === true && value === '!' && prev.value === '[') {
  2934. value = '^';
  2935. }
  2936. prev.value += value;
  2937. append({ value });
  2938. continue;
  2939. }
  2940. /**
  2941. * If we're inside a quoted string, continue
  2942. * until we reach the closing double quote.
  2943. */
  2944. if (state.quotes === 1 && value !== '"') {
  2945. value = utils.escapeRegex(value);
  2946. prev.value += value;
  2947. append({ value });
  2948. continue;
  2949. }
  2950. /**
  2951. * Double quotes
  2952. */
  2953. if (value === '"') {
  2954. state.quotes = state.quotes === 1 ? 0 : 1;
  2955. if (opts.keepQuotes === true) {
  2956. push({ type: 'text', value });
  2957. }
  2958. continue;
  2959. }
  2960. /**
  2961. * Parentheses
  2962. */
  2963. if (value === '(') {
  2964. increment('parens');
  2965. push({ type: 'paren', value });
  2966. continue;
  2967. }
  2968. if (value === ')') {
  2969. if (state.parens === 0 && opts.strictBrackets === true) {
  2970. throw new SyntaxError(syntaxError('opening', '('));
  2971. }
  2972. const extglob = extglobs[extglobs.length - 1];
  2973. if (extglob && state.parens === extglob.parens + 1) {
  2974. extglobClose(extglobs.pop());
  2975. continue;
  2976. }
  2977. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  2978. decrement('parens');
  2979. continue;
  2980. }
  2981. /**
  2982. * Square brackets
  2983. */
  2984. if (value === '[') {
  2985. if (opts.nobracket === true || !remaining().includes(']')) {
  2986. if (opts.nobracket !== true && opts.strictBrackets === true) {
  2987. throw new SyntaxError(syntaxError('closing', ']'));
  2988. }
  2989. value = `\\${value}`;
  2990. } else {
  2991. increment('brackets');
  2992. }
  2993. push({ type: 'bracket', value });
  2994. continue;
  2995. }
  2996. if (value === ']') {
  2997. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  2998. push({ type: 'text', value, output: `\\${value}` });
  2999. continue;
  3000. }
  3001. if (state.brackets === 0) {
  3002. if (opts.strictBrackets === true) {
  3003. throw new SyntaxError(syntaxError('opening', '['));
  3004. }
  3005. push({ type: 'text', value, output: `\\${value}` });
  3006. continue;
  3007. }
  3008. decrement('brackets');
  3009. const prevValue = prev.value.slice(1);
  3010. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  3011. value = `/${value}`;
  3012. }
  3013. prev.value += value;
  3014. append({ value });
  3015. // when literal brackets are explicitly disabled
  3016. // assume we should match with a regex character class
  3017. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  3018. continue;
  3019. }
  3020. const escaped = utils.escapeRegex(prev.value);
  3021. state.output = state.output.slice(0, -prev.value.length);
  3022. // when literal brackets are explicitly enabled
  3023. // assume we should escape the brackets to match literal characters
  3024. if (opts.literalBrackets === true) {
  3025. state.output += escaped;
  3026. prev.value = escaped;
  3027. continue;
  3028. }
  3029. // when the user specifies nothing, try to match both
  3030. prev.value = `(${capture}${escaped}|${prev.value})`;
  3031. state.output += prev.value;
  3032. continue;
  3033. }
  3034. /**
  3035. * Braces
  3036. */
  3037. if (value === '{' && opts.nobrace !== true) {
  3038. increment('braces');
  3039. const open = {
  3040. type: 'brace',
  3041. value,
  3042. output: '(',
  3043. outputIndex: state.output.length,
  3044. tokensIndex: state.tokens.length
  3045. };
  3046. braces.push(open);
  3047. push(open);
  3048. continue;
  3049. }
  3050. if (value === '}') {
  3051. const brace = braces[braces.length - 1];
  3052. if (opts.nobrace === true || !brace) {
  3053. push({ type: 'text', value, output: value });
  3054. continue;
  3055. }
  3056. let output = ')';
  3057. if (brace.dots === true) {
  3058. const arr = tokens.slice();
  3059. const range = [];
  3060. for (let i = arr.length - 1; i >= 0; i--) {
  3061. tokens.pop();
  3062. if (arr[i].type === 'brace') {
  3063. break;
  3064. }
  3065. if (arr[i].type !== 'dots') {
  3066. range.unshift(arr[i].value);
  3067. }
  3068. }
  3069. output = expandRange(range, opts);
  3070. state.backtrack = true;
  3071. }
  3072. if (brace.comma !== true && brace.dots !== true) {
  3073. const out = state.output.slice(0, brace.outputIndex);
  3074. const toks = state.tokens.slice(brace.tokensIndex);
  3075. brace.value = brace.output = '\\{';
  3076. value = output = '\\}';
  3077. state.output = out;
  3078. for (const t of toks) {
  3079. state.output += (t.output || t.value);
  3080. }
  3081. }
  3082. push({ type: 'brace', value, output });
  3083. decrement('braces');
  3084. braces.pop();
  3085. continue;
  3086. }
  3087. /**
  3088. * Pipes
  3089. */
  3090. if (value === '|') {
  3091. if (extglobs.length > 0) {
  3092. extglobs[extglobs.length - 1].conditions++;
  3093. }
  3094. push({ type: 'text', value });
  3095. continue;
  3096. }
  3097. /**
  3098. * Commas
  3099. */
  3100. if (value === ',') {
  3101. let output = value;
  3102. const brace = braces[braces.length - 1];
  3103. if (brace && stack[stack.length - 1] === 'braces') {
  3104. brace.comma = true;
  3105. output = '|';
  3106. }
  3107. push({ type: 'comma', value, output });
  3108. continue;
  3109. }
  3110. /**
  3111. * Slashes
  3112. */
  3113. if (value === '/') {
  3114. // if the beginning of the glob is "./", advance the start
  3115. // to the current index, and don't add the "./" characters
  3116. // to the state. This greatly simplifies lookbehinds when
  3117. // checking for BOS characters like "!" and "." (not "./")
  3118. if (prev.type === 'dot' && state.index === state.start + 1) {
  3119. state.start = state.index + 1;
  3120. state.consumed = '';
  3121. state.output = '';
  3122. tokens.pop();
  3123. prev = bos; // reset "prev" to the first token
  3124. continue;
  3125. }
  3126. push({ type: 'slash', value, output: SLASH_LITERAL });
  3127. continue;
  3128. }
  3129. /**
  3130. * Dots
  3131. */
  3132. if (value === '.') {
  3133. if (state.braces > 0 && prev.type === 'dot') {
  3134. if (prev.value === '.') prev.output = DOT_LITERAL;
  3135. const brace = braces[braces.length - 1];
  3136. prev.type = 'dots';
  3137. prev.output += value;
  3138. prev.value += value;
  3139. brace.dots = true;
  3140. continue;
  3141. }
  3142. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  3143. push({ type: 'text', value, output: DOT_LITERAL });
  3144. continue;
  3145. }
  3146. push({ type: 'dot', value, output: DOT_LITERAL });
  3147. continue;
  3148. }
  3149. /**
  3150. * Question marks
  3151. */
  3152. if (value === '?') {
  3153. const isGroup = prev && prev.value === '(';
  3154. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3155. extglobOpen('qmark', value);
  3156. continue;
  3157. }
  3158. if (prev && prev.type === 'paren') {
  3159. const next = peek();
  3160. let output = value;
  3161. if (next === '<' && !utils.supportsLookbehinds()) {
  3162. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  3163. }
  3164. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  3165. output = `\\${value}`;
  3166. }
  3167. push({ type: 'text', value, output });
  3168. continue;
  3169. }
  3170. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  3171. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  3172. continue;
  3173. }
  3174. push({ type: 'qmark', value, output: QMARK });
  3175. continue;
  3176. }
  3177. /**
  3178. * Exclamation
  3179. */
  3180. if (value === '!') {
  3181. if (opts.noextglob !== true && peek() === '(') {
  3182. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  3183. extglobOpen('negate', value);
  3184. continue;
  3185. }
  3186. }
  3187. if (opts.nonegate !== true && state.index === 0) {
  3188. negate();
  3189. continue;
  3190. }
  3191. }
  3192. /**
  3193. * Plus
  3194. */
  3195. if (value === '+') {
  3196. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3197. extglobOpen('plus', value);
  3198. continue;
  3199. }
  3200. if ((prev && prev.value === '(') || opts.regex === false) {
  3201. push({ type: 'plus', value, output: PLUS_LITERAL });
  3202. continue;
  3203. }
  3204. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  3205. push({ type: 'plus', value });
  3206. continue;
  3207. }
  3208. push({ type: 'plus', value: PLUS_LITERAL });
  3209. continue;
  3210. }
  3211. /**
  3212. * Plain text
  3213. */
  3214. if (value === '@') {
  3215. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3216. push({ type: 'at', extglob: true, value, output: '' });
  3217. continue;
  3218. }
  3219. push({ type: 'text', value });
  3220. continue;
  3221. }
  3222. /**
  3223. * Plain text
  3224. */
  3225. if (value !== '*') {
  3226. if (value === '$' || value === '^') {
  3227. value = `\\${value}`;
  3228. }
  3229. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  3230. if (match) {
  3231. value += match[0];
  3232. state.index += match[0].length;
  3233. }
  3234. push({ type: 'text', value });
  3235. continue;
  3236. }
  3237. /**
  3238. * Stars
  3239. */
  3240. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  3241. prev.type = 'star';
  3242. prev.star = true;
  3243. prev.value += value;
  3244. prev.output = star;
  3245. state.backtrack = true;
  3246. state.globstar = true;
  3247. consume(value);
  3248. continue;
  3249. }
  3250. let rest = remaining();
  3251. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  3252. extglobOpen('star', value);
  3253. continue;
  3254. }
  3255. if (prev.type === 'star') {
  3256. if (opts.noglobstar === true) {
  3257. consume(value);
  3258. continue;
  3259. }
  3260. const prior = prev.prev;
  3261. const before = prior.prev;
  3262. const isStart = prior.type === 'slash' || prior.type === 'bos';
  3263. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  3264. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  3265. push({ type: 'star', value, output: '' });
  3266. continue;
  3267. }
  3268. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  3269. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  3270. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  3271. push({ type: 'star', value, output: '' });
  3272. continue;
  3273. }
  3274. // strip consecutive `/**/`
  3275. while (rest.slice(0, 3) === '/**') {
  3276. const after = input[state.index + 4];
  3277. if (after && after !== '/') {
  3278. break;
  3279. }
  3280. rest = rest.slice(3);
  3281. consume('/**', 3);
  3282. }
  3283. if (prior.type === 'bos' && eos()) {
  3284. prev.type = 'globstar';
  3285. prev.value += value;
  3286. prev.output = globstar(opts);
  3287. state.output = prev.output;
  3288. state.globstar = true;
  3289. consume(value);
  3290. continue;
  3291. }
  3292. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  3293. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3294. prior.output = `(?:${prior.output}`;
  3295. prev.type = 'globstar';
  3296. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  3297. prev.value += value;
  3298. state.globstar = true;
  3299. state.output += prior.output + prev.output;
  3300. consume(value);
  3301. continue;
  3302. }
  3303. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  3304. const end = rest[1] !== void 0 ? '|$' : '';
  3305. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3306. prior.output = `(?:${prior.output}`;
  3307. prev.type = 'globstar';
  3308. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  3309. prev.value += value;
  3310. state.output += prior.output + prev.output;
  3311. state.globstar = true;
  3312. consume(value + advance());
  3313. push({ type: 'slash', value: '/', output: '' });
  3314. continue;
  3315. }
  3316. if (prior.type === 'bos' && rest[0] === '/') {
  3317. prev.type = 'globstar';
  3318. prev.value += value;
  3319. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  3320. state.output = prev.output;
  3321. state.globstar = true;
  3322. consume(value + advance());
  3323. push({ type: 'slash', value: '/', output: '' });
  3324. continue;
  3325. }
  3326. // remove single star from output
  3327. state.output = state.output.slice(0, -prev.output.length);
  3328. // reset previous token to globstar
  3329. prev.type = 'globstar';
  3330. prev.output = globstar(opts);
  3331. prev.value += value;
  3332. // reset output with globstar
  3333. state.output += prev.output;
  3334. state.globstar = true;
  3335. consume(value);
  3336. continue;
  3337. }
  3338. const token = { type: 'star', value, output: star };
  3339. if (opts.bash === true) {
  3340. token.output = '.*?';
  3341. if (prev.type === 'bos' || prev.type === 'slash') {
  3342. token.output = nodot + token.output;
  3343. }
  3344. push(token);
  3345. continue;
  3346. }
  3347. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  3348. token.output = value;
  3349. push(token);
  3350. continue;
  3351. }
  3352. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  3353. if (prev.type === 'dot') {
  3354. state.output += NO_DOT_SLASH;
  3355. prev.output += NO_DOT_SLASH;
  3356. } else if (opts.dot === true) {
  3357. state.output += NO_DOTS_SLASH;
  3358. prev.output += NO_DOTS_SLASH;
  3359. } else {
  3360. state.output += nodot;
  3361. prev.output += nodot;
  3362. }
  3363. if (peek() !== '*') {
  3364. state.output += ONE_CHAR;
  3365. prev.output += ONE_CHAR;
  3366. }
  3367. }
  3368. push(token);
  3369. }
  3370. while (state.brackets > 0) {
  3371. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  3372. state.output = utils.escapeLast(state.output, '[');
  3373. decrement('brackets');
  3374. }
  3375. while (state.parens > 0) {
  3376. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  3377. state.output = utils.escapeLast(state.output, '(');
  3378. decrement('parens');
  3379. }
  3380. while (state.braces > 0) {
  3381. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  3382. state.output = utils.escapeLast(state.output, '{');
  3383. decrement('braces');
  3384. }
  3385. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  3386. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  3387. }
  3388. // rebuild the output if we had to backtrack at any point
  3389. if (state.backtrack === true) {
  3390. state.output = '';
  3391. for (const token of state.tokens) {
  3392. state.output += token.output != null ? token.output : token.value;
  3393. if (token.suffix) {
  3394. state.output += token.suffix;
  3395. }
  3396. }
  3397. }
  3398. return state;
  3399. };
  3400. /**
  3401. * Fast paths for creating regular expressions for common glob patterns.
  3402. * This can significantly speed up processing and has very little downside
  3403. * impact when none of the fast paths match.
  3404. */
  3405. parse.fastpaths = (input, options) => {
  3406. const opts = { ...options };
  3407. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3408. const len = input.length;
  3409. if (len > max) {
  3410. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3411. }
  3412. input = REPLACEMENTS[input] || input;
  3413. const win32 = utils.isWindows(options);
  3414. // create constants based on platform, for windows or posix
  3415. const {
  3416. DOT_LITERAL,
  3417. SLASH_LITERAL,
  3418. ONE_CHAR,
  3419. DOTS_SLASH,
  3420. NO_DOT,
  3421. NO_DOTS,
  3422. NO_DOTS_SLASH,
  3423. STAR,
  3424. START_ANCHOR
  3425. } = constants.globChars(win32);
  3426. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  3427. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  3428. const capture = opts.capture ? '' : '?:';
  3429. const state = { negated: false, prefix: '' };
  3430. let star = opts.bash === true ? '.*?' : STAR;
  3431. if (opts.capture) {
  3432. star = `(${star})`;
  3433. }
  3434. const globstar = opts => {
  3435. if (opts.noglobstar === true) return star;
  3436. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3437. };
  3438. const create = str => {
  3439. switch (str) {
  3440. case '*':
  3441. return `${nodot}${ONE_CHAR}${star}`;
  3442. case '.*':
  3443. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  3444. case '*.*':
  3445. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3446. case '*/*':
  3447. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  3448. case '**':
  3449. return nodot + globstar(opts);
  3450. case '**/*':
  3451. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  3452. case '**/*.*':
  3453. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3454. case '**/.*':
  3455. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  3456. default: {
  3457. const match = /^(.*?)\.(\w+)$/.exec(str);
  3458. if (!match) return;
  3459. const source = create(match[1]);
  3460. if (!source) return;
  3461. return source + DOT_LITERAL + match[2];
  3462. }
  3463. }
  3464. };
  3465. const output = utils.removePrefix(input, state);
  3466. let source = create(output);
  3467. if (source && opts.strictSlashes !== true) {
  3468. source += `${SLASH_LITERAL}?`;
  3469. }
  3470. return source;
  3471. };
  3472. parse_1$1 = parse;
  3473. return parse_1$1;
  3474. }
  3475. var picomatch_1;
  3476. var hasRequiredPicomatch$1;
  3477. function requirePicomatch$1 () {
  3478. if (hasRequiredPicomatch$1) return picomatch_1;
  3479. hasRequiredPicomatch$1 = 1;
  3480. const path = require$$0$1;
  3481. const scan = /*@__PURE__*/ requireScan();
  3482. const parse = /*@__PURE__*/ requireParse$1();
  3483. const utils = /*@__PURE__*/ requireUtils$1();
  3484. const constants = /*@__PURE__*/ requireConstants$2();
  3485. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  3486. /**
  3487. * Creates a matcher function from one or more glob patterns. The
  3488. * returned function takes a string to match as its first argument,
  3489. * and returns true if the string is a match. The returned matcher
  3490. * function also takes a boolean as the second argument that, when true,
  3491. * returns an object with additional information.
  3492. *
  3493. * ```js
  3494. * const picomatch = require('picomatch');
  3495. * // picomatch(glob[, options]);
  3496. *
  3497. * const isMatch = picomatch('*.!(*a)');
  3498. * console.log(isMatch('a.a')); //=> false
  3499. * console.log(isMatch('a.b')); //=> true
  3500. * ```
  3501. * @name picomatch
  3502. * @param {String|Array} `globs` One or more glob patterns.
  3503. * @param {Object=} `options`
  3504. * @return {Function=} Returns a matcher function.
  3505. * @api public
  3506. */
  3507. const picomatch = (glob, options, returnState = false) => {
  3508. if (Array.isArray(glob)) {
  3509. const fns = glob.map(input => picomatch(input, options, returnState));
  3510. const arrayMatcher = str => {
  3511. for (const isMatch of fns) {
  3512. const state = isMatch(str);
  3513. if (state) return state;
  3514. }
  3515. return false;
  3516. };
  3517. return arrayMatcher;
  3518. }
  3519. const isState = isObject(glob) && glob.tokens && glob.input;
  3520. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  3521. throw new TypeError('Expected pattern to be a non-empty string');
  3522. }
  3523. const opts = options || {};
  3524. const posix = utils.isWindows(options);
  3525. const regex = isState
  3526. ? picomatch.compileRe(glob, options)
  3527. : picomatch.makeRe(glob, options, false, true);
  3528. const state = regex.state;
  3529. delete regex.state;
  3530. let isIgnored = () => false;
  3531. if (opts.ignore) {
  3532. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  3533. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  3534. }
  3535. const matcher = (input, returnObject = false) => {
  3536. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  3537. const result = { glob, state, regex, posix, input, output, match, isMatch };
  3538. if (typeof opts.onResult === 'function') {
  3539. opts.onResult(result);
  3540. }
  3541. if (isMatch === false) {
  3542. result.isMatch = false;
  3543. return returnObject ? result : false;
  3544. }
  3545. if (isIgnored(input)) {
  3546. if (typeof opts.onIgnore === 'function') {
  3547. opts.onIgnore(result);
  3548. }
  3549. result.isMatch = false;
  3550. return returnObject ? result : false;
  3551. }
  3552. if (typeof opts.onMatch === 'function') {
  3553. opts.onMatch(result);
  3554. }
  3555. return returnObject ? result : true;
  3556. };
  3557. if (returnState) {
  3558. matcher.state = state;
  3559. }
  3560. return matcher;
  3561. };
  3562. /**
  3563. * Test `input` with the given `regex`. This is used by the main
  3564. * `picomatch()` function to test the input string.
  3565. *
  3566. * ```js
  3567. * const picomatch = require('picomatch');
  3568. * // picomatch.test(input, regex[, options]);
  3569. *
  3570. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  3571. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  3572. * ```
  3573. * @param {String} `input` String to test.
  3574. * @param {RegExp} `regex`
  3575. * @return {Object} Returns an object with matching info.
  3576. * @api public
  3577. */
  3578. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  3579. if (typeof input !== 'string') {
  3580. throw new TypeError('Expected input to be a string');
  3581. }
  3582. if (input === '') {
  3583. return { isMatch: false, output: '' };
  3584. }
  3585. const opts = options || {};
  3586. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  3587. let match = input === glob;
  3588. let output = (match && format) ? format(input) : input;
  3589. if (match === false) {
  3590. output = format ? format(input) : input;
  3591. match = output === glob;
  3592. }
  3593. if (match === false || opts.capture === true) {
  3594. if (opts.matchBase === true || opts.basename === true) {
  3595. match = picomatch.matchBase(input, regex, options, posix);
  3596. } else {
  3597. match = regex.exec(output);
  3598. }
  3599. }
  3600. return { isMatch: Boolean(match), match, output };
  3601. };
  3602. /**
  3603. * Match the basename of a filepath.
  3604. *
  3605. * ```js
  3606. * const picomatch = require('picomatch');
  3607. * // picomatch.matchBase(input, glob[, options]);
  3608. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  3609. * ```
  3610. * @param {String} `input` String to test.
  3611. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  3612. * @return {Boolean}
  3613. * @api public
  3614. */
  3615. picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  3616. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  3617. return regex.test(path.basename(input));
  3618. };
  3619. /**
  3620. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  3621. *
  3622. * ```js
  3623. * const picomatch = require('picomatch');
  3624. * // picomatch.isMatch(string, patterns[, options]);
  3625. *
  3626. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  3627. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  3628. * ```
  3629. * @param {String|Array} str The string to test.
  3630. * @param {String|Array} patterns One or more glob patterns to use for matching.
  3631. * @param {Object} [options] See available [options](#options).
  3632. * @return {Boolean} Returns true if any patterns match `str`
  3633. * @api public
  3634. */
  3635. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  3636. /**
  3637. * Parse a glob pattern to create the source string for a regular
  3638. * expression.
  3639. *
  3640. * ```js
  3641. * const picomatch = require('picomatch');
  3642. * const result = picomatch.parse(pattern[, options]);
  3643. * ```
  3644. * @param {String} `pattern`
  3645. * @param {Object} `options`
  3646. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  3647. * @api public
  3648. */
  3649. picomatch.parse = (pattern, options) => {
  3650. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  3651. return parse(pattern, { ...options, fastpaths: false });
  3652. };
  3653. /**
  3654. * Scan a glob pattern to separate the pattern into segments.
  3655. *
  3656. * ```js
  3657. * const picomatch = require('picomatch');
  3658. * // picomatch.scan(input[, options]);
  3659. *
  3660. * const result = picomatch.scan('!./foo/*.js');
  3661. * console.log(result);
  3662. * { prefix: '!./',
  3663. * input: '!./foo/*.js',
  3664. * start: 3,
  3665. * base: 'foo',
  3666. * glob: '*.js',
  3667. * isBrace: false,
  3668. * isBracket: false,
  3669. * isGlob: true,
  3670. * isExtglob: false,
  3671. * isGlobstar: false,
  3672. * negated: true }
  3673. * ```
  3674. * @param {String} `input` Glob pattern to scan.
  3675. * @param {Object} `options`
  3676. * @return {Object} Returns an object with
  3677. * @api public
  3678. */
  3679. picomatch.scan = (input, options) => scan(input, options);
  3680. /**
  3681. * Compile a regular expression from the `state` object returned by the
  3682. * [parse()](#parse) method.
  3683. *
  3684. * @param {Object} `state`
  3685. * @param {Object} `options`
  3686. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  3687. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  3688. * @return {RegExp}
  3689. * @api public
  3690. */
  3691. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  3692. if (returnOutput === true) {
  3693. return state.output;
  3694. }
  3695. const opts = options || {};
  3696. const prepend = opts.contains ? '' : '^';
  3697. const append = opts.contains ? '' : '$';
  3698. let source = `${prepend}(?:${state.output})${append}`;
  3699. if (state && state.negated === true) {
  3700. source = `^(?!${source}).*$`;
  3701. }
  3702. const regex = picomatch.toRegex(source, options);
  3703. if (returnState === true) {
  3704. regex.state = state;
  3705. }
  3706. return regex;
  3707. };
  3708. /**
  3709. * Create a regular expression from a parsed glob pattern.
  3710. *
  3711. * ```js
  3712. * const picomatch = require('picomatch');
  3713. * const state = picomatch.parse('*.js');
  3714. * // picomatch.compileRe(state[, options]);
  3715. *
  3716. * console.log(picomatch.compileRe(state));
  3717. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3718. * ```
  3719. * @param {String} `state` The object returned from the `.parse` method.
  3720. * @param {Object} `options`
  3721. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  3722. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  3723. * @return {RegExp} Returns a regex created from the given pattern.
  3724. * @api public
  3725. */
  3726. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  3727. if (!input || typeof input !== 'string') {
  3728. throw new TypeError('Expected a non-empty string');
  3729. }
  3730. let parsed = { negated: false, fastpaths: true };
  3731. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  3732. parsed.output = parse.fastpaths(input, options);
  3733. }
  3734. if (!parsed.output) {
  3735. parsed = parse(input, options);
  3736. }
  3737. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  3738. };
  3739. /**
  3740. * Create a regular expression from the given regex source string.
  3741. *
  3742. * ```js
  3743. * const picomatch = require('picomatch');
  3744. * // picomatch.toRegex(source[, options]);
  3745. *
  3746. * const { output } = picomatch.parse('*.js');
  3747. * console.log(picomatch.toRegex(output));
  3748. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3749. * ```
  3750. * @param {String} `source` Regular expression source string.
  3751. * @param {Object} `options`
  3752. * @return {RegExp}
  3753. * @api public
  3754. */
  3755. picomatch.toRegex = (source, options) => {
  3756. try {
  3757. const opts = options || {};
  3758. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  3759. } catch (err) {
  3760. if (options && options.debug === true) throw err;
  3761. return /$^/;
  3762. }
  3763. };
  3764. /**
  3765. * Picomatch constants.
  3766. * @return {Object}
  3767. */
  3768. picomatch.constants = constants;
  3769. /**
  3770. * Expose "picomatch"
  3771. */
  3772. picomatch_1 = picomatch;
  3773. return picomatch_1;
  3774. }
  3775. var picomatch;
  3776. var hasRequiredPicomatch;
  3777. function requirePicomatch () {
  3778. if (hasRequiredPicomatch) return picomatch;
  3779. hasRequiredPicomatch = 1;
  3780. picomatch = /*@__PURE__*/ requirePicomatch$1();
  3781. return picomatch;
  3782. }
  3783. /*!
  3784. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  3785. *
  3786. * Copyright (c) 2014-2018, Jon Schlinkert.
  3787. * Released under the MIT License.
  3788. */
  3789. var normalizePath;
  3790. var hasRequiredNormalizePath;
  3791. function requireNormalizePath () {
  3792. if (hasRequiredNormalizePath) return normalizePath;
  3793. hasRequiredNormalizePath = 1;
  3794. normalizePath = function(path, stripTrailing) {
  3795. if (typeof path !== 'string') {
  3796. throw new TypeError('expected path to be a string');
  3797. }
  3798. if (path === '\\' || path === '/') return '/';
  3799. var len = path.length;
  3800. if (len <= 1) return path;
  3801. // ensure that win32 namespaces has two leading slashes, so that the path is
  3802. // handled properly by the win32 version of path.parse() after being normalized
  3803. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  3804. var prefix = '';
  3805. if (len > 4 && path[3] === '\\') {
  3806. var ch = path[2];
  3807. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  3808. path = path.slice(2);
  3809. prefix = '//';
  3810. }
  3811. }
  3812. var segs = path.split(/[/\\]+/);
  3813. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  3814. segs.pop();
  3815. }
  3816. return prefix + segs.join('/');
  3817. };
  3818. return normalizePath;
  3819. }
  3820. var anymatch_1 = anymatch.exports;
  3821. var hasRequiredAnymatch;
  3822. function requireAnymatch () {
  3823. if (hasRequiredAnymatch) return anymatch.exports;
  3824. hasRequiredAnymatch = 1;
  3825. Object.defineProperty(anymatch_1, "__esModule", { value: true });
  3826. const picomatch = /*@__PURE__*/ requirePicomatch();
  3827. const normalizePath = /*@__PURE__*/ requireNormalizePath();
  3828. /**
  3829. * @typedef {(testString: string) => boolean} AnymatchFn
  3830. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  3831. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  3832. */
  3833. const BANG = '!';
  3834. const DEFAULT_OPTIONS = {returnIndex: false};
  3835. const arrify = (item) => Array.isArray(item) ? item : [item];
  3836. /**
  3837. * @param {AnymatchPattern} matcher
  3838. * @param {object} options
  3839. * @returns {AnymatchFn}
  3840. */
  3841. const createPattern = (matcher, options) => {
  3842. if (typeof matcher === 'function') {
  3843. return matcher;
  3844. }
  3845. if (typeof matcher === 'string') {
  3846. const glob = picomatch(matcher, options);
  3847. return (string) => matcher === string || glob(string);
  3848. }
  3849. if (matcher instanceof RegExp) {
  3850. return (string) => matcher.test(string);
  3851. }
  3852. return (string) => false;
  3853. };
  3854. /**
  3855. * @param {Array<Function>} patterns
  3856. * @param {Array<Function>} negPatterns
  3857. * @param {String|Array} args
  3858. * @param {Boolean} returnIndex
  3859. * @returns {boolean|number}
  3860. */
  3861. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  3862. const isList = Array.isArray(args);
  3863. const _path = isList ? args[0] : args;
  3864. if (!isList && typeof _path !== 'string') {
  3865. throw new TypeError('anymatch: second argument must be a string: got ' +
  3866. Object.prototype.toString.call(_path))
  3867. }
  3868. const path = normalizePath(_path, false);
  3869. for (let index = 0; index < negPatterns.length; index++) {
  3870. const nglob = negPatterns[index];
  3871. if (nglob(path)) {
  3872. return returnIndex ? -1 : false;
  3873. }
  3874. }
  3875. const applied = isList && [path].concat(args.slice(1));
  3876. for (let index = 0; index < patterns.length; index++) {
  3877. const pattern = patterns[index];
  3878. if (isList ? pattern(...applied) : pattern(path)) {
  3879. return returnIndex ? index : true;
  3880. }
  3881. }
  3882. return returnIndex ? -1 : false;
  3883. };
  3884. /**
  3885. * @param {AnymatchMatcher} matchers
  3886. * @param {Array|string} testString
  3887. * @param {object} options
  3888. * @returns {boolean|number|Function}
  3889. */
  3890. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  3891. if (matchers == null) {
  3892. throw new TypeError('anymatch: specify first argument');
  3893. }
  3894. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  3895. const returnIndex = opts.returnIndex || false;
  3896. // Early cache for matchers.
  3897. const mtchers = arrify(matchers);
  3898. const negatedGlobs = mtchers
  3899. .filter(item => typeof item === 'string' && item.charAt(0) === BANG)
  3900. .map(item => item.slice(1))
  3901. .map(item => picomatch(item, opts));
  3902. const patterns = mtchers
  3903. .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG))
  3904. .map(matcher => createPattern(matcher, opts));
  3905. if (testString == null) {
  3906. return (testString, ri = false) => {
  3907. const returnIndex = typeof ri === 'boolean' ? ri : false;
  3908. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  3909. }
  3910. }
  3911. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  3912. };
  3913. anymatch$1.default = anymatch$1;
  3914. anymatch.exports = anymatch$1;
  3915. return anymatch.exports;
  3916. }
  3917. /*!
  3918. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  3919. *
  3920. * Copyright (c) 2014-2016, Jon Schlinkert.
  3921. * Licensed under the MIT License.
  3922. */
  3923. var isExtglob;
  3924. var hasRequiredIsExtglob;
  3925. function requireIsExtglob () {
  3926. if (hasRequiredIsExtglob) return isExtglob;
  3927. hasRequiredIsExtglob = 1;
  3928. isExtglob = function isExtglob(str) {
  3929. if (typeof str !== 'string' || str === '') {
  3930. return false;
  3931. }
  3932. var match;
  3933. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  3934. if (match[2]) return true;
  3935. str = str.slice(match.index + match[0].length);
  3936. }
  3937. return false;
  3938. };
  3939. return isExtglob;
  3940. }
  3941. /*!
  3942. * is-glob <https://github.com/jonschlinkert/is-glob>
  3943. *
  3944. * Copyright (c) 2014-2017, Jon Schlinkert.
  3945. * Released under the MIT License.
  3946. */
  3947. var isGlob;
  3948. var hasRequiredIsGlob;
  3949. function requireIsGlob () {
  3950. if (hasRequiredIsGlob) return isGlob;
  3951. hasRequiredIsGlob = 1;
  3952. var isExtglob = /*@__PURE__*/ requireIsExtglob();
  3953. var chars = { '{': '}', '(': ')', '[': ']'};
  3954. var strictCheck = function(str) {
  3955. if (str[0] === '!') {
  3956. return true;
  3957. }
  3958. var index = 0;
  3959. var pipeIndex = -2;
  3960. var closeSquareIndex = -2;
  3961. var closeCurlyIndex = -2;
  3962. var closeParenIndex = -2;
  3963. var backSlashIndex = -2;
  3964. while (index < str.length) {
  3965. if (str[index] === '*') {
  3966. return true;
  3967. }
  3968. if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
  3969. return true;
  3970. }
  3971. if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
  3972. if (closeSquareIndex < index) {
  3973. closeSquareIndex = str.indexOf(']', index);
  3974. }
  3975. if (closeSquareIndex > index) {
  3976. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  3977. return true;
  3978. }
  3979. backSlashIndex = str.indexOf('\\', index);
  3980. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  3981. return true;
  3982. }
  3983. }
  3984. }
  3985. if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
  3986. closeCurlyIndex = str.indexOf('}', index);
  3987. if (closeCurlyIndex > index) {
  3988. backSlashIndex = str.indexOf('\\', index);
  3989. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
  3990. return true;
  3991. }
  3992. }
  3993. }
  3994. if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
  3995. closeParenIndex = str.indexOf(')', index);
  3996. if (closeParenIndex > index) {
  3997. backSlashIndex = str.indexOf('\\', index);
  3998. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  3999. return true;
  4000. }
  4001. }
  4002. }
  4003. if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
  4004. if (pipeIndex < index) {
  4005. pipeIndex = str.indexOf('|', index);
  4006. }
  4007. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
  4008. closeParenIndex = str.indexOf(')', pipeIndex);
  4009. if (closeParenIndex > pipeIndex) {
  4010. backSlashIndex = str.indexOf('\\', pipeIndex);
  4011. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  4012. return true;
  4013. }
  4014. }
  4015. }
  4016. }
  4017. if (str[index] === '\\') {
  4018. var open = str[index + 1];
  4019. index += 2;
  4020. var close = chars[open];
  4021. if (close) {
  4022. var n = str.indexOf(close, index);
  4023. if (n !== -1) {
  4024. index = n + 1;
  4025. }
  4026. }
  4027. if (str[index] === '!') {
  4028. return true;
  4029. }
  4030. } else {
  4031. index++;
  4032. }
  4033. }
  4034. return false;
  4035. };
  4036. var relaxedCheck = function(str) {
  4037. if (str[0] === '!') {
  4038. return true;
  4039. }
  4040. var index = 0;
  4041. while (index < str.length) {
  4042. if (/[*?{}()[\]]/.test(str[index])) {
  4043. return true;
  4044. }
  4045. if (str[index] === '\\') {
  4046. var open = str[index + 1];
  4047. index += 2;
  4048. var close = chars[open];
  4049. if (close) {
  4050. var n = str.indexOf(close, index);
  4051. if (n !== -1) {
  4052. index = n + 1;
  4053. }
  4054. }
  4055. if (str[index] === '!') {
  4056. return true;
  4057. }
  4058. } else {
  4059. index++;
  4060. }
  4061. }
  4062. return false;
  4063. };
  4064. isGlob = function isGlob(str, options) {
  4065. if (typeof str !== 'string' || str === '') {
  4066. return false;
  4067. }
  4068. if (isExtglob(str)) {
  4069. return true;
  4070. }
  4071. var check = strictCheck;
  4072. // optionally relax check
  4073. if (options && options.strict === false) {
  4074. check = relaxedCheck;
  4075. }
  4076. return check(str);
  4077. };
  4078. return isGlob;
  4079. }
  4080. var globParent;
  4081. var hasRequiredGlobParent;
  4082. function requireGlobParent () {
  4083. if (hasRequiredGlobParent) return globParent;
  4084. hasRequiredGlobParent = 1;
  4085. var isGlob = /*@__PURE__*/ requireIsGlob();
  4086. var pathPosixDirname = require$$0$1.posix.dirname;
  4087. var isWin32 = require$$2$1.platform() === 'win32';
  4088. var slash = '/';
  4089. var backslash = /\\/g;
  4090. var enclosure = /[\{\[].*[\}\]]$/;
  4091. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  4092. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  4093. /**
  4094. * @param {string} str
  4095. * @param {Object} opts
  4096. * @param {boolean} [opts.flipBackslashes=true]
  4097. * @returns {string}
  4098. */
  4099. globParent = function globParent(str, opts) {
  4100. var options = Object.assign({ flipBackslashes: true }, opts);
  4101. // flip windows path separators
  4102. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  4103. str = str.replace(backslash, slash);
  4104. }
  4105. // special case for strings ending in enclosure containing path separator
  4106. if (enclosure.test(str)) {
  4107. str += slash;
  4108. }
  4109. // preserves full path in case of trailing path separator
  4110. str += 'a';
  4111. // remove path parts that are globby
  4112. do {
  4113. str = pathPosixDirname(str);
  4114. } while (isGlob(str) || globby.test(str));
  4115. // remove escape chars and return result
  4116. return str.replace(escaped, '$1');
  4117. };
  4118. return globParent;
  4119. }
  4120. var utils = {};
  4121. var hasRequiredUtils;
  4122. function requireUtils () {
  4123. if (hasRequiredUtils) return utils;
  4124. hasRequiredUtils = 1;
  4125. (function (exports) {
  4126. exports.isInteger = num => {
  4127. if (typeof num === 'number') {
  4128. return Number.isInteger(num);
  4129. }
  4130. if (typeof num === 'string' && num.trim() !== '') {
  4131. return Number.isInteger(Number(num));
  4132. }
  4133. return false;
  4134. };
  4135. /**
  4136. * Find a node of the given type
  4137. */
  4138. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  4139. /**
  4140. * Find a node of the given type
  4141. */
  4142. exports.exceedsLimit = (min, max, step = 1, limit) => {
  4143. if (limit === false) return false;
  4144. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  4145. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  4146. };
  4147. /**
  4148. * Escape the given node with '\\' before node.value
  4149. */
  4150. exports.escapeNode = (block, n = 0, type) => {
  4151. const node = block.nodes[n];
  4152. if (!node) return;
  4153. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  4154. if (node.escaped !== true) {
  4155. node.value = '\\' + node.value;
  4156. node.escaped = true;
  4157. }
  4158. }
  4159. };
  4160. /**
  4161. * Returns true if the given brace node should be enclosed in literal braces
  4162. */
  4163. exports.encloseBrace = node => {
  4164. if (node.type !== 'brace') return false;
  4165. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  4166. node.invalid = true;
  4167. return true;
  4168. }
  4169. return false;
  4170. };
  4171. /**
  4172. * Returns true if a brace node is invalid.
  4173. */
  4174. exports.isInvalidBrace = block => {
  4175. if (block.type !== 'brace') return false;
  4176. if (block.invalid === true || block.dollar) return true;
  4177. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  4178. block.invalid = true;
  4179. return true;
  4180. }
  4181. if (block.open !== true || block.close !== true) {
  4182. block.invalid = true;
  4183. return true;
  4184. }
  4185. return false;
  4186. };
  4187. /**
  4188. * Returns true if a node is an open or close node
  4189. */
  4190. exports.isOpenOrClose = node => {
  4191. if (node.type === 'open' || node.type === 'close') {
  4192. return true;
  4193. }
  4194. return node.open === true || node.close === true;
  4195. };
  4196. /**
  4197. * Reduce an array of text nodes.
  4198. */
  4199. exports.reduce = nodes => nodes.reduce((acc, node) => {
  4200. if (node.type === 'text') acc.push(node.value);
  4201. if (node.type === 'range') node.type = 'text';
  4202. return acc;
  4203. }, []);
  4204. /**
  4205. * Flatten an array
  4206. */
  4207. exports.flatten = (...args) => {
  4208. const result = [];
  4209. const flat = arr => {
  4210. for (let i = 0; i < arr.length; i++) {
  4211. const ele = arr[i];
  4212. if (Array.isArray(ele)) {
  4213. flat(ele);
  4214. continue;
  4215. }
  4216. if (ele !== undefined) {
  4217. result.push(ele);
  4218. }
  4219. }
  4220. return result;
  4221. };
  4222. flat(args);
  4223. return result;
  4224. };
  4225. } (utils));
  4226. return utils;
  4227. }
  4228. var stringify;
  4229. var hasRequiredStringify;
  4230. function requireStringify () {
  4231. if (hasRequiredStringify) return stringify;
  4232. hasRequiredStringify = 1;
  4233. const utils = /*@__PURE__*/ requireUtils();
  4234. stringify = (ast, options = {}) => {
  4235. const stringify = (node, parent = {}) => {
  4236. const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
  4237. const invalidNode = node.invalid === true && options.escapeInvalid === true;
  4238. let output = '';
  4239. if (node.value) {
  4240. if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
  4241. return '\\' + node.value;
  4242. }
  4243. return node.value;
  4244. }
  4245. if (node.value) {
  4246. return node.value;
  4247. }
  4248. if (node.nodes) {
  4249. for (const child of node.nodes) {
  4250. output += stringify(child);
  4251. }
  4252. }
  4253. return output;
  4254. };
  4255. return stringify(ast);
  4256. };
  4257. return stringify;
  4258. }
  4259. /*!
  4260. * is-number <https://github.com/jonschlinkert/is-number>
  4261. *
  4262. * Copyright (c) 2014-present, Jon Schlinkert.
  4263. * Released under the MIT License.
  4264. */
  4265. var isNumber;
  4266. var hasRequiredIsNumber;
  4267. function requireIsNumber () {
  4268. if (hasRequiredIsNumber) return isNumber;
  4269. hasRequiredIsNumber = 1;
  4270. isNumber = function(num) {
  4271. if (typeof num === 'number') {
  4272. return num - num === 0;
  4273. }
  4274. if (typeof num === 'string' && num.trim() !== '') {
  4275. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  4276. }
  4277. return false;
  4278. };
  4279. return isNumber;
  4280. }
  4281. /*!
  4282. * to-regex-range <https://github.com/micromatch/to-regex-range>
  4283. *
  4284. * Copyright (c) 2015-present, Jon Schlinkert.
  4285. * Released under the MIT License.
  4286. */
  4287. var toRegexRange_1;
  4288. var hasRequiredToRegexRange;
  4289. function requireToRegexRange () {
  4290. if (hasRequiredToRegexRange) return toRegexRange_1;
  4291. hasRequiredToRegexRange = 1;
  4292. const isNumber = /*@__PURE__*/ requireIsNumber();
  4293. const toRegexRange = (min, max, options) => {
  4294. if (isNumber(min) === false) {
  4295. throw new TypeError('toRegexRange: expected the first argument to be a number');
  4296. }
  4297. if (max === void 0 || min === max) {
  4298. return String(min);
  4299. }
  4300. if (isNumber(max) === false) {
  4301. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  4302. }
  4303. let opts = { relaxZeros: true, ...options };
  4304. if (typeof opts.strictZeros === 'boolean') {
  4305. opts.relaxZeros = opts.strictZeros === false;
  4306. }
  4307. let relax = String(opts.relaxZeros);
  4308. let shorthand = String(opts.shorthand);
  4309. let capture = String(opts.capture);
  4310. let wrap = String(opts.wrap);
  4311. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  4312. if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
  4313. return toRegexRange.cache[cacheKey].result;
  4314. }
  4315. let a = Math.min(min, max);
  4316. let b = Math.max(min, max);
  4317. if (Math.abs(a - b) === 1) {
  4318. let result = min + '|' + max;
  4319. if (opts.capture) {
  4320. return `(${result})`;
  4321. }
  4322. if (opts.wrap === false) {
  4323. return result;
  4324. }
  4325. return `(?:${result})`;
  4326. }
  4327. let isPadded = hasPadding(min) || hasPadding(max);
  4328. let state = { min, max, a, b };
  4329. let positives = [];
  4330. let negatives = [];
  4331. if (isPadded) {
  4332. state.isPadded = isPadded;
  4333. state.maxLen = String(state.max).length;
  4334. }
  4335. if (a < 0) {
  4336. let newMin = b < 0 ? Math.abs(b) : 1;
  4337. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  4338. a = state.a = 0;
  4339. }
  4340. if (b >= 0) {
  4341. positives = splitToPatterns(a, b, state, opts);
  4342. }
  4343. state.negatives = negatives;
  4344. state.positives = positives;
  4345. state.result = collatePatterns(negatives, positives);
  4346. if (opts.capture === true) {
  4347. state.result = `(${state.result})`;
  4348. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  4349. state.result = `(?:${state.result})`;
  4350. }
  4351. toRegexRange.cache[cacheKey] = state;
  4352. return state.result;
  4353. };
  4354. function collatePatterns(neg, pos, options) {
  4355. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  4356. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  4357. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  4358. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  4359. return subpatterns.join('|');
  4360. }
  4361. function splitToRanges(min, max) {
  4362. let nines = 1;
  4363. let zeros = 1;
  4364. let stop = countNines(min, nines);
  4365. let stops = new Set([max]);
  4366. while (min <= stop && stop <= max) {
  4367. stops.add(stop);
  4368. nines += 1;
  4369. stop = countNines(min, nines);
  4370. }
  4371. stop = countZeros(max + 1, zeros) - 1;
  4372. while (min < stop && stop <= max) {
  4373. stops.add(stop);
  4374. zeros += 1;
  4375. stop = countZeros(max + 1, zeros) - 1;
  4376. }
  4377. stops = [...stops];
  4378. stops.sort(compare);
  4379. return stops;
  4380. }
  4381. /**
  4382. * Convert a range to a regex pattern
  4383. * @param {Number} `start`
  4384. * @param {Number} `stop`
  4385. * @return {String}
  4386. */
  4387. function rangeToPattern(start, stop, options) {
  4388. if (start === stop) {
  4389. return { pattern: start, count: [], digits: 0 };
  4390. }
  4391. let zipped = zip(start, stop);
  4392. let digits = zipped.length;
  4393. let pattern = '';
  4394. let count = 0;
  4395. for (let i = 0; i < digits; i++) {
  4396. let [startDigit, stopDigit] = zipped[i];
  4397. if (startDigit === stopDigit) {
  4398. pattern += startDigit;
  4399. } else if (startDigit !== '0' || stopDigit !== '9') {
  4400. pattern += toCharacterClass(startDigit, stopDigit);
  4401. } else {
  4402. count++;
  4403. }
  4404. }
  4405. if (count) {
  4406. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  4407. }
  4408. return { pattern, count: [count], digits };
  4409. }
  4410. function splitToPatterns(min, max, tok, options) {
  4411. let ranges = splitToRanges(min, max);
  4412. let tokens = [];
  4413. let start = min;
  4414. let prev;
  4415. for (let i = 0; i < ranges.length; i++) {
  4416. let max = ranges[i];
  4417. let obj = rangeToPattern(String(start), String(max), options);
  4418. let zeros = '';
  4419. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  4420. if (prev.count.length > 1) {
  4421. prev.count.pop();
  4422. }
  4423. prev.count.push(obj.count[0]);
  4424. prev.string = prev.pattern + toQuantifier(prev.count);
  4425. start = max + 1;
  4426. continue;
  4427. }
  4428. if (tok.isPadded) {
  4429. zeros = padZeros(max, tok, options);
  4430. }
  4431. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  4432. tokens.push(obj);
  4433. start = max + 1;
  4434. prev = obj;
  4435. }
  4436. return tokens;
  4437. }
  4438. function filterPatterns(arr, comparison, prefix, intersection, options) {
  4439. let result = [];
  4440. for (let ele of arr) {
  4441. let { string } = ele;
  4442. // only push if _both_ are negative...
  4443. if (!intersection && !contains(comparison, 'string', string)) {
  4444. result.push(prefix + string);
  4445. }
  4446. // or _both_ are positive
  4447. if (intersection && contains(comparison, 'string', string)) {
  4448. result.push(prefix + string);
  4449. }
  4450. }
  4451. return result;
  4452. }
  4453. /**
  4454. * Zip strings
  4455. */
  4456. function zip(a, b) {
  4457. let arr = [];
  4458. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  4459. return arr;
  4460. }
  4461. function compare(a, b) {
  4462. return a > b ? 1 : b > a ? -1 : 0;
  4463. }
  4464. function contains(arr, key, val) {
  4465. return arr.some(ele => ele[key] === val);
  4466. }
  4467. function countNines(min, len) {
  4468. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  4469. }
  4470. function countZeros(integer, zeros) {
  4471. return integer - (integer % Math.pow(10, zeros));
  4472. }
  4473. function toQuantifier(digits) {
  4474. let [start = 0, stop = ''] = digits;
  4475. if (stop || start > 1) {
  4476. return `{${start + (stop ? ',' + stop : '')}}`;
  4477. }
  4478. return '';
  4479. }
  4480. function toCharacterClass(a, b, options) {
  4481. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  4482. }
  4483. function hasPadding(str) {
  4484. return /^-?(0+)\d/.test(str);
  4485. }
  4486. function padZeros(value, tok, options) {
  4487. if (!tok.isPadded) {
  4488. return value;
  4489. }
  4490. let diff = Math.abs(tok.maxLen - String(value).length);
  4491. let relax = options.relaxZeros !== false;
  4492. switch (diff) {
  4493. case 0:
  4494. return '';
  4495. case 1:
  4496. return relax ? '0?' : '0';
  4497. case 2:
  4498. return relax ? '0{0,2}' : '00';
  4499. default: {
  4500. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  4501. }
  4502. }
  4503. }
  4504. /**
  4505. * Cache
  4506. */
  4507. toRegexRange.cache = {};
  4508. toRegexRange.clearCache = () => (toRegexRange.cache = {});
  4509. /**
  4510. * Expose `toRegexRange`
  4511. */
  4512. toRegexRange_1 = toRegexRange;
  4513. return toRegexRange_1;
  4514. }
  4515. /*!
  4516. * fill-range <https://github.com/jonschlinkert/fill-range>
  4517. *
  4518. * Copyright (c) 2014-present, Jon Schlinkert.
  4519. * Licensed under the MIT License.
  4520. */
  4521. var fillRange;
  4522. var hasRequiredFillRange;
  4523. function requireFillRange () {
  4524. if (hasRequiredFillRange) return fillRange;
  4525. hasRequiredFillRange = 1;
  4526. const util = require$$2;
  4527. const toRegexRange = /*@__PURE__*/ requireToRegexRange();
  4528. const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  4529. const transform = toNumber => {
  4530. return value => toNumber === true ? Number(value) : String(value);
  4531. };
  4532. const isValidValue = value => {
  4533. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  4534. };
  4535. const isNumber = num => Number.isInteger(+num);
  4536. const zeros = input => {
  4537. let value = `${input}`;
  4538. let index = -1;
  4539. if (value[0] === '-') value = value.slice(1);
  4540. if (value === '0') return false;
  4541. while (value[++index] === '0');
  4542. return index > 0;
  4543. };
  4544. const stringify = (start, end, options) => {
  4545. if (typeof start === 'string' || typeof end === 'string') {
  4546. return true;
  4547. }
  4548. return options.stringify === true;
  4549. };
  4550. const pad = (input, maxLength, toNumber) => {
  4551. if (maxLength > 0) {
  4552. let dash = input[0] === '-' ? '-' : '';
  4553. if (dash) input = input.slice(1);
  4554. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  4555. }
  4556. if (toNumber === false) {
  4557. return String(input);
  4558. }
  4559. return input;
  4560. };
  4561. const toMaxLen = (input, maxLength) => {
  4562. let negative = input[0] === '-' ? '-' : '';
  4563. if (negative) {
  4564. input = input.slice(1);
  4565. maxLength--;
  4566. }
  4567. while (input.length < maxLength) input = '0' + input;
  4568. return negative ? ('-' + input) : input;
  4569. };
  4570. const toSequence = (parts, options, maxLen) => {
  4571. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  4572. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  4573. let prefix = options.capture ? '' : '?:';
  4574. let positives = '';
  4575. let negatives = '';
  4576. let result;
  4577. if (parts.positives.length) {
  4578. positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|');
  4579. }
  4580. if (parts.negatives.length) {
  4581. negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`;
  4582. }
  4583. if (positives && negatives) {
  4584. result = `${positives}|${negatives}`;
  4585. } else {
  4586. result = positives || negatives;
  4587. }
  4588. if (options.wrap) {
  4589. return `(${prefix}${result})`;
  4590. }
  4591. return result;
  4592. };
  4593. const toRange = (a, b, isNumbers, options) => {
  4594. if (isNumbers) {
  4595. return toRegexRange(a, b, { wrap: false, ...options });
  4596. }
  4597. let start = String.fromCharCode(a);
  4598. if (a === b) return start;
  4599. let stop = String.fromCharCode(b);
  4600. return `[${start}-${stop}]`;
  4601. };
  4602. const toRegex = (start, end, options) => {
  4603. if (Array.isArray(start)) {
  4604. let wrap = options.wrap === true;
  4605. let prefix = options.capture ? '' : '?:';
  4606. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  4607. }
  4608. return toRegexRange(start, end, options);
  4609. };
  4610. const rangeError = (...args) => {
  4611. return new RangeError('Invalid range arguments: ' + util.inspect(...args));
  4612. };
  4613. const invalidRange = (start, end, options) => {
  4614. if (options.strictRanges === true) throw rangeError([start, end]);
  4615. return [];
  4616. };
  4617. const invalidStep = (step, options) => {
  4618. if (options.strictRanges === true) {
  4619. throw new TypeError(`Expected step "${step}" to be a number`);
  4620. }
  4621. return [];
  4622. };
  4623. const fillNumbers = (start, end, step = 1, options = {}) => {
  4624. let a = Number(start);
  4625. let b = Number(end);
  4626. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  4627. if (options.strictRanges === true) throw rangeError([start, end]);
  4628. return [];
  4629. }
  4630. // fix negative zero
  4631. if (a === 0) a = 0;
  4632. if (b === 0) b = 0;
  4633. let descending = a > b;
  4634. let startString = String(start);
  4635. let endString = String(end);
  4636. let stepString = String(step);
  4637. step = Math.max(Math.abs(step), 1);
  4638. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  4639. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  4640. let toNumber = padded === false && stringify(start, end, options) === false;
  4641. let format = options.transform || transform(toNumber);
  4642. if (options.toRegex && step === 1) {
  4643. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  4644. }
  4645. let parts = { negatives: [], positives: [] };
  4646. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  4647. let range = [];
  4648. let index = 0;
  4649. while (descending ? a >= b : a <= b) {
  4650. if (options.toRegex === true && step > 1) {
  4651. push(a);
  4652. } else {
  4653. range.push(pad(format(a, index), maxLen, toNumber));
  4654. }
  4655. a = descending ? a - step : a + step;
  4656. index++;
  4657. }
  4658. if (options.toRegex === true) {
  4659. return step > 1
  4660. ? toSequence(parts, options, maxLen)
  4661. : toRegex(range, null, { wrap: false, ...options });
  4662. }
  4663. return range;
  4664. };
  4665. const fillLetters = (start, end, step = 1, options = {}) => {
  4666. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  4667. return invalidRange(start, end, options);
  4668. }
  4669. let format = options.transform || (val => String.fromCharCode(val));
  4670. let a = `${start}`.charCodeAt(0);
  4671. let b = `${end}`.charCodeAt(0);
  4672. let descending = a > b;
  4673. let min = Math.min(a, b);
  4674. let max = Math.max(a, b);
  4675. if (options.toRegex && step === 1) {
  4676. return toRange(min, max, false, options);
  4677. }
  4678. let range = [];
  4679. let index = 0;
  4680. while (descending ? a >= b : a <= b) {
  4681. range.push(format(a, index));
  4682. a = descending ? a - step : a + step;
  4683. index++;
  4684. }
  4685. if (options.toRegex === true) {
  4686. return toRegex(range, null, { wrap: false, options });
  4687. }
  4688. return range;
  4689. };
  4690. const fill = (start, end, step, options = {}) => {
  4691. if (end == null && isValidValue(start)) {
  4692. return [start];
  4693. }
  4694. if (!isValidValue(start) || !isValidValue(end)) {
  4695. return invalidRange(start, end, options);
  4696. }
  4697. if (typeof step === 'function') {
  4698. return fill(start, end, 1, { transform: step });
  4699. }
  4700. if (isObject(step)) {
  4701. return fill(start, end, 0, step);
  4702. }
  4703. let opts = { ...options };
  4704. if (opts.capture === true) opts.wrap = true;
  4705. step = step || opts.step || 1;
  4706. if (!isNumber(step)) {
  4707. if (step != null && !isObject(step)) return invalidStep(step, opts);
  4708. return fill(start, end, 1, step);
  4709. }
  4710. if (isNumber(start) && isNumber(end)) {
  4711. return fillNumbers(start, end, step, opts);
  4712. }
  4713. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  4714. };
  4715. fillRange = fill;
  4716. return fillRange;
  4717. }
  4718. var compile_1;
  4719. var hasRequiredCompile;
  4720. function requireCompile () {
  4721. if (hasRequiredCompile) return compile_1;
  4722. hasRequiredCompile = 1;
  4723. const fill = /*@__PURE__*/ requireFillRange();
  4724. const utils = /*@__PURE__*/ requireUtils();
  4725. const compile = (ast, options = {}) => {
  4726. const walk = (node, parent = {}) => {
  4727. const invalidBlock = utils.isInvalidBrace(parent);
  4728. const invalidNode = node.invalid === true && options.escapeInvalid === true;
  4729. const invalid = invalidBlock === true || invalidNode === true;
  4730. const prefix = options.escapeInvalid === true ? '\\' : '';
  4731. let output = '';
  4732. if (node.isOpen === true) {
  4733. return prefix + node.value;
  4734. }
  4735. if (node.isClose === true) {
  4736. console.log('node.isClose', prefix, node.value);
  4737. return prefix + node.value;
  4738. }
  4739. if (node.type === 'open') {
  4740. return invalid ? prefix + node.value : '(';
  4741. }
  4742. if (node.type === 'close') {
  4743. return invalid ? prefix + node.value : ')';
  4744. }
  4745. if (node.type === 'comma') {
  4746. return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
  4747. }
  4748. if (node.value) {
  4749. return node.value;
  4750. }
  4751. if (node.nodes && node.ranges > 0) {
  4752. const args = utils.reduce(node.nodes);
  4753. const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true });
  4754. if (range.length !== 0) {
  4755. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  4756. }
  4757. }
  4758. if (node.nodes) {
  4759. for (const child of node.nodes) {
  4760. output += walk(child, node);
  4761. }
  4762. }
  4763. return output;
  4764. };
  4765. return walk(ast);
  4766. };
  4767. compile_1 = compile;
  4768. return compile_1;
  4769. }
  4770. var expand_1;
  4771. var hasRequiredExpand;
  4772. function requireExpand () {
  4773. if (hasRequiredExpand) return expand_1;
  4774. hasRequiredExpand = 1;
  4775. const fill = /*@__PURE__*/ requireFillRange();
  4776. const stringify = /*@__PURE__*/ requireStringify();
  4777. const utils = /*@__PURE__*/ requireUtils();
  4778. const append = (queue = '', stash = '', enclose = false) => {
  4779. const result = [];
  4780. queue = [].concat(queue);
  4781. stash = [].concat(stash);
  4782. if (!stash.length) return queue;
  4783. if (!queue.length) {
  4784. return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
  4785. }
  4786. for (const item of queue) {
  4787. if (Array.isArray(item)) {
  4788. for (const value of item) {
  4789. result.push(append(value, stash, enclose));
  4790. }
  4791. } else {
  4792. for (let ele of stash) {
  4793. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  4794. result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
  4795. }
  4796. }
  4797. }
  4798. return utils.flatten(result);
  4799. };
  4800. const expand = (ast, options = {}) => {
  4801. const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit;
  4802. const walk = (node, parent = {}) => {
  4803. node.queue = [];
  4804. let p = parent;
  4805. let q = parent.queue;
  4806. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  4807. p = p.parent;
  4808. q = p.queue;
  4809. }
  4810. if (node.invalid || node.dollar) {
  4811. q.push(append(q.pop(), stringify(node, options)));
  4812. return;
  4813. }
  4814. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  4815. q.push(append(q.pop(), ['{}']));
  4816. return;
  4817. }
  4818. if (node.nodes && node.ranges > 0) {
  4819. const args = utils.reduce(node.nodes);
  4820. if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
  4821. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  4822. }
  4823. let range = fill(...args, options);
  4824. if (range.length === 0) {
  4825. range = stringify(node, options);
  4826. }
  4827. q.push(append(q.pop(), range));
  4828. node.nodes = [];
  4829. return;
  4830. }
  4831. const enclose = utils.encloseBrace(node);
  4832. let queue = node.queue;
  4833. let block = node;
  4834. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  4835. block = block.parent;
  4836. queue = block.queue;
  4837. }
  4838. for (let i = 0; i < node.nodes.length; i++) {
  4839. const child = node.nodes[i];
  4840. if (child.type === 'comma' && node.type === 'brace') {
  4841. if (i === 1) queue.push('');
  4842. queue.push('');
  4843. continue;
  4844. }
  4845. if (child.type === 'close') {
  4846. q.push(append(q.pop(), queue, enclose));
  4847. continue;
  4848. }
  4849. if (child.value && child.type !== 'open') {
  4850. queue.push(append(queue.pop(), child.value));
  4851. continue;
  4852. }
  4853. if (child.nodes) {
  4854. walk(child, node);
  4855. }
  4856. }
  4857. return queue;
  4858. };
  4859. return utils.flatten(walk(ast));
  4860. };
  4861. expand_1 = expand;
  4862. return expand_1;
  4863. }
  4864. var constants$1;
  4865. var hasRequiredConstants$1;
  4866. function requireConstants$1 () {
  4867. if (hasRequiredConstants$1) return constants$1;
  4868. hasRequiredConstants$1 = 1;
  4869. constants$1 = {
  4870. MAX_LENGTH: 10000,
  4871. // Digits
  4872. CHAR_0: '0', /* 0 */
  4873. CHAR_9: '9', /* 9 */
  4874. // Alphabet chars.
  4875. CHAR_UPPERCASE_A: 'A', /* A */
  4876. CHAR_LOWERCASE_A: 'a', /* a */
  4877. CHAR_UPPERCASE_Z: 'Z', /* Z */
  4878. CHAR_LOWERCASE_Z: 'z', /* z */
  4879. CHAR_LEFT_PARENTHESES: '(', /* ( */
  4880. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  4881. CHAR_ASTERISK: '*', /* * */
  4882. // Non-alphabetic chars.
  4883. CHAR_AMPERSAND: '&', /* & */
  4884. CHAR_AT: '@', /* @ */
  4885. CHAR_BACKSLASH: '\\', /* \ */
  4886. CHAR_BACKTICK: '`', /* ` */
  4887. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  4888. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  4889. CHAR_COLON: ':', /* : */
  4890. CHAR_COMMA: ',', /* , */
  4891. CHAR_DOLLAR: '$', /* . */
  4892. CHAR_DOT: '.', /* . */
  4893. CHAR_DOUBLE_QUOTE: '"', /* " */
  4894. CHAR_EQUAL: '=', /* = */
  4895. CHAR_EXCLAMATION_MARK: '!', /* ! */
  4896. CHAR_FORM_FEED: '\f', /* \f */
  4897. CHAR_FORWARD_SLASH: '/', /* / */
  4898. CHAR_HASH: '#', /* # */
  4899. CHAR_HYPHEN_MINUS: '-', /* - */
  4900. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  4901. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  4902. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  4903. CHAR_LINE_FEED: '\n', /* \n */
  4904. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  4905. CHAR_PERCENT: '%', /* % */
  4906. CHAR_PLUS: '+', /* + */
  4907. CHAR_QUESTION_MARK: '?', /* ? */
  4908. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  4909. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  4910. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  4911. CHAR_SEMICOLON: ';', /* ; */
  4912. CHAR_SINGLE_QUOTE: '\'', /* ' */
  4913. CHAR_SPACE: ' ', /* */
  4914. CHAR_TAB: '\t', /* \t */
  4915. CHAR_UNDERSCORE: '_', /* _ */
  4916. CHAR_VERTICAL_LINE: '|', /* | */
  4917. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  4918. };
  4919. return constants$1;
  4920. }
  4921. var parse_1;
  4922. var hasRequiredParse;
  4923. function requireParse () {
  4924. if (hasRequiredParse) return parse_1;
  4925. hasRequiredParse = 1;
  4926. const stringify = /*@__PURE__*/ requireStringify();
  4927. /**
  4928. * Constants
  4929. */
  4930. const {
  4931. MAX_LENGTH,
  4932. CHAR_BACKSLASH, /* \ */
  4933. CHAR_BACKTICK, /* ` */
  4934. CHAR_COMMA, /* , */
  4935. CHAR_DOT, /* . */
  4936. CHAR_LEFT_PARENTHESES, /* ( */
  4937. CHAR_RIGHT_PARENTHESES, /* ) */
  4938. CHAR_LEFT_CURLY_BRACE, /* { */
  4939. CHAR_RIGHT_CURLY_BRACE, /* } */
  4940. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  4941. CHAR_RIGHT_SQUARE_BRACKET, /* ] */
  4942. CHAR_DOUBLE_QUOTE, /* " */
  4943. CHAR_SINGLE_QUOTE, /* ' */
  4944. CHAR_NO_BREAK_SPACE,
  4945. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  4946. } = /*@__PURE__*/ requireConstants$1();
  4947. /**
  4948. * parse
  4949. */
  4950. const parse = (input, options = {}) => {
  4951. if (typeof input !== 'string') {
  4952. throw new TypeError('Expected a string');
  4953. }
  4954. const opts = options || {};
  4955. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  4956. if (input.length > max) {
  4957. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  4958. }
  4959. const ast = { type: 'root', input, nodes: [] };
  4960. const stack = [ast];
  4961. let block = ast;
  4962. let prev = ast;
  4963. let brackets = 0;
  4964. const length = input.length;
  4965. let index = 0;
  4966. let depth = 0;
  4967. let value;
  4968. /**
  4969. * Helpers
  4970. */
  4971. const advance = () => input[index++];
  4972. const push = node => {
  4973. if (node.type === 'text' && prev.type === 'dot') {
  4974. prev.type = 'text';
  4975. }
  4976. if (prev && prev.type === 'text' && node.type === 'text') {
  4977. prev.value += node.value;
  4978. return;
  4979. }
  4980. block.nodes.push(node);
  4981. node.parent = block;
  4982. node.prev = prev;
  4983. prev = node;
  4984. return node;
  4985. };
  4986. push({ type: 'bos' });
  4987. while (index < length) {
  4988. block = stack[stack.length - 1];
  4989. value = advance();
  4990. /**
  4991. * Invalid chars
  4992. */
  4993. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  4994. continue;
  4995. }
  4996. /**
  4997. * Escaped chars
  4998. */
  4999. if (value === CHAR_BACKSLASH) {
  5000. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  5001. continue;
  5002. }
  5003. /**
  5004. * Right square bracket (literal): ']'
  5005. */
  5006. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  5007. push({ type: 'text', value: '\\' + value });
  5008. continue;
  5009. }
  5010. /**
  5011. * Left square bracket: '['
  5012. */
  5013. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  5014. brackets++;
  5015. let next;
  5016. while (index < length && (next = advance())) {
  5017. value += next;
  5018. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  5019. brackets++;
  5020. continue;
  5021. }
  5022. if (next === CHAR_BACKSLASH) {
  5023. value += advance();
  5024. continue;
  5025. }
  5026. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  5027. brackets--;
  5028. if (brackets === 0) {
  5029. break;
  5030. }
  5031. }
  5032. }
  5033. push({ type: 'text', value });
  5034. continue;
  5035. }
  5036. /**
  5037. * Parentheses
  5038. */
  5039. if (value === CHAR_LEFT_PARENTHESES) {
  5040. block = push({ type: 'paren', nodes: [] });
  5041. stack.push(block);
  5042. push({ type: 'text', value });
  5043. continue;
  5044. }
  5045. if (value === CHAR_RIGHT_PARENTHESES) {
  5046. if (block.type !== 'paren') {
  5047. push({ type: 'text', value });
  5048. continue;
  5049. }
  5050. block = stack.pop();
  5051. push({ type: 'text', value });
  5052. block = stack[stack.length - 1];
  5053. continue;
  5054. }
  5055. /**
  5056. * Quotes: '|"|`
  5057. */
  5058. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  5059. const open = value;
  5060. let next;
  5061. if (options.keepQuotes !== true) {
  5062. value = '';
  5063. }
  5064. while (index < length && (next = advance())) {
  5065. if (next === CHAR_BACKSLASH) {
  5066. value += next + advance();
  5067. continue;
  5068. }
  5069. if (next === open) {
  5070. if (options.keepQuotes === true) value += next;
  5071. break;
  5072. }
  5073. value += next;
  5074. }
  5075. push({ type: 'text', value });
  5076. continue;
  5077. }
  5078. /**
  5079. * Left curly brace: '{'
  5080. */
  5081. if (value === CHAR_LEFT_CURLY_BRACE) {
  5082. depth++;
  5083. const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  5084. const brace = {
  5085. type: 'brace',
  5086. open: true,
  5087. close: false,
  5088. dollar,
  5089. depth,
  5090. commas: 0,
  5091. ranges: 0,
  5092. nodes: []
  5093. };
  5094. block = push(brace);
  5095. stack.push(block);
  5096. push({ type: 'open', value });
  5097. continue;
  5098. }
  5099. /**
  5100. * Right curly brace: '}'
  5101. */
  5102. if (value === CHAR_RIGHT_CURLY_BRACE) {
  5103. if (block.type !== 'brace') {
  5104. push({ type: 'text', value });
  5105. continue;
  5106. }
  5107. const type = 'close';
  5108. block = stack.pop();
  5109. block.close = true;
  5110. push({ type, value });
  5111. depth--;
  5112. block = stack[stack.length - 1];
  5113. continue;
  5114. }
  5115. /**
  5116. * Comma: ','
  5117. */
  5118. if (value === CHAR_COMMA && depth > 0) {
  5119. if (block.ranges > 0) {
  5120. block.ranges = 0;
  5121. const open = block.nodes.shift();
  5122. block.nodes = [open, { type: 'text', value: stringify(block) }];
  5123. }
  5124. push({ type: 'comma', value });
  5125. block.commas++;
  5126. continue;
  5127. }
  5128. /**
  5129. * Dot: '.'
  5130. */
  5131. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  5132. const siblings = block.nodes;
  5133. if (depth === 0 || siblings.length === 0) {
  5134. push({ type: 'text', value });
  5135. continue;
  5136. }
  5137. if (prev.type === 'dot') {
  5138. block.range = [];
  5139. prev.value += value;
  5140. prev.type = 'range';
  5141. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  5142. block.invalid = true;
  5143. block.ranges = 0;
  5144. prev.type = 'text';
  5145. continue;
  5146. }
  5147. block.ranges++;
  5148. block.args = [];
  5149. continue;
  5150. }
  5151. if (prev.type === 'range') {
  5152. siblings.pop();
  5153. const before = siblings[siblings.length - 1];
  5154. before.value += prev.value + value;
  5155. prev = before;
  5156. block.ranges--;
  5157. continue;
  5158. }
  5159. push({ type: 'dot', value });
  5160. continue;
  5161. }
  5162. /**
  5163. * Text
  5164. */
  5165. push({ type: 'text', value });
  5166. }
  5167. // Mark imbalanced braces and brackets as invalid
  5168. do {
  5169. block = stack.pop();
  5170. if (block.type !== 'root') {
  5171. block.nodes.forEach(node => {
  5172. if (!node.nodes) {
  5173. if (node.type === 'open') node.isOpen = true;
  5174. if (node.type === 'close') node.isClose = true;
  5175. if (!node.nodes) node.type = 'text';
  5176. node.invalid = true;
  5177. }
  5178. });
  5179. // get the location of the block on parent.nodes (block's siblings)
  5180. const parent = stack[stack.length - 1];
  5181. const index = parent.nodes.indexOf(block);
  5182. // replace the (invalid) block with it's nodes
  5183. parent.nodes.splice(index, 1, ...block.nodes);
  5184. }
  5185. } while (stack.length > 0);
  5186. push({ type: 'eos' });
  5187. return ast;
  5188. };
  5189. parse_1 = parse;
  5190. return parse_1;
  5191. }
  5192. var braces_1;
  5193. var hasRequiredBraces;
  5194. function requireBraces () {
  5195. if (hasRequiredBraces) return braces_1;
  5196. hasRequiredBraces = 1;
  5197. const stringify = /*@__PURE__*/ requireStringify();
  5198. const compile = /*@__PURE__*/ requireCompile();
  5199. const expand = /*@__PURE__*/ requireExpand();
  5200. const parse = /*@__PURE__*/ requireParse();
  5201. /**
  5202. * Expand the given pattern or create a regex-compatible string.
  5203. *
  5204. * ```js
  5205. * const braces = require('braces');
  5206. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  5207. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  5208. * ```
  5209. * @param {String} `str`
  5210. * @param {Object} `options`
  5211. * @return {String}
  5212. * @api public
  5213. */
  5214. const braces = (input, options = {}) => {
  5215. let output = [];
  5216. if (Array.isArray(input)) {
  5217. for (const pattern of input) {
  5218. const result = braces.create(pattern, options);
  5219. if (Array.isArray(result)) {
  5220. output.push(...result);
  5221. } else {
  5222. output.push(result);
  5223. }
  5224. }
  5225. } else {
  5226. output = [].concat(braces.create(input, options));
  5227. }
  5228. if (options && options.expand === true && options.nodupes === true) {
  5229. output = [...new Set(output)];
  5230. }
  5231. return output;
  5232. };
  5233. /**
  5234. * Parse the given `str` with the given `options`.
  5235. *
  5236. * ```js
  5237. * // braces.parse(pattern, [, options]);
  5238. * const ast = braces.parse('a/{b,c}/d');
  5239. * console.log(ast);
  5240. * ```
  5241. * @param {String} pattern Brace pattern to parse
  5242. * @param {Object} options
  5243. * @return {Object} Returns an AST
  5244. * @api public
  5245. */
  5246. braces.parse = (input, options = {}) => parse(input, options);
  5247. /**
  5248. * Creates a braces string from an AST, or an AST node.
  5249. *
  5250. * ```js
  5251. * const braces = require('braces');
  5252. * let ast = braces.parse('foo/{a,b}/bar');
  5253. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  5254. * ```
  5255. * @param {String} `input` Brace pattern or AST.
  5256. * @param {Object} `options`
  5257. * @return {Array} Returns an array of expanded values.
  5258. * @api public
  5259. */
  5260. braces.stringify = (input, options = {}) => {
  5261. if (typeof input === 'string') {
  5262. return stringify(braces.parse(input, options), options);
  5263. }
  5264. return stringify(input, options);
  5265. };
  5266. /**
  5267. * Compiles a brace pattern into a regex-compatible, optimized string.
  5268. * This method is called by the main [braces](#braces) function by default.
  5269. *
  5270. * ```js
  5271. * const braces = require('braces');
  5272. * console.log(braces.compile('a/{b,c}/d'));
  5273. * //=> ['a/(b|c)/d']
  5274. * ```
  5275. * @param {String} `input` Brace pattern or AST.
  5276. * @param {Object} `options`
  5277. * @return {Array} Returns an array of expanded values.
  5278. * @api public
  5279. */
  5280. braces.compile = (input, options = {}) => {
  5281. if (typeof input === 'string') {
  5282. input = braces.parse(input, options);
  5283. }
  5284. return compile(input, options);
  5285. };
  5286. /**
  5287. * Expands a brace pattern into an array. This method is called by the
  5288. * main [braces](#braces) function when `options.expand` is true. Before
  5289. * using this method it's recommended that you read the [performance notes](#performance))
  5290. * and advantages of using [.compile](#compile) instead.
  5291. *
  5292. * ```js
  5293. * const braces = require('braces');
  5294. * console.log(braces.expand('a/{b,c}/d'));
  5295. * //=> ['a/b/d', 'a/c/d'];
  5296. * ```
  5297. * @param {String} `pattern` Brace pattern
  5298. * @param {Object} `options`
  5299. * @return {Array} Returns an array of expanded values.
  5300. * @api public
  5301. */
  5302. braces.expand = (input, options = {}) => {
  5303. if (typeof input === 'string') {
  5304. input = braces.parse(input, options);
  5305. }
  5306. let result = expand(input, options);
  5307. // filter out empty strings if specified
  5308. if (options.noempty === true) {
  5309. result = result.filter(Boolean);
  5310. }
  5311. // filter out duplicates if specified
  5312. if (options.nodupes === true) {
  5313. result = [...new Set(result)];
  5314. }
  5315. return result;
  5316. };
  5317. /**
  5318. * Processes a brace pattern and returns either an expanded array
  5319. * (if `options.expand` is true), a highly optimized regex-compatible string.
  5320. * This method is called by the main [braces](#braces) function.
  5321. *
  5322. * ```js
  5323. * const braces = require('braces');
  5324. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  5325. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  5326. * ```
  5327. * @param {String} `pattern` Brace pattern
  5328. * @param {Object} `options`
  5329. * @return {Array} Returns an array of expanded values.
  5330. * @api public
  5331. */
  5332. braces.create = (input, options = {}) => {
  5333. if (input === '' || input.length < 3) {
  5334. return [input];
  5335. }
  5336. return options.expand !== true
  5337. ? braces.compile(input, options)
  5338. : braces.expand(input, options);
  5339. };
  5340. /**
  5341. * Expose "braces"
  5342. */
  5343. braces_1 = braces;
  5344. return braces_1;
  5345. }
  5346. const require$$0 = [
  5347. "3dm",
  5348. "3ds",
  5349. "3g2",
  5350. "3gp",
  5351. "7z",
  5352. "a",
  5353. "aac",
  5354. "adp",
  5355. "afdesign",
  5356. "afphoto",
  5357. "afpub",
  5358. "ai",
  5359. "aif",
  5360. "aiff",
  5361. "alz",
  5362. "ape",
  5363. "apk",
  5364. "appimage",
  5365. "ar",
  5366. "arj",
  5367. "asf",
  5368. "au",
  5369. "avi",
  5370. "bak",
  5371. "baml",
  5372. "bh",
  5373. "bin",
  5374. "bk",
  5375. "bmp",
  5376. "btif",
  5377. "bz2",
  5378. "bzip2",
  5379. "cab",
  5380. "caf",
  5381. "cgm",
  5382. "class",
  5383. "cmx",
  5384. "cpio",
  5385. "cr2",
  5386. "cur",
  5387. "dat",
  5388. "dcm",
  5389. "deb",
  5390. "dex",
  5391. "djvu",
  5392. "dll",
  5393. "dmg",
  5394. "dng",
  5395. "doc",
  5396. "docm",
  5397. "docx",
  5398. "dot",
  5399. "dotm",
  5400. "dra",
  5401. "DS_Store",
  5402. "dsk",
  5403. "dts",
  5404. "dtshd",
  5405. "dvb",
  5406. "dwg",
  5407. "dxf",
  5408. "ecelp4800",
  5409. "ecelp7470",
  5410. "ecelp9600",
  5411. "egg",
  5412. "eol",
  5413. "eot",
  5414. "epub",
  5415. "exe",
  5416. "f4v",
  5417. "fbs",
  5418. "fh",
  5419. "fla",
  5420. "flac",
  5421. "flatpak",
  5422. "fli",
  5423. "flv",
  5424. "fpx",
  5425. "fst",
  5426. "fvt",
  5427. "g3",
  5428. "gh",
  5429. "gif",
  5430. "graffle",
  5431. "gz",
  5432. "gzip",
  5433. "h261",
  5434. "h263",
  5435. "h264",
  5436. "icns",
  5437. "ico",
  5438. "ief",
  5439. "img",
  5440. "ipa",
  5441. "iso",
  5442. "jar",
  5443. "jpeg",
  5444. "jpg",
  5445. "jpgv",
  5446. "jpm",
  5447. "jxr",
  5448. "key",
  5449. "ktx",
  5450. "lha",
  5451. "lib",
  5452. "lvp",
  5453. "lz",
  5454. "lzh",
  5455. "lzma",
  5456. "lzo",
  5457. "m3u",
  5458. "m4a",
  5459. "m4v",
  5460. "mar",
  5461. "mdi",
  5462. "mht",
  5463. "mid",
  5464. "midi",
  5465. "mj2",
  5466. "mka",
  5467. "mkv",
  5468. "mmr",
  5469. "mng",
  5470. "mobi",
  5471. "mov",
  5472. "movie",
  5473. "mp3",
  5474. "mp4",
  5475. "mp4a",
  5476. "mpeg",
  5477. "mpg",
  5478. "mpga",
  5479. "mxu",
  5480. "nef",
  5481. "npx",
  5482. "numbers",
  5483. "nupkg",
  5484. "o",
  5485. "odp",
  5486. "ods",
  5487. "odt",
  5488. "oga",
  5489. "ogg",
  5490. "ogv",
  5491. "otf",
  5492. "ott",
  5493. "pages",
  5494. "pbm",
  5495. "pcx",
  5496. "pdb",
  5497. "pdf",
  5498. "pea",
  5499. "pgm",
  5500. "pic",
  5501. "png",
  5502. "pnm",
  5503. "pot",
  5504. "potm",
  5505. "potx",
  5506. "ppa",
  5507. "ppam",
  5508. "ppm",
  5509. "pps",
  5510. "ppsm",
  5511. "ppsx",
  5512. "ppt",
  5513. "pptm",
  5514. "pptx",
  5515. "psd",
  5516. "pya",
  5517. "pyc",
  5518. "pyo",
  5519. "pyv",
  5520. "qt",
  5521. "rar",
  5522. "ras",
  5523. "raw",
  5524. "resources",
  5525. "rgb",
  5526. "rip",
  5527. "rlc",
  5528. "rmf",
  5529. "rmvb",
  5530. "rpm",
  5531. "rtf",
  5532. "rz",
  5533. "s3m",
  5534. "s7z",
  5535. "scpt",
  5536. "sgi",
  5537. "shar",
  5538. "snap",
  5539. "sil",
  5540. "sketch",
  5541. "slk",
  5542. "smv",
  5543. "snk",
  5544. "so",
  5545. "stl",
  5546. "suo",
  5547. "sub",
  5548. "swf",
  5549. "tar",
  5550. "tbz",
  5551. "tbz2",
  5552. "tga",
  5553. "tgz",
  5554. "thmx",
  5555. "tif",
  5556. "tiff",
  5557. "tlz",
  5558. "ttc",
  5559. "ttf",
  5560. "txz",
  5561. "udf",
  5562. "uvh",
  5563. "uvi",
  5564. "uvm",
  5565. "uvp",
  5566. "uvs",
  5567. "uvu",
  5568. "viv",
  5569. "vob",
  5570. "war",
  5571. "wav",
  5572. "wax",
  5573. "wbmp",
  5574. "wdp",
  5575. "weba",
  5576. "webm",
  5577. "webp",
  5578. "whl",
  5579. "wim",
  5580. "wm",
  5581. "wma",
  5582. "wmv",
  5583. "wmx",
  5584. "woff",
  5585. "woff2",
  5586. "wrm",
  5587. "wvx",
  5588. "xbm",
  5589. "xif",
  5590. "xla",
  5591. "xlam",
  5592. "xls",
  5593. "xlsb",
  5594. "xlsm",
  5595. "xlsx",
  5596. "xlt",
  5597. "xltm",
  5598. "xltx",
  5599. "xm",
  5600. "xmind",
  5601. "xpi",
  5602. "xpm",
  5603. "xwd",
  5604. "xz",
  5605. "z",
  5606. "zip",
  5607. "zipx"
  5608. ];
  5609. var binaryExtensions;
  5610. var hasRequiredBinaryExtensions;
  5611. function requireBinaryExtensions () {
  5612. if (hasRequiredBinaryExtensions) return binaryExtensions;
  5613. hasRequiredBinaryExtensions = 1;
  5614. binaryExtensions = require$$0;
  5615. return binaryExtensions;
  5616. }
  5617. var isBinaryPath;
  5618. var hasRequiredIsBinaryPath;
  5619. function requireIsBinaryPath () {
  5620. if (hasRequiredIsBinaryPath) return isBinaryPath;
  5621. hasRequiredIsBinaryPath = 1;
  5622. const path = require$$0$1;
  5623. const binaryExtensions = /*@__PURE__*/ requireBinaryExtensions();
  5624. const extensions = new Set(binaryExtensions);
  5625. isBinaryPath = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase());
  5626. return isBinaryPath;
  5627. }
  5628. var constants = {};
  5629. var hasRequiredConstants;
  5630. function requireConstants () {
  5631. if (hasRequiredConstants) return constants;
  5632. hasRequiredConstants = 1;
  5633. (function (exports) {
  5634. const {sep} = require$$0$1;
  5635. const {platform} = process;
  5636. const os = require$$2$1;
  5637. exports.EV_ALL = 'all';
  5638. exports.EV_READY = 'ready';
  5639. exports.EV_ADD = 'add';
  5640. exports.EV_CHANGE = 'change';
  5641. exports.EV_ADD_DIR = 'addDir';
  5642. exports.EV_UNLINK = 'unlink';
  5643. exports.EV_UNLINK_DIR = 'unlinkDir';
  5644. exports.EV_RAW = 'raw';
  5645. exports.EV_ERROR = 'error';
  5646. exports.STR_DATA = 'data';
  5647. exports.STR_END = 'end';
  5648. exports.STR_CLOSE = 'close';
  5649. exports.FSEVENT_CREATED = 'created';
  5650. exports.FSEVENT_MODIFIED = 'modified';
  5651. exports.FSEVENT_DELETED = 'deleted';
  5652. exports.FSEVENT_MOVED = 'moved';
  5653. exports.FSEVENT_CLONED = 'cloned';
  5654. exports.FSEVENT_UNKNOWN = 'unknown';
  5655. exports.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1;
  5656. exports.FSEVENT_TYPE_FILE = 'file';
  5657. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  5658. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  5659. exports.KEY_LISTENERS = 'listeners';
  5660. exports.KEY_ERR = 'errHandlers';
  5661. exports.KEY_RAW = 'rawEmitters';
  5662. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  5663. exports.DOT_SLASH = `.${sep}`;
  5664. exports.BACK_SLASH_RE = /\\/g;
  5665. exports.DOUBLE_SLASH_RE = /\/\//;
  5666. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  5667. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  5668. exports.REPLACER_RE = /^\.[/\\]/;
  5669. exports.SLASH = '/';
  5670. exports.SLASH_SLASH = '//';
  5671. exports.BRACE_START = '{';
  5672. exports.BANG = '!';
  5673. exports.ONE_DOT = '.';
  5674. exports.TWO_DOTS = '..';
  5675. exports.STAR = '*';
  5676. exports.GLOBSTAR = '**';
  5677. exports.ROOT_GLOBSTAR = '/**/*';
  5678. exports.SLASH_GLOBSTAR = '/**';
  5679. exports.DIR_SUFFIX = 'Dir';
  5680. exports.ANYMATCH_OPTS = {dot: true};
  5681. exports.STRING_TYPE = 'string';
  5682. exports.FUNCTION_TYPE = 'function';
  5683. exports.EMPTY_STR = '';
  5684. exports.EMPTY_FN = () => {};
  5685. exports.IDENTITY_FN = val => val;
  5686. exports.isWindows = platform === 'win32';
  5687. exports.isMacos = platform === 'darwin';
  5688. exports.isLinux = platform === 'linux';
  5689. exports.isIBMi = os.type() === 'OS400';
  5690. } (constants));
  5691. return constants;
  5692. }
  5693. var nodefsHandler;
  5694. var hasRequiredNodefsHandler;
  5695. function requireNodefsHandler () {
  5696. if (hasRequiredNodefsHandler) return nodefsHandler;
  5697. hasRequiredNodefsHandler = 1;
  5698. const fs = require$$0$2;
  5699. const sysPath = require$$0$1;
  5700. const { promisify } = require$$2;
  5701. const isBinaryPath = /*@__PURE__*/ requireIsBinaryPath();
  5702. const {
  5703. isWindows,
  5704. isLinux,
  5705. EMPTY_FN,
  5706. EMPTY_STR,
  5707. KEY_LISTENERS,
  5708. KEY_ERR,
  5709. KEY_RAW,
  5710. HANDLER_KEYS,
  5711. EV_CHANGE,
  5712. EV_ADD,
  5713. EV_ADD_DIR,
  5714. EV_ERROR,
  5715. STR_DATA,
  5716. STR_END,
  5717. BRACE_START,
  5718. STAR
  5719. } = /*@__PURE__*/ requireConstants();
  5720. const THROTTLE_MODE_WATCH = 'watch';
  5721. const open = promisify(fs.open);
  5722. const stat = promisify(fs.stat);
  5723. const lstat = promisify(fs.lstat);
  5724. const close = promisify(fs.close);
  5725. const fsrealpath = promisify(fs.realpath);
  5726. const statMethods = { lstat, stat };
  5727. // TODO: emit errors properly. Example: EMFILE on Macos.
  5728. const foreach = (val, fn) => {
  5729. if (val instanceof Set) {
  5730. val.forEach(fn);
  5731. } else {
  5732. fn(val);
  5733. }
  5734. };
  5735. const addAndConvert = (main, prop, item) => {
  5736. let container = main[prop];
  5737. if (!(container instanceof Set)) {
  5738. main[prop] = container = new Set([container]);
  5739. }
  5740. container.add(item);
  5741. };
  5742. const clearItem = cont => key => {
  5743. const set = cont[key];
  5744. if (set instanceof Set) {
  5745. set.clear();
  5746. } else {
  5747. delete cont[key];
  5748. }
  5749. };
  5750. const delFromSet = (main, prop, item) => {
  5751. const container = main[prop];
  5752. if (container instanceof Set) {
  5753. container.delete(item);
  5754. } else if (container === item) {
  5755. delete main[prop];
  5756. }
  5757. };
  5758. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  5759. /**
  5760. * @typedef {String} Path
  5761. */
  5762. // fs_watch helpers
  5763. // object to hold per-process fs_watch instances
  5764. // (may be shared across chokidar FSWatcher instances)
  5765. /**
  5766. * @typedef {Object} FsWatchContainer
  5767. * @property {Set} listeners
  5768. * @property {Set} errHandlers
  5769. * @property {Set} rawEmitters
  5770. * @property {fs.FSWatcher=} watcher
  5771. * @property {Boolean=} watcherUnusable
  5772. */
  5773. /**
  5774. * @type {Map<String,FsWatchContainer>}
  5775. */
  5776. const FsWatchInstances = new Map();
  5777. /**
  5778. * Instantiates the fs_watch interface
  5779. * @param {String} path to be watched
  5780. * @param {Object} options to be passed to fs_watch
  5781. * @param {Function} listener main event handler
  5782. * @param {Function} errHandler emits info about errors
  5783. * @param {Function} emitRaw emits raw event data
  5784. * @returns {fs.FSWatcher} new fsevents instance
  5785. */
  5786. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  5787. const handleEvent = (rawEvent, evPath) => {
  5788. listener(path);
  5789. emitRaw(rawEvent, evPath, {watchedPath: path});
  5790. // emit based on events occurring for files from a directory's watcher in
  5791. // case the file's watcher misses it (and rely on throttling to de-dupe)
  5792. if (evPath && path !== evPath) {
  5793. fsWatchBroadcast(
  5794. sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath)
  5795. );
  5796. }
  5797. };
  5798. try {
  5799. return fs.watch(path, options, handleEvent);
  5800. } catch (error) {
  5801. errHandler(error);
  5802. }
  5803. }
  5804. /**
  5805. * Helper for passing fs_watch event data to a collection of listeners
  5806. * @param {Path} fullPath absolute path bound to fs_watch instance
  5807. * @param {String} type listener type
  5808. * @param {*=} val1 arguments to be passed to listeners
  5809. * @param {*=} val2
  5810. * @param {*=} val3
  5811. */
  5812. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  5813. const cont = FsWatchInstances.get(fullPath);
  5814. if (!cont) return;
  5815. foreach(cont[type], (listener) => {
  5816. listener(val1, val2, val3);
  5817. });
  5818. };
  5819. /**
  5820. * Instantiates the fs_watch interface or binds listeners
  5821. * to an existing one covering the same file system entry
  5822. * @param {String} path
  5823. * @param {String} fullPath absolute path
  5824. * @param {Object} options to be passed to fs_watch
  5825. * @param {Object} handlers container for event listener functions
  5826. */
  5827. const setFsWatchListener = (path, fullPath, options, handlers) => {
  5828. const {listener, errHandler, rawEmitter} = handlers;
  5829. let cont = FsWatchInstances.get(fullPath);
  5830. /** @type {fs.FSWatcher=} */
  5831. let watcher;
  5832. if (!options.persistent) {
  5833. watcher = createFsWatchInstance(
  5834. path, options, listener, errHandler, rawEmitter
  5835. );
  5836. return watcher.close.bind(watcher);
  5837. }
  5838. if (cont) {
  5839. addAndConvert(cont, KEY_LISTENERS, listener);
  5840. addAndConvert(cont, KEY_ERR, errHandler);
  5841. addAndConvert(cont, KEY_RAW, rawEmitter);
  5842. } else {
  5843. watcher = createFsWatchInstance(
  5844. path,
  5845. options,
  5846. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  5847. errHandler, // no need to use broadcast here
  5848. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  5849. );
  5850. if (!watcher) return;
  5851. watcher.on(EV_ERROR, async (error) => {
  5852. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  5853. cont.watcherUnusable = true; // documented since Node 10.4.1
  5854. // Workaround for https://github.com/joyent/node/issues/4337
  5855. if (isWindows && error.code === 'EPERM') {
  5856. try {
  5857. const fd = await open(path, 'r');
  5858. await close(fd);
  5859. broadcastErr(error);
  5860. } catch (err) {}
  5861. } else {
  5862. broadcastErr(error);
  5863. }
  5864. });
  5865. cont = {
  5866. listeners: listener,
  5867. errHandlers: errHandler,
  5868. rawEmitters: rawEmitter,
  5869. watcher
  5870. };
  5871. FsWatchInstances.set(fullPath, cont);
  5872. }
  5873. // const index = cont.listeners.indexOf(listener);
  5874. // removes this instance's listeners and closes the underlying fs_watch
  5875. // instance if there are no more listeners left
  5876. return () => {
  5877. delFromSet(cont, KEY_LISTENERS, listener);
  5878. delFromSet(cont, KEY_ERR, errHandler);
  5879. delFromSet(cont, KEY_RAW, rawEmitter);
  5880. if (isEmptySet(cont.listeners)) {
  5881. // Check to protect against issue gh-730.
  5882. // if (cont.watcherUnusable) {
  5883. cont.watcher.close();
  5884. // }
  5885. FsWatchInstances.delete(fullPath);
  5886. HANDLER_KEYS.forEach(clearItem(cont));
  5887. cont.watcher = undefined;
  5888. Object.freeze(cont);
  5889. }
  5890. };
  5891. };
  5892. // fs_watchFile helpers
  5893. // object to hold per-process fs_watchFile instances
  5894. // (may be shared across chokidar FSWatcher instances)
  5895. const FsWatchFileInstances = new Map();
  5896. /**
  5897. * Instantiates the fs_watchFile interface or binds listeners
  5898. * to an existing one covering the same file system entry
  5899. * @param {String} path to be watched
  5900. * @param {String} fullPath absolute path
  5901. * @param {Object} options options to be passed to fs_watchFile
  5902. * @param {Object} handlers container for event listener functions
  5903. * @returns {Function} closer
  5904. */
  5905. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  5906. const {listener, rawEmitter} = handlers;
  5907. let cont = FsWatchFileInstances.get(fullPath);
  5908. const copts = cont && cont.options;
  5909. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  5910. fs.unwatchFile(fullPath);
  5911. cont = undefined;
  5912. }
  5913. /* eslint-enable no-unused-vars, prefer-destructuring */
  5914. if (cont) {
  5915. addAndConvert(cont, KEY_LISTENERS, listener);
  5916. addAndConvert(cont, KEY_RAW, rawEmitter);
  5917. } else {
  5918. // TODO
  5919. // listeners.add(listener);
  5920. // rawEmitters.add(rawEmitter);
  5921. cont = {
  5922. listeners: listener,
  5923. rawEmitters: rawEmitter,
  5924. options,
  5925. watcher: fs.watchFile(fullPath, options, (curr, prev) => {
  5926. foreach(cont.rawEmitters, (rawEmitter) => {
  5927. rawEmitter(EV_CHANGE, fullPath, {curr, prev});
  5928. });
  5929. const currmtime = curr.mtimeMs;
  5930. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  5931. foreach(cont.listeners, (listener) => listener(path, curr));
  5932. }
  5933. })
  5934. };
  5935. FsWatchFileInstances.set(fullPath, cont);
  5936. }
  5937. // const index = cont.listeners.indexOf(listener);
  5938. // Removes this instance's listeners and closes the underlying fs_watchFile
  5939. // instance if there are no more listeners left.
  5940. return () => {
  5941. delFromSet(cont, KEY_LISTENERS, listener);
  5942. delFromSet(cont, KEY_RAW, rawEmitter);
  5943. if (isEmptySet(cont.listeners)) {
  5944. FsWatchFileInstances.delete(fullPath);
  5945. fs.unwatchFile(fullPath);
  5946. cont.options = cont.watcher = undefined;
  5947. Object.freeze(cont);
  5948. }
  5949. };
  5950. };
  5951. /**
  5952. * @mixin
  5953. */
  5954. class NodeFsHandler {
  5955. /**
  5956. * @param {import("../index").FSWatcher} fsW
  5957. */
  5958. constructor(fsW) {
  5959. this.fsw = fsW;
  5960. this._boundHandleError = (error) => fsW._handleError(error);
  5961. }
  5962. /**
  5963. * Watch file for changes with fs_watchFile or fs_watch.
  5964. * @param {String} path to file or dir
  5965. * @param {Function} listener on fs change
  5966. * @returns {Function} closer for the watcher instance
  5967. */
  5968. _watchWithNodeFs(path, listener) {
  5969. const opts = this.fsw.options;
  5970. const directory = sysPath.dirname(path);
  5971. const basename = sysPath.basename(path);
  5972. const parent = this.fsw._getWatchedDir(directory);
  5973. parent.add(basename);
  5974. const absolutePath = sysPath.resolve(path);
  5975. const options = {persistent: opts.persistent};
  5976. if (!listener) listener = EMPTY_FN;
  5977. let closer;
  5978. if (opts.usePolling) {
  5979. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  5980. opts.binaryInterval : opts.interval;
  5981. closer = setFsWatchFileListener(path, absolutePath, options, {
  5982. listener,
  5983. rawEmitter: this.fsw._emitRaw
  5984. });
  5985. } else {
  5986. closer = setFsWatchListener(path, absolutePath, options, {
  5987. listener,
  5988. errHandler: this._boundHandleError,
  5989. rawEmitter: this.fsw._emitRaw
  5990. });
  5991. }
  5992. return closer;
  5993. }
  5994. /**
  5995. * Watch a file and emit add event if warranted.
  5996. * @param {Path} file Path
  5997. * @param {fs.Stats} stats result of fs_stat
  5998. * @param {Boolean} initialAdd was the file added at watch instantiation?
  5999. * @returns {Function} closer for the watcher instance
  6000. */
  6001. _handleFile(file, stats, initialAdd) {
  6002. if (this.fsw.closed) {
  6003. return;
  6004. }
  6005. const dirname = sysPath.dirname(file);
  6006. const basename = sysPath.basename(file);
  6007. const parent = this.fsw._getWatchedDir(dirname);
  6008. // stats is always present
  6009. let prevStats = stats;
  6010. // if the file is already being watched, do nothing
  6011. if (parent.has(basename)) return;
  6012. const listener = async (path, newStats) => {
  6013. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  6014. if (!newStats || newStats.mtimeMs === 0) {
  6015. try {
  6016. const newStats = await stat(file);
  6017. if (this.fsw.closed) return;
  6018. // Check that change event was not fired because of changed only accessTime.
  6019. const at = newStats.atimeMs;
  6020. const mt = newStats.mtimeMs;
  6021. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  6022. this.fsw._emit(EV_CHANGE, file, newStats);
  6023. }
  6024. if (isLinux && prevStats.ino !== newStats.ino) {
  6025. this.fsw._closeFile(path);
  6026. prevStats = newStats;
  6027. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  6028. } else {
  6029. prevStats = newStats;
  6030. }
  6031. } catch (error) {
  6032. // Fix issues where mtime is null but file is still present
  6033. this.fsw._remove(dirname, basename);
  6034. }
  6035. // add is about to be emitted if file not already tracked in parent
  6036. } else if (parent.has(basename)) {
  6037. // Check that change event was not fired because of changed only accessTime.
  6038. const at = newStats.atimeMs;
  6039. const mt = newStats.mtimeMs;
  6040. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  6041. this.fsw._emit(EV_CHANGE, file, newStats);
  6042. }
  6043. prevStats = newStats;
  6044. }
  6045. };
  6046. // kick off the watcher
  6047. const closer = this._watchWithNodeFs(file, listener);
  6048. // emit an add event if we're supposed to
  6049. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  6050. if (!this.fsw._throttle(EV_ADD, file, 0)) return;
  6051. this.fsw._emit(EV_ADD, file, stats);
  6052. }
  6053. return closer;
  6054. }
  6055. /**
  6056. * Handle symlinks encountered while reading a dir.
  6057. * @param {Object} entry returned by readdirp
  6058. * @param {String} directory path of dir being read
  6059. * @param {String} path of this item
  6060. * @param {String} item basename of this item
  6061. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  6062. */
  6063. async _handleSymlink(entry, directory, path, item) {
  6064. if (this.fsw.closed) {
  6065. return;
  6066. }
  6067. const full = entry.fullPath;
  6068. const dir = this.fsw._getWatchedDir(directory);
  6069. if (!this.fsw.options.followSymlinks) {
  6070. // watch symlink directly (don't follow) and detect changes
  6071. this.fsw._incrReadyCount();
  6072. let linkPath;
  6073. try {
  6074. linkPath = await fsrealpath(path);
  6075. } catch (e) {
  6076. this.fsw._emitReady();
  6077. return true;
  6078. }
  6079. if (this.fsw.closed) return;
  6080. if (dir.has(item)) {
  6081. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  6082. this.fsw._symlinkPaths.set(full, linkPath);
  6083. this.fsw._emit(EV_CHANGE, path, entry.stats);
  6084. }
  6085. } else {
  6086. dir.add(item);
  6087. this.fsw._symlinkPaths.set(full, linkPath);
  6088. this.fsw._emit(EV_ADD, path, entry.stats);
  6089. }
  6090. this.fsw._emitReady();
  6091. return true;
  6092. }
  6093. // don't follow the same symlink more than once
  6094. if (this.fsw._symlinkPaths.has(full)) {
  6095. return true;
  6096. }
  6097. this.fsw._symlinkPaths.set(full, true);
  6098. }
  6099. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  6100. // Normalize the directory name on Windows
  6101. directory = sysPath.join(directory, EMPTY_STR);
  6102. if (!wh.hasGlob) {
  6103. throttler = this.fsw._throttle('readdir', directory, 1000);
  6104. if (!throttler) return;
  6105. }
  6106. const previous = this.fsw._getWatchedDir(wh.path);
  6107. const current = new Set();
  6108. let stream = this.fsw._readdirp(directory, {
  6109. fileFilter: entry => wh.filterPath(entry),
  6110. directoryFilter: entry => wh.filterDir(entry),
  6111. depth: 0
  6112. }).on(STR_DATA, async (entry) => {
  6113. if (this.fsw.closed) {
  6114. stream = undefined;
  6115. return;
  6116. }
  6117. const item = entry.path;
  6118. let path = sysPath.join(directory, item);
  6119. current.add(item);
  6120. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  6121. return;
  6122. }
  6123. if (this.fsw.closed) {
  6124. stream = undefined;
  6125. return;
  6126. }
  6127. // Files that present in current directory snapshot
  6128. // but absent in previous are added to watch list and
  6129. // emit `add` event.
  6130. if (item === target || !target && !previous.has(item)) {
  6131. this.fsw._incrReadyCount();
  6132. // ensure relativeness of path is preserved in case of watcher reuse
  6133. path = sysPath.join(dir, sysPath.relative(dir, path));
  6134. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  6135. }
  6136. }).on(EV_ERROR, this._boundHandleError);
  6137. return new Promise(resolve =>
  6138. stream.once(STR_END, () => {
  6139. if (this.fsw.closed) {
  6140. stream = undefined;
  6141. return;
  6142. }
  6143. const wasThrottled = throttler ? throttler.clear() : false;
  6144. resolve();
  6145. // Files that absent in current directory snapshot
  6146. // but present in previous emit `remove` event
  6147. // and are removed from @watched[directory].
  6148. previous.getChildren().filter((item) => {
  6149. return item !== directory &&
  6150. !current.has(item) &&
  6151. // in case of intersecting globs;
  6152. // a path may have been filtered out of this readdir, but
  6153. // shouldn't be removed because it matches a different glob
  6154. (!wh.hasGlob || wh.filterPath({
  6155. fullPath: sysPath.resolve(directory, item)
  6156. }));
  6157. }).forEach((item) => {
  6158. this.fsw._remove(directory, item);
  6159. });
  6160. stream = undefined;
  6161. // one more time for any missed in case changes came in extremely quickly
  6162. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  6163. })
  6164. );
  6165. }
  6166. /**
  6167. * Read directory to add / remove files from `@watched` list and re-read it on change.
  6168. * @param {String} dir fs path
  6169. * @param {fs.Stats} stats
  6170. * @param {Boolean} initialAdd
  6171. * @param {Number} depth relative to user-supplied path
  6172. * @param {String} target child path targeted for watch
  6173. * @param {Object} wh Common watch helpers for this path
  6174. * @param {String} realpath
  6175. * @returns {Promise<Function>} closer for the watcher instance.
  6176. */
  6177. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  6178. const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
  6179. const tracked = parentDir.has(sysPath.basename(dir));
  6180. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  6181. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats);
  6182. }
  6183. // ensure dir is tracked (harmless if redundant)
  6184. parentDir.add(sysPath.basename(dir));
  6185. this.fsw._getWatchedDir(dir);
  6186. let throttler;
  6187. let closer;
  6188. const oDepth = this.fsw.options.depth;
  6189. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  6190. if (!target) {
  6191. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  6192. if (this.fsw.closed) return;
  6193. }
  6194. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  6195. // if current directory is removed, do nothing
  6196. if (stats && stats.mtimeMs === 0) return;
  6197. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  6198. });
  6199. }
  6200. return closer;
  6201. }
  6202. /**
  6203. * Handle added file, directory, or glob pattern.
  6204. * Delegates call to _handleFile / _handleDir after checks.
  6205. * @param {String} path to file or ir
  6206. * @param {Boolean} initialAdd was the file added at watch instantiation?
  6207. * @param {Object} priorWh depth relative to user-supplied path
  6208. * @param {Number} depth Child path actually targeted for watch
  6209. * @param {String=} target Child path actually targeted for watch
  6210. * @returns {Promise}
  6211. */
  6212. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  6213. const ready = this.fsw._emitReady;
  6214. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  6215. ready();
  6216. return false;
  6217. }
  6218. const wh = this.fsw._getWatchHelpers(path, depth);
  6219. if (!wh.hasGlob && priorWh) {
  6220. wh.hasGlob = priorWh.hasGlob;
  6221. wh.globFilter = priorWh.globFilter;
  6222. wh.filterPath = entry => priorWh.filterPath(entry);
  6223. wh.filterDir = entry => priorWh.filterDir(entry);
  6224. }
  6225. // evaluate what is at the path we're being asked to watch
  6226. try {
  6227. const stats = await statMethods[wh.statMethod](wh.watchPath);
  6228. if (this.fsw.closed) return;
  6229. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  6230. ready();
  6231. return false;
  6232. }
  6233. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START);
  6234. let closer;
  6235. if (stats.isDirectory()) {
  6236. const absPath = sysPath.resolve(path);
  6237. const targetPath = follow ? await fsrealpath(path) : path;
  6238. if (this.fsw.closed) return;
  6239. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  6240. if (this.fsw.closed) return;
  6241. // preserve this symlink's target path
  6242. if (absPath !== targetPath && targetPath !== undefined) {
  6243. this.fsw._symlinkPaths.set(absPath, targetPath);
  6244. }
  6245. } else if (stats.isSymbolicLink()) {
  6246. const targetPath = follow ? await fsrealpath(path) : path;
  6247. if (this.fsw.closed) return;
  6248. const parent = sysPath.dirname(wh.watchPath);
  6249. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  6250. this.fsw._emit(EV_ADD, wh.watchPath, stats);
  6251. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  6252. if (this.fsw.closed) return;
  6253. // preserve this symlink's target path
  6254. if (targetPath !== undefined) {
  6255. this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
  6256. }
  6257. } else {
  6258. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  6259. }
  6260. ready();
  6261. this.fsw._addPathCloser(path, closer);
  6262. return false;
  6263. } catch (error) {
  6264. if (this.fsw._handleError(error)) {
  6265. ready();
  6266. return path;
  6267. }
  6268. }
  6269. }
  6270. }
  6271. nodefsHandler = NodeFsHandler;
  6272. return nodefsHandler;
  6273. }
  6274. var fseventsHandler = {exports: {}};
  6275. const require$$3 = /*@__PURE__*/getAugmentedNamespace(fseventsImporter);
  6276. var hasRequiredFseventsHandler;
  6277. function requireFseventsHandler () {
  6278. if (hasRequiredFseventsHandler) return fseventsHandler.exports;
  6279. hasRequiredFseventsHandler = 1;
  6280. const fs = require$$0$2;
  6281. const sysPath = require$$0$1;
  6282. const { promisify } = require$$2;
  6283. let fsevents;
  6284. try {
  6285. fsevents = require$$3.getFsEvents();
  6286. } catch (error) {
  6287. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  6288. }
  6289. if (fsevents) {
  6290. // TODO: real check
  6291. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  6292. if (mtch && mtch[1] && mtch[2]) {
  6293. const maj = Number.parseInt(mtch[1], 10);
  6294. const min = Number.parseInt(mtch[2], 10);
  6295. if (maj === 8 && min < 16) {
  6296. fsevents = undefined;
  6297. }
  6298. }
  6299. }
  6300. const {
  6301. EV_ADD,
  6302. EV_CHANGE,
  6303. EV_ADD_DIR,
  6304. EV_UNLINK,
  6305. EV_ERROR,
  6306. STR_DATA,
  6307. STR_END,
  6308. FSEVENT_CREATED,
  6309. FSEVENT_MODIFIED,
  6310. FSEVENT_DELETED,
  6311. FSEVENT_MOVED,
  6312. // FSEVENT_CLONED,
  6313. FSEVENT_UNKNOWN,
  6314. FSEVENT_FLAG_MUST_SCAN_SUBDIRS,
  6315. FSEVENT_TYPE_FILE,
  6316. FSEVENT_TYPE_DIRECTORY,
  6317. FSEVENT_TYPE_SYMLINK,
  6318. ROOT_GLOBSTAR,
  6319. DIR_SUFFIX,
  6320. DOT_SLASH,
  6321. FUNCTION_TYPE,
  6322. EMPTY_FN,
  6323. IDENTITY_FN
  6324. } = /*@__PURE__*/ requireConstants();
  6325. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  6326. const stat = promisify(fs.stat);
  6327. const lstat = promisify(fs.lstat);
  6328. const realpath = promisify(fs.realpath);
  6329. const statMethods = { stat, lstat };
  6330. /**
  6331. * @typedef {String} Path
  6332. */
  6333. /**
  6334. * @typedef {Object} FsEventsWatchContainer
  6335. * @property {Set<Function>} listeners
  6336. * @property {Function} rawEmitter
  6337. * @property {{stop: Function}} watcher
  6338. */
  6339. // fsevents instance helper functions
  6340. /**
  6341. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  6342. * @type {Map<Path,FsEventsWatchContainer>}
  6343. */
  6344. const FSEventsWatchers = new Map();
  6345. // Threshold of duplicate path prefixes at which to start
  6346. // consolidating going forward
  6347. const consolidateThreshhold = 10;
  6348. const wrongEventFlags = new Set([
  6349. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  6350. ]);
  6351. /**
  6352. * Instantiates the fsevents interface
  6353. * @param {Path} path path to be watched
  6354. * @param {Function} callback called when fsevents is bound and ready
  6355. * @returns {{stop: Function}} new fsevents instance
  6356. */
  6357. const createFSEventsInstance = (path, callback) => {
  6358. const stop = fsevents.watch(path, callback);
  6359. return {stop};
  6360. };
  6361. /**
  6362. * Instantiates the fsevents interface or binds listeners to an existing one covering
  6363. * the same file tree.
  6364. * @param {Path} path - to be watched
  6365. * @param {Path} realPath - real path for symlinks
  6366. * @param {Function} listener - called when fsevents emits events
  6367. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  6368. * @returns {Function} closer
  6369. */
  6370. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  6371. let watchPath = sysPath.extname(realPath) ? sysPath.dirname(realPath) : realPath;
  6372. const parentPath = sysPath.dirname(watchPath);
  6373. let cont = FSEventsWatchers.get(watchPath);
  6374. // If we've accumulated a substantial number of paths that
  6375. // could have been consolidated by watching one directory
  6376. // above the current one, create a watcher on the parent
  6377. // path instead, so that we do consolidate going forward.
  6378. if (couldConsolidate(parentPath)) {
  6379. watchPath = parentPath;
  6380. }
  6381. const resolvedPath = sysPath.resolve(path);
  6382. const hasSymlink = resolvedPath !== realPath;
  6383. const filteredListener = (fullPath, flags, info) => {
  6384. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  6385. if (
  6386. fullPath === resolvedPath ||
  6387. !fullPath.indexOf(resolvedPath + sysPath.sep)
  6388. ) listener(fullPath, flags, info);
  6389. };
  6390. // check if there is already a watcher on a parent path
  6391. // modifies `watchPath` to the parent path when it finds a match
  6392. let watchedParent = false;
  6393. for (const watchedPath of FSEventsWatchers.keys()) {
  6394. if (realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep) === 0) {
  6395. watchPath = watchedPath;
  6396. cont = FSEventsWatchers.get(watchPath);
  6397. watchedParent = true;
  6398. break;
  6399. }
  6400. }
  6401. if (cont || watchedParent) {
  6402. cont.listeners.add(filteredListener);
  6403. } else {
  6404. cont = {
  6405. listeners: new Set([filteredListener]),
  6406. rawEmitter,
  6407. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  6408. if (!cont.listeners.size) return;
  6409. if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return;
  6410. const info = fsevents.getInfo(fullPath, flags);
  6411. cont.listeners.forEach(list => {
  6412. list(fullPath, flags, info);
  6413. });
  6414. cont.rawEmitter(info.event, fullPath, info);
  6415. })
  6416. };
  6417. FSEventsWatchers.set(watchPath, cont);
  6418. }
  6419. // removes this instance's listeners and closes the underlying fsevents
  6420. // instance if there are no more listeners left
  6421. return () => {
  6422. const lst = cont.listeners;
  6423. lst.delete(filteredListener);
  6424. if (!lst.size) {
  6425. FSEventsWatchers.delete(watchPath);
  6426. if (cont.watcher) return cont.watcher.stop().then(() => {
  6427. cont.rawEmitter = cont.watcher = undefined;
  6428. Object.freeze(cont);
  6429. });
  6430. }
  6431. };
  6432. }
  6433. // Decide whether or not we should start a new higher-level
  6434. // parent watcher
  6435. const couldConsolidate = (path) => {
  6436. let count = 0;
  6437. for (const watchPath of FSEventsWatchers.keys()) {
  6438. if (watchPath.indexOf(path) === 0) {
  6439. count++;
  6440. if (count >= consolidateThreshhold) {
  6441. return true;
  6442. }
  6443. }
  6444. }
  6445. return false;
  6446. };
  6447. // returns boolean indicating whether fsevents can be used
  6448. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  6449. // determines subdirectory traversal levels from root to path
  6450. const calcDepth = (path, root) => {
  6451. let i = 0;
  6452. while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++;
  6453. return i;
  6454. };
  6455. // returns boolean indicating whether the fsevents' event info has the same type
  6456. // as the one returned by fs.stat
  6457. const sameTypes = (info, stats) => (
  6458. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  6459. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  6460. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  6461. );
  6462. /**
  6463. * @mixin
  6464. */
  6465. class FsEventsHandler {
  6466. /**
  6467. * @param {import('../index').FSWatcher} fsw
  6468. */
  6469. constructor(fsw) {
  6470. this.fsw = fsw;
  6471. }
  6472. checkIgnored(path, stats) {
  6473. const ipaths = this.fsw._ignoredPaths;
  6474. if (this.fsw._isIgnored(path, stats)) {
  6475. ipaths.add(path);
  6476. if (stats && stats.isDirectory()) {
  6477. ipaths.add(path + ROOT_GLOBSTAR);
  6478. }
  6479. return true;
  6480. }
  6481. ipaths.delete(path);
  6482. ipaths.delete(path + ROOT_GLOBSTAR);
  6483. }
  6484. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  6485. const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD;
  6486. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6487. }
  6488. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  6489. try {
  6490. const stats = await stat(path);
  6491. if (this.fsw.closed) return;
  6492. if (sameTypes(info, stats)) {
  6493. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6494. } else {
  6495. this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6496. }
  6497. } catch (error) {
  6498. if (error.code === 'EACCES') {
  6499. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6500. } else {
  6501. this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6502. }
  6503. }
  6504. }
  6505. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  6506. if (this.fsw.closed || this.checkIgnored(path)) return;
  6507. if (event === EV_UNLINK) {
  6508. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  6509. // suppress unlink events on never before seen files
  6510. if (isDirectory || watchedDir.has(item)) {
  6511. this.fsw._remove(parent, item, isDirectory);
  6512. }
  6513. } else {
  6514. if (event === EV_ADD) {
  6515. // track new directories
  6516. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  6517. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  6518. // push symlinks back to the top of the stack to get handled
  6519. const curDepth = opts.depth === undefined ?
  6520. undefined : calcDepth(fullPath, realPath) + 1;
  6521. return this._addToFsEvents(path, false, true, curDepth);
  6522. }
  6523. // track new paths
  6524. // (other than symlinks being followed, which will be tracked soon)
  6525. this.fsw._getWatchedDir(parent).add(item);
  6526. }
  6527. /**
  6528. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  6529. */
  6530. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  6531. this.fsw._emit(eventName, path);
  6532. if (eventName === EV_ADD_DIR) this._addToFsEvents(path, false, true);
  6533. }
  6534. }
  6535. /**
  6536. * Handle symlinks encountered during directory scan
  6537. * @param {String} watchPath - file/dir path to be watched with fsevents
  6538. * @param {String} realPath - real path (in case of symlinks)
  6539. * @param {Function} transform - path transformer
  6540. * @param {Function} globFilter - path filter in case a glob pattern was provided
  6541. * @returns {Function} closer for the watcher instance
  6542. */
  6543. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  6544. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  6545. const opts = this.fsw.options;
  6546. const watchCallback = async (fullPath, flags, info) => {
  6547. if (this.fsw.closed) return;
  6548. if (
  6549. opts.depth !== undefined &&
  6550. calcDepth(fullPath, realPath) > opts.depth
  6551. ) return;
  6552. const path = transform(sysPath.join(
  6553. watchPath, sysPath.relative(watchPath, fullPath)
  6554. ));
  6555. if (globFilter && !globFilter(path)) return;
  6556. // ensure directories are tracked
  6557. const parent = sysPath.dirname(path);
  6558. const item = sysPath.basename(path);
  6559. const watchedDir = this.fsw._getWatchedDir(
  6560. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  6561. );
  6562. // correct for wrong events emitted
  6563. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  6564. if (typeof opts.ignored === FUNCTION_TYPE) {
  6565. let stats;
  6566. try {
  6567. stats = await stat(path);
  6568. } catch (error) {}
  6569. if (this.fsw.closed) return;
  6570. if (this.checkIgnored(path, stats)) return;
  6571. if (sameTypes(info, stats)) {
  6572. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6573. } else {
  6574. this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6575. }
  6576. } else {
  6577. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6578. }
  6579. } else {
  6580. switch (info.event) {
  6581. case FSEVENT_CREATED:
  6582. case FSEVENT_MODIFIED:
  6583. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6584. case FSEVENT_DELETED:
  6585. case FSEVENT_MOVED:
  6586. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6587. }
  6588. }
  6589. };
  6590. const closer = setFSEventsListener(
  6591. watchPath,
  6592. realPath,
  6593. watchCallback,
  6594. this.fsw._emitRaw
  6595. );
  6596. this.fsw._emitReady();
  6597. return closer;
  6598. }
  6599. /**
  6600. * Handle symlinks encountered during directory scan
  6601. * @param {String} linkPath path to symlink
  6602. * @param {String} fullPath absolute path to the symlink
  6603. * @param {Function} transform pre-existing path transformer
  6604. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  6605. * @returns {Promise<void>}
  6606. */
  6607. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  6608. // don't follow the same symlink more than once
  6609. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  6610. this.fsw._symlinkPaths.set(fullPath, true);
  6611. this.fsw._incrReadyCount();
  6612. try {
  6613. const linkTarget = await realpath(linkPath);
  6614. if (this.fsw.closed) return;
  6615. if (this.fsw._isIgnored(linkTarget)) {
  6616. return this.fsw._emitReady();
  6617. }
  6618. this.fsw._incrReadyCount();
  6619. // add the linkTarget for watching with a wrapper for transform
  6620. // that causes emitted paths to incorporate the link's path
  6621. this._addToFsEvents(linkTarget || linkPath, (path) => {
  6622. let aliasedPath = linkPath;
  6623. if (linkTarget && linkTarget !== DOT_SLASH) {
  6624. aliasedPath = path.replace(linkTarget, linkPath);
  6625. } else if (path !== DOT_SLASH) {
  6626. aliasedPath = sysPath.join(linkPath, path);
  6627. }
  6628. return transform(aliasedPath);
  6629. }, false, curDepth);
  6630. } catch(error) {
  6631. if (this.fsw._handleError(error)) {
  6632. return this.fsw._emitReady();
  6633. }
  6634. }
  6635. }
  6636. /**
  6637. *
  6638. * @param {Path} newPath
  6639. * @param {fs.Stats} stats
  6640. */
  6641. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  6642. const pp = processPath(newPath);
  6643. const isDir = stats.isDirectory();
  6644. const dirObj = this.fsw._getWatchedDir(sysPath.dirname(pp));
  6645. const base = sysPath.basename(pp);
  6646. // ensure empty dirs get tracked
  6647. if (isDir) this.fsw._getWatchedDir(pp);
  6648. if (dirObj.has(base)) return;
  6649. dirObj.add(base);
  6650. if (!opts.ignoreInitial || forceAdd === true) {
  6651. this.fsw._emit(isDir ? EV_ADD_DIR : EV_ADD, pp, stats);
  6652. }
  6653. }
  6654. initWatch(realPath, path, wh, processPath) {
  6655. if (this.fsw.closed) return;
  6656. const closer = this._watchWithFsEvents(
  6657. wh.watchPath,
  6658. sysPath.resolve(realPath || wh.watchPath),
  6659. processPath,
  6660. wh.globFilter
  6661. );
  6662. this.fsw._addPathCloser(path, closer);
  6663. }
  6664. /**
  6665. * Handle added path with fsevents
  6666. * @param {String} path file/dir path or glob pattern
  6667. * @param {Function|Boolean=} transform converts working path to what the user expects
  6668. * @param {Boolean=} forceAdd ensure add is emitted
  6669. * @param {Number=} priorDepth Level of subdirectories already traversed.
  6670. * @returns {Promise<void>}
  6671. */
  6672. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  6673. if (this.fsw.closed) {
  6674. return;
  6675. }
  6676. const opts = this.fsw.options;
  6677. const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN;
  6678. const wh = this.fsw._getWatchHelpers(path);
  6679. // evaluate what is at the path we're being asked to watch
  6680. try {
  6681. const stats = await statMethods[wh.statMethod](wh.watchPath);
  6682. if (this.fsw.closed) return;
  6683. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  6684. throw null;
  6685. }
  6686. if (stats.isDirectory()) {
  6687. // emit addDir unless this is a glob parent
  6688. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  6689. // don't recurse further if it would exceed depth setting
  6690. if (priorDepth && priorDepth > opts.depth) return;
  6691. // scan the contents of the dir
  6692. this.fsw._readdirp(wh.watchPath, {
  6693. fileFilter: entry => wh.filterPath(entry),
  6694. directoryFilter: entry => wh.filterDir(entry),
  6695. ...Depth(opts.depth - (priorDepth || 0))
  6696. }).on(STR_DATA, (entry) => {
  6697. // need to check filterPath on dirs b/c filterDir is less restrictive
  6698. if (this.fsw.closed) {
  6699. return;
  6700. }
  6701. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  6702. const joinedPath = sysPath.join(wh.watchPath, entry.path);
  6703. const {fullPath} = entry;
  6704. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  6705. // preserve the current depth here since it can't be derived from
  6706. // real paths past the symlink
  6707. const curDepth = opts.depth === undefined ?
  6708. undefined : calcDepth(joinedPath, sysPath.resolve(wh.watchPath)) + 1;
  6709. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  6710. } else {
  6711. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  6712. }
  6713. }).on(EV_ERROR, EMPTY_FN).on(STR_END, () => {
  6714. this.fsw._emitReady();
  6715. });
  6716. } else {
  6717. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  6718. this.fsw._emitReady();
  6719. }
  6720. } catch (error) {
  6721. if (!error || this.fsw._handleError(error)) {
  6722. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  6723. this.fsw._emitReady();
  6724. this.fsw._emitReady();
  6725. }
  6726. }
  6727. if (opts.persistent && forceAdd !== true) {
  6728. if (typeof transform === FUNCTION_TYPE) {
  6729. // realpath has already been resolved
  6730. this.initWatch(undefined, path, wh, processPath);
  6731. } else {
  6732. let realPath;
  6733. try {
  6734. realPath = await realpath(wh.watchPath);
  6735. } catch (e) {}
  6736. this.initWatch(realPath, path, wh, processPath);
  6737. }
  6738. }
  6739. }
  6740. }
  6741. fseventsHandler.exports = FsEventsHandler;
  6742. fseventsHandler.exports.canUse = canUse;
  6743. return fseventsHandler.exports;
  6744. }
  6745. var hasRequiredChokidar;
  6746. function requireChokidar () {
  6747. if (hasRequiredChokidar) return chokidar$1;
  6748. hasRequiredChokidar = 1;
  6749. const { EventEmitter } = require$$0$3;
  6750. const fs = require$$0$2;
  6751. const sysPath = require$$0$1;
  6752. const { promisify } = require$$2;
  6753. const readdirp = /*@__PURE__*/ requireReaddirp();
  6754. const anymatch = /*@__PURE__*/ requireAnymatch().default;
  6755. const globParent = /*@__PURE__*/ requireGlobParent();
  6756. const isGlob = /*@__PURE__*/ requireIsGlob();
  6757. const braces = /*@__PURE__*/ requireBraces();
  6758. const normalizePath = /*@__PURE__*/ requireNormalizePath();
  6759. const NodeFsHandler = /*@__PURE__*/ requireNodefsHandler();
  6760. const FsEventsHandler = /*@__PURE__*/ requireFseventsHandler();
  6761. const {
  6762. EV_ALL,
  6763. EV_READY,
  6764. EV_ADD,
  6765. EV_CHANGE,
  6766. EV_UNLINK,
  6767. EV_ADD_DIR,
  6768. EV_UNLINK_DIR,
  6769. EV_RAW,
  6770. EV_ERROR,
  6771. STR_CLOSE,
  6772. STR_END,
  6773. BACK_SLASH_RE,
  6774. DOUBLE_SLASH_RE,
  6775. SLASH_OR_BACK_SLASH_RE,
  6776. DOT_RE,
  6777. REPLACER_RE,
  6778. SLASH,
  6779. SLASH_SLASH,
  6780. BRACE_START,
  6781. BANG,
  6782. ONE_DOT,
  6783. TWO_DOTS,
  6784. GLOBSTAR,
  6785. SLASH_GLOBSTAR,
  6786. ANYMATCH_OPTS,
  6787. STRING_TYPE,
  6788. FUNCTION_TYPE,
  6789. EMPTY_STR,
  6790. EMPTY_FN,
  6791. isWindows,
  6792. isMacos,
  6793. isIBMi
  6794. } = /*@__PURE__*/ requireConstants();
  6795. const stat = promisify(fs.stat);
  6796. const readdir = promisify(fs.readdir);
  6797. /**
  6798. * @typedef {String} Path
  6799. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  6800. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  6801. */
  6802. /**
  6803. *
  6804. * @typedef {Object} WatchHelpers
  6805. * @property {Boolean} followSymlinks
  6806. * @property {'stat'|'lstat'} statMethod
  6807. * @property {Path} path
  6808. * @property {Path} watchPath
  6809. * @property {Function} entryPath
  6810. * @property {Boolean} hasGlob
  6811. * @property {Object} globFilter
  6812. * @property {Function} filterPath
  6813. * @property {Function} filterDir
  6814. */
  6815. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  6816. const flatten = (list, result = []) => {
  6817. list.forEach(item => {
  6818. if (Array.isArray(item)) {
  6819. flatten(item, result);
  6820. } else {
  6821. result.push(item);
  6822. }
  6823. });
  6824. return result;
  6825. };
  6826. const unifyPaths = (paths_) => {
  6827. /**
  6828. * @type {Array<String>}
  6829. */
  6830. const paths = flatten(arrify(paths_));
  6831. if (!paths.every(p => typeof p === STRING_TYPE)) {
  6832. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  6833. }
  6834. return paths.map(normalizePathToUnix);
  6835. };
  6836. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  6837. // because "//StoragePC/DrivePool/Movies" is a valid network path
  6838. const toUnix = (string) => {
  6839. let str = string.replace(BACK_SLASH_RE, SLASH);
  6840. let prepend = false;
  6841. if (str.startsWith(SLASH_SLASH)) {
  6842. prepend = true;
  6843. }
  6844. while (str.match(DOUBLE_SLASH_RE)) {
  6845. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  6846. }
  6847. if (prepend) {
  6848. str = SLASH + str;
  6849. }
  6850. return str;
  6851. };
  6852. // Our version of upath.normalize
  6853. // TODO: this is not equal to path-normalize module - investigate why
  6854. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  6855. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  6856. if (typeof path !== STRING_TYPE) return path;
  6857. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  6858. };
  6859. const getAbsolutePath = (path, cwd) => {
  6860. if (sysPath.isAbsolute(path)) {
  6861. return path;
  6862. }
  6863. if (path.startsWith(BANG)) {
  6864. return BANG + sysPath.join(cwd, path.slice(1));
  6865. }
  6866. return sysPath.join(cwd, path);
  6867. };
  6868. const undef = (opts, key) => opts[key] === undefined;
  6869. /**
  6870. * Directory entry.
  6871. * @property {Path} path
  6872. * @property {Set<Path>} items
  6873. */
  6874. class DirEntry {
  6875. /**
  6876. * @param {Path} dir
  6877. * @param {Function} removeWatcher
  6878. */
  6879. constructor(dir, removeWatcher) {
  6880. this.path = dir;
  6881. this._removeWatcher = removeWatcher;
  6882. /** @type {Set<Path>} */
  6883. this.items = new Set();
  6884. }
  6885. add(item) {
  6886. const {items} = this;
  6887. if (!items) return;
  6888. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  6889. }
  6890. async remove(item) {
  6891. const {items} = this;
  6892. if (!items) return;
  6893. items.delete(item);
  6894. if (items.size > 0) return;
  6895. const dir = this.path;
  6896. try {
  6897. await readdir(dir);
  6898. } catch (err) {
  6899. if (this._removeWatcher) {
  6900. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  6901. }
  6902. }
  6903. }
  6904. has(item) {
  6905. const {items} = this;
  6906. if (!items) return;
  6907. return items.has(item);
  6908. }
  6909. /**
  6910. * @returns {Array<String>}
  6911. */
  6912. getChildren() {
  6913. const {items} = this;
  6914. if (!items) return;
  6915. return [...items.values()];
  6916. }
  6917. dispose() {
  6918. this.items.clear();
  6919. delete this.path;
  6920. delete this._removeWatcher;
  6921. delete this.items;
  6922. Object.freeze(this);
  6923. }
  6924. }
  6925. const STAT_METHOD_F = 'stat';
  6926. const STAT_METHOD_L = 'lstat';
  6927. class WatchHelper {
  6928. constructor(path, watchPath, follow, fsw) {
  6929. this.fsw = fsw;
  6930. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  6931. this.watchPath = watchPath;
  6932. this.fullWatchPath = sysPath.resolve(watchPath);
  6933. this.hasGlob = watchPath !== path;
  6934. /** @type {object|boolean} */
  6935. if (path === EMPTY_STR) this.hasGlob = false;
  6936. this.globSymlink = this.hasGlob && follow ? undefined : false;
  6937. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  6938. this.dirParts = this.getDirParts(path);
  6939. this.dirParts.forEach((parts) => {
  6940. if (parts.length > 1) parts.pop();
  6941. });
  6942. this.followSymlinks = follow;
  6943. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  6944. }
  6945. checkGlobSymlink(entry) {
  6946. // only need to resolve once
  6947. // first entry should always have entry.parentDir === EMPTY_STR
  6948. if (this.globSymlink === undefined) {
  6949. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  6950. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  6951. }
  6952. if (this.globSymlink) {
  6953. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  6954. }
  6955. return entry.fullPath;
  6956. }
  6957. entryPath(entry) {
  6958. return sysPath.join(this.watchPath,
  6959. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  6960. );
  6961. }
  6962. filterPath(entry) {
  6963. const {stats} = entry;
  6964. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  6965. const resolvedPath = this.entryPath(entry);
  6966. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  6967. this.globFilter(resolvedPath) : true;
  6968. return matchesGlob &&
  6969. this.fsw._isntIgnored(resolvedPath, stats) &&
  6970. this.fsw._hasReadPermissions(stats);
  6971. }
  6972. getDirParts(path) {
  6973. if (!this.hasGlob) return [];
  6974. const parts = [];
  6975. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  6976. expandedPath.forEach((path) => {
  6977. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  6978. });
  6979. return parts;
  6980. }
  6981. filterDir(entry) {
  6982. if (this.hasGlob) {
  6983. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  6984. let globstar = false;
  6985. this.unmatchedGlob = !this.dirParts.some((parts) => {
  6986. return parts.every((part, i) => {
  6987. if (part === GLOBSTAR) globstar = true;
  6988. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  6989. });
  6990. });
  6991. }
  6992. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  6993. }
  6994. }
  6995. /**
  6996. * Watches files & directories for changes. Emitted events:
  6997. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  6998. *
  6999. * new FSWatcher()
  7000. * .add(directories)
  7001. * .on('add', path => log('File', path, 'was added'))
  7002. */
  7003. class FSWatcher extends EventEmitter {
  7004. // Not indenting methods for history sake; for now.
  7005. constructor(_opts) {
  7006. super();
  7007. const opts = {};
  7008. if (_opts) Object.assign(opts, _opts); // for frozen objects
  7009. /** @type {Map<String, DirEntry>} */
  7010. this._watched = new Map();
  7011. /** @type {Map<String, Array>} */
  7012. this._closers = new Map();
  7013. /** @type {Set<String>} */
  7014. this._ignoredPaths = new Set();
  7015. /** @type {Map<ThrottleType, Map>} */
  7016. this._throttled = new Map();
  7017. /** @type {Map<Path, String|Boolean>} */
  7018. this._symlinkPaths = new Map();
  7019. this._streams = new Set();
  7020. this.closed = false;
  7021. // Set up default options.
  7022. if (undef(opts, 'persistent')) opts.persistent = true;
  7023. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  7024. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  7025. if (undef(opts, 'interval')) opts.interval = 100;
  7026. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  7027. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  7028. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  7029. // Enable fsevents on OS X when polling isn't explicitly enabled.
  7030. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  7031. // If we can't use fsevents, ensure the options reflect it's disabled.
  7032. const canUseFsEvents = FsEventsHandler.canUse();
  7033. if (!canUseFsEvents) opts.useFsEvents = false;
  7034. // Use polling on Mac if not using fsevents.
  7035. // Other platforms use non-polling fs_watch.
  7036. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  7037. opts.usePolling = isMacos;
  7038. }
  7039. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  7040. if(isIBMi) {
  7041. opts.usePolling = true;
  7042. }
  7043. // Global override (useful for end-developers that need to force polling for all
  7044. // instances of chokidar, regardless of usage/dependency depth)
  7045. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  7046. if (envPoll !== undefined) {
  7047. const envLower = envPoll.toLowerCase();
  7048. if (envLower === 'false' || envLower === '0') {
  7049. opts.usePolling = false;
  7050. } else if (envLower === 'true' || envLower === '1') {
  7051. opts.usePolling = true;
  7052. } else {
  7053. opts.usePolling = !!envLower;
  7054. }
  7055. }
  7056. const envInterval = process.env.CHOKIDAR_INTERVAL;
  7057. if (envInterval) {
  7058. opts.interval = Number.parseInt(envInterval, 10);
  7059. }
  7060. // Editor atomic write normalization enabled by default with fs.watch
  7061. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  7062. if (opts.atomic) this._pendingUnlinks = new Map();
  7063. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  7064. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  7065. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  7066. const awf = opts.awaitWriteFinish;
  7067. if (awf) {
  7068. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  7069. if (!awf.pollInterval) awf.pollInterval = 100;
  7070. this._pendingWrites = new Map();
  7071. }
  7072. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  7073. let readyCalls = 0;
  7074. this._emitReady = () => {
  7075. readyCalls++;
  7076. if (readyCalls >= this._readyCount) {
  7077. this._emitReady = EMPTY_FN;
  7078. this._readyEmitted = true;
  7079. // use process.nextTick to allow time for listener to be bound
  7080. process.nextTick(() => this.emit(EV_READY));
  7081. }
  7082. };
  7083. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  7084. this._readyEmitted = false;
  7085. this.options = opts;
  7086. // Initialize with proper watcher.
  7087. if (opts.useFsEvents) {
  7088. this._fsEventsHandler = new FsEventsHandler(this);
  7089. } else {
  7090. this._nodeFsHandler = new NodeFsHandler(this);
  7091. }
  7092. // You’re frozen when your heart’s not open.
  7093. Object.freeze(opts);
  7094. }
  7095. // Public methods
  7096. /**
  7097. * Adds paths to be watched on an existing FSWatcher instance
  7098. * @param {Path|Array<Path>} paths_
  7099. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  7100. * @param {Boolean=} _internal private; indicates a non-user add
  7101. * @returns {FSWatcher} for chaining
  7102. */
  7103. add(paths_, _origAdd, _internal) {
  7104. const {cwd, disableGlobbing} = this.options;
  7105. this.closed = false;
  7106. let paths = unifyPaths(paths_);
  7107. if (cwd) {
  7108. paths = paths.map((path) => {
  7109. const absPath = getAbsolutePath(path, cwd);
  7110. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  7111. if (disableGlobbing || !isGlob(path)) {
  7112. return absPath;
  7113. }
  7114. return normalizePath(absPath);
  7115. });
  7116. }
  7117. // set aside negated glob strings
  7118. paths = paths.filter((path) => {
  7119. if (path.startsWith(BANG)) {
  7120. this._ignoredPaths.add(path.slice(1));
  7121. return false;
  7122. }
  7123. // if a path is being added that was previously ignored, stop ignoring it
  7124. this._ignoredPaths.delete(path);
  7125. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  7126. // reset the cached userIgnored anymatch fn
  7127. // to make ignoredPaths changes effective
  7128. this._userIgnored = undefined;
  7129. return true;
  7130. });
  7131. if (this.options.useFsEvents && this._fsEventsHandler) {
  7132. if (!this._readyCount) this._readyCount = paths.length;
  7133. if (this.options.persistent) this._readyCount += paths.length;
  7134. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  7135. } else {
  7136. if (!this._readyCount) this._readyCount = 0;
  7137. this._readyCount += paths.length;
  7138. Promise.all(
  7139. paths.map(async path => {
  7140. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  7141. if (res) this._emitReady();
  7142. return res;
  7143. })
  7144. ).then(results => {
  7145. if (this.closed) return;
  7146. results.filter(item => item).forEach(item => {
  7147. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  7148. });
  7149. });
  7150. }
  7151. return this;
  7152. }
  7153. /**
  7154. * Close watchers or start ignoring events from specified paths.
  7155. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  7156. * @returns {FSWatcher} for chaining
  7157. */
  7158. unwatch(paths_) {
  7159. if (this.closed) return this;
  7160. const paths = unifyPaths(paths_);
  7161. const {cwd} = this.options;
  7162. paths.forEach((path) => {
  7163. // convert to absolute path unless relative path already matches
  7164. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  7165. if (cwd) path = sysPath.join(cwd, path);
  7166. path = sysPath.resolve(path);
  7167. }
  7168. this._closePath(path);
  7169. this._ignoredPaths.add(path);
  7170. if (this._watched.has(path)) {
  7171. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  7172. }
  7173. // reset the cached userIgnored anymatch fn
  7174. // to make ignoredPaths changes effective
  7175. this._userIgnored = undefined;
  7176. });
  7177. return this;
  7178. }
  7179. /**
  7180. * Close watchers and remove all listeners from watched paths.
  7181. * @returns {Promise<void>}.
  7182. */
  7183. close() {
  7184. if (this.closed) return this._closePromise;
  7185. this.closed = true;
  7186. // Memory management.
  7187. this.removeAllListeners();
  7188. const closers = [];
  7189. this._closers.forEach(closerList => closerList.forEach(closer => {
  7190. const promise = closer();
  7191. if (promise instanceof Promise) closers.push(promise);
  7192. }));
  7193. this._streams.forEach(stream => stream.destroy());
  7194. this._userIgnored = undefined;
  7195. this._readyCount = 0;
  7196. this._readyEmitted = false;
  7197. this._watched.forEach(dirent => dirent.dispose());
  7198. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  7199. this[`_${key}`].clear();
  7200. });
  7201. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  7202. return this._closePromise;
  7203. }
  7204. /**
  7205. * Expose list of watched paths
  7206. * @returns {Object} for chaining
  7207. */
  7208. getWatched() {
  7209. const watchList = {};
  7210. this._watched.forEach((entry, dir) => {
  7211. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  7212. watchList[key || ONE_DOT] = entry.getChildren().sort();
  7213. });
  7214. return watchList;
  7215. }
  7216. emitWithAll(event, args) {
  7217. this.emit(...args);
  7218. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  7219. }
  7220. // Common helpers
  7221. // --------------
  7222. /**
  7223. * Normalize and emit events.
  7224. * Calling _emit DOES NOT MEAN emit() would be called!
  7225. * @param {EventName} event Type of event
  7226. * @param {Path} path File or directory path
  7227. * @param {*=} val1 arguments to be passed with event
  7228. * @param {*=} val2
  7229. * @param {*=} val3
  7230. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  7231. */
  7232. async _emit(event, path, val1, val2, val3) {
  7233. if (this.closed) return;
  7234. const opts = this.options;
  7235. if (isWindows) path = sysPath.normalize(path);
  7236. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  7237. /** @type Array<any> */
  7238. const args = [event, path];
  7239. if (val3 !== undefined) args.push(val1, val2, val3);
  7240. else if (val2 !== undefined) args.push(val1, val2);
  7241. else if (val1 !== undefined) args.push(val1);
  7242. const awf = opts.awaitWriteFinish;
  7243. let pw;
  7244. if (awf && (pw = this._pendingWrites.get(path))) {
  7245. pw.lastChange = new Date();
  7246. return this;
  7247. }
  7248. if (opts.atomic) {
  7249. if (event === EV_UNLINK) {
  7250. this._pendingUnlinks.set(path, args);
  7251. setTimeout(() => {
  7252. this._pendingUnlinks.forEach((entry, path) => {
  7253. this.emit(...entry);
  7254. this.emit(EV_ALL, ...entry);
  7255. this._pendingUnlinks.delete(path);
  7256. });
  7257. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  7258. return this;
  7259. }
  7260. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  7261. event = args[0] = EV_CHANGE;
  7262. this._pendingUnlinks.delete(path);
  7263. }
  7264. }
  7265. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  7266. const awfEmit = (err, stats) => {
  7267. if (err) {
  7268. event = args[0] = EV_ERROR;
  7269. args[1] = err;
  7270. this.emitWithAll(event, args);
  7271. } else if (stats) {
  7272. // if stats doesn't exist the file must have been deleted
  7273. if (args.length > 2) {
  7274. args[2] = stats;
  7275. } else {
  7276. args.push(stats);
  7277. }
  7278. this.emitWithAll(event, args);
  7279. }
  7280. };
  7281. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  7282. return this;
  7283. }
  7284. if (event === EV_CHANGE) {
  7285. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  7286. if (isThrottled) return this;
  7287. }
  7288. if (opts.alwaysStat && val1 === undefined &&
  7289. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  7290. ) {
  7291. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  7292. let stats;
  7293. try {
  7294. stats = await stat(fullPath);
  7295. } catch (err) {}
  7296. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  7297. if (!stats || this.closed) return;
  7298. args.push(stats);
  7299. }
  7300. this.emitWithAll(event, args);
  7301. return this;
  7302. }
  7303. /**
  7304. * Common handler for errors
  7305. * @param {Error} error
  7306. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  7307. */
  7308. _handleError(error) {
  7309. const code = error && error.code;
  7310. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  7311. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  7312. ) {
  7313. this.emit(EV_ERROR, error);
  7314. }
  7315. return error || this.closed;
  7316. }
  7317. /**
  7318. * Helper utility for throttling
  7319. * @param {ThrottleType} actionType type being throttled
  7320. * @param {Path} path being acted upon
  7321. * @param {Number} timeout duration of time to suppress duplicate actions
  7322. * @returns {Object|false} tracking object or false if action should be suppressed
  7323. */
  7324. _throttle(actionType, path, timeout) {
  7325. if (!this._throttled.has(actionType)) {
  7326. this._throttled.set(actionType, new Map());
  7327. }
  7328. /** @type {Map<Path, Object>} */
  7329. const action = this._throttled.get(actionType);
  7330. /** @type {Object} */
  7331. const actionPath = action.get(path);
  7332. if (actionPath) {
  7333. actionPath.count++;
  7334. return false;
  7335. }
  7336. let timeoutObject;
  7337. const clear = () => {
  7338. const item = action.get(path);
  7339. const count = item ? item.count : 0;
  7340. action.delete(path);
  7341. clearTimeout(timeoutObject);
  7342. if (item) clearTimeout(item.timeoutObject);
  7343. return count;
  7344. };
  7345. timeoutObject = setTimeout(clear, timeout);
  7346. const thr = {timeoutObject, clear, count: 0};
  7347. action.set(path, thr);
  7348. return thr;
  7349. }
  7350. _incrReadyCount() {
  7351. return this._readyCount++;
  7352. }
  7353. /**
  7354. * Awaits write operation to finish.
  7355. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  7356. * @param {Path} path being acted upon
  7357. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  7358. * @param {EventName} event
  7359. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  7360. */
  7361. _awaitWriteFinish(path, threshold, event, awfEmit) {
  7362. let timeoutHandler;
  7363. let fullPath = path;
  7364. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  7365. fullPath = sysPath.join(this.options.cwd, path);
  7366. }
  7367. const now = new Date();
  7368. const awaitWriteFinish = (prevStat) => {
  7369. fs.stat(fullPath, (err, curStat) => {
  7370. if (err || !this._pendingWrites.has(path)) {
  7371. if (err && err.code !== 'ENOENT') awfEmit(err);
  7372. return;
  7373. }
  7374. const now = Number(new Date());
  7375. if (prevStat && curStat.size !== prevStat.size) {
  7376. this._pendingWrites.get(path).lastChange = now;
  7377. }
  7378. const pw = this._pendingWrites.get(path);
  7379. const df = now - pw.lastChange;
  7380. if (df >= threshold) {
  7381. this._pendingWrites.delete(path);
  7382. awfEmit(undefined, curStat);
  7383. } else {
  7384. timeoutHandler = setTimeout(
  7385. awaitWriteFinish,
  7386. this.options.awaitWriteFinish.pollInterval,
  7387. curStat
  7388. );
  7389. }
  7390. });
  7391. };
  7392. if (!this._pendingWrites.has(path)) {
  7393. this._pendingWrites.set(path, {
  7394. lastChange: now,
  7395. cancelWait: () => {
  7396. this._pendingWrites.delete(path);
  7397. clearTimeout(timeoutHandler);
  7398. return event;
  7399. }
  7400. });
  7401. timeoutHandler = setTimeout(
  7402. awaitWriteFinish,
  7403. this.options.awaitWriteFinish.pollInterval
  7404. );
  7405. }
  7406. }
  7407. _getGlobIgnored() {
  7408. return [...this._ignoredPaths.values()];
  7409. }
  7410. /**
  7411. * Determines whether user has asked to ignore this path.
  7412. * @param {Path} path filepath or dir
  7413. * @param {fs.Stats=} stats result of fs.stat
  7414. * @returns {Boolean}
  7415. */
  7416. _isIgnored(path, stats) {
  7417. if (this.options.atomic && DOT_RE.test(path)) return true;
  7418. if (!this._userIgnored) {
  7419. const {cwd} = this.options;
  7420. const ign = this.options.ignored;
  7421. const ignored = ign && ign.map(normalizeIgnored(cwd));
  7422. const paths = arrify(ignored)
  7423. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  7424. .map((path) => path + SLASH_GLOBSTAR);
  7425. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  7426. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  7427. }
  7428. return this._userIgnored([path, stats]);
  7429. }
  7430. _isntIgnored(path, stat) {
  7431. return !this._isIgnored(path, stat);
  7432. }
  7433. /**
  7434. * Provides a set of common helpers and properties relating to symlink and glob handling.
  7435. * @param {Path} path file, directory, or glob pattern being watched
  7436. * @param {Number=} depth at any depth > 0, this isn't a glob
  7437. * @returns {WatchHelper} object containing helpers for this path
  7438. */
  7439. _getWatchHelpers(path, depth) {
  7440. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  7441. const follow = this.options.followSymlinks;
  7442. return new WatchHelper(path, watchPath, follow, this);
  7443. }
  7444. // Directory helpers
  7445. // -----------------
  7446. /**
  7447. * Provides directory tracking objects
  7448. * @param {String} directory path of the directory
  7449. * @returns {DirEntry} the directory's tracking object
  7450. */
  7451. _getWatchedDir(directory) {
  7452. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  7453. const dir = sysPath.resolve(directory);
  7454. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  7455. return this._watched.get(dir);
  7456. }
  7457. // File helpers
  7458. // ------------
  7459. /**
  7460. * Check for read permissions.
  7461. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  7462. * @param {fs.Stats} stats - object, result of fs_stat
  7463. * @returns {Boolean} indicates whether the file can be read
  7464. */
  7465. _hasReadPermissions(stats) {
  7466. if (this.options.ignorePermissionErrors) return true;
  7467. // stats.mode may be bigint
  7468. const md = stats && Number.parseInt(stats.mode, 10);
  7469. const st = md & 0o777;
  7470. const it = Number.parseInt(st.toString(8)[0], 10);
  7471. return Boolean(4 & it);
  7472. }
  7473. /**
  7474. * Handles emitting unlink events for
  7475. * files and directories, and via recursion, for
  7476. * files and directories within directories that are unlinked
  7477. * @param {String} directory within which the following item is located
  7478. * @param {String} item base path of item/directory
  7479. * @returns {void}
  7480. */
  7481. _remove(directory, item, isDirectory) {
  7482. // if what is being deleted is a directory, get that directory's paths
  7483. // for recursive deleting and cleaning of watched object
  7484. // if it is not a directory, nestedDirectoryChildren will be empty array
  7485. const path = sysPath.join(directory, item);
  7486. const fullPath = sysPath.resolve(path);
  7487. isDirectory = isDirectory != null
  7488. ? isDirectory
  7489. : this._watched.has(path) || this._watched.has(fullPath);
  7490. // prevent duplicate handling in case of arriving here nearly simultaneously
  7491. // via multiple paths (such as _handleFile and _handleDir)
  7492. if (!this._throttle('remove', path, 100)) return;
  7493. // if the only watched file is removed, watch for its return
  7494. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  7495. this.add(directory, item, true);
  7496. }
  7497. // This will create a new entry in the watched object in either case
  7498. // so we got to do the directory check beforehand
  7499. const wp = this._getWatchedDir(path);
  7500. const nestedDirectoryChildren = wp.getChildren();
  7501. // Recursively remove children directories / files.
  7502. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  7503. // Check if item was on the watched list and remove it
  7504. const parent = this._getWatchedDir(directory);
  7505. const wasTracked = parent.has(item);
  7506. parent.remove(item);
  7507. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  7508. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  7509. // but never removed from the map in case the path was deleted.
  7510. // This leads to an incorrect state if the path was recreated:
  7511. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  7512. if (this._symlinkPaths.has(fullPath)) {
  7513. this._symlinkPaths.delete(fullPath);
  7514. }
  7515. // If we wait for this file to be fully written, cancel the wait.
  7516. let relPath = path;
  7517. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  7518. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  7519. const event = this._pendingWrites.get(relPath).cancelWait();
  7520. if (event === EV_ADD) return;
  7521. }
  7522. // The Entry will either be a directory that just got removed
  7523. // or a bogus entry to a file, in either case we have to remove it
  7524. this._watched.delete(path);
  7525. this._watched.delete(fullPath);
  7526. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  7527. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  7528. // Avoid conflicts if we later create another file with the same name
  7529. if (!this.options.useFsEvents) {
  7530. this._closePath(path);
  7531. }
  7532. }
  7533. /**
  7534. * Closes all watchers for a path
  7535. * @param {Path} path
  7536. */
  7537. _closePath(path) {
  7538. this._closeFile(path);
  7539. const dir = sysPath.dirname(path);
  7540. this._getWatchedDir(dir).remove(sysPath.basename(path));
  7541. }
  7542. /**
  7543. * Closes only file-specific watchers
  7544. * @param {Path} path
  7545. */
  7546. _closeFile(path) {
  7547. const closers = this._closers.get(path);
  7548. if (!closers) return;
  7549. closers.forEach(closer => closer());
  7550. this._closers.delete(path);
  7551. }
  7552. /**
  7553. *
  7554. * @param {Path} path
  7555. * @param {Function} closer
  7556. */
  7557. _addPathCloser(path, closer) {
  7558. if (!closer) return;
  7559. let list = this._closers.get(path);
  7560. if (!list) {
  7561. list = [];
  7562. this._closers.set(path, list);
  7563. }
  7564. list.push(closer);
  7565. }
  7566. _readdirp(root, opts) {
  7567. if (this.closed) return;
  7568. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  7569. let stream = readdirp(root, options);
  7570. this._streams.add(stream);
  7571. stream.once(STR_CLOSE, () => {
  7572. stream = undefined;
  7573. });
  7574. stream.once(STR_END, () => {
  7575. if (stream) {
  7576. this._streams.delete(stream);
  7577. stream = undefined;
  7578. }
  7579. });
  7580. return stream;
  7581. }
  7582. }
  7583. // Export FSWatcher class
  7584. chokidar$1.FSWatcher = FSWatcher;
  7585. /**
  7586. * Instantiates watcher with paths to be tracked.
  7587. * @param {String|Array<String>} paths file/directory paths and/or globs
  7588. * @param {Object=} options chokidar opts
  7589. * @returns an instance of FSWatcher for chaining.
  7590. */
  7591. const watch = (paths, options) => {
  7592. const watcher = new FSWatcher(options);
  7593. watcher.add(paths);
  7594. return watcher;
  7595. };
  7596. chokidar$1.watch = watch;
  7597. return chokidar$1;
  7598. }
  7599. var chokidarExports = /*@__PURE__*/ requireChokidar();
  7600. const chokidar = /*@__PURE__*/getDefaultExportFromCjs(chokidarExports);
  7601. class FileWatcher {
  7602. constructor(task, chokidarOptions) {
  7603. this.transformWatchers = new Map();
  7604. this.chokidarOptions = chokidarOptions;
  7605. this.task = task;
  7606. this.watcher = this.createWatcher(null);
  7607. }
  7608. close() {
  7609. this.watcher.close();
  7610. for (const watcher of this.transformWatchers.values()) {
  7611. watcher.close();
  7612. }
  7613. }
  7614. unwatch(id) {
  7615. this.watcher.unwatch(id);
  7616. const transformWatcher = this.transformWatchers.get(id);
  7617. if (transformWatcher) {
  7618. this.transformWatchers.delete(id);
  7619. transformWatcher.close();
  7620. }
  7621. }
  7622. watch(id, isTransformDependency) {
  7623. if (isTransformDependency) {
  7624. const watcher = this.transformWatchers.get(id) ?? this.createWatcher(id);
  7625. watcher.add(id);
  7626. this.transformWatchers.set(id, watcher);
  7627. }
  7628. else {
  7629. this.watcher.add(id);
  7630. }
  7631. }
  7632. createWatcher(transformWatcherId) {
  7633. const task = this.task;
  7634. const isLinux = platform() === 'linux';
  7635. const isFreeBSD = platform() === 'freebsd';
  7636. const isTransformDependency = transformWatcherId !== null;
  7637. const handleChange = (id, event) => {
  7638. const changedId = transformWatcherId || id;
  7639. if (isLinux || isFreeBSD) {
  7640. // unwatching and watching fixes an issue with chokidar where on certain systems,
  7641. // a file that was unlinked and immediately recreated would create a change event
  7642. // but then no longer any further events
  7643. watcher.unwatch(changedId);
  7644. watcher.add(changedId);
  7645. }
  7646. task.invalidate(changedId, { event, isTransformDependency });
  7647. };
  7648. const watcher = chokidar
  7649. .watch([], this.chokidarOptions)
  7650. .on('add', id => handleChange(id, 'create'))
  7651. .on('change', id => handleChange(id, 'update'))
  7652. .on('unlink', id => handleChange(id, 'delete'));
  7653. return watcher;
  7654. }
  7655. }
  7656. const eventsRewrites = {
  7657. create: {
  7658. create: 'buggy',
  7659. delete: null, //delete file from map
  7660. update: 'create'
  7661. },
  7662. delete: {
  7663. create: 'update',
  7664. delete: 'buggy',
  7665. update: 'buggy'
  7666. },
  7667. update: {
  7668. create: 'buggy',
  7669. delete: 'delete',
  7670. update: 'update'
  7671. }
  7672. };
  7673. class Watcher {
  7674. constructor(optionsList, emitter) {
  7675. this.buildDelay = 0;
  7676. this.buildTimeout = null;
  7677. this.closed = false;
  7678. this.invalidatedIds = new Map();
  7679. this.rerun = false;
  7680. this.running = true;
  7681. this.emitter = emitter;
  7682. emitter.close = this.close.bind(this);
  7683. this.tasks = optionsList.map(options => new Task(this, options));
  7684. for (const { watch } of optionsList) {
  7685. if (watch && typeof watch.buildDelay === 'number') {
  7686. this.buildDelay = Math.max(this.buildDelay, watch.buildDelay);
  7687. }
  7688. }
  7689. process$1.nextTick(() => this.run());
  7690. }
  7691. async close() {
  7692. if (this.closed)
  7693. return;
  7694. this.closed = true;
  7695. if (this.buildTimeout)
  7696. clearTimeout(this.buildTimeout);
  7697. for (const task of this.tasks) {
  7698. task.close();
  7699. }
  7700. await this.emitter.emit('close');
  7701. this.emitter.removeAllListeners();
  7702. }
  7703. invalidate(file) {
  7704. if (file) {
  7705. const previousEvent = this.invalidatedIds.get(file.id);
  7706. const event = previousEvent ? eventsRewrites[previousEvent][file.event] : file.event;
  7707. if (event === 'buggy') {
  7708. //TODO: throws or warn? Currently just ignore, uses new event
  7709. this.invalidatedIds.set(file.id, file.event);
  7710. }
  7711. else if (event === null) {
  7712. this.invalidatedIds.delete(file.id);
  7713. }
  7714. else {
  7715. this.invalidatedIds.set(file.id, event);
  7716. }
  7717. }
  7718. if (this.running) {
  7719. this.rerun = true;
  7720. return;
  7721. }
  7722. if (this.buildTimeout)
  7723. clearTimeout(this.buildTimeout);
  7724. this.buildTimeout = setTimeout(async () => {
  7725. this.buildTimeout = null;
  7726. try {
  7727. await Promise.all([...this.invalidatedIds].map(([id, event]) => this.emitter.emit('change', id, { event })));
  7728. this.invalidatedIds.clear();
  7729. await this.emitter.emit('restart');
  7730. this.emitter.removeListenersForCurrentRun();
  7731. this.run();
  7732. }
  7733. catch (error) {
  7734. this.invalidatedIds.clear();
  7735. await this.emitter.emit('event', {
  7736. code: 'ERROR',
  7737. error,
  7738. result: null
  7739. });
  7740. await this.emitter.emit('event', {
  7741. code: 'END'
  7742. });
  7743. }
  7744. }, this.buildDelay);
  7745. }
  7746. async run() {
  7747. this.running = true;
  7748. await this.emitter.emit('event', {
  7749. code: 'START'
  7750. });
  7751. for (const task of this.tasks) {
  7752. await task.run();
  7753. }
  7754. this.running = false;
  7755. await this.emitter.emit('event', {
  7756. code: 'END'
  7757. });
  7758. if (this.rerun) {
  7759. this.rerun = false;
  7760. this.invalidate();
  7761. }
  7762. }
  7763. }
  7764. class Task {
  7765. constructor(watcher, options) {
  7766. this.cache = { modules: [] };
  7767. this.watchFiles = [];
  7768. this.closed = false;
  7769. this.invalidated = true;
  7770. this.watched = new Set();
  7771. this.watcher = watcher;
  7772. this.options = options;
  7773. this.skipWrite = Boolean(options.watch && options.watch.skipWrite);
  7774. this.outputs = this.options.output;
  7775. this.outputFiles = this.outputs.map(output => {
  7776. if (output.file || output.dir)
  7777. return path.resolve(output.file || output.dir);
  7778. return undefined;
  7779. });
  7780. this.watchOptions = this.options.watch || {};
  7781. this.filter = createFilter(this.watchOptions.include, this.watchOptions.exclude);
  7782. this.fileWatcher = new FileWatcher(this, {
  7783. ...this.watchOptions.chokidar,
  7784. disableGlobbing: true,
  7785. ignoreInitial: true
  7786. });
  7787. }
  7788. close() {
  7789. this.closed = true;
  7790. this.fileWatcher.close();
  7791. }
  7792. invalidate(id, details) {
  7793. this.invalidated = true;
  7794. if (details.isTransformDependency) {
  7795. for (const module of this.cache.modules) {
  7796. if (!module.transformDependencies.includes(id))
  7797. continue;
  7798. // effective invalidation
  7799. module.originalCode = null;
  7800. }
  7801. }
  7802. this.watcher.invalidate({ event: details.event, id });
  7803. this.watchOptions.onInvalidate?.(id);
  7804. }
  7805. async run() {
  7806. if (!this.invalidated)
  7807. return;
  7808. this.invalidated = false;
  7809. const options = {
  7810. ...this.options,
  7811. cache: this.cache
  7812. };
  7813. const start = Date.now();
  7814. await this.watcher.emitter.emit('event', {
  7815. code: 'BUNDLE_START',
  7816. input: this.options.input,
  7817. output: this.outputFiles
  7818. });
  7819. let result = null;
  7820. try {
  7821. result = await rollupInternal(options, this.watcher.emitter);
  7822. if (this.closed) {
  7823. return;
  7824. }
  7825. this.updateWatchedFiles(result);
  7826. if (!this.skipWrite) {
  7827. await Promise.all(this.outputs.map(output => result.write(output)));
  7828. if (this.closed) {
  7829. return;
  7830. }
  7831. this.updateWatchedFiles(result);
  7832. }
  7833. await this.watcher.emitter.emit('event', {
  7834. code: 'BUNDLE_END',
  7835. duration: Date.now() - start,
  7836. input: this.options.input,
  7837. output: this.outputFiles,
  7838. result
  7839. });
  7840. }
  7841. catch (error) {
  7842. if (!this.closed) {
  7843. if (Array.isArray(error.watchFiles)) {
  7844. for (const id of error.watchFiles) {
  7845. this.watchFile(id);
  7846. }
  7847. }
  7848. if (error.id) {
  7849. this.cache.modules = this.cache.modules.filter(module => module.id !== error.id);
  7850. }
  7851. }
  7852. await this.watcher.emitter.emit('event', {
  7853. code: 'ERROR',
  7854. error,
  7855. result
  7856. });
  7857. }
  7858. }
  7859. updateWatchedFiles(result) {
  7860. const previouslyWatched = this.watched;
  7861. this.watched = new Set();
  7862. this.watchFiles = result.watchFiles;
  7863. this.cache = result.cache;
  7864. for (const id of this.watchFiles) {
  7865. this.watchFile(id);
  7866. }
  7867. for (const module of this.cache.modules) {
  7868. for (const depId of module.transformDependencies) {
  7869. this.watchFile(depId, true);
  7870. }
  7871. }
  7872. for (const id of previouslyWatched) {
  7873. if (!this.watched.has(id)) {
  7874. this.fileWatcher.unwatch(id);
  7875. }
  7876. }
  7877. }
  7878. watchFile(id, isTransformDependency = false) {
  7879. if (!this.filter(id))
  7880. return;
  7881. this.watched.add(id);
  7882. if (this.outputFiles.includes(id)) {
  7883. throw new Error('Cannot import the generated bundle');
  7884. }
  7885. // this is necessary to ensure that any 'renamed' files
  7886. // continue to be watched following an error
  7887. this.fileWatcher.watch(id, isTransformDependency);
  7888. }
  7889. }
  7890. export { Task, Watcher };