UNPKG

107 kBJavaScriptView Raw
1#!/usr/bin/env node
2'use strict';
3
4var tools_ts = require('../utils/index.js');
5var path$1 = require('path');
6var index_ts = require('../lib/index.js');
7var fs = require('fs');
8var index_ts$2 = require('../utils/parser/index.js');
9var index_ts$1 = require('../utils/style/index.js');
10var require$$0$1 = require('util');
11var require$$0$2 = require('events');
12var assert = require('assert');
13
14function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
15
16var path__default = /*#__PURE__*/_interopDefaultLegacy(path$1);
17var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
18var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
19var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
20var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
21
22const flagSymbol = Symbol('arg flag');
23
24class ArgError extends Error {
25 constructor(msg, code) {
26 super(msg);
27 this.name = 'ArgError';
28 this.code = code;
29
30 Object.setPrototypeOf(this, ArgError.prototype);
31 }
32}
33
34function arg(
35 opts,
36 {
37 argv = process.argv.slice(2),
38 permissive = false,
39 stopAtPositional = false
40 } = {}
41) {
42 if (!opts) {
43 throw new ArgError(
44 'argument specification object is required',
45 'ARG_CONFIG_NO_SPEC'
46 );
47 }
48
49 const result = { _: [] };
50
51 const aliases = {};
52 const handlers = {};
53
54 for (const key of Object.keys(opts)) {
55 if (!key) {
56 throw new ArgError(
57 'argument key cannot be an empty string',
58 'ARG_CONFIG_EMPTY_KEY'
59 );
60 }
61
62 if (key[0] !== '-') {
63 throw new ArgError(
64 `argument key must start with '-' but found: '${key}'`,
65 'ARG_CONFIG_NONOPT_KEY'
66 );
67 }
68
69 if (key.length === 1) {
70 throw new ArgError(
71 `argument key must have a name; singular '-' keys are not allowed: ${key}`,
72 'ARG_CONFIG_NONAME_KEY'
73 );
74 }
75
76 if (typeof opts[key] === 'string') {
77 aliases[key] = opts[key];
78 continue;
79 }
80
81 let type = opts[key];
82 let isFlag = false;
83
84 if (
85 Array.isArray(type) &&
86 type.length === 1 &&
87 typeof type[0] === 'function'
88 ) {
89 const [fn] = type;
90 type = (value, name, prev = []) => {
91 prev.push(fn(value, name, prev[prev.length - 1]));
92 return prev;
93 };
94 isFlag = fn === Boolean || fn[flagSymbol] === true;
95 } else if (typeof type === 'function') {
96 isFlag = type === Boolean || type[flagSymbol] === true;
97 } else {
98 throw new ArgError(
99 `type missing or not a function or valid array type: ${key}`,
100 'ARG_CONFIG_VAD_TYPE'
101 );
102 }
103
104 if (key[1] !== '-' && key.length > 2) {
105 throw new ArgError(
106 `short argument keys (with a single hyphen) must have only one character: ${key}`,
107 'ARG_CONFIG_SHORTOPT_TOOLONG'
108 );
109 }
110
111 handlers[key] = [type, isFlag];
112 }
113
114 for (let i = 0, len = argv.length; i < len; i++) {
115 const wholeArg = argv[i];
116
117 if (stopAtPositional && result._.length > 0) {
118 result._ = result._.concat(argv.slice(i));
119 break;
120 }
121
122 if (wholeArg === '--') {
123 result._ = result._.concat(argv.slice(i + 1));
124 break;
125 }
126
127 if (wholeArg.length > 1 && wholeArg[0] === '-') {
128 /* eslint-disable operator-linebreak */
129 const separatedArguments =
130 wholeArg[1] === '-' || wholeArg.length === 2
131 ? [wholeArg]
132 : wholeArg
133 .slice(1)
134 .split('')
135 .map((a) => `-${a}`);
136 /* eslint-enable operator-linebreak */
137
138 for (let j = 0; j < separatedArguments.length; j++) {
139 const arg = separatedArguments[j];
140 const [originalArgName, argStr] =
141 arg[1] === '-' ? arg.split(/=(.*)/, 2) : [arg, undefined];
142
143 let argName = originalArgName;
144 while (argName in aliases) {
145 argName = aliases[argName];
146 }
147
148 if (!(argName in handlers)) {
149 if (permissive) {
150 result._.push(arg);
151 continue;
152 } else {
153 throw new ArgError(
154 `unknown or unexpected option: ${originalArgName}`,
155 'ARG_UNKNOWN_OPTION'
156 );
157 }
158 }
159
160 const [type, isFlag] = handlers[argName];
161
162 if (!isFlag && j + 1 < separatedArguments.length) {
163 throw new ArgError(
164 `option requires argument (but was followed by another short argument): ${originalArgName}`,
165 'ARG_MISSING_REQUIRED_SHORTARG'
166 );
167 }
168
169 if (isFlag) {
170 result[argName] = type(true, argName, result[argName]);
171 } else if (argStr === undefined) {
172 if (
173 argv.length < i + 2 ||
174 (argv[i + 1].length > 1 &&
175 argv[i + 1][0] === '-' &&
176 !(
177 argv[i + 1].match(/^-?\d*(\.(?=\d))?\d*$/) &&
178 (type === Number ||
179 // eslint-disable-next-line no-undef
180 (typeof BigInt !== 'undefined' && type === BigInt))
181 ))
182 ) {
183 const extended =
184 originalArgName === argName ? '' : ` (alias for ${argName})`;
185 throw new ArgError(
186 `option requires argument: ${originalArgName}${extended}`,
187 'ARG_MISSING_REQUIRED_LONGARG'
188 );
189 }
190
191 result[argName] = type(argv[i + 1], argName, result[argName]);
192 ++i;
193 } else {
194 result[argName] = type(argStr, argName, result[argName]);
195 }
196 }
197 } else {
198 result._.push(wholeArg);
199 }
200 }
201
202 return result;
203}
204
205arg.flag = (fn) => {
206 fn[flagSymbol] = true;
207 return fn;
208};
209
210// Utility types
211arg.COUNT = arg.flag((v, name, existingCount) => (existingCount || 0) + 1);
212
213// Expose error class
214arg.ArgError = ArgError;
215
216var arg_1 = arg;
217
218// Copyright Joyent, Inc. and other Node contributors.
219//
220// Permission is hereby granted, free of charge, to any person obtaining a
221// copy of this software and associated documentation files (the
222// "Software"), to deal in the Software without restriction, including
223// without limitation the rights to use, copy, modify, merge, publish,
224// distribute, sublicense, and/or sell copies of the Software, and to permit
225// persons to whom the Software is furnished to do so, subject to the
226// following conditions:
227//
228// The above copyright notice and this permission notice shall be included
229// in all copies or substantial portions of the Software.
230//
231// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
232// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
233// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
234// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
235// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
236// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
237// USE OR OTHER DEALINGS IN THE SOFTWARE.
238
239
240var isWindows = process.platform === 'win32';
241
242
243// JavaScript implementation of realpath, ported from node pre-v6
244
245var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
246
247function rethrow() {
248 // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
249 // is fairly slow to generate.
250 var callback;
251 if (DEBUG) {
252 var backtrace = new Error;
253 callback = debugCallback;
254 } else
255 callback = missingCallback;
256
257 return callback;
258
259 function debugCallback(err) {
260 if (err) {
261 backtrace.message = err.message;
262 err = backtrace;
263 missingCallback(err);
264 }
265 }
266
267 function missingCallback(err) {
268 if (err) {
269 if (process.throwDeprecation)
270 throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
271 else if (!process.noDeprecation) {
272 var msg = 'fs: missing callback ' + (err.stack || err.message);
273 if (process.traceDeprecation)
274 console.trace(msg);
275 else
276 console.error(msg);
277 }
278 }
279 }
280}
281
282function maybeCallback(cb) {
283 return typeof cb === 'function' ? cb : rethrow();
284}
285
286path__default['default'].normalize;
287
288// Regexp that finds the next partion of a (partial) path
289// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
290if (isWindows) {
291 var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
292} else {
293 var nextPartRe = /(.*?)(?:[\/]+|$)/g;
294}
295
296// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
297if (isWindows) {
298 var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
299} else {
300 var splitRootRe = /^[\/]*/;
301}
302
303var realpathSync$1 = function realpathSync(p, cache) {
304 // make p is absolute
305 p = path__default['default'].resolve(p);
306
307 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
308 return cache[p];
309 }
310
311 var original = p,
312 seenLinks = {},
313 knownHard = {};
314
315 // current character position in p
316 var pos;
317 // the partial path so far, including a trailing slash if any
318 var current;
319 // the partial path without a trailing slash (except when pointing at a root)
320 var base;
321 // the partial path scanned in the previous round, with slash
322 var previous;
323
324 start();
325
326 function start() {
327 // Skip over roots
328 var m = splitRootRe.exec(p);
329 pos = m[0].length;
330 current = m[0];
331 base = m[0];
332 previous = '';
333
334 // On windows, check that the root exists. On unix there is no need.
335 if (isWindows && !knownHard[base]) {
336 fs__default['default'].lstatSync(base);
337 knownHard[base] = true;
338 }
339 }
340
341 // walk down the path, swapping out linked pathparts for their real
342 // values
343 // NB: p.length changes.
344 while (pos < p.length) {
345 // find the next part
346 nextPartRe.lastIndex = pos;
347 var result = nextPartRe.exec(p);
348 previous = current;
349 current += result[0];
350 base = previous + result[1];
351 pos = nextPartRe.lastIndex;
352
353 // continue if not a symlink
354 if (knownHard[base] || (cache && cache[base] === base)) {
355 continue;
356 }
357
358 var resolvedLink;
359 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
360 // some known symbolic link. no need to stat again.
361 resolvedLink = cache[base];
362 } else {
363 var stat = fs__default['default'].lstatSync(base);
364 if (!stat.isSymbolicLink()) {
365 knownHard[base] = true;
366 if (cache) cache[base] = base;
367 continue;
368 }
369
370 // read the link if it wasn't read before
371 // dev/ino always return 0 on windows, so skip the check.
372 var linkTarget = null;
373 if (!isWindows) {
374 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
375 if (seenLinks.hasOwnProperty(id)) {
376 linkTarget = seenLinks[id];
377 }
378 }
379 if (linkTarget === null) {
380 fs__default['default'].statSync(base);
381 linkTarget = fs__default['default'].readlinkSync(base);
382 }
383 resolvedLink = path__default['default'].resolve(previous, linkTarget);
384 // track this, if given a cache.
385 if (cache) cache[base] = resolvedLink;
386 if (!isWindows) seenLinks[id] = linkTarget;
387 }
388
389 // resolve the link, then start over
390 p = path__default['default'].resolve(resolvedLink, p.slice(pos));
391 start();
392 }
393
394 if (cache) cache[original] = p;
395
396 return p;
397};
398
399
400var realpath$1 = function realpath(p, cache, cb) {
401 if (typeof cb !== 'function') {
402 cb = maybeCallback(cache);
403 cache = null;
404 }
405
406 // make p is absolute
407 p = path__default['default'].resolve(p);
408
409 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
410 return process.nextTick(cb.bind(null, null, cache[p]));
411 }
412
413 var original = p,
414 seenLinks = {},
415 knownHard = {};
416
417 // current character position in p
418 var pos;
419 // the partial path so far, including a trailing slash if any
420 var current;
421 // the partial path without a trailing slash (except when pointing at a root)
422 var base;
423 // the partial path scanned in the previous round, with slash
424 var previous;
425
426 start();
427
428 function start() {
429 // Skip over roots
430 var m = splitRootRe.exec(p);
431 pos = m[0].length;
432 current = m[0];
433 base = m[0];
434 previous = '';
435
436 // On windows, check that the root exists. On unix there is no need.
437 if (isWindows && !knownHard[base]) {
438 fs__default['default'].lstat(base, function(err) {
439 if (err) return cb(err);
440 knownHard[base] = true;
441 LOOP();
442 });
443 } else {
444 process.nextTick(LOOP);
445 }
446 }
447
448 // walk down the path, swapping out linked pathparts for their real
449 // values
450 function LOOP() {
451 // stop if scanned past end of path
452 if (pos >= p.length) {
453 if (cache) cache[original] = p;
454 return cb(null, p);
455 }
456
457 // find the next part
458 nextPartRe.lastIndex = pos;
459 var result = nextPartRe.exec(p);
460 previous = current;
461 current += result[0];
462 base = previous + result[1];
463 pos = nextPartRe.lastIndex;
464
465 // continue if not a symlink
466 if (knownHard[base] || (cache && cache[base] === base)) {
467 return process.nextTick(LOOP);
468 }
469
470 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
471 // known symbolic link. no need to stat again.
472 return gotResolvedLink(cache[base]);
473 }
474
475 return fs__default['default'].lstat(base, gotStat);
476 }
477
478 function gotStat(err, stat) {
479 if (err) return cb(err);
480
481 // if not a symlink, skip to the next path part
482 if (!stat.isSymbolicLink()) {
483 knownHard[base] = true;
484 if (cache) cache[base] = base;
485 return process.nextTick(LOOP);
486 }
487
488 // stat & read the link if not read before
489 // call gotTarget as soon as the link target is known
490 // dev/ino always return 0 on windows, so skip the check.
491 if (!isWindows) {
492 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
493 if (seenLinks.hasOwnProperty(id)) {
494 return gotTarget(null, seenLinks[id], base);
495 }
496 }
497 fs__default['default'].stat(base, function(err) {
498 if (err) return cb(err);
499
500 fs__default['default'].readlink(base, function(err, target) {
501 if (!isWindows) seenLinks[id] = target;
502 gotTarget(err, target);
503 });
504 });
505 }
506
507 function gotTarget(err, target, base) {
508 if (err) return cb(err);
509
510 var resolvedLink = path__default['default'].resolve(previous, target);
511 if (cache) cache[base] = resolvedLink;
512 gotResolvedLink(resolvedLink);
513 }
514
515 function gotResolvedLink(resolvedLink) {
516 // resolve the link, then start over
517 p = path__default['default'].resolve(resolvedLink, p.slice(pos));
518 start();
519 }
520};
521
522var old = {
523 realpathSync: realpathSync$1,
524 realpath: realpath$1
525};
526
527var fs_realpath = realpath;
528realpath.realpath = realpath;
529realpath.sync = realpathSync;
530realpath.realpathSync = realpathSync;
531realpath.monkeypatch = monkeypatch;
532realpath.unmonkeypatch = unmonkeypatch;
533
534
535var origRealpath = fs__default['default'].realpath;
536var origRealpathSync = fs__default['default'].realpathSync;
537
538var version = process.version;
539var ok = /^v[0-5]\./.test(version);
540
541
542function newError (er) {
543 return er && er.syscall === 'realpath' && (
544 er.code === 'ELOOP' ||
545 er.code === 'ENOMEM' ||
546 er.code === 'ENAMETOOLONG'
547 )
548}
549
550function realpath (p, cache, cb) {
551 if (ok) {
552 return origRealpath(p, cache, cb)
553 }
554
555 if (typeof cache === 'function') {
556 cb = cache;
557 cache = null;
558 }
559 origRealpath(p, cache, function (er, result) {
560 if (newError(er)) {
561 old.realpath(p, cache, cb);
562 } else {
563 cb(er, result);
564 }
565 });
566}
567
568function realpathSync (p, cache) {
569 if (ok) {
570 return origRealpathSync(p, cache)
571 }
572
573 try {
574 return origRealpathSync(p, cache)
575 } catch (er) {
576 if (newError(er)) {
577 return old.realpathSync(p, cache)
578 } else {
579 throw er
580 }
581 }
582}
583
584function monkeypatch () {
585 fs__default['default'].realpath = realpath;
586 fs__default['default'].realpathSync = realpathSync;
587}
588
589function unmonkeypatch () {
590 fs__default['default'].realpath = origRealpath;
591 fs__default['default'].realpathSync = origRealpathSync;
592}
593
594var concatMap = function (xs, fn) {
595 var res = [];
596 for (var i = 0; i < xs.length; i++) {
597 var x = fn(xs[i], i);
598 if (isArray(x)) res.push.apply(res, x);
599 else res.push(x);
600 }
601 return res;
602};
603
604var isArray = Array.isArray || function (xs) {
605 return Object.prototype.toString.call(xs) === '[object Array]';
606};
607
608var balancedMatch = balanced;
609function balanced(a, b, str) {
610 if (a instanceof RegExp) a = maybeMatch(a, str);
611 if (b instanceof RegExp) b = maybeMatch(b, str);
612
613 var r = range(a, b, str);
614
615 return r && {
616 start: r[0],
617 end: r[1],
618 pre: str.slice(0, r[0]),
619 body: str.slice(r[0] + a.length, r[1]),
620 post: str.slice(r[1] + b.length)
621 };
622}
623
624function maybeMatch(reg, str) {
625 var m = str.match(reg);
626 return m ? m[0] : null;
627}
628
629balanced.range = range;
630function range(a, b, str) {
631 var begs, beg, left, right, result;
632 var ai = str.indexOf(a);
633 var bi = str.indexOf(b, ai + 1);
634 var i = ai;
635
636 if (ai >= 0 && bi > 0) {
637 if(a===b) {
638 return [ai, bi];
639 }
640 begs = [];
641 left = str.length;
642
643 while (i >= 0 && !result) {
644 if (i == ai) {
645 begs.push(i);
646 ai = str.indexOf(a, i + 1);
647 } else if (begs.length == 1) {
648 result = [ begs.pop(), bi ];
649 } else {
650 beg = begs.pop();
651 if (beg < left) {
652 left = beg;
653 right = bi;
654 }
655
656 bi = str.indexOf(b, i + 1);
657 }
658
659 i = ai < bi && ai >= 0 ? ai : bi;
660 }
661
662 if (begs.length) {
663 result = [ left, right ];
664 }
665 }
666
667 return result;
668}
669
670var braceExpansion = expandTop;
671
672var escSlash = '\0SLASH'+Math.random()+'\0';
673var escOpen = '\0OPEN'+Math.random()+'\0';
674var escClose = '\0CLOSE'+Math.random()+'\0';
675var escComma = '\0COMMA'+Math.random()+'\0';
676var escPeriod = '\0PERIOD'+Math.random()+'\0';
677
678function numeric(str) {
679 return parseInt(str, 10) == str
680 ? parseInt(str, 10)
681 : str.charCodeAt(0);
682}
683
684function escapeBraces(str) {
685 return str.split('\\\\').join(escSlash)
686 .split('\\{').join(escOpen)
687 .split('\\}').join(escClose)
688 .split('\\,').join(escComma)
689 .split('\\.').join(escPeriod);
690}
691
692function unescapeBraces(str) {
693 return str.split(escSlash).join('\\')
694 .split(escOpen).join('{')
695 .split(escClose).join('}')
696 .split(escComma).join(',')
697 .split(escPeriod).join('.');
698}
699
700
701// Basically just str.split(","), but handling cases
702// where we have nested braced sections, which should be
703// treated as individual members, like {a,{b,c},d}
704function parseCommaParts(str) {
705 if (!str)
706 return [''];
707
708 var parts = [];
709 var m = balancedMatch('{', '}', str);
710
711 if (!m)
712 return str.split(',');
713
714 var pre = m.pre;
715 var body = m.body;
716 var post = m.post;
717 var p = pre.split(',');
718
719 p[p.length-1] += '{' + body + '}';
720 var postParts = parseCommaParts(post);
721 if (post.length) {
722 p[p.length-1] += postParts.shift();
723 p.push.apply(p, postParts);
724 }
725
726 parts.push.apply(parts, p);
727
728 return parts;
729}
730
731function expandTop(str) {
732 if (!str)
733 return [];
734
735 // I don't know why Bash 4.3 does this, but it does.
736 // Anything starting with {} will have the first two bytes preserved
737 // but *only* at the top level, so {},a}b will not expand to anything,
738 // but a{},b}c will be expanded to [a}c,abc].
739 // One could argue that this is a bug in Bash, but since the goal of
740 // this module is to match Bash's rules, we escape a leading {}
741 if (str.substr(0, 2) === '{}') {
742 str = '\\{\\}' + str.substr(2);
743 }
744
745 return expand(escapeBraces(str), true).map(unescapeBraces);
746}
747
748function embrace(str) {
749 return '{' + str + '}';
750}
751function isPadded(el) {
752 return /^-?0\d/.test(el);
753}
754
755function lte(i, y) {
756 return i <= y;
757}
758function gte(i, y) {
759 return i >= y;
760}
761
762function expand(str, isTop) {
763 var expansions = [];
764
765 var m = balancedMatch('{', '}', str);
766 if (!m || /\$$/.test(m.pre)) return [str];
767
768 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
769 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
770 var isSequence = isNumericSequence || isAlphaSequence;
771 var isOptions = m.body.indexOf(',') >= 0;
772 if (!isSequence && !isOptions) {
773 // {a},b}
774 if (m.post.match(/,.*\}/)) {
775 str = m.pre + '{' + m.body + escClose + m.post;
776 return expand(str);
777 }
778 return [str];
779 }
780
781 var n;
782 if (isSequence) {
783 n = m.body.split(/\.\./);
784 } else {
785 n = parseCommaParts(m.body);
786 if (n.length === 1) {
787 // x{{a,b}}y ==> x{a}y x{b}y
788 n = expand(n[0], false).map(embrace);
789 if (n.length === 1) {
790 var post = m.post.length
791 ? expand(m.post, false)
792 : [''];
793 return post.map(function(p) {
794 return m.pre + n[0] + p;
795 });
796 }
797 }
798 }
799
800 // at this point, n is the parts, and we know it's not a comma set
801 // with a single entry.
802
803 // no need to expand pre, since it is guaranteed to be free of brace-sets
804 var pre = m.pre;
805 var post = m.post.length
806 ? expand(m.post, false)
807 : [''];
808
809 var N;
810
811 if (isSequence) {
812 var x = numeric(n[0]);
813 var y = numeric(n[1]);
814 var width = Math.max(n[0].length, n[1].length);
815 var incr = n.length == 3
816 ? Math.abs(numeric(n[2]))
817 : 1;
818 var test = lte;
819 var reverse = y < x;
820 if (reverse) {
821 incr *= -1;
822 test = gte;
823 }
824 var pad = n.some(isPadded);
825
826 N = [];
827
828 for (var i = x; test(i, y); i += incr) {
829 var c;
830 if (isAlphaSequence) {
831 c = String.fromCharCode(i);
832 if (c === '\\')
833 c = '';
834 } else {
835 c = String(i);
836 if (pad) {
837 var need = width - c.length;
838 if (need > 0) {
839 var z = new Array(need + 1).join('0');
840 if (i < 0)
841 c = '-' + z + c.slice(1);
842 else
843 c = z + c;
844 }
845 }
846 }
847 N.push(c);
848 }
849 } else {
850 N = concatMap(n, function(el) { return expand(el, false) });
851 }
852
853 for (var j = 0; j < N.length; j++) {
854 for (var k = 0; k < post.length; k++) {
855 var expansion = pre + N[j] + post[k];
856 if (!isTop || isSequence || expansion)
857 expansions.push(expansion);
858 }
859 }
860
861 return expansions;
862}
863
864var minimatch_1 = minimatch;
865minimatch.Minimatch = Minimatch$1;
866
867var path = { sep: '/' };
868try {
869 path = path__default['default'];
870} catch (er) {}
871
872var GLOBSTAR = minimatch.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
873
874
875var plTypes = {
876 '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
877 '?': { open: '(?:', close: ')?' },
878 '+': { open: '(?:', close: ')+' },
879 '*': { open: '(?:', close: ')*' },
880 '@': { open: '(?:', close: ')' }
881};
882
883// any single thing other than /
884// don't need to escape / when using new RegExp()
885var qmark = '[^/]';
886
887// * => any number of characters
888var star = qmark + '*?';
889
890// ** when dots are allowed. Anything goes, except .. and .
891// not (^ or / followed by one or two dots followed by $ or /),
892// followed by anything, any number of times.
893var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
894
895// not a ^ or / followed by a dot,
896// followed by anything, any number of times.
897var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
898
899// characters that need to be escaped in RegExp.
900var reSpecials = charSet('().*{}+?[]^$\\!');
901
902// "abc" -> { a:true, b:true, c:true }
903function charSet (s) {
904 return s.split('').reduce(function (set, c) {
905 set[c] = true;
906 return set
907 }, {})
908}
909
910// normalizes slashes.
911var slashSplit = /\/+/;
912
913minimatch.filter = filter;
914function filter (pattern, options) {
915 options = options || {};
916 return function (p, i, list) {
917 return minimatch(p, pattern, options)
918 }
919}
920
921function ext (a, b) {
922 a = a || {};
923 b = b || {};
924 var t = {};
925 Object.keys(b).forEach(function (k) {
926 t[k] = b[k];
927 });
928 Object.keys(a).forEach(function (k) {
929 t[k] = a[k];
930 });
931 return t
932}
933
934minimatch.defaults = function (def) {
935 if (!def || !Object.keys(def).length) return minimatch
936
937 var orig = minimatch;
938
939 var m = function minimatch (p, pattern, options) {
940 return orig.minimatch(p, pattern, ext(def, options))
941 };
942
943 m.Minimatch = function Minimatch (pattern, options) {
944 return new orig.Minimatch(pattern, ext(def, options))
945 };
946
947 return m
948};
949
950Minimatch$1.defaults = function (def) {
951 if (!def || !Object.keys(def).length) return Minimatch$1
952 return minimatch.defaults(def).Minimatch
953};
954
955function minimatch (p, pattern, options) {
956 if (typeof pattern !== 'string') {
957 throw new TypeError('glob pattern string required')
958 }
959
960 if (!options) options = {};
961
962 // shortcut: comments match nothing.
963 if (!options.nocomment && pattern.charAt(0) === '#') {
964 return false
965 }
966
967 // "" only matches ""
968 if (pattern.trim() === '') return p === ''
969
970 return new Minimatch$1(pattern, options).match(p)
971}
972
973function Minimatch$1 (pattern, options) {
974 if (!(this instanceof Minimatch$1)) {
975 return new Minimatch$1(pattern, options)
976 }
977
978 if (typeof pattern !== 'string') {
979 throw new TypeError('glob pattern string required')
980 }
981
982 if (!options) options = {};
983 pattern = pattern.trim();
984
985 // windows support: need to use /, not \
986 if (path.sep !== '/') {
987 pattern = pattern.split(path.sep).join('/');
988 }
989
990 this.options = options;
991 this.set = [];
992 this.pattern = pattern;
993 this.regexp = null;
994 this.negate = false;
995 this.comment = false;
996 this.empty = false;
997
998 // make the set of regexps etc.
999 this.make();
1000}
1001
1002Minimatch$1.prototype.debug = function () {};
1003
1004Minimatch$1.prototype.make = make;
1005function make () {
1006 // don't do it more than once.
1007 if (this._made) return
1008
1009 var pattern = this.pattern;
1010 var options = this.options;
1011
1012 // empty patterns and comments match nothing.
1013 if (!options.nocomment && pattern.charAt(0) === '#') {
1014 this.comment = true;
1015 return
1016 }
1017 if (!pattern) {
1018 this.empty = true;
1019 return
1020 }
1021
1022 // step 1: figure out negation, etc.
1023 this.parseNegate();
1024
1025 // step 2: expand braces
1026 var set = this.globSet = this.braceExpand();
1027
1028 if (options.debug) this.debug = console.error;
1029
1030 this.debug(this.pattern, set);
1031
1032 // step 3: now we have a set, so turn each one into a series of path-portion
1033 // matching patterns.
1034 // These will be regexps, except in the case of "**", which is
1035 // set to the GLOBSTAR object for globstar behavior,
1036 // and will not contain any / characters
1037 set = this.globParts = set.map(function (s) {
1038 return s.split(slashSplit)
1039 });
1040
1041 this.debug(this.pattern, set);
1042
1043 // glob --> regexps
1044 set = set.map(function (s, si, set) {
1045 return s.map(this.parse, this)
1046 }, this);
1047
1048 this.debug(this.pattern, set);
1049
1050 // filter out everything that didn't compile properly.
1051 set = set.filter(function (s) {
1052 return s.indexOf(false) === -1
1053 });
1054
1055 this.debug(this.pattern, set);
1056
1057 this.set = set;
1058}
1059
1060Minimatch$1.prototype.parseNegate = parseNegate;
1061function parseNegate () {
1062 var pattern = this.pattern;
1063 var negate = false;
1064 var options = this.options;
1065 var negateOffset = 0;
1066
1067 if (options.nonegate) return
1068
1069 for (var i = 0, l = pattern.length
1070 ; i < l && pattern.charAt(i) === '!'
1071 ; i++) {
1072 negate = !negate;
1073 negateOffset++;
1074 }
1075
1076 if (negateOffset) this.pattern = pattern.substr(negateOffset);
1077 this.negate = negate;
1078}
1079
1080// Brace expansion:
1081// a{b,c}d -> abd acd
1082// a{b,}c -> abc ac
1083// a{0..3}d -> a0d a1d a2d a3d
1084// a{b,c{d,e}f}g -> abg acdfg acefg
1085// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
1086//
1087// Invalid sets are not expanded.
1088// a{2..}b -> a{2..}b
1089// a{b}c -> a{b}c
1090minimatch.braceExpand = function (pattern, options) {
1091 return braceExpand(pattern, options)
1092};
1093
1094Minimatch$1.prototype.braceExpand = braceExpand;
1095
1096function braceExpand (pattern, options) {
1097 if (!options) {
1098 if (this instanceof Minimatch$1) {
1099 options = this.options;
1100 } else {
1101 options = {};
1102 }
1103 }
1104
1105 pattern = typeof pattern === 'undefined'
1106 ? this.pattern : pattern;
1107
1108 if (typeof pattern === 'undefined') {
1109 throw new TypeError('undefined pattern')
1110 }
1111
1112 if (options.nobrace ||
1113 !pattern.match(/\{.*\}/)) {
1114 // shortcut. no need to expand.
1115 return [pattern]
1116 }
1117
1118 return braceExpansion(pattern)
1119}
1120
1121// parse a component of the expanded set.
1122// At this point, no pattern may contain "/" in it
1123// so we're going to return a 2d array, where each entry is the full
1124// pattern, split on '/', and then turned into a regular expression.
1125// A regexp is made at the end which joins each array with an
1126// escaped /, and another full one which joins each regexp with |.
1127//
1128// Following the lead of Bash 4.1, note that "**" only has special meaning
1129// when it is the *only* thing in a path portion. Otherwise, any series
1130// of * is equivalent to a single *. Globstar behavior is enabled by
1131// default, and can be disabled by setting options.noglobstar.
1132Minimatch$1.prototype.parse = parse;
1133var SUBPARSE = {};
1134function parse (pattern, isSub) {
1135 if (pattern.length > 1024 * 64) {
1136 throw new TypeError('pattern is too long')
1137 }
1138
1139 var options = this.options;
1140
1141 // shortcuts
1142 if (!options.noglobstar && pattern === '**') return GLOBSTAR
1143 if (pattern === '') return ''
1144
1145 var re = '';
1146 var hasMagic = !!options.nocase;
1147 var escaping = false;
1148 // ? => one single character
1149 var patternListStack = [];
1150 var negativeLists = [];
1151 var stateChar;
1152 var inClass = false;
1153 var reClassStart = -1;
1154 var classStart = -1;
1155 // . and .. never match anything that doesn't start with .,
1156 // even when options.dot is set.
1157 var patternStart = pattern.charAt(0) === '.' ? '' // anything
1158 // not (start or / followed by . or .. followed by / or end)
1159 : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
1160 : '(?!\\.)';
1161 var self = this;
1162
1163 function clearStateChar () {
1164 if (stateChar) {
1165 // we had some state-tracking character
1166 // that wasn't consumed by this pass.
1167 switch (stateChar) {
1168 case '*':
1169 re += star;
1170 hasMagic = true;
1171 break
1172 case '?':
1173 re += qmark;
1174 hasMagic = true;
1175 break
1176 default:
1177 re += '\\' + stateChar;
1178 break
1179 }
1180 self.debug('clearStateChar %j %j', stateChar, re);
1181 stateChar = false;
1182 }
1183 }
1184
1185 for (var i = 0, len = pattern.length, c
1186 ; (i < len) && (c = pattern.charAt(i))
1187 ; i++) {
1188 this.debug('%s\t%s %s %j', pattern, i, re, c);
1189
1190 // skip over any that are escaped.
1191 if (escaping && reSpecials[c]) {
1192 re += '\\' + c;
1193 escaping = false;
1194 continue
1195 }
1196
1197 switch (c) {
1198 case '/':
1199 // completely not allowed, even escaped.
1200 // Should already be path-split by now.
1201 return false
1202
1203 case '\\':
1204 clearStateChar();
1205 escaping = true;
1206 continue
1207
1208 // the various stateChar values
1209 // for the "extglob" stuff.
1210 case '?':
1211 case '*':
1212 case '+':
1213 case '@':
1214 case '!':
1215 this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
1216
1217 // all of those are literals inside a class, except that
1218 // the glob [!a] means [^a] in regexp
1219 if (inClass) {
1220 this.debug(' in class');
1221 if (c === '!' && i === classStart + 1) c = '^';
1222 re += c;
1223 continue
1224 }
1225
1226 // if we already have a stateChar, then it means
1227 // that there was something like ** or +? in there.
1228 // Handle the stateChar, then proceed with this one.
1229 self.debug('call clearStateChar %j', stateChar);
1230 clearStateChar();
1231 stateChar = c;
1232 // if extglob is disabled, then +(asdf|foo) isn't a thing.
1233 // just clear the statechar *now*, rather than even diving into
1234 // the patternList stuff.
1235 if (options.noext) clearStateChar();
1236 continue
1237
1238 case '(':
1239 if (inClass) {
1240 re += '(';
1241 continue
1242 }
1243
1244 if (!stateChar) {
1245 re += '\\(';
1246 continue
1247 }
1248
1249 patternListStack.push({
1250 type: stateChar,
1251 start: i - 1,
1252 reStart: re.length,
1253 open: plTypes[stateChar].open,
1254 close: plTypes[stateChar].close
1255 });
1256 // negation is (?:(?!js)[^/]*)
1257 re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
1258 this.debug('plType %j %j', stateChar, re);
1259 stateChar = false;
1260 continue
1261
1262 case ')':
1263 if (inClass || !patternListStack.length) {
1264 re += '\\)';
1265 continue
1266 }
1267
1268 clearStateChar();
1269 hasMagic = true;
1270 var pl = patternListStack.pop();
1271 // negation is (?:(?!js)[^/]*)
1272 // The others are (?:<pattern>)<type>
1273 re += pl.close;
1274 if (pl.type === '!') {
1275 negativeLists.push(pl);
1276 }
1277 pl.reEnd = re.length;
1278 continue
1279
1280 case '|':
1281 if (inClass || !patternListStack.length || escaping) {
1282 re += '\\|';
1283 escaping = false;
1284 continue
1285 }
1286
1287 clearStateChar();
1288 re += '|';
1289 continue
1290
1291 // these are mostly the same in regexp and glob
1292 case '[':
1293 // swallow any state-tracking char before the [
1294 clearStateChar();
1295
1296 if (inClass) {
1297 re += '\\' + c;
1298 continue
1299 }
1300
1301 inClass = true;
1302 classStart = i;
1303 reClassStart = re.length;
1304 re += c;
1305 continue
1306
1307 case ']':
1308 // a right bracket shall lose its special
1309 // meaning and represent itself in
1310 // a bracket expression if it occurs
1311 // first in the list. -- POSIX.2 2.8.3.2
1312 if (i === classStart + 1 || !inClass) {
1313 re += '\\' + c;
1314 escaping = false;
1315 continue
1316 }
1317
1318 // handle the case where we left a class open.
1319 // "[z-a]" is valid, equivalent to "\[z-a\]"
1320 if (inClass) {
1321 // split where the last [ was, make sure we don't have
1322 // an invalid re. if so, re-walk the contents of the
1323 // would-be class to re-translate any characters that
1324 // were passed through as-is
1325 // TODO: It would probably be faster to determine this
1326 // without a try/catch and a new RegExp, but it's tricky
1327 // to do safely. For now, this is safe and works.
1328 var cs = pattern.substring(classStart + 1, i);
1329 try {
1330 RegExp('[' + cs + ']');
1331 } catch (er) {
1332 // not a valid class!
1333 var sp = this.parse(cs, SUBPARSE);
1334 re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
1335 hasMagic = hasMagic || sp[1];
1336 inClass = false;
1337 continue
1338 }
1339 }
1340
1341 // finish up the class.
1342 hasMagic = true;
1343 inClass = false;
1344 re += c;
1345 continue
1346
1347 default:
1348 // swallow any state char that wasn't consumed
1349 clearStateChar();
1350
1351 if (escaping) {
1352 // no need
1353 escaping = false;
1354 } else if (reSpecials[c]
1355 && !(c === '^' && inClass)) {
1356 re += '\\';
1357 }
1358
1359 re += c;
1360
1361 } // switch
1362 } // for
1363
1364 // handle the case where we left a class open.
1365 // "[abc" is valid, equivalent to "\[abc"
1366 if (inClass) {
1367 // split where the last [ was, and escape it
1368 // this is a huge pita. We now have to re-walk
1369 // the contents of the would-be class to re-translate
1370 // any characters that were passed through as-is
1371 cs = pattern.substr(classStart + 1);
1372 sp = this.parse(cs, SUBPARSE);
1373 re = re.substr(0, reClassStart) + '\\[' + sp[0];
1374 hasMagic = hasMagic || sp[1];
1375 }
1376
1377 // handle the case where we had a +( thing at the *end*
1378 // of the pattern.
1379 // each pattern list stack adds 3 chars, and we need to go through
1380 // and escape any | chars that were passed through as-is for the regexp.
1381 // Go through and escape them, taking care not to double-escape any
1382 // | chars that were already escaped.
1383 for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
1384 var tail = re.slice(pl.reStart + pl.open.length);
1385 this.debug('setting tail', re, pl);
1386 // maybe some even number of \, then maybe 1 \, followed by a |
1387 tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
1388 if (!$2) {
1389 // the | isn't already escaped, so escape it.
1390 $2 = '\\';
1391 }
1392
1393 // need to escape all those slashes *again*, without escaping the
1394 // one that we need for escaping the | character. As it works out,
1395 // escaping an even number of slashes can be done by simply repeating
1396 // it exactly after itself. That's why this trick works.
1397 //
1398 // I am sorry that you have to see this.
1399 return $1 + $1 + $2 + '|'
1400 });
1401
1402 this.debug('tail=%j\n %s', tail, tail, pl, re);
1403 var t = pl.type === '*' ? star
1404 : pl.type === '?' ? qmark
1405 : '\\' + pl.type;
1406
1407 hasMagic = true;
1408 re = re.slice(0, pl.reStart) + t + '\\(' + tail;
1409 }
1410
1411 // handle trailing things that only matter at the very end.
1412 clearStateChar();
1413 if (escaping) {
1414 // trailing \\
1415 re += '\\\\';
1416 }
1417
1418 // only need to apply the nodot start if the re starts with
1419 // something that could conceivably capture a dot
1420 var addPatternStart = false;
1421 switch (re.charAt(0)) {
1422 case '.':
1423 case '[':
1424 case '(': addPatternStart = true;
1425 }
1426
1427 // Hack to work around lack of negative lookbehind in JS
1428 // A pattern like: *.!(x).!(y|z) needs to ensure that a name
1429 // like 'a.xyz.yz' doesn't match. So, the first negative
1430 // lookahead, has to look ALL the way ahead, to the end of
1431 // the pattern.
1432 for (var n = negativeLists.length - 1; n > -1; n--) {
1433 var nl = negativeLists[n];
1434
1435 var nlBefore = re.slice(0, nl.reStart);
1436 var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
1437 var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
1438 var nlAfter = re.slice(nl.reEnd);
1439
1440 nlLast += nlAfter;
1441
1442 // Handle nested stuff like *(*.js|!(*.json)), where open parens
1443 // mean that we should *not* include the ) in the bit that is considered
1444 // "after" the negated section.
1445 var openParensBefore = nlBefore.split('(').length - 1;
1446 var cleanAfter = nlAfter;
1447 for (i = 0; i < openParensBefore; i++) {
1448 cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
1449 }
1450 nlAfter = cleanAfter;
1451
1452 var dollar = '';
1453 if (nlAfter === '' && isSub !== SUBPARSE) {
1454 dollar = '$';
1455 }
1456 var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
1457 re = newRe;
1458 }
1459
1460 // if the re is not "" at this point, then we need to make sure
1461 // it doesn't match against an empty path part.
1462 // Otherwise a/* will match a/, which it should not.
1463 if (re !== '' && hasMagic) {
1464 re = '(?=.)' + re;
1465 }
1466
1467 if (addPatternStart) {
1468 re = patternStart + re;
1469 }
1470
1471 // parsing just a piece of a larger pattern.
1472 if (isSub === SUBPARSE) {
1473 return [re, hasMagic]
1474 }
1475
1476 // skip the regexp for non-magical patterns
1477 // unescape anything in it, though, so that it'll be
1478 // an exact match against a file etc.
1479 if (!hasMagic) {
1480 return globUnescape(pattern)
1481 }
1482
1483 var flags = options.nocase ? 'i' : '';
1484 try {
1485 var regExp = new RegExp('^' + re + '$', flags);
1486 } catch (er) {
1487 // If it was an invalid regular expression, then it can't match
1488 // anything. This trick looks for a character after the end of
1489 // the string, which is of course impossible, except in multi-line
1490 // mode, but it's not a /m regex.
1491 return new RegExp('$.')
1492 }
1493
1494 regExp._glob = pattern;
1495 regExp._src = re;
1496
1497 return regExp
1498}
1499
1500minimatch.makeRe = function (pattern, options) {
1501 return new Minimatch$1(pattern, options || {}).makeRe()
1502};
1503
1504Minimatch$1.prototype.makeRe = makeRe;
1505function makeRe () {
1506 if (this.regexp || this.regexp === false) return this.regexp
1507
1508 // at this point, this.set is a 2d array of partial
1509 // pattern strings, or "**".
1510 //
1511 // It's better to use .match(). This function shouldn't
1512 // be used, really, but it's pretty convenient sometimes,
1513 // when you just want to work with a regex.
1514 var set = this.set;
1515
1516 if (!set.length) {
1517 this.regexp = false;
1518 return this.regexp
1519 }
1520 var options = this.options;
1521
1522 var twoStar = options.noglobstar ? star
1523 : options.dot ? twoStarDot
1524 : twoStarNoDot;
1525 var flags = options.nocase ? 'i' : '';
1526
1527 var re = set.map(function (pattern) {
1528 return pattern.map(function (p) {
1529 return (p === GLOBSTAR) ? twoStar
1530 : (typeof p === 'string') ? regExpEscape(p)
1531 : p._src
1532 }).join('\\\/')
1533 }).join('|');
1534
1535 // must match entire pattern
1536 // ending in a * or ** will make it less strict.
1537 re = '^(?:' + re + ')$';
1538
1539 // can match anything, as long as it's not this.
1540 if (this.negate) re = '^(?!' + re + ').*$';
1541
1542 try {
1543 this.regexp = new RegExp(re, flags);
1544 } catch (ex) {
1545 this.regexp = false;
1546 }
1547 return this.regexp
1548}
1549
1550minimatch.match = function (list, pattern, options) {
1551 options = options || {};
1552 var mm = new Minimatch$1(pattern, options);
1553 list = list.filter(function (f) {
1554 return mm.match(f)
1555 });
1556 if (mm.options.nonull && !list.length) {
1557 list.push(pattern);
1558 }
1559 return list
1560};
1561
1562Minimatch$1.prototype.match = match;
1563function match (f, partial) {
1564 this.debug('match', f, this.pattern);
1565 // short-circuit in the case of busted things.
1566 // comments, etc.
1567 if (this.comment) return false
1568 if (this.empty) return f === ''
1569
1570 if (f === '/' && partial) return true
1571
1572 var options = this.options;
1573
1574 // windows: need to use /, not \
1575 if (path.sep !== '/') {
1576 f = f.split(path.sep).join('/');
1577 }
1578
1579 // treat the test path as a set of pathparts.
1580 f = f.split(slashSplit);
1581 this.debug(this.pattern, 'split', f);
1582
1583 // just ONE of the pattern sets in this.set needs to match
1584 // in order for it to be valid. If negating, then just one
1585 // match means that we have failed.
1586 // Either way, return on the first hit.
1587
1588 var set = this.set;
1589 this.debug(this.pattern, 'set', set);
1590
1591 // Find the basename of the path by looking for the last non-empty segment
1592 var filename;
1593 var i;
1594 for (i = f.length - 1; i >= 0; i--) {
1595 filename = f[i];
1596 if (filename) break
1597 }
1598
1599 for (i = 0; i < set.length; i++) {
1600 var pattern = set[i];
1601 var file = f;
1602 if (options.matchBase && pattern.length === 1) {
1603 file = [filename];
1604 }
1605 var hit = this.matchOne(file, pattern, partial);
1606 if (hit) {
1607 if (options.flipNegate) return true
1608 return !this.negate
1609 }
1610 }
1611
1612 // didn't get any hits. this is success if it's a negative
1613 // pattern, failure otherwise.
1614 if (options.flipNegate) return false
1615 return this.negate
1616}
1617
1618// set partial to true to test if, for example,
1619// "/a/b" matches the start of "/*/b/*/d"
1620// Partial means, if you run out of file before you run
1621// out of pattern, then that's fine, as long as all
1622// the parts match.
1623Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
1624 var options = this.options;
1625
1626 this.debug('matchOne',
1627 { 'this': this, file: file, pattern: pattern });
1628
1629 this.debug('matchOne', file.length, pattern.length);
1630
1631 for (var fi = 0,
1632 pi = 0,
1633 fl = file.length,
1634 pl = pattern.length
1635 ; (fi < fl) && (pi < pl)
1636 ; fi++, pi++) {
1637 this.debug('matchOne loop');
1638 var p = pattern[pi];
1639 var f = file[fi];
1640
1641 this.debug(pattern, p, f);
1642
1643 // should be impossible.
1644 // some invalid regexp stuff in the set.
1645 if (p === false) return false
1646
1647 if (p === GLOBSTAR) {
1648 this.debug('GLOBSTAR', [pattern, p, f]);
1649
1650 // "**"
1651 // a/**/b/**/c would match the following:
1652 // a/b/x/y/z/c
1653 // a/x/y/z/b/c
1654 // a/b/x/b/x/c
1655 // a/b/c
1656 // To do this, take the rest of the pattern after
1657 // the **, and see if it would match the file remainder.
1658 // If so, return success.
1659 // If not, the ** "swallows" a segment, and try again.
1660 // This is recursively awful.
1661 //
1662 // a/**/b/**/c matching a/b/x/y/z/c
1663 // - a matches a
1664 // - doublestar
1665 // - matchOne(b/x/y/z/c, b/**/c)
1666 // - b matches b
1667 // - doublestar
1668 // - matchOne(x/y/z/c, c) -> no
1669 // - matchOne(y/z/c, c) -> no
1670 // - matchOne(z/c, c) -> no
1671 // - matchOne(c, c) yes, hit
1672 var fr = fi;
1673 var pr = pi + 1;
1674 if (pr === pl) {
1675 this.debug('** at the end');
1676 // a ** at the end will just swallow the rest.
1677 // We have found a match.
1678 // however, it will not swallow /.x, unless
1679 // options.dot is set.
1680 // . and .. are *never* matched by **, for explosively
1681 // exponential reasons.
1682 for (; fi < fl; fi++) {
1683 if (file[fi] === '.' || file[fi] === '..' ||
1684 (!options.dot && file[fi].charAt(0) === '.')) return false
1685 }
1686 return true
1687 }
1688
1689 // ok, let's see if we can swallow whatever we can.
1690 while (fr < fl) {
1691 var swallowee = file[fr];
1692
1693 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
1694
1695 // XXX remove this slice. Just pass the start index.
1696 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
1697 this.debug('globstar found match!', fr, fl, swallowee);
1698 // found a match.
1699 return true
1700 } else {
1701 // can't swallow "." or ".." ever.
1702 // can only swallow ".foo" when explicitly asked.
1703 if (swallowee === '.' || swallowee === '..' ||
1704 (!options.dot && swallowee.charAt(0) === '.')) {
1705 this.debug('dot detected!', file, fr, pattern, pr);
1706 break
1707 }
1708
1709 // ** swallows a segment, and continue.
1710 this.debug('globstar swallow a segment, and continue');
1711 fr++;
1712 }
1713 }
1714
1715 // no match was found.
1716 // However, in partial mode, we can't say this is necessarily over.
1717 // If there's more *pattern* left, then
1718 if (partial) {
1719 // ran out of file
1720 this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
1721 if (fr === fl) return true
1722 }
1723 return false
1724 }
1725
1726 // something other than **
1727 // non-magic patterns just have to match exactly
1728 // patterns with magic have been turned into regexps.
1729 var hit;
1730 if (typeof p === 'string') {
1731 if (options.nocase) {
1732 hit = f.toLowerCase() === p.toLowerCase();
1733 } else {
1734 hit = f === p;
1735 }
1736 this.debug('string match', p, f, hit);
1737 } else {
1738 hit = f.match(p);
1739 this.debug('pattern match', p, f, hit);
1740 }
1741
1742 if (!hit) return false
1743 }
1744
1745 // Note: ending in / means that we'll get a final ""
1746 // at the end of the pattern. This can only match a
1747 // corresponding "" at the end of the file.
1748 // If the file ends in /, then it can only match a
1749 // a pattern that ends in /, unless the pattern just
1750 // doesn't have any more for it. But, a/b/ should *not*
1751 // match "a/b/*", even though "" matches against the
1752 // [^/]*? pattern, except in partial mode, where it might
1753 // simply not be reached yet.
1754 // However, a/b/ should still satisfy a/*
1755
1756 // now either we fell off the end of the pattern, or we're done.
1757 if (fi === fl && pi === pl) {
1758 // ran out of pattern and filename at the same time.
1759 // an exact hit!
1760 return true
1761 } else if (fi === fl) {
1762 // ran out of file, but still had pattern left.
1763 // this is ok if we're doing the match as part of
1764 // a glob fs traversal.
1765 return partial
1766 } else if (pi === pl) {
1767 // ran out of pattern, still have file left.
1768 // this is only acceptable if we're on the very last
1769 // empty segment of a file with a trailing slash.
1770 // a/* should match a/b/
1771 var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
1772 return emptyFileEnd
1773 }
1774
1775 // should be unreachable.
1776 throw new Error('wtf?')
1777};
1778
1779// replace stuff like \* with *
1780function globUnescape (s) {
1781 return s.replace(/\\(.)/g, '$1')
1782}
1783
1784function regExpEscape (s) {
1785 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
1786}
1787
1788function createCommonjsModule(fn) {
1789 var module = { exports: {} };
1790 return fn(module, module.exports), module.exports;
1791}
1792
1793var inherits_browser = createCommonjsModule(function (module) {
1794if (typeof Object.create === 'function') {
1795 // implementation from standard node.js 'util' module
1796 module.exports = function inherits(ctor, superCtor) {
1797 if (superCtor) {
1798 ctor.super_ = superCtor;
1799 ctor.prototype = Object.create(superCtor.prototype, {
1800 constructor: {
1801 value: ctor,
1802 enumerable: false,
1803 writable: true,
1804 configurable: true
1805 }
1806 });
1807 }
1808 };
1809} else {
1810 // old school shim for old browsers
1811 module.exports = function inherits(ctor, superCtor) {
1812 if (superCtor) {
1813 ctor.super_ = superCtor;
1814 var TempCtor = function () {};
1815 TempCtor.prototype = superCtor.prototype;
1816 ctor.prototype = new TempCtor();
1817 ctor.prototype.constructor = ctor;
1818 }
1819 };
1820}
1821});
1822
1823var inherits = createCommonjsModule(function (module) {
1824try {
1825 var util = require$$0__default['default'];
1826 /* istanbul ignore next */
1827 if (typeof util.inherits !== 'function') throw '';
1828 module.exports = util.inherits;
1829} catch (e) {
1830 /* istanbul ignore next */
1831 module.exports = inherits_browser;
1832}
1833});
1834
1835function posix(path) {
1836 return path.charAt(0) === '/';
1837}
1838
1839function win32(path) {
1840 // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
1841 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
1842 var result = splitDeviceRe.exec(path);
1843 var device = result[1] || '';
1844 var isUnc = Boolean(device && device.charAt(1) !== ':');
1845
1846 // UNC paths are always absolute
1847 return Boolean(result[2] || isUnc);
1848}
1849
1850var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
1851var posix_1 = posix;
1852var win32_1 = win32;
1853pathIsAbsolute.posix = posix_1;
1854pathIsAbsolute.win32 = win32_1;
1855
1856var setopts_1 = setopts$2;
1857var ownProp_1 = ownProp$2;
1858var makeAbs_1 = makeAbs;
1859var finish_1 = finish;
1860var mark_1 = mark;
1861var isIgnored_1 = isIgnored$2;
1862var childrenIgnored_1 = childrenIgnored$2;
1863
1864function ownProp$2 (obj, field) {
1865 return Object.prototype.hasOwnProperty.call(obj, field)
1866}
1867
1868
1869
1870
1871var Minimatch = minimatch_1.Minimatch;
1872
1873function alphasort (a, b) {
1874 return a.localeCompare(b, 'en')
1875}
1876
1877function setupIgnores (self, options) {
1878 self.ignore = options.ignore || [];
1879
1880 if (!Array.isArray(self.ignore))
1881 self.ignore = [self.ignore];
1882
1883 if (self.ignore.length) {
1884 self.ignore = self.ignore.map(ignoreMap);
1885 }
1886}
1887
1888// ignore patterns are always in dot:true mode.
1889function ignoreMap (pattern) {
1890 var gmatcher = null;
1891 if (pattern.slice(-3) === '/**') {
1892 var gpattern = pattern.replace(/(\/\*\*)+$/, '');
1893 gmatcher = new Minimatch(gpattern, { dot: true });
1894 }
1895
1896 return {
1897 matcher: new Minimatch(pattern, { dot: true }),
1898 gmatcher: gmatcher
1899 }
1900}
1901
1902function setopts$2 (self, pattern, options) {
1903 if (!options)
1904 options = {};
1905
1906 // base-matching: just use globstar for that.
1907 if (options.matchBase && -1 === pattern.indexOf("/")) {
1908 if (options.noglobstar) {
1909 throw new Error("base matching requires globstar")
1910 }
1911 pattern = "**/" + pattern;
1912 }
1913
1914 self.silent = !!options.silent;
1915 self.pattern = pattern;
1916 self.strict = options.strict !== false;
1917 self.realpath = !!options.realpath;
1918 self.realpathCache = options.realpathCache || Object.create(null);
1919 self.follow = !!options.follow;
1920 self.dot = !!options.dot;
1921 self.mark = !!options.mark;
1922 self.nodir = !!options.nodir;
1923 if (self.nodir)
1924 self.mark = true;
1925 self.sync = !!options.sync;
1926 self.nounique = !!options.nounique;
1927 self.nonull = !!options.nonull;
1928 self.nosort = !!options.nosort;
1929 self.nocase = !!options.nocase;
1930 self.stat = !!options.stat;
1931 self.noprocess = !!options.noprocess;
1932 self.absolute = !!options.absolute;
1933
1934 self.maxLength = options.maxLength || Infinity;
1935 self.cache = options.cache || Object.create(null);
1936 self.statCache = options.statCache || Object.create(null);
1937 self.symlinks = options.symlinks || Object.create(null);
1938
1939 setupIgnores(self, options);
1940
1941 self.changedCwd = false;
1942 var cwd = process.cwd();
1943 if (!ownProp$2(options, "cwd"))
1944 self.cwd = cwd;
1945 else {
1946 self.cwd = path__default['default'].resolve(options.cwd);
1947 self.changedCwd = self.cwd !== cwd;
1948 }
1949
1950 self.root = options.root || path__default['default'].resolve(self.cwd, "/");
1951 self.root = path__default['default'].resolve(self.root);
1952 if (process.platform === "win32")
1953 self.root = self.root.replace(/\\/g, "/");
1954
1955 // TODO: is an absolute `cwd` supposed to be resolved against `root`?
1956 // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
1957 self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
1958 if (process.platform === "win32")
1959 self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
1960 self.nomount = !!options.nomount;
1961
1962 // disable comments and negation in Minimatch.
1963 // Note that they are not supported in Glob itself anyway.
1964 options.nonegate = true;
1965 options.nocomment = true;
1966
1967 self.minimatch = new Minimatch(pattern, options);
1968 self.options = self.minimatch.options;
1969}
1970
1971function finish (self) {
1972 var nou = self.nounique;
1973 var all = nou ? [] : Object.create(null);
1974
1975 for (var i = 0, l = self.matches.length; i < l; i ++) {
1976 var matches = self.matches[i];
1977 if (!matches || Object.keys(matches).length === 0) {
1978 if (self.nonull) {
1979 // do like the shell, and spit out the literal glob
1980 var literal = self.minimatch.globSet[i];
1981 if (nou)
1982 all.push(literal);
1983 else
1984 all[literal] = true;
1985 }
1986 } else {
1987 // had matches
1988 var m = Object.keys(matches);
1989 if (nou)
1990 all.push.apply(all, m);
1991 else
1992 m.forEach(function (m) {
1993 all[m] = true;
1994 });
1995 }
1996 }
1997
1998 if (!nou)
1999 all = Object.keys(all);
2000
2001 if (!self.nosort)
2002 all = all.sort(alphasort);
2003
2004 // at *some* point we statted all of these
2005 if (self.mark) {
2006 for (var i = 0; i < all.length; i++) {
2007 all[i] = self._mark(all[i]);
2008 }
2009 if (self.nodir) {
2010 all = all.filter(function (e) {
2011 var notDir = !(/\/$/.test(e));
2012 var c = self.cache[e] || self.cache[makeAbs(self, e)];
2013 if (notDir && c)
2014 notDir = c !== 'DIR' && !Array.isArray(c);
2015 return notDir
2016 });
2017 }
2018 }
2019
2020 if (self.ignore.length)
2021 all = all.filter(function(m) {
2022 return !isIgnored$2(self, m)
2023 });
2024
2025 self.found = all;
2026}
2027
2028function mark (self, p) {
2029 var abs = makeAbs(self, p);
2030 var c = self.cache[abs];
2031 var m = p;
2032 if (c) {
2033 var isDir = c === 'DIR' || Array.isArray(c);
2034 var slash = p.slice(-1) === '/';
2035
2036 if (isDir && !slash)
2037 m += '/';
2038 else if (!isDir && slash)
2039 m = m.slice(0, -1);
2040
2041 if (m !== p) {
2042 var mabs = makeAbs(self, m);
2043 self.statCache[mabs] = self.statCache[abs];
2044 self.cache[mabs] = self.cache[abs];
2045 }
2046 }
2047
2048 return m
2049}
2050
2051// lotta situps...
2052function makeAbs (self, f) {
2053 var abs = f;
2054 if (f.charAt(0) === '/') {
2055 abs = path__default['default'].join(self.root, f);
2056 } else if (pathIsAbsolute(f) || f === '') {
2057 abs = f;
2058 } else if (self.changedCwd) {
2059 abs = path__default['default'].resolve(self.cwd, f);
2060 } else {
2061 abs = path__default['default'].resolve(f);
2062 }
2063
2064 if (process.platform === 'win32')
2065 abs = abs.replace(/\\/g, '/');
2066
2067 return abs
2068}
2069
2070
2071// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
2072// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
2073function isIgnored$2 (self, path) {
2074 if (!self.ignore.length)
2075 return false
2076
2077 return self.ignore.some(function(item) {
2078 return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
2079 })
2080}
2081
2082function childrenIgnored$2 (self, path) {
2083 if (!self.ignore.length)
2084 return false
2085
2086 return self.ignore.some(function(item) {
2087 return !!(item.gmatcher && item.gmatcher.match(path))
2088 })
2089}
2090
2091var common = {
2092 setopts: setopts_1,
2093 ownProp: ownProp_1,
2094 makeAbs: makeAbs_1,
2095 finish: finish_1,
2096 mark: mark_1,
2097 isIgnored: isIgnored_1,
2098 childrenIgnored: childrenIgnored_1
2099};
2100
2101var require$$0 = glob_1;
2102
2103var sync = globSync;
2104globSync.GlobSync = GlobSync$1;
2105require$$0.Glob;
2106
2107
2108
2109
2110
2111var setopts$1 = common.setopts;
2112var ownProp$1 = common.ownProp;
2113var childrenIgnored$1 = common.childrenIgnored;
2114var isIgnored$1 = common.isIgnored;
2115
2116function globSync (pattern, options) {
2117 if (typeof options === 'function' || arguments.length === 3)
2118 throw new TypeError('callback provided to sync glob\n'+
2119 'See: https://github.com/isaacs/node-glob/issues/167')
2120
2121 return new GlobSync$1(pattern, options).found
2122}
2123
2124function GlobSync$1 (pattern, options) {
2125 if (!pattern)
2126 throw new Error('must provide pattern')
2127
2128 if (typeof options === 'function' || arguments.length === 3)
2129 throw new TypeError('callback provided to sync glob\n'+
2130 'See: https://github.com/isaacs/node-glob/issues/167')
2131
2132 if (!(this instanceof GlobSync$1))
2133 return new GlobSync$1(pattern, options)
2134
2135 setopts$1(this, pattern, options);
2136
2137 if (this.noprocess)
2138 return this
2139
2140 var n = this.minimatch.set.length;
2141 this.matches = new Array(n);
2142 for (var i = 0; i < n; i ++) {
2143 this._process(this.minimatch.set[i], i, false);
2144 }
2145 this._finish();
2146}
2147
2148GlobSync$1.prototype._finish = function () {
2149 assert__default['default'](this instanceof GlobSync$1);
2150 if (this.realpath) {
2151 var self = this;
2152 this.matches.forEach(function (matchset, index) {
2153 var set = self.matches[index] = Object.create(null);
2154 for (var p in matchset) {
2155 try {
2156 p = self._makeAbs(p);
2157 var real = fs_realpath.realpathSync(p, self.realpathCache);
2158 set[real] = true;
2159 } catch (er) {
2160 if (er.syscall === 'stat')
2161 set[self._makeAbs(p)] = true;
2162 else
2163 throw er
2164 }
2165 }
2166 });
2167 }
2168 common.finish(this);
2169};
2170
2171
2172GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
2173 assert__default['default'](this instanceof GlobSync$1);
2174
2175 // Get the first [n] parts of pattern that are all strings.
2176 var n = 0;
2177 while (typeof pattern[n] === 'string') {
2178 n ++;
2179 }
2180 // now n is the index of the first one that is *not* a string.
2181
2182 // See if there's anything else
2183 var prefix;
2184 switch (n) {
2185 // if not, then this is rather simple
2186 case pattern.length:
2187 this._processSimple(pattern.join('/'), index);
2188 return
2189
2190 case 0:
2191 // pattern *starts* with some non-trivial item.
2192 // going to readdir(cwd), but not include the prefix in matches.
2193 prefix = null;
2194 break
2195
2196 default:
2197 // pattern has some string bits in the front.
2198 // whatever it starts with, whether that's 'absolute' like /foo/bar,
2199 // or 'relative' like '../baz'
2200 prefix = pattern.slice(0, n).join('/');
2201 break
2202 }
2203
2204 var remain = pattern.slice(n);
2205
2206 // get the list of entries.
2207 var read;
2208 if (prefix === null)
2209 read = '.';
2210 else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
2211 if (!prefix || !pathIsAbsolute(prefix))
2212 prefix = '/' + prefix;
2213 read = prefix;
2214 } else
2215 read = prefix;
2216
2217 var abs = this._makeAbs(read);
2218
2219 //if ignored, skip processing
2220 if (childrenIgnored$1(this, read))
2221 return
2222
2223 var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
2224 if (isGlobStar)
2225 this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
2226 else
2227 this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
2228};
2229
2230
2231GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
2232 var entries = this._readdir(abs, inGlobStar);
2233
2234 // if the abs isn't a dir, then nothing can match!
2235 if (!entries)
2236 return
2237
2238 // It will only match dot entries if it starts with a dot, or if
2239 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
2240 var pn = remain[0];
2241 var negate = !!this.minimatch.negate;
2242 var rawGlob = pn._glob;
2243 var dotOk = this.dot || rawGlob.charAt(0) === '.';
2244
2245 var matchedEntries = [];
2246 for (var i = 0; i < entries.length; i++) {
2247 var e = entries[i];
2248 if (e.charAt(0) !== '.' || dotOk) {
2249 var m;
2250 if (negate && !prefix) {
2251 m = !e.match(pn);
2252 } else {
2253 m = e.match(pn);
2254 }
2255 if (m)
2256 matchedEntries.push(e);
2257 }
2258 }
2259
2260 var len = matchedEntries.length;
2261 // If there are no matched entries, then nothing matches.
2262 if (len === 0)
2263 return
2264
2265 // if this is the last remaining pattern bit, then no need for
2266 // an additional stat *unless* the user has specified mark or
2267 // stat explicitly. We know they exist, since readdir returned
2268 // them.
2269
2270 if (remain.length === 1 && !this.mark && !this.stat) {
2271 if (!this.matches[index])
2272 this.matches[index] = Object.create(null);
2273
2274 for (var i = 0; i < len; i ++) {
2275 var e = matchedEntries[i];
2276 if (prefix) {
2277 if (prefix.slice(-1) !== '/')
2278 e = prefix + '/' + e;
2279 else
2280 e = prefix + e;
2281 }
2282
2283 if (e.charAt(0) === '/' && !this.nomount) {
2284 e = path__default['default'].join(this.root, e);
2285 }
2286 this._emitMatch(index, e);
2287 }
2288 // This was the last one, and no stats were needed
2289 return
2290 }
2291
2292 // now test all matched entries as stand-ins for that part
2293 // of the pattern.
2294 remain.shift();
2295 for (var i = 0; i < len; i ++) {
2296 var e = matchedEntries[i];
2297 var newPattern;
2298 if (prefix)
2299 newPattern = [prefix, e];
2300 else
2301 newPattern = [e];
2302 this._process(newPattern.concat(remain), index, inGlobStar);
2303 }
2304};
2305
2306
2307GlobSync$1.prototype._emitMatch = function (index, e) {
2308 if (isIgnored$1(this, e))
2309 return
2310
2311 var abs = this._makeAbs(e);
2312
2313 if (this.mark)
2314 e = this._mark(e);
2315
2316 if (this.absolute) {
2317 e = abs;
2318 }
2319
2320 if (this.matches[index][e])
2321 return
2322
2323 if (this.nodir) {
2324 var c = this.cache[abs];
2325 if (c === 'DIR' || Array.isArray(c))
2326 return
2327 }
2328
2329 this.matches[index][e] = true;
2330
2331 if (this.stat)
2332 this._stat(e);
2333};
2334
2335
2336GlobSync$1.prototype._readdirInGlobStar = function (abs) {
2337 // follow all symlinked directories forever
2338 // just proceed as if this is a non-globstar situation
2339 if (this.follow)
2340 return this._readdir(abs, false)
2341
2342 var entries;
2343 var lstat;
2344 try {
2345 lstat = fs__default['default'].lstatSync(abs);
2346 } catch (er) {
2347 if (er.code === 'ENOENT') {
2348 // lstat failed, doesn't exist
2349 return null
2350 }
2351 }
2352
2353 var isSym = lstat && lstat.isSymbolicLink();
2354 this.symlinks[abs] = isSym;
2355
2356 // If it's not a symlink or a dir, then it's definitely a regular file.
2357 // don't bother doing a readdir in that case.
2358 if (!isSym && lstat && !lstat.isDirectory())
2359 this.cache[abs] = 'FILE';
2360 else
2361 entries = this._readdir(abs, false);
2362
2363 return entries
2364};
2365
2366GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
2367
2368 if (inGlobStar && !ownProp$1(this.symlinks, abs))
2369 return this._readdirInGlobStar(abs)
2370
2371 if (ownProp$1(this.cache, abs)) {
2372 var c = this.cache[abs];
2373 if (!c || c === 'FILE')
2374 return null
2375
2376 if (Array.isArray(c))
2377 return c
2378 }
2379
2380 try {
2381 return this._readdirEntries(abs, fs__default['default'].readdirSync(abs))
2382 } catch (er) {
2383 this._readdirError(abs, er);
2384 return null
2385 }
2386};
2387
2388GlobSync$1.prototype._readdirEntries = function (abs, entries) {
2389 // if we haven't asked to stat everything, then just
2390 // assume that everything in there exists, so we can avoid
2391 // having to stat it a second time.
2392 if (!this.mark && !this.stat) {
2393 for (var i = 0; i < entries.length; i ++) {
2394 var e = entries[i];
2395 if (abs === '/')
2396 e = abs + e;
2397 else
2398 e = abs + '/' + e;
2399 this.cache[e] = true;
2400 }
2401 }
2402
2403 this.cache[abs] = entries;
2404
2405 // mark and cache dir-ness
2406 return entries
2407};
2408
2409GlobSync$1.prototype._readdirError = function (f, er) {
2410 // handle errors, and cache the information
2411 switch (er.code) {
2412 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
2413 case 'ENOTDIR': // totally normal. means it *does* exist.
2414 var abs = this._makeAbs(f);
2415 this.cache[abs] = 'FILE';
2416 if (abs === this.cwdAbs) {
2417 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
2418 error.path = this.cwd;
2419 error.code = er.code;
2420 throw error
2421 }
2422 break
2423
2424 case 'ENOENT': // not terribly unusual
2425 case 'ELOOP':
2426 case 'ENAMETOOLONG':
2427 case 'UNKNOWN':
2428 this.cache[this._makeAbs(f)] = false;
2429 break
2430
2431 default: // some unusual error. Treat as failure.
2432 this.cache[this._makeAbs(f)] = false;
2433 if (this.strict)
2434 throw er
2435 if (!this.silent)
2436 console.error('glob error', er);
2437 break
2438 }
2439};
2440
2441GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
2442
2443 var entries = this._readdir(abs, inGlobStar);
2444
2445 // no entries means not a dir, so it can never have matches
2446 // foo.txt/** doesn't match foo.txt
2447 if (!entries)
2448 return
2449
2450 // test without the globstar, and with every child both below
2451 // and replacing the globstar.
2452 var remainWithoutGlobStar = remain.slice(1);
2453 var gspref = prefix ? [ prefix ] : [];
2454 var noGlobStar = gspref.concat(remainWithoutGlobStar);
2455
2456 // the noGlobStar pattern exits the inGlobStar state
2457 this._process(noGlobStar, index, false);
2458
2459 var len = entries.length;
2460 var isSym = this.symlinks[abs];
2461
2462 // If it's a symlink, and we're in a globstar, then stop
2463 if (isSym && inGlobStar)
2464 return
2465
2466 for (var i = 0; i < len; i++) {
2467 var e = entries[i];
2468 if (e.charAt(0) === '.' && !this.dot)
2469 continue
2470
2471 // these two cases enter the inGlobStar state
2472 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
2473 this._process(instead, index, true);
2474
2475 var below = gspref.concat(entries[i], remain);
2476 this._process(below, index, true);
2477 }
2478};
2479
2480GlobSync$1.prototype._processSimple = function (prefix, index) {
2481 // XXX review this. Shouldn't it be doing the mounting etc
2482 // before doing stat? kinda weird?
2483 var exists = this._stat(prefix);
2484
2485 if (!this.matches[index])
2486 this.matches[index] = Object.create(null);
2487
2488 // If it doesn't exist, then just mark the lack of results
2489 if (!exists)
2490 return
2491
2492 if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
2493 var trail = /[\/\\]$/.test(prefix);
2494 if (prefix.charAt(0) === '/') {
2495 prefix = path__default['default'].join(this.root, prefix);
2496 } else {
2497 prefix = path__default['default'].resolve(this.root, prefix);
2498 if (trail)
2499 prefix += '/';
2500 }
2501 }
2502
2503 if (process.platform === 'win32')
2504 prefix = prefix.replace(/\\/g, '/');
2505
2506 // Mark this as a match
2507 this._emitMatch(index, prefix);
2508};
2509
2510// Returns either 'DIR', 'FILE', or false
2511GlobSync$1.prototype._stat = function (f) {
2512 var abs = this._makeAbs(f);
2513 var needDir = f.slice(-1) === '/';
2514
2515 if (f.length > this.maxLength)
2516 return false
2517
2518 if (!this.stat && ownProp$1(this.cache, abs)) {
2519 var c = this.cache[abs];
2520
2521 if (Array.isArray(c))
2522 c = 'DIR';
2523
2524 // It exists, but maybe not how we need it
2525 if (!needDir || c === 'DIR')
2526 return c
2527
2528 if (needDir && c === 'FILE')
2529 return false
2530
2531 // otherwise we have to stat, because maybe c=true
2532 // if we know it exists, but not what it is.
2533 }
2534 var stat = this.statCache[abs];
2535 if (!stat) {
2536 var lstat;
2537 try {
2538 lstat = fs__default['default'].lstatSync(abs);
2539 } catch (er) {
2540 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
2541 this.statCache[abs] = false;
2542 return false
2543 }
2544 }
2545
2546 if (lstat && lstat.isSymbolicLink()) {
2547 try {
2548 stat = fs__default['default'].statSync(abs);
2549 } catch (er) {
2550 stat = lstat;
2551 }
2552 } else {
2553 stat = lstat;
2554 }
2555 }
2556
2557 this.statCache[abs] = stat;
2558
2559 var c = true;
2560 if (stat)
2561 c = stat.isDirectory() ? 'DIR' : 'FILE';
2562
2563 this.cache[abs] = this.cache[abs] || c;
2564
2565 if (needDir && c === 'FILE')
2566 return false
2567
2568 return c
2569};
2570
2571GlobSync$1.prototype._mark = function (p) {
2572 return common.mark(this, p)
2573};
2574
2575GlobSync$1.prototype._makeAbs = function (f) {
2576 return common.makeAbs(this, f)
2577};
2578
2579// Returns a wrapper function that returns a wrapped callback
2580// The wrapper function should do some stuff, and return a
2581// presumably different callback function.
2582// This makes sure that own properties are retained, so that
2583// decorations and such are not lost along the way.
2584var wrappy_1 = wrappy;
2585function wrappy (fn, cb) {
2586 if (fn && cb) return wrappy(fn)(cb)
2587
2588 if (typeof fn !== 'function')
2589 throw new TypeError('need wrapper function')
2590
2591 Object.keys(fn).forEach(function (k) {
2592 wrapper[k] = fn[k];
2593 });
2594
2595 return wrapper
2596
2597 function wrapper() {
2598 var args = new Array(arguments.length);
2599 for (var i = 0; i < args.length; i++) {
2600 args[i] = arguments[i];
2601 }
2602 var ret = fn.apply(this, args);
2603 var cb = args[args.length-1];
2604 if (typeof ret === 'function' && ret !== cb) {
2605 Object.keys(cb).forEach(function (k) {
2606 ret[k] = cb[k];
2607 });
2608 }
2609 return ret
2610 }
2611}
2612
2613var once_1 = wrappy_1(once);
2614var strict = wrappy_1(onceStrict);
2615
2616once.proto = once(function () {
2617 Object.defineProperty(Function.prototype, 'once', {
2618 value: function () {
2619 return once(this)
2620 },
2621 configurable: true
2622 });
2623
2624 Object.defineProperty(Function.prototype, 'onceStrict', {
2625 value: function () {
2626 return onceStrict(this)
2627 },
2628 configurable: true
2629 });
2630});
2631
2632function once (fn) {
2633 var f = function () {
2634 if (f.called) return f.value
2635 f.called = true;
2636 return f.value = fn.apply(this, arguments)
2637 };
2638 f.called = false;
2639 return f
2640}
2641
2642function onceStrict (fn) {
2643 var f = function () {
2644 if (f.called)
2645 throw new Error(f.onceError)
2646 f.called = true;
2647 return f.value = fn.apply(this, arguments)
2648 };
2649 var name = fn.name || 'Function wrapped with `once`';
2650 f.onceError = name + " shouldn't be called more than once";
2651 f.called = false;
2652 return f
2653}
2654once_1.strict = strict;
2655
2656var reqs = Object.create(null);
2657
2658
2659var inflight_1 = wrappy_1(inflight);
2660
2661function inflight (key, cb) {
2662 if (reqs[key]) {
2663 reqs[key].push(cb);
2664 return null
2665 } else {
2666 reqs[key] = [cb];
2667 return makeres(key)
2668 }
2669}
2670
2671function makeres (key) {
2672 return once_1(function RES () {
2673 var cbs = reqs[key];
2674 var len = cbs.length;
2675 var args = slice(arguments);
2676
2677 // XXX It's somewhat ambiguous whether a new callback added in this
2678 // pass should be queued for later execution if something in the
2679 // list of callbacks throws, or if it should just be discarded.
2680 // However, it's such an edge case that it hardly matters, and either
2681 // choice is likely as surprising as the other.
2682 // As it happens, we do go ahead and schedule it for later execution.
2683 try {
2684 for (var i = 0; i < len; i++) {
2685 cbs[i].apply(null, args);
2686 }
2687 } finally {
2688 if (cbs.length > len) {
2689 // added more in the interim.
2690 // de-zalgo, just in case, but don't call again.
2691 cbs.splice(0, len);
2692 process.nextTick(function () {
2693 RES.apply(null, args);
2694 });
2695 } else {
2696 delete reqs[key];
2697 }
2698 }
2699 })
2700}
2701
2702function slice (args) {
2703 var length = args.length;
2704 var array = [];
2705
2706 for (var i = 0; i < length; i++) array[i] = args[i];
2707 return array
2708}
2709
2710// Approach:
2711//
2712// 1. Get the minimatch set
2713// 2. For each pattern in the set, PROCESS(pattern, false)
2714// 3. Store matches per-set, then uniq them
2715//
2716// PROCESS(pattern, inGlobStar)
2717// Get the first [n] items from pattern that are all strings
2718// Join these together. This is PREFIX.
2719// If there is no more remaining, then stat(PREFIX) and
2720// add to matches if it succeeds. END.
2721//
2722// If inGlobStar and PREFIX is symlink and points to dir
2723// set ENTRIES = []
2724// else readdir(PREFIX) as ENTRIES
2725// If fail, END
2726//
2727// with ENTRIES
2728// If pattern[n] is GLOBSTAR
2729// // handle the case where the globstar match is empty
2730// // by pruning it out, and testing the resulting pattern
2731// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
2732// // handle other cases.
2733// for ENTRY in ENTRIES (not dotfiles)
2734// // attach globstar + tail onto the entry
2735// // Mark that this entry is a globstar match
2736// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
2737//
2738// else // not globstar
2739// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
2740// Test ENTRY against pattern[n]
2741// If fails, continue
2742// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
2743//
2744// Caveat:
2745// Cache all stats and readdirs results to minimize syscall. Since all
2746// we ever care about is existence and directory-ness, we can just keep
2747// `true` for files, and [children,...] for directories, or `false` for
2748// things that don't exist.
2749
2750var glob_1 = glob;
2751
2752var EE = require$$0__default$1['default'].EventEmitter;
2753
2754
2755
2756
2757
2758var setopts = common.setopts;
2759var ownProp = common.ownProp;
2760
2761
2762var childrenIgnored = common.childrenIgnored;
2763var isIgnored = common.isIgnored;
2764
2765
2766
2767function glob (pattern, options, cb) {
2768 if (typeof options === 'function') cb = options, options = {};
2769 if (!options) options = {};
2770
2771 if (options.sync) {
2772 if (cb)
2773 throw new TypeError('callback provided to sync glob')
2774 return sync(pattern, options)
2775 }
2776
2777 return new Glob(pattern, options, cb)
2778}
2779
2780glob.sync = sync;
2781var GlobSync = glob.GlobSync = sync.GlobSync;
2782
2783// old api surface
2784glob.glob = glob;
2785
2786function extend (origin, add) {
2787 if (add === null || typeof add !== 'object') {
2788 return origin
2789 }
2790
2791 var keys = Object.keys(add);
2792 var i = keys.length;
2793 while (i--) {
2794 origin[keys[i]] = add[keys[i]];
2795 }
2796 return origin
2797}
2798
2799glob.hasMagic = function (pattern, options_) {
2800 var options = extend({}, options_);
2801 options.noprocess = true;
2802
2803 var g = new Glob(pattern, options);
2804 var set = g.minimatch.set;
2805
2806 if (!pattern)
2807 return false
2808
2809 if (set.length > 1)
2810 return true
2811
2812 for (var j = 0; j < set[0].length; j++) {
2813 if (typeof set[0][j] !== 'string')
2814 return true
2815 }
2816
2817 return false
2818};
2819
2820glob.Glob = Glob;
2821inherits(Glob, EE);
2822function Glob (pattern, options, cb) {
2823 if (typeof options === 'function') {
2824 cb = options;
2825 options = null;
2826 }
2827
2828 if (options && options.sync) {
2829 if (cb)
2830 throw new TypeError('callback provided to sync glob')
2831 return new GlobSync(pattern, options)
2832 }
2833
2834 if (!(this instanceof Glob))
2835 return new Glob(pattern, options, cb)
2836
2837 setopts(this, pattern, options);
2838 this._didRealPath = false;
2839
2840 // process each pattern in the minimatch set
2841 var n = this.minimatch.set.length;
2842
2843 // The matches are stored as {<filename>: true,...} so that
2844 // duplicates are automagically pruned.
2845 // Later, we do an Object.keys() on these.
2846 // Keep them as a list so we can fill in when nonull is set.
2847 this.matches = new Array(n);
2848
2849 if (typeof cb === 'function') {
2850 cb = once_1(cb);
2851 this.on('error', cb);
2852 this.on('end', function (matches) {
2853 cb(null, matches);
2854 });
2855 }
2856
2857 var self = this;
2858 this._processing = 0;
2859
2860 this._emitQueue = [];
2861 this._processQueue = [];
2862 this.paused = false;
2863
2864 if (this.noprocess)
2865 return this
2866
2867 if (n === 0)
2868 return done()
2869
2870 var sync = true;
2871 for (var i = 0; i < n; i ++) {
2872 this._process(this.minimatch.set[i], i, false, done);
2873 }
2874 sync = false;
2875
2876 function done () {
2877 --self._processing;
2878 if (self._processing <= 0) {
2879 if (sync) {
2880 process.nextTick(function () {
2881 self._finish();
2882 });
2883 } else {
2884 self._finish();
2885 }
2886 }
2887 }
2888}
2889
2890Glob.prototype._finish = function () {
2891 assert__default['default'](this instanceof Glob);
2892 if (this.aborted)
2893 return
2894
2895 if (this.realpath && !this._didRealpath)
2896 return this._realpath()
2897
2898 common.finish(this);
2899 this.emit('end', this.found);
2900};
2901
2902Glob.prototype._realpath = function () {
2903 if (this._didRealpath)
2904 return
2905
2906 this._didRealpath = true;
2907
2908 var n = this.matches.length;
2909 if (n === 0)
2910 return this._finish()
2911
2912 var self = this;
2913 for (var i = 0; i < this.matches.length; i++)
2914 this._realpathSet(i, next);
2915
2916 function next () {
2917 if (--n === 0)
2918 self._finish();
2919 }
2920};
2921
2922Glob.prototype._realpathSet = function (index, cb) {
2923 var matchset = this.matches[index];
2924 if (!matchset)
2925 return cb()
2926
2927 var found = Object.keys(matchset);
2928 var self = this;
2929 var n = found.length;
2930
2931 if (n === 0)
2932 return cb()
2933
2934 var set = this.matches[index] = Object.create(null);
2935 found.forEach(function (p, i) {
2936 // If there's a problem with the stat, then it means that
2937 // one or more of the links in the realpath couldn't be
2938 // resolved. just return the abs value in that case.
2939 p = self._makeAbs(p);
2940 fs_realpath.realpath(p, self.realpathCache, function (er, real) {
2941 if (!er)
2942 set[real] = true;
2943 else if (er.syscall === 'stat')
2944 set[p] = true;
2945 else
2946 self.emit('error', er); // srsly wtf right here
2947
2948 if (--n === 0) {
2949 self.matches[index] = set;
2950 cb();
2951 }
2952 });
2953 });
2954};
2955
2956Glob.prototype._mark = function (p) {
2957 return common.mark(this, p)
2958};
2959
2960Glob.prototype._makeAbs = function (f) {
2961 return common.makeAbs(this, f)
2962};
2963
2964Glob.prototype.abort = function () {
2965 this.aborted = true;
2966 this.emit('abort');
2967};
2968
2969Glob.prototype.pause = function () {
2970 if (!this.paused) {
2971 this.paused = true;
2972 this.emit('pause');
2973 }
2974};
2975
2976Glob.prototype.resume = function () {
2977 if (this.paused) {
2978 this.emit('resume');
2979 this.paused = false;
2980 if (this._emitQueue.length) {
2981 var eq = this._emitQueue.slice(0);
2982 this._emitQueue.length = 0;
2983 for (var i = 0; i < eq.length; i ++) {
2984 var e = eq[i];
2985 this._emitMatch(e[0], e[1]);
2986 }
2987 }
2988 if (this._processQueue.length) {
2989 var pq = this._processQueue.slice(0);
2990 this._processQueue.length = 0;
2991 for (var i = 0; i < pq.length; i ++) {
2992 var p = pq[i];
2993 this._processing--;
2994 this._process(p[0], p[1], p[2], p[3]);
2995 }
2996 }
2997 }
2998};
2999
3000Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
3001 assert__default['default'](this instanceof Glob);
3002 assert__default['default'](typeof cb === 'function');
3003
3004 if (this.aborted)
3005 return
3006
3007 this._processing++;
3008 if (this.paused) {
3009 this._processQueue.push([pattern, index, inGlobStar, cb]);
3010 return
3011 }
3012
3013 //console.error('PROCESS %d', this._processing, pattern)
3014
3015 // Get the first [n] parts of pattern that are all strings.
3016 var n = 0;
3017 while (typeof pattern[n] === 'string') {
3018 n ++;
3019 }
3020 // now n is the index of the first one that is *not* a string.
3021
3022 // see if there's anything else
3023 var prefix;
3024 switch (n) {
3025 // if not, then this is rather simple
3026 case pattern.length:
3027 this._processSimple(pattern.join('/'), index, cb);
3028 return
3029
3030 case 0:
3031 // pattern *starts* with some non-trivial item.
3032 // going to readdir(cwd), but not include the prefix in matches.
3033 prefix = null;
3034 break
3035
3036 default:
3037 // pattern has some string bits in the front.
3038 // whatever it starts with, whether that's 'absolute' like /foo/bar,
3039 // or 'relative' like '../baz'
3040 prefix = pattern.slice(0, n).join('/');
3041 break
3042 }
3043
3044 var remain = pattern.slice(n);
3045
3046 // get the list of entries.
3047 var read;
3048 if (prefix === null)
3049 read = '.';
3050 else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
3051 if (!prefix || !pathIsAbsolute(prefix))
3052 prefix = '/' + prefix;
3053 read = prefix;
3054 } else
3055 read = prefix;
3056
3057 var abs = this._makeAbs(read);
3058
3059 //if ignored, skip _processing
3060 if (childrenIgnored(this, read))
3061 return cb()
3062
3063 var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
3064 if (isGlobStar)
3065 this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
3066 else
3067 this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
3068};
3069
3070Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
3071 var self = this;
3072 this._readdir(abs, inGlobStar, function (er, entries) {
3073 return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
3074 });
3075};
3076
3077Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
3078
3079 // if the abs isn't a dir, then nothing can match!
3080 if (!entries)
3081 return cb()
3082
3083 // It will only match dot entries if it starts with a dot, or if
3084 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
3085 var pn = remain[0];
3086 var negate = !!this.minimatch.negate;
3087 var rawGlob = pn._glob;
3088 var dotOk = this.dot || rawGlob.charAt(0) === '.';
3089
3090 var matchedEntries = [];
3091 for (var i = 0; i < entries.length; i++) {
3092 var e = entries[i];
3093 if (e.charAt(0) !== '.' || dotOk) {
3094 var m;
3095 if (negate && !prefix) {
3096 m = !e.match(pn);
3097 } else {
3098 m = e.match(pn);
3099 }
3100 if (m)
3101 matchedEntries.push(e);
3102 }
3103 }
3104
3105 //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
3106
3107 var len = matchedEntries.length;
3108 // If there are no matched entries, then nothing matches.
3109 if (len === 0)
3110 return cb()
3111
3112 // if this is the last remaining pattern bit, then no need for
3113 // an additional stat *unless* the user has specified mark or
3114 // stat explicitly. We know they exist, since readdir returned
3115 // them.
3116
3117 if (remain.length === 1 && !this.mark && !this.stat) {
3118 if (!this.matches[index])
3119 this.matches[index] = Object.create(null);
3120
3121 for (var i = 0; i < len; i ++) {
3122 var e = matchedEntries[i];
3123 if (prefix) {
3124 if (prefix !== '/')
3125 e = prefix + '/' + e;
3126 else
3127 e = prefix + e;
3128 }
3129
3130 if (e.charAt(0) === '/' && !this.nomount) {
3131 e = path__default['default'].join(this.root, e);
3132 }
3133 this._emitMatch(index, e);
3134 }
3135 // This was the last one, and no stats were needed
3136 return cb()
3137 }
3138
3139 // now test all matched entries as stand-ins for that part
3140 // of the pattern.
3141 remain.shift();
3142 for (var i = 0; i < len; i ++) {
3143 var e = matchedEntries[i];
3144 if (prefix) {
3145 if (prefix !== '/')
3146 e = prefix + '/' + e;
3147 else
3148 e = prefix + e;
3149 }
3150 this._process([e].concat(remain), index, inGlobStar, cb);
3151 }
3152 cb();
3153};
3154
3155Glob.prototype._emitMatch = function (index, e) {
3156 if (this.aborted)
3157 return
3158
3159 if (isIgnored(this, e))
3160 return
3161
3162 if (this.paused) {
3163 this._emitQueue.push([index, e]);
3164 return
3165 }
3166
3167 var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
3168
3169 if (this.mark)
3170 e = this._mark(e);
3171
3172 if (this.absolute)
3173 e = abs;
3174
3175 if (this.matches[index][e])
3176 return
3177
3178 if (this.nodir) {
3179 var c = this.cache[abs];
3180 if (c === 'DIR' || Array.isArray(c))
3181 return
3182 }
3183
3184 this.matches[index][e] = true;
3185
3186 var st = this.statCache[abs];
3187 if (st)
3188 this.emit('stat', e, st);
3189
3190 this.emit('match', e);
3191};
3192
3193Glob.prototype._readdirInGlobStar = function (abs, cb) {
3194 if (this.aborted)
3195 return
3196
3197 // follow all symlinked directories forever
3198 // just proceed as if this is a non-globstar situation
3199 if (this.follow)
3200 return this._readdir(abs, false, cb)
3201
3202 var lstatkey = 'lstat\0' + abs;
3203 var self = this;
3204 var lstatcb = inflight_1(lstatkey, lstatcb_);
3205
3206 if (lstatcb)
3207 fs__default['default'].lstat(abs, lstatcb);
3208
3209 function lstatcb_ (er, lstat) {
3210 if (er && er.code === 'ENOENT')
3211 return cb()
3212
3213 var isSym = lstat && lstat.isSymbolicLink();
3214 self.symlinks[abs] = isSym;
3215
3216 // If it's not a symlink or a dir, then it's definitely a regular file.
3217 // don't bother doing a readdir in that case.
3218 if (!isSym && lstat && !lstat.isDirectory()) {
3219 self.cache[abs] = 'FILE';
3220 cb();
3221 } else
3222 self._readdir(abs, false, cb);
3223 }
3224};
3225
3226Glob.prototype._readdir = function (abs, inGlobStar, cb) {
3227 if (this.aborted)
3228 return
3229
3230 cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb);
3231 if (!cb)
3232 return
3233
3234 //console.error('RD %j %j', +inGlobStar, abs)
3235 if (inGlobStar && !ownProp(this.symlinks, abs))
3236 return this._readdirInGlobStar(abs, cb)
3237
3238 if (ownProp(this.cache, abs)) {
3239 var c = this.cache[abs];
3240 if (!c || c === 'FILE')
3241 return cb()
3242
3243 if (Array.isArray(c))
3244 return cb(null, c)
3245 }
3246 fs__default['default'].readdir(abs, readdirCb(this, abs, cb));
3247};
3248
3249function readdirCb (self, abs, cb) {
3250 return function (er, entries) {
3251 if (er)
3252 self._readdirError(abs, er, cb);
3253 else
3254 self._readdirEntries(abs, entries, cb);
3255 }
3256}
3257
3258Glob.prototype._readdirEntries = function (abs, entries, cb) {
3259 if (this.aborted)
3260 return
3261
3262 // if we haven't asked to stat everything, then just
3263 // assume that everything in there exists, so we can avoid
3264 // having to stat it a second time.
3265 if (!this.mark && !this.stat) {
3266 for (var i = 0; i < entries.length; i ++) {
3267 var e = entries[i];
3268 if (abs === '/')
3269 e = abs + e;
3270 else
3271 e = abs + '/' + e;
3272 this.cache[e] = true;
3273 }
3274 }
3275
3276 this.cache[abs] = entries;
3277 return cb(null, entries)
3278};
3279
3280Glob.prototype._readdirError = function (f, er, cb) {
3281 if (this.aborted)
3282 return
3283
3284 // handle errors, and cache the information
3285 switch (er.code) {
3286 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
3287 case 'ENOTDIR': // totally normal. means it *does* exist.
3288 var abs = this._makeAbs(f);
3289 this.cache[abs] = 'FILE';
3290 if (abs === this.cwdAbs) {
3291 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
3292 error.path = this.cwd;
3293 error.code = er.code;
3294 this.emit('error', error);
3295 this.abort();
3296 }
3297 break
3298
3299 case 'ENOENT': // not terribly unusual
3300 case 'ELOOP':
3301 case 'ENAMETOOLONG':
3302 case 'UNKNOWN':
3303 this.cache[this._makeAbs(f)] = false;
3304 break
3305
3306 default: // some unusual error. Treat as failure.
3307 this.cache[this._makeAbs(f)] = false;
3308 if (this.strict) {
3309 this.emit('error', er);
3310 // If the error is handled, then we abort
3311 // if not, we threw out of here
3312 this.abort();
3313 }
3314 if (!this.silent)
3315 console.error('glob error', er);
3316 break
3317 }
3318
3319 return cb()
3320};
3321
3322Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
3323 var self = this;
3324 this._readdir(abs, inGlobStar, function (er, entries) {
3325 self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
3326 });
3327};
3328
3329
3330Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
3331 //console.error('pgs2', prefix, remain[0], entries)
3332
3333 // no entries means not a dir, so it can never have matches
3334 // foo.txt/** doesn't match foo.txt
3335 if (!entries)
3336 return cb()
3337
3338 // test without the globstar, and with every child both below
3339 // and replacing the globstar.
3340 var remainWithoutGlobStar = remain.slice(1);
3341 var gspref = prefix ? [ prefix ] : [];
3342 var noGlobStar = gspref.concat(remainWithoutGlobStar);
3343
3344 // the noGlobStar pattern exits the inGlobStar state
3345 this._process(noGlobStar, index, false, cb);
3346
3347 var isSym = this.symlinks[abs];
3348 var len = entries.length;
3349
3350 // If it's a symlink, and we're in a globstar, then stop
3351 if (isSym && inGlobStar)
3352 return cb()
3353
3354 for (var i = 0; i < len; i++) {
3355 var e = entries[i];
3356 if (e.charAt(0) === '.' && !this.dot)
3357 continue
3358
3359 // these two cases enter the inGlobStar state
3360 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
3361 this._process(instead, index, true, cb);
3362
3363 var below = gspref.concat(entries[i], remain);
3364 this._process(below, index, true, cb);
3365 }
3366
3367 cb();
3368};
3369
3370Glob.prototype._processSimple = function (prefix, index, cb) {
3371 // XXX review this. Shouldn't it be doing the mounting etc
3372 // before doing stat? kinda weird?
3373 var self = this;
3374 this._stat(prefix, function (er, exists) {
3375 self._processSimple2(prefix, index, er, exists, cb);
3376 });
3377};
3378Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
3379
3380 //console.error('ps2', prefix, exists)
3381
3382 if (!this.matches[index])
3383 this.matches[index] = Object.create(null);
3384
3385 // If it doesn't exist, then just mark the lack of results
3386 if (!exists)
3387 return cb()
3388
3389 if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
3390 var trail = /[\/\\]$/.test(prefix);
3391 if (prefix.charAt(0) === '/') {
3392 prefix = path__default['default'].join(this.root, prefix);
3393 } else {
3394 prefix = path__default['default'].resolve(this.root, prefix);
3395 if (trail)
3396 prefix += '/';
3397 }
3398 }
3399
3400 if (process.platform === 'win32')
3401 prefix = prefix.replace(/\\/g, '/');
3402
3403 // Mark this as a match
3404 this._emitMatch(index, prefix);
3405 cb();
3406};
3407
3408// Returns either 'DIR', 'FILE', or false
3409Glob.prototype._stat = function (f, cb) {
3410 var abs = this._makeAbs(f);
3411 var needDir = f.slice(-1) === '/';
3412
3413 if (f.length > this.maxLength)
3414 return cb()
3415
3416 if (!this.stat && ownProp(this.cache, abs)) {
3417 var c = this.cache[abs];
3418
3419 if (Array.isArray(c))
3420 c = 'DIR';
3421
3422 // It exists, but maybe not how we need it
3423 if (!needDir || c === 'DIR')
3424 return cb(null, c)
3425
3426 if (needDir && c === 'FILE')
3427 return cb()
3428
3429 // otherwise we have to stat, because maybe c=true
3430 // if we know it exists, but not what it is.
3431 }
3432 var stat = this.statCache[abs];
3433 if (stat !== undefined) {
3434 if (stat === false)
3435 return cb(null, stat)
3436 else {
3437 var type = stat.isDirectory() ? 'DIR' : 'FILE';
3438 if (needDir && type === 'FILE')
3439 return cb()
3440 else
3441 return cb(null, type, stat)
3442 }
3443 }
3444
3445 var self = this;
3446 var statcb = inflight_1('stat\0' + abs, lstatcb_);
3447 if (statcb)
3448 fs__default['default'].lstat(abs, statcb);
3449
3450 function lstatcb_ (er, lstat) {
3451 if (lstat && lstat.isSymbolicLink()) {
3452 // If it's a symlink, then treat it as the target, unless
3453 // the target does not exist, then treat it as a file.
3454 return fs__default['default'].stat(abs, function (er, stat) {
3455 if (er)
3456 self._stat2(f, abs, null, lstat, cb);
3457 else
3458 self._stat2(f, abs, er, stat, cb);
3459 })
3460 } else {
3461 self._stat2(f, abs, er, lstat, cb);
3462 }
3463 }
3464};
3465
3466Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
3467 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
3468 this.statCache[abs] = false;
3469 return cb()
3470 }
3471
3472 var needDir = f.slice(-1) === '/';
3473 this.statCache[abs] = stat;
3474
3475 if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
3476 return cb(null, false, stat)
3477
3478 var c = true;
3479 if (stat)
3480 c = stat.isDirectory() ? 'DIR' : 'FILE';
3481 this.cache[abs] = this.cache[abs] || c;
3482
3483 if (needDir && c === 'FILE')
3484 return cb()
3485
3486 return cb(null, c, stat)
3487};
3488
3489function _nullishCoalesce$1(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
3490class Console {
3491 static log(...message) {
3492 // eslint-disable-next-line no-console
3493 console.log(...message);
3494 }
3495 static error(...message) {
3496 // eslint-disable-next-line no-console
3497 console.error(...message);
3498 }
3499 static time(label) {
3500 // eslint-disable-next-line no-console
3501 console.time(label);
3502 }
3503 static timeEnd(label) {
3504 // eslint-disable-next-line no-console
3505 console.timeEnd(label);
3506 }
3507}
3508
3509function globArray(patterns, options) {
3510 const list = [];
3511
3512 patterns.forEach(pattern => {
3513 if (pattern[0] === '!') {
3514 let i = list.length-1;
3515 while(i > -1) {
3516 if (!minimatch_1(list[i], pattern)) {
3517 list.splice(i, 1);
3518 }
3519 i--;
3520 }
3521
3522 }
3523 else {
3524 const newList = glob_1.sync(pattern, options);
3525 newList.forEach(item => {
3526 if (list.indexOf(item)===-1) {
3527 list.push(item);
3528 }
3529 });
3530 }
3531 });
3532
3533 return list;
3534}
3535
3536function getVersion() {
3537 // eslint-disable-next-line quotes
3538 return `windicss-with-web-api 0.2.2`; // replace by rollup
3539}
3540
3541function fuzzy(content) {
3542 return _nullishCoalesce$1(content.match(/([^<>"'`\s]*[^<>"'`\s:])|([^<>"'`\s.(){}[\]#=%]*[^<>"'`\s.(){}[\]#=%:])/g), () => ( []));
3543}
3544
3545function generateTemplate(
3546 folder,
3547 outputPath = 'windi.css'
3548) {
3549 if (!(fs__default['default'].existsSync(folder) && fs__default['default'].lstatSync(folder).isDirectory())) {
3550 fs__default['default'].mkdirSync(folder);
3551 if (!fs__default['default'].existsSync(folder))
3552 throw new Error(`Folder ${folder} creation failed.`);
3553 }
3554 folder = path__default['default'].resolve(folder);
3555 const template = `<!DOCTYPE html>
3556 <html lang="en">
3557
3558 <head>
3559 <meta charset="UTF-8">
3560 <meta name="viewport" content="width=device-width, initial-scale=1.0">
3561 <title>${path__default['default'].basename(folder)}</title>
3562 <link rel="stylesheet" href="${outputPath}">
3563 </head>
3564
3565 <body class="bg-gray-100">
3566 <div class="container mx-auto flex flex-col justify-center items-center h-screen">
3567 <div class="lg:flex shadow rounded-lg">
3568 <div class="bg-blue-500 rounded-t-lg lg:rounded-tr-none lg:rounded-l-lg lg:w-4/12 py-4 h-full flex flex-col justify-center">
3569 <div class="text-center tracking-wide">
3570 <div class="text-white font-bold text-8xl lg:text-4xl">24</div>
3571 <div class="text-white font-normal text-4xl pt-4 lg:pt-0 lg:text-2xl">Sept</div>
3572 </div>
3573 </div>
3574 <div class="w-full px-1 bg-white py-5 lg:px-2 lg:py-2 tracking-wide">
3575 <div class="flex flex-row lg:justify-start justify-center">
3576 <div class="text-gray-700 font-light text-sm text-center lg:text-left px-2">
3577 1:30 PM
3578 </div>
3579 <div class="text-gray-700 font-light text-sm text-center lg:text-left px-2">
3580 Organiser : IHC
3581 </div>
3582 </div>
3583 <div class="text-gray-700 text-xl pb-1 text-center lg:text-left px-2">
3584 International Conference Dubai
3585 </div>
3586
3587 <div class="text-gray-800 font-light text-sm pt-1 text-center lg:text-left px-2">
3588 A-142/1, A-142, Ganesh Nagar, Tilak Nagar, New Delhi, 110018
3589 </div>
3590 </div>
3591 <div class="flex flex-row items-center w-full lg:w-1/3 bg-white lg:justify-end justify-center px-2 py-4 lg:px-0 rounded-lg">
3592 <span class="tracking-wider text-gray-600 cursor-pointer bg-gray-100 hover:bg-gray-200 px-4 py-2 text-sm rounded-lg leading-loose mx-2">
3593 Going
3594 </span>
3595 </div>
3596 </div>
3597 </div>
3598 </body>
3599 </html>`;
3600 const inputPath = path__default['default'].join(folder, 'index.html');
3601 outputPath = path__default['default'].join(folder, outputPath);
3602 fs__default['default'].writeFileSync(inputPath, template);
3603 fs__default['default'].writeFileSync(outputPath, '');
3604 return { html: inputPath, css: outputPath };
3605}
3606
3607function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
3608
3609const doc = `Generate css from text files that containing windi classes.
3610By default, it will use interpretation mode to generate a single css file.
3611
3612Usage:
3613 windicss [filenames]
3614 windicss [filenames] -c -m -d
3615 windicss [filenames] -c -s -m -d
3616 windicss [filenames] [-c | -i] [-a] [-b | -s] [-m] [-d] [-p <prefix:string>] [-o <path:string>] [--args arguments]
3617
3618Options:
3619 -h, --help Print this help message and exit.
3620 -v, --version Print windicss current version and exit.
3621
3622 -i, --interpret Interpretation mode, generate class selectors. This is the default behavior.
3623 -c, --compile Compilation mode, combine the class name in each row into a single class.
3624 -a, --attributify Attributify mode, generate attribute selectors. Attributify mode can be mixed with the other two modes.
3625 -t, --preflight Add preflights, default is false.
3626
3627 -b, --combine Combine all css into one single file. This is the default behavior.
3628 -s, --separate Generate a separate css file for each input file.
3629
3630 -d, --dev Enable hot reload and watch mode.
3631 -m, --minify Generate minimized css file.
3632 -z, --fuzzy Enable fuzzy match, only works in interpration mode.
3633 -p, --prefix PREFIX Set the css class name prefix, only valid in compilation mode. The default prefix is 'windi-'.
3634 -o, --output PATH Set output css file path.
3635 -f, --config PATH Set config file path.
3636
3637 --style Parse and transform windi style block.
3638 --init PATH Start a new project on the path.
3639`;
3640
3641const args = arg_1({
3642 // Types
3643 '--help': Boolean,
3644 '--version': Boolean,
3645 '--compile': Boolean,
3646 '--interpret': Boolean,
3647 '--attributify': Boolean,
3648 '--preflight': Boolean,
3649 '--combine': Boolean,
3650 '--separate': Boolean,
3651 '--dev': Boolean,
3652 '--minify': Boolean,
3653 '--fuzzy': Boolean,
3654 '--style': Boolean,
3655 '--init': String,
3656 '--prefix': String,
3657 '--output': String,
3658 '--config': String,
3659
3660 // Aliases
3661 '-h': '--help',
3662 '-v': '--version',
3663 '-i': '--interpret',
3664 '-c': '--compile',
3665 '-a': '--attributify',
3666 '-t': '--preflight',
3667 '-b': '--combine',
3668 '-s': '--separate',
3669 '-d': '--dev',
3670 '-m': '--minify',
3671 '-p': '--prefix',
3672 '-o': '--output',
3673 '-f': '--config',
3674 '-z': '--fuzzy',
3675});
3676
3677if (args['--help'] || (args._.length === 0 && Object.keys(args).length === 1)) {
3678 Console.log(doc);
3679 process.exit();
3680}
3681
3682if (args['--version']) {
3683 Console.log(getVersion());
3684 process.exit();
3685}
3686
3687if (args['--init']) {
3688 const template = generateTemplate(args['--init'], args['--output']);
3689 args._.push(template.html);
3690 args['--preflight'] = true;
3691 args['--output'] = template.css;
3692}
3693
3694const configFile = args['--config'] ? path$1.resolve(args['--config']) : undefined;
3695let preflights = {};
3696let styleSheets = {};
3697let processor = new index_ts.Processor(configFile ? require(configFile) : undefined);
3698let safelist = processor.config('safelist');
3699
3700if (configFile) Console.log('Config file:', configFile);
3701
3702function compile(files) {
3703 // compilation mode
3704 const prefix = _nullishCoalesce(args['--prefix'], () => ( 'windi-'));
3705 files.forEach((file) => {
3706 let indexStart = 0;
3707 const outputStyle = [];
3708 const outputHTML = [];
3709 const html = fs.readFileSync(file).toString();
3710 const parser = new index_ts$2.HTMLParser(html);
3711
3712 // Match ClassName then replace with new ClassName
3713 parser.parseClasses().forEach((p) => {
3714 outputHTML.push(html.substring(indexStart, p.start));
3715 const utility = processor.compile(p.result, prefix, true, args['--dev']); // Set third argument to false to hide comments;
3716 outputStyle.push(utility.styleSheet);
3717 outputHTML.push([utility.className, ...utility.ignored].join(' '));
3718 indexStart = p.end;
3719 });
3720 outputHTML.push(html.substring(indexStart));
3721 const added = (
3722 outputStyle.reduce(
3723 (previousValue, currentValue) =>
3724 previousValue.extend(currentValue),
3725 new index_ts$1.StyleSheet()
3726 )
3727 );
3728 styleSheets[file] = args['--dev'] ? (styleSheets[file]? styleSheets[file].extend(added) : added) : added;
3729
3730 const outputFile = file.replace(/(?=\.\w+$)/, '.windi');
3731 fs.writeFile(outputFile, outputHTML.join(''), () => null);
3732 Console.log(`${file} -> ${outputFile}`);
3733 if (args['--preflight']) {
3734 if (args['--dev']) {
3735 const preflight = processor.preflight(html, true, true, true, true);
3736 preflights[file] = preflights[file] ? preflights[file].extend(preflight) : preflight;
3737 } else {
3738 preflights[file] = processor.preflight(html);
3739 }
3740 }
3741 });
3742}
3743
3744function interpret(files) {
3745 // interpretation mode
3746 files.forEach((file) => {
3747 const content = fs.readFileSync(file).toString();
3748 let classes = [];
3749 if (args['--fuzzy']) {
3750 classes = fuzzy(content);
3751 } else {
3752 const parser = new index_ts$2.HTMLParser(content);
3753 classes = parser.parseClasses().map((i) => i.result);
3754 }
3755 const extractors = processor.config('extract.extractors') ;
3756 if (extractors) {
3757 for (const { extractor, extensions } of extractors) {
3758 if (extensions.includes(path$1.extname(file).slice(1))) {
3759 const result = extractor(content);
3760 if ('classes' in result && result.classes) {
3761 classes = [...classes, ...result.classes];
3762 }
3763 }
3764 }
3765 }
3766 if (args['--dev']) {
3767 const utility = processor.interpret(classes.join(' '), true);
3768 styleSheets[file] = styleSheets[file] ? styleSheets[file].extend(utility.styleSheet) : utility.styleSheet;
3769 if (args['--preflight']) {
3770 const preflight = processor.preflight(content, true, true, true, true);
3771 preflights[file] = preflights[file] ? preflights[file].extend(preflight) : preflight;
3772 }
3773 } else {
3774 const utility = processor.interpret(classes.join(' '));
3775 styleSheets[file] = utility.styleSheet;
3776 if (args['--preflight']) preflights[file] = processor.preflight(content);
3777 }
3778 });
3779}
3780
3781function attributify(files) {
3782 // attributify mode
3783 files.forEach((file) => {
3784 const parser = new index_ts$2.HTMLParser(fs.readFileSync(file).toString());
3785 const attrs = parser
3786 .parseAttrs()
3787 .reduceRight((a, b) => {
3788 if (b.key === 'class' || b.key === 'className') return a;
3789 if (b.key in a) {
3790 a[b.key] = Array.isArray(a[b.key])
3791 ? Array.isArray(b.value)? [ ...(a[b.key] ), ...b.value ]: [ ...(a[b.key] ), b.value ]
3792 : [ a[b.key] , ...(Array.isArray(b.value) ? b.value : [b.value]) ];
3793 return a;
3794 }
3795 return Object.assign(a, { [b.key]: b.value });
3796 }, {});
3797 if (args['--dev']) {
3798 const utility = processor.attributify(attrs, true);
3799 styleSheets[file] = styleSheets[file] ? styleSheets[file].extend(utility.styleSheet) : utility.styleSheet;
3800 } else {
3801 const utility = processor.attributify(attrs);
3802 styleSheets[file] = utility.styleSheet;
3803 }
3804 });
3805}
3806
3807function styleBlock(files) {
3808 files.forEach((file) => {
3809 const content = fs.readFileSync(file).toString();
3810 const block = content.match(/(?<=<style lang=['"]windi["']>)[\s\S]*(?=<\/style>)/);
3811 if (block && block.index) {
3812 const css = content.slice(block.index, block.index + block[0].length);
3813 const parser = new index_ts$2.CSSParser(css, processor);
3814 styleSheets[file] = styleSheets[file].extend(parser.parse());
3815 }
3816 });
3817}
3818
3819function build(files, update = false) {
3820 if (args['--compile']) {
3821 compile(files);
3822 } else {
3823 interpret(files);
3824 }
3825 if (args['--attributify']) attributify(files);
3826 if (args['--style']) styleBlock(files);
3827 if (args['--separate']) {
3828 for (const [file, sheet] of Object.entries(styleSheets)) {
3829 const outfile = file.replace(/\.\w+$/, '.windi.css');
3830 fs.writeFile(outfile, (args['--preflight'] ? tools_ts.deepCopy(sheet).extend(preflights[file], false) : sheet).build(args['--minify']), () => null);
3831 Console.log(`${file} -> ${outfile}`);
3832 }
3833 } else {
3834 let outputStyle = Object.values(styleSheets)
3835 .reduce(
3836 (previousValue, currentValue) =>
3837 previousValue.extend(currentValue),
3838 new index_ts$1.StyleSheet()
3839 )
3840 .sort()
3841 .combine();
3842 if (args['--preflight'])
3843 outputStyle = Object.values(preflights)
3844 .reduce(
3845 (previousValue, currentValue) =>
3846 previousValue.extend(currentValue),
3847 new index_ts$1.StyleSheet()
3848 )
3849 .sort()
3850 .combine()
3851 .extend(outputStyle);
3852 const filePath = _nullishCoalesce(args['--output'], () => ( 'windi.css'));
3853 fs.writeFile(filePath, outputStyle.build(args['--minify']), () => null);
3854 if (!update) {
3855 Console.log('Matched files:', files);
3856 Console.log('Output file:', path$1.resolve(filePath));
3857 }
3858 }
3859
3860}
3861
3862function buildSafeList(safelist) {
3863 if (safelist) {
3864 let classes = [];
3865 if (typeof safelist === 'string') {
3866 classes = safelist.split(/\s/).filter(i => i);
3867 }
3868 if (Array.isArray(safelist)) {
3869 for (const item of safelist) {
3870 if (typeof item === 'string') {
3871 classes.push(item);
3872 } else if (Array.isArray(item)) {
3873 classes = classes.concat(item);
3874 }
3875 }
3876 }
3877 styleSheets['safelist'] = processor.interpret(classes.join(' ')).styleSheet;
3878 }
3879}
3880
3881const patterns = args._
3882 .concat(processor.config('extract.include', []) )
3883 .concat((processor.config('extract.exclude', []) ).map(i => '!' + i));
3884
3885let matchFiles = globArray(patterns);
3886
3887if (matchFiles.length === 0) {
3888 Console.error('No files were matched!');
3889 process.exit();
3890}
3891
3892buildSafeList(safelist);
3893build(matchFiles);
3894
3895function watchBuild(file) {
3896 fs.watch(file, (event, path) => {
3897 if (event === 'rename') {
3898 const newFiles = globArray(patterns);
3899 const renamed = matchFiles.filter(i => !(newFiles.includes(i)))[0];
3900 if (fs.existsSync(path)) {
3901 Console.log('File', `'${renamed}'`, 'has been renamed to', `'${path}'`);
3902 matchFiles = newFiles;
3903 Console.log('Matched files:', matchFiles);
3904 } else {
3905 Console.log('File', `'${file}'`, 'has been deleted');
3906 fs.unwatchFile(file);
3907 matchFiles = newFiles;
3908 delete styleSheets[file];
3909 delete preflights[file];
3910 if (matchFiles.length > 0) {
3911 Console.log('Matched files:', matchFiles);
3912 Console.time('Building');
3913 }
3914 build([], true);
3915 if (matchFiles.length > 0) {
3916 Console.timeEnd('Building');
3917 } else {
3918 Console.error('No files were matched!');
3919 process.exit();
3920 }
3921 }
3922 }
3923 if (event === 'change') {
3924 Console.log('File', `'${path}'`, 'has been changed');
3925 Console.time('Building');
3926 build([file], true);
3927 Console.timeEnd('Building');
3928 }
3929 });
3930}
3931
3932function watchConfig(file) {
3933 if (!file) return;
3934 let stamp = 0;
3935 fs.watch(file, (event, path) => {
3936 if (event === 'change' && (stamp === 0 || + new Date() - stamp > 500)) {
3937 // fix fire twice event when change config file
3938 stamp = + new Date();
3939 Console.log('Config', `'${path}'`, 'has been changed');
3940 Console.time('Building');
3941 configFile && delete require.cache[configFile];
3942 processor = new index_ts.Processor(configFile ? require(configFile) : undefined);
3943 safelist = processor.config('safelist');
3944 styleSheets = {};
3945 preflights = {};
3946 buildSafeList(safelist);
3947 build(matchFiles, true);
3948 Console.timeEnd('Building');
3949 }
3950 });
3951}
3952
3953if (args['--dev']) {
3954 watchConfig(configFile);
3955 for (const file of matchFiles) {
3956 watchBuild(file);
3957 }
3958 for (const dir of Array.from(new Set(matchFiles.map(f => path$1.dirname(f))))) {
3959 fs.watch(dir, (event, path) => {
3960 if (event === 'rename' && fs.existsSync(path$1.join(dir, path))) {
3961 // when create new file
3962 const newFiles = globArray(patterns);
3963 if (newFiles.length > matchFiles.length) {
3964 const newFile = newFiles.filter(i => !matchFiles.includes(i))[0];
3965 Console.log('New file', `'${newFile}'`, 'added');
3966 matchFiles.push(newFile);
3967 Console.log('Matched files:', matchFiles);
3968 Console.time('Building');
3969 build([newFile], true);
3970 watchBuild(newFile);
3971 Console.timeEnd('Building');
3972 }
3973 }
3974 });
3975 }
3976}