UNPKG

378 kBJavaScriptView Raw
1'use strict';
2
3var fs$1 = require('fs');
4var path$1 = require('path');
5var Events = require('events');
6var Stream$1 = require('stream');
7var require$$0 = require('string_decoder');
8var assert = require('assert');
9var require$$0$1 = require('buffer');
10var realZlib = require('zlib');
11var util$1 = require('util');
12var crypto = require('crypto');
13var os = require('os');
14var tty = require('tty');
15var constants$1 = require('constants');
16var https = require('https');
17var child_process = require('child_process');
18var require$$2 = require('url');
19var require$$0$2 = require('net');
20var require$$1 = require('tls');
21
22function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
23
24var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1);
25var path__default = /*#__PURE__*/_interopDefaultLegacy(path$1);
26var Events__default = /*#__PURE__*/_interopDefaultLegacy(Events);
27var Stream__default = /*#__PURE__*/_interopDefaultLegacy(Stream$1);
28var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
29var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
30var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
31var realZlib__default = /*#__PURE__*/_interopDefaultLegacy(realZlib);
32var util__default = /*#__PURE__*/_interopDefaultLegacy(util$1);
33var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
34var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
35var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty);
36var constants__default = /*#__PURE__*/_interopDefaultLegacy(constants$1);
37var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
38var child_process__default = /*#__PURE__*/_interopDefaultLegacy(child_process);
39var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2);
40var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
41var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
42
43var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
44
45function createCommonjsModule(fn) {
46 var module = { exports: {} };
47 return fn(module, module.exports), module.exports;
48}
49
50// turn tar(1) style args like `C` into the more verbose things like `cwd`
51
52const argmap = new Map([
53 ['C', 'cwd'],
54 ['f', 'file'],
55 ['z', 'gzip'],
56 ['P', 'preservePaths'],
57 ['U', 'unlink'],
58 ['strip-components', 'strip'],
59 ['stripComponents', 'strip'],
60 ['keep-newer', 'newer'],
61 ['keepNewer', 'newer'],
62 ['keep-newer-files', 'newer'],
63 ['keepNewerFiles', 'newer'],
64 ['k', 'keep'],
65 ['keep-existing', 'keep'],
66 ['keepExisting', 'keep'],
67 ['m', 'noMtime'],
68 ['no-mtime', 'noMtime'],
69 ['p', 'preserveOwner'],
70 ['L', 'follow'],
71 ['h', 'follow'],
72]);
73
74var highLevelOpt = opt => opt ? Object.keys(opt).map(k => [
75 argmap.has(k) ? argmap.get(k) : k, opt[k],
76]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {};
77
78var iterator = function (Yallist) {
79 Yallist.prototype[Symbol.iterator] = function* () {
80 for (let walker = this.head; walker; walker = walker.next) {
81 yield walker.value;
82 }
83 };
84};
85
86var yallist = Yallist;
87
88Yallist.Node = Node;
89Yallist.create = Yallist;
90
91function Yallist (list) {
92 var self = this;
93 if (!(self instanceof Yallist)) {
94 self = new Yallist();
95 }
96
97 self.tail = null;
98 self.head = null;
99 self.length = 0;
100
101 if (list && typeof list.forEach === 'function') {
102 list.forEach(function (item) {
103 self.push(item);
104 });
105 } else if (arguments.length > 0) {
106 for (var i = 0, l = arguments.length; i < l; i++) {
107 self.push(arguments[i]);
108 }
109 }
110
111 return self
112}
113
114Yallist.prototype.removeNode = function (node) {
115 if (node.list !== this) {
116 throw new Error('removing node which does not belong to this list')
117 }
118
119 var next = node.next;
120 var prev = node.prev;
121
122 if (next) {
123 next.prev = prev;
124 }
125
126 if (prev) {
127 prev.next = next;
128 }
129
130 if (node === this.head) {
131 this.head = next;
132 }
133 if (node === this.tail) {
134 this.tail = prev;
135 }
136
137 node.list.length--;
138 node.next = null;
139 node.prev = null;
140 node.list = null;
141
142 return next
143};
144
145Yallist.prototype.unshiftNode = function (node) {
146 if (node === this.head) {
147 return
148 }
149
150 if (node.list) {
151 node.list.removeNode(node);
152 }
153
154 var head = this.head;
155 node.list = this;
156 node.next = head;
157 if (head) {
158 head.prev = node;
159 }
160
161 this.head = node;
162 if (!this.tail) {
163 this.tail = node;
164 }
165 this.length++;
166};
167
168Yallist.prototype.pushNode = function (node) {
169 if (node === this.tail) {
170 return
171 }
172
173 if (node.list) {
174 node.list.removeNode(node);
175 }
176
177 var tail = this.tail;
178 node.list = this;
179 node.prev = tail;
180 if (tail) {
181 tail.next = node;
182 }
183
184 this.tail = node;
185 if (!this.head) {
186 this.head = node;
187 }
188 this.length++;
189};
190
191Yallist.prototype.push = function () {
192 for (var i = 0, l = arguments.length; i < l; i++) {
193 push(this, arguments[i]);
194 }
195 return this.length
196};
197
198Yallist.prototype.unshift = function () {
199 for (var i = 0, l = arguments.length; i < l; i++) {
200 unshift(this, arguments[i]);
201 }
202 return this.length
203};
204
205Yallist.prototype.pop = function () {
206 if (!this.tail) {
207 return undefined
208 }
209
210 var res = this.tail.value;
211 this.tail = this.tail.prev;
212 if (this.tail) {
213 this.tail.next = null;
214 } else {
215 this.head = null;
216 }
217 this.length--;
218 return res
219};
220
221Yallist.prototype.shift = function () {
222 if (!this.head) {
223 return undefined
224 }
225
226 var res = this.head.value;
227 this.head = this.head.next;
228 if (this.head) {
229 this.head.prev = null;
230 } else {
231 this.tail = null;
232 }
233 this.length--;
234 return res
235};
236
237Yallist.prototype.forEach = function (fn, thisp) {
238 thisp = thisp || this;
239 for (var walker = this.head, i = 0; walker !== null; i++) {
240 fn.call(thisp, walker.value, i, this);
241 walker = walker.next;
242 }
243};
244
245Yallist.prototype.forEachReverse = function (fn, thisp) {
246 thisp = thisp || this;
247 for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
248 fn.call(thisp, walker.value, i, this);
249 walker = walker.prev;
250 }
251};
252
253Yallist.prototype.get = function (n) {
254 for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
255 // abort out of the list early if we hit a cycle
256 walker = walker.next;
257 }
258 if (i === n && walker !== null) {
259 return walker.value
260 }
261};
262
263Yallist.prototype.getReverse = function (n) {
264 for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
265 // abort out of the list early if we hit a cycle
266 walker = walker.prev;
267 }
268 if (i === n && walker !== null) {
269 return walker.value
270 }
271};
272
273Yallist.prototype.map = function (fn, thisp) {
274 thisp = thisp || this;
275 var res = new Yallist();
276 for (var walker = this.head; walker !== null;) {
277 res.push(fn.call(thisp, walker.value, this));
278 walker = walker.next;
279 }
280 return res
281};
282
283Yallist.prototype.mapReverse = function (fn, thisp) {
284 thisp = thisp || this;
285 var res = new Yallist();
286 for (var walker = this.tail; walker !== null;) {
287 res.push(fn.call(thisp, walker.value, this));
288 walker = walker.prev;
289 }
290 return res
291};
292
293Yallist.prototype.reduce = function (fn, initial) {
294 var acc;
295 var walker = this.head;
296 if (arguments.length > 1) {
297 acc = initial;
298 } else if (this.head) {
299 walker = this.head.next;
300 acc = this.head.value;
301 } else {
302 throw new TypeError('Reduce of empty list with no initial value')
303 }
304
305 for (var i = 0; walker !== null; i++) {
306 acc = fn(acc, walker.value, i);
307 walker = walker.next;
308 }
309
310 return acc
311};
312
313Yallist.prototype.reduceReverse = function (fn, initial) {
314 var acc;
315 var walker = this.tail;
316 if (arguments.length > 1) {
317 acc = initial;
318 } else if (this.tail) {
319 walker = this.tail.prev;
320 acc = this.tail.value;
321 } else {
322 throw new TypeError('Reduce of empty list with no initial value')
323 }
324
325 for (var i = this.length - 1; walker !== null; i--) {
326 acc = fn(acc, walker.value, i);
327 walker = walker.prev;
328 }
329
330 return acc
331};
332
333Yallist.prototype.toArray = function () {
334 var arr = new Array(this.length);
335 for (var i = 0, walker = this.head; walker !== null; i++) {
336 arr[i] = walker.value;
337 walker = walker.next;
338 }
339 return arr
340};
341
342Yallist.prototype.toArrayReverse = function () {
343 var arr = new Array(this.length);
344 for (var i = 0, walker = this.tail; walker !== null; i++) {
345 arr[i] = walker.value;
346 walker = walker.prev;
347 }
348 return arr
349};
350
351Yallist.prototype.slice = function (from, to) {
352 to = to || this.length;
353 if (to < 0) {
354 to += this.length;
355 }
356 from = from || 0;
357 if (from < 0) {
358 from += this.length;
359 }
360 var ret = new Yallist();
361 if (to < from || to < 0) {
362 return ret
363 }
364 if (from < 0) {
365 from = 0;
366 }
367 if (to > this.length) {
368 to = this.length;
369 }
370 for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
371 walker = walker.next;
372 }
373 for (; walker !== null && i < to; i++, walker = walker.next) {
374 ret.push(walker.value);
375 }
376 return ret
377};
378
379Yallist.prototype.sliceReverse = function (from, to) {
380 to = to || this.length;
381 if (to < 0) {
382 to += this.length;
383 }
384 from = from || 0;
385 if (from < 0) {
386 from += this.length;
387 }
388 var ret = new Yallist();
389 if (to < from || to < 0) {
390 return ret
391 }
392 if (from < 0) {
393 from = 0;
394 }
395 if (to > this.length) {
396 to = this.length;
397 }
398 for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
399 walker = walker.prev;
400 }
401 for (; walker !== null && i > from; i--, walker = walker.prev) {
402 ret.push(walker.value);
403 }
404 return ret
405};
406
407Yallist.prototype.splice = function (start, deleteCount, ...nodes) {
408 if (start > this.length) {
409 start = this.length - 1;
410 }
411 if (start < 0) {
412 start = this.length + start;
413 }
414
415 for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
416 walker = walker.next;
417 }
418
419 var ret = [];
420 for (var i = 0; walker && i < deleteCount; i++) {
421 ret.push(walker.value);
422 walker = this.removeNode(walker);
423 }
424 if (walker === null) {
425 walker = this.tail;
426 }
427
428 if (walker !== this.head && walker !== this.tail) {
429 walker = walker.prev;
430 }
431
432 for (var i = 0; i < nodes.length; i++) {
433 walker = insert(this, walker, nodes[i]);
434 }
435 return ret;
436};
437
438Yallist.prototype.reverse = function () {
439 var head = this.head;
440 var tail = this.tail;
441 for (var walker = head; walker !== null; walker = walker.prev) {
442 var p = walker.prev;
443 walker.prev = walker.next;
444 walker.next = p;
445 }
446 this.head = tail;
447 this.tail = head;
448 return this
449};
450
451function insert (self, node, value) {
452 var inserted = node === self.head ?
453 new Node(value, null, node, self) :
454 new Node(value, node, node.next, self);
455
456 if (inserted.next === null) {
457 self.tail = inserted;
458 }
459 if (inserted.prev === null) {
460 self.head = inserted;
461 }
462
463 self.length++;
464
465 return inserted
466}
467
468function push (self, item) {
469 self.tail = new Node(item, self.tail, null, self);
470 if (!self.head) {
471 self.head = self.tail;
472 }
473 self.length++;
474}
475
476function unshift (self, item) {
477 self.head = new Node(item, null, self.head, self);
478 if (!self.tail) {
479 self.tail = self.head;
480 }
481 self.length++;
482}
483
484function Node (value, prev, next, list) {
485 if (!(this instanceof Node)) {
486 return new Node(value, prev, next, list)
487 }
488
489 this.list = list;
490 this.value = value;
491
492 if (prev) {
493 prev.next = this;
494 this.prev = prev;
495 } else {
496 this.prev = null;
497 }
498
499 if (next) {
500 next.prev = this;
501 this.next = next;
502 } else {
503 this.next = null;
504 }
505}
506
507try {
508 // add if support for Symbol.iterator is present
509 iterator(Yallist);
510} catch (er) {}
511
512const SD = require$$0__default['default'].StringDecoder;
513
514const EOF$1 = Symbol('EOF');
515const MAYBE_EMIT_END = Symbol('maybeEmitEnd');
516const EMITTED_END = Symbol('emittedEnd');
517const EMITTING_END = Symbol('emittingEnd');
518const CLOSED = Symbol('closed');
519const READ$1 = Symbol('read');
520const FLUSH = Symbol('flush');
521const FLUSHCHUNK = Symbol('flushChunk');
522const ENCODING = Symbol('encoding');
523const DECODER = Symbol('decoder');
524const FLOWING = Symbol('flowing');
525const PAUSED = Symbol('paused');
526const RESUME = Symbol('resume');
527const BUFFERLENGTH = Symbol('bufferLength');
528const BUFFERPUSH = Symbol('bufferPush');
529const BUFFERSHIFT = Symbol('bufferShift');
530const OBJECTMODE = Symbol('objectMode');
531const DESTROYED = Symbol('destroyed');
532
533// TODO remove when Node v8 support drops
534const doIter = commonjsGlobal._MP_NO_ITERATOR_SYMBOLS_ !== '1';
535const ASYNCITERATOR = doIter && Symbol.asyncIterator
536 || Symbol('asyncIterator not implemented');
537const ITERATOR = doIter && Symbol.iterator
538 || Symbol('iterator not implemented');
539
540// events that mean 'the stream is over'
541// these are treated specially, and re-emitted
542// if they are listened for after emitting.
543const isEndish = ev =>
544 ev === 'end' ||
545 ev === 'finish' ||
546 ev === 'prefinish';
547
548const isArrayBuffer = b => b instanceof ArrayBuffer ||
549 typeof b === 'object' &&
550 b.constructor &&
551 b.constructor.name === 'ArrayBuffer' &&
552 b.byteLength >= 0;
553
554const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
555
556var minipass = class Minipass extends Stream__default['default'] {
557 constructor (options) {
558 super();
559 this[FLOWING] = false;
560 // whether we're explicitly paused
561 this[PAUSED] = false;
562 this.pipes = new yallist();
563 this.buffer = new yallist();
564 this[OBJECTMODE] = options && options.objectMode || false;
565 if (this[OBJECTMODE])
566 this[ENCODING] = null;
567 else
568 this[ENCODING] = options && options.encoding || null;
569 if (this[ENCODING] === 'buffer')
570 this[ENCODING] = null;
571 this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null;
572 this[EOF$1] = false;
573 this[EMITTED_END] = false;
574 this[EMITTING_END] = false;
575 this[CLOSED] = false;
576 this.writable = true;
577 this.readable = true;
578 this[BUFFERLENGTH] = 0;
579 this[DESTROYED] = false;
580 }
581
582 get bufferLength () { return this[BUFFERLENGTH] }
583
584 get encoding () { return this[ENCODING] }
585 set encoding (enc) {
586 if (this[OBJECTMODE])
587 throw new Error('cannot set encoding in objectMode')
588
589 if (this[ENCODING] && enc !== this[ENCODING] &&
590 (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
591 throw new Error('cannot change encoding')
592
593 if (this[ENCODING] !== enc) {
594 this[DECODER] = enc ? new SD(enc) : null;
595 if (this.buffer.length)
596 this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk));
597 }
598
599 this[ENCODING] = enc;
600 }
601
602 setEncoding (enc) {
603 this.encoding = enc;
604 }
605
606 get objectMode () { return this[OBJECTMODE] }
607 set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om; }
608
609 write (chunk, encoding, cb) {
610 if (this[EOF$1])
611 throw new Error('write after end')
612
613 if (this[DESTROYED]) {
614 this.emit('error', Object.assign(
615 new Error('Cannot call write after a stream was destroyed'),
616 { code: 'ERR_STREAM_DESTROYED' }
617 ));
618 return true
619 }
620
621 if (typeof encoding === 'function')
622 cb = encoding, encoding = 'utf8';
623
624 if (!encoding)
625 encoding = 'utf8';
626
627 // convert array buffers and typed array views into buffers
628 // at some point in the future, we may want to do the opposite!
629 // leave strings and buffers as-is
630 // anything else switches us into object mode
631 if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
632 if (isArrayBufferView(chunk))
633 chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
634 else if (isArrayBuffer(chunk))
635 chunk = Buffer.from(chunk);
636 else if (typeof chunk !== 'string')
637 // use the setter so we throw if we have encoding set
638 this.objectMode = true;
639 }
640
641 // this ensures at this point that the chunk is a buffer or string
642 // don't buffer it up or send it to the decoder
643 if (!this.objectMode && !chunk.length) {
644 if (this[BUFFERLENGTH] !== 0)
645 this.emit('readable');
646 if (cb)
647 cb();
648 return this.flowing
649 }
650
651 // fast-path writing strings of same encoding to a stream with
652 // an empty buffer, skipping the buffer/decoder dance
653 if (typeof chunk === 'string' && !this[OBJECTMODE] &&
654 // unless it is a string already ready for us to use
655 !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
656 chunk = Buffer.from(chunk, encoding);
657 }
658
659 if (Buffer.isBuffer(chunk) && this[ENCODING])
660 chunk = this[DECODER].write(chunk);
661
662 if (this.flowing) {
663 // if we somehow have something in the buffer, but we think we're
664 // flowing, then we need to flush all that out first, or we get
665 // chunks coming in out of order. Can't emit 'drain' here though,
666 // because we're mid-write, so that'd be bad.
667 if (this[BUFFERLENGTH] !== 0)
668 this[FLUSH](true);
669 this.emit('data', chunk);
670 } else
671 this[BUFFERPUSH](chunk);
672
673 if (this[BUFFERLENGTH] !== 0)
674 this.emit('readable');
675
676 if (cb)
677 cb();
678
679 return this.flowing
680 }
681
682 read (n) {
683 if (this[DESTROYED])
684 return null
685
686 try {
687 if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH])
688 return null
689
690 if (this[OBJECTMODE])
691 n = null;
692
693 if (this.buffer.length > 1 && !this[OBJECTMODE]) {
694 if (this.encoding)
695 this.buffer = new yallist([
696 Array.from(this.buffer).join('')
697 ]);
698 else
699 this.buffer = new yallist([
700 Buffer.concat(Array.from(this.buffer), this[BUFFERLENGTH])
701 ]);
702 }
703
704 return this[READ$1](n || null, this.buffer.head.value)
705 } finally {
706 this[MAYBE_EMIT_END]();
707 }
708 }
709
710 [READ$1] (n, chunk) {
711 if (n === chunk.length || n === null)
712 this[BUFFERSHIFT]();
713 else {
714 this.buffer.head.value = chunk.slice(n);
715 chunk = chunk.slice(0, n);
716 this[BUFFERLENGTH] -= n;
717 }
718
719 this.emit('data', chunk);
720
721 if (!this.buffer.length && !this[EOF$1])
722 this.emit('drain');
723
724 return chunk
725 }
726
727 end (chunk, encoding, cb) {
728 if (typeof chunk === 'function')
729 cb = chunk, chunk = null;
730 if (typeof encoding === 'function')
731 cb = encoding, encoding = 'utf8';
732 if (chunk)
733 this.write(chunk, encoding);
734 if (cb)
735 this.once('end', cb);
736 this[EOF$1] = true;
737 this.writable = false;
738
739 // if we haven't written anything, then go ahead and emit,
740 // even if we're not reading.
741 // we'll re-emit if a new 'end' listener is added anyway.
742 // This makes MP more suitable to write-only use cases.
743 if (this.flowing || !this[PAUSED])
744 this[MAYBE_EMIT_END]();
745 return this
746 }
747
748 // don't let the internal resume be overwritten
749 [RESUME] () {
750 if (this[DESTROYED])
751 return
752
753 this[PAUSED] = false;
754 this[FLOWING] = true;
755 this.emit('resume');
756 if (this.buffer.length)
757 this[FLUSH]();
758 else if (this[EOF$1])
759 this[MAYBE_EMIT_END]();
760 else
761 this.emit('drain');
762 }
763
764 resume () {
765 return this[RESUME]()
766 }
767
768 pause () {
769 this[FLOWING] = false;
770 this[PAUSED] = true;
771 }
772
773 get destroyed () {
774 return this[DESTROYED]
775 }
776
777 get flowing () {
778 return this[FLOWING]
779 }
780
781 get paused () {
782 return this[PAUSED]
783 }
784
785 [BUFFERPUSH] (chunk) {
786 if (this[OBJECTMODE])
787 this[BUFFERLENGTH] += 1;
788 else
789 this[BUFFERLENGTH] += chunk.length;
790 return this.buffer.push(chunk)
791 }
792
793 [BUFFERSHIFT] () {
794 if (this.buffer.length) {
795 if (this[OBJECTMODE])
796 this[BUFFERLENGTH] -= 1;
797 else
798 this[BUFFERLENGTH] -= this.buffer.head.value.length;
799 }
800 return this.buffer.shift()
801 }
802
803 [FLUSH] (noDrain) {
804 do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))
805
806 if (!noDrain && !this.buffer.length && !this[EOF$1])
807 this.emit('drain');
808 }
809
810 [FLUSHCHUNK] (chunk) {
811 return chunk ? (this.emit('data', chunk), this.flowing) : false
812 }
813
814 pipe (dest, opts) {
815 if (this[DESTROYED])
816 return
817
818 const ended = this[EMITTED_END];
819 opts = opts || {};
820 if (dest === process.stdout || dest === process.stderr)
821 opts.end = false;
822 else
823 opts.end = opts.end !== false;
824
825 const p = { dest: dest, opts: opts, ondrain: _ => this[RESUME]() };
826 this.pipes.push(p);
827
828 dest.on('drain', p.ondrain);
829 this[RESUME]();
830 // piping an ended stream ends immediately
831 if (ended && p.opts.end)
832 p.dest.end();
833 return dest
834 }
835
836 addListener (ev, fn) {
837 return this.on(ev, fn)
838 }
839
840 on (ev, fn) {
841 try {
842 return super.on(ev, fn)
843 } finally {
844 if (ev === 'data' && !this.pipes.length && !this.flowing)
845 this[RESUME]();
846 else if (isEndish(ev) && this[EMITTED_END]) {
847 super.emit(ev);
848 this.removeAllListeners(ev);
849 }
850 }
851 }
852
853 get emittedEnd () {
854 return this[EMITTED_END]
855 }
856
857 [MAYBE_EMIT_END] () {
858 if (!this[EMITTING_END] &&
859 !this[EMITTED_END] &&
860 !this[DESTROYED] &&
861 this.buffer.length === 0 &&
862 this[EOF$1]) {
863 this[EMITTING_END] = true;
864 this.emit('end');
865 this.emit('prefinish');
866 this.emit('finish');
867 if (this[CLOSED])
868 this.emit('close');
869 this[EMITTING_END] = false;
870 }
871 }
872
873 emit (ev, data) {
874 // error and close are only events allowed after calling destroy()
875 if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
876 return
877 else if (ev === 'data') {
878 if (!data)
879 return
880
881 if (this.pipes.length)
882 this.pipes.forEach(p =>
883 p.dest.write(data) === false && this.pause());
884 } else if (ev === 'end') {
885 // only actual end gets this treatment
886 if (this[EMITTED_END] === true)
887 return
888
889 this[EMITTED_END] = true;
890 this.readable = false;
891
892 if (this[DECODER]) {
893 data = this[DECODER].end();
894 if (data) {
895 this.pipes.forEach(p => p.dest.write(data));
896 super.emit('data', data);
897 }
898 }
899
900 this.pipes.forEach(p => {
901 p.dest.removeListener('drain', p.ondrain);
902 if (p.opts.end)
903 p.dest.end();
904 });
905 } else if (ev === 'close') {
906 this[CLOSED] = true;
907 // don't emit close before 'end' and 'finish'
908 if (!this[EMITTED_END] && !this[DESTROYED])
909 return
910 }
911
912 // TODO: replace with a spread operator when Node v4 support drops
913 const args = new Array(arguments.length);
914 args[0] = ev;
915 args[1] = data;
916 if (arguments.length > 2) {
917 for (let i = 2; i < arguments.length; i++) {
918 args[i] = arguments[i];
919 }
920 }
921
922 try {
923 return super.emit.apply(this, args)
924 } finally {
925 if (!isEndish(ev))
926 this[MAYBE_EMIT_END]();
927 else
928 this.removeAllListeners(ev);
929 }
930 }
931
932 // const all = await stream.collect()
933 collect () {
934 const buf = [];
935 if (!this[OBJECTMODE])
936 buf.dataLength = 0;
937 // set the promise first, in case an error is raised
938 // by triggering the flow here.
939 const p = this.promise();
940 this.on('data', c => {
941 buf.push(c);
942 if (!this[OBJECTMODE])
943 buf.dataLength += c.length;
944 });
945 return p.then(() => buf)
946 }
947
948 // const data = await stream.concat()
949 concat () {
950 return this[OBJECTMODE]
951 ? Promise.reject(new Error('cannot concat in objectMode'))
952 : this.collect().then(buf =>
953 this[OBJECTMODE]
954 ? Promise.reject(new Error('cannot concat in objectMode'))
955 : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
956 }
957
958 // stream.promise().then(() => done, er => emitted error)
959 promise () {
960 return new Promise((resolve, reject) => {
961 this.on(DESTROYED, () => reject(new Error('stream destroyed')));
962 this.on('end', () => resolve());
963 this.on('error', er => reject(er));
964 })
965 }
966
967 // for await (let chunk of stream)
968 [ASYNCITERATOR] () {
969 const next = () => {
970 const res = this.read();
971 if (res !== null)
972 return Promise.resolve({ done: false, value: res })
973
974 if (this[EOF$1])
975 return Promise.resolve({ done: true })
976
977 let resolve = null;
978 let reject = null;
979 const onerr = er => {
980 this.removeListener('data', ondata);
981 this.removeListener('end', onend);
982 reject(er);
983 };
984 const ondata = value => {
985 this.removeListener('error', onerr);
986 this.removeListener('end', onend);
987 this.pause();
988 resolve({ value: value, done: !!this[EOF$1] });
989 };
990 const onend = () => {
991 this.removeListener('error', onerr);
992 this.removeListener('data', ondata);
993 resolve({ done: true });
994 };
995 const ondestroy = () => onerr(new Error('stream destroyed'));
996 return new Promise((res, rej) => {
997 reject = rej;
998 resolve = res;
999 this.once(DESTROYED, ondestroy);
1000 this.once('error', onerr);
1001 this.once('end', onend);
1002 this.once('data', ondata);
1003 })
1004 };
1005
1006 return { next }
1007 }
1008
1009 // for (let chunk of stream)
1010 [ITERATOR] () {
1011 const next = () => {
1012 const value = this.read();
1013 const done = value === null;
1014 return { value, done }
1015 };
1016 return { next }
1017 }
1018
1019 destroy (er) {
1020 if (this[DESTROYED]) {
1021 if (er)
1022 this.emit('error', er);
1023 else
1024 this.emit(DESTROYED);
1025 return this
1026 }
1027
1028 this[DESTROYED] = true;
1029
1030 // throw away all buffered data, it's never coming out
1031 this.buffer = new yallist();
1032 this[BUFFERLENGTH] = 0;
1033
1034 if (typeof this.close === 'function' && !this[CLOSED])
1035 this.close();
1036
1037 if (er)
1038 this.emit('error', er);
1039 else // if no error to emit, still reject pending promises
1040 this.emit(DESTROYED);
1041
1042 return this
1043 }
1044
1045 static isStream (s) {
1046 return !!s && (s instanceof Minipass || s instanceof Stream__default['default'] ||
1047 s instanceof Events__default['default'] && (
1048 typeof s.pipe === 'function' || // readable
1049 (typeof s.write === 'function' && typeof s.end === 'function') // writable
1050 ))
1051 }
1052};
1053
1054// Update with any zlib constants that are added or changed in the future.
1055// Node v6 didn't export this, so we just hard code the version and rely
1056// on all the other hard-coded values from zlib v4736. When node v6
1057// support drops, we can just export the realZlibConstants object.
1058const realZlibConstants = realZlib__default['default'].constants ||
1059 /* istanbul ignore next */ { ZLIB_VERNUM: 4736 };
1060
1061var constants = Object.freeze(Object.assign(Object.create(null), {
1062 Z_NO_FLUSH: 0,
1063 Z_PARTIAL_FLUSH: 1,
1064 Z_SYNC_FLUSH: 2,
1065 Z_FULL_FLUSH: 3,
1066 Z_FINISH: 4,
1067 Z_BLOCK: 5,
1068 Z_OK: 0,
1069 Z_STREAM_END: 1,
1070 Z_NEED_DICT: 2,
1071 Z_ERRNO: -1,
1072 Z_STREAM_ERROR: -2,
1073 Z_DATA_ERROR: -3,
1074 Z_MEM_ERROR: -4,
1075 Z_BUF_ERROR: -5,
1076 Z_VERSION_ERROR: -6,
1077 Z_NO_COMPRESSION: 0,
1078 Z_BEST_SPEED: 1,
1079 Z_BEST_COMPRESSION: 9,
1080 Z_DEFAULT_COMPRESSION: -1,
1081 Z_FILTERED: 1,
1082 Z_HUFFMAN_ONLY: 2,
1083 Z_RLE: 3,
1084 Z_FIXED: 4,
1085 Z_DEFAULT_STRATEGY: 0,
1086 DEFLATE: 1,
1087 INFLATE: 2,
1088 GZIP: 3,
1089 GUNZIP: 4,
1090 DEFLATERAW: 5,
1091 INFLATERAW: 6,
1092 UNZIP: 7,
1093 BROTLI_DECODE: 8,
1094 BROTLI_ENCODE: 9,
1095 Z_MIN_WINDOWBITS: 8,
1096 Z_MAX_WINDOWBITS: 15,
1097 Z_DEFAULT_WINDOWBITS: 15,
1098 Z_MIN_CHUNK: 64,
1099 Z_MAX_CHUNK: Infinity,
1100 Z_DEFAULT_CHUNK: 16384,
1101 Z_MIN_MEMLEVEL: 1,
1102 Z_MAX_MEMLEVEL: 9,
1103 Z_DEFAULT_MEMLEVEL: 8,
1104 Z_MIN_LEVEL: -1,
1105 Z_MAX_LEVEL: 9,
1106 Z_DEFAULT_LEVEL: -1,
1107 BROTLI_OPERATION_PROCESS: 0,
1108 BROTLI_OPERATION_FLUSH: 1,
1109 BROTLI_OPERATION_FINISH: 2,
1110 BROTLI_OPERATION_EMIT_METADATA: 3,
1111 BROTLI_MODE_GENERIC: 0,
1112 BROTLI_MODE_TEXT: 1,
1113 BROTLI_MODE_FONT: 2,
1114 BROTLI_DEFAULT_MODE: 0,
1115 BROTLI_MIN_QUALITY: 0,
1116 BROTLI_MAX_QUALITY: 11,
1117 BROTLI_DEFAULT_QUALITY: 11,
1118 BROTLI_MIN_WINDOW_BITS: 10,
1119 BROTLI_MAX_WINDOW_BITS: 24,
1120 BROTLI_LARGE_MAX_WINDOW_BITS: 30,
1121 BROTLI_DEFAULT_WINDOW: 22,
1122 BROTLI_MIN_INPUT_BLOCK_BITS: 16,
1123 BROTLI_MAX_INPUT_BLOCK_BITS: 24,
1124 BROTLI_PARAM_MODE: 0,
1125 BROTLI_PARAM_QUALITY: 1,
1126 BROTLI_PARAM_LGWIN: 2,
1127 BROTLI_PARAM_LGBLOCK: 3,
1128 BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
1129 BROTLI_PARAM_SIZE_HINT: 5,
1130 BROTLI_PARAM_LARGE_WINDOW: 6,
1131 BROTLI_PARAM_NPOSTFIX: 7,
1132 BROTLI_PARAM_NDIRECT: 8,
1133 BROTLI_DECODER_RESULT_ERROR: 0,
1134 BROTLI_DECODER_RESULT_SUCCESS: 1,
1135 BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
1136 BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
1137 BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
1138 BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
1139 BROTLI_DECODER_NO_ERROR: 0,
1140 BROTLI_DECODER_SUCCESS: 1,
1141 BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
1142 BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
1143 BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,
1144 BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,
1145 BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,
1146 BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,
1147 BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,
1148 BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,
1149 BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,
1150 BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,
1151 BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,
1152 BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,
1153 BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,
1154 BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,
1155 BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,
1156 BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,
1157 BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,
1158 BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,
1159 BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,
1160 BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,
1161 BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,
1162 BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,
1163 BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,
1164 BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,
1165 BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,
1166 BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,
1167 BROTLI_DECODER_ERROR_UNREACHABLE: -31,
1168}, realZlibConstants));
1169
1170var minizlib = createCommonjsModule(function (module, exports) {
1171
1172
1173const Buffer = require$$0__default$1['default'].Buffer;
1174
1175
1176const constants$1 = exports.constants = constants;
1177
1178
1179const OriginalBufferConcat = Buffer.concat;
1180
1181const _superWrite = Symbol('_superWrite');
1182class ZlibError extends Error {
1183 constructor (err) {
1184 super('zlib: ' + err.message);
1185 this.code = err.code;
1186 this.errno = err.errno;
1187 /* istanbul ignore if */
1188 if (!this.code)
1189 this.code = 'ZLIB_ERROR';
1190
1191 this.message = 'zlib: ' + err.message;
1192 Error.captureStackTrace(this, this.constructor);
1193 }
1194
1195 get name () {
1196 return 'ZlibError'
1197 }
1198}
1199
1200// the Zlib class they all inherit from
1201// This thing manages the queue of requests, and returns
1202// true or false if there is anything in the queue when
1203// you call the .write() method.
1204const _opts = Symbol('opts');
1205const _flushFlag = Symbol('flushFlag');
1206const _finishFlushFlag = Symbol('finishFlushFlag');
1207const _fullFlushFlag = Symbol('fullFlushFlag');
1208const _handle = Symbol('handle');
1209const _onError = Symbol('onError');
1210const _sawError = Symbol('sawError');
1211const _level = Symbol('level');
1212const _strategy = Symbol('strategy');
1213const _ended = Symbol('ended');
1214
1215class ZlibBase extends minipass {
1216 constructor (opts, mode) {
1217 if (!opts || typeof opts !== 'object')
1218 throw new TypeError('invalid options for ZlibBase constructor')
1219
1220 super(opts);
1221 this[_sawError] = false;
1222 this[_ended] = false;
1223 this[_opts] = opts;
1224
1225 this[_flushFlag] = opts.flush;
1226 this[_finishFlushFlag] = opts.finishFlush;
1227 // this will throw if any options are invalid for the class selected
1228 try {
1229 this[_handle] = new realZlib__default['default'][mode](opts);
1230 } catch (er) {
1231 // make sure that all errors get decorated properly
1232 throw new ZlibError(er)
1233 }
1234
1235 this[_onError] = (err) => {
1236 // no sense raising multiple errors, since we abort on the first one.
1237 if (this[_sawError])
1238 return
1239
1240 this[_sawError] = true;
1241
1242 // there is no way to cleanly recover.
1243 // continuing only obscures problems.
1244 this.close();
1245 this.emit('error', err);
1246 };
1247
1248 this[_handle].on('error', er => this[_onError](new ZlibError(er)));
1249 this.once('end', () => this.close);
1250 }
1251
1252 close () {
1253 if (this[_handle]) {
1254 this[_handle].close();
1255 this[_handle] = null;
1256 this.emit('close');
1257 }
1258 }
1259
1260 reset () {
1261 if (!this[_sawError]) {
1262 assert__default['default'](this[_handle], 'zlib binding closed');
1263 return this[_handle].reset()
1264 }
1265 }
1266
1267 flush (flushFlag) {
1268 if (this.ended)
1269 return
1270
1271 if (typeof flushFlag !== 'number')
1272 flushFlag = this[_fullFlushFlag];
1273 this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag }));
1274 }
1275
1276 end (chunk, encoding, cb) {
1277 if (chunk)
1278 this.write(chunk, encoding);
1279 this.flush(this[_finishFlushFlag]);
1280 this[_ended] = true;
1281 return super.end(null, null, cb)
1282 }
1283
1284 get ended () {
1285 return this[_ended]
1286 }
1287
1288 write (chunk, encoding, cb) {
1289 // process the chunk using the sync process
1290 // then super.write() all the outputted chunks
1291 if (typeof encoding === 'function')
1292 cb = encoding, encoding = 'utf8';
1293
1294 if (typeof chunk === 'string')
1295 chunk = Buffer.from(chunk, encoding);
1296
1297 if (this[_sawError])
1298 return
1299 assert__default['default'](this[_handle], 'zlib binding closed');
1300
1301 // _processChunk tries to .close() the native handle after it's done, so we
1302 // intercept that by temporarily making it a no-op.
1303 const nativeHandle = this[_handle]._handle;
1304 const originalNativeClose = nativeHandle.close;
1305 nativeHandle.close = () => {};
1306 const originalClose = this[_handle].close;
1307 this[_handle].close = () => {};
1308 // It also calls `Buffer.concat()` at the end, which may be convenient
1309 // for some, but which we are not interested in as it slows us down.
1310 Buffer.concat = (args) => args;
1311 let result;
1312 try {
1313 const flushFlag = typeof chunk[_flushFlag] === 'number'
1314 ? chunk[_flushFlag] : this[_flushFlag];
1315 result = this[_handle]._processChunk(chunk, flushFlag);
1316 // if we don't throw, reset it back how it was
1317 Buffer.concat = OriginalBufferConcat;
1318 } catch (err) {
1319 // or if we do, put Buffer.concat() back before we emit error
1320 // Error events call into user code, which may call Buffer.concat()
1321 Buffer.concat = OriginalBufferConcat;
1322 this[_onError](new ZlibError(err));
1323 } finally {
1324 if (this[_handle]) {
1325 // Core zlib resets `_handle` to null after attempting to close the
1326 // native handle. Our no-op handler prevented actual closure, but we
1327 // need to restore the `._handle` property.
1328 this[_handle]._handle = nativeHandle;
1329 nativeHandle.close = originalNativeClose;
1330 this[_handle].close = originalClose;
1331 // `_processChunk()` adds an 'error' listener. If we don't remove it
1332 // after each call, these handlers start piling up.
1333 this[_handle].removeAllListeners('error');
1334 // make sure OUR error listener is still attached tho
1335 }
1336 }
1337
1338 if (this[_handle])
1339 this[_handle].on('error', er => this[_onError](new ZlibError(er)));
1340
1341 let writeReturn;
1342 if (result) {
1343 if (Array.isArray(result) && result.length > 0) {
1344 // The first buffer is always `handle._outBuffer`, which would be
1345 // re-used for later invocations; so, we always have to copy that one.
1346 writeReturn = this[_superWrite](Buffer.from(result[0]));
1347 for (let i = 1; i < result.length; i++) {
1348 writeReturn = this[_superWrite](result[i]);
1349 }
1350 } else {
1351 writeReturn = this[_superWrite](Buffer.from(result));
1352 }
1353 }
1354
1355 if (cb)
1356 cb();
1357 return writeReturn
1358 }
1359
1360 [_superWrite] (data) {
1361 return super.write(data)
1362 }
1363}
1364
1365class Zlib extends ZlibBase {
1366 constructor (opts, mode) {
1367 opts = opts || {};
1368
1369 opts.flush = opts.flush || constants$1.Z_NO_FLUSH;
1370 opts.finishFlush = opts.finishFlush || constants$1.Z_FINISH;
1371 super(opts, mode);
1372
1373 this[_fullFlushFlag] = constants$1.Z_FULL_FLUSH;
1374 this[_level] = opts.level;
1375 this[_strategy] = opts.strategy;
1376 }
1377
1378 params (level, strategy) {
1379 if (this[_sawError])
1380 return
1381
1382 if (!this[_handle])
1383 throw new Error('cannot switch params when binding is closed')
1384
1385 // no way to test this without also not supporting params at all
1386 /* istanbul ignore if */
1387 if (!this[_handle].params)
1388 throw new Error('not supported in this implementation')
1389
1390 if (this[_level] !== level || this[_strategy] !== strategy) {
1391 this.flush(constants$1.Z_SYNC_FLUSH);
1392 assert__default['default'](this[_handle], 'zlib binding closed');
1393 // .params() calls .flush(), but the latter is always async in the
1394 // core zlib. We override .flush() temporarily to intercept that and
1395 // flush synchronously.
1396 const origFlush = this[_handle].flush;
1397 this[_handle].flush = (flushFlag, cb) => {
1398 this.flush(flushFlag);
1399 cb();
1400 };
1401 try {
1402 this[_handle].params(level, strategy);
1403 } finally {
1404 this[_handle].flush = origFlush;
1405 }
1406 /* istanbul ignore else */
1407 if (this[_handle]) {
1408 this[_level] = level;
1409 this[_strategy] = strategy;
1410 }
1411 }
1412 }
1413}
1414
1415// minimal 2-byte header
1416class Deflate extends Zlib {
1417 constructor (opts) {
1418 super(opts, 'Deflate');
1419 }
1420}
1421
1422class Inflate extends Zlib {
1423 constructor (opts) {
1424 super(opts, 'Inflate');
1425 }
1426}
1427
1428// gzip - bigger header, same deflate compression
1429const _portable = Symbol('_portable');
1430class Gzip extends Zlib {
1431 constructor (opts) {
1432 super(opts, 'Gzip');
1433 this[_portable] = opts && !!opts.portable;
1434 }
1435
1436 [_superWrite] (data) {
1437 if (!this[_portable])
1438 return super[_superWrite](data)
1439
1440 // we'll always get the header emitted in one first chunk
1441 // overwrite the OS indicator byte with 0xFF
1442 this[_portable] = false;
1443 data[9] = 255;
1444 return super[_superWrite](data)
1445 }
1446}
1447
1448class Gunzip extends Zlib {
1449 constructor (opts) {
1450 super(opts, 'Gunzip');
1451 }
1452}
1453
1454// raw - no header
1455class DeflateRaw extends Zlib {
1456 constructor (opts) {
1457 super(opts, 'DeflateRaw');
1458 }
1459}
1460
1461class InflateRaw extends Zlib {
1462 constructor (opts) {
1463 super(opts, 'InflateRaw');
1464 }
1465}
1466
1467// auto-detect header.
1468class Unzip extends Zlib {
1469 constructor (opts) {
1470 super(opts, 'Unzip');
1471 }
1472}
1473
1474class Brotli extends ZlibBase {
1475 constructor (opts, mode) {
1476 opts = opts || {};
1477
1478 opts.flush = opts.flush || constants$1.BROTLI_OPERATION_PROCESS;
1479 opts.finishFlush = opts.finishFlush || constants$1.BROTLI_OPERATION_FINISH;
1480
1481 super(opts, mode);
1482
1483 this[_fullFlushFlag] = constants$1.BROTLI_OPERATION_FLUSH;
1484 }
1485}
1486
1487class BrotliCompress extends Brotli {
1488 constructor (opts) {
1489 super(opts, 'BrotliCompress');
1490 }
1491}
1492
1493class BrotliDecompress extends Brotli {
1494 constructor (opts) {
1495 super(opts, 'BrotliDecompress');
1496 }
1497}
1498
1499exports.Deflate = Deflate;
1500exports.Inflate = Inflate;
1501exports.Gzip = Gzip;
1502exports.Gunzip = Gunzip;
1503exports.DeflateRaw = DeflateRaw;
1504exports.InflateRaw = InflateRaw;
1505exports.Unzip = Unzip;
1506/* istanbul ignore else */
1507if (typeof realZlib__default['default'].BrotliCompress === 'function') {
1508 exports.BrotliCompress = BrotliCompress;
1509 exports.BrotliDecompress = BrotliDecompress;
1510} else {
1511 exports.BrotliCompress = exports.BrotliDecompress = class {
1512 constructor () {
1513 throw new Error('Brotli is not supported in this version of Node.js')
1514 }
1515 };
1516}
1517});
1518
1519const SLURP$1 = Symbol('slurp');
1520var readEntry = class ReadEntry extends minipass {
1521 constructor (header, ex, gex) {
1522 super();
1523 // read entries always start life paused. this is to avoid the
1524 // situation where Minipass's auto-ending empty streams results
1525 // in an entry ending before we're ready for it.
1526 this.pause();
1527 this.extended = ex;
1528 this.globalExtended = gex;
1529 this.header = header;
1530 this.startBlockSize = 512 * Math.ceil(header.size / 512);
1531 this.blockRemain = this.startBlockSize;
1532 this.remain = header.size;
1533 this.type = header.type;
1534 this.meta = false;
1535 this.ignore = false;
1536 switch (this.type) {
1537 case 'File':
1538 case 'OldFile':
1539 case 'Link':
1540 case 'SymbolicLink':
1541 case 'CharacterDevice':
1542 case 'BlockDevice':
1543 case 'Directory':
1544 case 'FIFO':
1545 case 'ContiguousFile':
1546 case 'GNUDumpDir':
1547 break
1548
1549 case 'NextFileHasLongLinkpath':
1550 case 'NextFileHasLongPath':
1551 case 'OldGnuLongPath':
1552 case 'GlobalExtendedHeader':
1553 case 'ExtendedHeader':
1554 case 'OldExtendedHeader':
1555 this.meta = true;
1556 break
1557
1558 // NOTE: gnutar and bsdtar treat unrecognized types as 'File'
1559 // it may be worth doing the same, but with a warning.
1560 default:
1561 this.ignore = true;
1562 }
1563
1564 this.path = header.path;
1565 this.mode = header.mode;
1566 if (this.mode)
1567 this.mode = this.mode & 0o7777;
1568 this.uid = header.uid;
1569 this.gid = header.gid;
1570 this.uname = header.uname;
1571 this.gname = header.gname;
1572 this.size = header.size;
1573 this.mtime = header.mtime;
1574 this.atime = header.atime;
1575 this.ctime = header.ctime;
1576 this.linkpath = header.linkpath;
1577 this.uname = header.uname;
1578 this.gname = header.gname;
1579
1580 if (ex)
1581 this[SLURP$1](ex);
1582 if (gex)
1583 this[SLURP$1](gex, true);
1584 }
1585
1586 write (data) {
1587 const writeLen = data.length;
1588 if (writeLen > this.blockRemain)
1589 throw new Error('writing more to entry than is appropriate')
1590
1591 const r = this.remain;
1592 const br = this.blockRemain;
1593 this.remain = Math.max(0, r - writeLen);
1594 this.blockRemain = Math.max(0, br - writeLen);
1595 if (this.ignore)
1596 return true
1597
1598 if (r >= writeLen)
1599 return super.write(data)
1600
1601 // r < writeLen
1602 return super.write(data.slice(0, r))
1603 }
1604
1605 [SLURP$1] (ex, global) {
1606 for (const k in ex) {
1607 // we slurp in everything except for the path attribute in
1608 // a global extended header, because that's weird.
1609 if (ex[k] !== null && ex[k] !== undefined &&
1610 !(global && k === 'path'))
1611 this[k] = ex[k];
1612 }
1613 }
1614};
1615
1616var types = createCommonjsModule(function (module, exports) {
1617// map types from key to human-friendly name
1618exports.name = new Map([
1619 ['0', 'File'],
1620 // same as File
1621 ['', 'OldFile'],
1622 ['1', 'Link'],
1623 ['2', 'SymbolicLink'],
1624 // Devices and FIFOs aren't fully supported
1625 // they are parsed, but skipped when unpacking
1626 ['3', 'CharacterDevice'],
1627 ['4', 'BlockDevice'],
1628 ['5', 'Directory'],
1629 ['6', 'FIFO'],
1630 // same as File
1631 ['7', 'ContiguousFile'],
1632 // pax headers
1633 ['g', 'GlobalExtendedHeader'],
1634 ['x', 'ExtendedHeader'],
1635 // vendor-specific stuff
1636 // skip
1637 ['A', 'SolarisACL'],
1638 // like 5, but with data, which should be skipped
1639 ['D', 'GNUDumpDir'],
1640 // metadata only, skip
1641 ['I', 'Inode'],
1642 // data = link path of next file
1643 ['K', 'NextFileHasLongLinkpath'],
1644 // data = path of next file
1645 ['L', 'NextFileHasLongPath'],
1646 // skip
1647 ['M', 'ContinuationFile'],
1648 // like L
1649 ['N', 'OldGnuLongPath'],
1650 // skip
1651 ['S', 'SparseFile'],
1652 // skip
1653 ['V', 'TapeVolumeHeader'],
1654 // like x
1655 ['X', 'OldExtendedHeader'],
1656]);
1657
1658// map the other direction
1659exports.code = new Map(Array.from(exports.name).map(kv => [kv[1], kv[0]]));
1660});
1661
1662// Tar can encode large and negative numbers using a leading byte of
1663// 0xff for negative, and 0x80 for positive.
1664
1665const encode = (num, buf) => {
1666 if (!Number.isSafeInteger(num))
1667 // The number is so large that javascript cannot represent it with integer
1668 // precision.
1669 throw Error('cannot encode number outside of javascript safe integer range')
1670 else if (num < 0)
1671 encodeNegative(num, buf);
1672 else
1673 encodePositive(num, buf);
1674 return buf
1675};
1676
1677const encodePositive = (num, buf) => {
1678 buf[0] = 0x80;
1679
1680 for (var i = buf.length; i > 1; i--) {
1681 buf[i - 1] = num & 0xff;
1682 num = Math.floor(num / 0x100);
1683 }
1684};
1685
1686const encodeNegative = (num, buf) => {
1687 buf[0] = 0xff;
1688 var flipped = false;
1689 num = num * -1;
1690 for (var i = buf.length; i > 1; i--) {
1691 var byte = num & 0xff;
1692 num = Math.floor(num / 0x100);
1693 if (flipped)
1694 buf[i - 1] = onesComp(byte);
1695 else if (byte === 0)
1696 buf[i - 1] = 0;
1697 else {
1698 flipped = true;
1699 buf[i - 1] = twosComp(byte);
1700 }
1701 }
1702};
1703
1704const parse$5 = (buf) => {
1705 const pre = buf[0];
1706 const value = pre === 0x80 ? pos(buf.slice(1, buf.length))
1707 : pre === 0xff ? twos(buf)
1708 : null;
1709 if (value === null)
1710 throw Error('invalid base256 encoding')
1711
1712 if (!Number.isSafeInteger(value))
1713 // The number is so large that javascript cannot represent it with integer
1714 // precision.
1715 throw Error('parsed number outside of javascript safe integer range')
1716
1717 return value
1718};
1719
1720const twos = (buf) => {
1721 var len = buf.length;
1722 var sum = 0;
1723 var flipped = false;
1724 for (var i = len - 1; i > -1; i--) {
1725 var byte = buf[i];
1726 var f;
1727 if (flipped)
1728 f = onesComp(byte);
1729 else if (byte === 0)
1730 f = byte;
1731 else {
1732 flipped = true;
1733 f = twosComp(byte);
1734 }
1735 if (f !== 0)
1736 sum -= f * Math.pow(256, len - i - 1);
1737 }
1738 return sum
1739};
1740
1741const pos = (buf) => {
1742 var len = buf.length;
1743 var sum = 0;
1744 for (var i = len - 1; i > -1; i--) {
1745 var byte = buf[i];
1746 if (byte !== 0)
1747 sum += byte * Math.pow(256, len - i - 1);
1748 }
1749 return sum
1750};
1751
1752const onesComp = byte => (0xff ^ byte) & 0xff;
1753
1754const twosComp = byte => ((0xff ^ byte) + 1) & 0xff;
1755
1756var largeNumbers = {
1757 encode,
1758 parse: parse$5,
1759};
1760
1761// parse a 512-byte header block to a data object, or vice-versa
1762// encode returns `true` if a pax extended header is needed, because
1763// the data could not be faithfully encoded in a simple header.
1764// (Also, check header.needPax to see if it needs a pax header.)
1765
1766
1767const pathModule = path__default['default'].posix;
1768
1769
1770const SLURP = Symbol('slurp');
1771const TYPE = Symbol('type');
1772
1773class Header {
1774 constructor (data, off, ex, gex) {
1775 this.cksumValid = false;
1776 this.needPax = false;
1777 this.nullBlock = false;
1778
1779 this.block = null;
1780 this.path = null;
1781 this.mode = null;
1782 this.uid = null;
1783 this.gid = null;
1784 this.size = null;
1785 this.mtime = null;
1786 this.cksum = null;
1787 this[TYPE] = '0';
1788 this.linkpath = null;
1789 this.uname = null;
1790 this.gname = null;
1791 this.devmaj = 0;
1792 this.devmin = 0;
1793 this.atime = null;
1794 this.ctime = null;
1795
1796 if (Buffer.isBuffer(data))
1797 this.decode(data, off || 0, ex, gex);
1798 else if (data)
1799 this.set(data);
1800 }
1801
1802 decode (buf, off, ex, gex) {
1803 if (!off)
1804 off = 0;
1805
1806 if (!buf || !(buf.length >= off + 512))
1807 throw new Error('need 512 bytes for header')
1808
1809 this.path = decString(buf, off, 100);
1810 this.mode = decNumber(buf, off + 100, 8);
1811 this.uid = decNumber(buf, off + 108, 8);
1812 this.gid = decNumber(buf, off + 116, 8);
1813 this.size = decNumber(buf, off + 124, 12);
1814 this.mtime = decDate(buf, off + 136, 12);
1815 this.cksum = decNumber(buf, off + 148, 12);
1816
1817 // if we have extended or global extended headers, apply them now
1818 // See https://github.com/npm/node-tar/pull/187
1819 this[SLURP](ex);
1820 this[SLURP](gex, true);
1821
1822 // old tar versions marked dirs as a file with a trailing /
1823 this[TYPE] = decString(buf, off + 156, 1);
1824 if (this[TYPE] === '')
1825 this[TYPE] = '0';
1826 if (this[TYPE] === '0' && this.path.substr(-1) === '/')
1827 this[TYPE] = '5';
1828
1829 // tar implementations sometimes incorrectly put the stat(dir).size
1830 // as the size in the tarball, even though Directory entries are
1831 // not able to have any body at all. In the very rare chance that
1832 // it actually DOES have a body, we weren't going to do anything with
1833 // it anyway, and it'll just be a warning about an invalid header.
1834 if (this[TYPE] === '5')
1835 this.size = 0;
1836
1837 this.linkpath = decString(buf, off + 157, 100);
1838 if (buf.slice(off + 257, off + 265).toString() === 'ustar\u000000') {
1839 this.uname = decString(buf, off + 265, 32);
1840 this.gname = decString(buf, off + 297, 32);
1841 this.devmaj = decNumber(buf, off + 329, 8);
1842 this.devmin = decNumber(buf, off + 337, 8);
1843 if (buf[off + 475] !== 0) {
1844 // definitely a prefix, definitely >130 chars.
1845 const prefix = decString(buf, off + 345, 155);
1846 this.path = prefix + '/' + this.path;
1847 } else {
1848 const prefix = decString(buf, off + 345, 130);
1849 if (prefix)
1850 this.path = prefix + '/' + this.path;
1851 this.atime = decDate(buf, off + 476, 12);
1852 this.ctime = decDate(buf, off + 488, 12);
1853 }
1854 }
1855
1856 let sum = 8 * 0x20;
1857 for (let i = off; i < off + 148; i++)
1858 sum += buf[i];
1859
1860 for (let i = off + 156; i < off + 512; i++)
1861 sum += buf[i];
1862
1863 this.cksumValid = sum === this.cksum;
1864 if (this.cksum === null && sum === 8 * 0x20)
1865 this.nullBlock = true;
1866 }
1867
1868 [SLURP] (ex, global) {
1869 for (const k in ex) {
1870 // we slurp in everything except for the path attribute in
1871 // a global extended header, because that's weird.
1872 if (ex[k] !== null && ex[k] !== undefined &&
1873 !(global && k === 'path'))
1874 this[k] = ex[k];
1875 }
1876 }
1877
1878 encode (buf, off) {
1879 if (!buf) {
1880 buf = this.block = Buffer.alloc(512);
1881 off = 0;
1882 }
1883
1884 if (!off)
1885 off = 0;
1886
1887 if (!(buf.length >= off + 512))
1888 throw new Error('need 512 bytes for header')
1889
1890 const prefixSize = this.ctime || this.atime ? 130 : 155;
1891 const split = splitPrefix(this.path || '', prefixSize);
1892 const path = split[0];
1893 const prefix = split[1];
1894 this.needPax = split[2];
1895
1896 this.needPax = encString(buf, off, 100, path) || this.needPax;
1897 this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax;
1898 this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax;
1899 this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax;
1900 this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax;
1901 this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax;
1902 buf[off + 156] = this[TYPE].charCodeAt(0);
1903 this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax;
1904 buf.write('ustar\u000000', off + 257, 8);
1905 this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax;
1906 this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax;
1907 this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax;
1908 this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax;
1909 this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax;
1910 if (buf[off + 475] !== 0)
1911 this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax;
1912 else {
1913 this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax;
1914 this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax;
1915 this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax;
1916 }
1917
1918 let sum = 8 * 0x20;
1919 for (let i = off; i < off + 148; i++)
1920 sum += buf[i];
1921
1922 for (let i = off + 156; i < off + 512; i++)
1923 sum += buf[i];
1924
1925 this.cksum = sum;
1926 encNumber(buf, off + 148, 8, this.cksum);
1927 this.cksumValid = true;
1928
1929 return this.needPax
1930 }
1931
1932 set (data) {
1933 for (const i in data) {
1934 if (data[i] !== null && data[i] !== undefined)
1935 this[i] = data[i];
1936 }
1937 }
1938
1939 get type () {
1940 return types.name.get(this[TYPE]) || this[TYPE]
1941 }
1942
1943 get typeKey () {
1944 return this[TYPE]
1945 }
1946
1947 set type (type) {
1948 if (types.code.has(type))
1949 this[TYPE] = types.code.get(type);
1950 else
1951 this[TYPE] = type;
1952 }
1953}
1954
1955const splitPrefix = (p, prefixSize) => {
1956 const pathSize = 100;
1957 let pp = p;
1958 let prefix = '';
1959 let ret;
1960 const root = pathModule.parse(p).root || '.';
1961
1962 if (Buffer.byteLength(pp) < pathSize)
1963 ret = [pp, prefix, false];
1964 else {
1965 // first set prefix to the dir, and path to the base
1966 prefix = pathModule.dirname(pp);
1967 pp = pathModule.basename(pp);
1968
1969 do {
1970 // both fit!
1971 if (Buffer.byteLength(pp) <= pathSize &&
1972 Buffer.byteLength(prefix) <= prefixSize)
1973 ret = [pp, prefix, false];
1974
1975 // prefix fits in prefix, but path doesn't fit in path
1976 else if (Buffer.byteLength(pp) > pathSize &&
1977 Buffer.byteLength(prefix) <= prefixSize)
1978 ret = [pp.substr(0, pathSize - 1), prefix, true];
1979
1980 else {
1981 // make path take a bit from prefix
1982 pp = pathModule.join(pathModule.basename(prefix), pp);
1983 prefix = pathModule.dirname(prefix);
1984 }
1985 } while (prefix !== root && !ret)
1986
1987 // at this point, found no resolution, just truncate
1988 if (!ret)
1989 ret = [p.substr(0, pathSize - 1), '', true];
1990 }
1991 return ret
1992};
1993
1994const decString = (buf, off, size) =>
1995 buf.slice(off, off + size).toString('utf8').replace(/\0.*/, '');
1996
1997const decDate = (buf, off, size) =>
1998 numToDate(decNumber(buf, off, size));
1999
2000const numToDate = num => num === null ? null : new Date(num * 1000);
2001
2002const decNumber = (buf, off, size) =>
2003 buf[off] & 0x80 ? largeNumbers.parse(buf.slice(off, off + size))
2004 : decSmallNumber(buf, off, size);
2005
2006const nanNull = value => isNaN(value) ? null : value;
2007
2008const decSmallNumber = (buf, off, size) =>
2009 nanNull(parseInt(
2010 buf.slice(off, off + size)
2011 .toString('utf8').replace(/\0.*$/, '').trim(), 8));
2012
2013// the maximum encodable as a null-terminated octal, by field size
2014const MAXNUM = {
2015 12: 0o77777777777,
2016 8: 0o7777777,
2017};
2018
2019const encNumber = (buf, off, size, number) =>
2020 number === null ? false :
2021 number > MAXNUM[size] || number < 0
2022 ? (largeNumbers.encode(number, buf.slice(off, off + size)), true)
2023 : (encSmallNumber(buf, off, size, number), false);
2024
2025const encSmallNumber = (buf, off, size, number) =>
2026 buf.write(octalString(number, size), off, size, 'ascii');
2027
2028const octalString = (number, size) =>
2029 padOctal(Math.floor(number).toString(8), size);
2030
2031const padOctal = (string, size) =>
2032 (string.length === size - 1 ? string
2033 : new Array(size - string.length - 1).join('0') + string + ' ') + '\0';
2034
2035const encDate = (buf, off, size, date) =>
2036 date === null ? false :
2037 encNumber(buf, off, size, date.getTime() / 1000);
2038
2039// enough to fill the longest string we've got
2040const NULLS = new Array(156).join('\0');
2041// pad with nulls, return true if it's longer or non-ascii
2042const encString = (buf, off, size, string) =>
2043 string === null ? false :
2044 (buf.write(string + NULLS, off, size, 'utf8'),
2045 string.length !== Buffer.byteLength(string) || string.length > size);
2046
2047var header = Header;
2048
2049class Pax {
2050 constructor (obj, global) {
2051 this.atime = obj.atime || null;
2052 this.charset = obj.charset || null;
2053 this.comment = obj.comment || null;
2054 this.ctime = obj.ctime || null;
2055 this.gid = obj.gid || null;
2056 this.gname = obj.gname || null;
2057 this.linkpath = obj.linkpath || null;
2058 this.mtime = obj.mtime || null;
2059 this.path = obj.path || null;
2060 this.size = obj.size || null;
2061 this.uid = obj.uid || null;
2062 this.uname = obj.uname || null;
2063 this.dev = obj.dev || null;
2064 this.ino = obj.ino || null;
2065 this.nlink = obj.nlink || null;
2066 this.global = global || false;
2067 }
2068
2069 encode () {
2070 const body = this.encodeBody();
2071 if (body === '')
2072 return null
2073
2074 const bodyLen = Buffer.byteLength(body);
2075 // round up to 512 bytes
2076 // add 512 for header
2077 const bufLen = 512 * Math.ceil(1 + bodyLen / 512);
2078 const buf = Buffer.allocUnsafe(bufLen);
2079
2080 // 0-fill the header section, it might not hit every field
2081 for (let i = 0; i < 512; i++)
2082 buf[i] = 0;
2083
2084 new header({
2085 // XXX split the path
2086 // then the path should be PaxHeader + basename, but less than 99,
2087 // prepend with the dirname
2088 path: ('PaxHeader/' + path__default['default'].basename(this.path)).slice(0, 99),
2089 mode: this.mode || 0o644,
2090 uid: this.uid || null,
2091 gid: this.gid || null,
2092 size: bodyLen,
2093 mtime: this.mtime || null,
2094 type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader',
2095 linkpath: '',
2096 uname: this.uname || '',
2097 gname: this.gname || '',
2098 devmaj: 0,
2099 devmin: 0,
2100 atime: this.atime || null,
2101 ctime: this.ctime || null,
2102 }).encode(buf);
2103
2104 buf.write(body, 512, bodyLen, 'utf8');
2105
2106 // null pad after the body
2107 for (let i = bodyLen + 512; i < buf.length; i++)
2108 buf[i] = 0;
2109
2110 return buf
2111 }
2112
2113 encodeBody () {
2114 return (
2115 this.encodeField('path') +
2116 this.encodeField('ctime') +
2117 this.encodeField('atime') +
2118 this.encodeField('dev') +
2119 this.encodeField('ino') +
2120 this.encodeField('nlink') +
2121 this.encodeField('charset') +
2122 this.encodeField('comment') +
2123 this.encodeField('gid') +
2124 this.encodeField('gname') +
2125 this.encodeField('linkpath') +
2126 this.encodeField('mtime') +
2127 this.encodeField('size') +
2128 this.encodeField('uid') +
2129 this.encodeField('uname')
2130 )
2131 }
2132
2133 encodeField (field) {
2134 if (this[field] === null || this[field] === undefined)
2135 return ''
2136 const v = this[field] instanceof Date ? this[field].getTime() / 1000
2137 : this[field];
2138 const s = ' ' +
2139 (field === 'dev' || field === 'ino' || field === 'nlink'
2140 ? 'SCHILY.' : '') +
2141 field + '=' + v + '\n';
2142 const byteLen = Buffer.byteLength(s);
2143 // the digits includes the length of the digits in ascii base-10
2144 // so if it's 9 characters, then adding 1 for the 9 makes it 10
2145 // which makes it 11 chars.
2146 let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1;
2147 if (byteLen + digits >= Math.pow(10, digits))
2148 digits += 1;
2149 const len = digits + byteLen;
2150 return len + s
2151 }
2152}
2153
2154Pax.parse = (string, ex, g) => new Pax(merge(parseKV(string), ex), g);
2155
2156const merge = (a, b) =>
2157 b ? Object.keys(a).reduce((s, k) => (s[k] = a[k], s), b) : a;
2158
2159const parseKV = string =>
2160 string
2161 .replace(/\n$/, '')
2162 .split('\n')
2163 .reduce(parseKVLine, Object.create(null));
2164
2165const parseKVLine = (set, line) => {
2166 const n = parseInt(line, 10);
2167
2168 // XXX Values with \n in them will fail this.
2169 // Refactor to not be a naive line-by-line parse.
2170 if (n !== Buffer.byteLength(line) + 1)
2171 return set
2172
2173 line = line.substr((n + ' ').length);
2174 const kv = line.split('=');
2175 const k = kv.shift().replace(/^SCHILY\.(dev|ino|nlink)/, '$1');
2176 if (!k)
2177 return set
2178
2179 const v = kv.join('=');
2180 set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k)
2181 ? new Date(v * 1000)
2182 : /^[0-9]+$/.test(v) ? +v
2183 : v;
2184 return set
2185};
2186
2187var pax = Pax;
2188
2189var warnMixin = Base => class extends Base {
2190 warn (code, message, data = {}) {
2191 if (this.file)
2192 data.file = this.file;
2193 if (this.cwd)
2194 data.cwd = this.cwd;
2195 data.code = message instanceof Error && message.code || code;
2196 data.tarCode = code;
2197 if (!this.strict && data.recoverable !== false) {
2198 if (message instanceof Error) {
2199 data = Object.assign(message, data);
2200 message = message.message;
2201 }
2202 this.emit('warn', data.tarCode, message, data);
2203 } else if (message instanceof Error)
2204 this.emit('error', Object.assign(message, data));
2205 else
2206 this.emit('error', Object.assign(new Error(`${code}: ${message}`), data));
2207 }
2208};
2209
2210// When writing files on Windows, translate the characters to their
2211// 0xf000 higher-encoded versions.
2212
2213const raw = [
2214 '|',
2215 '<',
2216 '>',
2217 '?',
2218 ':',
2219];
2220
2221const win = raw.map(char =>
2222 String.fromCharCode(0xf000 + char.charCodeAt(0)));
2223
2224const toWin = new Map(raw.map((char, i) => [char, win[i]]));
2225const toRaw = new Map(win.map((char, i) => [char, raw[i]]));
2226
2227var winchars = {
2228 encode: s => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s),
2229 decode: s => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s),
2230};
2231
2232var modeFix = (mode, isDir, portable) => {
2233 mode &= 0o7777;
2234
2235 // in portable mode, use the minimum reasonable umask
2236 // if this system creates files with 0o664 by default
2237 // (as some linux distros do), then we'll write the
2238 // archive with 0o644 instead. Also, don't ever create
2239 // a file that is not readable/writable by the owner.
2240 if (portable)
2241 mode = (mode | 0o600) & ~0o22;
2242
2243 // if dirs are readable, then they should be listable
2244 if (isDir) {
2245 if (mode & 0o400)
2246 mode |= 0o100;
2247 if (mode & 0o40)
2248 mode |= 0o10;
2249 if (mode & 0o4)
2250 mode |= 0o1;
2251 }
2252 return mode
2253};
2254
2255const maxReadSize = 16 * 1024 * 1024;
2256const PROCESS$1 = Symbol('process');
2257const FILE$1 = Symbol('file');
2258const DIRECTORY$1 = Symbol('directory');
2259const SYMLINK$1 = Symbol('symlink');
2260const HARDLINK$1 = Symbol('hardlink');
2261const HEADER = Symbol('header');
2262const READ = Symbol('read');
2263const LSTAT = Symbol('lstat');
2264const ONLSTAT = Symbol('onlstat');
2265const ONREAD = Symbol('onread');
2266const ONREADLINK = Symbol('onreadlink');
2267const OPENFILE = Symbol('openfile');
2268const ONOPENFILE = Symbol('onopenfile');
2269const CLOSE = Symbol('close');
2270const MODE = Symbol('mode');
2271
2272
2273
2274
2275
2276const WriteEntry = warnMixin(class WriteEntry extends minipass {
2277 constructor (p, opt) {
2278 opt = opt || {};
2279 super(opt);
2280 if (typeof p !== 'string')
2281 throw new TypeError('path is required')
2282 this.path = p;
2283 // suppress atime, ctime, uid, gid, uname, gname
2284 this.portable = !!opt.portable;
2285 // until node has builtin pwnam functions, this'll have to do
2286 this.myuid = process.getuid && process.getuid();
2287 this.myuser = process.env.USER || '';
2288 this.maxReadSize = opt.maxReadSize || maxReadSize;
2289 this.linkCache = opt.linkCache || new Map();
2290 this.statCache = opt.statCache || new Map();
2291 this.preservePaths = !!opt.preservePaths;
2292 this.cwd = opt.cwd || process.cwd();
2293 this.strict = !!opt.strict;
2294 this.noPax = !!opt.noPax;
2295 this.noMtime = !!opt.noMtime;
2296 this.mtime = opt.mtime || null;
2297
2298 if (typeof opt.onwarn === 'function')
2299 this.on('warn', opt.onwarn);
2300
2301 let pathWarn = false;
2302 if (!this.preservePaths && path__default['default'].win32.isAbsolute(p)) {
2303 // absolutes on posix are also absolutes on win32
2304 // so we only need to test this one to get both
2305 const parsed = path__default['default'].win32.parse(p);
2306 this.path = p.substr(parsed.root.length);
2307 pathWarn = parsed.root;
2308 }
2309
2310 this.win32 = !!opt.win32 || process.platform === 'win32';
2311 if (this.win32) {
2312 this.path = winchars.decode(this.path.replace(/\\/g, '/'));
2313 p = p.replace(/\\/g, '/');
2314 }
2315
2316 this.absolute = opt.absolute || path__default['default'].resolve(this.cwd, p);
2317
2318 if (this.path === '')
2319 this.path = './';
2320
2321 if (pathWarn) {
2322 this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, {
2323 entry: this,
2324 path: pathWarn + this.path,
2325 });
2326 }
2327
2328 if (this.statCache.has(this.absolute))
2329 this[ONLSTAT](this.statCache.get(this.absolute));
2330 else
2331 this[LSTAT]();
2332 }
2333
2334 [LSTAT] () {
2335 fs__default['default'].lstat(this.absolute, (er, stat) => {
2336 if (er)
2337 return this.emit('error', er)
2338 this[ONLSTAT](stat);
2339 });
2340 }
2341
2342 [ONLSTAT] (stat) {
2343 this.statCache.set(this.absolute, stat);
2344 this.stat = stat;
2345 if (!stat.isFile())
2346 stat.size = 0;
2347 this.type = getType(stat);
2348 this.emit('stat', stat);
2349 this[PROCESS$1]();
2350 }
2351
2352 [PROCESS$1] () {
2353 switch (this.type) {
2354 case 'File': return this[FILE$1]()
2355 case 'Directory': return this[DIRECTORY$1]()
2356 case 'SymbolicLink': return this[SYMLINK$1]()
2357 // unsupported types are ignored.
2358 default: return this.end()
2359 }
2360 }
2361
2362 [MODE] (mode) {
2363 return modeFix(mode, this.type === 'Directory', this.portable)
2364 }
2365
2366 [HEADER] () {
2367 if (this.type === 'Directory' && this.portable)
2368 this.noMtime = true;
2369
2370 this.header = new header({
2371 path: this.path,
2372 linkpath: this.linkpath,
2373 // only the permissions and setuid/setgid/sticky bitflags
2374 // not the higher-order bits that specify file type
2375 mode: this[MODE](this.stat.mode),
2376 uid: this.portable ? null : this.stat.uid,
2377 gid: this.portable ? null : this.stat.gid,
2378 size: this.stat.size,
2379 mtime: this.noMtime ? null : this.mtime || this.stat.mtime,
2380 type: this.type,
2381 uname: this.portable ? null :
2382 this.stat.uid === this.myuid ? this.myuser : '',
2383 atime: this.portable ? null : this.stat.atime,
2384 ctime: this.portable ? null : this.stat.ctime,
2385 });
2386
2387 if (this.header.encode() && !this.noPax) {
2388 this.write(new pax({
2389 atime: this.portable ? null : this.header.atime,
2390 ctime: this.portable ? null : this.header.ctime,
2391 gid: this.portable ? null : this.header.gid,
2392 mtime: this.noMtime ? null : this.mtime || this.header.mtime,
2393 path: this.path,
2394 linkpath: this.linkpath,
2395 size: this.header.size,
2396 uid: this.portable ? null : this.header.uid,
2397 uname: this.portable ? null : this.header.uname,
2398 dev: this.portable ? null : this.stat.dev,
2399 ino: this.portable ? null : this.stat.ino,
2400 nlink: this.portable ? null : this.stat.nlink,
2401 }).encode());
2402 }
2403 this.write(this.header.block);
2404 }
2405
2406 [DIRECTORY$1] () {
2407 if (this.path.substr(-1) !== '/')
2408 this.path += '/';
2409 this.stat.size = 0;
2410 this[HEADER]();
2411 this.end();
2412 }
2413
2414 [SYMLINK$1] () {
2415 fs__default['default'].readlink(this.absolute, (er, linkpath) => {
2416 if (er)
2417 return this.emit('error', er)
2418 this[ONREADLINK](linkpath);
2419 });
2420 }
2421
2422 [ONREADLINK] (linkpath) {
2423 this.linkpath = linkpath.replace(/\\/g, '/');
2424 this[HEADER]();
2425 this.end();
2426 }
2427
2428 [HARDLINK$1] (linkpath) {
2429 this.type = 'Link';
2430 this.linkpath = path__default['default'].relative(this.cwd, linkpath).replace(/\\/g, '/');
2431 this.stat.size = 0;
2432 this[HEADER]();
2433 this.end();
2434 }
2435
2436 [FILE$1] () {
2437 if (this.stat.nlink > 1) {
2438 const linkKey = this.stat.dev + ':' + this.stat.ino;
2439 if (this.linkCache.has(linkKey)) {
2440 const linkpath = this.linkCache.get(linkKey);
2441 if (linkpath.indexOf(this.cwd) === 0)
2442 return this[HARDLINK$1](linkpath)
2443 }
2444 this.linkCache.set(linkKey, this.absolute);
2445 }
2446
2447 this[HEADER]();
2448 if (this.stat.size === 0)
2449 return this.end()
2450
2451 this[OPENFILE]();
2452 }
2453
2454 [OPENFILE] () {
2455 fs__default['default'].open(this.absolute, 'r', (er, fd) => {
2456 if (er)
2457 return this.emit('error', er)
2458 this[ONOPENFILE](fd);
2459 });
2460 }
2461
2462 [ONOPENFILE] (fd) {
2463 const blockLen = 512 * Math.ceil(this.stat.size / 512);
2464 const bufLen = Math.min(blockLen, this.maxReadSize);
2465 const buf = Buffer.allocUnsafe(bufLen);
2466 this[READ](fd, buf, 0, buf.length, 0, this.stat.size, blockLen);
2467 }
2468
2469 [READ] (fd, buf, offset, length, pos, remain, blockRemain) {
2470 fs__default['default'].read(fd, buf, offset, length, pos, (er, bytesRead) => {
2471 if (er) {
2472 // ignoring the error from close(2) is a bad practice, but at
2473 // this point we already have an error, don't need another one
2474 return this[CLOSE](fd, () => this.emit('error', er))
2475 }
2476 this[ONREAD](fd, buf, offset, length, pos, remain, blockRemain, bytesRead);
2477 });
2478 }
2479
2480 [CLOSE] (fd, cb) {
2481 fs__default['default'].close(fd, cb);
2482 }
2483
2484 [ONREAD] (fd, buf, offset, length, pos, remain, blockRemain, bytesRead) {
2485 if (bytesRead <= 0 && remain > 0) {
2486 const er = new Error('encountered unexpected EOF');
2487 er.path = this.absolute;
2488 er.syscall = 'read';
2489 er.code = 'EOF';
2490 return this[CLOSE](fd, () => this.emit('error', er))
2491 }
2492
2493 if (bytesRead > remain) {
2494 const er = new Error('did not encounter expected EOF');
2495 er.path = this.absolute;
2496 er.syscall = 'read';
2497 er.code = 'EOF';
2498 return this[CLOSE](fd, () => this.emit('error', er))
2499 }
2500
2501 // null out the rest of the buffer, if we could fit the block padding
2502 if (bytesRead === remain) {
2503 for (let i = bytesRead; i < length && bytesRead < blockRemain; i++) {
2504 buf[i + offset] = 0;
2505 bytesRead++;
2506 remain++;
2507 }
2508 }
2509
2510 const writeBuf = offset === 0 && bytesRead === buf.length ?
2511 buf : buf.slice(offset, offset + bytesRead);
2512 remain -= bytesRead;
2513 blockRemain -= bytesRead;
2514 pos += bytesRead;
2515 offset += bytesRead;
2516
2517 this.write(writeBuf);
2518
2519 if (!remain) {
2520 if (blockRemain)
2521 this.write(Buffer.alloc(blockRemain));
2522 return this[CLOSE](fd, er => er ? this.emit('error', er) : this.end())
2523 }
2524
2525 if (offset >= length) {
2526 buf = Buffer.allocUnsafe(length);
2527 offset = 0;
2528 }
2529 length = buf.length - offset;
2530 this[READ](fd, buf, offset, length, pos, remain, blockRemain);
2531 }
2532});
2533
2534class WriteEntrySync$1 extends WriteEntry {
2535 [LSTAT] () {
2536 this[ONLSTAT](fs__default['default'].lstatSync(this.absolute));
2537 }
2538
2539 [SYMLINK$1] () {
2540 this[ONREADLINK](fs__default['default'].readlinkSync(this.absolute));
2541 }
2542
2543 [OPENFILE] () {
2544 this[ONOPENFILE](fs__default['default'].openSync(this.absolute, 'r'));
2545 }
2546
2547 [READ] (fd, buf, offset, length, pos, remain, blockRemain) {
2548 let threw = true;
2549 try {
2550 const bytesRead = fs__default['default'].readSync(fd, buf, offset, length, pos);
2551 this[ONREAD](fd, buf, offset, length, pos, remain, blockRemain, bytesRead);
2552 threw = false;
2553 } finally {
2554 // ignoring the error from close(2) is a bad practice, but at
2555 // this point we already have an error, don't need another one
2556 if (threw) {
2557 try {
2558 this[CLOSE](fd, () => {});
2559 } catch (er) {}
2560 }
2561 }
2562 }
2563
2564 [CLOSE] (fd, cb) {
2565 fs__default['default'].closeSync(fd);
2566 cb();
2567 }
2568}
2569
2570const WriteEntryTar$1 = warnMixin(class WriteEntryTar extends minipass {
2571 constructor (readEntry, opt) {
2572 opt = opt || {};
2573 super(opt);
2574 this.preservePaths = !!opt.preservePaths;
2575 this.portable = !!opt.portable;
2576 this.strict = !!opt.strict;
2577 this.noPax = !!opt.noPax;
2578 this.noMtime = !!opt.noMtime;
2579
2580 this.readEntry = readEntry;
2581 this.type = readEntry.type;
2582 if (this.type === 'Directory' && this.portable)
2583 this.noMtime = true;
2584
2585 this.path = readEntry.path;
2586 this.mode = this[MODE](readEntry.mode);
2587 this.uid = this.portable ? null : readEntry.uid;
2588 this.gid = this.portable ? null : readEntry.gid;
2589 this.uname = this.portable ? null : readEntry.uname;
2590 this.gname = this.portable ? null : readEntry.gname;
2591 this.size = readEntry.size;
2592 this.mtime = this.noMtime ? null : opt.mtime || readEntry.mtime;
2593 this.atime = this.portable ? null : readEntry.atime;
2594 this.ctime = this.portable ? null : readEntry.ctime;
2595 this.linkpath = readEntry.linkpath;
2596
2597 if (typeof opt.onwarn === 'function')
2598 this.on('warn', opt.onwarn);
2599
2600 let pathWarn = false;
2601 if (path__default['default'].isAbsolute(this.path) && !this.preservePaths) {
2602 const parsed = path__default['default'].parse(this.path);
2603 pathWarn = parsed.root;
2604 this.path = this.path.substr(parsed.root.length);
2605 }
2606
2607 this.remain = readEntry.size;
2608 this.blockRemain = readEntry.startBlockSize;
2609
2610 this.header = new header({
2611 path: this.path,
2612 linkpath: this.linkpath,
2613 // only the permissions and setuid/setgid/sticky bitflags
2614 // not the higher-order bits that specify file type
2615 mode: this.mode,
2616 uid: this.portable ? null : this.uid,
2617 gid: this.portable ? null : this.gid,
2618 size: this.size,
2619 mtime: this.noMtime ? null : this.mtime,
2620 type: this.type,
2621 uname: this.portable ? null : this.uname,
2622 atime: this.portable ? null : this.atime,
2623 ctime: this.portable ? null : this.ctime,
2624 });
2625
2626 if (pathWarn) {
2627 this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, {
2628 entry: this,
2629 path: pathWarn + this.path,
2630 });
2631 }
2632
2633 if (this.header.encode() && !this.noPax) {
2634 super.write(new pax({
2635 atime: this.portable ? null : this.atime,
2636 ctime: this.portable ? null : this.ctime,
2637 gid: this.portable ? null : this.gid,
2638 mtime: this.noMtime ? null : this.mtime,
2639 path: this.path,
2640 linkpath: this.linkpath,
2641 size: this.size,
2642 uid: this.portable ? null : this.uid,
2643 uname: this.portable ? null : this.uname,
2644 dev: this.portable ? null : this.readEntry.dev,
2645 ino: this.portable ? null : this.readEntry.ino,
2646 nlink: this.portable ? null : this.readEntry.nlink,
2647 }).encode());
2648 }
2649
2650 super.write(this.header.block);
2651 readEntry.pipe(this);
2652 }
2653
2654 [MODE] (mode) {
2655 return modeFix(mode, this.type === 'Directory', this.portable)
2656 }
2657
2658 write (data) {
2659 const writeLen = data.length;
2660 if (writeLen > this.blockRemain)
2661 throw new Error('writing more to entry than is appropriate')
2662 this.blockRemain -= writeLen;
2663 return super.write(data)
2664 }
2665
2666 end () {
2667 if (this.blockRemain)
2668 this.write(Buffer.alloc(this.blockRemain));
2669 return super.end()
2670 }
2671});
2672
2673WriteEntry.Sync = WriteEntrySync$1;
2674WriteEntry.Tar = WriteEntryTar$1;
2675
2676const getType = stat =>
2677 stat.isFile() ? 'File'
2678 : stat.isDirectory() ? 'Directory'
2679 : stat.isSymbolicLink() ? 'SymbolicLink'
2680 : 'Unsupported';
2681
2682var writeEntry = WriteEntry;
2683
2684// A readable tar stream creator
2685// Technically, this is a transform stream that you write paths into,
2686// and tar format comes out of.
2687// The `add()` method is like `write()` but returns this,
2688// and end() return `this` as well, so you can
2689// do `new Pack(opt).add('files').add('dir').end().pipe(output)
2690// You could also do something like:
2691// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar'))
2692
2693class PackJob {
2694 constructor (path, absolute) {
2695 this.path = path || './';
2696 this.absolute = absolute;
2697 this.entry = null;
2698 this.stat = null;
2699 this.readdir = null;
2700 this.pending = false;
2701 this.ignore = false;
2702 this.piped = false;
2703 }
2704}
2705
2706
2707
2708
2709
2710const WriteEntrySync = writeEntry.Sync;
2711const WriteEntryTar = writeEntry.Tar;
2712
2713const EOF = Buffer.alloc(1024);
2714const ONSTAT = Symbol('onStat');
2715const ENDED$2 = Symbol('ended');
2716const QUEUE$1 = Symbol('queue');
2717const CURRENT = Symbol('current');
2718const PROCESS = Symbol('process');
2719const PROCESSING = Symbol('processing');
2720const PROCESSJOB = Symbol('processJob');
2721const JOBS = Symbol('jobs');
2722const JOBDONE = Symbol('jobDone');
2723const ADDFSENTRY = Symbol('addFSEntry');
2724const ADDTARENTRY = Symbol('addTarEntry');
2725const STAT = Symbol('stat');
2726const READDIR = Symbol('readdir');
2727const ONREADDIR = Symbol('onreaddir');
2728const PIPE = Symbol('pipe');
2729const ENTRY = Symbol('entry');
2730const ENTRYOPT = Symbol('entryOpt');
2731const WRITEENTRYCLASS = Symbol('writeEntryClass');
2732const WRITE = Symbol('write');
2733const ONDRAIN = Symbol('ondrain');
2734
2735
2736
2737
2738
2739const Pack = warnMixin(class Pack extends minipass {
2740 constructor (opt) {
2741 super(opt);
2742 opt = opt || Object.create(null);
2743 this.opt = opt;
2744 this.file = opt.file || '';
2745 this.cwd = opt.cwd || process.cwd();
2746 this.maxReadSize = opt.maxReadSize;
2747 this.preservePaths = !!opt.preservePaths;
2748 this.strict = !!opt.strict;
2749 this.noPax = !!opt.noPax;
2750 this.prefix = (opt.prefix || '').replace(/(\\|\/)+$/, '');
2751 this.linkCache = opt.linkCache || new Map();
2752 this.statCache = opt.statCache || new Map();
2753 this.readdirCache = opt.readdirCache || new Map();
2754
2755 this[WRITEENTRYCLASS] = writeEntry;
2756 if (typeof opt.onwarn === 'function')
2757 this.on('warn', opt.onwarn);
2758
2759 this.portable = !!opt.portable;
2760 this.zip = null;
2761 if (opt.gzip) {
2762 if (typeof opt.gzip !== 'object')
2763 opt.gzip = {};
2764 if (this.portable)
2765 opt.gzip.portable = true;
2766 this.zip = new minizlib.Gzip(opt.gzip);
2767 this.zip.on('data', chunk => super.write(chunk));
2768 this.zip.on('end', _ => super.end());
2769 this.zip.on('drain', _ => this[ONDRAIN]());
2770 this.on('resume', _ => this.zip.resume());
2771 } else
2772 this.on('drain', this[ONDRAIN]);
2773
2774 this.noDirRecurse = !!opt.noDirRecurse;
2775 this.follow = !!opt.follow;
2776 this.noMtime = !!opt.noMtime;
2777 this.mtime = opt.mtime || null;
2778
2779 this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true;
2780
2781 this[QUEUE$1] = new yallist();
2782 this[JOBS] = 0;
2783 this.jobs = +opt.jobs || 4;
2784 this[PROCESSING] = false;
2785 this[ENDED$2] = false;
2786 }
2787
2788 [WRITE] (chunk) {
2789 return super.write(chunk)
2790 }
2791
2792 add (path) {
2793 this.write(path);
2794 return this
2795 }
2796
2797 end (path) {
2798 if (path)
2799 this.write(path);
2800 this[ENDED$2] = true;
2801 this[PROCESS]();
2802 return this
2803 }
2804
2805 write (path) {
2806 if (this[ENDED$2])
2807 throw new Error('write after end')
2808
2809 if (path instanceof readEntry)
2810 this[ADDTARENTRY](path);
2811 else
2812 this[ADDFSENTRY](path);
2813 return this.flowing
2814 }
2815
2816 [ADDTARENTRY] (p) {
2817 const absolute = path__default['default'].resolve(this.cwd, p.path);
2818 if (this.prefix)
2819 p.path = this.prefix + '/' + p.path.replace(/^\.(\/+|$)/, '');
2820
2821 // in this case, we don't have to wait for the stat
2822 if (!this.filter(p.path, p))
2823 p.resume();
2824 else {
2825 const job = new PackJob(p.path, absolute, false);
2826 job.entry = new WriteEntryTar(p, this[ENTRYOPT](job));
2827 job.entry.on('end', _ => this[JOBDONE](job));
2828 this[JOBS] += 1;
2829 this[QUEUE$1].push(job);
2830 }
2831
2832 this[PROCESS]();
2833 }
2834
2835 [ADDFSENTRY] (p) {
2836 const absolute = path__default['default'].resolve(this.cwd, p);
2837 if (this.prefix)
2838 p = this.prefix + '/' + p.replace(/^\.(\/+|$)/, '');
2839
2840 this[QUEUE$1].push(new PackJob(p, absolute));
2841 this[PROCESS]();
2842 }
2843
2844 [STAT] (job) {
2845 job.pending = true;
2846 this[JOBS] += 1;
2847 const stat = this.follow ? 'stat' : 'lstat';
2848 fs__default['default'][stat](job.absolute, (er, stat) => {
2849 job.pending = false;
2850 this[JOBS] -= 1;
2851 if (er)
2852 this.emit('error', er);
2853 else
2854 this[ONSTAT](job, stat);
2855 });
2856 }
2857
2858 [ONSTAT] (job, stat) {
2859 this.statCache.set(job.absolute, stat);
2860 job.stat = stat;
2861
2862 // now we have the stat, we can filter it.
2863 if (!this.filter(job.path, stat))
2864 job.ignore = true;
2865
2866 this[PROCESS]();
2867 }
2868
2869 [READDIR] (job) {
2870 job.pending = true;
2871 this[JOBS] += 1;
2872 fs__default['default'].readdir(job.absolute, (er, entries) => {
2873 job.pending = false;
2874 this[JOBS] -= 1;
2875 if (er)
2876 return this.emit('error', er)
2877 this[ONREADDIR](job, entries);
2878 });
2879 }
2880
2881 [ONREADDIR] (job, entries) {
2882 this.readdirCache.set(job.absolute, entries);
2883 job.readdir = entries;
2884 this[PROCESS]();
2885 }
2886
2887 [PROCESS] () {
2888 if (this[PROCESSING])
2889 return
2890
2891 this[PROCESSING] = true;
2892 for (let w = this[QUEUE$1].head;
2893 w !== null && this[JOBS] < this.jobs;
2894 w = w.next) {
2895 this[PROCESSJOB](w.value);
2896 if (w.value.ignore) {
2897 const p = w.next;
2898 this[QUEUE$1].removeNode(w);
2899 w.next = p;
2900 }
2901 }
2902
2903 this[PROCESSING] = false;
2904
2905 if (this[ENDED$2] && !this[QUEUE$1].length && this[JOBS] === 0) {
2906 if (this.zip)
2907 this.zip.end(EOF);
2908 else {
2909 super.write(EOF);
2910 super.end();
2911 }
2912 }
2913 }
2914
2915 get [CURRENT] () {
2916 return this[QUEUE$1] && this[QUEUE$1].head && this[QUEUE$1].head.value
2917 }
2918
2919 [JOBDONE] (job) {
2920 this[QUEUE$1].shift();
2921 this[JOBS] -= 1;
2922 this[PROCESS]();
2923 }
2924
2925 [PROCESSJOB] (job) {
2926 if (job.pending)
2927 return
2928
2929 if (job.entry) {
2930 if (job === this[CURRENT] && !job.piped)
2931 this[PIPE](job);
2932 return
2933 }
2934
2935 if (!job.stat) {
2936 if (this.statCache.has(job.absolute))
2937 this[ONSTAT](job, this.statCache.get(job.absolute));
2938 else
2939 this[STAT](job);
2940 }
2941 if (!job.stat)
2942 return
2943
2944 // filtered out!
2945 if (job.ignore)
2946 return
2947
2948 if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) {
2949 if (this.readdirCache.has(job.absolute))
2950 this[ONREADDIR](job, this.readdirCache.get(job.absolute));
2951 else
2952 this[READDIR](job);
2953 if (!job.readdir)
2954 return
2955 }
2956
2957 // we know it doesn't have an entry, because that got checked above
2958 job.entry = this[ENTRY](job);
2959 if (!job.entry) {
2960 job.ignore = true;
2961 return
2962 }
2963
2964 if (job === this[CURRENT] && !job.piped)
2965 this[PIPE](job);
2966 }
2967
2968 [ENTRYOPT] (job) {
2969 return {
2970 onwarn: (code, msg, data) => this.warn(code, msg, data),
2971 noPax: this.noPax,
2972 cwd: this.cwd,
2973 absolute: job.absolute,
2974 preservePaths: this.preservePaths,
2975 maxReadSize: this.maxReadSize,
2976 strict: this.strict,
2977 portable: this.portable,
2978 linkCache: this.linkCache,
2979 statCache: this.statCache,
2980 noMtime: this.noMtime,
2981 mtime: this.mtime,
2982 }
2983 }
2984
2985 [ENTRY] (job) {
2986 this[JOBS] += 1;
2987 try {
2988 return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job))
2989 .on('end', () => this[JOBDONE](job))
2990 .on('error', er => this.emit('error', er))
2991 } catch (er) {
2992 this.emit('error', er);
2993 }
2994 }
2995
2996 [ONDRAIN] () {
2997 if (this[CURRENT] && this[CURRENT].entry)
2998 this[CURRENT].entry.resume();
2999 }
3000
3001 // like .pipe() but using super, because our write() is special
3002 [PIPE] (job) {
3003 job.piped = true;
3004
3005 if (job.readdir) {
3006 job.readdir.forEach(entry => {
3007 const p = this.prefix ?
3008 job.path.slice(this.prefix.length + 1) || './'
3009 : job.path;
3010
3011 const base = p === './' ? '' : p.replace(/\/*$/, '/');
3012 this[ADDFSENTRY](base + entry);
3013 });
3014 }
3015
3016 const source = job.entry;
3017 const zip = this.zip;
3018
3019 if (zip) {
3020 source.on('data', chunk => {
3021 if (!zip.write(chunk))
3022 source.pause();
3023 });
3024 } else {
3025 source.on('data', chunk => {
3026 if (!super.write(chunk))
3027 source.pause();
3028 });
3029 }
3030 }
3031
3032 pause () {
3033 if (this.zip)
3034 this.zip.pause();
3035 return super.pause()
3036 }
3037});
3038
3039class PackSync extends Pack {
3040 constructor (opt) {
3041 super(opt);
3042 this[WRITEENTRYCLASS] = WriteEntrySync;
3043 }
3044
3045 // pause/resume are no-ops in sync streams.
3046 pause () {}
3047 resume () {}
3048
3049 [STAT] (job) {
3050 const stat = this.follow ? 'statSync' : 'lstatSync';
3051 this[ONSTAT](job, fs__default['default'][stat](job.absolute));
3052 }
3053
3054 [READDIR] (job, stat) {
3055 this[ONREADDIR](job, fs__default['default'].readdirSync(job.absolute));
3056 }
3057
3058 // gotta get it all in this tick
3059 [PIPE] (job) {
3060 const source = job.entry;
3061 const zip = this.zip;
3062
3063 if (job.readdir) {
3064 job.readdir.forEach(entry => {
3065 const p = this.prefix ?
3066 job.path.slice(this.prefix.length + 1) || './'
3067 : job.path;
3068
3069 const base = p === './' ? '' : p.replace(/\/*$/, '/');
3070 this[ADDFSENTRY](base + entry);
3071 });
3072 }
3073
3074 if (zip) {
3075 source.on('data', chunk => {
3076 zip.write(chunk);
3077 });
3078 } else {
3079 source.on('data', chunk => {
3080 super[WRITE](chunk);
3081 });
3082 }
3083 }
3084}
3085
3086Pack.Sync = PackSync;
3087
3088var pack = Pack;
3089
3090const EE$1 = Events__default['default'].EventEmitter;
3091
3092
3093let writev = fs__default['default'].writev;
3094/* istanbul ignore next */
3095if (!writev) {
3096 // This entire block can be removed if support for earlier than Node.js
3097 // 12.9.0 is not needed.
3098 const binding = process.binding('fs');
3099 const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback;
3100
3101 writev = (fd, iovec, pos, cb) => {
3102 const done = (er, bw) => cb(er, bw, iovec);
3103 const req = new FSReqWrap();
3104 req.oncomplete = done;
3105 binding.writeBuffers(fd, iovec, pos, req);
3106 };
3107}
3108
3109const _autoClose = Symbol('_autoClose');
3110const _close = Symbol('_close');
3111const _ended = Symbol('_ended');
3112const _fd = Symbol('_fd');
3113const _finished = Symbol('_finished');
3114const _flags = Symbol('_flags');
3115const _flush = Symbol('_flush');
3116const _handleChunk = Symbol('_handleChunk');
3117const _makeBuf = Symbol('_makeBuf');
3118const _mode = Symbol('_mode');
3119const _needDrain = Symbol('_needDrain');
3120const _onerror = Symbol('_onerror');
3121const _onopen = Symbol('_onopen');
3122const _onread = Symbol('_onread');
3123const _onwrite = Symbol('_onwrite');
3124const _open = Symbol('_open');
3125const _path = Symbol('_path');
3126const _pos = Symbol('_pos');
3127const _queue = Symbol('_queue');
3128const _read = Symbol('_read');
3129const _readSize = Symbol('_readSize');
3130const _reading = Symbol('_reading');
3131const _remain = Symbol('_remain');
3132const _size = Symbol('_size');
3133const _write = Symbol('_write');
3134const _writing = Symbol('_writing');
3135const _defaultFlag = Symbol('_defaultFlag');
3136const _errored = Symbol('_errored');
3137
3138class ReadStream extends minipass {
3139 constructor (path, opt) {
3140 opt = opt || {};
3141 super(opt);
3142
3143 this.readable = true;
3144 this.writable = false;
3145
3146 if (typeof path !== 'string')
3147 throw new TypeError('path must be a string')
3148
3149 this[_errored] = false;
3150 this[_fd] = typeof opt.fd === 'number' ? opt.fd : null;
3151 this[_path] = path;
3152 this[_readSize] = opt.readSize || 16*1024*1024;
3153 this[_reading] = false;
3154 this[_size] = typeof opt.size === 'number' ? opt.size : Infinity;
3155 this[_remain] = this[_size];
3156 this[_autoClose] = typeof opt.autoClose === 'boolean' ?
3157 opt.autoClose : true;
3158
3159 if (typeof this[_fd] === 'number')
3160 this[_read]();
3161 else
3162 this[_open]();
3163 }
3164
3165 get fd () { return this[_fd] }
3166 get path () { return this[_path] }
3167
3168 write () {
3169 throw new TypeError('this is a readable stream')
3170 }
3171
3172 end () {
3173 throw new TypeError('this is a readable stream')
3174 }
3175
3176 [_open] () {
3177 fs__default['default'].open(this[_path], 'r', (er, fd) => this[_onopen](er, fd));
3178 }
3179
3180 [_onopen] (er, fd) {
3181 if (er)
3182 this[_onerror](er);
3183 else {
3184 this[_fd] = fd;
3185 this.emit('open', fd);
3186 this[_read]();
3187 }
3188 }
3189
3190 [_makeBuf] () {
3191 return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain]))
3192 }
3193
3194 [_read] () {
3195 if (!this[_reading]) {
3196 this[_reading] = true;
3197 const buf = this[_makeBuf]();
3198 /* istanbul ignore if */
3199 if (buf.length === 0)
3200 return process.nextTick(() => this[_onread](null, 0, buf))
3201 fs__default['default'].read(this[_fd], buf, 0, buf.length, null, (er, br, buf) =>
3202 this[_onread](er, br, buf));
3203 }
3204 }
3205
3206 [_onread] (er, br, buf) {
3207 this[_reading] = false;
3208 if (er)
3209 this[_onerror](er);
3210 else if (this[_handleChunk](br, buf))
3211 this[_read]();
3212 }
3213
3214 [_close] () {
3215 if (this[_autoClose] && typeof this[_fd] === 'number') {
3216 const fd = this[_fd];
3217 this[_fd] = null;
3218 fs__default['default'].close(fd, er => er ? this.emit('error', er) : this.emit('close'));
3219 }
3220 }
3221
3222 [_onerror] (er) {
3223 this[_reading] = true;
3224 this[_close]();
3225 this.emit('error', er);
3226 }
3227
3228 [_handleChunk] (br, buf) {
3229 let ret = false;
3230 // no effect if infinite
3231 this[_remain] -= br;
3232 if (br > 0)
3233 ret = super.write(br < buf.length ? buf.slice(0, br) : buf);
3234
3235 if (br === 0 || this[_remain] <= 0) {
3236 ret = false;
3237 this[_close]();
3238 super.end();
3239 }
3240
3241 return ret
3242 }
3243
3244 emit (ev, data) {
3245 switch (ev) {
3246 case 'prefinish':
3247 case 'finish':
3248 break
3249
3250 case 'drain':
3251 if (typeof this[_fd] === 'number')
3252 this[_read]();
3253 break
3254
3255 case 'error':
3256 if (this[_errored])
3257 return
3258 this[_errored] = true;
3259 return super.emit(ev, data)
3260
3261 default:
3262 return super.emit(ev, data)
3263 }
3264 }
3265}
3266
3267class ReadStreamSync extends ReadStream {
3268 [_open] () {
3269 let threw = true;
3270 try {
3271 this[_onopen](null, fs__default['default'].openSync(this[_path], 'r'));
3272 threw = false;
3273 } finally {
3274 if (threw)
3275 this[_close]();
3276 }
3277 }
3278
3279 [_read] () {
3280 let threw = true;
3281 try {
3282 if (!this[_reading]) {
3283 this[_reading] = true;
3284 do {
3285 const buf = this[_makeBuf]();
3286 /* istanbul ignore next */
3287 const br = buf.length === 0 ? 0
3288 : fs__default['default'].readSync(this[_fd], buf, 0, buf.length, null);
3289 if (!this[_handleChunk](br, buf))
3290 break
3291 } while (true)
3292 this[_reading] = false;
3293 }
3294 threw = false;
3295 } finally {
3296 if (threw)
3297 this[_close]();
3298 }
3299 }
3300
3301 [_close] () {
3302 if (this[_autoClose] && typeof this[_fd] === 'number') {
3303 const fd = this[_fd];
3304 this[_fd] = null;
3305 fs__default['default'].closeSync(fd);
3306 this.emit('close');
3307 }
3308 }
3309}
3310
3311class WriteStream extends EE$1 {
3312 constructor (path, opt) {
3313 opt = opt || {};
3314 super(opt);
3315 this.readable = false;
3316 this.writable = true;
3317 this[_errored] = false;
3318 this[_writing] = false;
3319 this[_ended] = false;
3320 this[_needDrain] = false;
3321 this[_queue] = [];
3322 this[_path] = path;
3323 this[_fd] = typeof opt.fd === 'number' ? opt.fd : null;
3324 this[_mode] = opt.mode === undefined ? 0o666 : opt.mode;
3325 this[_pos] = typeof opt.start === 'number' ? opt.start : null;
3326 this[_autoClose] = typeof opt.autoClose === 'boolean' ?
3327 opt.autoClose : true;
3328
3329 // truncating makes no sense when writing into the middle
3330 const defaultFlag = this[_pos] !== null ? 'r+' : 'w';
3331 this[_defaultFlag] = opt.flags === undefined;
3332 this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags;
3333
3334 if (this[_fd] === null)
3335 this[_open]();
3336 }
3337
3338 emit (ev, data) {
3339 if (ev === 'error') {
3340 if (this[_errored])
3341 return
3342 this[_errored] = true;
3343 }
3344 return super.emit(ev, data)
3345 }
3346
3347
3348 get fd () { return this[_fd] }
3349 get path () { return this[_path] }
3350
3351 [_onerror] (er) {
3352 this[_close]();
3353 this[_writing] = true;
3354 this.emit('error', er);
3355 }
3356
3357 [_open] () {
3358 fs__default['default'].open(this[_path], this[_flags], this[_mode],
3359 (er, fd) => this[_onopen](er, fd));
3360 }
3361
3362 [_onopen] (er, fd) {
3363 if (this[_defaultFlag] &&
3364 this[_flags] === 'r+' &&
3365 er && er.code === 'ENOENT') {
3366 this[_flags] = 'w';
3367 this[_open]();
3368 } else if (er)
3369 this[_onerror](er);
3370 else {
3371 this[_fd] = fd;
3372 this.emit('open', fd);
3373 this[_flush]();
3374 }
3375 }
3376
3377 end (buf, enc) {
3378 if (buf)
3379 this.write(buf, enc);
3380
3381 this[_ended] = true;
3382
3383 // synthetic after-write logic, where drain/finish live
3384 if (!this[_writing] && !this[_queue].length &&
3385 typeof this[_fd] === 'number')
3386 this[_onwrite](null, 0);
3387 return this
3388 }
3389
3390 write (buf, enc) {
3391 if (typeof buf === 'string')
3392 buf = Buffer.from(buf, enc);
3393
3394 if (this[_ended]) {
3395 this.emit('error', new Error('write() after end()'));
3396 return false
3397 }
3398
3399 if (this[_fd] === null || this[_writing] || this[_queue].length) {
3400 this[_queue].push(buf);
3401 this[_needDrain] = true;
3402 return false
3403 }
3404
3405 this[_writing] = true;
3406 this[_write](buf);
3407 return true
3408 }
3409
3410 [_write] (buf) {
3411 fs__default['default'].write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) =>
3412 this[_onwrite](er, bw));
3413 }
3414
3415 [_onwrite] (er, bw) {
3416 if (er)
3417 this[_onerror](er);
3418 else {
3419 if (this[_pos] !== null)
3420 this[_pos] += bw;
3421 if (this[_queue].length)
3422 this[_flush]();
3423 else {
3424 this[_writing] = false;
3425
3426 if (this[_ended] && !this[_finished]) {
3427 this[_finished] = true;
3428 this[_close]();
3429 this.emit('finish');
3430 } else if (this[_needDrain]) {
3431 this[_needDrain] = false;
3432 this.emit('drain');
3433 }
3434 }
3435 }
3436 }
3437
3438 [_flush] () {
3439 if (this[_queue].length === 0) {
3440 if (this[_ended])
3441 this[_onwrite](null, 0);
3442 } else if (this[_queue].length === 1)
3443 this[_write](this[_queue].pop());
3444 else {
3445 const iovec = this[_queue];
3446 this[_queue] = [];
3447 writev(this[_fd], iovec, this[_pos],
3448 (er, bw) => this[_onwrite](er, bw));
3449 }
3450 }
3451
3452 [_close] () {
3453 if (this[_autoClose] && typeof this[_fd] === 'number') {
3454 const fd = this[_fd];
3455 this[_fd] = null;
3456 fs__default['default'].close(fd, er => er ? this.emit('error', er) : this.emit('close'));
3457 }
3458 }
3459}
3460
3461class WriteStreamSync extends WriteStream {
3462 [_open] () {
3463 let fd;
3464 // only wrap in a try{} block if we know we'll retry, to avoid
3465 // the rethrow obscuring the error's source frame in most cases.
3466 if (this[_defaultFlag] && this[_flags] === 'r+') {
3467 try {
3468 fd = fs__default['default'].openSync(this[_path], this[_flags], this[_mode]);
3469 } catch (er) {
3470 if (er.code === 'ENOENT') {
3471 this[_flags] = 'w';
3472 return this[_open]()
3473 } else
3474 throw er
3475 }
3476 } else
3477 fd = fs__default['default'].openSync(this[_path], this[_flags], this[_mode]);
3478
3479 this[_onopen](null, fd);
3480 }
3481
3482 [_close] () {
3483 if (this[_autoClose] && typeof this[_fd] === 'number') {
3484 const fd = this[_fd];
3485 this[_fd] = null;
3486 fs__default['default'].closeSync(fd);
3487 this.emit('close');
3488 }
3489 }
3490
3491 [_write] (buf) {
3492 // throw the original, but try to close if it fails
3493 let threw = true;
3494 try {
3495 this[_onwrite](null,
3496 fs__default['default'].writeSync(this[_fd], buf, 0, buf.length, this[_pos]));
3497 threw = false;
3498 } finally {
3499 if (threw)
3500 try { this[_close](); } catch (_) {}
3501 }
3502 }
3503}
3504
3505var ReadStream_1 = ReadStream;
3506var ReadStreamSync_1 = ReadStreamSync;
3507
3508var WriteStream_1 = WriteStream;
3509var WriteStreamSync_1 = WriteStreamSync;
3510
3511var fsMinipass = {
3512 ReadStream: ReadStream_1,
3513 ReadStreamSync: ReadStreamSync_1,
3514 WriteStream: WriteStream_1,
3515 WriteStreamSync: WriteStreamSync_1
3516};
3517
3518// this[BUFFER] is the remainder of a chunk if we're waiting for
3519// the full 512 bytes of a header to come in. We will Buffer.concat()
3520// it to the next write(), which is a mem copy, but a small one.
3521//
3522// this[QUEUE] is a Yallist of entries that haven't been emitted
3523// yet this can only get filled up if the user keeps write()ing after
3524// a write() returns false, or does a write() with more than one entry
3525//
3526// We don't buffer chunks, we always parse them and either create an
3527// entry, or push it into the active entry. The ReadEntry class knows
3528// to throw data away if .ignore=true
3529//
3530// Shift entry off the buffer when it emits 'end', and emit 'entry' for
3531// the next one in the list.
3532//
3533// At any time, we're pushing body chunks into the entry at WRITEENTRY,
3534// and waiting for 'end' on the entry at READENTRY
3535//
3536// ignored entries get .resume() called on them straight away
3537
3538
3539
3540
3541
3542const maxMetaEntrySize = 1024 * 1024;
3543
3544
3545
3546
3547const gzipHeader = Buffer.from([0x1f, 0x8b]);
3548const STATE = Symbol('state');
3549const WRITEENTRY = Symbol('writeEntry');
3550const READENTRY = Symbol('readEntry');
3551const NEXTENTRY = Symbol('nextEntry');
3552const PROCESSENTRY = Symbol('processEntry');
3553const EX = Symbol('extendedHeader');
3554const GEX = Symbol('globalExtendedHeader');
3555const META = Symbol('meta');
3556const EMITMETA = Symbol('emitMeta');
3557const BUFFER = Symbol('buffer');
3558const QUEUE = Symbol('queue');
3559const ENDED$1 = Symbol('ended');
3560const EMITTEDEND = Symbol('emittedEnd');
3561const EMIT = Symbol('emit');
3562const UNZIP = Symbol('unzip');
3563const CONSUMECHUNK = Symbol('consumeChunk');
3564const CONSUMECHUNKSUB = Symbol('consumeChunkSub');
3565const CONSUMEBODY = Symbol('consumeBody');
3566const CONSUMEMETA = Symbol('consumeMeta');
3567const CONSUMEHEADER = Symbol('consumeHeader');
3568const CONSUMING = Symbol('consuming');
3569const BUFFERCONCAT = Symbol('bufferConcat');
3570const MAYBEEND = Symbol('maybeEnd');
3571const WRITING = Symbol('writing');
3572const ABORTED = Symbol('aborted');
3573const DONE = Symbol('onDone');
3574const SAW_VALID_ENTRY = Symbol('sawValidEntry');
3575const SAW_NULL_BLOCK = Symbol('sawNullBlock');
3576const SAW_EOF = Symbol('sawEOF');
3577
3578const noop = _ => true;
3579
3580var parse$4 = warnMixin(class Parser extends Events__default['default'] {
3581 constructor (opt) {
3582 opt = opt || {};
3583 super(opt);
3584
3585 this.file = opt.file || '';
3586
3587 // set to boolean false when an entry starts. 1024 bytes of \0
3588 // is technically a valid tarball, albeit a boring one.
3589 this[SAW_VALID_ENTRY] = null;
3590
3591 // these BADARCHIVE errors can't be detected early. listen on DONE.
3592 this.on(DONE, _ => {
3593 if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) {
3594 // either less than 1 block of data, or all entries were invalid.
3595 // Either way, probably not even a tarball.
3596 this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format');
3597 }
3598 });
3599
3600 if (opt.ondone)
3601 this.on(DONE, opt.ondone);
3602 else {
3603 this.on(DONE, _ => {
3604 this.emit('prefinish');
3605 this.emit('finish');
3606 this.emit('end');
3607 this.emit('close');
3608 });
3609 }
3610
3611 this.strict = !!opt.strict;
3612 this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize;
3613 this.filter = typeof opt.filter === 'function' ? opt.filter : noop;
3614
3615 // have to set this so that streams are ok piping into it
3616 this.writable = true;
3617 this.readable = false;
3618
3619 this[QUEUE] = new yallist();
3620 this[BUFFER] = null;
3621 this[READENTRY] = null;
3622 this[WRITEENTRY] = null;
3623 this[STATE] = 'begin';
3624 this[META] = '';
3625 this[EX] = null;
3626 this[GEX] = null;
3627 this[ENDED$1] = false;
3628 this[UNZIP] = null;
3629 this[ABORTED] = false;
3630 this[SAW_NULL_BLOCK] = false;
3631 this[SAW_EOF] = false;
3632 if (typeof opt.onwarn === 'function')
3633 this.on('warn', opt.onwarn);
3634 if (typeof opt.onentry === 'function')
3635 this.on('entry', opt.onentry);
3636 }
3637
3638 [CONSUMEHEADER] (chunk, position) {
3639 if (this[SAW_VALID_ENTRY] === null)
3640 this[SAW_VALID_ENTRY] = false;
3641 let header$1;
3642 try {
3643 header$1 = new header(chunk, position, this[EX], this[GEX]);
3644 } catch (er) {
3645 return this.warn('TAR_ENTRY_INVALID', er)
3646 }
3647
3648 if (header$1.nullBlock) {
3649 if (this[SAW_NULL_BLOCK]) {
3650 this[SAW_EOF] = true;
3651 // ending an archive with no entries. pointless, but legal.
3652 if (this[STATE] === 'begin')
3653 this[STATE] = 'header';
3654 this[EMIT]('eof');
3655 } else {
3656 this[SAW_NULL_BLOCK] = true;
3657 this[EMIT]('nullBlock');
3658 }
3659 } else {
3660 this[SAW_NULL_BLOCK] = false;
3661 if (!header$1.cksumValid)
3662 this.warn('TAR_ENTRY_INVALID', 'checksum failure', {header: header$1});
3663 else if (!header$1.path)
3664 this.warn('TAR_ENTRY_INVALID', 'path is required', {header: header$1});
3665 else {
3666 const type = header$1.type;
3667 if (/^(Symbolic)?Link$/.test(type) && !header$1.linkpath)
3668 this.warn('TAR_ENTRY_INVALID', 'linkpath required', {header: header$1});
3669 else if (!/^(Symbolic)?Link$/.test(type) && header$1.linkpath)
3670 this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', {header: header$1});
3671 else {
3672 const entry = this[WRITEENTRY] = new readEntry(header$1, this[EX], this[GEX]);
3673
3674 // we do this for meta & ignored entries as well, because they
3675 // are still valid tar, or else we wouldn't know to ignore them
3676 if (!this[SAW_VALID_ENTRY]) {
3677 if (entry.remain) {
3678 // this might be the one!
3679 const onend = () => {
3680 if (!entry.invalid)
3681 this[SAW_VALID_ENTRY] = true;
3682 };
3683 entry.on('end', onend);
3684 } else
3685 this[SAW_VALID_ENTRY] = true;
3686 }
3687
3688 if (entry.meta) {
3689 if (entry.size > this.maxMetaEntrySize) {
3690 entry.ignore = true;
3691 this[EMIT]('ignoredEntry', entry);
3692 this[STATE] = 'ignore';
3693 entry.resume();
3694 } else if (entry.size > 0) {
3695 this[META] = '';
3696 entry.on('data', c => this[META] += c);
3697 this[STATE] = 'meta';
3698 }
3699 } else {
3700 this[EX] = null;
3701 entry.ignore = entry.ignore || !this.filter(entry.path, entry);
3702
3703 if (entry.ignore) {
3704 // probably valid, just not something we care about
3705 this[EMIT]('ignoredEntry', entry);
3706 this[STATE] = entry.remain ? 'ignore' : 'header';
3707 entry.resume();
3708 } else {
3709 if (entry.remain)
3710 this[STATE] = 'body';
3711 else {
3712 this[STATE] = 'header';
3713 entry.end();
3714 }
3715
3716 if (!this[READENTRY]) {
3717 this[QUEUE].push(entry);
3718 this[NEXTENTRY]();
3719 } else
3720 this[QUEUE].push(entry);
3721 }
3722 }
3723 }
3724 }
3725 }
3726 }
3727
3728 [PROCESSENTRY] (entry) {
3729 let go = true;
3730
3731 if (!entry) {
3732 this[READENTRY] = null;
3733 go = false;
3734 } else if (Array.isArray(entry))
3735 this.emit.apply(this, entry);
3736 else {
3737 this[READENTRY] = entry;
3738 this.emit('entry', entry);
3739 if (!entry.emittedEnd) {
3740 entry.on('end', _ => this[NEXTENTRY]());
3741 go = false;
3742 }
3743 }
3744
3745 return go
3746 }
3747
3748 [NEXTENTRY] () {
3749 do {} while (this[PROCESSENTRY](this[QUEUE].shift()))
3750
3751 if (!this[QUEUE].length) {
3752 // At this point, there's nothing in the queue, but we may have an
3753 // entry which is being consumed (readEntry).
3754 // If we don't, then we definitely can handle more data.
3755 // If we do, and either it's flowing, or it has never had any data
3756 // written to it, then it needs more.
3757 // The only other possibility is that it has returned false from a
3758 // write() call, so we wait for the next drain to continue.
3759 const re = this[READENTRY];
3760 const drainNow = !re || re.flowing || re.size === re.remain;
3761 if (drainNow) {
3762 if (!this[WRITING])
3763 this.emit('drain');
3764 } else
3765 re.once('drain', _ => this.emit('drain'));
3766 }
3767 }
3768
3769 [CONSUMEBODY] (chunk, position) {
3770 // write up to but no more than writeEntry.blockRemain
3771 const entry = this[WRITEENTRY];
3772 const br = entry.blockRemain;
3773 const c = (br >= chunk.length && position === 0) ? chunk
3774 : chunk.slice(position, position + br);
3775
3776 entry.write(c);
3777
3778 if (!entry.blockRemain) {
3779 this[STATE] = 'header';
3780 this[WRITEENTRY] = null;
3781 entry.end();
3782 }
3783
3784 return c.length
3785 }
3786
3787 [CONSUMEMETA] (chunk, position) {
3788 const entry = this[WRITEENTRY];
3789 const ret = this[CONSUMEBODY](chunk, position);
3790
3791 // if we finished, then the entry is reset
3792 if (!this[WRITEENTRY])
3793 this[EMITMETA](entry);
3794
3795 return ret
3796 }
3797
3798 [EMIT] (ev, data, extra) {
3799 if (!this[QUEUE].length && !this[READENTRY])
3800 this.emit(ev, data, extra);
3801 else
3802 this[QUEUE].push([ev, data, extra]);
3803 }
3804
3805 [EMITMETA] (entry) {
3806 this[EMIT]('meta', this[META]);
3807 switch (entry.type) {
3808 case 'ExtendedHeader':
3809 case 'OldExtendedHeader':
3810 this[EX] = pax.parse(this[META], this[EX], false);
3811 break
3812
3813 case 'GlobalExtendedHeader':
3814 this[GEX] = pax.parse(this[META], this[GEX], true);
3815 break
3816
3817 case 'NextFileHasLongPath':
3818 case 'OldGnuLongPath':
3819 this[EX] = this[EX] || Object.create(null);
3820 this[EX].path = this[META].replace(/\0.*/, '');
3821 break
3822
3823 case 'NextFileHasLongLinkpath':
3824 this[EX] = this[EX] || Object.create(null);
3825 this[EX].linkpath = this[META].replace(/\0.*/, '');
3826 break
3827
3828 /* istanbul ignore next */
3829 default: throw new Error('unknown meta: ' + entry.type)
3830 }
3831 }
3832
3833 abort (error) {
3834 this[ABORTED] = true;
3835 this.emit('abort', error);
3836 // always throws, even in non-strict mode
3837 this.warn('TAR_ABORT', error, { recoverable: false });
3838 }
3839
3840 write (chunk) {
3841 if (this[ABORTED])
3842 return
3843
3844 // first write, might be gzipped
3845 if (this[UNZIP] === null && chunk) {
3846 if (this[BUFFER]) {
3847 chunk = Buffer.concat([this[BUFFER], chunk]);
3848 this[BUFFER] = null;
3849 }
3850 if (chunk.length < gzipHeader.length) {
3851 this[BUFFER] = chunk;
3852 return true
3853 }
3854 for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) {
3855 if (chunk[i] !== gzipHeader[i])
3856 this[UNZIP] = false;
3857 }
3858 if (this[UNZIP] === null) {
3859 const ended = this[ENDED$1];
3860 this[ENDED$1] = false;
3861 this[UNZIP] = new minizlib.Unzip();
3862 this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk));
3863 this[UNZIP].on('error', er => this.abort(er));
3864 this[UNZIP].on('end', _ => {
3865 this[ENDED$1] = true;
3866 this[CONSUMECHUNK]();
3867 });
3868 this[WRITING] = true;
3869 const ret = this[UNZIP][ended ? 'end' : 'write'](chunk);
3870 this[WRITING] = false;
3871 return ret
3872 }
3873 }
3874
3875 this[WRITING] = true;
3876 if (this[UNZIP])
3877 this[UNZIP].write(chunk);
3878 else
3879 this[CONSUMECHUNK](chunk);
3880 this[WRITING] = false;
3881
3882 // return false if there's a queue, or if the current entry isn't flowing
3883 const ret =
3884 this[QUEUE].length ? false :
3885 this[READENTRY] ? this[READENTRY].flowing :
3886 true;
3887
3888 // if we have no queue, then that means a clogged READENTRY
3889 if (!ret && !this[QUEUE].length)
3890 this[READENTRY].once('drain', _ => this.emit('drain'));
3891
3892 return ret
3893 }
3894
3895 [BUFFERCONCAT] (c) {
3896 if (c && !this[ABORTED])
3897 this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c;
3898 }
3899
3900 [MAYBEEND] () {
3901 if (this[ENDED$1] &&
3902 !this[EMITTEDEND] &&
3903 !this[ABORTED] &&
3904 !this[CONSUMING]) {
3905 this[EMITTEDEND] = true;
3906 const entry = this[WRITEENTRY];
3907 if (entry && entry.blockRemain) {
3908 // truncated, likely a damaged file
3909 const have = this[BUFFER] ? this[BUFFER].length : 0;
3910 this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${
3911 entry.blockRemain} more bytes, only ${have} available)`, {entry});
3912 if (this[BUFFER])
3913 entry.write(this[BUFFER]);
3914 entry.end();
3915 }
3916 this[EMIT](DONE);
3917 }
3918 }
3919
3920 [CONSUMECHUNK] (chunk) {
3921 if (this[CONSUMING])
3922 this[BUFFERCONCAT](chunk);
3923 else if (!chunk && !this[BUFFER])
3924 this[MAYBEEND]();
3925 else {
3926 this[CONSUMING] = true;
3927 if (this[BUFFER]) {
3928 this[BUFFERCONCAT](chunk);
3929 const c = this[BUFFER];
3930 this[BUFFER] = null;
3931 this[CONSUMECHUNKSUB](c);
3932 } else
3933 this[CONSUMECHUNKSUB](chunk);
3934
3935 while (this[BUFFER] &&
3936 this[BUFFER].length >= 512 &&
3937 !this[ABORTED] &&
3938 !this[SAW_EOF]) {
3939 const c = this[BUFFER];
3940 this[BUFFER] = null;
3941 this[CONSUMECHUNKSUB](c);
3942 }
3943 this[CONSUMING] = false;
3944 }
3945
3946 if (!this[BUFFER] || this[ENDED$1])
3947 this[MAYBEEND]();
3948 }
3949
3950 [CONSUMECHUNKSUB] (chunk) {
3951 // we know that we are in CONSUMING mode, so anything written goes into
3952 // the buffer. Advance the position and put any remainder in the buffer.
3953 let position = 0;
3954 const length = chunk.length;
3955 while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) {
3956 switch (this[STATE]) {
3957 case 'begin':
3958 case 'header':
3959 this[CONSUMEHEADER](chunk, position);
3960 position += 512;
3961 break
3962
3963 case 'ignore':
3964 case 'body':
3965 position += this[CONSUMEBODY](chunk, position);
3966 break
3967
3968 case 'meta':
3969 position += this[CONSUMEMETA](chunk, position);
3970 break
3971
3972 /* istanbul ignore next */
3973 default:
3974 throw new Error('invalid state: ' + this[STATE])
3975 }
3976 }
3977
3978 if (position < length) {
3979 if (this[BUFFER])
3980 this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]]);
3981 else
3982 this[BUFFER] = chunk.slice(position);
3983 }
3984 }
3985
3986 end (chunk) {
3987 if (!this[ABORTED]) {
3988 if (this[UNZIP])
3989 this[UNZIP].end(chunk);
3990 else {
3991 this[ENDED$1] = true;
3992 this.write(chunk);
3993 }
3994 }
3995 }
3996});
3997
3998// XXX: This shares a lot in common with extract.js
3999// maybe some DRY opportunity here?
4000
4001// tar -t
4002
4003
4004
4005
4006
4007
4008var list_1 = (opt_, files, cb) => {
4009 if (typeof opt_ === 'function')
4010 cb = opt_, files = null, opt_ = {};
4011 else if (Array.isArray(opt_))
4012 files = opt_, opt_ = {};
4013
4014 if (typeof files === 'function')
4015 cb = files, files = null;
4016
4017 if (!files)
4018 files = [];
4019 else
4020 files = Array.from(files);
4021
4022 const opt = highLevelOpt(opt_);
4023
4024 if (opt.sync && typeof cb === 'function')
4025 throw new TypeError('callback not supported for sync tar functions')
4026
4027 if (!opt.file && typeof cb === 'function')
4028 throw new TypeError('callback only supported with file option')
4029
4030 if (files.length)
4031 filesFilter$1(opt, files);
4032
4033 if (!opt.noResume)
4034 onentryFunction(opt);
4035
4036 return opt.file && opt.sync ? listFileSync(opt)
4037 : opt.file ? listFile(opt, cb)
4038 : list(opt)
4039};
4040
4041const onentryFunction = opt => {
4042 const onentry = opt.onentry;
4043 opt.onentry = onentry ? e => {
4044 onentry(e);
4045 e.resume();
4046 } : e => e.resume();
4047};
4048
4049// construct a filter that limits the file entries listed
4050// include child entries if a dir is included
4051const filesFilter$1 = (opt, files) => {
4052 const map = new Map(files.map(f => [f.replace(/\/+$/, ''), true]));
4053 const filter = opt.filter;
4054
4055 const mapHas = (file, r) => {
4056 const root = r || path__default['default'].parse(file).root || '.';
4057 const ret = file === root ? false
4058 : map.has(file) ? map.get(file)
4059 : mapHas(path__default['default'].dirname(file), root);
4060
4061 map.set(file, ret);
4062 return ret
4063 };
4064
4065 opt.filter = filter
4066 ? (file, entry) => filter(file, entry) && mapHas(file.replace(/\/+$/, ''))
4067 : file => mapHas(file.replace(/\/+$/, ''));
4068};
4069
4070const listFileSync = opt => {
4071 const p = list(opt);
4072 const file = opt.file;
4073 let threw = true;
4074 let fd;
4075 try {
4076 const stat = fs__default['default'].statSync(file);
4077 const readSize = opt.maxReadSize || 16 * 1024 * 1024;
4078 if (stat.size < readSize)
4079 p.end(fs__default['default'].readFileSync(file));
4080 else {
4081 let pos = 0;
4082 const buf = Buffer.allocUnsafe(readSize);
4083 fd = fs__default['default'].openSync(file, 'r');
4084 while (pos < stat.size) {
4085 const bytesRead = fs__default['default'].readSync(fd, buf, 0, readSize, pos);
4086 pos += bytesRead;
4087 p.write(buf.slice(0, bytesRead));
4088 }
4089 p.end();
4090 }
4091 threw = false;
4092 } finally {
4093 if (threw && fd) {
4094 try {
4095 fs__default['default'].closeSync(fd);
4096 } catch (er) {}
4097 }
4098 }
4099};
4100
4101const listFile = (opt, cb) => {
4102 const parse = new parse$4(opt);
4103 const readSize = opt.maxReadSize || 16 * 1024 * 1024;
4104
4105 const file = opt.file;
4106 const p = new Promise((resolve, reject) => {
4107 parse.on('error', reject);
4108 parse.on('end', resolve);
4109
4110 fs__default['default'].stat(file, (er, stat) => {
4111 if (er)
4112 reject(er);
4113 else {
4114 const stream = new fsMinipass.ReadStream(file, {
4115 readSize: readSize,
4116 size: stat.size,
4117 });
4118 stream.on('error', reject);
4119 stream.pipe(parse);
4120 }
4121 });
4122 });
4123 return cb ? p.then(cb, cb) : p
4124};
4125
4126const list = opt => new parse$4(opt);
4127
4128// tar -c
4129
4130
4131
4132
4133
4134
4135
4136var create_1 = (opt_, files, cb) => {
4137 if (typeof files === 'function')
4138 cb = files;
4139
4140 if (Array.isArray(opt_))
4141 files = opt_, opt_ = {};
4142
4143 if (!files || !Array.isArray(files) || !files.length)
4144 throw new TypeError('no files or directories specified')
4145
4146 files = Array.from(files);
4147
4148 const opt = highLevelOpt(opt_);
4149
4150 if (opt.sync && typeof cb === 'function')
4151 throw new TypeError('callback not supported for sync tar functions')
4152
4153 if (!opt.file && typeof cb === 'function')
4154 throw new TypeError('callback only supported with file option')
4155
4156 return opt.file && opt.sync ? createFileSync(opt, files)
4157 : opt.file ? createFile(opt, files, cb)
4158 : opt.sync ? createSync(opt, files)
4159 : create(opt, files)
4160};
4161
4162const createFileSync = (opt, files) => {
4163 const p = new pack.Sync(opt);
4164 const stream = new fsMinipass.WriteStreamSync(opt.file, {
4165 mode: opt.mode || 0o666,
4166 });
4167 p.pipe(stream);
4168 addFilesSync$1(p, files);
4169};
4170
4171const createFile = (opt, files, cb) => {
4172 const p = new pack(opt);
4173 const stream = new fsMinipass.WriteStream(opt.file, {
4174 mode: opt.mode || 0o666,
4175 });
4176 p.pipe(stream);
4177
4178 const promise = new Promise((res, rej) => {
4179 stream.on('error', rej);
4180 stream.on('close', res);
4181 p.on('error', rej);
4182 });
4183
4184 addFilesAsync$1(p, files);
4185
4186 return cb ? promise.then(cb, cb) : promise
4187};
4188
4189const addFilesSync$1 = (p, files) => {
4190 files.forEach(file => {
4191 if (file.charAt(0) === '@') {
4192 list_1({
4193 file: path__default['default'].resolve(p.cwd, file.substr(1)),
4194 sync: true,
4195 noResume: true,
4196 onentry: entry => p.add(entry),
4197 });
4198 } else
4199 p.add(file);
4200 });
4201 p.end();
4202};
4203
4204const addFilesAsync$1 = (p, files) => {
4205 while (files.length) {
4206 const file = files.shift();
4207 if (file.charAt(0) === '@') {
4208 return list_1({
4209 file: path__default['default'].resolve(p.cwd, file.substr(1)),
4210 noResume: true,
4211 onentry: entry => p.add(entry),
4212 }).then(_ => addFilesAsync$1(p, files))
4213 } else
4214 p.add(file);
4215 }
4216 p.end();
4217};
4218
4219const createSync = (opt, files) => {
4220 const p = new pack.Sync(opt);
4221 addFilesSync$1(p, files);
4222 return p
4223};
4224
4225const create = (opt, files) => {
4226 const p = new pack(opt);
4227 addFilesAsync$1(p, files);
4228 return p
4229};
4230
4231// tar -r
4232
4233
4234
4235
4236
4237
4238
4239// starting at the head of the file, read a Header
4240// If the checksum is invalid, that's our position to start writing
4241// If it is, jump forward by the specified size (round up to 512)
4242// and try again.
4243// Write the new Pack stream starting there.
4244
4245
4246
4247var replace_1 = (opt_, files, cb) => {
4248 const opt = highLevelOpt(opt_);
4249
4250 if (!opt.file)
4251 throw new TypeError('file is required')
4252
4253 if (opt.gzip)
4254 throw new TypeError('cannot append to compressed archives')
4255
4256 if (!files || !Array.isArray(files) || !files.length)
4257 throw new TypeError('no files or directories specified')
4258
4259 files = Array.from(files);
4260
4261 return opt.sync ? replaceSync(opt, files)
4262 : replace(opt, files, cb)
4263};
4264
4265const replaceSync = (opt, files) => {
4266 const p = new pack.Sync(opt);
4267
4268 let threw = true;
4269 let fd;
4270 let position;
4271
4272 try {
4273 try {
4274 fd = fs__default['default'].openSync(opt.file, 'r+');
4275 } catch (er) {
4276 if (er.code === 'ENOENT')
4277 fd = fs__default['default'].openSync(opt.file, 'w+');
4278 else
4279 throw er
4280 }
4281
4282 const st = fs__default['default'].fstatSync(fd);
4283 const headBuf = Buffer.alloc(512);
4284
4285 POSITION: for (position = 0; position < st.size; position += 512) {
4286 for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) {
4287 bytes = fs__default['default'].readSync(
4288 fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos
4289 );
4290
4291 if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b)
4292 throw new Error('cannot append to compressed archives')
4293
4294 if (!bytes)
4295 break POSITION
4296 }
4297
4298 const h = new header(headBuf);
4299 if (!h.cksumValid)
4300 break
4301 const entryBlockSize = 512 * Math.ceil(h.size / 512);
4302 if (position + entryBlockSize + 512 > st.size)
4303 break
4304 // the 512 for the header we just parsed will be added as well
4305 // also jump ahead all the blocks for the body
4306 position += entryBlockSize;
4307 if (opt.mtimeCache)
4308 opt.mtimeCache.set(h.path, h.mtime);
4309 }
4310 threw = false;
4311
4312 streamSync(opt, p, position, fd, files);
4313 } finally {
4314 if (threw) {
4315 try {
4316 fs__default['default'].closeSync(fd);
4317 } catch (er) {}
4318 }
4319 }
4320};
4321
4322const streamSync = (opt, p, position, fd, files) => {
4323 const stream = new fsMinipass.WriteStreamSync(opt.file, {
4324 fd: fd,
4325 start: position,
4326 });
4327 p.pipe(stream);
4328 addFilesSync(p, files);
4329};
4330
4331const replace = (opt, files, cb) => {
4332 files = Array.from(files);
4333 const p = new pack(opt);
4334
4335 const getPos = (fd, size, cb_) => {
4336 const cb = (er, pos) => {
4337 if (er)
4338 fs__default['default'].close(fd, _ => cb_(er));
4339 else
4340 cb_(null, pos);
4341 };
4342
4343 let position = 0;
4344 if (size === 0)
4345 return cb(null, 0)
4346
4347 let bufPos = 0;
4348 const headBuf = Buffer.alloc(512);
4349 const onread = (er, bytes) => {
4350 if (er)
4351 return cb(er)
4352 bufPos += bytes;
4353 if (bufPos < 512 && bytes) {
4354 return fs__default['default'].read(
4355 fd, headBuf, bufPos, headBuf.length - bufPos,
4356 position + bufPos, onread
4357 )
4358 }
4359
4360 if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b)
4361 return cb(new Error('cannot append to compressed archives'))
4362
4363 // truncated header
4364 if (bufPos < 512)
4365 return cb(null, position)
4366
4367 const h = new header(headBuf);
4368 if (!h.cksumValid)
4369 return cb(null, position)
4370
4371 const entryBlockSize = 512 * Math.ceil(h.size / 512);
4372 if (position + entryBlockSize + 512 > size)
4373 return cb(null, position)
4374
4375 position += entryBlockSize + 512;
4376 if (position >= size)
4377 return cb(null, position)
4378
4379 if (opt.mtimeCache)
4380 opt.mtimeCache.set(h.path, h.mtime);
4381 bufPos = 0;
4382 fs__default['default'].read(fd, headBuf, 0, 512, position, onread);
4383 };
4384 fs__default['default'].read(fd, headBuf, 0, 512, position, onread);
4385 };
4386
4387 const promise = new Promise((resolve, reject) => {
4388 p.on('error', reject);
4389 let flag = 'r+';
4390 const onopen = (er, fd) => {
4391 if (er && er.code === 'ENOENT' && flag === 'r+') {
4392 flag = 'w+';
4393 return fs__default['default'].open(opt.file, flag, onopen)
4394 }
4395
4396 if (er)
4397 return reject(er)
4398
4399 fs__default['default'].fstat(fd, (er, st) => {
4400 if (er)
4401 return reject(er)
4402 getPos(fd, st.size, (er, position) => {
4403 if (er)
4404 return reject(er)
4405 const stream = new fsMinipass.WriteStream(opt.file, {
4406 fd: fd,
4407 start: position,
4408 });
4409 p.pipe(stream);
4410 stream.on('error', reject);
4411 stream.on('close', resolve);
4412 addFilesAsync(p, files);
4413 });
4414 });
4415 };
4416 fs__default['default'].open(opt.file, flag, onopen);
4417 });
4418
4419 return cb ? promise.then(cb, cb) : promise
4420};
4421
4422const addFilesSync = (p, files) => {
4423 files.forEach(file => {
4424 if (file.charAt(0) === '@') {
4425 list_1({
4426 file: path__default['default'].resolve(p.cwd, file.substr(1)),
4427 sync: true,
4428 noResume: true,
4429 onentry: entry => p.add(entry),
4430 });
4431 } else
4432 p.add(file);
4433 });
4434 p.end();
4435};
4436
4437const addFilesAsync = (p, files) => {
4438 while (files.length) {
4439 const file = files.shift();
4440 if (file.charAt(0) === '@') {
4441 return list_1({
4442 file: path__default['default'].resolve(p.cwd, file.substr(1)),
4443 noResume: true,
4444 onentry: entry => p.add(entry),
4445 }).then(_ => addFilesAsync(p, files))
4446 } else
4447 p.add(file);
4448 }
4449 p.end();
4450};
4451
4452// tar -u
4453
4454
4455
4456// just call tar.r with the filter and mtimeCache
4457
4458var update = (opt_, files, cb) => {
4459 const opt = highLevelOpt(opt_);
4460
4461 if (!opt.file)
4462 throw new TypeError('file is required')
4463
4464 if (opt.gzip)
4465 throw new TypeError('cannot append to compressed archives')
4466
4467 if (!files || !Array.isArray(files) || !files.length)
4468 throw new TypeError('no files or directories specified')
4469
4470 files = Array.from(files);
4471
4472 mtimeFilter(opt);
4473 return replace_1(opt, files, cb)
4474};
4475
4476const mtimeFilter = opt => {
4477 const filter = opt.filter;
4478
4479 if (!opt.mtimeCache)
4480 opt.mtimeCache = new Map();
4481
4482 opt.filter = filter ? (path, stat) =>
4483 filter(path, stat) && !(opt.mtimeCache.get(path) > stat.mtime)
4484 : (path, stat) => !(opt.mtimeCache.get(path) > stat.mtime);
4485};
4486
4487const { promisify: promisify$1 } = util__default['default'];
4488
4489const optsArg = opts => {
4490 if (!opts)
4491 opts = { mode: 0o777, fs: fs__default['default'] };
4492 else if (typeof opts === 'object')
4493 opts = { mode: 0o777, fs: fs__default['default'], ...opts };
4494 else if (typeof opts === 'number')
4495 opts = { mode: opts, fs: fs__default['default'] };
4496 else if (typeof opts === 'string')
4497 opts = { mode: parseInt(opts, 8), fs: fs__default['default'] };
4498 else
4499 throw new TypeError('invalid options argument')
4500
4501 opts.mkdir = opts.mkdir || opts.fs.mkdir || fs__default['default'].mkdir;
4502 opts.mkdirAsync = promisify$1(opts.mkdir);
4503 opts.stat = opts.stat || opts.fs.stat || fs__default['default'].stat;
4504 opts.statAsync = promisify$1(opts.stat);
4505 opts.statSync = opts.statSync || opts.fs.statSync || fs__default['default'].statSync;
4506 opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs__default['default'].mkdirSync;
4507 return opts
4508};
4509var optsArg_1 = optsArg;
4510
4511const platform$2 = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform;
4512const { resolve, parse: parse$3 } = path__default['default'];
4513const pathArg = path => {
4514 if (/\0/.test(path)) {
4515 // simulate same failure that node raises
4516 throw Object.assign(
4517 new TypeError('path must be a string without null bytes'),
4518 {
4519 path,
4520 code: 'ERR_INVALID_ARG_VALUE',
4521 }
4522 )
4523 }
4524
4525 path = resolve(path);
4526 if (platform$2 === 'win32') {
4527 const badWinChars = /[*|"<>?:]/;
4528 const {root} = parse$3(path);
4529 if (badWinChars.test(path.substr(root.length))) {
4530 throw Object.assign(new Error('Illegal characters in path.'), {
4531 path,
4532 code: 'EINVAL',
4533 })
4534 }
4535 }
4536
4537 return path
4538};
4539var pathArg_1 = pathArg;
4540
4541const {dirname: dirname$2} = path__default['default'];
4542
4543const findMade$1 = (opts, parent, path = undefined) => {
4544 // we never want the 'made' return value to be a root directory
4545 if (path === parent)
4546 return Promise.resolve()
4547
4548 return opts.statAsync(parent).then(
4549 st => st.isDirectory() ? path : undefined, // will fail later
4550 er => er.code === 'ENOENT'
4551 ? findMade$1(opts, dirname$2(parent), parent)
4552 : undefined
4553 )
4554};
4555
4556const findMadeSync$1 = (opts, parent, path = undefined) => {
4557 if (path === parent)
4558 return undefined
4559
4560 try {
4561 return opts.statSync(parent).isDirectory() ? path : undefined
4562 } catch (er) {
4563 return er.code === 'ENOENT'
4564 ? findMadeSync$1(opts, dirname$2(parent), parent)
4565 : undefined
4566 }
4567};
4568
4569var findMade_1 = {findMade: findMade$1, findMadeSync: findMadeSync$1};
4570
4571const {dirname: dirname$1} = path__default['default'];
4572
4573const mkdirpManual$2 = (path, opts, made) => {
4574 opts.recursive = false;
4575 const parent = dirname$1(path);
4576 if (parent === path) {
4577 return opts.mkdirAsync(path, opts).catch(er => {
4578 // swallowed by recursive implementation on posix systems
4579 // any other error is a failure
4580 if (er.code !== 'EISDIR')
4581 throw er
4582 })
4583 }
4584
4585 return opts.mkdirAsync(path, opts).then(() => made || path, er => {
4586 if (er.code === 'ENOENT')
4587 return mkdirpManual$2(parent, opts)
4588 .then(made => mkdirpManual$2(path, opts, made))
4589 if (er.code !== 'EEXIST' && er.code !== 'EROFS')
4590 throw er
4591 return opts.statAsync(path).then(st => {
4592 if (st.isDirectory())
4593 return made
4594 else
4595 throw er
4596 }, () => { throw er })
4597 })
4598};
4599
4600const mkdirpManualSync$2 = (path, opts, made) => {
4601 const parent = dirname$1(path);
4602 opts.recursive = false;
4603
4604 if (parent === path) {
4605 try {
4606 return opts.mkdirSync(path, opts)
4607 } catch (er) {
4608 // swallowed by recursive implementation on posix systems
4609 // any other error is a failure
4610 if (er.code !== 'EISDIR')
4611 throw er
4612 else
4613 return
4614 }
4615 }
4616
4617 try {
4618 opts.mkdirSync(path, opts);
4619 return made || path
4620 } catch (er) {
4621 if (er.code === 'ENOENT')
4622 return mkdirpManualSync$2(path, opts, mkdirpManualSync$2(parent, opts, made))
4623 if (er.code !== 'EEXIST' && er.code !== 'EROFS')
4624 throw er
4625 try {
4626 if (!opts.statSync(path).isDirectory())
4627 throw er
4628 } catch (_) {
4629 throw er
4630 }
4631 }
4632};
4633
4634var mkdirpManual_1 = {mkdirpManual: mkdirpManual$2, mkdirpManualSync: mkdirpManualSync$2};
4635
4636const {dirname} = path__default['default'];
4637const {findMade, findMadeSync} = findMade_1;
4638const {mkdirpManual: mkdirpManual$1, mkdirpManualSync: mkdirpManualSync$1} = mkdirpManual_1;
4639
4640const mkdirpNative$1 = (path, opts) => {
4641 opts.recursive = true;
4642 const parent = dirname(path);
4643 if (parent === path)
4644 return opts.mkdirAsync(path, opts)
4645
4646 return findMade(opts, path).then(made =>
4647 opts.mkdirAsync(path, opts).then(() => made)
4648 .catch(er => {
4649 if (er.code === 'ENOENT')
4650 return mkdirpManual$1(path, opts)
4651 else
4652 throw er
4653 }))
4654};
4655
4656const mkdirpNativeSync$1 = (path, opts) => {
4657 opts.recursive = true;
4658 const parent = dirname(path);
4659 if (parent === path)
4660 return opts.mkdirSync(path, opts)
4661
4662 const made = findMadeSync(opts, path);
4663 try {
4664 opts.mkdirSync(path, opts);
4665 return made
4666 } catch (er) {
4667 if (er.code === 'ENOENT')
4668 return mkdirpManualSync$1(path, opts)
4669 else
4670 throw er
4671 }
4672};
4673
4674var mkdirpNative_1 = {mkdirpNative: mkdirpNative$1, mkdirpNativeSync: mkdirpNativeSync$1};
4675
4676const version$1 = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version;
4677const versArr = version$1.replace(/^v/, '').split('.');
4678const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12;
4679
4680const useNative$1 = !hasNative ? () => false : opts => opts.mkdir === fs__default['default'].mkdir;
4681const useNativeSync$1 = !hasNative ? () => false : opts => opts.mkdirSync === fs__default['default'].mkdirSync;
4682
4683var useNative_1 = {useNative: useNative$1, useNativeSync: useNativeSync$1};
4684
4685const {mkdirpNative, mkdirpNativeSync} = mkdirpNative_1;
4686const {mkdirpManual, mkdirpManualSync} = mkdirpManual_1;
4687const {useNative, useNativeSync} = useNative_1;
4688
4689
4690const mkdirp$3 = (path, opts) => {
4691 path = pathArg_1(path);
4692 opts = optsArg_1(opts);
4693 return useNative(opts)
4694 ? mkdirpNative(path, opts)
4695 : mkdirpManual(path, opts)
4696};
4697
4698const mkdirpSync = (path, opts) => {
4699 path = pathArg_1(path);
4700 opts = optsArg_1(opts);
4701 return useNativeSync(opts)
4702 ? mkdirpNativeSync(path, opts)
4703 : mkdirpManualSync(path, opts)
4704};
4705
4706mkdirp$3.sync = mkdirpSync;
4707mkdirp$3.native = (path, opts) => mkdirpNative(pathArg_1(path), optsArg_1(opts));
4708mkdirp$3.manual = (path, opts) => mkdirpManual(pathArg_1(path), optsArg_1(opts));
4709mkdirp$3.nativeSync = (path, opts) => mkdirpNativeSync(pathArg_1(path), optsArg_1(opts));
4710mkdirp$3.manualSync = (path, opts) => mkdirpManualSync(pathArg_1(path), optsArg_1(opts));
4711
4712var mkdirp_1 = mkdirp$3;
4713
4714/* istanbul ignore next */
4715const LCHOWN = fs__default['default'].lchown ? 'lchown' : 'chown';
4716/* istanbul ignore next */
4717const LCHOWNSYNC = fs__default['default'].lchownSync ? 'lchownSync' : 'chownSync';
4718
4719/* istanbul ignore next */
4720const needEISDIRHandled = fs__default['default'].lchown &&
4721 !process.version.match(/v1[1-9]+\./) &&
4722 !process.version.match(/v10\.[6-9]/);
4723
4724const lchownSync = (path, uid, gid) => {
4725 try {
4726 return fs__default['default'][LCHOWNSYNC](path, uid, gid)
4727 } catch (er) {
4728 if (er.code !== 'ENOENT')
4729 throw er
4730 }
4731};
4732
4733/* istanbul ignore next */
4734const chownSync = (path, uid, gid) => {
4735 try {
4736 return fs__default['default'].chownSync(path, uid, gid)
4737 } catch (er) {
4738 if (er.code !== 'ENOENT')
4739 throw er
4740 }
4741};
4742
4743/* istanbul ignore next */
4744const handleEISDIR =
4745 needEISDIRHandled ? (path, uid, gid, cb) => er => {
4746 // Node prior to v10 had a very questionable implementation of
4747 // fs.lchown, which would always try to call fs.open on a directory
4748 // Fall back to fs.chown in those cases.
4749 if (!er || er.code !== 'EISDIR')
4750 cb(er);
4751 else
4752 fs__default['default'].chown(path, uid, gid, cb);
4753 }
4754 : (_, __, ___, cb) => cb;
4755
4756/* istanbul ignore next */
4757const handleEISDirSync =
4758 needEISDIRHandled ? (path, uid, gid) => {
4759 try {
4760 return lchownSync(path, uid, gid)
4761 } catch (er) {
4762 if (er.code !== 'EISDIR')
4763 throw er
4764 chownSync(path, uid, gid);
4765 }
4766 }
4767 : (path, uid, gid) => lchownSync(path, uid, gid);
4768
4769// fs.readdir could only accept an options object as of node v6
4770const nodeVersion = process.version;
4771let readdir = (path, options, cb) => fs__default['default'].readdir(path, options, cb);
4772let readdirSync = (path, options) => fs__default['default'].readdirSync(path, options);
4773/* istanbul ignore next */
4774if (/^v4\./.test(nodeVersion))
4775 readdir = (path, options, cb) => fs__default['default'].readdir(path, cb);
4776
4777const chown = (cpath, uid, gid, cb) => {
4778 fs__default['default'][LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => {
4779 // Skip ENOENT error
4780 cb(er && er.code !== 'ENOENT' ? er : null);
4781 }));
4782};
4783
4784const chownrKid = (p, child, uid, gid, cb) => {
4785 if (typeof child === 'string')
4786 return fs__default['default'].lstat(path__default['default'].resolve(p, child), (er, stats) => {
4787 // Skip ENOENT error
4788 if (er)
4789 return cb(er.code !== 'ENOENT' ? er : null)
4790 stats.name = child;
4791 chownrKid(p, stats, uid, gid, cb);
4792 })
4793
4794 if (child.isDirectory()) {
4795 chownr(path__default['default'].resolve(p, child.name), uid, gid, er => {
4796 if (er)
4797 return cb(er)
4798 const cpath = path__default['default'].resolve(p, child.name);
4799 chown(cpath, uid, gid, cb);
4800 });
4801 } else {
4802 const cpath = path__default['default'].resolve(p, child.name);
4803 chown(cpath, uid, gid, cb);
4804 }
4805};
4806
4807
4808const chownr = (p, uid, gid, cb) => {
4809 readdir(p, { withFileTypes: true }, (er, children) => {
4810 // any error other than ENOTDIR or ENOTSUP means it's not readable,
4811 // or doesn't exist. give up.
4812 if (er) {
4813 if (er.code === 'ENOENT')
4814 return cb()
4815 else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP')
4816 return cb(er)
4817 }
4818 if (er || !children.length)
4819 return chown(p, uid, gid, cb)
4820
4821 let len = children.length;
4822 let errState = null;
4823 const then = er => {
4824 if (errState)
4825 return
4826 if (er)
4827 return cb(errState = er)
4828 if (-- len === 0)
4829 return chown(p, uid, gid, cb)
4830 };
4831
4832 children.forEach(child => chownrKid(p, child, uid, gid, then));
4833 });
4834};
4835
4836const chownrKidSync = (p, child, uid, gid) => {
4837 if (typeof child === 'string') {
4838 try {
4839 const stats = fs__default['default'].lstatSync(path__default['default'].resolve(p, child));
4840 stats.name = child;
4841 child = stats;
4842 } catch (er) {
4843 if (er.code === 'ENOENT')
4844 return
4845 else
4846 throw er
4847 }
4848 }
4849
4850 if (child.isDirectory())
4851 chownrSync(path__default['default'].resolve(p, child.name), uid, gid);
4852
4853 handleEISDirSync(path__default['default'].resolve(p, child.name), uid, gid);
4854};
4855
4856const chownrSync = (p, uid, gid) => {
4857 let children;
4858 try {
4859 children = readdirSync(p, { withFileTypes: true });
4860 } catch (er) {
4861 if (er.code === 'ENOENT')
4862 return
4863 else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP')
4864 return handleEISDirSync(p, uid, gid)
4865 else
4866 throw er
4867 }
4868
4869 if (children && children.length)
4870 children.forEach(child => chownrKidSync(p, child, uid, gid));
4871
4872 return handleEISDirSync(p, uid, gid)
4873};
4874
4875var chownr_1 = chownr;
4876chownr.sync = chownrSync;
4877
4878// wrapper around mkdirp for tar's needs.
4879
4880// TODO: This should probably be a class, not functionally
4881// passing around state in a gazillion args.
4882
4883
4884
4885
4886
4887
4888class SymlinkError extends Error {
4889 constructor (symlink, path) {
4890 super('Cannot extract through symbolic link');
4891 this.path = path;
4892 this.symlink = symlink;
4893 }
4894
4895 get name () {
4896 return 'SylinkError'
4897 }
4898}
4899
4900class CwdError extends Error {
4901 constructor (path, code) {
4902 super(code + ': Cannot cd into \'' + path + '\'');
4903 this.path = path;
4904 this.code = code;
4905 }
4906
4907 get name () {
4908 return 'CwdError'
4909 }
4910}
4911
4912var mkdir = (dir, opt, cb) => {
4913 // if there's any overlap between mask and mode,
4914 // then we'll need an explicit chmod
4915 const umask = opt.umask;
4916 const mode = opt.mode | 0o0700;
4917 const needChmod = (mode & umask) !== 0;
4918
4919 const uid = opt.uid;
4920 const gid = opt.gid;
4921 const doChown = typeof uid === 'number' &&
4922 typeof gid === 'number' &&
4923 (uid !== opt.processUid || gid !== opt.processGid);
4924
4925 const preserve = opt.preserve;
4926 const unlink = opt.unlink;
4927 const cache = opt.cache;
4928 const cwd = opt.cwd;
4929
4930 const done = (er, created) => {
4931 if (er)
4932 cb(er);
4933 else {
4934 cache.set(dir, true);
4935 if (created && doChown)
4936 chownr_1(created, uid, gid, er => done(er));
4937 else if (needChmod)
4938 fs__default['default'].chmod(dir, mode, cb);
4939 else
4940 cb();
4941 }
4942 };
4943
4944 if (cache && cache.get(dir) === true)
4945 return done()
4946
4947 if (dir === cwd) {
4948 return fs__default['default'].stat(dir, (er, st) => {
4949 if (er || !st.isDirectory())
4950 er = new CwdError(dir, er && er.code || 'ENOTDIR');
4951 done(er);
4952 })
4953 }
4954
4955 if (preserve)
4956 return mkdirp_1(dir, {mode}).then(made => done(null, made), done)
4957
4958 const sub = path__default['default'].relative(cwd, dir);
4959 const parts = sub.split(/\/|\\/);
4960 mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done);
4961};
4962
4963const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => {
4964 if (!parts.length)
4965 return cb(null, created)
4966 const p = parts.shift();
4967 const part = base + '/' + p;
4968 if (cache.get(part))
4969 return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb)
4970 fs__default['default'].mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb));
4971};
4972
4973const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => er => {
4974 if (er) {
4975 if (er.path && path__default['default'].dirname(er.path) === cwd &&
4976 (er.code === 'ENOTDIR' || er.code === 'ENOENT'))
4977 return cb(new CwdError(cwd, er.code))
4978
4979 fs__default['default'].lstat(part, (statEr, st) => {
4980 if (statEr)
4981 cb(statEr);
4982 else if (st.isDirectory())
4983 mkdir_(part, parts, mode, cache, unlink, cwd, created, cb);
4984 else if (unlink) {
4985 fs__default['default'].unlink(part, er => {
4986 if (er)
4987 return cb(er)
4988 fs__default['default'].mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb));
4989 });
4990 } else if (st.isSymbolicLink())
4991 return cb(new SymlinkError(part, part + '/' + parts.join('/')))
4992 else
4993 cb(er);
4994 });
4995 } else {
4996 created = created || part;
4997 mkdir_(part, parts, mode, cache, unlink, cwd, created, cb);
4998 }
4999};
5000
5001var sync$1 = (dir, opt) => {
5002 // if there's any overlap between mask and mode,
5003 // then we'll need an explicit chmod
5004 const umask = opt.umask;
5005 const mode = opt.mode | 0o0700;
5006 const needChmod = (mode & umask) !== 0;
5007
5008 const uid = opt.uid;
5009 const gid = opt.gid;
5010 const doChown = typeof uid === 'number' &&
5011 typeof gid === 'number' &&
5012 (uid !== opt.processUid || gid !== opt.processGid);
5013
5014 const preserve = opt.preserve;
5015 const unlink = opt.unlink;
5016 const cache = opt.cache;
5017 const cwd = opt.cwd;
5018
5019 const done = (created) => {
5020 cache.set(dir, true);
5021 if (created && doChown)
5022 chownr_1.sync(created, uid, gid);
5023 if (needChmod)
5024 fs__default['default'].chmodSync(dir, mode);
5025 };
5026
5027 if (cache && cache.get(dir) === true)
5028 return done()
5029
5030 if (dir === cwd) {
5031 let ok = false;
5032 let code = 'ENOTDIR';
5033 try {
5034 ok = fs__default['default'].statSync(dir).isDirectory();
5035 } catch (er) {
5036 code = er.code;
5037 } finally {
5038 if (!ok)
5039 throw new CwdError(dir, code)
5040 }
5041 done();
5042 return
5043 }
5044
5045 if (preserve)
5046 return done(mkdirp_1.sync(dir, mode))
5047
5048 const sub = path__default['default'].relative(cwd, dir);
5049 const parts = sub.split(/\/|\\/);
5050 let created = null;
5051 for (let p = parts.shift(), part = cwd;
5052 p && (part += '/' + p);
5053 p = parts.shift()) {
5054 if (cache.get(part))
5055 continue
5056
5057 try {
5058 fs__default['default'].mkdirSync(part, mode);
5059 created = created || part;
5060 cache.set(part, true);
5061 } catch (er) {
5062 if (er.path && path__default['default'].dirname(er.path) === cwd &&
5063 (er.code === 'ENOTDIR' || er.code === 'ENOENT'))
5064 return new CwdError(cwd, er.code)
5065
5066 const st = fs__default['default'].lstatSync(part);
5067 if (st.isDirectory()) {
5068 cache.set(part, true);
5069 continue
5070 } else if (unlink) {
5071 fs__default['default'].unlinkSync(part);
5072 fs__default['default'].mkdirSync(part, mode);
5073 created = created || part;
5074 cache.set(part, true);
5075 continue
5076 } else if (st.isSymbolicLink())
5077 return new SymlinkError(part, part + '/' + parts.join('/'))
5078 }
5079 }
5080
5081 return done(created)
5082};
5083mkdir.sync = sync$1;
5084
5085// A path exclusive reservation system
5086// reserve([list, of, paths], fn)
5087// When the fn is first in line for all its paths, it
5088// is called with a cb that clears the reservation.
5089//
5090// Used by async unpack to avoid clobbering paths in use,
5091// while still allowing maximal safe parallelization.
5092
5093
5094
5095var pathReservations = () => {
5096 // path => [function or Set]
5097 // A Set object means a directory reservation
5098 // A fn is a direct reservation on that path
5099 const queues = new Map();
5100
5101 // fn => {paths:[path,...], dirs:[path, ...]}
5102 const reservations = new Map();
5103
5104 // return a set of parent dirs for a given path
5105 const { join } = path__default['default'];
5106 const getDirs = path =>
5107 join(path).split(/[\\/]/).slice(0, -1).reduce((set, path) =>
5108 set.length ? set.concat(join(set[set.length - 1], path)) : [path], []);
5109
5110 // functions currently running
5111 const running = new Set();
5112
5113 // return the queues for each path the function cares about
5114 // fn => {paths, dirs}
5115 const getQueues = fn => {
5116 const res = reservations.get(fn);
5117 /* istanbul ignore if - unpossible */
5118 if (!res)
5119 throw new Error('function does not have any path reservations')
5120 return {
5121 paths: res.paths.map(path => queues.get(path)),
5122 dirs: [...res.dirs].map(path => queues.get(path)),
5123 }
5124 };
5125
5126 // check if fn is first in line for all its paths, and is
5127 // included in the first set for all its dir queues
5128 const check = fn => {
5129 const {paths, dirs} = getQueues(fn);
5130 return paths.every(q => q[0] === fn) &&
5131 dirs.every(q => q[0] instanceof Set && q[0].has(fn))
5132 };
5133
5134 // run the function if it's first in line and not already running
5135 const run = fn => {
5136 if (running.has(fn) || !check(fn))
5137 return false
5138 running.add(fn);
5139 fn(() => clear(fn));
5140 return true
5141 };
5142
5143 const clear = fn => {
5144 if (!running.has(fn))
5145 return false
5146
5147 const { paths, dirs } = reservations.get(fn);
5148 const next = new Set();
5149
5150 paths.forEach(path => {
5151 const q = queues.get(path);
5152 assert__default['default'].equal(q[0], fn);
5153 if (q.length === 1)
5154 queues.delete(path);
5155 else {
5156 q.shift();
5157 if (typeof q[0] === 'function')
5158 next.add(q[0]);
5159 else
5160 q[0].forEach(fn => next.add(fn));
5161 }
5162 });
5163
5164 dirs.forEach(dir => {
5165 const q = queues.get(dir);
5166 assert__default['default'](q[0] instanceof Set);
5167 if (q[0].size === 1 && q.length === 1)
5168 queues.delete(dir);
5169 else if (q[0].size === 1) {
5170 q.shift();
5171
5172 // must be a function or else the Set would've been reused
5173 next.add(q[0]);
5174 } else
5175 q[0].delete(fn);
5176 });
5177 running.delete(fn);
5178
5179 next.forEach(fn => run(fn));
5180 return true
5181 };
5182
5183 const reserve = (paths, fn) => {
5184 const dirs = new Set(
5185 paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b))
5186 );
5187 reservations.set(fn, {dirs, paths});
5188 paths.forEach(path => {
5189 const q = queues.get(path);
5190 if (!q)
5191 queues.set(path, [fn]);
5192 else
5193 q.push(fn);
5194 });
5195 dirs.forEach(dir => {
5196 const q = queues.get(dir);
5197 if (!q)
5198 queues.set(dir, [new Set([fn])]);
5199 else if (q[q.length - 1] instanceof Set)
5200 q[q.length - 1].add(fn);
5201 else
5202 q.push(new Set([fn]));
5203 });
5204
5205 return run(fn)
5206 };
5207
5208 return { check, reserve }
5209};
5210
5211// Get the appropriate flag to use for creating files
5212// We use fmap on Windows platforms for files less than
5213// 512kb. This is a fairly low limit, but avoids making
5214// things slower in some cases. Since most of what this
5215// library is used for is extracting tarballs of many
5216// relatively small files in npm packages and the like,
5217// it can be a big boost on Windows platforms.
5218// Only supported in Node v12.9.0 and above.
5219const platform$1 = process.env.__FAKE_PLATFORM__ || process.platform;
5220const isWindows$2 = platform$1 === 'win32';
5221const fs = commonjsGlobal.__FAKE_TESTING_FS__ || fs__default['default'];
5222
5223/* istanbul ignore next */
5224const { O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP = 0 } = fs.constants;
5225
5226const fMapEnabled = isWindows$2 && !!UV_FS_O_FILEMAP;
5227const fMapLimit = 512 * 1024;
5228const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY;
5229var getWriteFlag = !fMapEnabled ? () => 'w'
5230 : size => size < fMapLimit ? fMapFlag : 'w';
5231
5232// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet.
5233// but the path reservations are required to avoid race conditions where
5234// parallelized unpack ops may mess with one another, due to dependencies
5235// (like a Link depending on its target) or destructive operations (like
5236// clobbering an fs object to create one of a different type.)
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247const ONENTRY = Symbol('onEntry');
5248const CHECKFS = Symbol('checkFs');
5249const CHECKFS2 = Symbol('checkFs2');
5250const ISREUSABLE = Symbol('isReusable');
5251const MAKEFS = Symbol('makeFs');
5252const FILE = Symbol('file');
5253const DIRECTORY = Symbol('directory');
5254const LINK = Symbol('link');
5255const SYMLINK = Symbol('symlink');
5256const HARDLINK = Symbol('hardlink');
5257const UNSUPPORTED = Symbol('unsupported');
5258const CHECKPATH = Symbol('checkPath');
5259const MKDIR = Symbol('mkdir');
5260const ONERROR = Symbol('onError');
5261const PENDING = Symbol('pending');
5262const PEND = Symbol('pend');
5263const UNPEND = Symbol('unpend');
5264const ENDED = Symbol('ended');
5265const MAYBECLOSE = Symbol('maybeClose');
5266const SKIP = Symbol('skip');
5267const DOCHOWN = Symbol('doChown');
5268const UID = Symbol('uid');
5269const GID = Symbol('gid');
5270
5271
5272
5273/* istanbul ignore next */
5274const neverCalled = () => {
5275 throw new Error('sync function called cb somehow?!?')
5276};
5277
5278// Unlinks on Windows are not atomic.
5279//
5280// This means that if you have a file entry, followed by another
5281// file entry with an identical name, and you cannot re-use the file
5282// (because it's a hardlink, or because unlink:true is set, or it's
5283// Windows, which does not have useful nlink values), then the unlink
5284// will be committed to the disk AFTER the new file has been written
5285// over the old one, deleting the new file.
5286//
5287// To work around this, on Windows systems, we rename the file and then
5288// delete the renamed file. It's a sloppy kludge, but frankly, I do not
5289// know of a better way to do this, given windows' non-atomic unlink
5290// semantics.
5291//
5292// See: https://github.com/npm/node-tar/issues/183
5293/* istanbul ignore next */
5294const unlinkFile = (path, cb) => {
5295 if (process.platform !== 'win32')
5296 return fs__default['default'].unlink(path, cb)
5297
5298 const name = path + '.DELETE.' + crypto__default['default'].randomBytes(16).toString('hex');
5299 fs__default['default'].rename(path, name, er => {
5300 if (er)
5301 return cb(er)
5302 fs__default['default'].unlink(name, cb);
5303 });
5304};
5305
5306/* istanbul ignore next */
5307const unlinkFileSync = path => {
5308 if (process.platform !== 'win32')
5309 return fs__default['default'].unlinkSync(path)
5310
5311 const name = path + '.DELETE.' + crypto__default['default'].randomBytes(16).toString('hex');
5312 fs__default['default'].renameSync(path, name);
5313 fs__default['default'].unlinkSync(name);
5314};
5315
5316// this.gid, entry.gid, this.processUid
5317const uint32 = (a, b, c) =>
5318 a === a >>> 0 ? a
5319 : b === b >>> 0 ? b
5320 : c;
5321
5322class Unpack extends parse$4 {
5323 constructor (opt) {
5324 if (!opt)
5325 opt = {};
5326
5327 opt.ondone = _ => {
5328 this[ENDED] = true;
5329 this[MAYBECLOSE]();
5330 };
5331
5332 super(opt);
5333
5334 this.reservations = pathReservations();
5335
5336 this.transform = typeof opt.transform === 'function' ? opt.transform : null;
5337
5338 this.writable = true;
5339 this.readable = false;
5340
5341 this[PENDING] = 0;
5342 this[ENDED] = false;
5343
5344 this.dirCache = opt.dirCache || new Map();
5345
5346 if (typeof opt.uid === 'number' || typeof opt.gid === 'number') {
5347 // need both or neither
5348 if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number')
5349 throw new TypeError('cannot set owner without number uid and gid')
5350 if (opt.preserveOwner) {
5351 throw new TypeError(
5352 'cannot preserve owner in archive and also set owner explicitly')
5353 }
5354 this.uid = opt.uid;
5355 this.gid = opt.gid;
5356 this.setOwner = true;
5357 } else {
5358 this.uid = null;
5359 this.gid = null;
5360 this.setOwner = false;
5361 }
5362
5363 // default true for root
5364 if (opt.preserveOwner === undefined && typeof opt.uid !== 'number')
5365 this.preserveOwner = process.getuid && process.getuid() === 0;
5366 else
5367 this.preserveOwner = !!opt.preserveOwner;
5368
5369 this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ?
5370 process.getuid() : null;
5371 this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ?
5372 process.getgid() : null;
5373
5374 // mostly just for testing, but useful in some cases.
5375 // Forcibly trigger a chown on every entry, no matter what
5376 this.forceChown = opt.forceChown === true;
5377
5378 // turn ><?| in filenames into 0xf000-higher encoded forms
5379 this.win32 = !!opt.win32 || process.platform === 'win32';
5380
5381 // do not unpack over files that are newer than what's in the archive
5382 this.newer = !!opt.newer;
5383
5384 // do not unpack over ANY files
5385 this.keep = !!opt.keep;
5386
5387 // do not set mtime/atime of extracted entries
5388 this.noMtime = !!opt.noMtime;
5389
5390 // allow .., absolute path entries, and unpacking through symlinks
5391 // without this, warn and skip .., relativize absolutes, and error
5392 // on symlinks in extraction path
5393 this.preservePaths = !!opt.preservePaths;
5394
5395 // unlink files and links before writing. This breaks existing hard
5396 // links, and removes symlink directories rather than erroring
5397 this.unlink = !!opt.unlink;
5398
5399 this.cwd = path__default['default'].resolve(opt.cwd || process.cwd());
5400 this.strip = +opt.strip || 0;
5401 // if we're not chmodding, then we don't need the process umask
5402 this.processUmask = opt.noChmod ? 0 : process.umask();
5403 this.umask = typeof opt.umask === 'number' ? opt.umask : this.processUmask;
5404
5405 // default mode for dirs created as parents
5406 this.dmode = opt.dmode || (0o0777 & (~this.umask));
5407 this.fmode = opt.fmode || (0o0666 & (~this.umask));
5408
5409 this.on('entry', entry => this[ONENTRY](entry));
5410 }
5411
5412 // a bad or damaged archive is a warning for Parser, but an error
5413 // when extracting. Mark those errors as unrecoverable, because
5414 // the Unpack contract cannot be met.
5415 warn (code, msg, data = {}) {
5416 if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT')
5417 data.recoverable = false;
5418 return super.warn(code, msg, data)
5419 }
5420
5421 [MAYBECLOSE] () {
5422 if (this[ENDED] && this[PENDING] === 0) {
5423 this.emit('prefinish');
5424 this.emit('finish');
5425 this.emit('end');
5426 this.emit('close');
5427 }
5428 }
5429
5430 [CHECKPATH] (entry) {
5431 if (this.strip) {
5432 const parts = entry.path.split(/\/|\\/);
5433 if (parts.length < this.strip)
5434 return false
5435 entry.path = parts.slice(this.strip).join('/');
5436
5437 if (entry.type === 'Link') {
5438 const linkparts = entry.linkpath.split(/\/|\\/);
5439 if (linkparts.length >= this.strip)
5440 entry.linkpath = linkparts.slice(this.strip).join('/');
5441 }
5442 }
5443
5444 if (!this.preservePaths) {
5445 const p = entry.path;
5446 if (p.match(/(^|\/|\\)\.\.(\\|\/|$)/)) {
5447 this.warn('TAR_ENTRY_ERROR', `path contains '..'`, {
5448 entry,
5449 path: p,
5450 });
5451 return false
5452 }
5453
5454 // absolutes on posix are also absolutes on win32
5455 // so we only need to test this one to get both
5456 if (path__default['default'].win32.isAbsolute(p)) {
5457 const parsed = path__default['default'].win32.parse(p);
5458 entry.path = p.substr(parsed.root.length);
5459 const r = parsed.root;
5460 this.warn('TAR_ENTRY_INFO', `stripping ${r} from absolute path`, {
5461 entry,
5462 path: p,
5463 });
5464 }
5465 }
5466
5467 // only encode : chars that aren't drive letter indicators
5468 if (this.win32) {
5469 const parsed = path__default['default'].win32.parse(entry.path);
5470 entry.path = parsed.root === '' ? winchars.encode(entry.path)
5471 : parsed.root + winchars.encode(entry.path.substr(parsed.root.length));
5472 }
5473
5474 if (path__default['default'].isAbsolute(entry.path))
5475 entry.absolute = entry.path;
5476 else
5477 entry.absolute = path__default['default'].resolve(this.cwd, entry.path);
5478
5479 return true
5480 }
5481
5482 [ONENTRY] (entry) {
5483 if (!this[CHECKPATH](entry))
5484 return entry.resume()
5485
5486 assert__default['default'].equal(typeof entry.absolute, 'string');
5487
5488 switch (entry.type) {
5489 case 'Directory':
5490 case 'GNUDumpDir':
5491 if (entry.mode)
5492 entry.mode = entry.mode | 0o700;
5493
5494 case 'File':
5495 case 'OldFile':
5496 case 'ContiguousFile':
5497 case 'Link':
5498 case 'SymbolicLink':
5499 return this[CHECKFS](entry)
5500
5501 case 'CharacterDevice':
5502 case 'BlockDevice':
5503 case 'FIFO':
5504 default:
5505 return this[UNSUPPORTED](entry)
5506 }
5507 }
5508
5509 [ONERROR] (er, entry) {
5510 // Cwd has to exist, or else nothing works. That's serious.
5511 // Other errors are warnings, which raise the error in strict
5512 // mode, but otherwise continue on.
5513 if (er.name === 'CwdError')
5514 this.emit('error', er);
5515 else {
5516 this.warn('TAR_ENTRY_ERROR', er, {entry});
5517 this[UNPEND]();
5518 entry.resume();
5519 }
5520 }
5521
5522 [MKDIR] (dir, mode, cb) {
5523 mkdir(dir, {
5524 uid: this.uid,
5525 gid: this.gid,
5526 processUid: this.processUid,
5527 processGid: this.processGid,
5528 umask: this.processUmask,
5529 preserve: this.preservePaths,
5530 unlink: this.unlink,
5531 cache: this.dirCache,
5532 cwd: this.cwd,
5533 mode: mode,
5534 noChmod: this.noChmod,
5535 }, cb);
5536 }
5537
5538 [DOCHOWN] (entry) {
5539 // in preserve owner mode, chown if the entry doesn't match process
5540 // in set owner mode, chown if setting doesn't match process
5541 return this.forceChown ||
5542 this.preserveOwner &&
5543 (typeof entry.uid === 'number' && entry.uid !== this.processUid ||
5544 typeof entry.gid === 'number' && entry.gid !== this.processGid)
5545 ||
5546 (typeof this.uid === 'number' && this.uid !== this.processUid ||
5547 typeof this.gid === 'number' && this.gid !== this.processGid)
5548 }
5549
5550 [UID] (entry) {
5551 return uint32(this.uid, entry.uid, this.processUid)
5552 }
5553
5554 [GID] (entry) {
5555 return uint32(this.gid, entry.gid, this.processGid)
5556 }
5557
5558 [FILE] (entry, fullyDone) {
5559 const mode = entry.mode & 0o7777 || this.fmode;
5560 const stream = new fsMinipass.WriteStream(entry.absolute, {
5561 flags: getWriteFlag(entry.size),
5562 mode: mode,
5563 autoClose: false,
5564 });
5565 stream.on('error', er => this[ONERROR](er, entry));
5566
5567 let actions = 1;
5568 const done = er => {
5569 if (er)
5570 return this[ONERROR](er, entry)
5571
5572 if (--actions === 0) {
5573 fs__default['default'].close(stream.fd, er => {
5574 fullyDone();
5575 er ? this[ONERROR](er, entry) : this[UNPEND]();
5576 });
5577 }
5578 };
5579
5580 stream.on('finish', _ => {
5581 // if futimes fails, try utimes
5582 // if utimes fails, fail with the original error
5583 // same for fchown/chown
5584 const abs = entry.absolute;
5585 const fd = stream.fd;
5586
5587 if (entry.mtime && !this.noMtime) {
5588 actions++;
5589 const atime = entry.atime || new Date();
5590 const mtime = entry.mtime;
5591 fs__default['default'].futimes(fd, atime, mtime, er =>
5592 er ? fs__default['default'].utimes(abs, atime, mtime, er2 => done(er2 && er))
5593 : done());
5594 }
5595
5596 if (this[DOCHOWN](entry)) {
5597 actions++;
5598 const uid = this[UID](entry);
5599 const gid = this[GID](entry);
5600 fs__default['default'].fchown(fd, uid, gid, er =>
5601 er ? fs__default['default'].chown(abs, uid, gid, er2 => done(er2 && er))
5602 : done());
5603 }
5604
5605 done();
5606 });
5607
5608 const tx = this.transform ? this.transform(entry) || entry : entry;
5609 if (tx !== entry) {
5610 tx.on('error', er => this[ONERROR](er, entry));
5611 entry.pipe(tx);
5612 }
5613 tx.pipe(stream);
5614 }
5615
5616 [DIRECTORY] (entry, fullyDone) {
5617 const mode = entry.mode & 0o7777 || this.dmode;
5618 this[MKDIR](entry.absolute, mode, er => {
5619 if (er) {
5620 fullyDone();
5621 return this[ONERROR](er, entry)
5622 }
5623
5624 let actions = 1;
5625 const done = _ => {
5626 if (--actions === 0) {
5627 fullyDone();
5628 this[UNPEND]();
5629 entry.resume();
5630 }
5631 };
5632
5633 if (entry.mtime && !this.noMtime) {
5634 actions++;
5635 fs__default['default'].utimes(entry.absolute, entry.atime || new Date(), entry.mtime, done);
5636 }
5637
5638 if (this[DOCHOWN](entry)) {
5639 actions++;
5640 fs__default['default'].chown(entry.absolute, this[UID](entry), this[GID](entry), done);
5641 }
5642
5643 done();
5644 });
5645 }
5646
5647 [UNSUPPORTED] (entry) {
5648 entry.unsupported = true;
5649 this.warn('TAR_ENTRY_UNSUPPORTED',
5650 `unsupported entry type: ${entry.type}`, {entry});
5651 entry.resume();
5652 }
5653
5654 [SYMLINK] (entry, done) {
5655 this[LINK](entry, entry.linkpath, 'symlink', done);
5656 }
5657
5658 [HARDLINK] (entry, done) {
5659 this[LINK](entry, path__default['default'].resolve(this.cwd, entry.linkpath), 'link', done);
5660 }
5661
5662 [PEND] () {
5663 this[PENDING]++;
5664 }
5665
5666 [UNPEND] () {
5667 this[PENDING]--;
5668 this[MAYBECLOSE]();
5669 }
5670
5671 [SKIP] (entry) {
5672 this[UNPEND]();
5673 entry.resume();
5674 }
5675
5676 // Check if we can reuse an existing filesystem entry safely and
5677 // overwrite it, rather than unlinking and recreating
5678 // Windows doesn't report a useful nlink, so we just never reuse entries
5679 [ISREUSABLE] (entry, st) {
5680 return entry.type === 'File' &&
5681 !this.unlink &&
5682 st.isFile() &&
5683 st.nlink <= 1 &&
5684 process.platform !== 'win32'
5685 }
5686
5687 // check if a thing is there, and if so, try to clobber it
5688 [CHECKFS] (entry) {
5689 this[PEND]();
5690 const paths = [entry.path];
5691 if (entry.linkpath)
5692 paths.push(entry.linkpath);
5693 this.reservations.reserve(paths, done => this[CHECKFS2](entry, done));
5694 }
5695
5696 [CHECKFS2] (entry, done) {
5697 this[MKDIR](path__default['default'].dirname(entry.absolute), this.dmode, er => {
5698 if (er) {
5699 done();
5700 return this[ONERROR](er, entry)
5701 }
5702 fs__default['default'].lstat(entry.absolute, (er, st) => {
5703 if (st && (this.keep || this.newer && st.mtime > entry.mtime)) {
5704 this[SKIP](entry);
5705 done();
5706 } else if (er || this[ISREUSABLE](entry, st))
5707 this[MAKEFS](null, entry, done);
5708
5709 else if (st.isDirectory()) {
5710 if (entry.type === 'Directory') {
5711 if (!this.noChmod && (!entry.mode || (st.mode & 0o7777) === entry.mode))
5712 this[MAKEFS](null, entry, done);
5713 else {
5714 fs__default['default'].chmod(entry.absolute, entry.mode,
5715 er => this[MAKEFS](er, entry, done));
5716 }
5717 } else
5718 fs__default['default'].rmdir(entry.absolute, er => this[MAKEFS](er, entry, done));
5719 } else
5720 unlinkFile(entry.absolute, er => this[MAKEFS](er, entry, done));
5721 });
5722 });
5723 }
5724
5725 [MAKEFS] (er, entry, done) {
5726 if (er)
5727 return this[ONERROR](er, entry)
5728
5729 switch (entry.type) {
5730 case 'File':
5731 case 'OldFile':
5732 case 'ContiguousFile':
5733 return this[FILE](entry, done)
5734
5735 case 'Link':
5736 return this[HARDLINK](entry, done)
5737
5738 case 'SymbolicLink':
5739 return this[SYMLINK](entry, done)
5740
5741 case 'Directory':
5742 case 'GNUDumpDir':
5743 return this[DIRECTORY](entry, done)
5744 }
5745 }
5746
5747 [LINK] (entry, linkpath, link, done) {
5748 // XXX: get the type ('file' or 'dir') for windows
5749 fs__default['default'][link](linkpath, entry.absolute, er => {
5750 if (er)
5751 return this[ONERROR](er, entry)
5752 done();
5753 this[UNPEND]();
5754 entry.resume();
5755 });
5756 }
5757}
5758
5759class UnpackSync extends Unpack {
5760 [CHECKFS] (entry) {
5761 const er = this[MKDIR](path__default['default'].dirname(entry.absolute), this.dmode, neverCalled);
5762 if (er)
5763 return this[ONERROR](er, entry)
5764 try {
5765 const st = fs__default['default'].lstatSync(entry.absolute);
5766 if (this.keep || this.newer && st.mtime > entry.mtime)
5767 return this[SKIP](entry)
5768 else if (this[ISREUSABLE](entry, st))
5769 return this[MAKEFS](null, entry, neverCalled)
5770 else {
5771 try {
5772 if (st.isDirectory()) {
5773 if (entry.type === 'Directory') {
5774 if (!this.noChmod && entry.mode && (st.mode & 0o7777) !== entry.mode)
5775 fs__default['default'].chmodSync(entry.absolute, entry.mode);
5776 } else
5777 fs__default['default'].rmdirSync(entry.absolute);
5778 } else
5779 unlinkFileSync(entry.absolute);
5780 return this[MAKEFS](null, entry, neverCalled)
5781 } catch (er) {
5782 return this[ONERROR](er, entry)
5783 }
5784 }
5785 } catch (er) {
5786 return this[MAKEFS](null, entry, neverCalled)
5787 }
5788 }
5789
5790 [FILE] (entry, _) {
5791 const mode = entry.mode & 0o7777 || this.fmode;
5792
5793 const oner = er => {
5794 let closeError;
5795 try {
5796 fs__default['default'].closeSync(fd);
5797 } catch (e) {
5798 closeError = e;
5799 }
5800 if (er || closeError)
5801 this[ONERROR](er || closeError, entry);
5802 };
5803
5804 let fd;
5805 try {
5806 fd = fs__default['default'].openSync(entry.absolute, getWriteFlag(entry.size), mode);
5807 } catch (er) {
5808 return oner(er)
5809 }
5810 const tx = this.transform ? this.transform(entry) || entry : entry;
5811 if (tx !== entry) {
5812 tx.on('error', er => this[ONERROR](er, entry));
5813 entry.pipe(tx);
5814 }
5815
5816 tx.on('data', chunk => {
5817 try {
5818 fs__default['default'].writeSync(fd, chunk, 0, chunk.length);
5819 } catch (er) {
5820 oner(er);
5821 }
5822 });
5823
5824 tx.on('end', _ => {
5825 let er = null;
5826 // try both, falling futimes back to utimes
5827 // if either fails, handle the first error
5828 if (entry.mtime && !this.noMtime) {
5829 const atime = entry.atime || new Date();
5830 const mtime = entry.mtime;
5831 try {
5832 fs__default['default'].futimesSync(fd, atime, mtime);
5833 } catch (futimeser) {
5834 try {
5835 fs__default['default'].utimesSync(entry.absolute, atime, mtime);
5836 } catch (utimeser) {
5837 er = futimeser;
5838 }
5839 }
5840 }
5841
5842 if (this[DOCHOWN](entry)) {
5843 const uid = this[UID](entry);
5844 const gid = this[GID](entry);
5845
5846 try {
5847 fs__default['default'].fchownSync(fd, uid, gid);
5848 } catch (fchowner) {
5849 try {
5850 fs__default['default'].chownSync(entry.absolute, uid, gid);
5851 } catch (chowner) {
5852 er = er || fchowner;
5853 }
5854 }
5855 }
5856
5857 oner(er);
5858 });
5859 }
5860
5861 [DIRECTORY] (entry, _) {
5862 const mode = entry.mode & 0o7777 || this.dmode;
5863 const er = this[MKDIR](entry.absolute, mode);
5864 if (er)
5865 return this[ONERROR](er, entry)
5866 if (entry.mtime && !this.noMtime) {
5867 try {
5868 fs__default['default'].utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime);
5869 } catch (er) {}
5870 }
5871 if (this[DOCHOWN](entry)) {
5872 try {
5873 fs__default['default'].chownSync(entry.absolute, this[UID](entry), this[GID](entry));
5874 } catch (er) {}
5875 }
5876 entry.resume();
5877 }
5878
5879 [MKDIR] (dir, mode) {
5880 try {
5881 return mkdir.sync(dir, {
5882 uid: this.uid,
5883 gid: this.gid,
5884 processUid: this.processUid,
5885 processGid: this.processGid,
5886 umask: this.processUmask,
5887 preserve: this.preservePaths,
5888 unlink: this.unlink,
5889 cache: this.dirCache,
5890 cwd: this.cwd,
5891 mode: mode,
5892 })
5893 } catch (er) {
5894 return er
5895 }
5896 }
5897
5898 [LINK] (entry, linkpath, link, _) {
5899 try {
5900 fs__default['default'][link + 'Sync'](linkpath, entry.absolute);
5901 entry.resume();
5902 } catch (er) {
5903 return this[ONERROR](er, entry)
5904 }
5905 }
5906}
5907
5908Unpack.Sync = UnpackSync;
5909var unpack = Unpack;
5910
5911// tar -x
5912
5913
5914
5915
5916
5917
5918var extract_1 = (opt_, files, cb) => {
5919 if (typeof opt_ === 'function')
5920 cb = opt_, files = null, opt_ = {};
5921 else if (Array.isArray(opt_))
5922 files = opt_, opt_ = {};
5923
5924 if (typeof files === 'function')
5925 cb = files, files = null;
5926
5927 if (!files)
5928 files = [];
5929 else
5930 files = Array.from(files);
5931
5932 const opt = highLevelOpt(opt_);
5933
5934 if (opt.sync && typeof cb === 'function')
5935 throw new TypeError('callback not supported for sync tar functions')
5936
5937 if (!opt.file && typeof cb === 'function')
5938 throw new TypeError('callback only supported with file option')
5939
5940 if (files.length)
5941 filesFilter(opt, files);
5942
5943 return opt.file && opt.sync ? extractFileSync(opt)
5944 : opt.file ? extractFile(opt, cb)
5945 : opt.sync ? extractSync(opt)
5946 : extract(opt)
5947};
5948
5949// construct a filter that limits the file entries listed
5950// include child entries if a dir is included
5951const filesFilter = (opt, files) => {
5952 const map = new Map(files.map(f => [f.replace(/\/+$/, ''), true]));
5953 const filter = opt.filter;
5954
5955 const mapHas = (file, r) => {
5956 const root = r || path__default['default'].parse(file).root || '.';
5957 const ret = file === root ? false
5958 : map.has(file) ? map.get(file)
5959 : mapHas(path__default['default'].dirname(file), root);
5960
5961 map.set(file, ret);
5962 return ret
5963 };
5964
5965 opt.filter = filter
5966 ? (file, entry) => filter(file, entry) && mapHas(file.replace(/\/+$/, ''))
5967 : file => mapHas(file.replace(/\/+$/, ''));
5968};
5969
5970const extractFileSync = opt => {
5971 const u = new unpack.Sync(opt);
5972
5973 const file = opt.file;
5974 const stat = fs__default['default'].statSync(file);
5975 // This trades a zero-byte read() syscall for a stat
5976 // However, it will usually result in less memory allocation
5977 const readSize = opt.maxReadSize || 16 * 1024 * 1024;
5978 const stream = new fsMinipass.ReadStreamSync(file, {
5979 readSize: readSize,
5980 size: stat.size,
5981 });
5982 stream.pipe(u);
5983};
5984
5985const extractFile = (opt, cb) => {
5986 const u = new unpack(opt);
5987 const readSize = opt.maxReadSize || 16 * 1024 * 1024;
5988
5989 const file = opt.file;
5990 const p = new Promise((resolve, reject) => {
5991 u.on('error', reject);
5992 u.on('close', resolve);
5993
5994 // This trades a zero-byte read() syscall for a stat
5995 // However, it will usually result in less memory allocation
5996 fs__default['default'].stat(file, (er, stat) => {
5997 if (er)
5998 reject(er);
5999 else {
6000 const stream = new fsMinipass.ReadStream(file, {
6001 readSize: readSize,
6002 size: stat.size,
6003 });
6004 stream.on('error', reject);
6005 stream.pipe(u);
6006 }
6007 });
6008 });
6009 return cb ? p.then(cb, cb) : p
6010};
6011
6012const extractSync = opt => new unpack.Sync(opt);
6013
6014const extract = opt => new unpack(opt);
6015
6016var tar = createCommonjsModule(function (module, exports) {
6017
6018// high-level commands
6019exports.c = exports.create = create_1;
6020exports.r = exports.replace = replace_1;
6021exports.t = exports.list = list_1;
6022exports.u = exports.update = update;
6023exports.x = exports.extract = extract_1;
6024
6025// classes
6026exports.Pack = pack;
6027exports.Unpack = unpack;
6028exports.Parse = parse$4;
6029exports.ReadEntry = readEntry;
6030exports.WriteEntry = writeEntry;
6031exports.Header = header;
6032exports.Pax = pax;
6033exports.types = types;
6034});
6035
6036var colorName = {
6037 "aliceblue": [240, 248, 255],
6038 "antiquewhite": [250, 235, 215],
6039 "aqua": [0, 255, 255],
6040 "aquamarine": [127, 255, 212],
6041 "azure": [240, 255, 255],
6042 "beige": [245, 245, 220],
6043 "bisque": [255, 228, 196],
6044 "black": [0, 0, 0],
6045 "blanchedalmond": [255, 235, 205],
6046 "blue": [0, 0, 255],
6047 "blueviolet": [138, 43, 226],
6048 "brown": [165, 42, 42],
6049 "burlywood": [222, 184, 135],
6050 "cadetblue": [95, 158, 160],
6051 "chartreuse": [127, 255, 0],
6052 "chocolate": [210, 105, 30],
6053 "coral": [255, 127, 80],
6054 "cornflowerblue": [100, 149, 237],
6055 "cornsilk": [255, 248, 220],
6056 "crimson": [220, 20, 60],
6057 "cyan": [0, 255, 255],
6058 "darkblue": [0, 0, 139],
6059 "darkcyan": [0, 139, 139],
6060 "darkgoldenrod": [184, 134, 11],
6061 "darkgray": [169, 169, 169],
6062 "darkgreen": [0, 100, 0],
6063 "darkgrey": [169, 169, 169],
6064 "darkkhaki": [189, 183, 107],
6065 "darkmagenta": [139, 0, 139],
6066 "darkolivegreen": [85, 107, 47],
6067 "darkorange": [255, 140, 0],
6068 "darkorchid": [153, 50, 204],
6069 "darkred": [139, 0, 0],
6070 "darksalmon": [233, 150, 122],
6071 "darkseagreen": [143, 188, 143],
6072 "darkslateblue": [72, 61, 139],
6073 "darkslategray": [47, 79, 79],
6074 "darkslategrey": [47, 79, 79],
6075 "darkturquoise": [0, 206, 209],
6076 "darkviolet": [148, 0, 211],
6077 "deeppink": [255, 20, 147],
6078 "deepskyblue": [0, 191, 255],
6079 "dimgray": [105, 105, 105],
6080 "dimgrey": [105, 105, 105],
6081 "dodgerblue": [30, 144, 255],
6082 "firebrick": [178, 34, 34],
6083 "floralwhite": [255, 250, 240],
6084 "forestgreen": [34, 139, 34],
6085 "fuchsia": [255, 0, 255],
6086 "gainsboro": [220, 220, 220],
6087 "ghostwhite": [248, 248, 255],
6088 "gold": [255, 215, 0],
6089 "goldenrod": [218, 165, 32],
6090 "gray": [128, 128, 128],
6091 "green": [0, 128, 0],
6092 "greenyellow": [173, 255, 47],
6093 "grey": [128, 128, 128],
6094 "honeydew": [240, 255, 240],
6095 "hotpink": [255, 105, 180],
6096 "indianred": [205, 92, 92],
6097 "indigo": [75, 0, 130],
6098 "ivory": [255, 255, 240],
6099 "khaki": [240, 230, 140],
6100 "lavender": [230, 230, 250],
6101 "lavenderblush": [255, 240, 245],
6102 "lawngreen": [124, 252, 0],
6103 "lemonchiffon": [255, 250, 205],
6104 "lightblue": [173, 216, 230],
6105 "lightcoral": [240, 128, 128],
6106 "lightcyan": [224, 255, 255],
6107 "lightgoldenrodyellow": [250, 250, 210],
6108 "lightgray": [211, 211, 211],
6109 "lightgreen": [144, 238, 144],
6110 "lightgrey": [211, 211, 211],
6111 "lightpink": [255, 182, 193],
6112 "lightsalmon": [255, 160, 122],
6113 "lightseagreen": [32, 178, 170],
6114 "lightskyblue": [135, 206, 250],
6115 "lightslategray": [119, 136, 153],
6116 "lightslategrey": [119, 136, 153],
6117 "lightsteelblue": [176, 196, 222],
6118 "lightyellow": [255, 255, 224],
6119 "lime": [0, 255, 0],
6120 "limegreen": [50, 205, 50],
6121 "linen": [250, 240, 230],
6122 "magenta": [255, 0, 255],
6123 "maroon": [128, 0, 0],
6124 "mediumaquamarine": [102, 205, 170],
6125 "mediumblue": [0, 0, 205],
6126 "mediumorchid": [186, 85, 211],
6127 "mediumpurple": [147, 112, 219],
6128 "mediumseagreen": [60, 179, 113],
6129 "mediumslateblue": [123, 104, 238],
6130 "mediumspringgreen": [0, 250, 154],
6131 "mediumturquoise": [72, 209, 204],
6132 "mediumvioletred": [199, 21, 133],
6133 "midnightblue": [25, 25, 112],
6134 "mintcream": [245, 255, 250],
6135 "mistyrose": [255, 228, 225],
6136 "moccasin": [255, 228, 181],
6137 "navajowhite": [255, 222, 173],
6138 "navy": [0, 0, 128],
6139 "oldlace": [253, 245, 230],
6140 "olive": [128, 128, 0],
6141 "olivedrab": [107, 142, 35],
6142 "orange": [255, 165, 0],
6143 "orangered": [255, 69, 0],
6144 "orchid": [218, 112, 214],
6145 "palegoldenrod": [238, 232, 170],
6146 "palegreen": [152, 251, 152],
6147 "paleturquoise": [175, 238, 238],
6148 "palevioletred": [219, 112, 147],
6149 "papayawhip": [255, 239, 213],
6150 "peachpuff": [255, 218, 185],
6151 "peru": [205, 133, 63],
6152 "pink": [255, 192, 203],
6153 "plum": [221, 160, 221],
6154 "powderblue": [176, 224, 230],
6155 "purple": [128, 0, 128],
6156 "rebeccapurple": [102, 51, 153],
6157 "red": [255, 0, 0],
6158 "rosybrown": [188, 143, 143],
6159 "royalblue": [65, 105, 225],
6160 "saddlebrown": [139, 69, 19],
6161 "salmon": [250, 128, 114],
6162 "sandybrown": [244, 164, 96],
6163 "seagreen": [46, 139, 87],
6164 "seashell": [255, 245, 238],
6165 "sienna": [160, 82, 45],
6166 "silver": [192, 192, 192],
6167 "skyblue": [135, 206, 235],
6168 "slateblue": [106, 90, 205],
6169 "slategray": [112, 128, 144],
6170 "slategrey": [112, 128, 144],
6171 "snow": [255, 250, 250],
6172 "springgreen": [0, 255, 127],
6173 "steelblue": [70, 130, 180],
6174 "tan": [210, 180, 140],
6175 "teal": [0, 128, 128],
6176 "thistle": [216, 191, 216],
6177 "tomato": [255, 99, 71],
6178 "turquoise": [64, 224, 208],
6179 "violet": [238, 130, 238],
6180 "wheat": [245, 222, 179],
6181 "white": [255, 255, 255],
6182 "whitesmoke": [245, 245, 245],
6183 "yellow": [255, 255, 0],
6184 "yellowgreen": [154, 205, 50]
6185};
6186
6187/* MIT license */
6188
6189/* eslint-disable no-mixed-operators */
6190
6191
6192// NOTE: conversions should only return primitive values (i.e. arrays, or
6193// values that give correct `typeof` results).
6194// do not use box values types (i.e. Number(), String(), etc.)
6195
6196const reverseKeywords = {};
6197for (const key of Object.keys(colorName)) {
6198 reverseKeywords[colorName[key]] = key;
6199}
6200
6201const convert$1 = {
6202 rgb: {channels: 3, labels: 'rgb'},
6203 hsl: {channels: 3, labels: 'hsl'},
6204 hsv: {channels: 3, labels: 'hsv'},
6205 hwb: {channels: 3, labels: 'hwb'},
6206 cmyk: {channels: 4, labels: 'cmyk'},
6207 xyz: {channels: 3, labels: 'xyz'},
6208 lab: {channels: 3, labels: 'lab'},
6209 lch: {channels: 3, labels: 'lch'},
6210 hex: {channels: 1, labels: ['hex']},
6211 keyword: {channels: 1, labels: ['keyword']},
6212 ansi16: {channels: 1, labels: ['ansi16']},
6213 ansi256: {channels: 1, labels: ['ansi256']},
6214 hcg: {channels: 3, labels: ['h', 'c', 'g']},
6215 apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
6216 gray: {channels: 1, labels: ['gray']}
6217};
6218
6219var conversions = convert$1;
6220
6221// Hide .channels and .labels properties
6222for (const model of Object.keys(convert$1)) {
6223 if (!('channels' in convert$1[model])) {
6224 throw new Error('missing channels property: ' + model);
6225 }
6226
6227 if (!('labels' in convert$1[model])) {
6228 throw new Error('missing channel labels property: ' + model);
6229 }
6230
6231 if (convert$1[model].labels.length !== convert$1[model].channels) {
6232 throw new Error('channel and label counts mismatch: ' + model);
6233 }
6234
6235 const {channels, labels} = convert$1[model];
6236 delete convert$1[model].channels;
6237 delete convert$1[model].labels;
6238 Object.defineProperty(convert$1[model], 'channels', {value: channels});
6239 Object.defineProperty(convert$1[model], 'labels', {value: labels});
6240}
6241
6242convert$1.rgb.hsl = function (rgb) {
6243 const r = rgb[0] / 255;
6244 const g = rgb[1] / 255;
6245 const b = rgb[2] / 255;
6246 const min = Math.min(r, g, b);
6247 const max = Math.max(r, g, b);
6248 const delta = max - min;
6249 let h;
6250 let s;
6251
6252 if (max === min) {
6253 h = 0;
6254 } else if (r === max) {
6255 h = (g - b) / delta;
6256 } else if (g === max) {
6257 h = 2 + (b - r) / delta;
6258 } else if (b === max) {
6259 h = 4 + (r - g) / delta;
6260 }
6261
6262 h = Math.min(h * 60, 360);
6263
6264 if (h < 0) {
6265 h += 360;
6266 }
6267
6268 const l = (min + max) / 2;
6269
6270 if (max === min) {
6271 s = 0;
6272 } else if (l <= 0.5) {
6273 s = delta / (max + min);
6274 } else {
6275 s = delta / (2 - max - min);
6276 }
6277
6278 return [h, s * 100, l * 100];
6279};
6280
6281convert$1.rgb.hsv = function (rgb) {
6282 let rdif;
6283 let gdif;
6284 let bdif;
6285 let h;
6286 let s;
6287
6288 const r = rgb[0] / 255;
6289 const g = rgb[1] / 255;
6290 const b = rgb[2] / 255;
6291 const v = Math.max(r, g, b);
6292 const diff = v - Math.min(r, g, b);
6293 const diffc = function (c) {
6294 return (v - c) / 6 / diff + 1 / 2;
6295 };
6296
6297 if (diff === 0) {
6298 h = 0;
6299 s = 0;
6300 } else {
6301 s = diff / v;
6302 rdif = diffc(r);
6303 gdif = diffc(g);
6304 bdif = diffc(b);
6305
6306 if (r === v) {
6307 h = bdif - gdif;
6308 } else if (g === v) {
6309 h = (1 / 3) + rdif - bdif;
6310 } else if (b === v) {
6311 h = (2 / 3) + gdif - rdif;
6312 }
6313
6314 if (h < 0) {
6315 h += 1;
6316 } else if (h > 1) {
6317 h -= 1;
6318 }
6319 }
6320
6321 return [
6322 h * 360,
6323 s * 100,
6324 v * 100
6325 ];
6326};
6327
6328convert$1.rgb.hwb = function (rgb) {
6329 const r = rgb[0];
6330 const g = rgb[1];
6331 let b = rgb[2];
6332 const h = convert$1.rgb.hsl(rgb)[0];
6333 const w = 1 / 255 * Math.min(r, Math.min(g, b));
6334
6335 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
6336
6337 return [h, w * 100, b * 100];
6338};
6339
6340convert$1.rgb.cmyk = function (rgb) {
6341 const r = rgb[0] / 255;
6342 const g = rgb[1] / 255;
6343 const b = rgb[2] / 255;
6344
6345 const k = Math.min(1 - r, 1 - g, 1 - b);
6346 const c = (1 - r - k) / (1 - k) || 0;
6347 const m = (1 - g - k) / (1 - k) || 0;
6348 const y = (1 - b - k) / (1 - k) || 0;
6349
6350 return [c * 100, m * 100, y * 100, k * 100];
6351};
6352
6353function comparativeDistance(x, y) {
6354 /*
6355 See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
6356 */
6357 return (
6358 ((x[0] - y[0]) ** 2) +
6359 ((x[1] - y[1]) ** 2) +
6360 ((x[2] - y[2]) ** 2)
6361 );
6362}
6363
6364convert$1.rgb.keyword = function (rgb) {
6365 const reversed = reverseKeywords[rgb];
6366 if (reversed) {
6367 return reversed;
6368 }
6369
6370 let currentClosestDistance = Infinity;
6371 let currentClosestKeyword;
6372
6373 for (const keyword of Object.keys(colorName)) {
6374 const value = colorName[keyword];
6375
6376 // Compute comparative distance
6377 const distance = comparativeDistance(rgb, value);
6378
6379 // Check if its less, if so set as closest
6380 if (distance < currentClosestDistance) {
6381 currentClosestDistance = distance;
6382 currentClosestKeyword = keyword;
6383 }
6384 }
6385
6386 return currentClosestKeyword;
6387};
6388
6389convert$1.keyword.rgb = function (keyword) {
6390 return colorName[keyword];
6391};
6392
6393convert$1.rgb.xyz = function (rgb) {
6394 let r = rgb[0] / 255;
6395 let g = rgb[1] / 255;
6396 let b = rgb[2] / 255;
6397
6398 // Assume sRGB
6399 r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
6400 g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
6401 b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
6402
6403 const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
6404 const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
6405 const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
6406
6407 return [x * 100, y * 100, z * 100];
6408};
6409
6410convert$1.rgb.lab = function (rgb) {
6411 const xyz = convert$1.rgb.xyz(rgb);
6412 let x = xyz[0];
6413 let y = xyz[1];
6414 let z = xyz[2];
6415
6416 x /= 95.047;
6417 y /= 100;
6418 z /= 108.883;
6419
6420 x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
6421 y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
6422 z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
6423
6424 const l = (116 * y) - 16;
6425 const a = 500 * (x - y);
6426 const b = 200 * (y - z);
6427
6428 return [l, a, b];
6429};
6430
6431convert$1.hsl.rgb = function (hsl) {
6432 const h = hsl[0] / 360;
6433 const s = hsl[1] / 100;
6434 const l = hsl[2] / 100;
6435 let t2;
6436 let t3;
6437 let val;
6438
6439 if (s === 0) {
6440 val = l * 255;
6441 return [val, val, val];
6442 }
6443
6444 if (l < 0.5) {
6445 t2 = l * (1 + s);
6446 } else {
6447 t2 = l + s - l * s;
6448 }
6449
6450 const t1 = 2 * l - t2;
6451
6452 const rgb = [0, 0, 0];
6453 for (let i = 0; i < 3; i++) {
6454 t3 = h + 1 / 3 * -(i - 1);
6455 if (t3 < 0) {
6456 t3++;
6457 }
6458
6459 if (t3 > 1) {
6460 t3--;
6461 }
6462
6463 if (6 * t3 < 1) {
6464 val = t1 + (t2 - t1) * 6 * t3;
6465 } else if (2 * t3 < 1) {
6466 val = t2;
6467 } else if (3 * t3 < 2) {
6468 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
6469 } else {
6470 val = t1;
6471 }
6472
6473 rgb[i] = val * 255;
6474 }
6475
6476 return rgb;
6477};
6478
6479convert$1.hsl.hsv = function (hsl) {
6480 const h = hsl[0];
6481 let s = hsl[1] / 100;
6482 let l = hsl[2] / 100;
6483 let smin = s;
6484 const lmin = Math.max(l, 0.01);
6485
6486 l *= 2;
6487 s *= (l <= 1) ? l : 2 - l;
6488 smin *= lmin <= 1 ? lmin : 2 - lmin;
6489 const v = (l + s) / 2;
6490 const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
6491
6492 return [h, sv * 100, v * 100];
6493};
6494
6495convert$1.hsv.rgb = function (hsv) {
6496 const h = hsv[0] / 60;
6497 const s = hsv[1] / 100;
6498 let v = hsv[2] / 100;
6499 const hi = Math.floor(h) % 6;
6500
6501 const f = h - Math.floor(h);
6502 const p = 255 * v * (1 - s);
6503 const q = 255 * v * (1 - (s * f));
6504 const t = 255 * v * (1 - (s * (1 - f)));
6505 v *= 255;
6506
6507 switch (hi) {
6508 case 0:
6509 return [v, t, p];
6510 case 1:
6511 return [q, v, p];
6512 case 2:
6513 return [p, v, t];
6514 case 3:
6515 return [p, q, v];
6516 case 4:
6517 return [t, p, v];
6518 case 5:
6519 return [v, p, q];
6520 }
6521};
6522
6523convert$1.hsv.hsl = function (hsv) {
6524 const h = hsv[0];
6525 const s = hsv[1] / 100;
6526 const v = hsv[2] / 100;
6527 const vmin = Math.max(v, 0.01);
6528 let sl;
6529 let l;
6530
6531 l = (2 - s) * v;
6532 const lmin = (2 - s) * vmin;
6533 sl = s * vmin;
6534 sl /= (lmin <= 1) ? lmin : 2 - lmin;
6535 sl = sl || 0;
6536 l /= 2;
6537
6538 return [h, sl * 100, l * 100];
6539};
6540
6541// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
6542convert$1.hwb.rgb = function (hwb) {
6543 const h = hwb[0] / 360;
6544 let wh = hwb[1] / 100;
6545 let bl = hwb[2] / 100;
6546 const ratio = wh + bl;
6547 let f;
6548
6549 // Wh + bl cant be > 1
6550 if (ratio > 1) {
6551 wh /= ratio;
6552 bl /= ratio;
6553 }
6554
6555 const i = Math.floor(6 * h);
6556 const v = 1 - bl;
6557 f = 6 * h - i;
6558
6559 if ((i & 0x01) !== 0) {
6560 f = 1 - f;
6561 }
6562
6563 const n = wh + f * (v - wh); // Linear interpolation
6564
6565 let r;
6566 let g;
6567 let b;
6568 /* eslint-disable max-statements-per-line,no-multi-spaces */
6569 switch (i) {
6570 default:
6571 case 6:
6572 case 0: r = v; g = n; b = wh; break;
6573 case 1: r = n; g = v; b = wh; break;
6574 case 2: r = wh; g = v; b = n; break;
6575 case 3: r = wh; g = n; b = v; break;
6576 case 4: r = n; g = wh; b = v; break;
6577 case 5: r = v; g = wh; b = n; break;
6578 }
6579 /* eslint-enable max-statements-per-line,no-multi-spaces */
6580
6581 return [r * 255, g * 255, b * 255];
6582};
6583
6584convert$1.cmyk.rgb = function (cmyk) {
6585 const c = cmyk[0] / 100;
6586 const m = cmyk[1] / 100;
6587 const y = cmyk[2] / 100;
6588 const k = cmyk[3] / 100;
6589
6590 const r = 1 - Math.min(1, c * (1 - k) + k);
6591 const g = 1 - Math.min(1, m * (1 - k) + k);
6592 const b = 1 - Math.min(1, y * (1 - k) + k);
6593
6594 return [r * 255, g * 255, b * 255];
6595};
6596
6597convert$1.xyz.rgb = function (xyz) {
6598 const x = xyz[0] / 100;
6599 const y = xyz[1] / 100;
6600 const z = xyz[2] / 100;
6601 let r;
6602 let g;
6603 let b;
6604
6605 r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
6606 g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
6607 b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
6608
6609 // Assume sRGB
6610 r = r > 0.0031308
6611 ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
6612 : r * 12.92;
6613
6614 g = g > 0.0031308
6615 ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
6616 : g * 12.92;
6617
6618 b = b > 0.0031308
6619 ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
6620 : b * 12.92;
6621
6622 r = Math.min(Math.max(0, r), 1);
6623 g = Math.min(Math.max(0, g), 1);
6624 b = Math.min(Math.max(0, b), 1);
6625
6626 return [r * 255, g * 255, b * 255];
6627};
6628
6629convert$1.xyz.lab = function (xyz) {
6630 let x = xyz[0];
6631 let y = xyz[1];
6632 let z = xyz[2];
6633
6634 x /= 95.047;
6635 y /= 100;
6636 z /= 108.883;
6637
6638 x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
6639 y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
6640 z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
6641
6642 const l = (116 * y) - 16;
6643 const a = 500 * (x - y);
6644 const b = 200 * (y - z);
6645
6646 return [l, a, b];
6647};
6648
6649convert$1.lab.xyz = function (lab) {
6650 const l = lab[0];
6651 const a = lab[1];
6652 const b = lab[2];
6653 let x;
6654 let y;
6655 let z;
6656
6657 y = (l + 16) / 116;
6658 x = a / 500 + y;
6659 z = y - b / 200;
6660
6661 const y2 = y ** 3;
6662 const x2 = x ** 3;
6663 const z2 = z ** 3;
6664 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
6665 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
6666 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
6667
6668 x *= 95.047;
6669 y *= 100;
6670 z *= 108.883;
6671
6672 return [x, y, z];
6673};
6674
6675convert$1.lab.lch = function (lab) {
6676 const l = lab[0];
6677 const a = lab[1];
6678 const b = lab[2];
6679 let h;
6680
6681 const hr = Math.atan2(b, a);
6682 h = hr * 360 / 2 / Math.PI;
6683
6684 if (h < 0) {
6685 h += 360;
6686 }
6687
6688 const c = Math.sqrt(a * a + b * b);
6689
6690 return [l, c, h];
6691};
6692
6693convert$1.lch.lab = function (lch) {
6694 const l = lch[0];
6695 const c = lch[1];
6696 const h = lch[2];
6697
6698 const hr = h / 360 * 2 * Math.PI;
6699 const a = c * Math.cos(hr);
6700 const b = c * Math.sin(hr);
6701
6702 return [l, a, b];
6703};
6704
6705convert$1.rgb.ansi16 = function (args, saturation = null) {
6706 const [r, g, b] = args;
6707 let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
6708
6709 value = Math.round(value / 50);
6710
6711 if (value === 0) {
6712 return 30;
6713 }
6714
6715 let ansi = 30
6716 + ((Math.round(b / 255) << 2)
6717 | (Math.round(g / 255) << 1)
6718 | Math.round(r / 255));
6719
6720 if (value === 2) {
6721 ansi += 60;
6722 }
6723
6724 return ansi;
6725};
6726
6727convert$1.hsv.ansi16 = function (args) {
6728 // Optimization here; we already know the value and don't need to get
6729 // it converted for us.
6730 return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
6731};
6732
6733convert$1.rgb.ansi256 = function (args) {
6734 const r = args[0];
6735 const g = args[1];
6736 const b = args[2];
6737
6738 // We use the extended greyscale palette here, with the exception of
6739 // black and white. normal palette only has 4 greyscale shades.
6740 if (r === g && g === b) {
6741 if (r < 8) {
6742 return 16;
6743 }
6744
6745 if (r > 248) {
6746 return 231;
6747 }
6748
6749 return Math.round(((r - 8) / 247) * 24) + 232;
6750 }
6751
6752 const ansi = 16
6753 + (36 * Math.round(r / 255 * 5))
6754 + (6 * Math.round(g / 255 * 5))
6755 + Math.round(b / 255 * 5);
6756
6757 return ansi;
6758};
6759
6760convert$1.ansi16.rgb = function (args) {
6761 let color = args % 10;
6762
6763 // Handle greyscale
6764 if (color === 0 || color === 7) {
6765 if (args > 50) {
6766 color += 3.5;
6767 }
6768
6769 color = color / 10.5 * 255;
6770
6771 return [color, color, color];
6772 }
6773
6774 const mult = (~~(args > 50) + 1) * 0.5;
6775 const r = ((color & 1) * mult) * 255;
6776 const g = (((color >> 1) & 1) * mult) * 255;
6777 const b = (((color >> 2) & 1) * mult) * 255;
6778
6779 return [r, g, b];
6780};
6781
6782convert$1.ansi256.rgb = function (args) {
6783 // Handle greyscale
6784 if (args >= 232) {
6785 const c = (args - 232) * 10 + 8;
6786 return [c, c, c];
6787 }
6788
6789 args -= 16;
6790
6791 let rem;
6792 const r = Math.floor(args / 36) / 5 * 255;
6793 const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
6794 const b = (rem % 6) / 5 * 255;
6795
6796 return [r, g, b];
6797};
6798
6799convert$1.rgb.hex = function (args) {
6800 const integer = ((Math.round(args[0]) & 0xFF) << 16)
6801 + ((Math.round(args[1]) & 0xFF) << 8)
6802 + (Math.round(args[2]) & 0xFF);
6803
6804 const string = integer.toString(16).toUpperCase();
6805 return '000000'.substring(string.length) + string;
6806};
6807
6808convert$1.hex.rgb = function (args) {
6809 const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
6810 if (!match) {
6811 return [0, 0, 0];
6812 }
6813
6814 let colorString = match[0];
6815
6816 if (match[0].length === 3) {
6817 colorString = colorString.split('').map(char => {
6818 return char + char;
6819 }).join('');
6820 }
6821
6822 const integer = parseInt(colorString, 16);
6823 const r = (integer >> 16) & 0xFF;
6824 const g = (integer >> 8) & 0xFF;
6825 const b = integer & 0xFF;
6826
6827 return [r, g, b];
6828};
6829
6830convert$1.rgb.hcg = function (rgb) {
6831 const r = rgb[0] / 255;
6832 const g = rgb[1] / 255;
6833 const b = rgb[2] / 255;
6834 const max = Math.max(Math.max(r, g), b);
6835 const min = Math.min(Math.min(r, g), b);
6836 const chroma = (max - min);
6837 let grayscale;
6838 let hue;
6839
6840 if (chroma < 1) {
6841 grayscale = min / (1 - chroma);
6842 } else {
6843 grayscale = 0;
6844 }
6845
6846 if (chroma <= 0) {
6847 hue = 0;
6848 } else
6849 if (max === r) {
6850 hue = ((g - b) / chroma) % 6;
6851 } else
6852 if (max === g) {
6853 hue = 2 + (b - r) / chroma;
6854 } else {
6855 hue = 4 + (r - g) / chroma;
6856 }
6857
6858 hue /= 6;
6859 hue %= 1;
6860
6861 return [hue * 360, chroma * 100, grayscale * 100];
6862};
6863
6864convert$1.hsl.hcg = function (hsl) {
6865 const s = hsl[1] / 100;
6866 const l = hsl[2] / 100;
6867
6868 const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
6869
6870 let f = 0;
6871 if (c < 1.0) {
6872 f = (l - 0.5 * c) / (1.0 - c);
6873 }
6874
6875 return [hsl[0], c * 100, f * 100];
6876};
6877
6878convert$1.hsv.hcg = function (hsv) {
6879 const s = hsv[1] / 100;
6880 const v = hsv[2] / 100;
6881
6882 const c = s * v;
6883 let f = 0;
6884
6885 if (c < 1.0) {
6886 f = (v - c) / (1 - c);
6887 }
6888
6889 return [hsv[0], c * 100, f * 100];
6890};
6891
6892convert$1.hcg.rgb = function (hcg) {
6893 const h = hcg[0] / 360;
6894 const c = hcg[1] / 100;
6895 const g = hcg[2] / 100;
6896
6897 if (c === 0.0) {
6898 return [g * 255, g * 255, g * 255];
6899 }
6900
6901 const pure = [0, 0, 0];
6902 const hi = (h % 1) * 6;
6903 const v = hi % 1;
6904 const w = 1 - v;
6905 let mg = 0;
6906
6907 /* eslint-disable max-statements-per-line */
6908 switch (Math.floor(hi)) {
6909 case 0:
6910 pure[0] = 1; pure[1] = v; pure[2] = 0; break;
6911 case 1:
6912 pure[0] = w; pure[1] = 1; pure[2] = 0; break;
6913 case 2:
6914 pure[0] = 0; pure[1] = 1; pure[2] = v; break;
6915 case 3:
6916 pure[0] = 0; pure[1] = w; pure[2] = 1; break;
6917 case 4:
6918 pure[0] = v; pure[1] = 0; pure[2] = 1; break;
6919 default:
6920 pure[0] = 1; pure[1] = 0; pure[2] = w;
6921 }
6922 /* eslint-enable max-statements-per-line */
6923
6924 mg = (1.0 - c) * g;
6925
6926 return [
6927 (c * pure[0] + mg) * 255,
6928 (c * pure[1] + mg) * 255,
6929 (c * pure[2] + mg) * 255
6930 ];
6931};
6932
6933convert$1.hcg.hsv = function (hcg) {
6934 const c = hcg[1] / 100;
6935 const g = hcg[2] / 100;
6936
6937 const v = c + g * (1.0 - c);
6938 let f = 0;
6939
6940 if (v > 0.0) {
6941 f = c / v;
6942 }
6943
6944 return [hcg[0], f * 100, v * 100];
6945};
6946
6947convert$1.hcg.hsl = function (hcg) {
6948 const c = hcg[1] / 100;
6949 const g = hcg[2] / 100;
6950
6951 const l = g * (1.0 - c) + 0.5 * c;
6952 let s = 0;
6953
6954 if (l > 0.0 && l < 0.5) {
6955 s = c / (2 * l);
6956 } else
6957 if (l >= 0.5 && l < 1.0) {
6958 s = c / (2 * (1 - l));
6959 }
6960
6961 return [hcg[0], s * 100, l * 100];
6962};
6963
6964convert$1.hcg.hwb = function (hcg) {
6965 const c = hcg[1] / 100;
6966 const g = hcg[2] / 100;
6967 const v = c + g * (1.0 - c);
6968 return [hcg[0], (v - c) * 100, (1 - v) * 100];
6969};
6970
6971convert$1.hwb.hcg = function (hwb) {
6972 const w = hwb[1] / 100;
6973 const b = hwb[2] / 100;
6974 const v = 1 - b;
6975 const c = v - w;
6976 let g = 0;
6977
6978 if (c < 1) {
6979 g = (v - c) / (1 - c);
6980 }
6981
6982 return [hwb[0], c * 100, g * 100];
6983};
6984
6985convert$1.apple.rgb = function (apple) {
6986 return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
6987};
6988
6989convert$1.rgb.apple = function (rgb) {
6990 return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
6991};
6992
6993convert$1.gray.rgb = function (args) {
6994 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
6995};
6996
6997convert$1.gray.hsl = function (args) {
6998 return [0, 0, args[0]];
6999};
7000
7001convert$1.gray.hsv = convert$1.gray.hsl;
7002
7003convert$1.gray.hwb = function (gray) {
7004 return [0, 100, gray[0]];
7005};
7006
7007convert$1.gray.cmyk = function (gray) {
7008 return [0, 0, 0, gray[0]];
7009};
7010
7011convert$1.gray.lab = function (gray) {
7012 return [gray[0], 0, 0];
7013};
7014
7015convert$1.gray.hex = function (gray) {
7016 const val = Math.round(gray[0] / 100 * 255) & 0xFF;
7017 const integer = (val << 16) + (val << 8) + val;
7018
7019 const string = integer.toString(16).toUpperCase();
7020 return '000000'.substring(string.length) + string;
7021};
7022
7023convert$1.rgb.gray = function (rgb) {
7024 const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
7025 return [val / 255 * 100];
7026};
7027
7028/*
7029 This function routes a model to all other models.
7030
7031 all functions that are routed have a property `.conversion` attached
7032 to the returned synthetic function. This property is an array
7033 of strings, each with the steps in between the 'from' and 'to'
7034 color models (inclusive).
7035
7036 conversions that are not possible simply are not included.
7037*/
7038
7039function buildGraph() {
7040 const graph = {};
7041 // https://jsperf.com/object-keys-vs-for-in-with-closure/3
7042 const models = Object.keys(conversions);
7043
7044 for (let len = models.length, i = 0; i < len; i++) {
7045 graph[models[i]] = {
7046 // http://jsperf.com/1-vs-infinity
7047 // micro-opt, but this is simple.
7048 distance: -1,
7049 parent: null
7050 };
7051 }
7052
7053 return graph;
7054}
7055
7056// https://en.wikipedia.org/wiki/Breadth-first_search
7057function deriveBFS(fromModel) {
7058 const graph = buildGraph();
7059 const queue = [fromModel]; // Unshift -> queue -> pop
7060
7061 graph[fromModel].distance = 0;
7062
7063 while (queue.length) {
7064 const current = queue.pop();
7065 const adjacents = Object.keys(conversions[current]);
7066
7067 for (let len = adjacents.length, i = 0; i < len; i++) {
7068 const adjacent = adjacents[i];
7069 const node = graph[adjacent];
7070
7071 if (node.distance === -1) {
7072 node.distance = graph[current].distance + 1;
7073 node.parent = current;
7074 queue.unshift(adjacent);
7075 }
7076 }
7077 }
7078
7079 return graph;
7080}
7081
7082function link(from, to) {
7083 return function (args) {
7084 return to(from(args));
7085 };
7086}
7087
7088function wrapConversion(toModel, graph) {
7089 const path = [graph[toModel].parent, toModel];
7090 let fn = conversions[graph[toModel].parent][toModel];
7091
7092 let cur = graph[toModel].parent;
7093 while (graph[cur].parent) {
7094 path.unshift(graph[cur].parent);
7095 fn = link(conversions[graph[cur].parent][cur], fn);
7096 cur = graph[cur].parent;
7097 }
7098
7099 fn.conversion = path;
7100 return fn;
7101}
7102
7103var route = function (fromModel) {
7104 const graph = deriveBFS(fromModel);
7105 const conversion = {};
7106
7107 const models = Object.keys(graph);
7108 for (let len = models.length, i = 0; i < len; i++) {
7109 const toModel = models[i];
7110 const node = graph[toModel];
7111
7112 if (node.parent === null) {
7113 // No possible conversion, or this node is the source model.
7114 continue;
7115 }
7116
7117 conversion[toModel] = wrapConversion(toModel, graph);
7118 }
7119
7120 return conversion;
7121};
7122
7123const convert = {};
7124
7125const models = Object.keys(conversions);
7126
7127function wrapRaw(fn) {
7128 const wrappedFn = function (...args) {
7129 const arg0 = args[0];
7130 if (arg0 === undefined || arg0 === null) {
7131 return arg0;
7132 }
7133
7134 if (arg0.length > 1) {
7135 args = arg0;
7136 }
7137
7138 return fn(args);
7139 };
7140
7141 // Preserve .conversion property if there is one
7142 if ('conversion' in fn) {
7143 wrappedFn.conversion = fn.conversion;
7144 }
7145
7146 return wrappedFn;
7147}
7148
7149function wrapRounded(fn) {
7150 const wrappedFn = function (...args) {
7151 const arg0 = args[0];
7152
7153 if (arg0 === undefined || arg0 === null) {
7154 return arg0;
7155 }
7156
7157 if (arg0.length > 1) {
7158 args = arg0;
7159 }
7160
7161 const result = fn(args);
7162
7163 // We're assuming the result is an array here.
7164 // see notice in conversions.js; don't use box types
7165 // in conversion functions.
7166 if (typeof result === 'object') {
7167 for (let len = result.length, i = 0; i < len; i++) {
7168 result[i] = Math.round(result[i]);
7169 }
7170 }
7171
7172 return result;
7173 };
7174
7175 // Preserve .conversion property if there is one
7176 if ('conversion' in fn) {
7177 wrappedFn.conversion = fn.conversion;
7178 }
7179
7180 return wrappedFn;
7181}
7182
7183models.forEach(fromModel => {
7184 convert[fromModel] = {};
7185
7186 Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
7187 Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
7188
7189 const routes = route(fromModel);
7190 const routeModels = Object.keys(routes);
7191
7192 routeModels.forEach(toModel => {
7193 const fn = routes[toModel];
7194
7195 convert[fromModel][toModel] = wrapRounded(fn);
7196 convert[fromModel][toModel].raw = wrapRaw(fn);
7197 });
7198});
7199
7200var colorConvert = convert;
7201
7202var ansiStyles = createCommonjsModule(function (module) {
7203
7204const wrapAnsi16 = (fn, offset) => (...args) => {
7205 const code = fn(...args);
7206 return `\u001B[${code + offset}m`;
7207};
7208
7209const wrapAnsi256 = (fn, offset) => (...args) => {
7210 const code = fn(...args);
7211 return `\u001B[${38 + offset};5;${code}m`;
7212};
7213
7214const wrapAnsi16m = (fn, offset) => (...args) => {
7215 const rgb = fn(...args);
7216 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
7217};
7218
7219const ansi2ansi = n => n;
7220const rgb2rgb = (r, g, b) => [r, g, b];
7221
7222const setLazyProperty = (object, property, get) => {
7223 Object.defineProperty(object, property, {
7224 get: () => {
7225 const value = get();
7226
7227 Object.defineProperty(object, property, {
7228 value,
7229 enumerable: true,
7230 configurable: true
7231 });
7232
7233 return value;
7234 },
7235 enumerable: true,
7236 configurable: true
7237 });
7238};
7239
7240/** @type {typeof import('color-convert')} */
7241let colorConvert$1;
7242const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
7243 if (colorConvert$1 === undefined) {
7244 colorConvert$1 = colorConvert;
7245 }
7246
7247 const offset = isBackground ? 10 : 0;
7248 const styles = {};
7249
7250 for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) {
7251 const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
7252 if (sourceSpace === targetSpace) {
7253 styles[name] = wrap(identity, offset);
7254 } else if (typeof suite === 'object') {
7255 styles[name] = wrap(suite[targetSpace], offset);
7256 }
7257 }
7258
7259 return styles;
7260};
7261
7262function assembleStyles() {
7263 const codes = new Map();
7264 const styles = {
7265 modifier: {
7266 reset: [0, 0],
7267 // 21 isn't widely supported and 22 does the same thing
7268 bold: [1, 22],
7269 dim: [2, 22],
7270 italic: [3, 23],
7271 underline: [4, 24],
7272 inverse: [7, 27],
7273 hidden: [8, 28],
7274 strikethrough: [9, 29]
7275 },
7276 color: {
7277 black: [30, 39],
7278 red: [31, 39],
7279 green: [32, 39],
7280 yellow: [33, 39],
7281 blue: [34, 39],
7282 magenta: [35, 39],
7283 cyan: [36, 39],
7284 white: [37, 39],
7285
7286 // Bright color
7287 blackBright: [90, 39],
7288 redBright: [91, 39],
7289 greenBright: [92, 39],
7290 yellowBright: [93, 39],
7291 blueBright: [94, 39],
7292 magentaBright: [95, 39],
7293 cyanBright: [96, 39],
7294 whiteBright: [97, 39]
7295 },
7296 bgColor: {
7297 bgBlack: [40, 49],
7298 bgRed: [41, 49],
7299 bgGreen: [42, 49],
7300 bgYellow: [43, 49],
7301 bgBlue: [44, 49],
7302 bgMagenta: [45, 49],
7303 bgCyan: [46, 49],
7304 bgWhite: [47, 49],
7305
7306 // Bright color
7307 bgBlackBright: [100, 49],
7308 bgRedBright: [101, 49],
7309 bgGreenBright: [102, 49],
7310 bgYellowBright: [103, 49],
7311 bgBlueBright: [104, 49],
7312 bgMagentaBright: [105, 49],
7313 bgCyanBright: [106, 49],
7314 bgWhiteBright: [107, 49]
7315 }
7316 };
7317
7318 // Alias bright black as gray (and grey)
7319 styles.color.gray = styles.color.blackBright;
7320 styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
7321 styles.color.grey = styles.color.blackBright;
7322 styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
7323
7324 for (const [groupName, group] of Object.entries(styles)) {
7325 for (const [styleName, style] of Object.entries(group)) {
7326 styles[styleName] = {
7327 open: `\u001B[${style[0]}m`,
7328 close: `\u001B[${style[1]}m`
7329 };
7330
7331 group[styleName] = styles[styleName];
7332
7333 codes.set(style[0], style[1]);
7334 }
7335
7336 Object.defineProperty(styles, groupName, {
7337 value: group,
7338 enumerable: false
7339 });
7340 }
7341
7342 Object.defineProperty(styles, 'codes', {
7343 value: codes,
7344 enumerable: false
7345 });
7346
7347 styles.color.close = '\u001B[39m';
7348 styles.bgColor.close = '\u001B[49m';
7349
7350 setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
7351 setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
7352 setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
7353 setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
7354 setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
7355 setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
7356
7357 return styles;
7358}
7359
7360// Make the export immutable
7361Object.defineProperty(module, 'exports', {
7362 enumerable: true,
7363 get: assembleStyles
7364});
7365});
7366
7367var hasFlag = (flag, argv = process.argv) => {
7368 const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
7369 const position = argv.indexOf(prefix + flag);
7370 const terminatorPosition = argv.indexOf('--');
7371 return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
7372};
7373
7374const {env} = process;
7375
7376let forceColor;
7377if (hasFlag('no-color') ||
7378 hasFlag('no-colors') ||
7379 hasFlag('color=false') ||
7380 hasFlag('color=never')) {
7381 forceColor = 0;
7382} else if (hasFlag('color') ||
7383 hasFlag('colors') ||
7384 hasFlag('color=true') ||
7385 hasFlag('color=always')) {
7386 forceColor = 1;
7387}
7388
7389if ('FORCE_COLOR' in env) {
7390 if (env.FORCE_COLOR === 'true') {
7391 forceColor = 1;
7392 } else if (env.FORCE_COLOR === 'false') {
7393 forceColor = 0;
7394 } else {
7395 forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
7396 }
7397}
7398
7399function translateLevel(level) {
7400 if (level === 0) {
7401 return false;
7402 }
7403
7404 return {
7405 level,
7406 hasBasic: true,
7407 has256: level >= 2,
7408 has16m: level >= 3
7409 };
7410}
7411
7412function supportsColor(haveStream, streamIsTTY) {
7413 if (forceColor === 0) {
7414 return 0;
7415 }
7416
7417 if (hasFlag('color=16m') ||
7418 hasFlag('color=full') ||
7419 hasFlag('color=truecolor')) {
7420 return 3;
7421 }
7422
7423 if (hasFlag('color=256')) {
7424 return 2;
7425 }
7426
7427 if (haveStream && !streamIsTTY && forceColor === undefined) {
7428 return 0;
7429 }
7430
7431 const min = forceColor || 0;
7432
7433 if (env.TERM === 'dumb') {
7434 return min;
7435 }
7436
7437 if (process.platform === 'win32') {
7438 // Windows 10 build 10586 is the first Windows release that supports 256 colors.
7439 // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
7440 const osRelease = os__default['default'].release().split('.');
7441 if (
7442 Number(osRelease[0]) >= 10 &&
7443 Number(osRelease[2]) >= 10586
7444 ) {
7445 return Number(osRelease[2]) >= 14931 ? 3 : 2;
7446 }
7447
7448 return 1;
7449 }
7450
7451 if ('CI' in env) {
7452 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
7453 return 1;
7454 }
7455
7456 return min;
7457 }
7458
7459 if ('TEAMCITY_VERSION' in env) {
7460 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
7461 }
7462
7463 if (env.COLORTERM === 'truecolor') {
7464 return 3;
7465 }
7466
7467 if ('TERM_PROGRAM' in env) {
7468 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
7469
7470 switch (env.TERM_PROGRAM) {
7471 case 'iTerm.app':
7472 return version >= 3 ? 3 : 2;
7473 case 'Apple_Terminal':
7474 return 2;
7475 // No default
7476 }
7477 }
7478
7479 if (/-256(color)?$/i.test(env.TERM)) {
7480 return 2;
7481 }
7482
7483 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
7484 return 1;
7485 }
7486
7487 if ('COLORTERM' in env) {
7488 return 1;
7489 }
7490
7491 return min;
7492}
7493
7494function getSupportLevel(stream) {
7495 const level = supportsColor(stream, stream && stream.isTTY);
7496 return translateLevel(level);
7497}
7498
7499var supportsColor_1 = {
7500 supportsColor: getSupportLevel,
7501 stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))),
7502 stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2)))
7503};
7504
7505const stringReplaceAll$1 = (string, substring, replacer) => {
7506 let index = string.indexOf(substring);
7507 if (index === -1) {
7508 return string;
7509 }
7510
7511 const substringLength = substring.length;
7512 let endIndex = 0;
7513 let returnValue = '';
7514 do {
7515 returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
7516 endIndex = index + substringLength;
7517 index = string.indexOf(substring, endIndex);
7518 } while (index !== -1);
7519
7520 returnValue += string.substr(endIndex);
7521 return returnValue;
7522};
7523
7524const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
7525 let endIndex = 0;
7526 let returnValue = '';
7527 do {
7528 const gotCR = string[index - 1] === '\r';
7529 returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
7530 endIndex = index + 1;
7531 index = string.indexOf('\n', endIndex);
7532 } while (index !== -1);
7533
7534 returnValue += string.substr(endIndex);
7535 return returnValue;
7536};
7537
7538var util = {
7539 stringReplaceAll: stringReplaceAll$1,
7540 stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
7541};
7542
7543const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
7544const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
7545const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
7546const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
7547
7548const ESCAPES = new Map([
7549 ['n', '\n'],
7550 ['r', '\r'],
7551 ['t', '\t'],
7552 ['b', '\b'],
7553 ['f', '\f'],
7554 ['v', '\v'],
7555 ['0', '\0'],
7556 ['\\', '\\'],
7557 ['e', '\u001B'],
7558 ['a', '\u0007']
7559]);
7560
7561function unescape(c) {
7562 const u = c[0] === 'u';
7563 const bracket = c[1] === '{';
7564
7565 if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
7566 return String.fromCharCode(parseInt(c.slice(1), 16));
7567 }
7568
7569 if (u && bracket) {
7570 return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
7571 }
7572
7573 return ESCAPES.get(c) || c;
7574}
7575
7576function parseArguments(name, arguments_) {
7577 const results = [];
7578 const chunks = arguments_.trim().split(/\s*,\s*/g);
7579 let matches;
7580
7581 for (const chunk of chunks) {
7582 const number = Number(chunk);
7583 if (!Number.isNaN(number)) {
7584 results.push(number);
7585 } else if ((matches = chunk.match(STRING_REGEX))) {
7586 results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
7587 } else {
7588 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
7589 }
7590 }
7591
7592 return results;
7593}
7594
7595function parseStyle(style) {
7596 STYLE_REGEX.lastIndex = 0;
7597
7598 const results = [];
7599 let matches;
7600
7601 while ((matches = STYLE_REGEX.exec(style)) !== null) {
7602 const name = matches[1];
7603
7604 if (matches[2]) {
7605 const args = parseArguments(name, matches[2]);
7606 results.push([name].concat(args));
7607 } else {
7608 results.push([name]);
7609 }
7610 }
7611
7612 return results;
7613}
7614
7615function buildStyle(chalk, styles) {
7616 const enabled = {};
7617
7618 for (const layer of styles) {
7619 for (const style of layer.styles) {
7620 enabled[style[0]] = layer.inverse ? null : style.slice(1);
7621 }
7622 }
7623
7624 let current = chalk;
7625 for (const [styleName, styles] of Object.entries(enabled)) {
7626 if (!Array.isArray(styles)) {
7627 continue;
7628 }
7629
7630 if (!(styleName in current)) {
7631 throw new Error(`Unknown Chalk style: ${styleName}`);
7632 }
7633
7634 current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
7635 }
7636
7637 return current;
7638}
7639
7640var templates = (chalk, temporary) => {
7641 const styles = [];
7642 const chunks = [];
7643 let chunk = [];
7644
7645 // eslint-disable-next-line max-params
7646 temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
7647 if (escapeCharacter) {
7648 chunk.push(unescape(escapeCharacter));
7649 } else if (style) {
7650 const string = chunk.join('');
7651 chunk = [];
7652 chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
7653 styles.push({inverse, styles: parseStyle(style)});
7654 } else if (close) {
7655 if (styles.length === 0) {
7656 throw new Error('Found extraneous } in Chalk template literal');
7657 }
7658
7659 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
7660 chunk = [];
7661 styles.pop();
7662 } else {
7663 chunk.push(character);
7664 }
7665 });
7666
7667 chunks.push(chunk.join(''));
7668
7669 if (styles.length > 0) {
7670 const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
7671 throw new Error(errMessage);
7672 }
7673
7674 return chunks.join('');
7675};
7676
7677const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1;
7678const {
7679 stringReplaceAll,
7680 stringEncaseCRLFWithFirstIndex
7681} = util;
7682
7683const {isArray: isArray$1} = Array;
7684
7685// `supportsColor.level` → `ansiStyles.color[name]` mapping
7686const levelMapping = [
7687 'ansi',
7688 'ansi',
7689 'ansi256',
7690 'ansi16m'
7691];
7692
7693const styles = Object.create(null);
7694
7695const applyOptions = (object, options = {}) => {
7696 if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
7697 throw new Error('The `level` option should be an integer from 0 to 3');
7698 }
7699
7700 // Detect level if not set manually
7701 const colorLevel = stdoutColor ? stdoutColor.level : 0;
7702 object.level = options.level === undefined ? colorLevel : options.level;
7703};
7704
7705class ChalkClass {
7706 constructor(options) {
7707 // eslint-disable-next-line no-constructor-return
7708 return chalkFactory(options);
7709 }
7710}
7711
7712const chalkFactory = options => {
7713 const chalk = {};
7714 applyOptions(chalk, options);
7715
7716 chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
7717
7718 Object.setPrototypeOf(chalk, Chalk.prototype);
7719 Object.setPrototypeOf(chalk.template, chalk);
7720
7721 chalk.template.constructor = () => {
7722 throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
7723 };
7724
7725 chalk.template.Instance = ChalkClass;
7726
7727 return chalk.template;
7728};
7729
7730function Chalk(options) {
7731 return chalkFactory(options);
7732}
7733
7734for (const [styleName, style] of Object.entries(ansiStyles)) {
7735 styles[styleName] = {
7736 get() {
7737 const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
7738 Object.defineProperty(this, styleName, {value: builder});
7739 return builder;
7740 }
7741 };
7742}
7743
7744styles.visible = {
7745 get() {
7746 const builder = createBuilder(this, this._styler, true);
7747 Object.defineProperty(this, 'visible', {value: builder});
7748 return builder;
7749 }
7750};
7751
7752const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
7753
7754for (const model of usedModels) {
7755 styles[model] = {
7756 get() {
7757 const {level} = this;
7758 return function (...arguments_) {
7759 const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
7760 return createBuilder(this, styler, this._isEmpty);
7761 };
7762 }
7763 };
7764}
7765
7766for (const model of usedModels) {
7767 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
7768 styles[bgModel] = {
7769 get() {
7770 const {level} = this;
7771 return function (...arguments_) {
7772 const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
7773 return createBuilder(this, styler, this._isEmpty);
7774 };
7775 }
7776 };
7777}
7778
7779const proto = Object.defineProperties(() => {}, {
7780 ...styles,
7781 level: {
7782 enumerable: true,
7783 get() {
7784 return this._generator.level;
7785 },
7786 set(level) {
7787 this._generator.level = level;
7788 }
7789 }
7790});
7791
7792const createStyler = (open, close, parent) => {
7793 let openAll;
7794 let closeAll;
7795 if (parent === undefined) {
7796 openAll = open;
7797 closeAll = close;
7798 } else {
7799 openAll = parent.openAll + open;
7800 closeAll = close + parent.closeAll;
7801 }
7802
7803 return {
7804 open,
7805 close,
7806 openAll,
7807 closeAll,
7808 parent
7809 };
7810};
7811
7812const createBuilder = (self, _styler, _isEmpty) => {
7813 const builder = (...arguments_) => {
7814 if (isArray$1(arguments_[0]) && isArray$1(arguments_[0].raw)) {
7815 // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
7816 return applyStyle(builder, chalkTag(builder, ...arguments_));
7817 }
7818
7819 // Single argument is hot path, implicit coercion is faster than anything
7820 // eslint-disable-next-line no-implicit-coercion
7821 return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
7822 };
7823
7824 // We alter the prototype because we must return a function, but there is
7825 // no way to create a function with a different prototype
7826 Object.setPrototypeOf(builder, proto);
7827
7828 builder._generator = self;
7829 builder._styler = _styler;
7830 builder._isEmpty = _isEmpty;
7831
7832 return builder;
7833};
7834
7835const applyStyle = (self, string) => {
7836 if (self.level <= 0 || !string) {
7837 return self._isEmpty ? '' : string;
7838 }
7839
7840 let styler = self._styler;
7841
7842 if (styler === undefined) {
7843 return string;
7844 }
7845
7846 const {openAll, closeAll} = styler;
7847 if (string.indexOf('\u001B') !== -1) {
7848 while (styler !== undefined) {
7849 // Replace any instances already present with a re-opening code
7850 // otherwise only the part of the string until said closing code
7851 // will be colored, and the rest will simply be 'plain'.
7852 string = stringReplaceAll(string, styler.close, styler.open);
7853
7854 styler = styler.parent;
7855 }
7856 }
7857
7858 // We can move both next actions out of loop, because remaining actions in loop won't have
7859 // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
7860 // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
7861 const lfIndex = string.indexOf('\n');
7862 if (lfIndex !== -1) {
7863 string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
7864 }
7865
7866 return openAll + string + closeAll;
7867};
7868
7869let template;
7870const chalkTag = (chalk, ...strings) => {
7871 const [firstString] = strings;
7872
7873 if (!isArray$1(firstString) || !isArray$1(firstString.raw)) {
7874 // If chalk() was called by itself or with a string,
7875 // return the string itself as a string.
7876 return strings.join(' ');
7877 }
7878
7879 const arguments_ = strings.slice(1);
7880 const parts = [firstString.raw[0]];
7881
7882 for (let i = 1; i < firstString.length; i++) {
7883 parts.push(
7884 String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
7885 String(firstString.raw[i])
7886 );
7887 }
7888
7889 if (template === undefined) {
7890 template = templates;
7891 }
7892
7893 return template(chalk, parts.join(''));
7894};
7895
7896Object.defineProperties(Chalk.prototype, styles);
7897
7898const chalk = Chalk(); // eslint-disable-line new-cap
7899chalk.supportsColor = stdoutColor;
7900chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
7901chalk.stderr.supportsColor = stderrColor;
7902
7903var source = chalk;
7904
7905var fs_1 = clone(fs__default['default']);
7906
7907function clone (obj) {
7908 if (obj === null || typeof obj !== 'object')
7909 return obj
7910
7911 if (obj instanceof Object)
7912 var copy = { __proto__: obj.__proto__ };
7913 else
7914 var copy = Object.create(null);
7915
7916 Object.getOwnPropertyNames(obj).forEach(function (key) {
7917 Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
7918 });
7919
7920 return copy
7921}
7922
7923var origCwd = process.cwd;
7924var cwd = null;
7925
7926var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
7927
7928process.cwd = function() {
7929 if (!cwd)
7930 cwd = origCwd.call(process);
7931 return cwd
7932};
7933try {
7934 process.cwd();
7935} catch (er) {}
7936
7937var chdir = process.chdir;
7938process.chdir = function(d) {
7939 cwd = null;
7940 chdir.call(process, d);
7941};
7942
7943var polyfills = patch;
7944
7945function patch (fs) {
7946 // (re-)implement some things that are known busted or missing.
7947
7948 // lchmod, broken prior to 0.6.2
7949 // back-port the fix here.
7950 if (constants__default['default'].hasOwnProperty('O_SYMLINK') &&
7951 process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
7952 patchLchmod(fs);
7953 }
7954
7955 // lutimes implementation, or no-op
7956 if (!fs.lutimes) {
7957 patchLutimes(fs);
7958 }
7959
7960 // https://github.com/isaacs/node-graceful-fs/issues/4
7961 // Chown should not fail on einval or eperm if non-root.
7962 // It should not fail on enosys ever, as this just indicates
7963 // that a fs doesn't support the intended operation.
7964
7965 fs.chown = chownFix(fs.chown);
7966 fs.fchown = chownFix(fs.fchown);
7967 fs.lchown = chownFix(fs.lchown);
7968
7969 fs.chmod = chmodFix(fs.chmod);
7970 fs.fchmod = chmodFix(fs.fchmod);
7971 fs.lchmod = chmodFix(fs.lchmod);
7972
7973 fs.chownSync = chownFixSync(fs.chownSync);
7974 fs.fchownSync = chownFixSync(fs.fchownSync);
7975 fs.lchownSync = chownFixSync(fs.lchownSync);
7976
7977 fs.chmodSync = chmodFixSync(fs.chmodSync);
7978 fs.fchmodSync = chmodFixSync(fs.fchmodSync);
7979 fs.lchmodSync = chmodFixSync(fs.lchmodSync);
7980
7981 fs.stat = statFix(fs.stat);
7982 fs.fstat = statFix(fs.fstat);
7983 fs.lstat = statFix(fs.lstat);
7984
7985 fs.statSync = statFixSync(fs.statSync);
7986 fs.fstatSync = statFixSync(fs.fstatSync);
7987 fs.lstatSync = statFixSync(fs.lstatSync);
7988
7989 // if lchmod/lchown do not exist, then make them no-ops
7990 if (!fs.lchmod) {
7991 fs.lchmod = function (path, mode, cb) {
7992 if (cb) process.nextTick(cb);
7993 };
7994 fs.lchmodSync = function () {};
7995 }
7996 if (!fs.lchown) {
7997 fs.lchown = function (path, uid, gid, cb) {
7998 if (cb) process.nextTick(cb);
7999 };
8000 fs.lchownSync = function () {};
8001 }
8002
8003 // on Windows, A/V software can lock the directory, causing this
8004 // to fail with an EACCES or EPERM if the directory contains newly
8005 // created files. Try again on failure, for up to 60 seconds.
8006
8007 // Set the timeout this long because some Windows Anti-Virus, such as Parity
8008 // bit9, may lock files for up to a minute, causing npm package install
8009 // failures. Also, take care to yield the scheduler. Windows scheduling gives
8010 // CPU to a busy looping process, which can cause the program causing the lock
8011 // contention to be starved of CPU by node, so the contention doesn't resolve.
8012 if (platform === "win32") {
8013 fs.rename = (function (fs$rename) { return function (from, to, cb) {
8014 var start = Date.now();
8015 var backoff = 0;
8016 fs$rename(from, to, function CB (er) {
8017 if (er
8018 && (er.code === "EACCES" || er.code === "EPERM")
8019 && Date.now() - start < 60000) {
8020 setTimeout(function() {
8021 fs.stat(to, function (stater, st) {
8022 if (stater && stater.code === "ENOENT")
8023 fs$rename(from, to, CB);
8024 else
8025 cb(er);
8026 });
8027 }, backoff);
8028 if (backoff < 100)
8029 backoff += 10;
8030 return;
8031 }
8032 if (cb) cb(er);
8033 });
8034 }})(fs.rename);
8035 }
8036
8037 // if read() returns EAGAIN, then just try it again.
8038 fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) {
8039 var callback;
8040 if (callback_ && typeof callback_ === 'function') {
8041 var eagCounter = 0;
8042 callback = function (er, _, __) {
8043 if (er && er.code === 'EAGAIN' && eagCounter < 10) {
8044 eagCounter ++;
8045 return fs$read.call(fs, fd, buffer, offset, length, position, callback)
8046 }
8047 callback_.apply(this, arguments);
8048 };
8049 }
8050 return fs$read.call(fs, fd, buffer, offset, length, position, callback)
8051 }})(fs.read);
8052
8053 fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
8054 var eagCounter = 0;
8055 while (true) {
8056 try {
8057 return fs$readSync.call(fs, fd, buffer, offset, length, position)
8058 } catch (er) {
8059 if (er.code === 'EAGAIN' && eagCounter < 10) {
8060 eagCounter ++;
8061 continue
8062 }
8063 throw er
8064 }
8065 }
8066 }})(fs.readSync);
8067}
8068
8069function patchLchmod (fs) {
8070 fs.lchmod = function (path, mode, callback) {
8071 fs.open( path
8072 , constants__default['default'].O_WRONLY | constants__default['default'].O_SYMLINK
8073 , mode
8074 , function (err, fd) {
8075 if (err) {
8076 if (callback) callback(err);
8077 return
8078 }
8079 // prefer to return the chmod error, if one occurs,
8080 // but still try to close, and report closing errors if they occur.
8081 fs.fchmod(fd, mode, function (err) {
8082 fs.close(fd, function(err2) {
8083 if (callback) callback(err || err2);
8084 });
8085 });
8086 });
8087 };
8088
8089 fs.lchmodSync = function (path, mode) {
8090 var fd = fs.openSync(path, constants__default['default'].O_WRONLY | constants__default['default'].O_SYMLINK, mode);
8091
8092 // prefer to return the chmod error, if one occurs,
8093 // but still try to close, and report closing errors if they occur.
8094 var threw = true;
8095 var ret;
8096 try {
8097 ret = fs.fchmodSync(fd, mode);
8098 threw = false;
8099 } finally {
8100 if (threw) {
8101 try {
8102 fs.closeSync(fd);
8103 } catch (er) {}
8104 } else {
8105 fs.closeSync(fd);
8106 }
8107 }
8108 return ret
8109 };
8110}
8111
8112function patchLutimes (fs) {
8113 if (constants__default['default'].hasOwnProperty("O_SYMLINK")) {
8114 fs.lutimes = function (path, at, mt, cb) {
8115 fs.open(path, constants__default['default'].O_SYMLINK, function (er, fd) {
8116 if (er) {
8117 if (cb) cb(er);
8118 return
8119 }
8120 fs.futimes(fd, at, mt, function (er) {
8121 fs.close(fd, function (er2) {
8122 if (cb) cb(er || er2);
8123 });
8124 });
8125 });
8126 };
8127
8128 fs.lutimesSync = function (path, at, mt) {
8129 var fd = fs.openSync(path, constants__default['default'].O_SYMLINK);
8130 var ret;
8131 var threw = true;
8132 try {
8133 ret = fs.futimesSync(fd, at, mt);
8134 threw = false;
8135 } finally {
8136 if (threw) {
8137 try {
8138 fs.closeSync(fd);
8139 } catch (er) {}
8140 } else {
8141 fs.closeSync(fd);
8142 }
8143 }
8144 return ret
8145 };
8146
8147 } else {
8148 fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); };
8149 fs.lutimesSync = function () {};
8150 }
8151}
8152
8153function chmodFix (orig) {
8154 if (!orig) return orig
8155 return function (target, mode, cb) {
8156 return orig.call(fs_1, target, mode, function (er) {
8157 if (chownErOk(er)) er = null;
8158 if (cb) cb.apply(this, arguments);
8159 })
8160 }
8161}
8162
8163function chmodFixSync (orig) {
8164 if (!orig) return orig
8165 return function (target, mode) {
8166 try {
8167 return orig.call(fs_1, target, mode)
8168 } catch (er) {
8169 if (!chownErOk(er)) throw er
8170 }
8171 }
8172}
8173
8174
8175function chownFix (orig) {
8176 if (!orig) return orig
8177 return function (target, uid, gid, cb) {
8178 return orig.call(fs_1, target, uid, gid, function (er) {
8179 if (chownErOk(er)) er = null;
8180 if (cb) cb.apply(this, arguments);
8181 })
8182 }
8183}
8184
8185function chownFixSync (orig) {
8186 if (!orig) return orig
8187 return function (target, uid, gid) {
8188 try {
8189 return orig.call(fs_1, target, uid, gid)
8190 } catch (er) {
8191 if (!chownErOk(er)) throw er
8192 }
8193 }
8194}
8195
8196
8197function statFix (orig) {
8198 if (!orig) return orig
8199 // Older versions of Node erroneously returned signed integers for
8200 // uid + gid.
8201 return function (target, cb) {
8202 return orig.call(fs_1, target, function (er, stats) {
8203 if (!stats) return cb.apply(this, arguments)
8204 if (stats.uid < 0) stats.uid += 0x100000000;
8205 if (stats.gid < 0) stats.gid += 0x100000000;
8206 if (cb) cb.apply(this, arguments);
8207 })
8208 }
8209}
8210
8211function statFixSync (orig) {
8212 if (!orig) return orig
8213 // Older versions of Node erroneously returned signed integers for
8214 // uid + gid.
8215 return function (target) {
8216 var stats = orig.call(fs_1, target);
8217 if (stats.uid < 0) stats.uid += 0x100000000;
8218 if (stats.gid < 0) stats.gid += 0x100000000;
8219 return stats;
8220 }
8221}
8222
8223// ENOSYS means that the fs doesn't support the op. Just ignore
8224// that, because it doesn't matter.
8225//
8226// if there's no getuid, or if getuid() is something other
8227// than 0, and the error is EINVAL or EPERM, then just ignore
8228// it.
8229//
8230// This specific case is a silent failure in cp, install, tar,
8231// and most other unix tools that manage permissions.
8232//
8233// When running as root, or if other types of errors are
8234// encountered, then it's strict.
8235function chownErOk (er) {
8236 if (!er)
8237 return true
8238
8239 if (er.code === "ENOSYS")
8240 return true
8241
8242 var nonroot = !process.getuid || process.getuid() !== 0;
8243 if (nonroot) {
8244 if (er.code === "EINVAL" || er.code === "EPERM")
8245 return true
8246 }
8247
8248 return false
8249}
8250
8251var Stream = Stream__default['default'].Stream;
8252
8253var legacyStreams = legacy;
8254
8255function legacy (fs) {
8256 return {
8257 ReadStream: ReadStream,
8258 WriteStream: WriteStream
8259 }
8260
8261 function ReadStream (path, options) {
8262 if (!(this instanceof ReadStream)) return new ReadStream(path, options);
8263
8264 Stream.call(this);
8265
8266 var self = this;
8267
8268 this.path = path;
8269 this.fd = null;
8270 this.readable = true;
8271 this.paused = false;
8272
8273 this.flags = 'r';
8274 this.mode = 438; /*=0666*/
8275 this.bufferSize = 64 * 1024;
8276
8277 options = options || {};
8278
8279 // Mixin options into this
8280 var keys = Object.keys(options);
8281 for (var index = 0, length = keys.length; index < length; index++) {
8282 var key = keys[index];
8283 this[key] = options[key];
8284 }
8285
8286 if (this.encoding) this.setEncoding(this.encoding);
8287
8288 if (this.start !== undefined) {
8289 if ('number' !== typeof this.start) {
8290 throw TypeError('start must be a Number');
8291 }
8292 if (this.end === undefined) {
8293 this.end = Infinity;
8294 } else if ('number' !== typeof this.end) {
8295 throw TypeError('end must be a Number');
8296 }
8297
8298 if (this.start > this.end) {
8299 throw new Error('start must be <= end');
8300 }
8301
8302 this.pos = this.start;
8303 }
8304
8305 if (this.fd !== null) {
8306 process.nextTick(function() {
8307 self._read();
8308 });
8309 return;
8310 }
8311
8312 fs.open(this.path, this.flags, this.mode, function (err, fd) {
8313 if (err) {
8314 self.emit('error', err);
8315 self.readable = false;
8316 return;
8317 }
8318
8319 self.fd = fd;
8320 self.emit('open', fd);
8321 self._read();
8322 });
8323 }
8324
8325 function WriteStream (path, options) {
8326 if (!(this instanceof WriteStream)) return new WriteStream(path, options);
8327
8328 Stream.call(this);
8329
8330 this.path = path;
8331 this.fd = null;
8332 this.writable = true;
8333
8334 this.flags = 'w';
8335 this.encoding = 'binary';
8336 this.mode = 438; /*=0666*/
8337 this.bytesWritten = 0;
8338
8339 options = options || {};
8340
8341 // Mixin options into this
8342 var keys = Object.keys(options);
8343 for (var index = 0, length = keys.length; index < length; index++) {
8344 var key = keys[index];
8345 this[key] = options[key];
8346 }
8347
8348 if (this.start !== undefined) {
8349 if ('number' !== typeof this.start) {
8350 throw TypeError('start must be a Number');
8351 }
8352 if (this.start < 0) {
8353 throw new Error('start must be >= zero');
8354 }
8355
8356 this.pos = this.start;
8357 }
8358
8359 this.busy = false;
8360 this._queue = [];
8361
8362 if (this.fd === null) {
8363 this._open = fs.open;
8364 this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
8365 this.flush();
8366 }
8367 }
8368}
8369
8370var gracefulFs = createCommonjsModule(function (module) {
8371var queue = [];
8372
8373
8374
8375function noop () {}
8376
8377var debug = noop;
8378if (util__default['default'].debuglog)
8379 debug = util__default['default'].debuglog('gfs4');
8380else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
8381 debug = function() {
8382 var m = util__default['default'].format.apply(util__default['default'], arguments);
8383 m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ');
8384 console.error(m);
8385 };
8386
8387if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
8388 process.on('exit', function() {
8389 debug(queue);
8390 assert__default['default'].equal(queue.length, 0);
8391 });
8392}
8393
8394module.exports = patch(fs_1);
8395if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) {
8396 module.exports = patch(fs__default['default']);
8397}
8398
8399// Always patch fs.close/closeSync, because we want to
8400// retry() whenever a close happens *anywhere* in the program.
8401// This is essential when multiple graceful-fs instances are
8402// in play at the same time.
8403module.exports.close =
8404fs__default['default'].close = (function (fs$close) { return function (fd, cb) {
8405 return fs$close.call(fs__default['default'], fd, function (err) {
8406 if (!err)
8407 retry();
8408
8409 if (typeof cb === 'function')
8410 cb.apply(this, arguments);
8411 })
8412}})(fs__default['default'].close);
8413
8414module.exports.closeSync =
8415fs__default['default'].closeSync = (function (fs$closeSync) { return function (fd) {
8416 // Note that graceful-fs also retries when fs.closeSync() fails.
8417 // Looks like a bug to me, although it's probably a harmless one.
8418 var rval = fs$closeSync.apply(fs__default['default'], arguments);
8419 retry();
8420 return rval
8421}})(fs__default['default'].closeSync);
8422
8423function patch (fs) {
8424 // Everything that references the open() function needs to be in here
8425 polyfills(fs);
8426 fs.gracefulify = patch;
8427 fs.FileReadStream = ReadStream; // Legacy name.
8428 fs.FileWriteStream = WriteStream; // Legacy name.
8429 fs.createReadStream = createReadStream;
8430 fs.createWriteStream = createWriteStream;
8431 var fs$readFile = fs.readFile;
8432 fs.readFile = readFile;
8433 function readFile (path, options, cb) {
8434 if (typeof options === 'function')
8435 cb = options, options = null;
8436
8437 return go$readFile(path, options, cb)
8438
8439 function go$readFile (path, options, cb) {
8440 return fs$readFile(path, options, function (err) {
8441 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
8442 enqueue([go$readFile, [path, options, cb]]);
8443 else {
8444 if (typeof cb === 'function')
8445 cb.apply(this, arguments);
8446 retry();
8447 }
8448 })
8449 }
8450 }
8451
8452 var fs$writeFile = fs.writeFile;
8453 fs.writeFile = writeFile;
8454 function writeFile (path, data, options, cb) {
8455 if (typeof options === 'function')
8456 cb = options, options = null;
8457
8458 return go$writeFile(path, data, options, cb)
8459
8460 function go$writeFile (path, data, options, cb) {
8461 return fs$writeFile(path, data, options, function (err) {
8462 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
8463 enqueue([go$writeFile, [path, data, options, cb]]);
8464 else {
8465 if (typeof cb === 'function')
8466 cb.apply(this, arguments);
8467 retry();
8468 }
8469 })
8470 }
8471 }
8472
8473 var fs$appendFile = fs.appendFile;
8474 if (fs$appendFile)
8475 fs.appendFile = appendFile;
8476 function appendFile (path, data, options, cb) {
8477 if (typeof options === 'function')
8478 cb = options, options = null;
8479
8480 return go$appendFile(path, data, options, cb)
8481
8482 function go$appendFile (path, data, options, cb) {
8483 return fs$appendFile(path, data, options, function (err) {
8484 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
8485 enqueue([go$appendFile, [path, data, options, cb]]);
8486 else {
8487 if (typeof cb === 'function')
8488 cb.apply(this, arguments);
8489 retry();
8490 }
8491 })
8492 }
8493 }
8494
8495 var fs$readdir = fs.readdir;
8496 fs.readdir = readdir;
8497 function readdir (path, options, cb) {
8498 var args = [path];
8499 if (typeof options !== 'function') {
8500 args.push(options);
8501 } else {
8502 cb = options;
8503 }
8504 args.push(go$readdir$cb);
8505
8506 return go$readdir(args)
8507
8508 function go$readdir$cb (err, files) {
8509 if (files && files.sort)
8510 files.sort();
8511
8512 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
8513 enqueue([go$readdir, [args]]);
8514 else {
8515 if (typeof cb === 'function')
8516 cb.apply(this, arguments);
8517 retry();
8518 }
8519 }
8520 }
8521
8522 function go$readdir (args) {
8523 return fs$readdir.apply(fs, args)
8524 }
8525
8526 if (process.version.substr(0, 4) === 'v0.8') {
8527 var legStreams = legacyStreams(fs);
8528 ReadStream = legStreams.ReadStream;
8529 WriteStream = legStreams.WriteStream;
8530 }
8531
8532 var fs$ReadStream = fs.ReadStream;
8533 ReadStream.prototype = Object.create(fs$ReadStream.prototype);
8534 ReadStream.prototype.open = ReadStream$open;
8535
8536 var fs$WriteStream = fs.WriteStream;
8537 WriteStream.prototype = Object.create(fs$WriteStream.prototype);
8538 WriteStream.prototype.open = WriteStream$open;
8539
8540 fs.ReadStream = ReadStream;
8541 fs.WriteStream = WriteStream;
8542
8543 function ReadStream (path, options) {
8544 if (this instanceof ReadStream)
8545 return fs$ReadStream.apply(this, arguments), this
8546 else
8547 return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
8548 }
8549
8550 function ReadStream$open () {
8551 var that = this;
8552 open(that.path, that.flags, that.mode, function (err, fd) {
8553 if (err) {
8554 if (that.autoClose)
8555 that.destroy();
8556
8557 that.emit('error', err);
8558 } else {
8559 that.fd = fd;
8560 that.emit('open', fd);
8561 that.read();
8562 }
8563 });
8564 }
8565
8566 function WriteStream (path, options) {
8567 if (this instanceof WriteStream)
8568 return fs$WriteStream.apply(this, arguments), this
8569 else
8570 return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
8571 }
8572
8573 function WriteStream$open () {
8574 var that = this;
8575 open(that.path, that.flags, that.mode, function (err, fd) {
8576 if (err) {
8577 that.destroy();
8578 that.emit('error', err);
8579 } else {
8580 that.fd = fd;
8581 that.emit('open', fd);
8582 }
8583 });
8584 }
8585
8586 function createReadStream (path, options) {
8587 return new ReadStream(path, options)
8588 }
8589
8590 function createWriteStream (path, options) {
8591 return new WriteStream(path, options)
8592 }
8593
8594 var fs$open = fs.open;
8595 fs.open = open;
8596 function open (path, flags, mode, cb) {
8597 if (typeof mode === 'function')
8598 cb = mode, mode = null;
8599
8600 return go$open(path, flags, mode, cb)
8601
8602 function go$open (path, flags, mode, cb) {
8603 return fs$open(path, flags, mode, function (err, fd) {
8604 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
8605 enqueue([go$open, [path, flags, mode, cb]]);
8606 else {
8607 if (typeof cb === 'function')
8608 cb.apply(this, arguments);
8609 retry();
8610 }
8611 })
8612 }
8613 }
8614
8615 return fs
8616}
8617
8618function enqueue (elem) {
8619 debug('ENQUEUE', elem[0].name, elem[1]);
8620 queue.push(elem);
8621}
8622
8623function retry () {
8624 var elem = queue.shift();
8625 if (elem) {
8626 debug('RETRY', elem[0].name, elem[1]);
8627 elem[0].apply(null, elem[1]);
8628 }
8629}
8630});
8631
8632var _0777 = parseInt('0777', 8);
8633
8634var mkdirp$2 = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
8635
8636function mkdirP (p, opts, f, made) {
8637 if (typeof opts === 'function') {
8638 f = opts;
8639 opts = {};
8640 }
8641 else if (!opts || typeof opts !== 'object') {
8642 opts = { mode: opts };
8643 }
8644
8645 var mode = opts.mode;
8646 var xfs = opts.fs || fs__default['default'];
8647
8648 if (mode === undefined) {
8649 mode = _0777 & (~process.umask());
8650 }
8651 if (!made) made = null;
8652
8653 var cb = f || function () {};
8654 p = path__default['default'].resolve(p);
8655
8656 xfs.mkdir(p, mode, function (er) {
8657 if (!er) {
8658 made = made || p;
8659 return cb(null, made);
8660 }
8661 switch (er.code) {
8662 case 'ENOENT':
8663 mkdirP(path__default['default'].dirname(p), opts, function (er, made) {
8664 if (er) cb(er, made);
8665 else mkdirP(p, opts, cb, made);
8666 });
8667 break;
8668
8669 // In the case of any other error, just see if there's a dir
8670 // there already. If so, then hooray! If not, then something
8671 // is borked.
8672 default:
8673 xfs.stat(p, function (er2, stat) {
8674 // if the stat fails, then that's super weird.
8675 // let the original error be the failure reason.
8676 if (er2 || !stat.isDirectory()) cb(er, made);
8677 else cb(null, made);
8678 });
8679 break;
8680 }
8681 });
8682}
8683
8684mkdirP.sync = function sync (p, opts, made) {
8685 if (!opts || typeof opts !== 'object') {
8686 opts = { mode: opts };
8687 }
8688
8689 var mode = opts.mode;
8690 var xfs = opts.fs || fs__default['default'];
8691
8692 if (mode === undefined) {
8693 mode = _0777 & (~process.umask());
8694 }
8695 if (!made) made = null;
8696
8697 p = path__default['default'].resolve(p);
8698
8699 try {
8700 xfs.mkdirSync(p, mode);
8701 made = made || p;
8702 }
8703 catch (err0) {
8704 switch (err0.code) {
8705 case 'ENOENT' :
8706 made = sync(path__default['default'].dirname(p), opts, made);
8707 sync(p, opts, made);
8708 break;
8709
8710 // In the case of any other error, just see if there's a dir
8711 // there already. If so, then hooray! If not, then something
8712 // is borked.
8713 default:
8714 var stat;
8715 try {
8716 stat = xfs.statSync(p);
8717 }
8718 catch (err1) {
8719 throw err0;
8720 }
8721 if (!stat.isDirectory()) throw err0;
8722 break;
8723 }
8724 }
8725
8726 return made;
8727};
8728
8729// Copyright Joyent, Inc. and other Node contributors.
8730//
8731// Permission is hereby granted, free of charge, to any person obtaining a
8732// copy of this software and associated documentation files (the
8733// "Software"), to deal in the Software without restriction, including
8734// without limitation the rights to use, copy, modify, merge, publish,
8735// distribute, sublicense, and/or sell copies of the Software, and to permit
8736// persons to whom the Software is furnished to do so, subject to the
8737// following conditions:
8738//
8739// The above copyright notice and this permission notice shall be included
8740// in all copies or substantial portions of the Software.
8741//
8742// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8743// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8744// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
8745// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
8746// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
8747// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
8748// USE OR OTHER DEALINGS IN THE SOFTWARE.
8749
8750
8751var isWindows$1 = process.platform === 'win32';
8752
8753
8754// JavaScript implementation of realpath, ported from node pre-v6
8755
8756var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
8757
8758function rethrow() {
8759 // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
8760 // is fairly slow to generate.
8761 var callback;
8762 if (DEBUG) {
8763 var backtrace = new Error;
8764 callback = debugCallback;
8765 } else
8766 callback = missingCallback;
8767
8768 return callback;
8769
8770 function debugCallback(err) {
8771 if (err) {
8772 backtrace.message = err.message;
8773 err = backtrace;
8774 missingCallback(err);
8775 }
8776 }
8777
8778 function missingCallback(err) {
8779 if (err) {
8780 if (process.throwDeprecation)
8781 throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
8782 else if (!process.noDeprecation) {
8783 var msg = 'fs: missing callback ' + (err.stack || err.message);
8784 if (process.traceDeprecation)
8785 console.trace(msg);
8786 else
8787 console.error(msg);
8788 }
8789 }
8790 }
8791}
8792
8793function maybeCallback(cb) {
8794 return typeof cb === 'function' ? cb : rethrow();
8795}
8796
8797path__default['default'].normalize;
8798
8799// Regexp that finds the next partion of a (partial) path
8800// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
8801if (isWindows$1) {
8802 var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
8803} else {
8804 var nextPartRe = /(.*?)(?:[\/]+|$)/g;
8805}
8806
8807// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
8808if (isWindows$1) {
8809 var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
8810} else {
8811 var splitRootRe = /^[\/]*/;
8812}
8813
8814var realpathSync$1 = function realpathSync(p, cache) {
8815 // make p is absolute
8816 p = path__default['default'].resolve(p);
8817
8818 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
8819 return cache[p];
8820 }
8821
8822 var original = p,
8823 seenLinks = {},
8824 knownHard = {};
8825
8826 // current character position in p
8827 var pos;
8828 // the partial path so far, including a trailing slash if any
8829 var current;
8830 // the partial path without a trailing slash (except when pointing at a root)
8831 var base;
8832 // the partial path scanned in the previous round, with slash
8833 var previous;
8834
8835 start();
8836
8837 function start() {
8838 // Skip over roots
8839 var m = splitRootRe.exec(p);
8840 pos = m[0].length;
8841 current = m[0];
8842 base = m[0];
8843 previous = '';
8844
8845 // On windows, check that the root exists. On unix there is no need.
8846 if (isWindows$1 && !knownHard[base]) {
8847 fs__default['default'].lstatSync(base);
8848 knownHard[base] = true;
8849 }
8850 }
8851
8852 // walk down the path, swapping out linked pathparts for their real
8853 // values
8854 // NB: p.length changes.
8855 while (pos < p.length) {
8856 // find the next part
8857 nextPartRe.lastIndex = pos;
8858 var result = nextPartRe.exec(p);
8859 previous = current;
8860 current += result[0];
8861 base = previous + result[1];
8862 pos = nextPartRe.lastIndex;
8863
8864 // continue if not a symlink
8865 if (knownHard[base] || (cache && cache[base] === base)) {
8866 continue;
8867 }
8868
8869 var resolvedLink;
8870 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
8871 // some known symbolic link. no need to stat again.
8872 resolvedLink = cache[base];
8873 } else {
8874 var stat = fs__default['default'].lstatSync(base);
8875 if (!stat.isSymbolicLink()) {
8876 knownHard[base] = true;
8877 if (cache) cache[base] = base;
8878 continue;
8879 }
8880
8881 // read the link if it wasn't read before
8882 // dev/ino always return 0 on windows, so skip the check.
8883 var linkTarget = null;
8884 if (!isWindows$1) {
8885 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
8886 if (seenLinks.hasOwnProperty(id)) {
8887 linkTarget = seenLinks[id];
8888 }
8889 }
8890 if (linkTarget === null) {
8891 fs__default['default'].statSync(base);
8892 linkTarget = fs__default['default'].readlinkSync(base);
8893 }
8894 resolvedLink = path__default['default'].resolve(previous, linkTarget);
8895 // track this, if given a cache.
8896 if (cache) cache[base] = resolvedLink;
8897 if (!isWindows$1) seenLinks[id] = linkTarget;
8898 }
8899
8900 // resolve the link, then start over
8901 p = path__default['default'].resolve(resolvedLink, p.slice(pos));
8902 start();
8903 }
8904
8905 if (cache) cache[original] = p;
8906
8907 return p;
8908};
8909
8910
8911var realpath$1 = function realpath(p, cache, cb) {
8912 if (typeof cb !== 'function') {
8913 cb = maybeCallback(cache);
8914 cache = null;
8915 }
8916
8917 // make p is absolute
8918 p = path__default['default'].resolve(p);
8919
8920 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
8921 return process.nextTick(cb.bind(null, null, cache[p]));
8922 }
8923
8924 var original = p,
8925 seenLinks = {},
8926 knownHard = {};
8927
8928 // current character position in p
8929 var pos;
8930 // the partial path so far, including a trailing slash if any
8931 var current;
8932 // the partial path without a trailing slash (except when pointing at a root)
8933 var base;
8934 // the partial path scanned in the previous round, with slash
8935 var previous;
8936
8937 start();
8938
8939 function start() {
8940 // Skip over roots
8941 var m = splitRootRe.exec(p);
8942 pos = m[0].length;
8943 current = m[0];
8944 base = m[0];
8945 previous = '';
8946
8947 // On windows, check that the root exists. On unix there is no need.
8948 if (isWindows$1 && !knownHard[base]) {
8949 fs__default['default'].lstat(base, function(err) {
8950 if (err) return cb(err);
8951 knownHard[base] = true;
8952 LOOP();
8953 });
8954 } else {
8955 process.nextTick(LOOP);
8956 }
8957 }
8958
8959 // walk down the path, swapping out linked pathparts for their real
8960 // values
8961 function LOOP() {
8962 // stop if scanned past end of path
8963 if (pos >= p.length) {
8964 if (cache) cache[original] = p;
8965 return cb(null, p);
8966 }
8967
8968 // find the next part
8969 nextPartRe.lastIndex = pos;
8970 var result = nextPartRe.exec(p);
8971 previous = current;
8972 current += result[0];
8973 base = previous + result[1];
8974 pos = nextPartRe.lastIndex;
8975
8976 // continue if not a symlink
8977 if (knownHard[base] || (cache && cache[base] === base)) {
8978 return process.nextTick(LOOP);
8979 }
8980
8981 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
8982 // known symbolic link. no need to stat again.
8983 return gotResolvedLink(cache[base]);
8984 }
8985
8986 return fs__default['default'].lstat(base, gotStat);
8987 }
8988
8989 function gotStat(err, stat) {
8990 if (err) return cb(err);
8991
8992 // if not a symlink, skip to the next path part
8993 if (!stat.isSymbolicLink()) {
8994 knownHard[base] = true;
8995 if (cache) cache[base] = base;
8996 return process.nextTick(LOOP);
8997 }
8998
8999 // stat & read the link if not read before
9000 // call gotTarget as soon as the link target is known
9001 // dev/ino always return 0 on windows, so skip the check.
9002 if (!isWindows$1) {
9003 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
9004 if (seenLinks.hasOwnProperty(id)) {
9005 return gotTarget(null, seenLinks[id], base);
9006 }
9007 }
9008 fs__default['default'].stat(base, function(err) {
9009 if (err) return cb(err);
9010
9011 fs__default['default'].readlink(base, function(err, target) {
9012 if (!isWindows$1) seenLinks[id] = target;
9013 gotTarget(err, target);
9014 });
9015 });
9016 }
9017
9018 function gotTarget(err, target, base) {
9019 if (err) return cb(err);
9020
9021 var resolvedLink = path__default['default'].resolve(previous, target);
9022 if (cache) cache[base] = resolvedLink;
9023 gotResolvedLink(resolvedLink);
9024 }
9025
9026 function gotResolvedLink(resolvedLink) {
9027 // resolve the link, then start over
9028 p = path__default['default'].resolve(resolvedLink, p.slice(pos));
9029 start();
9030 }
9031};
9032
9033var old = {
9034 realpathSync: realpathSync$1,
9035 realpath: realpath$1
9036};
9037
9038var fs_realpath = realpath;
9039realpath.realpath = realpath;
9040realpath.sync = realpathSync;
9041realpath.realpathSync = realpathSync;
9042realpath.monkeypatch = monkeypatch;
9043realpath.unmonkeypatch = unmonkeypatch;
9044
9045
9046var origRealpath = fs__default['default'].realpath;
9047var origRealpathSync = fs__default['default'].realpathSync;
9048
9049var version = process.version;
9050var ok = /^v[0-5]\./.test(version);
9051
9052
9053function newError (er) {
9054 return er && er.syscall === 'realpath' && (
9055 er.code === 'ELOOP' ||
9056 er.code === 'ENOMEM' ||
9057 er.code === 'ENAMETOOLONG'
9058 )
9059}
9060
9061function realpath (p, cache, cb) {
9062 if (ok) {
9063 return origRealpath(p, cache, cb)
9064 }
9065
9066 if (typeof cache === 'function') {
9067 cb = cache;
9068 cache = null;
9069 }
9070 origRealpath(p, cache, function (er, result) {
9071 if (newError(er)) {
9072 old.realpath(p, cache, cb);
9073 } else {
9074 cb(er, result);
9075 }
9076 });
9077}
9078
9079function realpathSync (p, cache) {
9080 if (ok) {
9081 return origRealpathSync(p, cache)
9082 }
9083
9084 try {
9085 return origRealpathSync(p, cache)
9086 } catch (er) {
9087 if (newError(er)) {
9088 return old.realpathSync(p, cache)
9089 } else {
9090 throw er
9091 }
9092 }
9093}
9094
9095function monkeypatch () {
9096 fs__default['default'].realpath = realpath;
9097 fs__default['default'].realpathSync = realpathSync;
9098}
9099
9100function unmonkeypatch () {
9101 fs__default['default'].realpath = origRealpath;
9102 fs__default['default'].realpathSync = origRealpathSync;
9103}
9104
9105var concatMap = function (xs, fn) {
9106 var res = [];
9107 for (var i = 0; i < xs.length; i++) {
9108 var x = fn(xs[i], i);
9109 if (isArray(x)) res.push.apply(res, x);
9110 else res.push(x);
9111 }
9112 return res;
9113};
9114
9115var isArray = Array.isArray || function (xs) {
9116 return Object.prototype.toString.call(xs) === '[object Array]';
9117};
9118
9119var balancedMatch = balanced;
9120function balanced(a, b, str) {
9121 if (a instanceof RegExp) a = maybeMatch(a, str);
9122 if (b instanceof RegExp) b = maybeMatch(b, str);
9123
9124 var r = range(a, b, str);
9125
9126 return r && {
9127 start: r[0],
9128 end: r[1],
9129 pre: str.slice(0, r[0]),
9130 body: str.slice(r[0] + a.length, r[1]),
9131 post: str.slice(r[1] + b.length)
9132 };
9133}
9134
9135function maybeMatch(reg, str) {
9136 var m = str.match(reg);
9137 return m ? m[0] : null;
9138}
9139
9140balanced.range = range;
9141function range(a, b, str) {
9142 var begs, beg, left, right, result;
9143 var ai = str.indexOf(a);
9144 var bi = str.indexOf(b, ai + 1);
9145 var i = ai;
9146
9147 if (ai >= 0 && bi > 0) {
9148 begs = [];
9149 left = str.length;
9150
9151 while (i >= 0 && !result) {
9152 if (i == ai) {
9153 begs.push(i);
9154 ai = str.indexOf(a, i + 1);
9155 } else if (begs.length == 1) {
9156 result = [ begs.pop(), bi ];
9157 } else {
9158 beg = begs.pop();
9159 if (beg < left) {
9160 left = beg;
9161 right = bi;
9162 }
9163
9164 bi = str.indexOf(b, i + 1);
9165 }
9166
9167 i = ai < bi && ai >= 0 ? ai : bi;
9168 }
9169
9170 if (begs.length) {
9171 result = [ left, right ];
9172 }
9173 }
9174
9175 return result;
9176}
9177
9178var braceExpansion = expandTop;
9179
9180var escSlash = '\0SLASH'+Math.random()+'\0';
9181var escOpen = '\0OPEN'+Math.random()+'\0';
9182var escClose = '\0CLOSE'+Math.random()+'\0';
9183var escComma = '\0COMMA'+Math.random()+'\0';
9184var escPeriod = '\0PERIOD'+Math.random()+'\0';
9185
9186function numeric(str) {
9187 return parseInt(str, 10) == str
9188 ? parseInt(str, 10)
9189 : str.charCodeAt(0);
9190}
9191
9192function escapeBraces(str) {
9193 return str.split('\\\\').join(escSlash)
9194 .split('\\{').join(escOpen)
9195 .split('\\}').join(escClose)
9196 .split('\\,').join(escComma)
9197 .split('\\.').join(escPeriod);
9198}
9199
9200function unescapeBraces(str) {
9201 return str.split(escSlash).join('\\')
9202 .split(escOpen).join('{')
9203 .split(escClose).join('}')
9204 .split(escComma).join(',')
9205 .split(escPeriod).join('.');
9206}
9207
9208
9209// Basically just str.split(","), but handling cases
9210// where we have nested braced sections, which should be
9211// treated as individual members, like {a,{b,c},d}
9212function parseCommaParts(str) {
9213 if (!str)
9214 return [''];
9215
9216 var parts = [];
9217 var m = balancedMatch('{', '}', str);
9218
9219 if (!m)
9220 return str.split(',');
9221
9222 var pre = m.pre;
9223 var body = m.body;
9224 var post = m.post;
9225 var p = pre.split(',');
9226
9227 p[p.length-1] += '{' + body + '}';
9228 var postParts = parseCommaParts(post);
9229 if (post.length) {
9230 p[p.length-1] += postParts.shift();
9231 p.push.apply(p, postParts);
9232 }
9233
9234 parts.push.apply(parts, p);
9235
9236 return parts;
9237}
9238
9239function expandTop(str) {
9240 if (!str)
9241 return [];
9242
9243 // I don't know why Bash 4.3 does this, but it does.
9244 // Anything starting with {} will have the first two bytes preserved
9245 // but *only* at the top level, so {},a}b will not expand to anything,
9246 // but a{},b}c will be expanded to [a}c,abc].
9247 // One could argue that this is a bug in Bash, but since the goal of
9248 // this module is to match Bash's rules, we escape a leading {}
9249 if (str.substr(0, 2) === '{}') {
9250 str = '\\{\\}' + str.substr(2);
9251 }
9252
9253 return expand(escapeBraces(str), true).map(unescapeBraces);
9254}
9255
9256function embrace(str) {
9257 return '{' + str + '}';
9258}
9259function isPadded(el) {
9260 return /^-?0\d/.test(el);
9261}
9262
9263function lte(i, y) {
9264 return i <= y;
9265}
9266function gte(i, y) {
9267 return i >= y;
9268}
9269
9270function expand(str, isTop) {
9271 var expansions = [];
9272
9273 var m = balancedMatch('{', '}', str);
9274 if (!m || /\$$/.test(m.pre)) return [str];
9275
9276 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
9277 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
9278 var isSequence = isNumericSequence || isAlphaSequence;
9279 var isOptions = m.body.indexOf(',') >= 0;
9280 if (!isSequence && !isOptions) {
9281 // {a},b}
9282 if (m.post.match(/,.*\}/)) {
9283 str = m.pre + '{' + m.body + escClose + m.post;
9284 return expand(str);
9285 }
9286 return [str];
9287 }
9288
9289 var n;
9290 if (isSequence) {
9291 n = m.body.split(/\.\./);
9292 } else {
9293 n = parseCommaParts(m.body);
9294 if (n.length === 1) {
9295 // x{{a,b}}y ==> x{a}y x{b}y
9296 n = expand(n[0], false).map(embrace);
9297 if (n.length === 1) {
9298 var post = m.post.length
9299 ? expand(m.post, false)
9300 : [''];
9301 return post.map(function(p) {
9302 return m.pre + n[0] + p;
9303 });
9304 }
9305 }
9306 }
9307
9308 // at this point, n is the parts, and we know it's not a comma set
9309 // with a single entry.
9310
9311 // no need to expand pre, since it is guaranteed to be free of brace-sets
9312 var pre = m.pre;
9313 var post = m.post.length
9314 ? expand(m.post, false)
9315 : [''];
9316
9317 var N;
9318
9319 if (isSequence) {
9320 var x = numeric(n[0]);
9321 var y = numeric(n[1]);
9322 var width = Math.max(n[0].length, n[1].length);
9323 var incr = n.length == 3
9324 ? Math.abs(numeric(n[2]))
9325 : 1;
9326 var test = lte;
9327 var reverse = y < x;
9328 if (reverse) {
9329 incr *= -1;
9330 test = gte;
9331 }
9332 var pad = n.some(isPadded);
9333
9334 N = [];
9335
9336 for (var i = x; test(i, y); i += incr) {
9337 var c;
9338 if (isAlphaSequence) {
9339 c = String.fromCharCode(i);
9340 if (c === '\\')
9341 c = '';
9342 } else {
9343 c = String(i);
9344 if (pad) {
9345 var need = width - c.length;
9346 if (need > 0) {
9347 var z = new Array(need + 1).join('0');
9348 if (i < 0)
9349 c = '-' + z + c.slice(1);
9350 else
9351 c = z + c;
9352 }
9353 }
9354 }
9355 N.push(c);
9356 }
9357 } else {
9358 N = concatMap(n, function(el) { return expand(el, false) });
9359 }
9360
9361 for (var j = 0; j < N.length; j++) {
9362 for (var k = 0; k < post.length; k++) {
9363 var expansion = pre + N[j] + post[k];
9364 if (!isTop || isSequence || expansion)
9365 expansions.push(expansion);
9366 }
9367 }
9368
9369 return expansions;
9370}
9371
9372var minimatch_1 = minimatch;
9373minimatch.Minimatch = Minimatch$1;
9374
9375var path = { sep: '/' };
9376try {
9377 path = path__default['default'];
9378} catch (er) {}
9379
9380var GLOBSTAR = minimatch.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
9381
9382
9383var plTypes = {
9384 '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
9385 '?': { open: '(?:', close: ')?' },
9386 '+': { open: '(?:', close: ')+' },
9387 '*': { open: '(?:', close: ')*' },
9388 '@': { open: '(?:', close: ')' }
9389};
9390
9391// any single thing other than /
9392// don't need to escape / when using new RegExp()
9393var qmark = '[^/]';
9394
9395// * => any number of characters
9396var star = qmark + '*?';
9397
9398// ** when dots are allowed. Anything goes, except .. and .
9399// not (^ or / followed by one or two dots followed by $ or /),
9400// followed by anything, any number of times.
9401var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
9402
9403// not a ^ or / followed by a dot,
9404// followed by anything, any number of times.
9405var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
9406
9407// characters that need to be escaped in RegExp.
9408var reSpecials = charSet('().*{}+?[]^$\\!');
9409
9410// "abc" -> { a:true, b:true, c:true }
9411function charSet (s) {
9412 return s.split('').reduce(function (set, c) {
9413 set[c] = true;
9414 return set
9415 }, {})
9416}
9417
9418// normalizes slashes.
9419var slashSplit = /\/+/;
9420
9421minimatch.filter = filter;
9422function filter (pattern, options) {
9423 options = options || {};
9424 return function (p, i, list) {
9425 return minimatch(p, pattern, options)
9426 }
9427}
9428
9429function ext (a, b) {
9430 a = a || {};
9431 b = b || {};
9432 var t = {};
9433 Object.keys(b).forEach(function (k) {
9434 t[k] = b[k];
9435 });
9436 Object.keys(a).forEach(function (k) {
9437 t[k] = a[k];
9438 });
9439 return t
9440}
9441
9442minimatch.defaults = function (def) {
9443 if (!def || !Object.keys(def).length) return minimatch
9444
9445 var orig = minimatch;
9446
9447 var m = function minimatch (p, pattern, options) {
9448 return orig.minimatch(p, pattern, ext(def, options))
9449 };
9450
9451 m.Minimatch = function Minimatch (pattern, options) {
9452 return new orig.Minimatch(pattern, ext(def, options))
9453 };
9454
9455 return m
9456};
9457
9458Minimatch$1.defaults = function (def) {
9459 if (!def || !Object.keys(def).length) return Minimatch$1
9460 return minimatch.defaults(def).Minimatch
9461};
9462
9463function minimatch (p, pattern, options) {
9464 if (typeof pattern !== 'string') {
9465 throw new TypeError('glob pattern string required')
9466 }
9467
9468 if (!options) options = {};
9469
9470 // shortcut: comments match nothing.
9471 if (!options.nocomment && pattern.charAt(0) === '#') {
9472 return false
9473 }
9474
9475 // "" only matches ""
9476 if (pattern.trim() === '') return p === ''
9477
9478 return new Minimatch$1(pattern, options).match(p)
9479}
9480
9481function Minimatch$1 (pattern, options) {
9482 if (!(this instanceof Minimatch$1)) {
9483 return new Minimatch$1(pattern, options)
9484 }
9485
9486 if (typeof pattern !== 'string') {
9487 throw new TypeError('glob pattern string required')
9488 }
9489
9490 if (!options) options = {};
9491 pattern = pattern.trim();
9492
9493 // windows support: need to use /, not \
9494 if (path.sep !== '/') {
9495 pattern = pattern.split(path.sep).join('/');
9496 }
9497
9498 this.options = options;
9499 this.set = [];
9500 this.pattern = pattern;
9501 this.regexp = null;
9502 this.negate = false;
9503 this.comment = false;
9504 this.empty = false;
9505
9506 // make the set of regexps etc.
9507 this.make();
9508}
9509
9510Minimatch$1.prototype.debug = function () {};
9511
9512Minimatch$1.prototype.make = make;
9513function make () {
9514 // don't do it more than once.
9515 if (this._made) return
9516
9517 var pattern = this.pattern;
9518 var options = this.options;
9519
9520 // empty patterns and comments match nothing.
9521 if (!options.nocomment && pattern.charAt(0) === '#') {
9522 this.comment = true;
9523 return
9524 }
9525 if (!pattern) {
9526 this.empty = true;
9527 return
9528 }
9529
9530 // step 1: figure out negation, etc.
9531 this.parseNegate();
9532
9533 // step 2: expand braces
9534 var set = this.globSet = this.braceExpand();
9535
9536 if (options.debug) this.debug = console.error;
9537
9538 this.debug(this.pattern, set);
9539
9540 // step 3: now we have a set, so turn each one into a series of path-portion
9541 // matching patterns.
9542 // These will be regexps, except in the case of "**", which is
9543 // set to the GLOBSTAR object for globstar behavior,
9544 // and will not contain any / characters
9545 set = this.globParts = set.map(function (s) {
9546 return s.split(slashSplit)
9547 });
9548
9549 this.debug(this.pattern, set);
9550
9551 // glob --> regexps
9552 set = set.map(function (s, si, set) {
9553 return s.map(this.parse, this)
9554 }, this);
9555
9556 this.debug(this.pattern, set);
9557
9558 // filter out everything that didn't compile properly.
9559 set = set.filter(function (s) {
9560 return s.indexOf(false) === -1
9561 });
9562
9563 this.debug(this.pattern, set);
9564
9565 this.set = set;
9566}
9567
9568Minimatch$1.prototype.parseNegate = parseNegate;
9569function parseNegate () {
9570 var pattern = this.pattern;
9571 var negate = false;
9572 var options = this.options;
9573 var negateOffset = 0;
9574
9575 if (options.nonegate) return
9576
9577 for (var i = 0, l = pattern.length
9578 ; i < l && pattern.charAt(i) === '!'
9579 ; i++) {
9580 negate = !negate;
9581 negateOffset++;
9582 }
9583
9584 if (negateOffset) this.pattern = pattern.substr(negateOffset);
9585 this.negate = negate;
9586}
9587
9588// Brace expansion:
9589// a{b,c}d -> abd acd
9590// a{b,}c -> abc ac
9591// a{0..3}d -> a0d a1d a2d a3d
9592// a{b,c{d,e}f}g -> abg acdfg acefg
9593// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
9594//
9595// Invalid sets are not expanded.
9596// a{2..}b -> a{2..}b
9597// a{b}c -> a{b}c
9598minimatch.braceExpand = function (pattern, options) {
9599 return braceExpand(pattern, options)
9600};
9601
9602Minimatch$1.prototype.braceExpand = braceExpand;
9603
9604function braceExpand (pattern, options) {
9605 if (!options) {
9606 if (this instanceof Minimatch$1) {
9607 options = this.options;
9608 } else {
9609 options = {};
9610 }
9611 }
9612
9613 pattern = typeof pattern === 'undefined'
9614 ? this.pattern : pattern;
9615
9616 if (typeof pattern === 'undefined') {
9617 throw new TypeError('undefined pattern')
9618 }
9619
9620 if (options.nobrace ||
9621 !pattern.match(/\{.*\}/)) {
9622 // shortcut. no need to expand.
9623 return [pattern]
9624 }
9625
9626 return braceExpansion(pattern)
9627}
9628
9629// parse a component of the expanded set.
9630// At this point, no pattern may contain "/" in it
9631// so we're going to return a 2d array, where each entry is the full
9632// pattern, split on '/', and then turned into a regular expression.
9633// A regexp is made at the end which joins each array with an
9634// escaped /, and another full one which joins each regexp with |.
9635//
9636// Following the lead of Bash 4.1, note that "**" only has special meaning
9637// when it is the *only* thing in a path portion. Otherwise, any series
9638// of * is equivalent to a single *. Globstar behavior is enabled by
9639// default, and can be disabled by setting options.noglobstar.
9640Minimatch$1.prototype.parse = parse$2;
9641var SUBPARSE = {};
9642function parse$2 (pattern, isSub) {
9643 if (pattern.length > 1024 * 64) {
9644 throw new TypeError('pattern is too long')
9645 }
9646
9647 var options = this.options;
9648
9649 // shortcuts
9650 if (!options.noglobstar && pattern === '**') return GLOBSTAR
9651 if (pattern === '') return ''
9652
9653 var re = '';
9654 var hasMagic = !!options.nocase;
9655 var escaping = false;
9656 // ? => one single character
9657 var patternListStack = [];
9658 var negativeLists = [];
9659 var stateChar;
9660 var inClass = false;
9661 var reClassStart = -1;
9662 var classStart = -1;
9663 // . and .. never match anything that doesn't start with .,
9664 // even when options.dot is set.
9665 var patternStart = pattern.charAt(0) === '.' ? '' // anything
9666 // not (start or / followed by . or .. followed by / or end)
9667 : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
9668 : '(?!\\.)';
9669 var self = this;
9670
9671 function clearStateChar () {
9672 if (stateChar) {
9673 // we had some state-tracking character
9674 // that wasn't consumed by this pass.
9675 switch (stateChar) {
9676 case '*':
9677 re += star;
9678 hasMagic = true;
9679 break
9680 case '?':
9681 re += qmark;
9682 hasMagic = true;
9683 break
9684 default:
9685 re += '\\' + stateChar;
9686 break
9687 }
9688 self.debug('clearStateChar %j %j', stateChar, re);
9689 stateChar = false;
9690 }
9691 }
9692
9693 for (var i = 0, len = pattern.length, c
9694 ; (i < len) && (c = pattern.charAt(i))
9695 ; i++) {
9696 this.debug('%s\t%s %s %j', pattern, i, re, c);
9697
9698 // skip over any that are escaped.
9699 if (escaping && reSpecials[c]) {
9700 re += '\\' + c;
9701 escaping = false;
9702 continue
9703 }
9704
9705 switch (c) {
9706 case '/':
9707 // completely not allowed, even escaped.
9708 // Should already be path-split by now.
9709 return false
9710
9711 case '\\':
9712 clearStateChar();
9713 escaping = true;
9714 continue
9715
9716 // the various stateChar values
9717 // for the "extglob" stuff.
9718 case '?':
9719 case '*':
9720 case '+':
9721 case '@':
9722 case '!':
9723 this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
9724
9725 // all of those are literals inside a class, except that
9726 // the glob [!a] means [^a] in regexp
9727 if (inClass) {
9728 this.debug(' in class');
9729 if (c === '!' && i === classStart + 1) c = '^';
9730 re += c;
9731 continue
9732 }
9733
9734 // if we already have a stateChar, then it means
9735 // that there was something like ** or +? in there.
9736 // Handle the stateChar, then proceed with this one.
9737 self.debug('call clearStateChar %j', stateChar);
9738 clearStateChar();
9739 stateChar = c;
9740 // if extglob is disabled, then +(asdf|foo) isn't a thing.
9741 // just clear the statechar *now*, rather than even diving into
9742 // the patternList stuff.
9743 if (options.noext) clearStateChar();
9744 continue
9745
9746 case '(':
9747 if (inClass) {
9748 re += '(';
9749 continue
9750 }
9751
9752 if (!stateChar) {
9753 re += '\\(';
9754 continue
9755 }
9756
9757 patternListStack.push({
9758 type: stateChar,
9759 start: i - 1,
9760 reStart: re.length,
9761 open: plTypes[stateChar].open,
9762 close: plTypes[stateChar].close
9763 });
9764 // negation is (?:(?!js)[^/]*)
9765 re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
9766 this.debug('plType %j %j', stateChar, re);
9767 stateChar = false;
9768 continue
9769
9770 case ')':
9771 if (inClass || !patternListStack.length) {
9772 re += '\\)';
9773 continue
9774 }
9775
9776 clearStateChar();
9777 hasMagic = true;
9778 var pl = patternListStack.pop();
9779 // negation is (?:(?!js)[^/]*)
9780 // The others are (?:<pattern>)<type>
9781 re += pl.close;
9782 if (pl.type === '!') {
9783 negativeLists.push(pl);
9784 }
9785 pl.reEnd = re.length;
9786 continue
9787
9788 case '|':
9789 if (inClass || !patternListStack.length || escaping) {
9790 re += '\\|';
9791 escaping = false;
9792 continue
9793 }
9794
9795 clearStateChar();
9796 re += '|';
9797 continue
9798
9799 // these are mostly the same in regexp and glob
9800 case '[':
9801 // swallow any state-tracking char before the [
9802 clearStateChar();
9803
9804 if (inClass) {
9805 re += '\\' + c;
9806 continue
9807 }
9808
9809 inClass = true;
9810 classStart = i;
9811 reClassStart = re.length;
9812 re += c;
9813 continue
9814
9815 case ']':
9816 // a right bracket shall lose its special
9817 // meaning and represent itself in
9818 // a bracket expression if it occurs
9819 // first in the list. -- POSIX.2 2.8.3.2
9820 if (i === classStart + 1 || !inClass) {
9821 re += '\\' + c;
9822 escaping = false;
9823 continue
9824 }
9825
9826 // handle the case where we left a class open.
9827 // "[z-a]" is valid, equivalent to "\[z-a\]"
9828 if (inClass) {
9829 // split where the last [ was, make sure we don't have
9830 // an invalid re. if so, re-walk the contents of the
9831 // would-be class to re-translate any characters that
9832 // were passed through as-is
9833 // TODO: It would probably be faster to determine this
9834 // without a try/catch and a new RegExp, but it's tricky
9835 // to do safely. For now, this is safe and works.
9836 var cs = pattern.substring(classStart + 1, i);
9837 try {
9838 RegExp('[' + cs + ']');
9839 } catch (er) {
9840 // not a valid class!
9841 var sp = this.parse(cs, SUBPARSE);
9842 re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
9843 hasMagic = hasMagic || sp[1];
9844 inClass = false;
9845 continue
9846 }
9847 }
9848
9849 // finish up the class.
9850 hasMagic = true;
9851 inClass = false;
9852 re += c;
9853 continue
9854
9855 default:
9856 // swallow any state char that wasn't consumed
9857 clearStateChar();
9858
9859 if (escaping) {
9860 // no need
9861 escaping = false;
9862 } else if (reSpecials[c]
9863 && !(c === '^' && inClass)) {
9864 re += '\\';
9865 }
9866
9867 re += c;
9868
9869 } // switch
9870 } // for
9871
9872 // handle the case where we left a class open.
9873 // "[abc" is valid, equivalent to "\[abc"
9874 if (inClass) {
9875 // split where the last [ was, and escape it
9876 // this is a huge pita. We now have to re-walk
9877 // the contents of the would-be class to re-translate
9878 // any characters that were passed through as-is
9879 cs = pattern.substr(classStart + 1);
9880 sp = this.parse(cs, SUBPARSE);
9881 re = re.substr(0, reClassStart) + '\\[' + sp[0];
9882 hasMagic = hasMagic || sp[1];
9883 }
9884
9885 // handle the case where we had a +( thing at the *end*
9886 // of the pattern.
9887 // each pattern list stack adds 3 chars, and we need to go through
9888 // and escape any | chars that were passed through as-is for the regexp.
9889 // Go through and escape them, taking care not to double-escape any
9890 // | chars that were already escaped.
9891 for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
9892 var tail = re.slice(pl.reStart + pl.open.length);
9893 this.debug('setting tail', re, pl);
9894 // maybe some even number of \, then maybe 1 \, followed by a |
9895 tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
9896 if (!$2) {
9897 // the | isn't already escaped, so escape it.
9898 $2 = '\\';
9899 }
9900
9901 // need to escape all those slashes *again*, without escaping the
9902 // one that we need for escaping the | character. As it works out,
9903 // escaping an even number of slashes can be done by simply repeating
9904 // it exactly after itself. That's why this trick works.
9905 //
9906 // I am sorry that you have to see this.
9907 return $1 + $1 + $2 + '|'
9908 });
9909
9910 this.debug('tail=%j\n %s', tail, tail, pl, re);
9911 var t = pl.type === '*' ? star
9912 : pl.type === '?' ? qmark
9913 : '\\' + pl.type;
9914
9915 hasMagic = true;
9916 re = re.slice(0, pl.reStart) + t + '\\(' + tail;
9917 }
9918
9919 // handle trailing things that only matter at the very end.
9920 clearStateChar();
9921 if (escaping) {
9922 // trailing \\
9923 re += '\\\\';
9924 }
9925
9926 // only need to apply the nodot start if the re starts with
9927 // something that could conceivably capture a dot
9928 var addPatternStart = false;
9929 switch (re.charAt(0)) {
9930 case '.':
9931 case '[':
9932 case '(': addPatternStart = true;
9933 }
9934
9935 // Hack to work around lack of negative lookbehind in JS
9936 // A pattern like: *.!(x).!(y|z) needs to ensure that a name
9937 // like 'a.xyz.yz' doesn't match. So, the first negative
9938 // lookahead, has to look ALL the way ahead, to the end of
9939 // the pattern.
9940 for (var n = negativeLists.length - 1; n > -1; n--) {
9941 var nl = negativeLists[n];
9942
9943 var nlBefore = re.slice(0, nl.reStart);
9944 var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
9945 var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
9946 var nlAfter = re.slice(nl.reEnd);
9947
9948 nlLast += nlAfter;
9949
9950 // Handle nested stuff like *(*.js|!(*.json)), where open parens
9951 // mean that we should *not* include the ) in the bit that is considered
9952 // "after" the negated section.
9953 var openParensBefore = nlBefore.split('(').length - 1;
9954 var cleanAfter = nlAfter;
9955 for (i = 0; i < openParensBefore; i++) {
9956 cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
9957 }
9958 nlAfter = cleanAfter;
9959
9960 var dollar = '';
9961 if (nlAfter === '' && isSub !== SUBPARSE) {
9962 dollar = '$';
9963 }
9964 var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
9965 re = newRe;
9966 }
9967
9968 // if the re is not "" at this point, then we need to make sure
9969 // it doesn't match against an empty path part.
9970 // Otherwise a/* will match a/, which it should not.
9971 if (re !== '' && hasMagic) {
9972 re = '(?=.)' + re;
9973 }
9974
9975 if (addPatternStart) {
9976 re = patternStart + re;
9977 }
9978
9979 // parsing just a piece of a larger pattern.
9980 if (isSub === SUBPARSE) {
9981 return [re, hasMagic]
9982 }
9983
9984 // skip the regexp for non-magical patterns
9985 // unescape anything in it, though, so that it'll be
9986 // an exact match against a file etc.
9987 if (!hasMagic) {
9988 return globUnescape(pattern)
9989 }
9990
9991 var flags = options.nocase ? 'i' : '';
9992 try {
9993 var regExp = new RegExp('^' + re + '$', flags);
9994 } catch (er) {
9995 // If it was an invalid regular expression, then it can't match
9996 // anything. This trick looks for a character after the end of
9997 // the string, which is of course impossible, except in multi-line
9998 // mode, but it's not a /m regex.
9999 return new RegExp('$.')
10000 }
10001
10002 regExp._glob = pattern;
10003 regExp._src = re;
10004
10005 return regExp
10006}
10007
10008minimatch.makeRe = function (pattern, options) {
10009 return new Minimatch$1(pattern, options || {}).makeRe()
10010};
10011
10012Minimatch$1.prototype.makeRe = makeRe;
10013function makeRe () {
10014 if (this.regexp || this.regexp === false) return this.regexp
10015
10016 // at this point, this.set is a 2d array of partial
10017 // pattern strings, or "**".
10018 //
10019 // It's better to use .match(). This function shouldn't
10020 // be used, really, but it's pretty convenient sometimes,
10021 // when you just want to work with a regex.
10022 var set = this.set;
10023
10024 if (!set.length) {
10025 this.regexp = false;
10026 return this.regexp
10027 }
10028 var options = this.options;
10029
10030 var twoStar = options.noglobstar ? star
10031 : options.dot ? twoStarDot
10032 : twoStarNoDot;
10033 var flags = options.nocase ? 'i' : '';
10034
10035 var re = set.map(function (pattern) {
10036 return pattern.map(function (p) {
10037 return (p === GLOBSTAR) ? twoStar
10038 : (typeof p === 'string') ? regExpEscape(p)
10039 : p._src
10040 }).join('\\\/')
10041 }).join('|');
10042
10043 // must match entire pattern
10044 // ending in a * or ** will make it less strict.
10045 re = '^(?:' + re + ')$';
10046
10047 // can match anything, as long as it's not this.
10048 if (this.negate) re = '^(?!' + re + ').*$';
10049
10050 try {
10051 this.regexp = new RegExp(re, flags);
10052 } catch (ex) {
10053 this.regexp = false;
10054 }
10055 return this.regexp
10056}
10057
10058minimatch.match = function (list, pattern, options) {
10059 options = options || {};
10060 var mm = new Minimatch$1(pattern, options);
10061 list = list.filter(function (f) {
10062 return mm.match(f)
10063 });
10064 if (mm.options.nonull && !list.length) {
10065 list.push(pattern);
10066 }
10067 return list
10068};
10069
10070Minimatch$1.prototype.match = match;
10071function match (f, partial) {
10072 this.debug('match', f, this.pattern);
10073 // short-circuit in the case of busted things.
10074 // comments, etc.
10075 if (this.comment) return false
10076 if (this.empty) return f === ''
10077
10078 if (f === '/' && partial) return true
10079
10080 var options = this.options;
10081
10082 // windows: need to use /, not \
10083 if (path.sep !== '/') {
10084 f = f.split(path.sep).join('/');
10085 }
10086
10087 // treat the test path as a set of pathparts.
10088 f = f.split(slashSplit);
10089 this.debug(this.pattern, 'split', f);
10090
10091 // just ONE of the pattern sets in this.set needs to match
10092 // in order for it to be valid. If negating, then just one
10093 // match means that we have failed.
10094 // Either way, return on the first hit.
10095
10096 var set = this.set;
10097 this.debug(this.pattern, 'set', set);
10098
10099 // Find the basename of the path by looking for the last non-empty segment
10100 var filename;
10101 var i;
10102 for (i = f.length - 1; i >= 0; i--) {
10103 filename = f[i];
10104 if (filename) break
10105 }
10106
10107 for (i = 0; i < set.length; i++) {
10108 var pattern = set[i];
10109 var file = f;
10110 if (options.matchBase && pattern.length === 1) {
10111 file = [filename];
10112 }
10113 var hit = this.matchOne(file, pattern, partial);
10114 if (hit) {
10115 if (options.flipNegate) return true
10116 return !this.negate
10117 }
10118 }
10119
10120 // didn't get any hits. this is success if it's a negative
10121 // pattern, failure otherwise.
10122 if (options.flipNegate) return false
10123 return this.negate
10124}
10125
10126// set partial to true to test if, for example,
10127// "/a/b" matches the start of "/*/b/*/d"
10128// Partial means, if you run out of file before you run
10129// out of pattern, then that's fine, as long as all
10130// the parts match.
10131Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
10132 var options = this.options;
10133
10134 this.debug('matchOne',
10135 { 'this': this, file: file, pattern: pattern });
10136
10137 this.debug('matchOne', file.length, pattern.length);
10138
10139 for (var fi = 0,
10140 pi = 0,
10141 fl = file.length,
10142 pl = pattern.length
10143 ; (fi < fl) && (pi < pl)
10144 ; fi++, pi++) {
10145 this.debug('matchOne loop');
10146 var p = pattern[pi];
10147 var f = file[fi];
10148
10149 this.debug(pattern, p, f);
10150
10151 // should be impossible.
10152 // some invalid regexp stuff in the set.
10153 if (p === false) return false
10154
10155 if (p === GLOBSTAR) {
10156 this.debug('GLOBSTAR', [pattern, p, f]);
10157
10158 // "**"
10159 // a/**/b/**/c would match the following:
10160 // a/b/x/y/z/c
10161 // a/x/y/z/b/c
10162 // a/b/x/b/x/c
10163 // a/b/c
10164 // To do this, take the rest of the pattern after
10165 // the **, and see if it would match the file remainder.
10166 // If so, return success.
10167 // If not, the ** "swallows" a segment, and try again.
10168 // This is recursively awful.
10169 //
10170 // a/**/b/**/c matching a/b/x/y/z/c
10171 // - a matches a
10172 // - doublestar
10173 // - matchOne(b/x/y/z/c, b/**/c)
10174 // - b matches b
10175 // - doublestar
10176 // - matchOne(x/y/z/c, c) -> no
10177 // - matchOne(y/z/c, c) -> no
10178 // - matchOne(z/c, c) -> no
10179 // - matchOne(c, c) yes, hit
10180 var fr = fi;
10181 var pr = pi + 1;
10182 if (pr === pl) {
10183 this.debug('** at the end');
10184 // a ** at the end will just swallow the rest.
10185 // We have found a match.
10186 // however, it will not swallow /.x, unless
10187 // options.dot is set.
10188 // . and .. are *never* matched by **, for explosively
10189 // exponential reasons.
10190 for (; fi < fl; fi++) {
10191 if (file[fi] === '.' || file[fi] === '..' ||
10192 (!options.dot && file[fi].charAt(0) === '.')) return false
10193 }
10194 return true
10195 }
10196
10197 // ok, let's see if we can swallow whatever we can.
10198 while (fr < fl) {
10199 var swallowee = file[fr];
10200
10201 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
10202
10203 // XXX remove this slice. Just pass the start index.
10204 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
10205 this.debug('globstar found match!', fr, fl, swallowee);
10206 // found a match.
10207 return true
10208 } else {
10209 // can't swallow "." or ".." ever.
10210 // can only swallow ".foo" when explicitly asked.
10211 if (swallowee === '.' || swallowee === '..' ||
10212 (!options.dot && swallowee.charAt(0) === '.')) {
10213 this.debug('dot detected!', file, fr, pattern, pr);
10214 break
10215 }
10216
10217 // ** swallows a segment, and continue.
10218 this.debug('globstar swallow a segment, and continue');
10219 fr++;
10220 }
10221 }
10222
10223 // no match was found.
10224 // However, in partial mode, we can't say this is necessarily over.
10225 // If there's more *pattern* left, then
10226 if (partial) {
10227 // ran out of file
10228 this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
10229 if (fr === fl) return true
10230 }
10231 return false
10232 }
10233
10234 // something other than **
10235 // non-magic patterns just have to match exactly
10236 // patterns with magic have been turned into regexps.
10237 var hit;
10238 if (typeof p === 'string') {
10239 if (options.nocase) {
10240 hit = f.toLowerCase() === p.toLowerCase();
10241 } else {
10242 hit = f === p;
10243 }
10244 this.debug('string match', p, f, hit);
10245 } else {
10246 hit = f.match(p);
10247 this.debug('pattern match', p, f, hit);
10248 }
10249
10250 if (!hit) return false
10251 }
10252
10253 // Note: ending in / means that we'll get a final ""
10254 // at the end of the pattern. This can only match a
10255 // corresponding "" at the end of the file.
10256 // If the file ends in /, then it can only match a
10257 // a pattern that ends in /, unless the pattern just
10258 // doesn't have any more for it. But, a/b/ should *not*
10259 // match "a/b/*", even though "" matches against the
10260 // [^/]*? pattern, except in partial mode, where it might
10261 // simply not be reached yet.
10262 // However, a/b/ should still satisfy a/*
10263
10264 // now either we fell off the end of the pattern, or we're done.
10265 if (fi === fl && pi === pl) {
10266 // ran out of pattern and filename at the same time.
10267 // an exact hit!
10268 return true
10269 } else if (fi === fl) {
10270 // ran out of file, but still had pattern left.
10271 // this is ok if we're doing the match as part of
10272 // a glob fs traversal.
10273 return partial
10274 } else if (pi === pl) {
10275 // ran out of pattern, still have file left.
10276 // this is only acceptable if we're on the very last
10277 // empty segment of a file with a trailing slash.
10278 // a/* should match a/b/
10279 var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
10280 return emptyFileEnd
10281 }
10282
10283 // should be unreachable.
10284 throw new Error('wtf?')
10285};
10286
10287// replace stuff like \* with *
10288function globUnescape (s) {
10289 return s.replace(/\\(.)/g, '$1')
10290}
10291
10292function regExpEscape (s) {
10293 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
10294}
10295
10296var inherits_browser = createCommonjsModule(function (module) {
10297if (typeof Object.create === 'function') {
10298 // implementation from standard node.js 'util' module
10299 module.exports = function inherits(ctor, superCtor) {
10300 ctor.super_ = superCtor;
10301 ctor.prototype = Object.create(superCtor.prototype, {
10302 constructor: {
10303 value: ctor,
10304 enumerable: false,
10305 writable: true,
10306 configurable: true
10307 }
10308 });
10309 };
10310} else {
10311 // old school shim for old browsers
10312 module.exports = function inherits(ctor, superCtor) {
10313 ctor.super_ = superCtor;
10314 var TempCtor = function () {};
10315 TempCtor.prototype = superCtor.prototype;
10316 ctor.prototype = new TempCtor();
10317 ctor.prototype.constructor = ctor;
10318 };
10319}
10320});
10321
10322var inherits = createCommonjsModule(function (module) {
10323try {
10324 var util = util__default['default'];
10325 if (typeof util.inherits !== 'function') throw '';
10326 module.exports = util.inherits;
10327} catch (e) {
10328 module.exports = inherits_browser;
10329}
10330});
10331
10332function posix(path) {
10333 return path.charAt(0) === '/';
10334}
10335
10336function win32(path) {
10337 // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
10338 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
10339 var result = splitDeviceRe.exec(path);
10340 var device = result[1] || '';
10341 var isUnc = Boolean(device && device.charAt(1) !== ':');
10342
10343 // UNC paths are always absolute
10344 return Boolean(result[2] || isUnc);
10345}
10346
10347var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
10348var posix_1 = posix;
10349var win32_1 = win32;
10350pathIsAbsolute.posix = posix_1;
10351pathIsAbsolute.win32 = win32_1;
10352
10353var alphasort_1 = alphasort;
10354var alphasorti_1 = alphasorti;
10355var setopts_1 = setopts$2;
10356var ownProp_1 = ownProp$2;
10357var makeAbs_1 = makeAbs;
10358var finish_1 = finish;
10359var mark_1 = mark;
10360var isIgnored_1 = isIgnored$2;
10361var childrenIgnored_1 = childrenIgnored$2;
10362
10363function ownProp$2 (obj, field) {
10364 return Object.prototype.hasOwnProperty.call(obj, field)
10365}
10366
10367
10368
10369
10370var Minimatch = minimatch_1.Minimatch;
10371
10372function alphasorti (a, b) {
10373 return a.toLowerCase().localeCompare(b.toLowerCase())
10374}
10375
10376function alphasort (a, b) {
10377 return a.localeCompare(b)
10378}
10379
10380function setupIgnores (self, options) {
10381 self.ignore = options.ignore || [];
10382
10383 if (!Array.isArray(self.ignore))
10384 self.ignore = [self.ignore];
10385
10386 if (self.ignore.length) {
10387 self.ignore = self.ignore.map(ignoreMap);
10388 }
10389}
10390
10391// ignore patterns are always in dot:true mode.
10392function ignoreMap (pattern) {
10393 var gmatcher = null;
10394 if (pattern.slice(-3) === '/**') {
10395 var gpattern = pattern.replace(/(\/\*\*)+$/, '');
10396 gmatcher = new Minimatch(gpattern, { dot: true });
10397 }
10398
10399 return {
10400 matcher: new Minimatch(pattern, { dot: true }),
10401 gmatcher: gmatcher
10402 }
10403}
10404
10405function setopts$2 (self, pattern, options) {
10406 if (!options)
10407 options = {};
10408
10409 // base-matching: just use globstar for that.
10410 if (options.matchBase && -1 === pattern.indexOf("/")) {
10411 if (options.noglobstar) {
10412 throw new Error("base matching requires globstar")
10413 }
10414 pattern = "**/" + pattern;
10415 }
10416
10417 self.silent = !!options.silent;
10418 self.pattern = pattern;
10419 self.strict = options.strict !== false;
10420 self.realpath = !!options.realpath;
10421 self.realpathCache = options.realpathCache || Object.create(null);
10422 self.follow = !!options.follow;
10423 self.dot = !!options.dot;
10424 self.mark = !!options.mark;
10425 self.nodir = !!options.nodir;
10426 if (self.nodir)
10427 self.mark = true;
10428 self.sync = !!options.sync;
10429 self.nounique = !!options.nounique;
10430 self.nonull = !!options.nonull;
10431 self.nosort = !!options.nosort;
10432 self.nocase = !!options.nocase;
10433 self.stat = !!options.stat;
10434 self.noprocess = !!options.noprocess;
10435 self.absolute = !!options.absolute;
10436
10437 self.maxLength = options.maxLength || Infinity;
10438 self.cache = options.cache || Object.create(null);
10439 self.statCache = options.statCache || Object.create(null);
10440 self.symlinks = options.symlinks || Object.create(null);
10441
10442 setupIgnores(self, options);
10443
10444 self.changedCwd = false;
10445 var cwd = process.cwd();
10446 if (!ownProp$2(options, "cwd"))
10447 self.cwd = cwd;
10448 else {
10449 self.cwd = path__default['default'].resolve(options.cwd);
10450 self.changedCwd = self.cwd !== cwd;
10451 }
10452
10453 self.root = options.root || path__default['default'].resolve(self.cwd, "/");
10454 self.root = path__default['default'].resolve(self.root);
10455 if (process.platform === "win32")
10456 self.root = self.root.replace(/\\/g, "/");
10457
10458 // TODO: is an absolute `cwd` supposed to be resolved against `root`?
10459 // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
10460 self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
10461 if (process.platform === "win32")
10462 self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
10463 self.nomount = !!options.nomount;
10464
10465 // disable comments and negation in Minimatch.
10466 // Note that they are not supported in Glob itself anyway.
10467 options.nonegate = true;
10468 options.nocomment = true;
10469
10470 self.minimatch = new Minimatch(pattern, options);
10471 self.options = self.minimatch.options;
10472}
10473
10474function finish (self) {
10475 var nou = self.nounique;
10476 var all = nou ? [] : Object.create(null);
10477
10478 for (var i = 0, l = self.matches.length; i < l; i ++) {
10479 var matches = self.matches[i];
10480 if (!matches || Object.keys(matches).length === 0) {
10481 if (self.nonull) {
10482 // do like the shell, and spit out the literal glob
10483 var literal = self.minimatch.globSet[i];
10484 if (nou)
10485 all.push(literal);
10486 else
10487 all[literal] = true;
10488 }
10489 } else {
10490 // had matches
10491 var m = Object.keys(matches);
10492 if (nou)
10493 all.push.apply(all, m);
10494 else
10495 m.forEach(function (m) {
10496 all[m] = true;
10497 });
10498 }
10499 }
10500
10501 if (!nou)
10502 all = Object.keys(all);
10503
10504 if (!self.nosort)
10505 all = all.sort(self.nocase ? alphasorti : alphasort);
10506
10507 // at *some* point we statted all of these
10508 if (self.mark) {
10509 for (var i = 0; i < all.length; i++) {
10510 all[i] = self._mark(all[i]);
10511 }
10512 if (self.nodir) {
10513 all = all.filter(function (e) {
10514 var notDir = !(/\/$/.test(e));
10515 var c = self.cache[e] || self.cache[makeAbs(self, e)];
10516 if (notDir && c)
10517 notDir = c !== 'DIR' && !Array.isArray(c);
10518 return notDir
10519 });
10520 }
10521 }
10522
10523 if (self.ignore.length)
10524 all = all.filter(function(m) {
10525 return !isIgnored$2(self, m)
10526 });
10527
10528 self.found = all;
10529}
10530
10531function mark (self, p) {
10532 var abs = makeAbs(self, p);
10533 var c = self.cache[abs];
10534 var m = p;
10535 if (c) {
10536 var isDir = c === 'DIR' || Array.isArray(c);
10537 var slash = p.slice(-1) === '/';
10538
10539 if (isDir && !slash)
10540 m += '/';
10541 else if (!isDir && slash)
10542 m = m.slice(0, -1);
10543
10544 if (m !== p) {
10545 var mabs = makeAbs(self, m);
10546 self.statCache[mabs] = self.statCache[abs];
10547 self.cache[mabs] = self.cache[abs];
10548 }
10549 }
10550
10551 return m
10552}
10553
10554// lotta situps...
10555function makeAbs (self, f) {
10556 var abs = f;
10557 if (f.charAt(0) === '/') {
10558 abs = path__default['default'].join(self.root, f);
10559 } else if (pathIsAbsolute(f) || f === '') {
10560 abs = f;
10561 } else if (self.changedCwd) {
10562 abs = path__default['default'].resolve(self.cwd, f);
10563 } else {
10564 abs = path__default['default'].resolve(f);
10565 }
10566
10567 if (process.platform === 'win32')
10568 abs = abs.replace(/\\/g, '/');
10569
10570 return abs
10571}
10572
10573
10574// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
10575// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
10576function isIgnored$2 (self, path) {
10577 if (!self.ignore.length)
10578 return false
10579
10580 return self.ignore.some(function(item) {
10581 return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
10582 })
10583}
10584
10585function childrenIgnored$2 (self, path) {
10586 if (!self.ignore.length)
10587 return false
10588
10589 return self.ignore.some(function(item) {
10590 return !!(item.gmatcher && item.gmatcher.match(path))
10591 })
10592}
10593
10594var common$1 = {
10595 alphasort: alphasort_1,
10596 alphasorti: alphasorti_1,
10597 setopts: setopts_1,
10598 ownProp: ownProp_1,
10599 makeAbs: makeAbs_1,
10600 finish: finish_1,
10601 mark: mark_1,
10602 isIgnored: isIgnored_1,
10603 childrenIgnored: childrenIgnored_1
10604};
10605
10606var sync = globSync;
10607globSync.GlobSync = GlobSync$1;
10608var setopts$1 = common$1.setopts;
10609var ownProp$1 = common$1.ownProp;
10610var childrenIgnored$1 = common$1.childrenIgnored;
10611var isIgnored$1 = common$1.isIgnored;
10612
10613function globSync (pattern, options) {
10614 if (typeof options === 'function' || arguments.length === 3)
10615 throw new TypeError('callback provided to sync glob\n'+
10616 'See: https://github.com/isaacs/node-glob/issues/167')
10617
10618 return new GlobSync$1(pattern, options).found
10619}
10620
10621function GlobSync$1 (pattern, options) {
10622 if (!pattern)
10623 throw new Error('must provide pattern')
10624
10625 if (typeof options === 'function' || arguments.length === 3)
10626 throw new TypeError('callback provided to sync glob\n'+
10627 'See: https://github.com/isaacs/node-glob/issues/167')
10628
10629 if (!(this instanceof GlobSync$1))
10630 return new GlobSync$1(pattern, options)
10631
10632 setopts$1(this, pattern, options);
10633
10634 if (this.noprocess)
10635 return this
10636
10637 var n = this.minimatch.set.length;
10638 this.matches = new Array(n);
10639 for (var i = 0; i < n; i ++) {
10640 this._process(this.minimatch.set[i], i, false);
10641 }
10642 this._finish();
10643}
10644
10645GlobSync$1.prototype._finish = function () {
10646 assert__default['default'](this instanceof GlobSync$1);
10647 if (this.realpath) {
10648 var self = this;
10649 this.matches.forEach(function (matchset, index) {
10650 var set = self.matches[index] = Object.create(null);
10651 for (var p in matchset) {
10652 try {
10653 p = self._makeAbs(p);
10654 var real = fs_realpath.realpathSync(p, self.realpathCache);
10655 set[real] = true;
10656 } catch (er) {
10657 if (er.syscall === 'stat')
10658 set[self._makeAbs(p)] = true;
10659 else
10660 throw er
10661 }
10662 }
10663 });
10664 }
10665 common$1.finish(this);
10666};
10667
10668
10669GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
10670 assert__default['default'](this instanceof GlobSync$1);
10671
10672 // Get the first [n] parts of pattern that are all strings.
10673 var n = 0;
10674 while (typeof pattern[n] === 'string') {
10675 n ++;
10676 }
10677 // now n is the index of the first one that is *not* a string.
10678
10679 // See if there's anything else
10680 var prefix;
10681 switch (n) {
10682 // if not, then this is rather simple
10683 case pattern.length:
10684 this._processSimple(pattern.join('/'), index);
10685 return
10686
10687 case 0:
10688 // pattern *starts* with some non-trivial item.
10689 // going to readdir(cwd), but not include the prefix in matches.
10690 prefix = null;
10691 break
10692
10693 default:
10694 // pattern has some string bits in the front.
10695 // whatever it starts with, whether that's 'absolute' like /foo/bar,
10696 // or 'relative' like '../baz'
10697 prefix = pattern.slice(0, n).join('/');
10698 break
10699 }
10700
10701 var remain = pattern.slice(n);
10702
10703 // get the list of entries.
10704 var read;
10705 if (prefix === null)
10706 read = '.';
10707 else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
10708 if (!prefix || !pathIsAbsolute(prefix))
10709 prefix = '/' + prefix;
10710 read = prefix;
10711 } else
10712 read = prefix;
10713
10714 var abs = this._makeAbs(read);
10715
10716 //if ignored, skip processing
10717 if (childrenIgnored$1(this, read))
10718 return
10719
10720 var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
10721 if (isGlobStar)
10722 this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
10723 else
10724 this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
10725};
10726
10727
10728GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
10729 var entries = this._readdir(abs, inGlobStar);
10730
10731 // if the abs isn't a dir, then nothing can match!
10732 if (!entries)
10733 return
10734
10735 // It will only match dot entries if it starts with a dot, or if
10736 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
10737 var pn = remain[0];
10738 var negate = !!this.minimatch.negate;
10739 var rawGlob = pn._glob;
10740 var dotOk = this.dot || rawGlob.charAt(0) === '.';
10741
10742 var matchedEntries = [];
10743 for (var i = 0; i < entries.length; i++) {
10744 var e = entries[i];
10745 if (e.charAt(0) !== '.' || dotOk) {
10746 var m;
10747 if (negate && !prefix) {
10748 m = !e.match(pn);
10749 } else {
10750 m = e.match(pn);
10751 }
10752 if (m)
10753 matchedEntries.push(e);
10754 }
10755 }
10756
10757 var len = matchedEntries.length;
10758 // If there are no matched entries, then nothing matches.
10759 if (len === 0)
10760 return
10761
10762 // if this is the last remaining pattern bit, then no need for
10763 // an additional stat *unless* the user has specified mark or
10764 // stat explicitly. We know they exist, since readdir returned
10765 // them.
10766
10767 if (remain.length === 1 && !this.mark && !this.stat) {
10768 if (!this.matches[index])
10769 this.matches[index] = Object.create(null);
10770
10771 for (var i = 0; i < len; i ++) {
10772 var e = matchedEntries[i];
10773 if (prefix) {
10774 if (prefix.slice(-1) !== '/')
10775 e = prefix + '/' + e;
10776 else
10777 e = prefix + e;
10778 }
10779
10780 if (e.charAt(0) === '/' && !this.nomount) {
10781 e = path__default['default'].join(this.root, e);
10782 }
10783 this._emitMatch(index, e);
10784 }
10785 // This was the last one, and no stats were needed
10786 return
10787 }
10788
10789 // now test all matched entries as stand-ins for that part
10790 // of the pattern.
10791 remain.shift();
10792 for (var i = 0; i < len; i ++) {
10793 var e = matchedEntries[i];
10794 var newPattern;
10795 if (prefix)
10796 newPattern = [prefix, e];
10797 else
10798 newPattern = [e];
10799 this._process(newPattern.concat(remain), index, inGlobStar);
10800 }
10801};
10802
10803
10804GlobSync$1.prototype._emitMatch = function (index, e) {
10805 if (isIgnored$1(this, e))
10806 return
10807
10808 var abs = this._makeAbs(e);
10809
10810 if (this.mark)
10811 e = this._mark(e);
10812
10813 if (this.absolute) {
10814 e = abs;
10815 }
10816
10817 if (this.matches[index][e])
10818 return
10819
10820 if (this.nodir) {
10821 var c = this.cache[abs];
10822 if (c === 'DIR' || Array.isArray(c))
10823 return
10824 }
10825
10826 this.matches[index][e] = true;
10827
10828 if (this.stat)
10829 this._stat(e);
10830};
10831
10832
10833GlobSync$1.prototype._readdirInGlobStar = function (abs) {
10834 // follow all symlinked directories forever
10835 // just proceed as if this is a non-globstar situation
10836 if (this.follow)
10837 return this._readdir(abs, false)
10838
10839 var entries;
10840 var lstat;
10841 try {
10842 lstat = fs__default['default'].lstatSync(abs);
10843 } catch (er) {
10844 if (er.code === 'ENOENT') {
10845 // lstat failed, doesn't exist
10846 return null
10847 }
10848 }
10849
10850 var isSym = lstat && lstat.isSymbolicLink();
10851 this.symlinks[abs] = isSym;
10852
10853 // If it's not a symlink or a dir, then it's definitely a regular file.
10854 // don't bother doing a readdir in that case.
10855 if (!isSym && lstat && !lstat.isDirectory())
10856 this.cache[abs] = 'FILE';
10857 else
10858 entries = this._readdir(abs, false);
10859
10860 return entries
10861};
10862
10863GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
10864
10865 if (inGlobStar && !ownProp$1(this.symlinks, abs))
10866 return this._readdirInGlobStar(abs)
10867
10868 if (ownProp$1(this.cache, abs)) {
10869 var c = this.cache[abs];
10870 if (!c || c === 'FILE')
10871 return null
10872
10873 if (Array.isArray(c))
10874 return c
10875 }
10876
10877 try {
10878 return this._readdirEntries(abs, fs__default['default'].readdirSync(abs))
10879 } catch (er) {
10880 this._readdirError(abs, er);
10881 return null
10882 }
10883};
10884
10885GlobSync$1.prototype._readdirEntries = function (abs, entries) {
10886 // if we haven't asked to stat everything, then just
10887 // assume that everything in there exists, so we can avoid
10888 // having to stat it a second time.
10889 if (!this.mark && !this.stat) {
10890 for (var i = 0; i < entries.length; i ++) {
10891 var e = entries[i];
10892 if (abs === '/')
10893 e = abs + e;
10894 else
10895 e = abs + '/' + e;
10896 this.cache[e] = true;
10897 }
10898 }
10899
10900 this.cache[abs] = entries;
10901
10902 // mark and cache dir-ness
10903 return entries
10904};
10905
10906GlobSync$1.prototype._readdirError = function (f, er) {
10907 // handle errors, and cache the information
10908 switch (er.code) {
10909 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
10910 case 'ENOTDIR': // totally normal. means it *does* exist.
10911 var abs = this._makeAbs(f);
10912 this.cache[abs] = 'FILE';
10913 if (abs === this.cwdAbs) {
10914 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
10915 error.path = this.cwd;
10916 error.code = er.code;
10917 throw error
10918 }
10919 break
10920
10921 case 'ENOENT': // not terribly unusual
10922 case 'ELOOP':
10923 case 'ENAMETOOLONG':
10924 case 'UNKNOWN':
10925 this.cache[this._makeAbs(f)] = false;
10926 break
10927
10928 default: // some unusual error. Treat as failure.
10929 this.cache[this._makeAbs(f)] = false;
10930 if (this.strict)
10931 throw er
10932 if (!this.silent)
10933 console.error('glob error', er);
10934 break
10935 }
10936};
10937
10938GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
10939
10940 var entries = this._readdir(abs, inGlobStar);
10941
10942 // no entries means not a dir, so it can never have matches
10943 // foo.txt/** doesn't match foo.txt
10944 if (!entries)
10945 return
10946
10947 // test without the globstar, and with every child both below
10948 // and replacing the globstar.
10949 var remainWithoutGlobStar = remain.slice(1);
10950 var gspref = prefix ? [ prefix ] : [];
10951 var noGlobStar = gspref.concat(remainWithoutGlobStar);
10952
10953 // the noGlobStar pattern exits the inGlobStar state
10954 this._process(noGlobStar, index, false);
10955
10956 var len = entries.length;
10957 var isSym = this.symlinks[abs];
10958
10959 // If it's a symlink, and we're in a globstar, then stop
10960 if (isSym && inGlobStar)
10961 return
10962
10963 for (var i = 0; i < len; i++) {
10964 var e = entries[i];
10965 if (e.charAt(0) === '.' && !this.dot)
10966 continue
10967
10968 // these two cases enter the inGlobStar state
10969 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
10970 this._process(instead, index, true);
10971
10972 var below = gspref.concat(entries[i], remain);
10973 this._process(below, index, true);
10974 }
10975};
10976
10977GlobSync$1.prototype._processSimple = function (prefix, index) {
10978 // XXX review this. Shouldn't it be doing the mounting etc
10979 // before doing stat? kinda weird?
10980 var exists = this._stat(prefix);
10981
10982 if (!this.matches[index])
10983 this.matches[index] = Object.create(null);
10984
10985 // If it doesn't exist, then just mark the lack of results
10986 if (!exists)
10987 return
10988
10989 if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
10990 var trail = /[\/\\]$/.test(prefix);
10991 if (prefix.charAt(0) === '/') {
10992 prefix = path__default['default'].join(this.root, prefix);
10993 } else {
10994 prefix = path__default['default'].resolve(this.root, prefix);
10995 if (trail)
10996 prefix += '/';
10997 }
10998 }
10999
11000 if (process.platform === 'win32')
11001 prefix = prefix.replace(/\\/g, '/');
11002
11003 // Mark this as a match
11004 this._emitMatch(index, prefix);
11005};
11006
11007// Returns either 'DIR', 'FILE', or false
11008GlobSync$1.prototype._stat = function (f) {
11009 var abs = this._makeAbs(f);
11010 var needDir = f.slice(-1) === '/';
11011
11012 if (f.length > this.maxLength)
11013 return false
11014
11015 if (!this.stat && ownProp$1(this.cache, abs)) {
11016 var c = this.cache[abs];
11017
11018 if (Array.isArray(c))
11019 c = 'DIR';
11020
11021 // It exists, but maybe not how we need it
11022 if (!needDir || c === 'DIR')
11023 return c
11024
11025 if (needDir && c === 'FILE')
11026 return false
11027
11028 // otherwise we have to stat, because maybe c=true
11029 // if we know it exists, but not what it is.
11030 }
11031 var stat = this.statCache[abs];
11032 if (!stat) {
11033 var lstat;
11034 try {
11035 lstat = fs__default['default'].lstatSync(abs);
11036 } catch (er) {
11037 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
11038 this.statCache[abs] = false;
11039 return false
11040 }
11041 }
11042
11043 if (lstat && lstat.isSymbolicLink()) {
11044 try {
11045 stat = fs__default['default'].statSync(abs);
11046 } catch (er) {
11047 stat = lstat;
11048 }
11049 } else {
11050 stat = lstat;
11051 }
11052 }
11053
11054 this.statCache[abs] = stat;
11055
11056 var c = true;
11057 if (stat)
11058 c = stat.isDirectory() ? 'DIR' : 'FILE';
11059
11060 this.cache[abs] = this.cache[abs] || c;
11061
11062 if (needDir && c === 'FILE')
11063 return false
11064
11065 return c
11066};
11067
11068GlobSync$1.prototype._mark = function (p) {
11069 return common$1.mark(this, p)
11070};
11071
11072GlobSync$1.prototype._makeAbs = function (f) {
11073 return common$1.makeAbs(this, f)
11074};
11075
11076// Returns a wrapper function that returns a wrapped callback
11077// The wrapper function should do some stuff, and return a
11078// presumably different callback function.
11079// This makes sure that own properties are retained, so that
11080// decorations and such are not lost along the way.
11081var wrappy_1 = wrappy;
11082function wrappy (fn, cb) {
11083 if (fn && cb) return wrappy(fn)(cb)
11084
11085 if (typeof fn !== 'function')
11086 throw new TypeError('need wrapper function')
11087
11088 Object.keys(fn).forEach(function (k) {
11089 wrapper[k] = fn[k];
11090 });
11091
11092 return wrapper
11093
11094 function wrapper() {
11095 var args = new Array(arguments.length);
11096 for (var i = 0; i < args.length; i++) {
11097 args[i] = arguments[i];
11098 }
11099 var ret = fn.apply(this, args);
11100 var cb = args[args.length-1];
11101 if (typeof ret === 'function' && ret !== cb) {
11102 Object.keys(cb).forEach(function (k) {
11103 ret[k] = cb[k];
11104 });
11105 }
11106 return ret
11107 }
11108}
11109
11110var once_1 = wrappy_1(once);
11111var strict = wrappy_1(onceStrict);
11112
11113once.proto = once(function () {
11114 Object.defineProperty(Function.prototype, 'once', {
11115 value: function () {
11116 return once(this)
11117 },
11118 configurable: true
11119 });
11120
11121 Object.defineProperty(Function.prototype, 'onceStrict', {
11122 value: function () {
11123 return onceStrict(this)
11124 },
11125 configurable: true
11126 });
11127});
11128
11129function once (fn) {
11130 var f = function () {
11131 if (f.called) return f.value
11132 f.called = true;
11133 return f.value = fn.apply(this, arguments)
11134 };
11135 f.called = false;
11136 return f
11137}
11138
11139function onceStrict (fn) {
11140 var f = function () {
11141 if (f.called)
11142 throw new Error(f.onceError)
11143 f.called = true;
11144 return f.value = fn.apply(this, arguments)
11145 };
11146 var name = fn.name || 'Function wrapped with `once`';
11147 f.onceError = name + " shouldn't be called more than once";
11148 f.called = false;
11149 return f
11150}
11151once_1.strict = strict;
11152
11153var reqs = Object.create(null);
11154
11155
11156var inflight_1 = wrappy_1(inflight);
11157
11158function inflight (key, cb) {
11159 if (reqs[key]) {
11160 reqs[key].push(cb);
11161 return null
11162 } else {
11163 reqs[key] = [cb];
11164 return makeres(key)
11165 }
11166}
11167
11168function makeres (key) {
11169 return once_1(function RES () {
11170 var cbs = reqs[key];
11171 var len = cbs.length;
11172 var args = slice(arguments);
11173
11174 // XXX It's somewhat ambiguous whether a new callback added in this
11175 // pass should be queued for later execution if something in the
11176 // list of callbacks throws, or if it should just be discarded.
11177 // However, it's such an edge case that it hardly matters, and either
11178 // choice is likely as surprising as the other.
11179 // As it happens, we do go ahead and schedule it for later execution.
11180 try {
11181 for (var i = 0; i < len; i++) {
11182 cbs[i].apply(null, args);
11183 }
11184 } finally {
11185 if (cbs.length > len) {
11186 // added more in the interim.
11187 // de-zalgo, just in case, but don't call again.
11188 cbs.splice(0, len);
11189 process.nextTick(function () {
11190 RES.apply(null, args);
11191 });
11192 } else {
11193 delete reqs[key];
11194 }
11195 }
11196 })
11197}
11198
11199function slice (args) {
11200 var length = args.length;
11201 var array = [];
11202
11203 for (var i = 0; i < length; i++) array[i] = args[i];
11204 return array
11205}
11206
11207// Approach:
11208//
11209// 1. Get the minimatch set
11210// 2. For each pattern in the set, PROCESS(pattern, false)
11211// 3. Store matches per-set, then uniq them
11212//
11213// PROCESS(pattern, inGlobStar)
11214// Get the first [n] items from pattern that are all strings
11215// Join these together. This is PREFIX.
11216// If there is no more remaining, then stat(PREFIX) and
11217// add to matches if it succeeds. END.
11218//
11219// If inGlobStar and PREFIX is symlink and points to dir
11220// set ENTRIES = []
11221// else readdir(PREFIX) as ENTRIES
11222// If fail, END
11223//
11224// with ENTRIES
11225// If pattern[n] is GLOBSTAR
11226// // handle the case where the globstar match is empty
11227// // by pruning it out, and testing the resulting pattern
11228// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
11229// // handle other cases.
11230// for ENTRY in ENTRIES (not dotfiles)
11231// // attach globstar + tail onto the entry
11232// // Mark that this entry is a globstar match
11233// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
11234//
11235// else // not globstar
11236// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
11237// Test ENTRY against pattern[n]
11238// If fails, continue
11239// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
11240//
11241// Caveat:
11242// Cache all stats and readdirs results to minimize syscall. Since all
11243// we ever care about is existence and directory-ness, we can just keep
11244// `true` for files, and [children,...] for directories, or `false` for
11245// things that don't exist.
11246
11247var glob_1 = glob$1;
11248
11249var EE = Events__default['default'].EventEmitter;
11250var setopts = common$1.setopts;
11251var ownProp = common$1.ownProp;
11252
11253
11254var childrenIgnored = common$1.childrenIgnored;
11255var isIgnored = common$1.isIgnored;
11256
11257
11258
11259function glob$1 (pattern, options, cb) {
11260 if (typeof options === 'function') cb = options, options = {};
11261 if (!options) options = {};
11262
11263 if (options.sync) {
11264 if (cb)
11265 throw new TypeError('callback provided to sync glob')
11266 return sync(pattern, options)
11267 }
11268
11269 return new Glob(pattern, options, cb)
11270}
11271
11272glob$1.sync = sync;
11273var GlobSync = glob$1.GlobSync = sync.GlobSync;
11274
11275// old api surface
11276glob$1.glob = glob$1;
11277
11278function extend (origin, add) {
11279 if (add === null || typeof add !== 'object') {
11280 return origin
11281 }
11282
11283 var keys = Object.keys(add);
11284 var i = keys.length;
11285 while (i--) {
11286 origin[keys[i]] = add[keys[i]];
11287 }
11288 return origin
11289}
11290
11291glob$1.hasMagic = function (pattern, options_) {
11292 var options = extend({}, options_);
11293 options.noprocess = true;
11294
11295 var g = new Glob(pattern, options);
11296 var set = g.minimatch.set;
11297
11298 if (!pattern)
11299 return false
11300
11301 if (set.length > 1)
11302 return true
11303
11304 for (var j = 0; j < set[0].length; j++) {
11305 if (typeof set[0][j] !== 'string')
11306 return true
11307 }
11308
11309 return false
11310};
11311
11312glob$1.Glob = Glob;
11313inherits(Glob, EE);
11314function Glob (pattern, options, cb) {
11315 if (typeof options === 'function') {
11316 cb = options;
11317 options = null;
11318 }
11319
11320 if (options && options.sync) {
11321 if (cb)
11322 throw new TypeError('callback provided to sync glob')
11323 return new GlobSync(pattern, options)
11324 }
11325
11326 if (!(this instanceof Glob))
11327 return new Glob(pattern, options, cb)
11328
11329 setopts(this, pattern, options);
11330 this._didRealPath = false;
11331
11332 // process each pattern in the minimatch set
11333 var n = this.minimatch.set.length;
11334
11335 // The matches are stored as {<filename>: true,...} so that
11336 // duplicates are automagically pruned.
11337 // Later, we do an Object.keys() on these.
11338 // Keep them as a list so we can fill in when nonull is set.
11339 this.matches = new Array(n);
11340
11341 if (typeof cb === 'function') {
11342 cb = once_1(cb);
11343 this.on('error', cb);
11344 this.on('end', function (matches) {
11345 cb(null, matches);
11346 });
11347 }
11348
11349 var self = this;
11350 this._processing = 0;
11351
11352 this._emitQueue = [];
11353 this._processQueue = [];
11354 this.paused = false;
11355
11356 if (this.noprocess)
11357 return this
11358
11359 if (n === 0)
11360 return done()
11361
11362 var sync = true;
11363 for (var i = 0; i < n; i ++) {
11364 this._process(this.minimatch.set[i], i, false, done);
11365 }
11366 sync = false;
11367
11368 function done () {
11369 --self._processing;
11370 if (self._processing <= 0) {
11371 if (sync) {
11372 process.nextTick(function () {
11373 self._finish();
11374 });
11375 } else {
11376 self._finish();
11377 }
11378 }
11379 }
11380}
11381
11382Glob.prototype._finish = function () {
11383 assert__default['default'](this instanceof Glob);
11384 if (this.aborted)
11385 return
11386
11387 if (this.realpath && !this._didRealpath)
11388 return this._realpath()
11389
11390 common$1.finish(this);
11391 this.emit('end', this.found);
11392};
11393
11394Glob.prototype._realpath = function () {
11395 if (this._didRealpath)
11396 return
11397
11398 this._didRealpath = true;
11399
11400 var n = this.matches.length;
11401 if (n === 0)
11402 return this._finish()
11403
11404 var self = this;
11405 for (var i = 0; i < this.matches.length; i++)
11406 this._realpathSet(i, next);
11407
11408 function next () {
11409 if (--n === 0)
11410 self._finish();
11411 }
11412};
11413
11414Glob.prototype._realpathSet = function (index, cb) {
11415 var matchset = this.matches[index];
11416 if (!matchset)
11417 return cb()
11418
11419 var found = Object.keys(matchset);
11420 var self = this;
11421 var n = found.length;
11422
11423 if (n === 0)
11424 return cb()
11425
11426 var set = this.matches[index] = Object.create(null);
11427 found.forEach(function (p, i) {
11428 // If there's a problem with the stat, then it means that
11429 // one or more of the links in the realpath couldn't be
11430 // resolved. just return the abs value in that case.
11431 p = self._makeAbs(p);
11432 fs_realpath.realpath(p, self.realpathCache, function (er, real) {
11433 if (!er)
11434 set[real] = true;
11435 else if (er.syscall === 'stat')
11436 set[p] = true;
11437 else
11438 self.emit('error', er); // srsly wtf right here
11439
11440 if (--n === 0) {
11441 self.matches[index] = set;
11442 cb();
11443 }
11444 });
11445 });
11446};
11447
11448Glob.prototype._mark = function (p) {
11449 return common$1.mark(this, p)
11450};
11451
11452Glob.prototype._makeAbs = function (f) {
11453 return common$1.makeAbs(this, f)
11454};
11455
11456Glob.prototype.abort = function () {
11457 this.aborted = true;
11458 this.emit('abort');
11459};
11460
11461Glob.prototype.pause = function () {
11462 if (!this.paused) {
11463 this.paused = true;
11464 this.emit('pause');
11465 }
11466};
11467
11468Glob.prototype.resume = function () {
11469 if (this.paused) {
11470 this.emit('resume');
11471 this.paused = false;
11472 if (this._emitQueue.length) {
11473 var eq = this._emitQueue.slice(0);
11474 this._emitQueue.length = 0;
11475 for (var i = 0; i < eq.length; i ++) {
11476 var e = eq[i];
11477 this._emitMatch(e[0], e[1]);
11478 }
11479 }
11480 if (this._processQueue.length) {
11481 var pq = this._processQueue.slice(0);
11482 this._processQueue.length = 0;
11483 for (var i = 0; i < pq.length; i ++) {
11484 var p = pq[i];
11485 this._processing--;
11486 this._process(p[0], p[1], p[2], p[3]);
11487 }
11488 }
11489 }
11490};
11491
11492Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
11493 assert__default['default'](this instanceof Glob);
11494 assert__default['default'](typeof cb === 'function');
11495
11496 if (this.aborted)
11497 return
11498
11499 this._processing++;
11500 if (this.paused) {
11501 this._processQueue.push([pattern, index, inGlobStar, cb]);
11502 return
11503 }
11504
11505 //console.error('PROCESS %d', this._processing, pattern)
11506
11507 // Get the first [n] parts of pattern that are all strings.
11508 var n = 0;
11509 while (typeof pattern[n] === 'string') {
11510 n ++;
11511 }
11512 // now n is the index of the first one that is *not* a string.
11513
11514 // see if there's anything else
11515 var prefix;
11516 switch (n) {
11517 // if not, then this is rather simple
11518 case pattern.length:
11519 this._processSimple(pattern.join('/'), index, cb);
11520 return
11521
11522 case 0:
11523 // pattern *starts* with some non-trivial item.
11524 // going to readdir(cwd), but not include the prefix in matches.
11525 prefix = null;
11526 break
11527
11528 default:
11529 // pattern has some string bits in the front.
11530 // whatever it starts with, whether that's 'absolute' like /foo/bar,
11531 // or 'relative' like '../baz'
11532 prefix = pattern.slice(0, n).join('/');
11533 break
11534 }
11535
11536 var remain = pattern.slice(n);
11537
11538 // get the list of entries.
11539 var read;
11540 if (prefix === null)
11541 read = '.';
11542 else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
11543 if (!prefix || !pathIsAbsolute(prefix))
11544 prefix = '/' + prefix;
11545 read = prefix;
11546 } else
11547 read = prefix;
11548
11549 var abs = this._makeAbs(read);
11550
11551 //if ignored, skip _processing
11552 if (childrenIgnored(this, read))
11553 return cb()
11554
11555 var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
11556 if (isGlobStar)
11557 this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
11558 else
11559 this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
11560};
11561
11562Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
11563 var self = this;
11564 this._readdir(abs, inGlobStar, function (er, entries) {
11565 return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
11566 });
11567};
11568
11569Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
11570
11571 // if the abs isn't a dir, then nothing can match!
11572 if (!entries)
11573 return cb()
11574
11575 // It will only match dot entries if it starts with a dot, or if
11576 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
11577 var pn = remain[0];
11578 var negate = !!this.minimatch.negate;
11579 var rawGlob = pn._glob;
11580 var dotOk = this.dot || rawGlob.charAt(0) === '.';
11581
11582 var matchedEntries = [];
11583 for (var i = 0; i < entries.length; i++) {
11584 var e = entries[i];
11585 if (e.charAt(0) !== '.' || dotOk) {
11586 var m;
11587 if (negate && !prefix) {
11588 m = !e.match(pn);
11589 } else {
11590 m = e.match(pn);
11591 }
11592 if (m)
11593 matchedEntries.push(e);
11594 }
11595 }
11596
11597 //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
11598
11599 var len = matchedEntries.length;
11600 // If there are no matched entries, then nothing matches.
11601 if (len === 0)
11602 return cb()
11603
11604 // if this is the last remaining pattern bit, then no need for
11605 // an additional stat *unless* the user has specified mark or
11606 // stat explicitly. We know they exist, since readdir returned
11607 // them.
11608
11609 if (remain.length === 1 && !this.mark && !this.stat) {
11610 if (!this.matches[index])
11611 this.matches[index] = Object.create(null);
11612
11613 for (var i = 0; i < len; i ++) {
11614 var e = matchedEntries[i];
11615 if (prefix) {
11616 if (prefix !== '/')
11617 e = prefix + '/' + e;
11618 else
11619 e = prefix + e;
11620 }
11621
11622 if (e.charAt(0) === '/' && !this.nomount) {
11623 e = path__default['default'].join(this.root, e);
11624 }
11625 this._emitMatch(index, e);
11626 }
11627 // This was the last one, and no stats were needed
11628 return cb()
11629 }
11630
11631 // now test all matched entries as stand-ins for that part
11632 // of the pattern.
11633 remain.shift();
11634 for (var i = 0; i < len; i ++) {
11635 var e = matchedEntries[i];
11636 if (prefix) {
11637 if (prefix !== '/')
11638 e = prefix + '/' + e;
11639 else
11640 e = prefix + e;
11641 }
11642 this._process([e].concat(remain), index, inGlobStar, cb);
11643 }
11644 cb();
11645};
11646
11647Glob.prototype._emitMatch = function (index, e) {
11648 if (this.aborted)
11649 return
11650
11651 if (isIgnored(this, e))
11652 return
11653
11654 if (this.paused) {
11655 this._emitQueue.push([index, e]);
11656 return
11657 }
11658
11659 var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
11660
11661 if (this.mark)
11662 e = this._mark(e);
11663
11664 if (this.absolute)
11665 e = abs;
11666
11667 if (this.matches[index][e])
11668 return
11669
11670 if (this.nodir) {
11671 var c = this.cache[abs];
11672 if (c === 'DIR' || Array.isArray(c))
11673 return
11674 }
11675
11676 this.matches[index][e] = true;
11677
11678 var st = this.statCache[abs];
11679 if (st)
11680 this.emit('stat', e, st);
11681
11682 this.emit('match', e);
11683};
11684
11685Glob.prototype._readdirInGlobStar = function (abs, cb) {
11686 if (this.aborted)
11687 return
11688
11689 // follow all symlinked directories forever
11690 // just proceed as if this is a non-globstar situation
11691 if (this.follow)
11692 return this._readdir(abs, false, cb)
11693
11694 var lstatkey = 'lstat\0' + abs;
11695 var self = this;
11696 var lstatcb = inflight_1(lstatkey, lstatcb_);
11697
11698 if (lstatcb)
11699 fs__default['default'].lstat(abs, lstatcb);
11700
11701 function lstatcb_ (er, lstat) {
11702 if (er && er.code === 'ENOENT')
11703 return cb()
11704
11705 var isSym = lstat && lstat.isSymbolicLink();
11706 self.symlinks[abs] = isSym;
11707
11708 // If it's not a symlink or a dir, then it's definitely a regular file.
11709 // don't bother doing a readdir in that case.
11710 if (!isSym && lstat && !lstat.isDirectory()) {
11711 self.cache[abs] = 'FILE';
11712 cb();
11713 } else
11714 self._readdir(abs, false, cb);
11715 }
11716};
11717
11718Glob.prototype._readdir = function (abs, inGlobStar, cb) {
11719 if (this.aborted)
11720 return
11721
11722 cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb);
11723 if (!cb)
11724 return
11725
11726 //console.error('RD %j %j', +inGlobStar, abs)
11727 if (inGlobStar && !ownProp(this.symlinks, abs))
11728 return this._readdirInGlobStar(abs, cb)
11729
11730 if (ownProp(this.cache, abs)) {
11731 var c = this.cache[abs];
11732 if (!c || c === 'FILE')
11733 return cb()
11734
11735 if (Array.isArray(c))
11736 return cb(null, c)
11737 }
11738 fs__default['default'].readdir(abs, readdirCb(this, abs, cb));
11739};
11740
11741function readdirCb (self, abs, cb) {
11742 return function (er, entries) {
11743 if (er)
11744 self._readdirError(abs, er, cb);
11745 else
11746 self._readdirEntries(abs, entries, cb);
11747 }
11748}
11749
11750Glob.prototype._readdirEntries = function (abs, entries, cb) {
11751 if (this.aborted)
11752 return
11753
11754 // if we haven't asked to stat everything, then just
11755 // assume that everything in there exists, so we can avoid
11756 // having to stat it a second time.
11757 if (!this.mark && !this.stat) {
11758 for (var i = 0; i < entries.length; i ++) {
11759 var e = entries[i];
11760 if (abs === '/')
11761 e = abs + e;
11762 else
11763 e = abs + '/' + e;
11764 this.cache[e] = true;
11765 }
11766 }
11767
11768 this.cache[abs] = entries;
11769 return cb(null, entries)
11770};
11771
11772Glob.prototype._readdirError = function (f, er, cb) {
11773 if (this.aborted)
11774 return
11775
11776 // handle errors, and cache the information
11777 switch (er.code) {
11778 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
11779 case 'ENOTDIR': // totally normal. means it *does* exist.
11780 var abs = this._makeAbs(f);
11781 this.cache[abs] = 'FILE';
11782 if (abs === this.cwdAbs) {
11783 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
11784 error.path = this.cwd;
11785 error.code = er.code;
11786 this.emit('error', error);
11787 this.abort();
11788 }
11789 break
11790
11791 case 'ENOENT': // not terribly unusual
11792 case 'ELOOP':
11793 case 'ENAMETOOLONG':
11794 case 'UNKNOWN':
11795 this.cache[this._makeAbs(f)] = false;
11796 break
11797
11798 default: // some unusual error. Treat as failure.
11799 this.cache[this._makeAbs(f)] = false;
11800 if (this.strict) {
11801 this.emit('error', er);
11802 // If the error is handled, then we abort
11803 // if not, we threw out of here
11804 this.abort();
11805 }
11806 if (!this.silent)
11807 console.error('glob error', er);
11808 break
11809 }
11810
11811 return cb()
11812};
11813
11814Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
11815 var self = this;
11816 this._readdir(abs, inGlobStar, function (er, entries) {
11817 self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
11818 });
11819};
11820
11821
11822Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
11823 //console.error('pgs2', prefix, remain[0], entries)
11824
11825 // no entries means not a dir, so it can never have matches
11826 // foo.txt/** doesn't match foo.txt
11827 if (!entries)
11828 return cb()
11829
11830 // test without the globstar, and with every child both below
11831 // and replacing the globstar.
11832 var remainWithoutGlobStar = remain.slice(1);
11833 var gspref = prefix ? [ prefix ] : [];
11834 var noGlobStar = gspref.concat(remainWithoutGlobStar);
11835
11836 // the noGlobStar pattern exits the inGlobStar state
11837 this._process(noGlobStar, index, false, cb);
11838
11839 var isSym = this.symlinks[abs];
11840 var len = entries.length;
11841
11842 // If it's a symlink, and we're in a globstar, then stop
11843 if (isSym && inGlobStar)
11844 return cb()
11845
11846 for (var i = 0; i < len; i++) {
11847 var e = entries[i];
11848 if (e.charAt(0) === '.' && !this.dot)
11849 continue
11850
11851 // these two cases enter the inGlobStar state
11852 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
11853 this._process(instead, index, true, cb);
11854
11855 var below = gspref.concat(entries[i], remain);
11856 this._process(below, index, true, cb);
11857 }
11858
11859 cb();
11860};
11861
11862Glob.prototype._processSimple = function (prefix, index, cb) {
11863 // XXX review this. Shouldn't it be doing the mounting etc
11864 // before doing stat? kinda weird?
11865 var self = this;
11866 this._stat(prefix, function (er, exists) {
11867 self._processSimple2(prefix, index, er, exists, cb);
11868 });
11869};
11870Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
11871
11872 //console.error('ps2', prefix, exists)
11873
11874 if (!this.matches[index])
11875 this.matches[index] = Object.create(null);
11876
11877 // If it doesn't exist, then just mark the lack of results
11878 if (!exists)
11879 return cb()
11880
11881 if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
11882 var trail = /[\/\\]$/.test(prefix);
11883 if (prefix.charAt(0) === '/') {
11884 prefix = path__default['default'].join(this.root, prefix);
11885 } else {
11886 prefix = path__default['default'].resolve(this.root, prefix);
11887 if (trail)
11888 prefix += '/';
11889 }
11890 }
11891
11892 if (process.platform === 'win32')
11893 prefix = prefix.replace(/\\/g, '/');
11894
11895 // Mark this as a match
11896 this._emitMatch(index, prefix);
11897 cb();
11898};
11899
11900// Returns either 'DIR', 'FILE', or false
11901Glob.prototype._stat = function (f, cb) {
11902 var abs = this._makeAbs(f);
11903 var needDir = f.slice(-1) === '/';
11904
11905 if (f.length > this.maxLength)
11906 return cb()
11907
11908 if (!this.stat && ownProp(this.cache, abs)) {
11909 var c = this.cache[abs];
11910
11911 if (Array.isArray(c))
11912 c = 'DIR';
11913
11914 // It exists, but maybe not how we need it
11915 if (!needDir || c === 'DIR')
11916 return cb(null, c)
11917
11918 if (needDir && c === 'FILE')
11919 return cb()
11920
11921 // otherwise we have to stat, because maybe c=true
11922 // if we know it exists, but not what it is.
11923 }
11924 var stat = this.statCache[abs];
11925 if (stat !== undefined) {
11926 if (stat === false)
11927 return cb(null, stat)
11928 else {
11929 var type = stat.isDirectory() ? 'DIR' : 'FILE';
11930 if (needDir && type === 'FILE')
11931 return cb()
11932 else
11933 return cb(null, type, stat)
11934 }
11935 }
11936
11937 var self = this;
11938 var statcb = inflight_1('stat\0' + abs, lstatcb_);
11939 if (statcb)
11940 fs__default['default'].lstat(abs, statcb);
11941
11942 function lstatcb_ (er, lstat) {
11943 if (lstat && lstat.isSymbolicLink()) {
11944 // If it's a symlink, then treat it as the target, unless
11945 // the target does not exist, then treat it as a file.
11946 return fs__default['default'].stat(abs, function (er, stat) {
11947 if (er)
11948 self._stat2(f, abs, null, lstat, cb);
11949 else
11950 self._stat2(f, abs, er, stat, cb);
11951 })
11952 } else {
11953 self._stat2(f, abs, er, lstat, cb);
11954 }
11955 }
11956};
11957
11958Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
11959 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
11960 this.statCache[abs] = false;
11961 return cb()
11962 }
11963
11964 var needDir = f.slice(-1) === '/';
11965 this.statCache[abs] = stat;
11966
11967 if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
11968 return cb(null, false, stat)
11969
11970 var c = true;
11971 if (stat)
11972 c = stat.isDirectory() ? 'DIR' : 'FILE';
11973 this.cache[abs] = this.cache[abs] || c;
11974
11975 if (needDir && c === 'FILE')
11976 return cb()
11977
11978 return cb(null, c, stat)
11979};
11980
11981var rimraf_1 = rimraf;
11982rimraf.sync = rimrafSync$1;
11983
11984
11985
11986
11987var glob = undefined;
11988try {
11989 glob = glob_1;
11990} catch (_err) {
11991 // treat glob as optional.
11992}
11993var _0666 = parseInt('666', 8);
11994
11995var defaultGlobOpts = {
11996 nosort: true,
11997 silent: true
11998};
11999
12000// for EMFILE handling
12001var timeout = 0;
12002
12003var isWindows = (process.platform === "win32");
12004
12005function defaults (options) {
12006 var methods = [
12007 'unlink',
12008 'chmod',
12009 'stat',
12010 'lstat',
12011 'rmdir',
12012 'readdir'
12013 ];
12014 methods.forEach(function(m) {
12015 options[m] = options[m] || fs__default['default'][m];
12016 m = m + 'Sync';
12017 options[m] = options[m] || fs__default['default'][m];
12018 });
12019
12020 options.maxBusyTries = options.maxBusyTries || 3;
12021 options.emfileWait = options.emfileWait || 1000;
12022 if (options.glob === false) {
12023 options.disableGlob = true;
12024 }
12025 if (options.disableGlob !== true && glob === undefined) {
12026 throw Error('glob dependency not found, set `options.disableGlob = true` if intentional')
12027 }
12028 options.disableGlob = options.disableGlob || false;
12029 options.glob = options.glob || defaultGlobOpts;
12030}
12031
12032function rimraf (p, options, cb) {
12033 if (typeof options === 'function') {
12034 cb = options;
12035 options = {};
12036 }
12037
12038 assert__default['default'](p, 'rimraf: missing path');
12039 assert__default['default'].equal(typeof p, 'string', 'rimraf: path should be a string');
12040 assert__default['default'].equal(typeof cb, 'function', 'rimraf: callback function required');
12041 assert__default['default'](options, 'rimraf: invalid options argument provided');
12042 assert__default['default'].equal(typeof options, 'object', 'rimraf: options should be object');
12043
12044 defaults(options);
12045
12046 var busyTries = 0;
12047 var errState = null;
12048 var n = 0;
12049
12050 if (options.disableGlob || !glob.hasMagic(p))
12051 return afterGlob(null, [p])
12052
12053 options.lstat(p, function (er, stat) {
12054 if (!er)
12055 return afterGlob(null, [p])
12056
12057 glob(p, options.glob, afterGlob);
12058 });
12059
12060 function next (er) {
12061 errState = errState || er;
12062 if (--n === 0)
12063 cb(errState);
12064 }
12065
12066 function afterGlob (er, results) {
12067 if (er)
12068 return cb(er)
12069
12070 n = results.length;
12071 if (n === 0)
12072 return cb()
12073
12074 results.forEach(function (p) {
12075 rimraf_(p, options, function CB (er) {
12076 if (er) {
12077 if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") &&
12078 busyTries < options.maxBusyTries) {
12079 busyTries ++;
12080 var time = busyTries * 100;
12081 // try again, with the same exact callback as this one.
12082 return setTimeout(function () {
12083 rimraf_(p, options, CB);
12084 }, time)
12085 }
12086
12087 // this one won't happen if graceful-fs is used.
12088 if (er.code === "EMFILE" && timeout < options.emfileWait) {
12089 return setTimeout(function () {
12090 rimraf_(p, options, CB);
12091 }, timeout ++)
12092 }
12093
12094 // already gone
12095 if (er.code === "ENOENT") er = null;
12096 }
12097
12098 timeout = 0;
12099 next(er);
12100 });
12101 });
12102 }
12103}
12104
12105// Two possible strategies.
12106// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
12107// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
12108//
12109// Both result in an extra syscall when you guess wrong. However, there
12110// are likely far more normal files in the world than directories. This
12111// is based on the assumption that a the average number of files per
12112// directory is >= 1.
12113//
12114// If anyone ever complains about this, then I guess the strategy could
12115// be made configurable somehow. But until then, YAGNI.
12116function rimraf_ (p, options, cb) {
12117 assert__default['default'](p);
12118 assert__default['default'](options);
12119 assert__default['default'](typeof cb === 'function');
12120
12121 // sunos lets the root user unlink directories, which is... weird.
12122 // so we have to lstat here and make sure it's not a dir.
12123 options.lstat(p, function (er, st) {
12124 if (er && er.code === "ENOENT")
12125 return cb(null)
12126
12127 // Windows can EPERM on stat. Life is suffering.
12128 if (er && er.code === "EPERM" && isWindows)
12129 fixWinEPERM(p, options, er, cb);
12130
12131 if (st && st.isDirectory())
12132 return rmdir(p, options, er, cb)
12133
12134 options.unlink(p, function (er) {
12135 if (er) {
12136 if (er.code === "ENOENT")
12137 return cb(null)
12138 if (er.code === "EPERM")
12139 return (isWindows)
12140 ? fixWinEPERM(p, options, er, cb)
12141 : rmdir(p, options, er, cb)
12142 if (er.code === "EISDIR")
12143 return rmdir(p, options, er, cb)
12144 }
12145 return cb(er)
12146 });
12147 });
12148}
12149
12150function fixWinEPERM (p, options, er, cb) {
12151 assert__default['default'](p);
12152 assert__default['default'](options);
12153 assert__default['default'](typeof cb === 'function');
12154 if (er)
12155 assert__default['default'](er instanceof Error);
12156
12157 options.chmod(p, _0666, function (er2) {
12158 if (er2)
12159 cb(er2.code === "ENOENT" ? null : er);
12160 else
12161 options.stat(p, function(er3, stats) {
12162 if (er3)
12163 cb(er3.code === "ENOENT" ? null : er);
12164 else if (stats.isDirectory())
12165 rmdir(p, options, er, cb);
12166 else
12167 options.unlink(p, cb);
12168 });
12169 });
12170}
12171
12172function fixWinEPERMSync (p, options, er) {
12173 assert__default['default'](p);
12174 assert__default['default'](options);
12175 if (er)
12176 assert__default['default'](er instanceof Error);
12177
12178 try {
12179 options.chmodSync(p, _0666);
12180 } catch (er2) {
12181 if (er2.code === "ENOENT")
12182 return
12183 else
12184 throw er
12185 }
12186
12187 try {
12188 var stats = options.statSync(p);
12189 } catch (er3) {
12190 if (er3.code === "ENOENT")
12191 return
12192 else
12193 throw er
12194 }
12195
12196 if (stats.isDirectory())
12197 rmdirSync(p, options, er);
12198 else
12199 options.unlinkSync(p);
12200}
12201
12202function rmdir (p, options, originalEr, cb) {
12203 assert__default['default'](p);
12204 assert__default['default'](options);
12205 if (originalEr)
12206 assert__default['default'](originalEr instanceof Error);
12207 assert__default['default'](typeof cb === 'function');
12208
12209 // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
12210 // if we guessed wrong, and it's not a directory, then
12211 // raise the original error.
12212 options.rmdir(p, function (er) {
12213 if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
12214 rmkids(p, options, cb);
12215 else if (er && er.code === "ENOTDIR")
12216 cb(originalEr);
12217 else
12218 cb(er);
12219 });
12220}
12221
12222function rmkids(p, options, cb) {
12223 assert__default['default'](p);
12224 assert__default['default'](options);
12225 assert__default['default'](typeof cb === 'function');
12226
12227 options.readdir(p, function (er, files) {
12228 if (er)
12229 return cb(er)
12230 var n = files.length;
12231 if (n === 0)
12232 return options.rmdir(p, cb)
12233 var errState;
12234 files.forEach(function (f) {
12235 rimraf(path__default['default'].join(p, f), options, function (er) {
12236 if (errState)
12237 return
12238 if (er)
12239 return cb(errState = er)
12240 if (--n === 0)
12241 options.rmdir(p, cb);
12242 });
12243 });
12244 });
12245}
12246
12247// this looks simpler, and is strictly *faster*, but will
12248// tie up the JavaScript thread and fail on excessively
12249// deep directory trees.
12250function rimrafSync$1 (p, options) {
12251 options = options || {};
12252 defaults(options);
12253
12254 assert__default['default'](p, 'rimraf: missing path');
12255 assert__default['default'].equal(typeof p, 'string', 'rimraf: path should be a string');
12256 assert__default['default'](options, 'rimraf: missing options');
12257 assert__default['default'].equal(typeof options, 'object', 'rimraf: options should be object');
12258
12259 var results;
12260
12261 if (options.disableGlob || !glob.hasMagic(p)) {
12262 results = [p];
12263 } else {
12264 try {
12265 options.lstatSync(p);
12266 results = [p];
12267 } catch (er) {
12268 results = glob.sync(p, options.glob);
12269 }
12270 }
12271
12272 if (!results.length)
12273 return
12274
12275 for (var i = 0; i < results.length; i++) {
12276 var p = results[i];
12277
12278 try {
12279 var st = options.lstatSync(p);
12280 } catch (er) {
12281 if (er.code === "ENOENT")
12282 return
12283
12284 // Windows can EPERM on stat. Life is suffering.
12285 if (er.code === "EPERM" && isWindows)
12286 fixWinEPERMSync(p, options, er);
12287 }
12288
12289 try {
12290 // sunos lets the root user unlink directories, which is... weird.
12291 if (st && st.isDirectory())
12292 rmdirSync(p, options, null);
12293 else
12294 options.unlinkSync(p);
12295 } catch (er) {
12296 if (er.code === "ENOENT")
12297 return
12298 if (er.code === "EPERM")
12299 return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
12300 if (er.code !== "EISDIR")
12301 throw er
12302
12303 rmdirSync(p, options, er);
12304 }
12305 }
12306}
12307
12308function rmdirSync (p, options, originalEr) {
12309 assert__default['default'](p);
12310 assert__default['default'](options);
12311 if (originalEr)
12312 assert__default['default'](originalEr instanceof Error);
12313
12314 try {
12315 options.rmdirSync(p);
12316 } catch (er) {
12317 if (er.code === "ENOENT")
12318 return
12319 if (er.code === "ENOTDIR")
12320 throw originalEr
12321 if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
12322 rmkidsSync(p, options);
12323 }
12324}
12325
12326function rmkidsSync (p, options) {
12327 assert__default['default'](p);
12328 assert__default['default'](options);
12329 options.readdirSync(p).forEach(function (f) {
12330 rimrafSync$1(path__default['default'].join(p, f), options);
12331 });
12332
12333 // We only end up here once we got ENOTEMPTY at least once, and
12334 // at this point, we are guaranteed to have removed all the kids.
12335 // So, we know that it won't be ENOENT or ENOTDIR or anything else.
12336 // try really hard to delete stuff on windows, because it has a
12337 // PROFOUNDLY annoying habit of not closing handles promptly when
12338 // files are deleted, resulting in spurious ENOTEMPTY errors.
12339 var retries = isWindows ? 100 : 1;
12340 var i = 0;
12341 do {
12342 var threw = true;
12343 try {
12344 var ret = options.rmdirSync(p, options);
12345 threw = false;
12346 return ret
12347 } finally {
12348 if (++i < retries && threw)
12349 continue
12350 }
12351 } while (true)
12352}
12353
12354function _interopDefault$1 (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
12355
12356
12357
12358var mkdirp$1 = _interopDefault$1(mkdirp$2);
12359
12360var _rimraf = _interopDefault$1(rimraf_1);
12361
12362function resolvePath ( args ) {
12363 return path__default['default'].resolve.apply( null, args );
12364}
12365
12366function resolvePathAndOptions ( args ) {
12367 var options;
12368 var pathargs;
12369
12370 if ( typeof args[ args.length - 1 ] === 'object' ) {
12371 options = args[ args.length - 1 ];
12372
12373 var i = args.length - 1;
12374 pathargs = new Array( i );
12375
12376 while ( i-- ) {
12377 pathargs[i] = args[i];
12378 }
12379 } else {
12380 options = {};
12381 pathargs = args;
12382 }
12383
12384 var resolvedPath = path__default['default'].resolve.apply( null, pathargs );
12385
12386 return { options: options, resolvedPath: resolvedPath };
12387}
12388
12389function copydirSync () {
12390 var ref = resolvePathAndOptions( arguments );
12391 var src = ref.resolvedPath;
12392 var readOptions = ref.options;
12393
12394 return {
12395 to: function to () {
12396 var ref = resolvePathAndOptions( arguments );
12397 var dest = ref.resolvedPath;
12398 var writeOptions = ref.options;
12399
12400 function copydir ( src, dest ) {
12401 mkdirp$1.sync( dest );
12402
12403 gracefulFs.readdirSync( src ).forEach( function (filename) {
12404 var srcpath = src + path__default['default'].sep + filename;
12405 var destpath = dest + path__default['default'].sep + filename;
12406
12407 if ( gracefulFs.statSync( srcpath ).isDirectory() ) {
12408 return copydir( srcpath, destpath );
12409 }
12410
12411 var data = gracefulFs.readFileSync( srcpath, readOptions );
12412 gracefulFs.writeFileSync( destpath, data, writeOptions );
12413 });
12414 }
12415
12416 copydir( src, dest );
12417 }
12418 };
12419}
12420
12421function rimrafSync () {
12422 _rimraf.sync( resolvePath( arguments ) );
12423}
12424
12425process.platform === 'win32';
12426
12427// file descriptor sync methods
12428gracefulFs.closeSync;
12429gracefulFs.fchmodSync;
12430gracefulFs.fchownSync;
12431gracefulFs.fstatSync;
12432gracefulFs.fsyncSync;
12433gracefulFs.ftruncateSync;
12434gracefulFs.futimesSync;
12435gracefulFs.readSync;
12436var copydirSync_1 = copydirSync;
12437var rimrafSync_1 = rimrafSync;
12438
12439var homeOrTmp = os__default['default'].homedir() || os__default['default'].tmpdir();
12440
12441/**
12442 * Helpers.
12443 */
12444var s = 1000;
12445var m = s * 60;
12446var h = m * 60;
12447var d = h * 24;
12448var w = d * 7;
12449var y = d * 365.25;
12450
12451/**
12452 * Parse or format the given `val`.
12453 *
12454 * Options:
12455 *
12456 * - `long` verbose formatting [false]
12457 *
12458 * @param {String|Number} val
12459 * @param {Object} [options]
12460 * @throws {Error} throw an error if val is not a non-empty string or a number
12461 * @return {String|Number}
12462 * @api public
12463 */
12464
12465var ms = function(val, options) {
12466 options = options || {};
12467 var type = typeof val;
12468 if (type === 'string' && val.length > 0) {
12469 return parse$1(val);
12470 } else if (type === 'number' && isFinite(val)) {
12471 return options.long ? fmtLong(val) : fmtShort(val);
12472 }
12473 throw new Error(
12474 'val is not a non-empty string or a valid number. val=' +
12475 JSON.stringify(val)
12476 );
12477};
12478
12479/**
12480 * Parse the given `str` and return milliseconds.
12481 *
12482 * @param {String} str
12483 * @return {Number}
12484 * @api private
12485 */
12486
12487function parse$1(str) {
12488 str = String(str);
12489 if (str.length > 100) {
12490 return;
12491 }
12492 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
12493 str
12494 );
12495 if (!match) {
12496 return;
12497 }
12498 var n = parseFloat(match[1]);
12499 var type = (match[2] || 'ms').toLowerCase();
12500 switch (type) {
12501 case 'years':
12502 case 'year':
12503 case 'yrs':
12504 case 'yr':
12505 case 'y':
12506 return n * y;
12507 case 'weeks':
12508 case 'week':
12509 case 'w':
12510 return n * w;
12511 case 'days':
12512 case 'day':
12513 case 'd':
12514 return n * d;
12515 case 'hours':
12516 case 'hour':
12517 case 'hrs':
12518 case 'hr':
12519 case 'h':
12520 return n * h;
12521 case 'minutes':
12522 case 'minute':
12523 case 'mins':
12524 case 'min':
12525 case 'm':
12526 return n * m;
12527 case 'seconds':
12528 case 'second':
12529 case 'secs':
12530 case 'sec':
12531 case 's':
12532 return n * s;
12533 case 'milliseconds':
12534 case 'millisecond':
12535 case 'msecs':
12536 case 'msec':
12537 case 'ms':
12538 return n;
12539 default:
12540 return undefined;
12541 }
12542}
12543
12544/**
12545 * Short format for `ms`.
12546 *
12547 * @param {Number} ms
12548 * @return {String}
12549 * @api private
12550 */
12551
12552function fmtShort(ms) {
12553 var msAbs = Math.abs(ms);
12554 if (msAbs >= d) {
12555 return Math.round(ms / d) + 'd';
12556 }
12557 if (msAbs >= h) {
12558 return Math.round(ms / h) + 'h';
12559 }
12560 if (msAbs >= m) {
12561 return Math.round(ms / m) + 'm';
12562 }
12563 if (msAbs >= s) {
12564 return Math.round(ms / s) + 's';
12565 }
12566 return ms + 'ms';
12567}
12568
12569/**
12570 * Long format for `ms`.
12571 *
12572 * @param {Number} ms
12573 * @return {String}
12574 * @api private
12575 */
12576
12577function fmtLong(ms) {
12578 var msAbs = Math.abs(ms);
12579 if (msAbs >= d) {
12580 return plural(ms, msAbs, d, 'day');
12581 }
12582 if (msAbs >= h) {
12583 return plural(ms, msAbs, h, 'hour');
12584 }
12585 if (msAbs >= m) {
12586 return plural(ms, msAbs, m, 'minute');
12587 }
12588 if (msAbs >= s) {
12589 return plural(ms, msAbs, s, 'second');
12590 }
12591 return ms + ' ms';
12592}
12593
12594/**
12595 * Pluralization helper.
12596 */
12597
12598function plural(ms, msAbs, n, name) {
12599 var isPlural = msAbs >= n * 1.5;
12600 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
12601}
12602
12603/**
12604 * This is the common logic for both the Node.js and web browser
12605 * implementations of `debug()`.
12606 */
12607
12608function setup(env) {
12609 createDebug.debug = createDebug;
12610 createDebug.default = createDebug;
12611 createDebug.coerce = coerce;
12612 createDebug.disable = disable;
12613 createDebug.enable = enable;
12614 createDebug.enabled = enabled;
12615 createDebug.humanize = ms;
12616 createDebug.destroy = destroy;
12617
12618 Object.keys(env).forEach(key => {
12619 createDebug[key] = env[key];
12620 });
12621
12622 /**
12623 * The currently active debug mode names, and names to skip.
12624 */
12625
12626 createDebug.names = [];
12627 createDebug.skips = [];
12628
12629 /**
12630 * Map of special "%n" handling functions, for the debug "format" argument.
12631 *
12632 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
12633 */
12634 createDebug.formatters = {};
12635
12636 /**
12637 * Selects a color for a debug namespace
12638 * @param {String} namespace The namespace string for the for the debug instance to be colored
12639 * @return {Number|String} An ANSI color code for the given namespace
12640 * @api private
12641 */
12642 function selectColor(namespace) {
12643 let hash = 0;
12644
12645 for (let i = 0; i < namespace.length; i++) {
12646 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
12647 hash |= 0; // Convert to 32bit integer
12648 }
12649
12650 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
12651 }
12652 createDebug.selectColor = selectColor;
12653
12654 /**
12655 * Create a debugger with the given `namespace`.
12656 *
12657 * @param {String} namespace
12658 * @return {Function}
12659 * @api public
12660 */
12661 function createDebug(namespace) {
12662 let prevTime;
12663 let enableOverride = null;
12664
12665 function debug(...args) {
12666 // Disabled?
12667 if (!debug.enabled) {
12668 return;
12669 }
12670
12671 const self = debug;
12672
12673 // Set `diff` timestamp
12674 const curr = Number(new Date());
12675 const ms = curr - (prevTime || curr);
12676 self.diff = ms;
12677 self.prev = prevTime;
12678 self.curr = curr;
12679 prevTime = curr;
12680
12681 args[0] = createDebug.coerce(args[0]);
12682
12683 if (typeof args[0] !== 'string') {
12684 // Anything else let's inspect with %O
12685 args.unshift('%O');
12686 }
12687
12688 // Apply any `formatters` transformations
12689 let index = 0;
12690 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
12691 // If we encounter an escaped % then don't increase the array index
12692 if (match === '%%') {
12693 return '%';
12694 }
12695 index++;
12696 const formatter = createDebug.formatters[format];
12697 if (typeof formatter === 'function') {
12698 const val = args[index];
12699 match = formatter.call(self, val);
12700
12701 // Now we need to remove `args[index]` since it's inlined in the `format`
12702 args.splice(index, 1);
12703 index--;
12704 }
12705 return match;
12706 });
12707
12708 // Apply env-specific formatting (colors, etc.)
12709 createDebug.formatArgs.call(self, args);
12710
12711 const logFn = self.log || createDebug.log;
12712 logFn.apply(self, args);
12713 }
12714
12715 debug.namespace = namespace;
12716 debug.useColors = createDebug.useColors();
12717 debug.color = createDebug.selectColor(namespace);
12718 debug.extend = extend;
12719 debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
12720
12721 Object.defineProperty(debug, 'enabled', {
12722 enumerable: true,
12723 configurable: false,
12724 get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,
12725 set: v => {
12726 enableOverride = v;
12727 }
12728 });
12729
12730 // Env-specific initialization logic for debug instances
12731 if (typeof createDebug.init === 'function') {
12732 createDebug.init(debug);
12733 }
12734
12735 return debug;
12736 }
12737
12738 function extend(namespace, delimiter) {
12739 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
12740 newDebug.log = this.log;
12741 return newDebug;
12742 }
12743
12744 /**
12745 * Enables a debug mode by namespaces. This can include modes
12746 * separated by a colon and wildcards.
12747 *
12748 * @param {String} namespaces
12749 * @api public
12750 */
12751 function enable(namespaces) {
12752 createDebug.save(namespaces);
12753
12754 createDebug.names = [];
12755 createDebug.skips = [];
12756
12757 let i;
12758 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
12759 const len = split.length;
12760
12761 for (i = 0; i < len; i++) {
12762 if (!split[i]) {
12763 // ignore empty strings
12764 continue;
12765 }
12766
12767 namespaces = split[i].replace(/\*/g, '.*?');
12768
12769 if (namespaces[0] === '-') {
12770 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
12771 } else {
12772 createDebug.names.push(new RegExp('^' + namespaces + '$'));
12773 }
12774 }
12775 }
12776
12777 /**
12778 * Disable debug output.
12779 *
12780 * @return {String} namespaces
12781 * @api public
12782 */
12783 function disable() {
12784 const namespaces = [
12785 ...createDebug.names.map(toNamespace),
12786 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
12787 ].join(',');
12788 createDebug.enable('');
12789 return namespaces;
12790 }
12791
12792 /**
12793 * Returns true if the given mode name is enabled, false otherwise.
12794 *
12795 * @param {String} name
12796 * @return {Boolean}
12797 * @api public
12798 */
12799 function enabled(name) {
12800 if (name[name.length - 1] === '*') {
12801 return true;
12802 }
12803
12804 let i;
12805 let len;
12806
12807 for (i = 0, len = createDebug.skips.length; i < len; i++) {
12808 if (createDebug.skips[i].test(name)) {
12809 return false;
12810 }
12811 }
12812
12813 for (i = 0, len = createDebug.names.length; i < len; i++) {
12814 if (createDebug.names[i].test(name)) {
12815 return true;
12816 }
12817 }
12818
12819 return false;
12820 }
12821
12822 /**
12823 * Convert regexp to namespace
12824 *
12825 * @param {RegExp} regxep
12826 * @return {String} namespace
12827 * @api private
12828 */
12829 function toNamespace(regexp) {
12830 return regexp.toString()
12831 .substring(2, regexp.toString().length - 2)
12832 .replace(/\.\*\?$/, '*');
12833 }
12834
12835 /**
12836 * Coerce `val`.
12837 *
12838 * @param {Mixed} val
12839 * @return {Mixed}
12840 * @api private
12841 */
12842 function coerce(val) {
12843 if (val instanceof Error) {
12844 return val.stack || val.message;
12845 }
12846 return val;
12847 }
12848
12849 /**
12850 * XXX DO NOT USE. This is a temporary stub function.
12851 * XXX It WILL be removed in the next major release.
12852 */
12853 function destroy() {
12854 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
12855 }
12856
12857 createDebug.enable(createDebug.load());
12858
12859 return createDebug;
12860}
12861
12862var common = setup;
12863
12864/* eslint-env browser */
12865
12866var browser = createCommonjsModule(function (module, exports) {
12867/**
12868 * This is the web browser implementation of `debug()`.
12869 */
12870
12871exports.formatArgs = formatArgs;
12872exports.save = save;
12873exports.load = load;
12874exports.useColors = useColors;
12875exports.storage = localstorage();
12876exports.destroy = (() => {
12877 let warned = false;
12878
12879 return () => {
12880 if (!warned) {
12881 warned = true;
12882 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
12883 }
12884 };
12885})();
12886
12887/**
12888 * Colors.
12889 */
12890
12891exports.colors = [
12892 '#0000CC',
12893 '#0000FF',
12894 '#0033CC',
12895 '#0033FF',
12896 '#0066CC',
12897 '#0066FF',
12898 '#0099CC',
12899 '#0099FF',
12900 '#00CC00',
12901 '#00CC33',
12902 '#00CC66',
12903 '#00CC99',
12904 '#00CCCC',
12905 '#00CCFF',
12906 '#3300CC',
12907 '#3300FF',
12908 '#3333CC',
12909 '#3333FF',
12910 '#3366CC',
12911 '#3366FF',
12912 '#3399CC',
12913 '#3399FF',
12914 '#33CC00',
12915 '#33CC33',
12916 '#33CC66',
12917 '#33CC99',
12918 '#33CCCC',
12919 '#33CCFF',
12920 '#6600CC',
12921 '#6600FF',
12922 '#6633CC',
12923 '#6633FF',
12924 '#66CC00',
12925 '#66CC33',
12926 '#9900CC',
12927 '#9900FF',
12928 '#9933CC',
12929 '#9933FF',
12930 '#99CC00',
12931 '#99CC33',
12932 '#CC0000',
12933 '#CC0033',
12934 '#CC0066',
12935 '#CC0099',
12936 '#CC00CC',
12937 '#CC00FF',
12938 '#CC3300',
12939 '#CC3333',
12940 '#CC3366',
12941 '#CC3399',
12942 '#CC33CC',
12943 '#CC33FF',
12944 '#CC6600',
12945 '#CC6633',
12946 '#CC9900',
12947 '#CC9933',
12948 '#CCCC00',
12949 '#CCCC33',
12950 '#FF0000',
12951 '#FF0033',
12952 '#FF0066',
12953 '#FF0099',
12954 '#FF00CC',
12955 '#FF00FF',
12956 '#FF3300',
12957 '#FF3333',
12958 '#FF3366',
12959 '#FF3399',
12960 '#FF33CC',
12961 '#FF33FF',
12962 '#FF6600',
12963 '#FF6633',
12964 '#FF9900',
12965 '#FF9933',
12966 '#FFCC00',
12967 '#FFCC33'
12968];
12969
12970/**
12971 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
12972 * and the Firebug extension (any Firefox version) are known
12973 * to support "%c" CSS customizations.
12974 *
12975 * TODO: add a `localStorage` variable to explicitly enable/disable colors
12976 */
12977
12978// eslint-disable-next-line complexity
12979function useColors() {
12980 // NB: In an Electron preload script, document will be defined but not fully
12981 // initialized. Since we know we're in Chrome, we'll just detect this case
12982 // explicitly
12983 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
12984 return true;
12985 }
12986
12987 // Internet Explorer and Edge do not support colors.
12988 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
12989 return false;
12990 }
12991
12992 // Is webkit? http://stackoverflow.com/a/16459606/376773
12993 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
12994 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
12995 // Is firebug? http://stackoverflow.com/a/398120/376773
12996 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
12997 // Is firefox >= v31?
12998 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
12999 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
13000 // Double check webkit in userAgent just in case we are in a worker
13001 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
13002}
13003
13004/**
13005 * Colorize log arguments if enabled.
13006 *
13007 * @api public
13008 */
13009
13010function formatArgs(args) {
13011 args[0] = (this.useColors ? '%c' : '') +
13012 this.namespace +
13013 (this.useColors ? ' %c' : ' ') +
13014 args[0] +
13015 (this.useColors ? '%c ' : ' ') +
13016 '+' + module.exports.humanize(this.diff);
13017
13018 if (!this.useColors) {
13019 return;
13020 }
13021
13022 const c = 'color: ' + this.color;
13023 args.splice(1, 0, c, 'color: inherit');
13024
13025 // The final "%c" is somewhat tricky, because there could be other
13026 // arguments passed either before or after the %c, so we need to
13027 // figure out the correct index to insert the CSS into
13028 let index = 0;
13029 let lastC = 0;
13030 args[0].replace(/%[a-zA-Z%]/g, match => {
13031 if (match === '%%') {
13032 return;
13033 }
13034 index++;
13035 if (match === '%c') {
13036 // We only are interested in the *last* %c
13037 // (the user may have provided their own)
13038 lastC = index;
13039 }
13040 });
13041
13042 args.splice(lastC, 0, c);
13043}
13044
13045/**
13046 * Invokes `console.debug()` when available.
13047 * No-op when `console.debug` is not a "function".
13048 * If `console.debug` is not available, falls back
13049 * to `console.log`.
13050 *
13051 * @api public
13052 */
13053exports.log = console.debug || console.log || (() => {});
13054
13055/**
13056 * Save `namespaces`.
13057 *
13058 * @param {String} namespaces
13059 * @api private
13060 */
13061function save(namespaces) {
13062 try {
13063 if (namespaces) {
13064 exports.storage.setItem('debug', namespaces);
13065 } else {
13066 exports.storage.removeItem('debug');
13067 }
13068 } catch (error) {
13069 // Swallow
13070 // XXX (@Qix-) should we be logging these?
13071 }
13072}
13073
13074/**
13075 * Load `namespaces`.
13076 *
13077 * @return {String} returns the previously persisted debug modes
13078 * @api private
13079 */
13080function load() {
13081 let r;
13082 try {
13083 r = exports.storage.getItem('debug');
13084 } catch (error) {
13085 // Swallow
13086 // XXX (@Qix-) should we be logging these?
13087 }
13088
13089 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
13090 if (!r && typeof process !== 'undefined' && 'env' in process) {
13091 r = process.env.DEBUG;
13092 }
13093
13094 return r;
13095}
13096
13097/**
13098 * Localstorage attempts to return the localstorage.
13099 *
13100 * This is necessary because safari throws
13101 * when a user disables cookies/localstorage
13102 * and you attempt to access it.
13103 *
13104 * @return {LocalStorage}
13105 * @api private
13106 */
13107
13108function localstorage() {
13109 try {
13110 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
13111 // The Browser also has localStorage in the global context.
13112 return localStorage;
13113 } catch (error) {
13114 // Swallow
13115 // XXX (@Qix-) should we be logging these?
13116 }
13117}
13118
13119module.exports = common(exports);
13120
13121const {formatters} = module.exports;
13122
13123/**
13124 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
13125 */
13126
13127formatters.j = function (v) {
13128 try {
13129 return JSON.stringify(v);
13130 } catch (error) {
13131 return '[UnexpectedJSONParseError]: ' + error.message;
13132 }
13133};
13134});
13135
13136/**
13137 * Module dependencies.
13138 */
13139
13140var node = createCommonjsModule(function (module, exports) {
13141/**
13142 * This is the Node.js implementation of `debug()`.
13143 */
13144
13145exports.init = init;
13146exports.log = log;
13147exports.formatArgs = formatArgs;
13148exports.save = save;
13149exports.load = load;
13150exports.useColors = useColors;
13151exports.destroy = util__default['default'].deprecate(
13152 () => {},
13153 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
13154);
13155
13156/**
13157 * Colors.
13158 */
13159
13160exports.colors = [6, 2, 3, 4, 5, 1];
13161
13162try {
13163 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
13164 // eslint-disable-next-line import/no-extraneous-dependencies
13165 const supportsColor = supportsColor_1;
13166
13167 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
13168 exports.colors = [
13169 20,
13170 21,
13171 26,
13172 27,
13173 32,
13174 33,
13175 38,
13176 39,
13177 40,
13178 41,
13179 42,
13180 43,
13181 44,
13182 45,
13183 56,
13184 57,
13185 62,
13186 63,
13187 68,
13188 69,
13189 74,
13190 75,
13191 76,
13192 77,
13193 78,
13194 79,
13195 80,
13196 81,
13197 92,
13198 93,
13199 98,
13200 99,
13201 112,
13202 113,
13203 128,
13204 129,
13205 134,
13206 135,
13207 148,
13208 149,
13209 160,
13210 161,
13211 162,
13212 163,
13213 164,
13214 165,
13215 166,
13216 167,
13217 168,
13218 169,
13219 170,
13220 171,
13221 172,
13222 173,
13223 178,
13224 179,
13225 184,
13226 185,
13227 196,
13228 197,
13229 198,
13230 199,
13231 200,
13232 201,
13233 202,
13234 203,
13235 204,
13236 205,
13237 206,
13238 207,
13239 208,
13240 209,
13241 214,
13242 215,
13243 220,
13244 221
13245 ];
13246 }
13247} catch (error) {
13248 // Swallow - we only care if `supports-color` is available; it doesn't have to be.
13249}
13250
13251/**
13252 * Build up the default `inspectOpts` object from the environment variables.
13253 *
13254 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
13255 */
13256
13257exports.inspectOpts = Object.keys(process.env).filter(key => {
13258 return /^debug_/i.test(key);
13259}).reduce((obj, key) => {
13260 // Camel-case
13261 const prop = key
13262 .substring(6)
13263 .toLowerCase()
13264 .replace(/_([a-z])/g, (_, k) => {
13265 return k.toUpperCase();
13266 });
13267
13268 // Coerce string value into JS value
13269 let val = process.env[key];
13270 if (/^(yes|on|true|enabled)$/i.test(val)) {
13271 val = true;
13272 } else if (/^(no|off|false|disabled)$/i.test(val)) {
13273 val = false;
13274 } else if (val === 'null') {
13275 val = null;
13276 } else {
13277 val = Number(val);
13278 }
13279
13280 obj[prop] = val;
13281 return obj;
13282}, {});
13283
13284/**
13285 * Is stdout a TTY? Colored output is enabled when `true`.
13286 */
13287
13288function useColors() {
13289 return 'colors' in exports.inspectOpts ?
13290 Boolean(exports.inspectOpts.colors) :
13291 tty__default['default'].isatty(process.stderr.fd);
13292}
13293
13294/**
13295 * Adds ANSI color escape codes if enabled.
13296 *
13297 * @api public
13298 */
13299
13300function formatArgs(args) {
13301 const {namespace: name, useColors} = this;
13302
13303 if (useColors) {
13304 const c = this.color;
13305 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
13306 const prefix = ` ${colorCode};1m${name} \u001B[0m`;
13307
13308 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
13309 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
13310 } else {
13311 args[0] = getDate() + name + ' ' + args[0];
13312 }
13313}
13314
13315function getDate() {
13316 if (exports.inspectOpts.hideDate) {
13317 return '';
13318 }
13319 return new Date().toISOString() + ' ';
13320}
13321
13322/**
13323 * Invokes `util.format()` with the specified arguments and writes to stderr.
13324 */
13325
13326function log(...args) {
13327 return process.stderr.write(util__default['default'].format(...args) + '\n');
13328}
13329
13330/**
13331 * Save `namespaces`.
13332 *
13333 * @param {String} namespaces
13334 * @api private
13335 */
13336function save(namespaces) {
13337 if (namespaces) {
13338 process.env.DEBUG = namespaces;
13339 } else {
13340 // If you set a process.env field to null or undefined, it gets cast to the
13341 // string 'null' or 'undefined'. Just delete instead.
13342 delete process.env.DEBUG;
13343 }
13344}
13345
13346/**
13347 * Load `namespaces`.
13348 *
13349 * @return {String} returns the previously persisted debug modes
13350 * @api private
13351 */
13352
13353function load() {
13354 return process.env.DEBUG;
13355}
13356
13357/**
13358 * Init logic for `debug` instances.
13359 *
13360 * Create a new `inspectOpts` object in case `useColors` is set
13361 * differently for a particular `debug` instance.
13362 */
13363
13364function init(debug) {
13365 debug.inspectOpts = {};
13366
13367 const keys = Object.keys(exports.inspectOpts);
13368 for (let i = 0; i < keys.length; i++) {
13369 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
13370 }
13371}
13372
13373module.exports = common(exports);
13374
13375const {formatters} = module.exports;
13376
13377/**
13378 * Map %o to `util.inspect()`, all on a single line.
13379 */
13380
13381formatters.o = function (v) {
13382 this.inspectOpts.colors = this.useColors;
13383 return util__default['default'].inspect(v, this.inspectOpts)
13384 .split('\n')
13385 .map(str => str.trim())
13386 .join(' ');
13387};
13388
13389/**
13390 * Map %O to `util.inspect()`, allowing multiple lines if needed.
13391 */
13392
13393formatters.O = function (v) {
13394 this.inspectOpts.colors = this.useColors;
13395 return util__default['default'].inspect(v, this.inspectOpts);
13396};
13397});
13398
13399/**
13400 * Detect Electron renderer / nwjs process, which is node, but we should
13401 * treat as a browser.
13402 */
13403
13404var src$1 = createCommonjsModule(function (module) {
13405if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
13406 module.exports = browser;
13407} else {
13408 module.exports = node;
13409}
13410});
13411
13412function promisify(fn) {
13413 return function (req, opts) {
13414 return new Promise((resolve, reject) => {
13415 fn.call(this, req, opts, (err, rtn) => {
13416 if (err) {
13417 reject(err);
13418 }
13419 else {
13420 resolve(rtn);
13421 }
13422 });
13423 });
13424 };
13425}
13426var _default$2 = promisify;
13427
13428
13429var promisify_1$1 = /*#__PURE__*/Object.defineProperty({
13430 default: _default$2
13431}, '__esModule', {value: true});
13432
13433var __importDefault$3 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
13434 return (mod && mod.__esModule) ? mod : { "default": mod };
13435};
13436
13437const debug_1$2 = __importDefault$3(src$1);
13438const promisify_1 = __importDefault$3(promisify_1$1);
13439const debug$2 = debug_1$2.default('agent-base');
13440function isAgent(v) {
13441 return Boolean(v) && typeof v.addRequest === 'function';
13442}
13443function isSecureEndpoint() {
13444 const { stack } = new Error();
13445 if (typeof stack !== 'string')
13446 return false;
13447 return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);
13448}
13449function createAgent(callback, opts) {
13450 return new createAgent.Agent(callback, opts);
13451}
13452(function (createAgent) {
13453 /**
13454 * Base `http.Agent` implementation.
13455 * No pooling/keep-alive is implemented by default.
13456 *
13457 * @param {Function} callback
13458 * @api public
13459 */
13460 class Agent extends Events__default['default'].EventEmitter {
13461 constructor(callback, _opts) {
13462 super();
13463 let opts = _opts;
13464 if (typeof callback === 'function') {
13465 this.callback = callback;
13466 }
13467 else if (callback) {
13468 opts = callback;
13469 }
13470 // Timeout for the socket to be returned from the callback
13471 this.timeout = null;
13472 if (opts && typeof opts.timeout === 'number') {
13473 this.timeout = opts.timeout;
13474 }
13475 // These aren't actually used by `agent-base`, but are required
13476 // for the TypeScript definition files in `@types/node` :/
13477 this.maxFreeSockets = 1;
13478 this.maxSockets = 1;
13479 this.maxTotalSockets = Infinity;
13480 this.sockets = {};
13481 this.freeSockets = {};
13482 this.requests = {};
13483 this.options = {};
13484 }
13485 get defaultPort() {
13486 if (typeof this.explicitDefaultPort === 'number') {
13487 return this.explicitDefaultPort;
13488 }
13489 return isSecureEndpoint() ? 443 : 80;
13490 }
13491 set defaultPort(v) {
13492 this.explicitDefaultPort = v;
13493 }
13494 get protocol() {
13495 if (typeof this.explicitProtocol === 'string') {
13496 return this.explicitProtocol;
13497 }
13498 return isSecureEndpoint() ? 'https:' : 'http:';
13499 }
13500 set protocol(v) {
13501 this.explicitProtocol = v;
13502 }
13503 callback(req, opts, fn) {
13504 throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`');
13505 }
13506 /**
13507 * Called by node-core's "_http_client.js" module when creating
13508 * a new HTTP request with this Agent instance.
13509 *
13510 * @api public
13511 */
13512 addRequest(req, _opts) {
13513 const opts = Object.assign({}, _opts);
13514 if (typeof opts.secureEndpoint !== 'boolean') {
13515 opts.secureEndpoint = isSecureEndpoint();
13516 }
13517 if (opts.host == null) {
13518 opts.host = 'localhost';
13519 }
13520 if (opts.port == null) {
13521 opts.port = opts.secureEndpoint ? 443 : 80;
13522 }
13523 if (opts.protocol == null) {
13524 opts.protocol = opts.secureEndpoint ? 'https:' : 'http:';
13525 }
13526 if (opts.host && opts.path) {
13527 // If both a `host` and `path` are specified then it's most
13528 // likely the result of a `url.parse()` call... we need to
13529 // remove the `path` portion so that `net.connect()` doesn't
13530 // attempt to open that as a unix socket file.
13531 delete opts.path;
13532 }
13533 delete opts.agent;
13534 delete opts.hostname;
13535 delete opts._defaultAgent;
13536 delete opts.defaultPort;
13537 delete opts.createConnection;
13538 // Hint to use "Connection: close"
13539 // XXX: non-documented `http` module API :(
13540 req._last = true;
13541 req.shouldKeepAlive = false;
13542 let timedOut = false;
13543 let timeoutId = null;
13544 const timeoutMs = opts.timeout || this.timeout;
13545 const onerror = (err) => {
13546 if (req._hadError)
13547 return;
13548 req.emit('error', err);
13549 // For Safety. Some additional errors might fire later on
13550 // and we need to make sure we don't double-fire the error event.
13551 req._hadError = true;
13552 };
13553 const ontimeout = () => {
13554 timeoutId = null;
13555 timedOut = true;
13556 const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`);
13557 err.code = 'ETIMEOUT';
13558 onerror(err);
13559 };
13560 const callbackError = (err) => {
13561 if (timedOut)
13562 return;
13563 if (timeoutId !== null) {
13564 clearTimeout(timeoutId);
13565 timeoutId = null;
13566 }
13567 onerror(err);
13568 };
13569 const onsocket = (socket) => {
13570 if (timedOut)
13571 return;
13572 if (timeoutId != null) {
13573 clearTimeout(timeoutId);
13574 timeoutId = null;
13575 }
13576 if (isAgent(socket)) {
13577 // `socket` is actually an `http.Agent` instance, so
13578 // relinquish responsibility for this `req` to the Agent
13579 // from here on
13580 debug$2('Callback returned another Agent instance %o', socket.constructor.name);
13581 socket.addRequest(req, opts);
13582 return;
13583 }
13584 if (socket) {
13585 socket.once('free', () => {
13586 this.freeSocket(socket, opts);
13587 });
13588 req.onSocket(socket);
13589 return;
13590 }
13591 const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``);
13592 onerror(err);
13593 };
13594 if (typeof this.callback !== 'function') {
13595 onerror(new Error('`callback` is not defined'));
13596 return;
13597 }
13598 if (!this.promisifiedCallback) {
13599 if (this.callback.length >= 3) {
13600 debug$2('Converting legacy callback function to promise');
13601 this.promisifiedCallback = promisify_1.default(this.callback);
13602 }
13603 else {
13604 this.promisifiedCallback = this.callback;
13605 }
13606 }
13607 if (typeof timeoutMs === 'number' && timeoutMs > 0) {
13608 timeoutId = setTimeout(ontimeout, timeoutMs);
13609 }
13610 if ('port' in opts && typeof opts.port !== 'number') {
13611 opts.port = Number(opts.port);
13612 }
13613 try {
13614 debug$2('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`);
13615 Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError);
13616 }
13617 catch (err) {
13618 Promise.reject(err).catch(callbackError);
13619 }
13620 }
13621 freeSocket(socket, opts) {
13622 debug$2('Freeing socket %o %o', socket.constructor.name, opts);
13623 socket.destroy();
13624 }
13625 destroy() {
13626 debug$2('Destroying agent %o', this.constructor.name);
13627 }
13628 }
13629 createAgent.Agent = Agent;
13630 // So that `instanceof` works correctly
13631 createAgent.prototype = createAgent.Agent.prototype;
13632})(createAgent || (createAgent = {}));
13633var src = createAgent;
13634
13635var __importDefault$2 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
13636 return (mod && mod.__esModule) ? mod : { "default": mod };
13637};
13638
13639const debug_1$1 = __importDefault$2(src$1);
13640const debug$1 = debug_1$1.default('https-proxy-agent:parse-proxy-response');
13641function parseProxyResponse(socket) {
13642 return new Promise((resolve, reject) => {
13643 // we need to buffer any HTTP traffic that happens with the proxy before we get
13644 // the CONNECT response, so that if the response is anything other than an "200"
13645 // response code, then we can re-play the "data" events on the socket once the
13646 // HTTP parser is hooked up...
13647 let buffersLength = 0;
13648 const buffers = [];
13649 function read() {
13650 const b = socket.read();
13651 if (b)
13652 ondata(b);
13653 else
13654 socket.once('readable', read);
13655 }
13656 function cleanup() {
13657 socket.removeListener('end', onend);
13658 socket.removeListener('error', onerror);
13659 socket.removeListener('close', onclose);
13660 socket.removeListener('readable', read);
13661 }
13662 function onclose(err) {
13663 debug$1('onclose had error %o', err);
13664 }
13665 function onend() {
13666 debug$1('onend');
13667 }
13668 function onerror(err) {
13669 cleanup();
13670 debug$1('onerror %o', err);
13671 reject(err);
13672 }
13673 function ondata(b) {
13674 buffers.push(b);
13675 buffersLength += b.length;
13676 const buffered = Buffer.concat(buffers, buffersLength);
13677 const endOfHeaders = buffered.indexOf('\r\n\r\n');
13678 if (endOfHeaders === -1) {
13679 // keep buffering
13680 debug$1('have not received end of HTTP headers yet...');
13681 read();
13682 return;
13683 }
13684 const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n'));
13685 const statusCode = +firstLine.split(' ')[1];
13686 debug$1('got proxy server response: %o', firstLine);
13687 resolve({
13688 statusCode,
13689 buffered
13690 });
13691 }
13692 socket.on('error', onerror);
13693 socket.on('close', onclose);
13694 socket.on('end', onend);
13695 read();
13696 });
13697}
13698var _default$1 = parseProxyResponse;
13699
13700
13701var parseProxyResponse_1 = /*#__PURE__*/Object.defineProperty({
13702 default: _default$1
13703}, '__esModule', {value: true});
13704
13705var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
13706 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
13707 return new (P || (P = Promise))(function (resolve, reject) {
13708 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
13709 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13710 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
13711 step((generator = generator.apply(thisArg, _arguments || [])).next());
13712 });
13713};
13714var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
13715 return (mod && mod.__esModule) ? mod : { "default": mod };
13716};
13717
13718const net_1 = __importDefault$1(require$$0__default$2['default']);
13719const tls_1 = __importDefault$1(require$$1__default['default']);
13720const url_1 = __importDefault$1(require$$2__default['default']);
13721const assert_1 = __importDefault$1(assert__default['default']);
13722const debug_1 = __importDefault$1(src$1);
13723
13724const parse_proxy_response_1 = __importDefault$1(parseProxyResponse_1);
13725const debug = debug_1.default('https-proxy-agent:agent');
13726/**
13727 * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
13728 * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
13729 *
13730 * Outgoing HTTP requests are first tunneled through the proxy server using the
13731 * `CONNECT` HTTP request method to establish a connection to the proxy server,
13732 * and then the proxy server connects to the destination target and issues the
13733 * HTTP request from the proxy server.
13734 *
13735 * `https:` requests have their socket connection upgraded to TLS once
13736 * the connection to the proxy server has been established.
13737 *
13738 * @api public
13739 */
13740class HttpsProxyAgent extends src.Agent {
13741 constructor(_opts) {
13742 let opts;
13743 if (typeof _opts === 'string') {
13744 opts = url_1.default.parse(_opts);
13745 }
13746 else {
13747 opts = _opts;
13748 }
13749 if (!opts) {
13750 throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
13751 }
13752 debug('creating new HttpsProxyAgent instance: %o', opts);
13753 super(opts);
13754 const proxy = Object.assign({}, opts);
13755 // If `true`, then connect to the proxy server over TLS.
13756 // Defaults to `false`.
13757 this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol);
13758 // Prefer `hostname` over `host`, and set the `port` if needed.
13759 proxy.host = proxy.hostname || proxy.host;
13760 if (typeof proxy.port === 'string') {
13761 proxy.port = parseInt(proxy.port, 10);
13762 }
13763 if (!proxy.port && proxy.host) {
13764 proxy.port = this.secureProxy ? 443 : 80;
13765 }
13766 // ALPN is supported by Node.js >= v5.
13767 // attempt to negotiate http/1.1 for proxy servers that support http/2
13768 if (this.secureProxy && !('ALPNProtocols' in proxy)) {
13769 proxy.ALPNProtocols = ['http 1.1'];
13770 }
13771 if (proxy.host && proxy.path) {
13772 // If both a `host` and `path` are specified then it's most likely
13773 // the result of a `url.parse()` call... we need to remove the
13774 // `path` portion so that `net.connect()` doesn't attempt to open
13775 // that as a Unix socket file.
13776 delete proxy.path;
13777 delete proxy.pathname;
13778 }
13779 this.proxy = proxy;
13780 }
13781 /**
13782 * Called when the node-core HTTP client library is creating a
13783 * new HTTP request.
13784 *
13785 * @api protected
13786 */
13787 callback(req, opts) {
13788 return __awaiter(this, void 0, void 0, function* () {
13789 const { proxy, secureProxy } = this;
13790 // Create a socket connection to the proxy server.
13791 let socket;
13792 if (secureProxy) {
13793 debug('Creating `tls.Socket`: %o', proxy);
13794 socket = tls_1.default.connect(proxy);
13795 }
13796 else {
13797 debug('Creating `net.Socket`: %o', proxy);
13798 socket = net_1.default.connect(proxy);
13799 }
13800 const headers = Object.assign({}, proxy.headers);
13801 const hostname = `${opts.host}:${opts.port}`;
13802 let payload = `CONNECT ${hostname} HTTP/1.1\r\n`;
13803 // Inject the `Proxy-Authorization` header if necessary.
13804 if (proxy.auth) {
13805 headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`;
13806 }
13807 // The `Host` header should only include the port
13808 // number when it is not the default port.
13809 let { host, port, secureEndpoint } = opts;
13810 if (!isDefaultPort(port, secureEndpoint)) {
13811 host += `:${port}`;
13812 }
13813 headers.Host = host;
13814 headers.Connection = 'close';
13815 for (const name of Object.keys(headers)) {
13816 payload += `${name}: ${headers[name]}\r\n`;
13817 }
13818 const proxyResponsePromise = parse_proxy_response_1.default(socket);
13819 socket.write(`${payload}\r\n`);
13820 const { statusCode, buffered } = yield proxyResponsePromise;
13821 if (statusCode === 200) {
13822 req.once('socket', resume);
13823 if (opts.secureEndpoint) {
13824 const servername = opts.servername || opts.host;
13825 if (!servername) {
13826 throw new Error('Could not determine "servername"');
13827 }
13828 // The proxy is connecting to a TLS server, so upgrade
13829 // this socket connection to a TLS connection.
13830 debug('Upgrading socket connection to TLS');
13831 return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket,
13832 servername }));
13833 }
13834 return socket;
13835 }
13836 // Some other status code that's not 200... need to re-play the HTTP
13837 // header "data" events onto the socket once the HTTP machinery is
13838 // attached so that the node core `http` can parse and handle the
13839 // error status code.
13840 // Close the original socket, and a new "fake" socket is returned
13841 // instead, so that the proxy doesn't get the HTTP request
13842 // written to it (which may contain `Authorization` headers or other
13843 // sensitive data).
13844 //
13845 // See: https://hackerone.com/reports/541502
13846 socket.destroy();
13847 const fakeSocket = new net_1.default.Socket();
13848 fakeSocket.readable = true;
13849 // Need to wait for the "socket" event to re-play the "data" events.
13850 req.once('socket', (s) => {
13851 debug('replaying proxy buffer for failed request');
13852 assert_1.default(s.listenerCount('data') > 0);
13853 // Replay the "buffered" Buffer onto the fake `socket`, since at
13854 // this point the HTTP module machinery has been hooked up for
13855 // the user.
13856 s.push(buffered);
13857 s.push(null);
13858 });
13859 return fakeSocket;
13860 });
13861 }
13862}
13863var _default = HttpsProxyAgent;
13864function resume(socket) {
13865 socket.resume();
13866}
13867function isDefaultPort(port, secure) {
13868 return Boolean((!secure && port === 80) || (secure && port === 443));
13869}
13870function isHTTPS(protocol) {
13871 return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false;
13872}
13873function omit(obj, ...keys) {
13874 const ret = {};
13875 let key;
13876 for (key in obj) {
13877 if (!keys.includes(key)) {
13878 ret[key] = obj[key];
13879 }
13880 }
13881 return ret;
13882}
13883
13884
13885var agent = /*#__PURE__*/Object.defineProperty({
13886 default: _default
13887}, '__esModule', {value: true});
13888
13889var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
13890 return (mod && mod.__esModule) ? mod : { "default": mod };
13891};
13892const agent_1 = __importDefault(agent);
13893function createHttpsProxyAgent(opts) {
13894 return new agent_1.default(opts);
13895}
13896(function (createHttpsProxyAgent) {
13897 createHttpsProxyAgent.HttpsProxyAgent = agent_1.default;
13898 createHttpsProxyAgent.prototype = agent_1.default.prototype;
13899})(createHttpsProxyAgent || (createHttpsProxyAgent = {}));
13900var dist = createHttpsProxyAgent;
13901
13902const tmpDirName = 'tmp';
13903const degitConfigName = 'degit.json';
13904
13905class DegitError extends Error {
13906 constructor(message, opts) {
13907 super(message);
13908 Object.assign(this, opts);
13909 }
13910}
13911
13912function tryRequire(file, opts) {
13913 try {
13914 if (opts && opts.clearCache === true) {
13915 delete require.cache[require.resolve(file)];
13916 }
13917 return require(file);
13918 } catch (err) {
13919 return null;
13920 }
13921}
13922
13923function exec(command) {
13924 return new Promise((fulfil, reject) => {
13925 child_process__default['default'].exec(command, (err, stdout, stderr) => {
13926 if (err) {
13927 reject(err);
13928 return;
13929 }
13930
13931 fulfil({ stdout, stderr });
13932 });
13933 });
13934}
13935
13936function mkdirp(dir) {
13937 const parent = path__default['default'].dirname(dir);
13938 if (parent === dir) return;
13939
13940 mkdirp(parent);
13941
13942 try {
13943 fs__default['default'].mkdirSync(dir);
13944 } catch (err) {
13945 if (err.code !== 'EEXIST') throw err;
13946 }
13947}
13948
13949function fetch(url, dest, proxy) {
13950 return new Promise((fulfil, reject) => {
13951 let options = url;
13952
13953 if (proxy) {
13954 const parsedUrl = require$$2__default['default'].parse(url);
13955 options = {
13956 hostname: parsedUrl.host,
13957 path: parsedUrl.path,
13958 agent: new dist(proxy)
13959 };
13960 }
13961
13962 https__default['default']
13963 .get(options, response => {
13964 const code = response.statusCode;
13965 if (code >= 400) {
13966 reject({ code, message: response.statusMessage });
13967 } else if (code >= 300) {
13968 fetch(response.headers.location, dest, proxy).then(fulfil, reject);
13969 } else {
13970 response
13971 .pipe(fs__default['default'].createWriteStream(dest))
13972 .on('finish', () => fulfil())
13973 .on('error', reject);
13974 }
13975 })
13976 .on('error', reject);
13977 });
13978}
13979
13980function stashFiles(dir, dest) {
13981 const tmpDir = path__default['default'].join(dir, tmpDirName);
13982 rimrafSync_1(tmpDir);
13983 mkdirp(tmpDir);
13984 fs__default['default'].readdirSync(dest).forEach(file => {
13985 const filePath = path__default['default'].join(dest, file);
13986 const targetPath = path__default['default'].join(tmpDir, file);
13987 const isDir = fs__default['default'].lstatSync(filePath).isDirectory();
13988 if (isDir) {
13989 copydirSync_1(filePath).to(targetPath);
13990 rimrafSync_1(filePath);
13991 } else {
13992 fs__default['default'].copyFileSync(filePath, targetPath);
13993 fs__default['default'].unlinkSync(filePath);
13994 }
13995 });
13996}
13997
13998function unstashFiles(dir, dest) {
13999 const tmpDir = path__default['default'].join(dir, tmpDirName);
14000 fs__default['default'].readdirSync(tmpDir).forEach(filename => {
14001 const tmpFile = path__default['default'].join(tmpDir, filename);
14002 const targetPath = path__default['default'].join(dest, filename);
14003 const isDir = fs__default['default'].lstatSync(tmpFile).isDirectory();
14004 if (isDir) {
14005 copydirSync_1(tmpFile).to(targetPath);
14006 rimrafSync_1(tmpFile);
14007 } else {
14008 if (filename !== 'degit.json') {
14009 fs__default['default'].copyFileSync(tmpFile, targetPath);
14010 }
14011 fs__default['default'].unlinkSync(tmpFile);
14012 }
14013 });
14014 rimrafSync_1(tmpDir);
14015}
14016
14017const base = path__default['default'].join(homeOrTmp, '.degit');
14018
14019const validModes = new Set(['tar', 'git']);
14020
14021function degit(src, opts) {
14022 return new Degit(src, opts);
14023}
14024
14025class Degit extends Events__default['default'] {
14026 constructor(src, opts = {}) {
14027 super();
14028
14029 this.src = src;
14030 this.cache = opts.cache;
14031 this.force = opts.force;
14032 this.verbose = opts.verbose;
14033 this.proxy = process.env.https_proxy; // TODO allow setting via --proxy
14034
14035 this.repo = parse(src);
14036 this.mode = opts.mode || this.repo.mode;
14037
14038 if (!validModes.has(this.mode)) {
14039 throw new Error(`Valid modes are ${Array.from(validModes).join(', ')}`);
14040 }
14041
14042 this._hasStashed = false;
14043
14044 this.directiveActions = {
14045 clone: async (dir, dest, action) => {
14046 if (this._hasStashed === false) {
14047 stashFiles(dir, dest);
14048 this._hasStashed = true;
14049 }
14050 const opts = Object.assign(
14051 { force: true },
14052 { cache: action.cache, verbose: action.verbose }
14053 );
14054 const d = degit(action.src, opts);
14055
14056 d.on('info', event => {
14057 console.error(
14058 source.cyan(`> ${event.message.replace('options.', '--')}`)
14059 );
14060 });
14061
14062 d.on('warn', event => {
14063 console.error(
14064 source.magenta(`! ${event.message.replace('options.', '--')}`)
14065 );
14066 });
14067
14068 await d.clone(dest).catch(err => {
14069 console.error(source.red(`! ${err.message}`));
14070 process.exit(1);
14071 });
14072 },
14073 remove: this.remove.bind(this)
14074 };
14075 }
14076
14077 _getDirectives(dest) {
14078 const directivesPath = path__default['default'].resolve(dest, degitConfigName);
14079 const directives =
14080 tryRequire(directivesPath, { clearCache: true }) || false;
14081 if (directives) {
14082 fs__default['default'].unlinkSync(directivesPath);
14083 }
14084
14085 return directives;
14086 }
14087
14088 async clone(dest) {
14089 this._checkDirIsEmpty(dest);
14090
14091 const { repo } = this;
14092
14093 const dir = path__default['default'].join(base, repo.site, repo.user, repo.name);
14094
14095 if (this.mode === 'tar') {
14096 await this._cloneWithTar(dir, dest);
14097 } else {
14098 await this._cloneWithGit(dir, dest);
14099 }
14100
14101 this._info({
14102 code: 'SUCCESS',
14103 message: `cloned ${source.bold(repo.user + '/' + repo.name)}#${source.bold(
14104 repo.ref
14105 )}${dest !== '.' ? ` to ${dest}` : ''}`,
14106 repo,
14107 dest
14108 });
14109
14110 const directives = this._getDirectives(dest);
14111 if (directives) {
14112 for (const d of directives) {
14113 // TODO, can this be a loop with an index to pass for better error messages?
14114 await this.directiveActions[d.action](dir, dest, d);
14115 }
14116 if (this._hasStashed === true) {
14117 unstashFiles(dir, dest);
14118 }
14119 }
14120 }
14121
14122 remove(dir, dest, action) {
14123 let files = action.files;
14124 if (!Array.isArray(files)) {
14125 files = [files];
14126 }
14127 const removedFiles = files
14128 .map(file => {
14129 const filePath = path__default['default'].resolve(dest, file);
14130 if (fs__default['default'].existsSync(filePath)) {
14131 const isDir = fs__default['default'].lstatSync(filePath).isDirectory();
14132 if (isDir) {
14133 rimrafSync_1(filePath);
14134 return file + '/';
14135 } else {
14136 fs__default['default'].unlinkSync(filePath);
14137 return file;
14138 }
14139 } else {
14140 this._warn({
14141 code: 'FILE_DOES_NOT_EXIST',
14142 message: `action wants to remove ${source.bold(
14143 file
14144 )} but it does not exist`
14145 });
14146 return null;
14147 }
14148 })
14149 .filter(d => d);
14150
14151 if (removedFiles.length > 0) {
14152 this._info({
14153 code: 'REMOVED',
14154 message: `removed: ${source.bold(
14155 removedFiles.map(d => source.bold(d)).join(', ')
14156 )}`
14157 });
14158 }
14159 }
14160
14161 _checkDirIsEmpty(dir) {
14162 try {
14163 const files = fs__default['default'].readdirSync(dir);
14164 if (files.length > 0) {
14165 if (this.force) {
14166 this._info({
14167 code: 'DEST_NOT_EMPTY',
14168 message: `destination directory is not empty. Using options.force, continuing`
14169 });
14170 } else {
14171 throw new DegitError(
14172 `destination directory is not empty, aborting. Use options.force to override`,
14173 {
14174 code: 'DEST_NOT_EMPTY'
14175 }
14176 );
14177 }
14178 } else {
14179 this._verbose({
14180 code: 'DEST_IS_EMPTY',
14181 message: `destination directory is empty`
14182 });
14183 }
14184 } catch (err) {
14185 if (err.code !== 'ENOENT') throw err;
14186 }
14187 }
14188
14189 _info(info) {
14190 this.emit('info', info);
14191 }
14192
14193 _warn(info) {
14194 this.emit('warn', info);
14195 }
14196
14197 _verbose(info) {
14198 if (this.verbose) this._info(info);
14199 }
14200
14201 async _getHash(repo, cached) {
14202 try {
14203 const refs = await fetchRefs(repo);
14204 if (repo.ref === 'HEAD') {
14205 return refs.find(ref => ref.type === 'HEAD').hash;
14206 }
14207 return this._selectRef(refs, repo.ref);
14208 } catch (err) {
14209 this._warn(err);
14210 this._verbose(err.original);
14211
14212 return this._getHashFromCache(repo, cached);
14213 }
14214 }
14215
14216 _getHashFromCache(repo, cached) {
14217 if (repo.ref in cached) {
14218 const hash = cached[repo.ref];
14219 this._info({
14220 code: 'USING_CACHE',
14221 message: `using cached commit hash ${hash}`
14222 });
14223 return hash;
14224 }
14225 }
14226
14227 _selectRef(refs, selector) {
14228 for (const ref of refs) {
14229 if (ref.name === selector) {
14230 this._verbose({
14231 code: 'FOUND_MATCH',
14232 message: `found matching commit hash: ${ref.hash}`
14233 });
14234 return ref.hash;
14235 }
14236 }
14237
14238 if (selector.length < 8) return null;
14239
14240 for (const ref of refs) {
14241 if (ref.hash.startsWith(selector)) return ref.hash;
14242 }
14243 }
14244
14245 async _cloneWithTar(dir, dest) {
14246 const { repo } = this;
14247
14248 const cached = tryRequire(path__default['default'].join(dir, 'map.json')) || {};
14249
14250 const hash = this.cache
14251 ? this._getHashFromCache(repo, cached)
14252 : await this._getHash(repo, cached);
14253
14254 const subdir = repo.subdir ? `${repo.name}-${hash}${repo.subdir}` : null;
14255
14256 if (!hash) {
14257 // TODO 'did you mean...?'
14258 throw new DegitError(`could not find commit hash for ${repo.ref}`, {
14259 code: 'MISSING_REF',
14260 ref: repo.ref
14261 });
14262 }
14263
14264 const file = `${dir}/${hash}.tar.gz`;
14265 const url =
14266 repo.site === 'gitlab'
14267 ? `${repo.url}/repository/archive.tar.gz?ref=${hash}`
14268 : repo.site === 'bitbucket'
14269 ? `${repo.url}/get/${hash}.tar.gz`
14270 : `${repo.url}/archive/${hash}.tar.gz`;
14271
14272 try {
14273 if (!this.cache) {
14274 try {
14275 fs__default['default'].statSync(file);
14276 this._verbose({
14277 code: 'FILE_EXISTS',
14278 message: `${file} already exists locally`
14279 });
14280 } catch (err) {
14281 mkdirp(path__default['default'].dirname(file));
14282
14283 if (this.proxy) {
14284 this._verbose({
14285 code: 'PROXY',
14286 message: `using proxy ${this.proxy}`
14287 });
14288 }
14289
14290 this._verbose({
14291 code: 'DOWNLOADING',
14292 message: `downloading ${url} to ${file}`
14293 });
14294
14295 await fetch(url, file, this.proxy);
14296 }
14297 }
14298 } catch (err) {
14299 throw new DegitError(`could not download ${url}`, {
14300 code: 'COULD_NOT_DOWNLOAD',
14301 url,
14302 original: err
14303 });
14304 }
14305
14306 updateCache(dir, repo, hash, cached);
14307
14308 this._verbose({
14309 code: 'EXTRACTING',
14310 message: `extracting ${
14311 subdir ? repo.subdir + ' from ' : ''
14312 }${file} to ${dest}`
14313 });
14314
14315 mkdirp(dest);
14316 await untar(file, dest, subdir);
14317 }
14318
14319 async _cloneWithGit(dir, dest) {
14320 await exec(`git clone ${this.repo.ssh} ${dest}`);
14321 await exec(`rm -rf ${path__default['default'].resolve(dest, '.git')}`);
14322 }
14323}
14324
14325const supported = new Set(['github', 'gitlab', 'bitbucket', 'git.sr.ht']);
14326
14327function parse(src) {
14328 const match = /^(?:(?:https:\/\/)?([^:/]+\.[^:/]+)\/|git@([^:/]+)[:/]|([^/]+):)?([^/\s]+)\/([^/\s#]+)(?:((?:\/[^/\s#]+)+))?(?:\/)?(?:#(.+))?/.exec(
14329 src
14330 );
14331 if (!match) {
14332 throw new DegitError(`could not parse ${src}`, {
14333 code: 'BAD_SRC'
14334 });
14335 }
14336
14337 const site = (match[1] || match[2] || match[3] || 'github').replace(
14338 /\.(com|org)$/,
14339 ''
14340 );
14341 if (!supported.has(site)) {
14342 throw new DegitError(
14343 `degit supports GitHub, GitLab, Sourcehut and BitBucket`,
14344 {
14345 code: 'UNSUPPORTED_HOST'
14346 }
14347 );
14348 }
14349
14350 const user = match[4];
14351 const name = match[5].replace(/\.git$/, '');
14352 const subdir = match[6];
14353 const ref = match[7] || 'HEAD';
14354
14355 const domain = `${site}.${
14356 site === 'bitbucket' ? 'org' : site === 'git.sr.ht' ? '' : 'com'
14357 }`;
14358 const url = `https://${domain}/${user}/${name}`;
14359 const ssh = `git@${domain}:${user}/${name}`;
14360
14361 const mode = supported.has(site) ? 'tar' : 'git';
14362
14363 return { site, user, name, ref, url, ssh, subdir, mode };
14364}
14365
14366async function untar(file, dest, subdir = null) {
14367 return tar.extract(
14368 {
14369 file,
14370 strip: subdir ? subdir.split('/').length : 1,
14371 C: dest
14372 },
14373 subdir ? [subdir] : []
14374 );
14375}
14376
14377async function fetchRefs(repo) {
14378 try {
14379 const { stdout } = await exec(`git ls-remote ${repo.url}`);
14380
14381 return stdout
14382 .split('\n')
14383 .filter(Boolean)
14384 .map(row => {
14385 const [hash, ref] = row.split('\t');
14386
14387 if (ref === 'HEAD') {
14388 return {
14389 type: 'HEAD',
14390 hash
14391 };
14392 }
14393
14394 const match = /refs\/(\w+)\/(.+)/.exec(ref);
14395 if (!match)
14396 throw new DegitError(`could not parse ${ref}`, {
14397 code: 'BAD_REF'
14398 });
14399
14400 return {
14401 type:
14402 match[1] === 'heads'
14403 ? 'branch'
14404 : match[1] === 'refs'
14405 ? 'ref'
14406 : match[1],
14407 name: match[2],
14408 hash
14409 };
14410 });
14411 } catch (error) {
14412 throw new DegitError(`could not fetch remote ${repo.url}`, {
14413 code: 'COULD_NOT_FETCH',
14414 url: repo.url,
14415 original: error
14416 });
14417 }
14418}
14419
14420function updateCache(dir, repo, hash, cached) {
14421 // update access logs
14422 const logs = tryRequire(path__default['default'].join(dir, 'access.json')) || {};
14423 logs[repo.ref] = new Date().toISOString();
14424 fs__default['default'].writeFileSync(
14425 path__default['default'].join(dir, 'access.json'),
14426 JSON.stringify(logs, null, ' ')
14427 );
14428
14429 if (cached[repo.ref] === hash) return;
14430
14431 const oldHash = cached[repo.ref];
14432 if (oldHash) {
14433 let used = false;
14434 for (const key in cached) {
14435 if (cached[key] === hash) {
14436 used = true;
14437 break;
14438 }
14439 }
14440
14441 if (!used) {
14442 // we no longer need this tar file
14443 try {
14444 fs__default['default'].unlinkSync(path__default['default'].join(dir, `${oldHash}.tar.gz`));
14445 } catch (err) {
14446 // ignore
14447 }
14448 }
14449 }
14450
14451 cached[repo.ref] = hash;
14452 fs__default['default'].writeFileSync(
14453 path__default['default'].join(dir, 'map.json'),
14454 JSON.stringify(cached, null, ' ')
14455 );
14456}
14457
14458exports.base = base;
14459exports.createCommonjsModule = createCommonjsModule;
14460exports.degit = degit;
14461exports.source = source;
14462exports.tryRequire = tryRequire;
14463//# sourceMappingURL=index-688c5d50.js.map