UNPKG

402 kBJavaScriptView Raw
1#!/usr/bin/env node
2'use strict';
3
4function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
5
6var util = _interopDefault(require('util'));
7var fs = _interopDefault(require('fs'));
8var path = _interopDefault(require('path'));
9var tty = _interopDefault(require('tty'));
10var os = _interopDefault(require('os'));
11var readableStream = _interopDefault(require('stream'));
12var zlib = _interopDefault(require('zlib'));
13var stream = _interopDefault(require('stream'));
14var events = _interopDefault(require('events'));
15var buffer = _interopDefault(require('buffer'));
16var url = _interopDefault(require('url'));
17var http = _interopDefault(require('http'));
18var https = _interopDefault(require('https'));
19var net = _interopDefault(require('net'));
20var assert = _interopDefault(require('assert'));
21
22function commonjsRequire () {
23 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
24}
25
26function unwrapExports (x) {
27 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x;
28}
29
30function createCommonjsModule(fn, module) {
31 return module = { exports: {} }, fn(module, module.exports), module.exports;
32}
33
34function getCjsExportFromNamespace (n) {
35 return n && n.default || n;
36}
37
38var hasFlag = (flag, argv) => {
39 argv = argv || process.argv;
40 const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
41 const pos = argv.indexOf(prefix + flag);
42 const terminatorPos = argv.indexOf('--');
43 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
44};
45
46const env = process.env;
47
48let forceColor;
49if (hasFlag('no-color') ||
50 hasFlag('no-colors') ||
51 hasFlag('color=false')) {
52 forceColor = false;
53} else if (hasFlag('color') ||
54 hasFlag('colors') ||
55 hasFlag('color=true') ||
56 hasFlag('color=always')) {
57 forceColor = true;
58}
59if ('FORCE_COLOR' in env) {
60 forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
61}
62
63function translateLevel(level) {
64 if (level === 0) {
65 return false;
66 }
67
68 return {
69 level,
70 hasBasic: true,
71 has256: level >= 2,
72 has16m: level >= 3
73 };
74}
75
76function supportsColor(stream$$1) {
77 if (forceColor === false) {
78 return 0;
79 }
80
81 if (hasFlag('color=16m') ||
82 hasFlag('color=full') ||
83 hasFlag('color=truecolor')) {
84 return 3;
85 }
86
87 if (hasFlag('color=256')) {
88 return 2;
89 }
90
91 if (stream$$1 && !stream$$1.isTTY && forceColor !== true) {
92 return 0;
93 }
94
95 const min = forceColor ? 1 : 0;
96
97 if (process.platform === 'win32') {
98 // Node.js 7.5.0 is the first version of Node.js to include a patch to
99 // libuv that enables 256 color output on Windows. Anything earlier and it
100 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
101 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
102 // release that supports 256 colors. Windows 10 build 14931 is the first release
103 // that supports 16m/TrueColor.
104 const osRelease = os.release().split('.');
105 if (
106 Number(process.versions.node.split('.')[0]) >= 8 &&
107 Number(osRelease[0]) >= 10 &&
108 Number(osRelease[2]) >= 10586
109 ) {
110 return Number(osRelease[2]) >= 14931 ? 3 : 2;
111 }
112
113 return 1;
114 }
115
116 if ('CI' in env) {
117 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
118 return 1;
119 }
120
121 return min;
122 }
123
124 if ('TEAMCITY_VERSION' in env) {
125 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
126 }
127
128 if (env.COLORTERM === 'truecolor') {
129 return 3;
130 }
131
132 if ('TERM_PROGRAM' in env) {
133 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
134
135 switch (env.TERM_PROGRAM) {
136 case 'iTerm.app':
137 return version >= 3 ? 3 : 2;
138 case 'Apple_Terminal':
139 return 2;
140 // No default
141 }
142 }
143
144 if (/-256(color)?$/i.test(env.TERM)) {
145 return 2;
146 }
147
148 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
149 return 1;
150 }
151
152 if ('COLORTERM' in env) {
153 return 1;
154 }
155
156 if (env.TERM === 'dumb') {
157 return min;
158 }
159
160 return min;
161}
162
163function getSupportLevel(stream$$1) {
164 const level = supportsColor(stream$$1);
165 return translateLevel(level);
166}
167
168var supportsColor_1 = {
169 supportsColor: getSupportLevel,
170 stdout: getSupportLevel(process.stdout),
171 stderr: getSupportLevel(process.stderr)
172};
173
174/**
175 * Helpers.
176 */
177
178var s = 1000;
179var m = s * 60;
180var h = m * 60;
181var d = h * 24;
182var w = d * 7;
183var y = d * 365.25;
184
185/**
186 * Parse or format the given `val`.
187 *
188 * Options:
189 *
190 * - `long` verbose formatting [false]
191 *
192 * @param {String|Number} val
193 * @param {Object} [options]
194 * @throws {Error} throw an error if val is not a non-empty string or a number
195 * @return {String|Number}
196 * @api public
197 */
198
199var ms = function(val, options) {
200 options = options || {};
201 var type = typeof val;
202 if (type === 'string' && val.length > 0) {
203 return parse(val);
204 } else if (type === 'number' && isNaN(val) === false) {
205 return options.long ? fmtLong(val) : fmtShort(val);
206 }
207 throw new Error(
208 'val is not a non-empty string or a valid number. val=' +
209 JSON.stringify(val)
210 );
211};
212
213/**
214 * Parse the given `str` and return milliseconds.
215 *
216 * @param {String} str
217 * @return {Number}
218 * @api private
219 */
220
221function parse(str) {
222 str = String(str);
223 if (str.length > 100) {
224 return;
225 }
226 var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
227 str
228 );
229 if (!match) {
230 return;
231 }
232 var n = parseFloat(match[1]);
233 var type = (match[2] || 'ms').toLowerCase();
234 switch (type) {
235 case 'years':
236 case 'year':
237 case 'yrs':
238 case 'yr':
239 case 'y':
240 return n * y;
241 case 'weeks':
242 case 'week':
243 case 'w':
244 return n * w;
245 case 'days':
246 case 'day':
247 case 'd':
248 return n * d;
249 case 'hours':
250 case 'hour':
251 case 'hrs':
252 case 'hr':
253 case 'h':
254 return n * h;
255 case 'minutes':
256 case 'minute':
257 case 'mins':
258 case 'min':
259 case 'm':
260 return n * m;
261 case 'seconds':
262 case 'second':
263 case 'secs':
264 case 'sec':
265 case 's':
266 return n * s;
267 case 'milliseconds':
268 case 'millisecond':
269 case 'msecs':
270 case 'msec':
271 case 'ms':
272 return n;
273 default:
274 return undefined;
275 }
276}
277
278/**
279 * Short format for `ms`.
280 *
281 * @param {Number} ms
282 * @return {String}
283 * @api private
284 */
285
286function fmtShort(ms) {
287 var msAbs = Math.abs(ms);
288 if (msAbs >= d) {
289 return Math.round(ms / d) + 'd';
290 }
291 if (msAbs >= h) {
292 return Math.round(ms / h) + 'h';
293 }
294 if (msAbs >= m) {
295 return Math.round(ms / m) + 'm';
296 }
297 if (msAbs >= s) {
298 return Math.round(ms / s) + 's';
299 }
300 return ms + 'ms';
301}
302
303/**
304 * Long format for `ms`.
305 *
306 * @param {Number} ms
307 * @return {String}
308 * @api private
309 */
310
311function fmtLong(ms) {
312 var msAbs = Math.abs(ms);
313 if (msAbs >= d) {
314 return plural(ms, msAbs, d, 'day');
315 }
316 if (msAbs >= h) {
317 return plural(ms, msAbs, h, 'hour');
318 }
319 if (msAbs >= m) {
320 return plural(ms, msAbs, m, 'minute');
321 }
322 if (msAbs >= s) {
323 return plural(ms, msAbs, s, 'second');
324 }
325 return ms + ' ms';
326}
327
328/**
329 * Pluralization helper.
330 */
331
332function plural(ms, msAbs, n, name) {
333 var isPlural = msAbs >= n * 1.5;
334 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
335}
336
337/**
338 * This is the common logic for both the Node.js and web browser
339 * implementations of `debug()`.
340 */
341
342function setup(env) {
343 createDebug.debug = createDebug;
344 createDebug.default = createDebug;
345 createDebug.coerce = coerce;
346 createDebug.disable = disable;
347 createDebug.enable = enable;
348 createDebug.enabled = enabled;
349 createDebug.humanize = ms;
350
351 Object.keys(env).forEach(key => {
352 createDebug[key] = env[key];
353 });
354
355 /**
356 * Active `debug` instances.
357 */
358 createDebug.instances = [];
359
360 /**
361 * The currently active debug mode names, and names to skip.
362 */
363
364 createDebug.names = [];
365 createDebug.skips = [];
366
367 /**
368 * Map of special "%n" handling functions, for the debug "format" argument.
369 *
370 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
371 */
372 createDebug.formatters = {};
373
374 /**
375 * Selects a color for a debug namespace
376 * @param {String} namespace The namespace string for the for the debug instance to be colored
377 * @return {Number|String} An ANSI color code for the given namespace
378 * @api private
379 */
380 function selectColor(namespace) {
381 let hash = 0;
382
383 for (let i = 0; i < namespace.length; i++) {
384 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
385 hash |= 0; // Convert to 32bit integer
386 }
387
388 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
389 }
390 createDebug.selectColor = selectColor;
391
392 /**
393 * Create a debugger with the given `namespace`.
394 *
395 * @param {String} namespace
396 * @return {Function}
397 * @api public
398 */
399 function createDebug(namespace) {
400 let prevTime;
401
402 function debug(...args) {
403 // Disabled?
404 if (!debug.enabled) {
405 return;
406 }
407
408 const self = debug;
409
410 // Set `diff` timestamp
411 const curr = Number(new Date());
412 const ms$$1 = curr - (prevTime || curr);
413 self.diff = ms$$1;
414 self.prev = prevTime;
415 self.curr = curr;
416 prevTime = curr;
417
418 args[0] = createDebug.coerce(args[0]);
419
420 if (typeof args[0] !== 'string') {
421 // Anything else let's inspect with %O
422 args.unshift('%O');
423 }
424
425 // Apply any `formatters` transformations
426 let index = 0;
427 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
428 // If we encounter an escaped % then don't increase the array index
429 if (match === '%%') {
430 return match;
431 }
432 index++;
433 const formatter = createDebug.formatters[format];
434 if (typeof formatter === 'function') {
435 const val = args[index];
436 match = formatter.call(self, val);
437
438 // Now we need to remove `args[index]` since it's inlined in the `format`
439 args.splice(index, 1);
440 index--;
441 }
442 return match;
443 });
444
445 // Apply env-specific formatting (colors, etc.)
446 createDebug.formatArgs.call(self, args);
447
448 const logFn = self.log || createDebug.log;
449 logFn.apply(self, args);
450 }
451
452 debug.namespace = namespace;
453 debug.enabled = createDebug.enabled(namespace);
454 debug.useColors = createDebug.useColors();
455 debug.color = selectColor(namespace);
456 debug.destroy = destroy;
457 debug.extend = extend;
458 // Debug.formatArgs = formatArgs;
459 // debug.rawLog = rawLog;
460
461 // env-specific initialization logic for debug instances
462 if (typeof createDebug.init === 'function') {
463 createDebug.init(debug);
464 }
465
466 createDebug.instances.push(debug);
467
468 return debug;
469 }
470
471 function destroy() {
472 const index = createDebug.instances.indexOf(this);
473 if (index !== -1) {
474 createDebug.instances.splice(index, 1);
475 return true;
476 }
477 return false;
478 }
479
480 function extend(namespace, delimiter) {
481 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
482 newDebug.log = this.log;
483 return newDebug;
484 }
485
486 /**
487 * Enables a debug mode by namespaces. This can include modes
488 * separated by a colon and wildcards.
489 *
490 * @param {String} namespaces
491 * @api public
492 */
493 function enable(namespaces) {
494 createDebug.save(namespaces);
495
496 createDebug.names = [];
497 createDebug.skips = [];
498
499 let i;
500 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
501 const len = split.length;
502
503 for (i = 0; i < len; i++) {
504 if (!split[i]) {
505 // ignore empty strings
506 continue;
507 }
508
509 namespaces = split[i].replace(/\*/g, '.*?');
510
511 if (namespaces[0] === '-') {
512 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
513 } else {
514 createDebug.names.push(new RegExp('^' + namespaces + '$'));
515 }
516 }
517
518 for (i = 0; i < createDebug.instances.length; i++) {
519 const instance = createDebug.instances[i];
520 instance.enabled = createDebug.enabled(instance.namespace);
521 }
522 }
523
524 /**
525 * Disable debug output.
526 *
527 * @return {String} namespaces
528 * @api public
529 */
530 function disable() {
531 const namespaces = [
532 ...createDebug.names.map(toNamespace),
533 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
534 ].join(',');
535 createDebug.enable('');
536 return namespaces;
537 }
538
539 /**
540 * Returns true if the given mode name is enabled, false otherwise.
541 *
542 * @param {String} name
543 * @return {Boolean}
544 * @api public
545 */
546 function enabled(name) {
547 if (name[name.length - 1] === '*') {
548 return true;
549 }
550
551 let i;
552 let len;
553
554 for (i = 0, len = createDebug.skips.length; i < len; i++) {
555 if (createDebug.skips[i].test(name)) {
556 return false;
557 }
558 }
559
560 for (i = 0, len = createDebug.names.length; i < len; i++) {
561 if (createDebug.names[i].test(name)) {
562 return true;
563 }
564 }
565
566 return false;
567 }
568
569 /**
570 * Convert regexp to namespace
571 *
572 * @param {RegExp} regxep
573 * @return {String} namespace
574 * @api private
575 */
576 function toNamespace(regexp) {
577 return regexp.toString()
578 .substring(2, regexp.toString().length - 2)
579 .replace(/\.\*\?$/, '*');
580 }
581
582 /**
583 * Coerce `val`.
584 *
585 * @param {Mixed} val
586 * @return {Mixed}
587 * @api private
588 */
589 function coerce(val) {
590 if (val instanceof Error) {
591 return val.stack || val.message;
592 }
593 return val;
594 }
595
596 createDebug.enable(createDebug.load());
597
598 return createDebug;
599}
600
601var common = setup;
602
603var node = createCommonjsModule(function (module, exports) {
604/**
605 * Module dependencies.
606 */
607
608
609
610
611/**
612 * This is the Node.js implementation of `debug()`.
613 */
614
615exports.init = init;
616exports.log = log;
617exports.formatArgs = formatArgs;
618exports.save = save;
619exports.load = load;
620exports.useColors = useColors;
621
622/**
623 * Colors.
624 */
625
626exports.colors = [6, 2, 3, 4, 5, 1];
627
628try {
629 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
630 // eslint-disable-next-line import/no-extraneous-dependencies
631 const supportsColor = supportsColor_1;
632
633 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
634 exports.colors = [
635 20,
636 21,
637 26,
638 27,
639 32,
640 33,
641 38,
642 39,
643 40,
644 41,
645 42,
646 43,
647 44,
648 45,
649 56,
650 57,
651 62,
652 63,
653 68,
654 69,
655 74,
656 75,
657 76,
658 77,
659 78,
660 79,
661 80,
662 81,
663 92,
664 93,
665 98,
666 99,
667 112,
668 113,
669 128,
670 129,
671 134,
672 135,
673 148,
674 149,
675 160,
676 161,
677 162,
678 163,
679 164,
680 165,
681 166,
682 167,
683 168,
684 169,
685 170,
686 171,
687 172,
688 173,
689 178,
690 179,
691 184,
692 185,
693 196,
694 197,
695 198,
696 199,
697 200,
698 201,
699 202,
700 203,
701 204,
702 205,
703 206,
704 207,
705 208,
706 209,
707 214,
708 215,
709 220,
710 221
711 ];
712 }
713} catch (error) {
714 // Swallow - we only care if `supports-color` is available; it doesn't have to be.
715}
716
717/**
718 * Build up the default `inspectOpts` object from the environment variables.
719 *
720 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
721 */
722
723exports.inspectOpts = Object.keys(process.env).filter(key => {
724 return /^debug_/i.test(key);
725}).reduce((obj, key) => {
726 // Camel-case
727 const prop = key
728 .substring(6)
729 .toLowerCase()
730 .replace(/_([a-z])/g, (_, k) => {
731 return k.toUpperCase();
732 });
733
734 // Coerce string value into JS value
735 let val = process.env[key];
736 if (/^(yes|on|true|enabled)$/i.test(val)) {
737 val = true;
738 } else if (/^(no|off|false|disabled)$/i.test(val)) {
739 val = false;
740 } else if (val === 'null') {
741 val = null;
742 } else {
743 val = Number(val);
744 }
745
746 obj[prop] = val;
747 return obj;
748}, {});
749
750/**
751 * Is stdout a TTY? Colored output is enabled when `true`.
752 */
753
754function useColors() {
755 return 'colors' in exports.inspectOpts ?
756 Boolean(exports.inspectOpts.colors) :
757 tty.isatty(process.stderr.fd);
758}
759
760/**
761 * Adds ANSI color escape codes if enabled.
762 *
763 * @api public
764 */
765
766function formatArgs(args) {
767 const {namespace: name, useColors} = this;
768
769 if (useColors) {
770 const c = this.color;
771 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
772 const prefix = ` ${colorCode};1m${name} \u001B[0m`;
773
774 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
775 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
776 } else {
777 args[0] = getDate() + name + ' ' + args[0];
778 }
779}
780
781function getDate() {
782 if (exports.inspectOpts.hideDate) {
783 return '';
784 }
785 return new Date().toISOString() + ' ';
786}
787
788/**
789 * Invokes `util.format()` with the specified arguments and writes to stderr.
790 */
791
792function log(...args) {
793 return process.stderr.write(util.format(...args) + '\n');
794}
795
796/**
797 * Save `namespaces`.
798 *
799 * @param {String} namespaces
800 * @api private
801 */
802function save(namespaces) {
803 if (namespaces) {
804 process.env.DEBUG = namespaces;
805 } else {
806 // If you set a process.env field to null or undefined, it gets cast to the
807 // string 'null' or 'undefined'. Just delete instead.
808 delete process.env.DEBUG;
809 }
810}
811
812/**
813 * Load `namespaces`.
814 *
815 * @return {String} returns the previously persisted debug modes
816 * @api private
817 */
818
819function load() {
820 return process.env.DEBUG;
821}
822
823/**
824 * Init logic for `debug` instances.
825 *
826 * Create a new `inspectOpts` object in case `useColors` is set
827 * differently for a particular `debug` instance.
828 */
829
830function init(debug) {
831 debug.inspectOpts = {};
832
833 const keys = Object.keys(exports.inspectOpts);
834 for (let i = 0; i < keys.length; i++) {
835 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
836 }
837}
838
839module.exports = common(exports);
840
841const {formatters} = module.exports;
842
843/**
844 * Map %o to `util.inspect()`, all on a single line.
845 */
846
847formatters.o = function (v) {
848 this.inspectOpts.colors = this.useColors;
849 return util.inspect(v, this.inspectOpts)
850 .replace(/\s*\n\s*/g, ' ');
851};
852
853/**
854 * Map %O to `util.inspect()`, allowing multiple lines if needed.
855 */
856
857formatters.O = function (v) {
858 this.inspectOpts.colors = this.useColors;
859 return util.inspect(v, this.inspectOpts);
860};
861});
862var node_1 = node.init;
863var node_2 = node.log;
864var node_3 = node.formatArgs;
865var node_4 = node.save;
866var node_5 = node.load;
867var node_6 = node.useColors;
868var node_7 = node.colors;
869var node_8 = node.inspectOpts;
870
871// Returns a wrapper function that returns a wrapped callback
872// The wrapper function should do some stuff, and return a
873// presumably different callback function.
874// This makes sure that own properties are retained, so that
875// decorations and such are not lost along the way.
876var wrappy_1 = wrappy;
877function wrappy (fn, cb) {
878 if (fn && cb) return wrappy(fn)(cb)
879
880 if (typeof fn !== 'function')
881 throw new TypeError('need wrapper function')
882
883 Object.keys(fn).forEach(function (k) {
884 wrapper[k] = fn[k];
885 });
886
887 return wrapper
888
889 function wrapper() {
890 var args = new Array(arguments.length);
891 for (var i = 0; i < args.length; i++) {
892 args[i] = arguments[i];
893 }
894 var ret = fn.apply(this, args);
895 var cb = args[args.length-1];
896 if (typeof ret === 'function' && ret !== cb) {
897 Object.keys(cb).forEach(function (k) {
898 ret[k] = cb[k];
899 });
900 }
901 return ret
902 }
903}
904
905var once_1 = wrappy_1(once);
906var strict = wrappy_1(onceStrict);
907
908once.proto = once(function () {
909 Object.defineProperty(Function.prototype, 'once', {
910 value: function () {
911 return once(this)
912 },
913 configurable: true
914 });
915
916 Object.defineProperty(Function.prototype, 'onceStrict', {
917 value: function () {
918 return onceStrict(this)
919 },
920 configurable: true
921 });
922});
923
924function once (fn) {
925 var f = function () {
926 if (f.called) return f.value
927 f.called = true;
928 return f.value = fn.apply(this, arguments)
929 };
930 f.called = false;
931 return f
932}
933
934function onceStrict (fn) {
935 var f = function () {
936 if (f.called)
937 throw new Error(f.onceError)
938 f.called = true;
939 return f.value = fn.apply(this, arguments)
940 };
941 var name = fn.name || 'Function wrapped with `once`';
942 f.onceError = name + " shouldn't be called more than once";
943 f.called = false;
944 return f
945}
946once_1.strict = strict;
947
948var noop = function() {};
949
950var isRequest = function(stream$$1) {
951 return stream$$1.setHeader && typeof stream$$1.abort === 'function';
952};
953
954var isChildProcess = function(stream$$1) {
955 return stream$$1.stdio && Array.isArray(stream$$1.stdio) && stream$$1.stdio.length === 3
956};
957
958var eos = function(stream$$1, opts, callback) {
959 if (typeof opts === 'function') return eos(stream$$1, null, opts);
960 if (!opts) opts = {};
961
962 callback = once_1(callback || noop);
963
964 var ws = stream$$1._writableState;
965 var rs = stream$$1._readableState;
966 var readable = opts.readable || (opts.readable !== false && stream$$1.readable);
967 var writable = opts.writable || (opts.writable !== false && stream$$1.writable);
968
969 var onlegacyfinish = function() {
970 if (!stream$$1.writable) onfinish();
971 };
972
973 var onfinish = function() {
974 writable = false;
975 if (!readable) callback.call(stream$$1);
976 };
977
978 var onend = function() {
979 readable = false;
980 if (!writable) callback.call(stream$$1);
981 };
982
983 var onexit = function(exitCode) {
984 callback.call(stream$$1, exitCode ? new Error('exited with error code: ' + exitCode) : null);
985 };
986
987 var onerror = function(err) {
988 callback.call(stream$$1, err);
989 };
990
991 var onclose = function() {
992 if (readable && !(rs && rs.ended)) return callback.call(stream$$1, new Error('premature close'));
993 if (writable && !(ws && ws.ended)) return callback.call(stream$$1, new Error('premature close'));
994 };
995
996 var onrequest = function() {
997 stream$$1.req.on('finish', onfinish);
998 };
999
1000 if (isRequest(stream$$1)) {
1001 stream$$1.on('complete', onfinish);
1002 stream$$1.on('abort', onclose);
1003 if (stream$$1.req) onrequest();
1004 else stream$$1.on('request', onrequest);
1005 } else if (writable && !ws) { // legacy streams
1006 stream$$1.on('end', onlegacyfinish);
1007 stream$$1.on('close', onlegacyfinish);
1008 }
1009
1010 if (isChildProcess(stream$$1)) stream$$1.on('exit', onexit);
1011
1012 stream$$1.on('end', onend);
1013 stream$$1.on('finish', onfinish);
1014 if (opts.error !== false) stream$$1.on('error', onerror);
1015 stream$$1.on('close', onclose);
1016
1017 return function() {
1018 stream$$1.removeListener('complete', onfinish);
1019 stream$$1.removeListener('abort', onclose);
1020 stream$$1.removeListener('request', onrequest);
1021 if (stream$$1.req) stream$$1.req.removeListener('finish', onfinish);
1022 stream$$1.removeListener('end', onlegacyfinish);
1023 stream$$1.removeListener('close', onlegacyfinish);
1024 stream$$1.removeListener('finish', onfinish);
1025 stream$$1.removeListener('exit', onexit);
1026 stream$$1.removeListener('end', onend);
1027 stream$$1.removeListener('error', onerror);
1028 stream$$1.removeListener('close', onclose);
1029 };
1030};
1031
1032var endOfStream = eos;
1033
1034// we only need fs to get the ReadStream and WriteStream prototypes
1035
1036var noop$1 = function () {};
1037var ancient = /^v?\.0/.test(process.version);
1038
1039var isFn = function (fn) {
1040 return typeof fn === 'function'
1041};
1042
1043var isFS = function (stream$$1) {
1044 if (!ancient) return false // newer node version do not need to care about fs is a special way
1045 if (!fs) return false // browser
1046 return (stream$$1 instanceof (fs.ReadStream || noop$1) || stream$$1 instanceof (fs.WriteStream || noop$1)) && isFn(stream$$1.close)
1047};
1048
1049var isRequest$1 = function (stream$$1) {
1050 return stream$$1.setHeader && isFn(stream$$1.abort)
1051};
1052
1053var destroyer = function (stream$$1, reading, writing, callback) {
1054 callback = once_1(callback);
1055
1056 var closed = false;
1057 stream$$1.on('close', function () {
1058 closed = true;
1059 });
1060
1061 endOfStream(stream$$1, {readable: reading, writable: writing}, function (err) {
1062 if (err) return callback(err)
1063 closed = true;
1064 callback();
1065 });
1066
1067 var destroyed = false;
1068 return function (err) {
1069 if (closed) return
1070 if (destroyed) return
1071 destroyed = true;
1072
1073 if (isFS(stream$$1)) return stream$$1.close(noop$1) // use close for fs streams to avoid fd leaks
1074 if (isRequest$1(stream$$1)) return stream$$1.abort() // request.destroy just do .end - .abort is what we want
1075
1076 if (isFn(stream$$1.destroy)) return stream$$1.destroy()
1077
1078 callback(err || new Error('stream was destroyed'));
1079 }
1080};
1081
1082var call = function (fn) {
1083 fn();
1084};
1085
1086var pipe = function (from, to) {
1087 return from.pipe(to)
1088};
1089
1090var pump = function () {
1091 var streams = Array.prototype.slice.call(arguments);
1092 var callback = isFn(streams[streams.length - 1] || noop$1) && streams.pop() || noop$1;
1093
1094 if (Array.isArray(streams[0])) streams = streams[0];
1095 if (streams.length < 2) throw new Error('pump requires two streams per minimum')
1096
1097 var error;
1098 var destroys = streams.map(function (stream$$1, i) {
1099 var reading = i < streams.length - 1;
1100 var writing = i > 0;
1101 return destroyer(stream$$1, reading, writing, function (err) {
1102 if (!error) error = err;
1103 if (err) destroys.forEach(call);
1104 if (reading) return
1105 destroys.forEach(call);
1106 callback(error);
1107 })
1108 });
1109
1110 return streams.reduce(pipe)
1111};
1112
1113var pump_1 = pump;
1114
1115var streamShift = shift;
1116
1117function shift (stream$$1) {
1118 var rs = stream$$1._readableState;
1119 if (!rs) return null
1120 return rs.objectMode ? stream$$1.read() : stream$$1.read(getStateLength(rs))
1121}
1122
1123function getStateLength (state) {
1124 if (state.buffer.length) {
1125 // Since node 6.3.0 state.buffer is a BufferList not an array
1126 if (state.buffer.head) {
1127 return state.buffer.head.data.length
1128 }
1129
1130 return state.buffer[0].length
1131 }
1132
1133 return state.length
1134}
1135
1136var streamEach = each;
1137
1138function each (stream$$1, fn, cb) {
1139 var want = true;
1140 var error = null;
1141 var ended = false;
1142 var running = false;
1143 var calling = false;
1144
1145 stream$$1.on('readable', onreadable);
1146 onreadable();
1147
1148 if (cb) endOfStream(stream$$1, {readable: true, writable: false}, done);
1149 return stream$$1
1150
1151 function done (err) {
1152 if (!error) error = err;
1153 ended = true;
1154 if (!running) cb(error);
1155 }
1156
1157 function onreadable () {
1158 if (want) read();
1159 }
1160
1161 function afterRead (err) {
1162 running = false;
1163
1164 if (err) {
1165 error = err;
1166 if (ended) return cb(error)
1167 stream$$1.destroy(err);
1168 return
1169 }
1170 if (ended) return cb(error)
1171 if (!calling) read();
1172 }
1173
1174 function read () {
1175 while (!running && !ended) {
1176 want = false;
1177
1178 var data = streamShift(stream$$1);
1179 if (ended) return
1180 if (data === null) {
1181 want = true;
1182 return
1183 }
1184
1185 running = true;
1186 calling = true;
1187 fn(data, afterRead);
1188 calling = false;
1189 }
1190 }
1191}
1192
1193// we only need fs to get the ReadStream and WriteStream prototypes
1194
1195var noop$2 = function () {};
1196var ancient$1 = /^v?\.0/.test(process.version);
1197
1198var isFn$1 = function (fn) {
1199 return typeof fn === 'function'
1200};
1201
1202var isFS$1 = function (stream$$1) {
1203 if (!ancient$1) return false // newer node version do not need to care about fs is a special way
1204 if (!fs) return false // browser
1205 return (stream$$1 instanceof (fs.ReadStream || noop$2) || stream$$1 instanceof (fs.WriteStream || noop$2)) && isFn$1(stream$$1.close)
1206};
1207
1208var isRequest$2 = function (stream$$1) {
1209 return stream$$1.setHeader && isFn$1(stream$$1.abort)
1210};
1211
1212var destroyer$1 = function (stream$$1, reading, writing, callback) {
1213 callback = once_1(callback);
1214
1215 var closed = false;
1216 stream$$1.on('close', function () {
1217 closed = true;
1218 });
1219
1220 endOfStream(stream$$1, {readable: reading, writable: writing}, function (err) {
1221 if (err) return callback(err)
1222 closed = true;
1223 callback();
1224 });
1225
1226 var destroyed = false;
1227 return function (err) {
1228 if (closed) return
1229 if (destroyed) return
1230 destroyed = true;
1231
1232 if (isFS$1(stream$$1)) return stream$$1.close(noop$2) // use close for fs streams to avoid fd leaks
1233 if (isRequest$2(stream$$1)) return stream$$1.abort() // request.destroy just do .end - .abort is what we want
1234
1235 if (isFn$1(stream$$1.destroy)) return stream$$1.destroy()
1236
1237 callback(err || new Error('stream was destroyed'));
1238 }
1239};
1240
1241var call$1 = function (fn) {
1242 fn();
1243};
1244
1245var pipe$1 = function (from, to) {
1246 return from.pipe(to)
1247};
1248
1249var pump$1 = function () {
1250 var streams = Array.prototype.slice.call(arguments);
1251 var callback = isFn$1(streams[streams.length - 1] || noop$2) && streams.pop() || noop$2;
1252
1253 if (Array.isArray(streams[0])) streams = streams[0];
1254 if (streams.length < 2) throw new Error('pump requires two streams per minimum')
1255
1256 var error;
1257 var destroys = streams.map(function (stream$$1, i) {
1258 var reading = i < streams.length - 1;
1259 var writing = i > 0;
1260 return destroyer$1(stream$$1, reading, writing, function (err) {
1261 if (!error) error = err;
1262 if (err) destroys.forEach(call$1);
1263 if (reading) return
1264 destroys.forEach(call$1);
1265 callback(error);
1266 })
1267 });
1268
1269 streams.reduce(pipe$1);
1270};
1271
1272var pump_1$1 = pump$1;
1273
1274var inherits_browser = createCommonjsModule(function (module) {
1275if (typeof Object.create === 'function') {
1276 // implementation from standard node.js 'util' module
1277 module.exports = function inherits(ctor, superCtor) {
1278 ctor.super_ = superCtor;
1279 ctor.prototype = Object.create(superCtor.prototype, {
1280 constructor: {
1281 value: ctor,
1282 enumerable: false,
1283 writable: true,
1284 configurable: true
1285 }
1286 });
1287 };
1288} else {
1289 // old school shim for old browsers
1290 module.exports = function inherits(ctor, superCtor) {
1291 ctor.super_ = superCtor;
1292 var TempCtor = function () {};
1293 TempCtor.prototype = superCtor.prototype;
1294 ctor.prototype = new TempCtor();
1295 ctor.prototype.constructor = ctor;
1296 };
1297}
1298});
1299
1300var inherits = createCommonjsModule(function (module) {
1301try {
1302 var util$$1 = util;
1303 if (typeof util$$1.inherits !== 'function') throw '';
1304 module.exports = util$$1.inherits;
1305} catch (e) {
1306 module.exports = inherits_browser;
1307}
1308});
1309
1310var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from)
1311 ? Buffer.from([0])
1312 : new Buffer([0]);
1313
1314var onuncork = function(self, fn) {
1315 if (self._corked) self.once('uncork', fn);
1316 else fn();
1317};
1318
1319var autoDestroy = function (self, err) {
1320 if (self._autoDestroy) self.destroy(err);
1321};
1322
1323var destroyer$2 = function(self, end) {
1324 return function(err) {
1325 if (err) autoDestroy(self, err.message === 'premature close' ? null : err);
1326 else if (end && !self._ended) self.end();
1327 }
1328};
1329
1330var end = function(ws, fn) {
1331 if (!ws) return fn()
1332 if (ws._writableState && ws._writableState.finished) return fn()
1333 if (ws._writableState) return ws.end(fn)
1334 ws.end();
1335 fn();
1336};
1337
1338var toStreams2 = function(rs) {
1339 return new (readableStream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
1340};
1341
1342var Duplexify = function(writable, readable, opts) {
1343 if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
1344 readableStream.Duplex.call(this, opts);
1345
1346 this._writable = null;
1347 this._readable = null;
1348 this._readable2 = null;
1349
1350 this._autoDestroy = !opts || opts.autoDestroy !== false;
1351 this._forwardDestroy = !opts || opts.destroy !== false;
1352 this._forwardEnd = !opts || opts.end !== false;
1353 this._corked = 1; // start corked
1354 this._ondrain = null;
1355 this._drained = false;
1356 this._forwarding = false;
1357 this._unwrite = null;
1358 this._unread = null;
1359 this._ended = false;
1360
1361 this.destroyed = false;
1362
1363 if (writable) this.setWritable(writable);
1364 if (readable) this.setReadable(readable);
1365};
1366
1367inherits(Duplexify, readableStream.Duplex);
1368
1369Duplexify.obj = function(writable, readable, opts) {
1370 if (!opts) opts = {};
1371 opts.objectMode = true;
1372 opts.highWaterMark = 16;
1373 return new Duplexify(writable, readable, opts)
1374};
1375
1376Duplexify.prototype.cork = function() {
1377 if (++this._corked === 1) this.emit('cork');
1378};
1379
1380Duplexify.prototype.uncork = function() {
1381 if (this._corked && --this._corked === 0) this.emit('uncork');
1382};
1383
1384Duplexify.prototype.setWritable = function(writable) {
1385 if (this._unwrite) this._unwrite();
1386
1387 if (this.destroyed) {
1388 if (writable && writable.destroy) writable.destroy();
1389 return
1390 }
1391
1392 if (writable === null || writable === false) {
1393 this.end();
1394 return
1395 }
1396
1397 var self = this;
1398 var unend = endOfStream(writable, {writable:true, readable:false}, destroyer$2(this, this._forwardEnd));
1399
1400 var ondrain = function() {
1401 var ondrain = self._ondrain;
1402 self._ondrain = null;
1403 if (ondrain) ondrain();
1404 };
1405
1406 var clear = function() {
1407 self._writable.removeListener('drain', ondrain);
1408 unend();
1409 };
1410
1411 if (this._unwrite) process.nextTick(ondrain); // force a drain on stream reset to avoid livelocks
1412
1413 this._writable = writable;
1414 this._writable.on('drain', ondrain);
1415 this._unwrite = clear;
1416
1417 this.uncork(); // always uncork setWritable
1418};
1419
1420Duplexify.prototype.setReadable = function(readable) {
1421 if (this._unread) this._unread();
1422
1423 if (this.destroyed) {
1424 if (readable && readable.destroy) readable.destroy();
1425 return
1426 }
1427
1428 if (readable === null || readable === false) {
1429 this.push(null);
1430 this.resume();
1431 return
1432 }
1433
1434 var self = this;
1435 var unend = endOfStream(readable, {writable:false, readable:true}, destroyer$2(this));
1436
1437 var onreadable = function() {
1438 self._forward();
1439 };
1440
1441 var onend = function() {
1442 self.push(null);
1443 };
1444
1445 var clear = function() {
1446 self._readable2.removeListener('readable', onreadable);
1447 self._readable2.removeListener('end', onend);
1448 unend();
1449 };
1450
1451 this._drained = true;
1452 this._readable = readable;
1453 this._readable2 = readable._readableState ? readable : toStreams2(readable);
1454 this._readable2.on('readable', onreadable);
1455 this._readable2.on('end', onend);
1456 this._unread = clear;
1457
1458 this._forward();
1459};
1460
1461Duplexify.prototype._read = function() {
1462 this._drained = true;
1463 this._forward();
1464};
1465
1466Duplexify.prototype._forward = function() {
1467 if (this._forwarding || !this._readable2 || !this._drained) return
1468 this._forwarding = true;
1469
1470 var data;
1471
1472 while (this._drained && (data = streamShift(this._readable2)) !== null) {
1473 if (this.destroyed) continue
1474 this._drained = this.push(data);
1475 }
1476
1477 this._forwarding = false;
1478};
1479
1480Duplexify.prototype.destroy = function(err) {
1481 if (this.destroyed) return
1482 this.destroyed = true;
1483
1484 var self = this;
1485 process.nextTick(function() {
1486 self._destroy(err);
1487 });
1488};
1489
1490Duplexify.prototype._destroy = function(err) {
1491 if (err) {
1492 var ondrain = this._ondrain;
1493 this._ondrain = null;
1494 if (ondrain) ondrain(err);
1495 else this.emit('error', err);
1496 }
1497
1498 if (this._forwardDestroy) {
1499 if (this._readable && this._readable.destroy) this._readable.destroy();
1500 if (this._writable && this._writable.destroy) this._writable.destroy();
1501 }
1502
1503 this.emit('close');
1504};
1505
1506Duplexify.prototype._write = function(data, enc, cb) {
1507 if (this.destroyed) return cb()
1508 if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
1509 if (data === SIGNAL_FLUSH) return this._finish(cb)
1510 if (!this._writable) return cb()
1511
1512 if (this._writable.write(data) === false) this._ondrain = cb;
1513 else cb();
1514};
1515
1516Duplexify.prototype._finish = function(cb) {
1517 var self = this;
1518 this.emit('preend');
1519 onuncork(this, function() {
1520 end(self._forwardEnd && self._writable, function() {
1521 // haxx to not emit prefinish twice
1522 if (self._writableState.prefinished === false) self._writableState.prefinished = true;
1523 self.emit('prefinish');
1524 onuncork(self, cb);
1525 });
1526 });
1527};
1528
1529Duplexify.prototype.end = function(data, enc, cb) {
1530 if (typeof data === 'function') return this.end(null, null, data)
1531 if (typeof enc === 'function') return this.end(data, null, enc)
1532 this._ended = true;
1533 if (data) this.write(data);
1534 if (!this._writableState.ending) this.write(SIGNAL_FLUSH);
1535 return readableStream.Writable.prototype.end.call(this, cb)
1536};
1537
1538var duplexify = Duplexify;
1539
1540var toArray = function(args) {
1541 if (!args.length) return []
1542 return Array.isArray(args[0]) ? args[0] : Array.prototype.slice.call(args)
1543};
1544
1545var define = function(opts) {
1546 var Pumpify = function() {
1547 var streams = toArray(arguments);
1548 if (!(this instanceof Pumpify)) return new Pumpify(streams)
1549 duplexify.call(this, null, null, opts);
1550 if (streams.length) this.setPipeline(streams);
1551 };
1552
1553 inherits(Pumpify, duplexify);
1554
1555 Pumpify.prototype.setPipeline = function() {
1556 var streams = toArray(arguments);
1557 var self = this;
1558 var ended = false;
1559 var w = streams[0];
1560 var r = streams[streams.length-1];
1561
1562 r = r.readable ? r : null;
1563 w = w.writable ? w : null;
1564
1565 var onclose = function() {
1566 streams[0].emit('error', new Error('stream was destroyed'));
1567 };
1568
1569 this.on('close', onclose);
1570 this.on('prefinish', function() {
1571 if (!ended) self.cork();
1572 });
1573
1574 pump_1$1(streams, function(err) {
1575 self.removeListener('close', onclose);
1576 if (err) return self.destroy(err.message === 'premature close' ? null : err)
1577 ended = true;
1578 // pump ends after the last stream is not writable *but*
1579 // pumpify still forwards the readable part so we need to catch errors
1580 // still, so reenable autoDestroy in this case
1581 if (self._autoDestroy === false) self._autoDestroy = true;
1582 self.uncork();
1583 });
1584
1585 if (this.destroyed) return onclose()
1586 this.setWritable(w);
1587 this.setReadable(r);
1588 };
1589
1590 return Pumpify
1591};
1592
1593var pumpify = define({autoDestroy:false, destroy:false});
1594var obj = define({autoDestroy: false, destroy:false, objectMode:true, highWaterMark:16});
1595var ctor = define;
1596pumpify.obj = obj;
1597pumpify.ctor = ctor;
1598
1599var immutable = extend;
1600
1601var hasOwnProperty = Object.prototype.hasOwnProperty;
1602
1603function extend() {
1604 var target = {};
1605
1606 for (var i = 0; i < arguments.length; i++) {
1607 var source = arguments[i];
1608
1609 for (var key in source) {
1610 if (hasOwnProperty.call(source, key)) {
1611 target[key] = source[key];
1612 }
1613 }
1614 }
1615
1616 return target
1617}
1618
1619var Transform = readableStream.Transform
1620 , inherits$1 = util.inherits;
1621
1622function DestroyableTransform(opts) {
1623 Transform.call(this, opts);
1624 this._destroyed = false;
1625}
1626
1627inherits$1(DestroyableTransform, Transform);
1628
1629DestroyableTransform.prototype.destroy = function(err) {
1630 if (this._destroyed) return
1631 this._destroyed = true;
1632
1633 var self = this;
1634 process.nextTick(function() {
1635 if (err)
1636 self.emit('error', err);
1637 self.emit('close');
1638 });
1639};
1640
1641// a noop _transform function
1642function noop$3 (chunk, enc, callback) {
1643 callback(null, chunk);
1644}
1645
1646
1647// create a new export function, used by both the main export and
1648// the .ctor export, contains common logic for dealing with arguments
1649function through2 (construct) {
1650 return function (options, transform, flush) {
1651 if (typeof options == 'function') {
1652 flush = transform;
1653 transform = options;
1654 options = {};
1655 }
1656
1657 if (typeof transform != 'function')
1658 transform = noop$3;
1659
1660 if (typeof flush != 'function')
1661 flush = null;
1662
1663 return construct(options, transform, flush)
1664 }
1665}
1666
1667
1668// main export, just make me a transform stream!
1669var through2_1 = through2(function (options, transform, flush) {
1670 var t2 = new DestroyableTransform(options);
1671
1672 t2._transform = transform;
1673
1674 if (flush)
1675 t2._flush = flush;
1676
1677 return t2
1678});
1679
1680
1681// make me a reusable prototype that I can `new`, or implicitly `new`
1682// with a constructor call
1683var ctor$1 = through2(function (options, transform, flush) {
1684 function Through2 (override) {
1685 if (!(this instanceof Through2))
1686 return new Through2(override)
1687
1688 this.options = immutable(options, override);
1689
1690 DestroyableTransform.call(this, this.options);
1691 }
1692
1693 inherits$1(Through2, DestroyableTransform);
1694
1695 Through2.prototype._transform = transform;
1696
1697 if (flush)
1698 Through2.prototype._flush = flush;
1699
1700 return Through2
1701});
1702
1703
1704var obj$1 = through2(function (options, transform, flush) {
1705 var t2 = new DestroyableTransform(immutable({ objectMode: true, highWaterMark: 16 }, options));
1706
1707 t2._transform = transform;
1708
1709 if (flush)
1710 t2._flush = flush;
1711
1712 return t2
1713});
1714through2_1.ctor = ctor$1;
1715through2_1.obj = obj$1;
1716
1717var toString = Object.prototype.toString;
1718
1719var isModern = (
1720 typeof Buffer.alloc === 'function' &&
1721 typeof Buffer.allocUnsafe === 'function' &&
1722 typeof Buffer.from === 'function'
1723);
1724
1725function isArrayBuffer (input) {
1726 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
1727}
1728
1729function fromArrayBuffer (obj, byteOffset, length) {
1730 byteOffset >>>= 0;
1731
1732 var maxLength = obj.byteLength - byteOffset;
1733
1734 if (maxLength < 0) {
1735 throw new RangeError("'offset' is out of bounds")
1736 }
1737
1738 if (length === undefined) {
1739 length = maxLength;
1740 } else {
1741 length >>>= 0;
1742
1743 if (length > maxLength) {
1744 throw new RangeError("'length' is out of bounds")
1745 }
1746 }
1747
1748 return isModern
1749 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
1750 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
1751}
1752
1753function fromString (string, encoding) {
1754 if (typeof encoding !== 'string' || encoding === '') {
1755 encoding = 'utf8';
1756 }
1757
1758 if (!Buffer.isEncoding(encoding)) {
1759 throw new TypeError('"encoding" must be a valid string encoding')
1760 }
1761
1762 return isModern
1763 ? Buffer.from(string, encoding)
1764 : new Buffer(string, encoding)
1765}
1766
1767function bufferFrom (value, encodingOrOffset, length) {
1768 if (typeof value === 'number') {
1769 throw new TypeError('"value" argument must not be a number')
1770 }
1771
1772 if (isArrayBuffer(value)) {
1773 return fromArrayBuffer(value, encodingOrOffset, length)
1774 }
1775
1776 if (typeof value === 'string') {
1777 return fromString(value, encodingOrOffset)
1778 }
1779
1780 return isModern
1781 ? Buffer.from(value)
1782 : new Buffer(value)
1783}
1784
1785var bufferFrom_1 = bufferFrom;
1786
1787var typedarray = createCommonjsModule(function (module, exports) {
1788var undefined = (void 0); // Paranoia
1789
1790// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to
1791// create, and consume so much memory, that the browser appears frozen.
1792var MAX_ARRAY_LENGTH = 1e5;
1793
1794// Approximations of internal ECMAScript conversion functions
1795var ECMAScript = (function() {
1796 // Stash a copy in case other scripts modify these
1797 var opts = Object.prototype.toString,
1798 ophop = Object.prototype.hasOwnProperty;
1799
1800 return {
1801 // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues:
1802 Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); },
1803 HasProperty: function(o, p) { return p in o; },
1804 HasOwnProperty: function(o, p) { return ophop.call(o, p); },
1805 IsCallable: function(o) { return typeof o === 'function'; },
1806 ToInt32: function(v) { return v >> 0; },
1807 ToUint32: function(v) { return v >>> 0; }
1808 };
1809}());
1810
1811// Snapshot intrinsics
1812var LN2 = Math.LN2,
1813 abs = Math.abs,
1814 floor = Math.floor,
1815 log = Math.log,
1816 min = Math.min,
1817 pow = Math.pow,
1818 round = Math.round;
1819
1820// ES5: lock down object properties
1821function configureProperties(obj) {
1822 if (getOwnPropNames && defineProp) {
1823 var props = getOwnPropNames(obj), i;
1824 for (i = 0; i < props.length; i += 1) {
1825 defineProp(obj, props[i], {
1826 value: obj[props[i]],
1827 writable: false,
1828 enumerable: false,
1829 configurable: false
1830 });
1831 }
1832 }
1833}
1834
1835// emulate ES5 getter/setter API using legacy APIs
1836// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx
1837// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but
1838// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless)
1839var defineProp;
1840if (Object.defineProperty && (function() {
1841 try {
1842 Object.defineProperty({}, 'x', {});
1843 return true;
1844 } catch (e) {
1845 return false;
1846 }
1847 })()) {
1848 defineProp = Object.defineProperty;
1849} else {
1850 defineProp = function(o, p, desc) {
1851 if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object");
1852 if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); }
1853 if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); }
1854 if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; }
1855 return o;
1856 };
1857}
1858
1859var getOwnPropNames = Object.getOwnPropertyNames || function (o) {
1860 if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object");
1861 var props = [], p;
1862 for (p in o) {
1863 if (ECMAScript.HasOwnProperty(o, p)) {
1864 props.push(p);
1865 }
1866 }
1867 return props;
1868};
1869
1870// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value)
1871// for index in 0 ... obj.length
1872function makeArrayAccessors(obj) {
1873 if (!defineProp) { return; }
1874
1875 if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill");
1876
1877 function makeArrayAccessor(index) {
1878 defineProp(obj, index, {
1879 'get': function() { return obj._getter(index); },
1880 'set': function(v) { obj._setter(index, v); },
1881 enumerable: true,
1882 configurable: false
1883 });
1884 }
1885
1886 var i;
1887 for (i = 0; i < obj.length; i += 1) {
1888 makeArrayAccessor(i);
1889 }
1890}
1891
1892// Internal conversion functions:
1893// pack<Type>() - take a number (interpreted as Type), output a byte array
1894// unpack<Type>() - take a byte array, output a Type-like number
1895
1896function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; }
1897function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; }
1898
1899function packI8(n) { return [n & 0xff]; }
1900function unpackI8(bytes) { return as_signed(bytes[0], 8); }
1901
1902function packU8(n) { return [n & 0xff]; }
1903function unpackU8(bytes) { return as_unsigned(bytes[0], 8); }
1904
1905function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; }
1906
1907function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
1908function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); }
1909
1910function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
1911function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); }
1912
1913function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
1914function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
1915
1916function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
1917function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
1918
1919function packIEEE754(v, ebits, fbits) {
1920
1921 var bias = (1 << (ebits - 1)) - 1,
1922 s, e, f, i, bits, str, bytes;
1923
1924 function roundToEven(n) {
1925 var w = floor(n), f = n - w;
1926 if (f < 0.5)
1927 return w;
1928 if (f > 0.5)
1929 return w + 1;
1930 return w % 2 ? w + 1 : w;
1931 }
1932
1933 // Compute sign, exponent, fraction
1934 if (v !== v) {
1935 // NaN
1936 // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
1937 e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0;
1938 } else if (v === Infinity || v === -Infinity) {
1939 e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0;
1940 } else if (v === 0) {
1941 e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0;
1942 } else {
1943 s = v < 0;
1944 v = abs(v);
1945
1946 if (v >= pow(2, 1 - bias)) {
1947 e = min(floor(log(v) / LN2), 1023);
1948 f = roundToEven(v / pow(2, e) * pow(2, fbits));
1949 if (f / pow(2, fbits) >= 2) {
1950 e = e + 1;
1951 f = 1;
1952 }
1953 if (e > bias) {
1954 // Overflow
1955 e = (1 << ebits) - 1;
1956 f = 0;
1957 } else {
1958 // Normalized
1959 e = e + bias;
1960 f = f - pow(2, fbits);
1961 }
1962 } else {
1963 // Denormalized
1964 e = 0;
1965 f = roundToEven(v / pow(2, 1 - bias - fbits));
1966 }
1967 }
1968
1969 // Pack sign, exponent, fraction
1970 bits = [];
1971 for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); }
1972 for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); }
1973 bits.push(s ? 1 : 0);
1974 bits.reverse();
1975 str = bits.join('');
1976
1977 // Bits to bytes
1978 bytes = [];
1979 while (str.length) {
1980 bytes.push(parseInt(str.substring(0, 8), 2));
1981 str = str.substring(8);
1982 }
1983 return bytes;
1984}
1985
1986function unpackIEEE754(bytes, ebits, fbits) {
1987
1988 // Bytes to bits
1989 var bits = [], i, j, b, str,
1990 bias, s, e, f;
1991
1992 for (i = bytes.length; i; i -= 1) {
1993 b = bytes[i - 1];
1994 for (j = 8; j; j -= 1) {
1995 bits.push(b % 2 ? 1 : 0); b = b >> 1;
1996 }
1997 }
1998 bits.reverse();
1999 str = bits.join('');
2000
2001 // Unpack sign, exponent, fraction
2002 bias = (1 << (ebits - 1)) - 1;
2003 s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
2004 e = parseInt(str.substring(1, 1 + ebits), 2);
2005 f = parseInt(str.substring(1 + ebits), 2);
2006
2007 // Produce number
2008 if (e === (1 << ebits) - 1) {
2009 return f !== 0 ? NaN : s * Infinity;
2010 } else if (e > 0) {
2011 // Normalized
2012 return s * pow(2, e - bias) * (1 + f / pow(2, fbits));
2013 } else if (f !== 0) {
2014 // Denormalized
2015 return s * pow(2, -(bias - 1)) * (f / pow(2, fbits));
2016 } else {
2017 return s < 0 ? -0 : 0;
2018 }
2019}
2020
2021function unpackF64(b) { return unpackIEEE754(b, 11, 52); }
2022function packF64(v) { return packIEEE754(v, 11, 52); }
2023function unpackF32(b) { return unpackIEEE754(b, 8, 23); }
2024function packF32(v) { return packIEEE754(v, 8, 23); }
2025
2026
2027//
2028// 3 The ArrayBuffer Type
2029//
2030
2031(function() {
2032
2033 /** @constructor */
2034 var ArrayBuffer = function ArrayBuffer(length) {
2035 length = ECMAScript.ToInt32(length);
2036 if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer');
2037
2038 this.byteLength = length;
2039 this._bytes = [];
2040 this._bytes.length = length;
2041
2042 var i;
2043 for (i = 0; i < this.byteLength; i += 1) {
2044 this._bytes[i] = 0;
2045 }
2046
2047 configureProperties(this);
2048 };
2049
2050 exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer;
2051
2052 //
2053 // 4 The ArrayBufferView Type
2054 //
2055
2056 // NOTE: this constructor is not exported
2057 /** @constructor */
2058 var ArrayBufferView = function ArrayBufferView() {
2059 //this.buffer = null;
2060 //this.byteOffset = 0;
2061 //this.byteLength = 0;
2062 };
2063
2064 //
2065 // 5 The Typed Array View Types
2066 //
2067
2068 function makeConstructor(bytesPerElement, pack, unpack) {
2069 // Each TypedArray type requires a distinct constructor instance with
2070 // identical logic, which this produces.
2071
2072 var ctor;
2073 ctor = function(buffer$$1, byteOffset, length) {
2074 var array, sequence, i, s;
2075
2076 if (!arguments.length || typeof arguments[0] === 'number') {
2077 // Constructor(unsigned long length)
2078 this.length = ECMAScript.ToInt32(arguments[0]);
2079 if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer');
2080
2081 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
2082 this.buffer = new ArrayBuffer(this.byteLength);
2083 this.byteOffset = 0;
2084 } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) {
2085 // Constructor(TypedArray array)
2086 array = arguments[0];
2087
2088 this.length = array.length;
2089 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
2090 this.buffer = new ArrayBuffer(this.byteLength);
2091 this.byteOffset = 0;
2092
2093 for (i = 0; i < this.length; i += 1) {
2094 this._setter(i, array._getter(i));
2095 }
2096 } else if (typeof arguments[0] === 'object' &&
2097 !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
2098 // Constructor(sequence<type> array)
2099 sequence = arguments[0];
2100
2101 this.length = ECMAScript.ToUint32(sequence.length);
2102 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
2103 this.buffer = new ArrayBuffer(this.byteLength);
2104 this.byteOffset = 0;
2105
2106 for (i = 0; i < this.length; i += 1) {
2107 s = sequence[i];
2108 this._setter(i, Number(s));
2109 }
2110 } else if (typeof arguments[0] === 'object' &&
2111 (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
2112 // Constructor(ArrayBuffer buffer,
2113 // optional unsigned long byteOffset, optional unsigned long length)
2114 this.buffer = buffer$$1;
2115
2116 this.byteOffset = ECMAScript.ToUint32(byteOffset);
2117 if (this.byteOffset > this.buffer.byteLength) {
2118 throw new RangeError("byteOffset out of range");
2119 }
2120
2121 if (this.byteOffset % this.BYTES_PER_ELEMENT) {
2122 // The given byteOffset must be a multiple of the element
2123 // size of the specific type, otherwise an exception is raised.
2124 throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size.");
2125 }
2126
2127 if (arguments.length < 3) {
2128 this.byteLength = this.buffer.byteLength - this.byteOffset;
2129
2130 if (this.byteLength % this.BYTES_PER_ELEMENT) {
2131 throw new RangeError("length of buffer minus byteOffset not a multiple of the element size");
2132 }
2133 this.length = this.byteLength / this.BYTES_PER_ELEMENT;
2134 } else {
2135 this.length = ECMAScript.ToUint32(length);
2136 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
2137 }
2138
2139 if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
2140 throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
2141 }
2142 } else {
2143 throw new TypeError("Unexpected argument type(s)");
2144 }
2145
2146 this.constructor = ctor;
2147
2148 configureProperties(this);
2149 makeArrayAccessors(this);
2150 };
2151
2152 ctor.prototype = new ArrayBufferView();
2153 ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement;
2154 ctor.prototype._pack = pack;
2155 ctor.prototype._unpack = unpack;
2156 ctor.BYTES_PER_ELEMENT = bytesPerElement;
2157
2158 // getter type (unsigned long index);
2159 ctor.prototype._getter = function(index) {
2160 if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
2161
2162 index = ECMAScript.ToUint32(index);
2163 if (index >= this.length) {
2164 return undefined;
2165 }
2166
2167 var bytes = [], i, o;
2168 for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
2169 i < this.BYTES_PER_ELEMENT;
2170 i += 1, o += 1) {
2171 bytes.push(this.buffer._bytes[o]);
2172 }
2173 return this._unpack(bytes);
2174 };
2175
2176 // NONSTANDARD: convenience alias for getter: type get(unsigned long index);
2177 ctor.prototype.get = ctor.prototype._getter;
2178
2179 // setter void (unsigned long index, type value);
2180 ctor.prototype._setter = function(index, value) {
2181 if (arguments.length < 2) throw new SyntaxError("Not enough arguments");
2182
2183 index = ECMAScript.ToUint32(index);
2184 if (index >= this.length) {
2185 return undefined;
2186 }
2187
2188 var bytes = this._pack(value), i, o;
2189 for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
2190 i < this.BYTES_PER_ELEMENT;
2191 i += 1, o += 1) {
2192 this.buffer._bytes[o] = bytes[i];
2193 }
2194 };
2195
2196 // void set(TypedArray array, optional unsigned long offset);
2197 // void set(sequence<type> array, optional unsigned long offset);
2198 ctor.prototype.set = function(index, value) {
2199 if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
2200 var array, sequence, offset, len,
2201 i, s, d,
2202 byteOffset, byteLength, tmp;
2203
2204 if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) {
2205 // void set(TypedArray array, optional unsigned long offset);
2206 array = arguments[0];
2207 offset = ECMAScript.ToUint32(arguments[1]);
2208
2209 if (offset + array.length > this.length) {
2210 throw new RangeError("Offset plus length of array is out of range");
2211 }
2212
2213 byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT;
2214 byteLength = array.length * this.BYTES_PER_ELEMENT;
2215
2216 if (array.buffer === this.buffer) {
2217 tmp = [];
2218 for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) {
2219 tmp[i] = array.buffer._bytes[s];
2220 }
2221 for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) {
2222 this.buffer._bytes[d] = tmp[i];
2223 }
2224 } else {
2225 for (i = 0, s = array.byteOffset, d = byteOffset;
2226 i < byteLength; i += 1, s += 1, d += 1) {
2227 this.buffer._bytes[d] = array.buffer._bytes[s];
2228 }
2229 }
2230 } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') {
2231 // void set(sequence<type> array, optional unsigned long offset);
2232 sequence = arguments[0];
2233 len = ECMAScript.ToUint32(sequence.length);
2234 offset = ECMAScript.ToUint32(arguments[1]);
2235
2236 if (offset + len > this.length) {
2237 throw new RangeError("Offset plus length of array is out of range");
2238 }
2239
2240 for (i = 0; i < len; i += 1) {
2241 s = sequence[i];
2242 this._setter(offset + i, Number(s));
2243 }
2244 } else {
2245 throw new TypeError("Unexpected argument type(s)");
2246 }
2247 };
2248
2249 // TypedArray subarray(long begin, optional long end);
2250 ctor.prototype.subarray = function(start, end) {
2251 function clamp(v, min, max) { return v < min ? min : v > max ? max : v; }
2252
2253 start = ECMAScript.ToInt32(start);
2254 end = ECMAScript.ToInt32(end);
2255
2256 if (arguments.length < 1) { start = 0; }
2257 if (arguments.length < 2) { end = this.length; }
2258
2259 if (start < 0) { start = this.length + start; }
2260 if (end < 0) { end = this.length + end; }
2261
2262 start = clamp(start, 0, this.length);
2263 end = clamp(end, 0, this.length);
2264
2265 var len = end - start;
2266 if (len < 0) {
2267 len = 0;
2268 }
2269
2270 return new this.constructor(
2271 this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len);
2272 };
2273
2274 return ctor;
2275 }
2276
2277 var Int8Array = makeConstructor(1, packI8, unpackI8);
2278 var Uint8Array = makeConstructor(1, packU8, unpackU8);
2279 var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8);
2280 var Int16Array = makeConstructor(2, packI16, unpackI16);
2281 var Uint16Array = makeConstructor(2, packU16, unpackU16);
2282 var Int32Array = makeConstructor(4, packI32, unpackI32);
2283 var Uint32Array = makeConstructor(4, packU32, unpackU32);
2284 var Float32Array = makeConstructor(4, packF32, unpackF32);
2285 var Float64Array = makeConstructor(8, packF64, unpackF64);
2286
2287 exports.Int8Array = exports.Int8Array || Int8Array;
2288 exports.Uint8Array = exports.Uint8Array || Uint8Array;
2289 exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray;
2290 exports.Int16Array = exports.Int16Array || Int16Array;
2291 exports.Uint16Array = exports.Uint16Array || Uint16Array;
2292 exports.Int32Array = exports.Int32Array || Int32Array;
2293 exports.Uint32Array = exports.Uint32Array || Uint32Array;
2294 exports.Float32Array = exports.Float32Array || Float32Array;
2295 exports.Float64Array = exports.Float64Array || Float64Array;
2296}());
2297
2298//
2299// 6 The DataView View Type
2300//
2301
2302(function() {
2303 function r(array, index) {
2304 return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index];
2305 }
2306
2307 var IS_BIG_ENDIAN = (function() {
2308 var u16array = new(exports.Uint16Array)([0x1234]),
2309 u8array = new(exports.Uint8Array)(u16array.buffer);
2310 return r(u8array, 0) === 0x12;
2311 }());
2312
2313 // Constructor(ArrayBuffer buffer,
2314 // optional unsigned long byteOffset,
2315 // optional unsigned long byteLength)
2316 /** @constructor */
2317 var DataView = function DataView(buffer$$1, byteOffset, byteLength) {
2318 if (arguments.length === 0) {
2319 buffer$$1 = new exports.ArrayBuffer(0);
2320 } else if (!(buffer$$1 instanceof exports.ArrayBuffer || ECMAScript.Class(buffer$$1) === 'ArrayBuffer')) {
2321 throw new TypeError("TypeError");
2322 }
2323
2324 this.buffer = buffer$$1 || new exports.ArrayBuffer(0);
2325
2326 this.byteOffset = ECMAScript.ToUint32(byteOffset);
2327 if (this.byteOffset > this.buffer.byteLength) {
2328 throw new RangeError("byteOffset out of range");
2329 }
2330
2331 if (arguments.length < 3) {
2332 this.byteLength = this.buffer.byteLength - this.byteOffset;
2333 } else {
2334 this.byteLength = ECMAScript.ToUint32(byteLength);
2335 }
2336
2337 if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
2338 throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
2339 }
2340
2341 configureProperties(this);
2342 };
2343
2344 function makeGetter(arrayType) {
2345 return function(byteOffset, littleEndian) {
2346
2347 byteOffset = ECMAScript.ToUint32(byteOffset);
2348
2349 if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
2350 throw new RangeError("Array index out of range");
2351 }
2352 byteOffset += this.byteOffset;
2353
2354 var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT),
2355 bytes = [], i;
2356 for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
2357 bytes.push(r(uint8Array, i));
2358 }
2359
2360 if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
2361 bytes.reverse();
2362 }
2363
2364 return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0);
2365 };
2366 }
2367
2368 DataView.prototype.getUint8 = makeGetter(exports.Uint8Array);
2369 DataView.prototype.getInt8 = makeGetter(exports.Int8Array);
2370 DataView.prototype.getUint16 = makeGetter(exports.Uint16Array);
2371 DataView.prototype.getInt16 = makeGetter(exports.Int16Array);
2372 DataView.prototype.getUint32 = makeGetter(exports.Uint32Array);
2373 DataView.prototype.getInt32 = makeGetter(exports.Int32Array);
2374 DataView.prototype.getFloat32 = makeGetter(exports.Float32Array);
2375 DataView.prototype.getFloat64 = makeGetter(exports.Float64Array);
2376
2377 function makeSetter(arrayType) {
2378 return function(byteOffset, value, littleEndian) {
2379
2380 byteOffset = ECMAScript.ToUint32(byteOffset);
2381 if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
2382 throw new RangeError("Array index out of range");
2383 }
2384
2385 // Get bytes
2386 var typeArray = new arrayType([value]),
2387 byteArray = new exports.Uint8Array(typeArray.buffer),
2388 bytes = [], i, byteView;
2389
2390 for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
2391 bytes.push(r(byteArray, i));
2392 }
2393
2394 // Flip if necessary
2395 if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
2396 bytes.reverse();
2397 }
2398
2399 // Write them
2400 byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT);
2401 byteView.set(bytes);
2402 };
2403 }
2404
2405 DataView.prototype.setUint8 = makeSetter(exports.Uint8Array);
2406 DataView.prototype.setInt8 = makeSetter(exports.Int8Array);
2407 DataView.prototype.setUint16 = makeSetter(exports.Uint16Array);
2408 DataView.prototype.setInt16 = makeSetter(exports.Int16Array);
2409 DataView.prototype.setUint32 = makeSetter(exports.Uint32Array);
2410 DataView.prototype.setInt32 = makeSetter(exports.Int32Array);
2411 DataView.prototype.setFloat32 = makeSetter(exports.Float32Array);
2412 DataView.prototype.setFloat64 = makeSetter(exports.Float64Array);
2413
2414 exports.DataView = exports.DataView || DataView;
2415
2416}());
2417});
2418var typedarray_1 = typedarray.ArrayBuffer;
2419var typedarray_2 = typedarray.Int8Array;
2420var typedarray_3 = typedarray.Uint8Array;
2421var typedarray_4 = typedarray.Uint8ClampedArray;
2422var typedarray_5 = typedarray.Int16Array;
2423var typedarray_6 = typedarray.Uint16Array;
2424var typedarray_7 = typedarray.Int32Array;
2425var typedarray_8 = typedarray.Uint32Array;
2426var typedarray_9 = typedarray.Float32Array;
2427var typedarray_10 = typedarray.Float64Array;
2428var typedarray_11 = typedarray.DataView;
2429
2430var Writable = readableStream.Writable;
2431
2432
2433
2434if (typeof Uint8Array === 'undefined') {
2435 var U8 = typedarray.Uint8Array;
2436} else {
2437 var U8 = Uint8Array;
2438}
2439
2440function ConcatStream(opts, cb) {
2441 if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb)
2442
2443 if (typeof opts === 'function') {
2444 cb = opts;
2445 opts = {};
2446 }
2447 if (!opts) opts = {};
2448
2449 var encoding = opts.encoding;
2450 var shouldInferEncoding = false;
2451
2452 if (!encoding) {
2453 shouldInferEncoding = true;
2454 } else {
2455 encoding = String(encoding).toLowerCase();
2456 if (encoding === 'u8' || encoding === 'uint8') {
2457 encoding = 'uint8array';
2458 }
2459 }
2460
2461 Writable.call(this, { objectMode: true });
2462
2463 this.encoding = encoding;
2464 this.shouldInferEncoding = shouldInferEncoding;
2465
2466 if (cb) this.on('finish', function () { cb(this.getBody()); });
2467 this.body = [];
2468}
2469
2470var concatStream = ConcatStream;
2471inherits(ConcatStream, Writable);
2472
2473ConcatStream.prototype._write = function(chunk, enc, next) {
2474 this.body.push(chunk);
2475 next();
2476};
2477
2478ConcatStream.prototype.inferEncoding = function (buff) {
2479 var firstBuffer = buff === undefined ? this.body[0] : buff;
2480 if (Buffer.isBuffer(firstBuffer)) return 'buffer'
2481 if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array'
2482 if (Array.isArray(firstBuffer)) return 'array'
2483 if (typeof firstBuffer === 'string') return 'string'
2484 if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object'
2485 return 'buffer'
2486};
2487
2488ConcatStream.prototype.getBody = function () {
2489 if (!this.encoding && this.body.length === 0) return []
2490 if (this.shouldInferEncoding) this.encoding = this.inferEncoding();
2491 if (this.encoding === 'array') return arrayConcat(this.body)
2492 if (this.encoding === 'string') return stringConcat(this.body)
2493 if (this.encoding === 'buffer') return bufferConcat(this.body)
2494 if (this.encoding === 'uint8array') return u8Concat(this.body)
2495 return this.body
2496};
2497
2498function isArrayish (arr) {
2499 return /Array\]$/.test(Object.prototype.toString.call(arr))
2500}
2501
2502function isBufferish (p) {
2503 return typeof p === 'string' || isArrayish(p) || (p && typeof p.subarray === 'function')
2504}
2505
2506function stringConcat (parts) {
2507 var strings = [];
2508 for (var i = 0; i < parts.length; i++) {
2509 var p = parts[i];
2510 if (typeof p === 'string') {
2511 strings.push(p);
2512 } else if (Buffer.isBuffer(p)) {
2513 strings.push(p);
2514 } else if (isBufferish(p)) {
2515 strings.push(bufferFrom_1(p));
2516 } else {
2517 strings.push(bufferFrom_1(String(p)));
2518 }
2519 }
2520 if (Buffer.isBuffer(parts[0])) {
2521 strings = Buffer.concat(strings);
2522 strings = strings.toString('utf8');
2523 } else {
2524 strings = strings.join('');
2525 }
2526 return strings
2527}
2528
2529function bufferConcat (parts) {
2530 var bufs = [];
2531 for (var i = 0; i < parts.length; i++) {
2532 var p = parts[i];
2533 if (Buffer.isBuffer(p)) {
2534 bufs.push(p);
2535 } else if (isBufferish(p)) {
2536 bufs.push(bufferFrom_1(p));
2537 } else {
2538 bufs.push(bufferFrom_1(String(p)));
2539 }
2540 }
2541 return Buffer.concat(bufs)
2542}
2543
2544function arrayConcat (parts) {
2545 var res = [];
2546 for (var i = 0; i < parts.length; i++) {
2547 res.push.apply(res, parts[i]);
2548 }
2549 return res
2550}
2551
2552function u8Concat (parts) {
2553 var len = 0;
2554 for (var i = 0; i < parts.length; i++) {
2555 if (typeof parts[i] === 'string') {
2556 parts[i] = bufferFrom_1(parts[i]);
2557 }
2558 len += parts[i].length;
2559 }
2560 var u8 = new U8(len);
2561 for (var i = 0, offset = 0; i < parts.length; i++) {
2562 var part = parts[i];
2563 for (var j = 0; j < part.length; j++) {
2564 u8[offset++] = part[j];
2565 }
2566 }
2567 return u8
2568}
2569
2570var Readable = readableStream.Readable;
2571
2572
2573var from2_1 = from2;
2574
2575from2.ctor = ctor$2;
2576from2.obj = obj$2;
2577
2578var Proto = ctor$2();
2579
2580function toFunction(list) {
2581 list = list.slice();
2582 return function (_, cb) {
2583 var err = null;
2584 var item = list.length ? list.shift() : null;
2585 if (item instanceof Error) {
2586 err = item;
2587 item = null;
2588 }
2589
2590 cb(err, item);
2591 }
2592}
2593
2594function from2(opts, read) {
2595 if (typeof opts !== 'object' || Array.isArray(opts)) {
2596 read = opts;
2597 opts = {};
2598 }
2599
2600 var rs = new Proto(opts);
2601 rs._from = Array.isArray(read) ? toFunction(read) : (read || noop$4);
2602 return rs
2603}
2604
2605function ctor$2(opts, read) {
2606 if (typeof opts === 'function') {
2607 read = opts;
2608 opts = {};
2609 }
2610
2611 opts = defaults(opts);
2612
2613 inherits(Class, Readable);
2614 function Class(override) {
2615 if (!(this instanceof Class)) return new Class(override)
2616 this._reading = false;
2617 this._callback = check;
2618 this.destroyed = false;
2619 Readable.call(this, override || opts);
2620
2621 var self = this;
2622 var hwm = this._readableState.highWaterMark;
2623
2624 function check(err, data) {
2625 if (self.destroyed) return
2626 if (err) return self.destroy(err)
2627 if (data === null) return self.push(null)
2628 self._reading = false;
2629 if (self.push(data)) self._read(hwm);
2630 }
2631 }
2632
2633 Class.prototype._from = read || noop$4;
2634 Class.prototype._read = function(size) {
2635 if (this._reading || this.destroyed) return
2636 this._reading = true;
2637 this._from(size, this._callback);
2638 };
2639
2640 Class.prototype.destroy = function(err) {
2641 if (this.destroyed) return
2642 this.destroyed = true;
2643
2644 var self = this;
2645 process.nextTick(function() {
2646 if (err) self.emit('error', err);
2647 self.emit('close');
2648 });
2649 };
2650
2651 return Class
2652}
2653
2654function obj$2(opts, read) {
2655 if (typeof opts === 'function' || Array.isArray(opts)) {
2656 read = opts;
2657 opts = {};
2658 }
2659
2660 opts = defaults(opts);
2661 opts.objectMode = true;
2662 opts.highWaterMark = 16;
2663
2664 return from2(opts, read)
2665}
2666
2667function noop$4 () {}
2668
2669function defaults(opts) {
2670 opts = opts || {};
2671 return opts
2672}
2673
2674var SIGNAL_FLUSH$1 =(Buffer.from && Buffer.from !== Uint8Array.from)
2675 ? Buffer.from([0])
2676 : new Buffer([0]);
2677
2678var flushWriteStream = WriteStream;
2679
2680function WriteStream (opts, write, flush) {
2681 if (!(this instanceof WriteStream)) return new WriteStream(opts, write, flush)
2682
2683 if (typeof opts === 'function') {
2684 flush = write;
2685 write = opts;
2686 opts = {};
2687 }
2688
2689 readableStream.Writable.call(this, opts);
2690
2691 this.destroyed = false;
2692 this._worker = write || null;
2693 this._flush = flush || null;
2694}
2695
2696inherits(WriteStream, readableStream.Writable);
2697
2698WriteStream.obj = function (opts, worker, flush) {
2699 if (typeof opts === 'function') return WriteStream.obj(null, opts, worker)
2700 if (!opts) opts = {};
2701 opts.objectMode = true;
2702 return new WriteStream(opts, worker, flush)
2703};
2704
2705WriteStream.prototype._write = function (data, enc, cb) {
2706 if (SIGNAL_FLUSH$1 === data) this._flush(cb);
2707 else this._worker(data, enc, cb);
2708};
2709
2710WriteStream.prototype.end = function (data, enc, cb) {
2711 if (!this._flush) return readableStream.Writable.prototype.end.apply(this, arguments)
2712 if (typeof data === 'function') return this.end(null, null, data)
2713 if (typeof enc === 'function') return this.end(data, null, enc)
2714 if (data) this.write(data);
2715 if (!this._writableState.ending) this.write(SIGNAL_FLUSH$1);
2716 return readableStream.Writable.prototype.end.call(this, cb)
2717};
2718
2719WriteStream.prototype.destroy = function (err) {
2720 if (this.destroyed) return
2721 this.destroyed = true;
2722 if (err) this.emit('error', err);
2723 this.emit('close');
2724};
2725
2726var ensureTwoPower = function(n) {
2727 if (n && !(n & (n - 1))) return n;
2728 var p = 1;
2729 while (p < n) p <<= 1;
2730 return p;
2731};
2732
2733var Cyclist = function(size) {
2734 if (!(this instanceof Cyclist)) return new Cyclist(size);
2735 size = ensureTwoPower(size);
2736 this.mask = size-1;
2737 this.size = size;
2738 this.values = new Array(size);
2739};
2740
2741Cyclist.prototype.put = function(index, val) {
2742 var pos = index & this.mask;
2743 this.values[pos] = val;
2744 return pos;
2745};
2746
2747Cyclist.prototype.get = function(index) {
2748 return this.values[index & this.mask];
2749};
2750
2751Cyclist.prototype.del = function(index) {
2752 var pos = index & this.mask;
2753 var val = this.values[pos];
2754 this.values[pos] = undefined;
2755 return val;
2756};
2757
2758var cyclist = Cyclist;
2759
2760var Transform$1 = readableStream.Transform;
2761
2762
2763
2764
2765var ParallelTransform = function(maxParallel, opts, ontransform) {
2766 if (!(this instanceof ParallelTransform)) return new ParallelTransform(maxParallel, opts, ontransform);
2767
2768 if (typeof maxParallel === 'function') {
2769 ontransform = maxParallel;
2770 opts = null;
2771 maxParallel = 1;
2772 }
2773 if (typeof opts === 'function') {
2774 ontransform = opts;
2775 opts = null;
2776 }
2777
2778 if (!opts) opts = {};
2779 if (!opts.highWaterMark) opts.highWaterMark = Math.max(maxParallel, 16);
2780 if (opts.objectMode !== false) opts.objectMode = true;
2781
2782 Transform$1.call(this, opts);
2783
2784 this._maxParallel = maxParallel;
2785 this._ontransform = ontransform;
2786 this._destroyed = false;
2787 this._flushed = false;
2788 this._ordered = opts.ordered !== false;
2789 this._buffer = this._ordered ? cyclist(maxParallel) : [];
2790 this._top = 0;
2791 this._bottom = 0;
2792 this._ondrain = null;
2793};
2794
2795inherits(ParallelTransform, Transform$1);
2796
2797ParallelTransform.prototype.destroy = function() {
2798 if (this._destroyed) return;
2799 this._destroyed = true;
2800 this.emit('close');
2801};
2802
2803ParallelTransform.prototype._transform = function(chunk, enc, callback) {
2804 var self = this;
2805 var pos = this._top++;
2806
2807 this._ontransform(chunk, function(err, data) {
2808 if (self._destroyed) return;
2809 if (err) {
2810 self.emit('error', err);
2811 self.push(null);
2812 self.destroy();
2813 return;
2814 }
2815 if (self._ordered) {
2816 self._buffer.put(pos, (data === undefined || data === null) ? null : data);
2817 }
2818 else {
2819 self._buffer.push(data);
2820 }
2821 self._drain();
2822 });
2823
2824 if (this._top - this._bottom < this._maxParallel) return callback();
2825 this._ondrain = callback;
2826};
2827
2828ParallelTransform.prototype._flush = function(callback) {
2829 this._flushed = true;
2830 this._ondrain = callback;
2831 this._drain();
2832};
2833
2834ParallelTransform.prototype._drain = function() {
2835 if (this._ordered) {
2836 while (this._buffer.get(this._bottom) !== undefined) {
2837 var data = this._buffer.del(this._bottom++);
2838 if (data === null) continue;
2839 this.push(data);
2840 }
2841 }
2842 else {
2843 while (this._buffer.length > 0) {
2844 var data = this._buffer.pop();
2845 this._bottom++;
2846 if (data === null) continue;
2847 this.push(data);
2848 }
2849 }
2850
2851
2852 if (!this._drained() || !this._ondrain) return;
2853
2854 var ondrain = this._ondrain;
2855 this._ondrain = null;
2856 ondrain();
2857};
2858
2859ParallelTransform.prototype._drained = function() {
2860 var diff = this._top - this._bottom;
2861 return this._flushed ? !diff : diff < this._maxParallel;
2862};
2863
2864var parallelTransform = ParallelTransform;
2865
2866var pipe$2 = pump_1;
2867var each$1 = streamEach;
2868var pipeline = pumpify;
2869var duplex = duplexify;
2870var through = through2_1;
2871var concat = concatStream;
2872var finished = endOfStream;
2873var from_1 = from2_1;
2874var to = flushWriteStream;
2875var parallel = parallelTransform;
2876
2877var mississippi = {
2878 pipe: pipe$2,
2879 each: each$1,
2880 pipeline: pipeline,
2881 duplex: duplex,
2882 through: through,
2883 concat: concat,
2884 finished: finished,
2885 from: from_1,
2886 to: to,
2887 parallel: parallel
2888};
2889
2890var githubParseLink = function (link) {
2891 if (typeof link !== 'string') {
2892 return {};
2893 }
2894
2895 return link.split(', ').reduce(function (result, part) {
2896 var match = part.match('<(.*?)>; rel="(.*?)"');
2897
2898 if (match && match.length === 3) {
2899 result[match[2]] = match[1];
2900 }
2901
2902 return result;
2903 }, {});
2904};
2905
2906const wrap = fn => new Promise(resolve => {
2907 resolve(fn());
2908});
2909
2910var pDoWhilst = (action, condition) => wrap(function loop() {
2911 return wrap(action).then(result => {
2912 if (condition(result)) {
2913 return loop();
2914 }
2915 });
2916});
2917
2918var name = "get-deno";
2919var version = "1.1.1";
2920var description = "deno installation script for npx";
2921var bin = "cli.compact.js";
2922var files = [
2923 "cli.compact.js"
2924];
2925var scripts = {
2926 lint: "eslint .",
2927 test: "tape test.js | tap-spec",
2928 build: "rollup -c rollup.config.js",
2929 prepublishOnly: "npm run build",
2930 release: "np"
2931};
2932var config = {
2933 repo: "denoland/deno",
2934 artifacts: {
2935 win32: "deno_win_x64.zip",
2936 darwin: "deno_osx_x64.gz",
2937 linux: "deno_linux_x64.gz"
2938 },
2939 umask: 755
2940};
2941var keywords = [
2942 "deno",
2943 "download",
2944 "install",
2945 "installer"
2946];
2947var repository = {
2948 type: "git",
2949 url: "git://github.com/vladimyr/get-deno.git"
2950};
2951var author = {
2952 email: "d.vladimyr+dev@gmail.com",
2953 name: "Dario Vladovic",
2954 url: "https://github.com/vladimyr"
2955};
2956var license = "MIT";
2957var bugs = {
2958 url: "https://github.com/vladimyr/get-deno/issues"
2959};
2960var homepage = "https://github.com/vladimyr/get-deno";
2961var dependencies = {
2962};
2963var devDependencies = {
2964 debug: "^4.1.1",
2965 eslint: "^5.12.0",
2966 "eslint-config-semistandard": "^13.0.0",
2967 "eslint-config-standard": "^12.0.0",
2968 "eslint-plugin-import": "^2.14.0",
2969 "eslint-plugin-node": "^8.0.1",
2970 "eslint-plugin-promise": "^4.0.1",
2971 "eslint-plugin-standard": "^4.0.0",
2972 "exit-hook": "^2.0.0",
2973 gauge: "^2.7.4",
2974 "gh-got": "^8.1.0",
2975 "github-parse-link": "^1.1.1",
2976 kleur: "^3.0.1",
2977 "make-dir": "^1.3.0",
2978 minimist: "^1.2.0",
2979 "minimist-options": "^3.0.2",
2980 mississippi: "^3.0.0",
2981 ms: "^2.1.1",
2982 ora: "^3.0.0",
2983 "p-do-whilst": "^0.1.0",
2984 "pretty-bytes": "^5.1.0",
2985 rollup: "^1.0.1",
2986 "rollup-plugin-commonjs": "^9.2.0",
2987 "rollup-plugin-json": "^3.1.0",
2988 "rollup-plugin-node-resolve": "^4.0.0",
2989 "rollup-plugin-postprocess": "^1.0.2",
2990 "rollup-plugin-re": "^1.0.7",
2991 "rollup-plugin-visualizer": "^0.9.2",
2992 semver: "^5.6.0",
2993 "tap-spec": "^5.0.0",
2994 tape: "^4.9.2",
2995 yauzl: "^2.10.0"
2996};
2997var _package = {
2998 name: name,
2999 version: version,
3000 description: description,
3001 bin: bin,
3002 files: files,
3003 scripts: scripts,
3004 config: config,
3005 keywords: keywords,
3006 repository: repository,
3007 author: author,
3008 license: license,
3009 bugs: bugs,
3010 homepage: homepage,
3011 dependencies: dependencies,
3012 devDependencies: devDependencies
3013};
3014
3015var _package$1 = /*#__PURE__*/Object.freeze({
3016 name: name,
3017 version: version,
3018 description: description,
3019 bin: bin,
3020 files: files,
3021 scripts: scripts,
3022 config: config,
3023 keywords: keywords,
3024 repository: repository,
3025 author: author,
3026 license: license,
3027 bugs: bugs,
3028 homepage: homepage,
3029 dependencies: dependencies,
3030 devDependencies: devDependencies,
3031 default: _package
3032});
3033
3034var pend = Pend;
3035
3036function Pend() {
3037 this.pending = 0;
3038 this.max = Infinity;
3039 this.listeners = [];
3040 this.waiting = [];
3041 this.error = null;
3042}
3043
3044Pend.prototype.go = function(fn) {
3045 if (this.pending < this.max) {
3046 pendGo(this, fn);
3047 } else {
3048 this.waiting.push(fn);
3049 }
3050};
3051
3052Pend.prototype.wait = function(cb) {
3053 if (this.pending === 0) {
3054 cb(this.error);
3055 } else {
3056 this.listeners.push(cb);
3057 }
3058};
3059
3060Pend.prototype.hold = function() {
3061 return pendHold(this);
3062};
3063
3064function pendHold(self) {
3065 self.pending += 1;
3066 var called = false;
3067 return onCb;
3068 function onCb(err) {
3069 if (called) throw new Error("callback called twice");
3070 called = true;
3071 self.error = self.error || err;
3072 self.pending -= 1;
3073 if (self.waiting.length > 0 && self.pending < self.max) {
3074 pendGo(self, self.waiting.shift());
3075 } else if (self.pending === 0) {
3076 var listeners = self.listeners;
3077 self.listeners = [];
3078 listeners.forEach(cbListener);
3079 }
3080 }
3081 function cbListener(listener) {
3082 listener(self.error);
3083 }
3084}
3085
3086function pendGo(self, fn) {
3087 fn(pendHold(self));
3088}
3089
3090var Readable$1 = stream.Readable;
3091var Writable$1 = stream.Writable;
3092var PassThrough = stream.PassThrough;
3093
3094var EventEmitter = events.EventEmitter;
3095
3096var createFromBuffer_1 = createFromBuffer;
3097var createFromFd_1 = createFromFd;
3098var BufferSlicer_1 = BufferSlicer;
3099var FdSlicer_1 = FdSlicer;
3100
3101util.inherits(FdSlicer, EventEmitter);
3102function FdSlicer(fd, options) {
3103 options = options || {};
3104 EventEmitter.call(this);
3105
3106 this.fd = fd;
3107 this.pend = new pend();
3108 this.pend.max = 1;
3109 this.refCount = 0;
3110 this.autoClose = !!options.autoClose;
3111}
3112
3113FdSlicer.prototype.read = function(buffer$$1, offset, length, position, callback) {
3114 var self = this;
3115 self.pend.go(function(cb) {
3116 fs.read(self.fd, buffer$$1, offset, length, position, function(err, bytesRead, buffer$$1) {
3117 cb();
3118 callback(err, bytesRead, buffer$$1);
3119 });
3120 });
3121};
3122
3123FdSlicer.prototype.write = function(buffer$$1, offset, length, position, callback) {
3124 var self = this;
3125 self.pend.go(function(cb) {
3126 fs.write(self.fd, buffer$$1, offset, length, position, function(err, written, buffer$$1) {
3127 cb();
3128 callback(err, written, buffer$$1);
3129 });
3130 });
3131};
3132
3133FdSlicer.prototype.createReadStream = function(options) {
3134 return new ReadStream(this, options);
3135};
3136
3137FdSlicer.prototype.createWriteStream = function(options) {
3138 return new WriteStream$1(this, options);
3139};
3140
3141FdSlicer.prototype.ref = function() {
3142 this.refCount += 1;
3143};
3144
3145FdSlicer.prototype.unref = function() {
3146 var self = this;
3147 self.refCount -= 1;
3148
3149 if (self.refCount > 0) return;
3150 if (self.refCount < 0) throw new Error("invalid unref");
3151
3152 if (self.autoClose) {
3153 fs.close(self.fd, onCloseDone);
3154 }
3155
3156 function onCloseDone(err) {
3157 if (err) {
3158 self.emit('error', err);
3159 } else {
3160 self.emit('close');
3161 }
3162 }
3163};
3164
3165util.inherits(ReadStream, Readable$1);
3166function ReadStream(context, options) {
3167 options = options || {};
3168 Readable$1.call(this, options);
3169
3170 this.context = context;
3171 this.context.ref();
3172
3173 this.start = options.start || 0;
3174 this.endOffset = options.end;
3175 this.pos = this.start;
3176 this.destroyed = false;
3177}
3178
3179ReadStream.prototype._read = function(n) {
3180 var self = this;
3181 if (self.destroyed) return;
3182
3183 var toRead = Math.min(self._readableState.highWaterMark, n);
3184 if (self.endOffset != null) {
3185 toRead = Math.min(toRead, self.endOffset - self.pos);
3186 }
3187 if (toRead <= 0) {
3188 self.destroyed = true;
3189 self.push(null);
3190 self.context.unref();
3191 return;
3192 }
3193 self.context.pend.go(function(cb) {
3194 if (self.destroyed) return cb();
3195 var buffer$$1 = new Buffer(toRead);
3196 fs.read(self.context.fd, buffer$$1, 0, toRead, self.pos, function(err, bytesRead) {
3197 if (err) {
3198 self.destroy(err);
3199 } else if (bytesRead === 0) {
3200 self.destroyed = true;
3201 self.push(null);
3202 self.context.unref();
3203 } else {
3204 self.pos += bytesRead;
3205 self.push(buffer$$1.slice(0, bytesRead));
3206 }
3207 cb();
3208 });
3209 });
3210};
3211
3212ReadStream.prototype.destroy = function(err) {
3213 if (this.destroyed) return;
3214 err = err || new Error("stream destroyed");
3215 this.destroyed = true;
3216 this.emit('error', err);
3217 this.context.unref();
3218};
3219
3220util.inherits(WriteStream$1, Writable$1);
3221function WriteStream$1(context, options) {
3222 options = options || {};
3223 Writable$1.call(this, options);
3224
3225 this.context = context;
3226 this.context.ref();
3227
3228 this.start = options.start || 0;
3229 this.endOffset = (options.end == null) ? Infinity : +options.end;
3230 this.bytesWritten = 0;
3231 this.pos = this.start;
3232 this.destroyed = false;
3233
3234 this.on('finish', this.destroy.bind(this));
3235}
3236
3237WriteStream$1.prototype._write = function(buffer$$1, encoding, callback) {
3238 var self = this;
3239 if (self.destroyed) return;
3240
3241 if (self.pos + buffer$$1.length > self.endOffset) {
3242 var err = new Error("maximum file length exceeded");
3243 err.code = 'ETOOBIG';
3244 self.destroy();
3245 callback(err);
3246 return;
3247 }
3248 self.context.pend.go(function(cb) {
3249 if (self.destroyed) return cb();
3250 fs.write(self.context.fd, buffer$$1, 0, buffer$$1.length, self.pos, function(err, bytes) {
3251 if (err) {
3252 self.destroy();
3253 cb();
3254 callback(err);
3255 } else {
3256 self.bytesWritten += bytes;
3257 self.pos += bytes;
3258 self.emit('progress');
3259 cb();
3260 callback();
3261 }
3262 });
3263 });
3264};
3265
3266WriteStream$1.prototype.destroy = function() {
3267 if (this.destroyed) return;
3268 this.destroyed = true;
3269 this.context.unref();
3270};
3271
3272util.inherits(BufferSlicer, EventEmitter);
3273function BufferSlicer(buffer$$1, options) {
3274 EventEmitter.call(this);
3275
3276 options = options || {};
3277 this.refCount = 0;
3278 this.buffer = buffer$$1;
3279 this.maxChunkSize = options.maxChunkSize || Number.MAX_SAFE_INTEGER;
3280}
3281
3282BufferSlicer.prototype.read = function(buffer$$1, offset, length, position, callback) {
3283 var end = position + length;
3284 var delta = end - this.buffer.length;
3285 var written = (delta > 0) ? delta : length;
3286 this.buffer.copy(buffer$$1, offset, position, end);
3287 setImmediate(function() {
3288 callback(null, written);
3289 });
3290};
3291
3292BufferSlicer.prototype.write = function(buffer$$1, offset, length, position, callback) {
3293 buffer$$1.copy(this.buffer, position, offset, offset + length);
3294 setImmediate(function() {
3295 callback(null, length, buffer$$1);
3296 });
3297};
3298
3299BufferSlicer.prototype.createReadStream = function(options) {
3300 options = options || {};
3301 var readStream = new PassThrough(options);
3302 readStream.destroyed = false;
3303 readStream.start = options.start || 0;
3304 readStream.endOffset = options.end;
3305 // by the time this function returns, we'll be done.
3306 readStream.pos = readStream.endOffset || this.buffer.length;
3307
3308 // respect the maxChunkSize option to slice up the chunk into smaller pieces.
3309 var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
3310 var offset = 0;
3311 while (true) {
3312 var nextOffset = offset + this.maxChunkSize;
3313 if (nextOffset >= entireSlice.length) {
3314 // last chunk
3315 if (offset < entireSlice.length) {
3316 readStream.write(entireSlice.slice(offset, entireSlice.length));
3317 }
3318 break;
3319 }
3320 readStream.write(entireSlice.slice(offset, nextOffset));
3321 offset = nextOffset;
3322 }
3323
3324 readStream.end();
3325 readStream.destroy = function() {
3326 readStream.destroyed = true;
3327 };
3328 return readStream;
3329};
3330
3331BufferSlicer.prototype.createWriteStream = function(options) {
3332 var bufferSlicer = this;
3333 options = options || {};
3334 var writeStream = new Writable$1(options);
3335 writeStream.start = options.start || 0;
3336 writeStream.endOffset = (options.end == null) ? this.buffer.length : +options.end;
3337 writeStream.bytesWritten = 0;
3338 writeStream.pos = writeStream.start;
3339 writeStream.destroyed = false;
3340 writeStream._write = function(buffer$$1, encoding, callback) {
3341 if (writeStream.destroyed) return;
3342
3343 var end = writeStream.pos + buffer$$1.length;
3344 if (end > writeStream.endOffset) {
3345 var err = new Error("maximum file length exceeded");
3346 err.code = 'ETOOBIG';
3347 writeStream.destroyed = true;
3348 callback(err);
3349 return;
3350 }
3351 buffer$$1.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer$$1.length);
3352
3353 writeStream.bytesWritten += buffer$$1.length;
3354 writeStream.pos = end;
3355 writeStream.emit('progress');
3356 callback();
3357 };
3358 writeStream.destroy = function() {
3359 writeStream.destroyed = true;
3360 };
3361 return writeStream;
3362};
3363
3364BufferSlicer.prototype.ref = function() {
3365 this.refCount += 1;
3366};
3367
3368BufferSlicer.prototype.unref = function() {
3369 this.refCount -= 1;
3370
3371 if (this.refCount < 0) {
3372 throw new Error("invalid unref");
3373 }
3374};
3375
3376function createFromBuffer(buffer$$1, options) {
3377 return new BufferSlicer(buffer$$1, options);
3378}
3379
3380function createFromFd(fd, options) {
3381 return new FdSlicer(fd, options);
3382}
3383
3384var fdSlicer = {
3385 createFromBuffer: createFromBuffer_1,
3386 createFromFd: createFromFd_1,
3387 BufferSlicer: BufferSlicer_1,
3388 FdSlicer: FdSlicer_1
3389};
3390
3391var Buffer$1 = buffer.Buffer;
3392
3393var CRC_TABLE = [
3394 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
3395 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
3396 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
3397 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
3398 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
3399 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
3400 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
3401 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
3402 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
3403 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
3404 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
3405 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
3406 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
3407 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
3408 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
3409 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
3410 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
3411 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
3412 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
3413 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
3414 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
3415 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
3416 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
3417 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
3418 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
3419 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
3420 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
3421 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
3422 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
3423 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
3424 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
3425 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
3426 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
3427 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
3428 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
3429 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
3430 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
3431 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
3432 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
3433 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
3434 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
3435 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
3436 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
3437 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
3438 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
3439 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
3440 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
3441 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
3442 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
3443 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
3444 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
3445 0x2d02ef8d
3446];
3447
3448if (typeof Int32Array !== 'undefined') {
3449 CRC_TABLE = new Int32Array(CRC_TABLE);
3450}
3451
3452function ensureBuffer(input) {
3453 if (Buffer$1.isBuffer(input)) {
3454 return input;
3455 }
3456
3457 var hasNewBufferAPI =
3458 typeof Buffer$1.alloc === "function" &&
3459 typeof Buffer$1.from === "function";
3460
3461 if (typeof input === "number") {
3462 return hasNewBufferAPI ? Buffer$1.alloc(input) : new Buffer$1(input);
3463 }
3464 else if (typeof input === "string") {
3465 return hasNewBufferAPI ? Buffer$1.from(input) : new Buffer$1(input);
3466 }
3467 else {
3468 throw new Error("input must be buffer, number, or string, received " +
3469 typeof input);
3470 }
3471}
3472
3473function bufferizeInt(num) {
3474 var tmp = ensureBuffer(4);
3475 tmp.writeInt32BE(num, 0);
3476 return tmp;
3477}
3478
3479function _crc32(buf, previous) {
3480 buf = ensureBuffer(buf);
3481 if (Buffer$1.isBuffer(previous)) {
3482 previous = previous.readUInt32BE(0);
3483 }
3484 var crc = ~~previous ^ -1;
3485 for (var n = 0; n < buf.length; n++) {
3486 crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8);
3487 }
3488 return (crc ^ -1);
3489}
3490
3491function crc32() {
3492 return bufferizeInt(_crc32.apply(null, arguments));
3493}
3494crc32.signed = function () {
3495 return _crc32.apply(null, arguments);
3496};
3497crc32.unsigned = function () {
3498 return _crc32.apply(null, arguments) >>> 0;
3499};
3500
3501var bufferCrc32 = crc32;
3502
3503var EventEmitter$1 = events.EventEmitter;
3504var Transform$2 = stream.Transform;
3505var PassThrough$1 = stream.PassThrough;
3506var Writable$2 = stream.Writable;
3507
3508var open_1 = open;
3509var fromFd_1 = fromFd;
3510var fromBuffer_1 = fromBuffer;
3511var fromRandomAccessReader_1 = fromRandomAccessReader;
3512var dosDateTimeToDate_1 = dosDateTimeToDate;
3513var validateFileName_1 = validateFileName;
3514var ZipFile_1 = ZipFile;
3515var Entry_1 = Entry;
3516var RandomAccessReader_1 = RandomAccessReader;
3517
3518function open(path$$1, options, callback) {
3519 if (typeof options === "function") {
3520 callback = options;
3521 options = null;
3522 }
3523 if (options == null) options = {};
3524 if (options.autoClose == null) options.autoClose = true;
3525 if (options.lazyEntries == null) options.lazyEntries = false;
3526 if (options.decodeStrings == null) options.decodeStrings = true;
3527 if (options.validateEntrySizes == null) options.validateEntrySizes = true;
3528 if (options.strictFileNames == null) options.strictFileNames = false;
3529 if (callback == null) callback = defaultCallback;
3530 fs.open(path$$1, "r", function(err, fd) {
3531 if (err) return callback(err);
3532 fromFd(fd, options, function(err, zipfile) {
3533 if (err) fs.close(fd, defaultCallback);
3534 callback(err, zipfile);
3535 });
3536 });
3537}
3538
3539function fromFd(fd, options, callback) {
3540 if (typeof options === "function") {
3541 callback = options;
3542 options = null;
3543 }
3544 if (options == null) options = {};
3545 if (options.autoClose == null) options.autoClose = false;
3546 if (options.lazyEntries == null) options.lazyEntries = false;
3547 if (options.decodeStrings == null) options.decodeStrings = true;
3548 if (options.validateEntrySizes == null) options.validateEntrySizes = true;
3549 if (options.strictFileNames == null) options.strictFileNames = false;
3550 if (callback == null) callback = defaultCallback;
3551 fs.fstat(fd, function(err, stats) {
3552 if (err) return callback(err);
3553 var reader = fdSlicer.createFromFd(fd, {autoClose: true});
3554 fromRandomAccessReader(reader, stats.size, options, callback);
3555 });
3556}
3557
3558function fromBuffer(buffer$$1, options, callback) {
3559 if (typeof options === "function") {
3560 callback = options;
3561 options = null;
3562 }
3563 if (options == null) options = {};
3564 options.autoClose = false;
3565 if (options.lazyEntries == null) options.lazyEntries = false;
3566 if (options.decodeStrings == null) options.decodeStrings = true;
3567 if (options.validateEntrySizes == null) options.validateEntrySizes = true;
3568 if (options.strictFileNames == null) options.strictFileNames = false;
3569 // limit the max chunk size. see https://github.com/thejoshwolfe/yauzl/issues/87
3570 var reader = fdSlicer.createFromBuffer(buffer$$1, {maxChunkSize: 0x10000});
3571 fromRandomAccessReader(reader, buffer$$1.length, options, callback);
3572}
3573
3574function fromRandomAccessReader(reader, totalSize, options, callback) {
3575 if (typeof options === "function") {
3576 callback = options;
3577 options = null;
3578 }
3579 if (options == null) options = {};
3580 if (options.autoClose == null) options.autoClose = true;
3581 if (options.lazyEntries == null) options.lazyEntries = false;
3582 if (options.decodeStrings == null) options.decodeStrings = true;
3583 var decodeStrings = !!options.decodeStrings;
3584 if (options.validateEntrySizes == null) options.validateEntrySizes = true;
3585 if (options.strictFileNames == null) options.strictFileNames = false;
3586 if (callback == null) callback = defaultCallback;
3587 if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
3588 if (totalSize > Number.MAX_SAFE_INTEGER) {
3589 throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");
3590 }
3591
3592 // the matching unref() call is in zipfile.close()
3593 reader.ref();
3594
3595 // eocdr means End of Central Directory Record.
3596 // search backwards for the eocdr signature.
3597 // the last field of the eocdr is a variable-length comment.
3598 // the comment size is encoded in a 2-byte field in the eocdr, which we can't find without trudging backwards through the comment to find it.
3599 // as a consequence of this design decision, it's possible to have ambiguous zip file metadata if a coherent eocdr was in the comment.
3600 // we search backwards for a eocdr signature, and hope that whoever made the zip file was smart enough to forbid the eocdr signature in the comment.
3601 var eocdrWithoutCommentSize = 22;
3602 var maxCommentSize = 0xffff; // 2-byte size
3603 var bufferSize = Math.min(eocdrWithoutCommentSize + maxCommentSize, totalSize);
3604 var buffer$$1 = newBuffer(bufferSize);
3605 var bufferReadStart = totalSize - buffer$$1.length;
3606 readAndAssertNoEof(reader, buffer$$1, 0, bufferSize, bufferReadStart, function(err) {
3607 if (err) return callback(err);
3608 for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
3609 if (buffer$$1.readUInt32LE(i) !== 0x06054b50) continue;
3610 // found eocdr
3611 var eocdrBuffer = buffer$$1.slice(i);
3612
3613 // 0 - End of central directory signature = 0x06054b50
3614 // 4 - Number of this disk
3615 var diskNumber = eocdrBuffer.readUInt16LE(4);
3616 if (diskNumber !== 0) {
3617 return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
3618 }
3619 // 6 - Disk where central directory starts
3620 // 8 - Number of central directory records on this disk
3621 // 10 - Total number of central directory records
3622 var entryCount = eocdrBuffer.readUInt16LE(10);
3623 // 12 - Size of central directory (bytes)
3624 // 16 - Offset of start of central directory, relative to start of archive
3625 var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
3626 // 20 - Comment length
3627 var commentLength = eocdrBuffer.readUInt16LE(20);
3628 var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
3629 if (commentLength !== expectedCommentLength) {
3630 return callback(new Error("invalid comment length. expected: " + expectedCommentLength + ". found: " + commentLength));
3631 }
3632 // 22 - Comment
3633 // the encoding is always cp437.
3634 var comment = decodeStrings ? decodeBuffer(eocdrBuffer, 22, eocdrBuffer.length, false)
3635 : eocdrBuffer.slice(22);
3636
3637 if (!(entryCount === 0xffff || centralDirectoryOffset === 0xffffffff)) {
3638 return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
3639 }
3640
3641 // ZIP64 format
3642
3643 // ZIP64 Zip64 end of central directory locator
3644 var zip64EocdlBuffer = newBuffer(20);
3645 var zip64EocdlOffset = bufferReadStart + i - zip64EocdlBuffer.length;
3646 readAndAssertNoEof(reader, zip64EocdlBuffer, 0, zip64EocdlBuffer.length, zip64EocdlOffset, function(err) {
3647 if (err) return callback(err);
3648
3649 // 0 - zip64 end of central dir locator signature = 0x07064b50
3650 if (zip64EocdlBuffer.readUInt32LE(0) !== 0x07064b50) {
3651 return callback(new Error("invalid zip64 end of central directory locator signature"));
3652 }
3653 // 4 - number of the disk with the start of the zip64 end of central directory
3654 // 8 - relative offset of the zip64 end of central directory record
3655 var zip64EocdrOffset = readUInt64LE(zip64EocdlBuffer, 8);
3656 // 16 - total number of disks
3657
3658 // ZIP64 end of central directory record
3659 var zip64EocdrBuffer = newBuffer(56);
3660 readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err) {
3661 if (err) return callback(err);
3662
3663 // 0 - zip64 end of central dir signature 4 bytes (0x06064b50)
3664 if (zip64EocdrBuffer.readUInt32LE(0) !== 0x06064b50) {
3665 return callback(new Error("invalid zip64 end of central directory record signature"));
3666 }
3667 // 4 - size of zip64 end of central directory record 8 bytes
3668 // 12 - version made by 2 bytes
3669 // 14 - version needed to extract 2 bytes
3670 // 16 - number of this disk 4 bytes
3671 // 20 - number of the disk with the start of the central directory 4 bytes
3672 // 24 - total number of entries in the central directory on this disk 8 bytes
3673 // 32 - total number of entries in the central directory 8 bytes
3674 entryCount = readUInt64LE(zip64EocdrBuffer, 32);
3675 // 40 - size of the central directory 8 bytes
3676 // 48 - offset of start of central directory with respect to the starting disk number 8 bytes
3677 centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
3678 // 56 - zip64 extensible data sector (variable size)
3679 return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
3680 });
3681 });
3682 return;
3683 }
3684 callback(new Error("end of central directory record signature not found"));
3685 });
3686}
3687
3688util.inherits(ZipFile, EventEmitter$1);
3689function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
3690 var self = this;
3691 EventEmitter$1.call(self);
3692 self.reader = reader;
3693 // forward close events
3694 self.reader.on("error", function(err) {
3695 // error closing the fd
3696 emitError(self, err);
3697 });
3698 self.reader.once("close", function() {
3699 self.emit("close");
3700 });
3701 self.readEntryCursor = centralDirectoryOffset;
3702 self.fileSize = fileSize;
3703 self.entryCount = entryCount;
3704 self.comment = comment;
3705 self.entriesRead = 0;
3706 self.autoClose = !!autoClose;
3707 self.lazyEntries = !!lazyEntries;
3708 self.decodeStrings = !!decodeStrings;
3709 self.validateEntrySizes = !!validateEntrySizes;
3710 self.strictFileNames = !!strictFileNames;
3711 self.isOpen = true;
3712 self.emittedError = false;
3713
3714 if (!self.lazyEntries) self._readEntry();
3715}
3716ZipFile.prototype.close = function() {
3717 if (!this.isOpen) return;
3718 this.isOpen = false;
3719 this.reader.unref();
3720};
3721
3722function emitErrorAndAutoClose(self, err) {
3723 if (self.autoClose) self.close();
3724 emitError(self, err);
3725}
3726function emitError(self, err) {
3727 if (self.emittedError) return;
3728 self.emittedError = true;
3729 self.emit("error", err);
3730}
3731
3732ZipFile.prototype.readEntry = function() {
3733 if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true");
3734 this._readEntry();
3735};
3736ZipFile.prototype._readEntry = function() {
3737 var self = this;
3738 if (self.entryCount === self.entriesRead) {
3739 // done with metadata
3740 setImmediate(function() {
3741 if (self.autoClose) self.close();
3742 if (self.emittedError) return;
3743 self.emit("end");
3744 });
3745 return;
3746 }
3747 if (self.emittedError) return;
3748 var buffer$$1 = newBuffer(46);
3749 readAndAssertNoEof(self.reader, buffer$$1, 0, buffer$$1.length, self.readEntryCursor, function(err) {
3750 if (err) return emitErrorAndAutoClose(self, err);
3751 if (self.emittedError) return;
3752 var entry = new Entry();
3753 // 0 - Central directory file header signature
3754 var signature = buffer$$1.readUInt32LE(0);
3755 if (signature !== 0x02014b50) return emitErrorAndAutoClose(self, new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
3756 // 4 - Version made by
3757 entry.versionMadeBy = buffer$$1.readUInt16LE(4);
3758 // 6 - Version needed to extract (minimum)
3759 entry.versionNeededToExtract = buffer$$1.readUInt16LE(6);
3760 // 8 - General purpose bit flag
3761 entry.generalPurposeBitFlag = buffer$$1.readUInt16LE(8);
3762 // 10 - Compression method
3763 entry.compressionMethod = buffer$$1.readUInt16LE(10);
3764 // 12 - File last modification time
3765 entry.lastModFileTime = buffer$$1.readUInt16LE(12);
3766 // 14 - File last modification date
3767 entry.lastModFileDate = buffer$$1.readUInt16LE(14);
3768 // 16 - CRC-32
3769 entry.crc32 = buffer$$1.readUInt32LE(16);
3770 // 20 - Compressed size
3771 entry.compressedSize = buffer$$1.readUInt32LE(20);
3772 // 24 - Uncompressed size
3773 entry.uncompressedSize = buffer$$1.readUInt32LE(24);
3774 // 28 - File name length (n)
3775 entry.fileNameLength = buffer$$1.readUInt16LE(28);
3776 // 30 - Extra field length (m)
3777 entry.extraFieldLength = buffer$$1.readUInt16LE(30);
3778 // 32 - File comment length (k)
3779 entry.fileCommentLength = buffer$$1.readUInt16LE(32);
3780 // 34 - Disk number where file starts
3781 // 36 - Internal file attributes
3782 entry.internalFileAttributes = buffer$$1.readUInt16LE(36);
3783 // 38 - External file attributes
3784 entry.externalFileAttributes = buffer$$1.readUInt32LE(38);
3785 // 42 - Relative offset of local file header
3786 entry.relativeOffsetOfLocalHeader = buffer$$1.readUInt32LE(42);
3787
3788 if (entry.generalPurposeBitFlag & 0x40) return emitErrorAndAutoClose(self, new Error("strong encryption is not supported"));
3789
3790 self.readEntryCursor += 46;
3791
3792 buffer$$1 = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
3793 readAndAssertNoEof(self.reader, buffer$$1, 0, buffer$$1.length, self.readEntryCursor, function(err) {
3794 if (err) return emitErrorAndAutoClose(self, err);
3795 if (self.emittedError) return;
3796 // 46 - File name
3797 var isUtf8 = (entry.generalPurposeBitFlag & 0x800) !== 0;
3798 entry.fileName = self.decodeStrings ? decodeBuffer(buffer$$1, 0, entry.fileNameLength, isUtf8)
3799 : buffer$$1.slice(0, entry.fileNameLength);
3800
3801 // 46+n - Extra field
3802 var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
3803 var extraFieldBuffer = buffer$$1.slice(entry.fileNameLength, fileCommentStart);
3804 entry.extraFields = [];
3805 var i = 0;
3806 while (i < extraFieldBuffer.length - 3) {
3807 var headerId = extraFieldBuffer.readUInt16LE(i + 0);
3808 var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
3809 var dataStart = i + 4;
3810 var dataEnd = dataStart + dataSize;
3811 if (dataEnd > extraFieldBuffer.length) return emitErrorAndAutoClose(self, new Error("extra field length exceeds extra field buffer size"));
3812 var dataBuffer = newBuffer(dataSize);
3813 extraFieldBuffer.copy(dataBuffer, 0, dataStart, dataEnd);
3814 entry.extraFields.push({
3815 id: headerId,
3816 data: dataBuffer,
3817 });
3818 i = dataEnd;
3819 }
3820
3821 // 46+n+m - File comment
3822 entry.fileComment = self.decodeStrings ? decodeBuffer(buffer$$1, fileCommentStart, fileCommentStart + entry.fileCommentLength, isUtf8)
3823 : buffer$$1.slice(fileCommentStart, fileCommentStart + entry.fileCommentLength);
3824 // compatibility hack for https://github.com/thejoshwolfe/yauzl/issues/47
3825 entry.comment = entry.fileComment;
3826
3827 self.readEntryCursor += buffer$$1.length;
3828 self.entriesRead += 1;
3829
3830 if (entry.uncompressedSize === 0xffffffff ||
3831 entry.compressedSize === 0xffffffff ||
3832 entry.relativeOffsetOfLocalHeader === 0xffffffff) {
3833 // ZIP64 format
3834 // find the Zip64 Extended Information Extra Field
3835 var zip64EiefBuffer = null;
3836 for (var i = 0; i < entry.extraFields.length; i++) {
3837 var extraField = entry.extraFields[i];
3838 if (extraField.id === 0x0001) {
3839 zip64EiefBuffer = extraField.data;
3840 break;
3841 }
3842 }
3843 if (zip64EiefBuffer == null) {
3844 return emitErrorAndAutoClose(self, new Error("expected zip64 extended information extra field"));
3845 }
3846 var index = 0;
3847 // 0 - Original Size 8 bytes
3848 if (entry.uncompressedSize === 0xffffffff) {
3849 if (index + 8 > zip64EiefBuffer.length) {
3850 return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include uncompressed size"));
3851 }
3852 entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
3853 index += 8;
3854 }
3855 // 8 - Compressed Size 8 bytes
3856 if (entry.compressedSize === 0xffffffff) {
3857 if (index + 8 > zip64EiefBuffer.length) {
3858 return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include compressed size"));
3859 }
3860 entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
3861 index += 8;
3862 }
3863 // 16 - Relative Header Offset 8 bytes
3864 if (entry.relativeOffsetOfLocalHeader === 0xffffffff) {
3865 if (index + 8 > zip64EiefBuffer.length) {
3866 return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include relative header offset"));
3867 }
3868 entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
3869 index += 8;
3870 }
3871 // 24 - Disk Start Number 4 bytes
3872 }
3873
3874 // check for Info-ZIP Unicode Path Extra Field (0x7075)
3875 // see https://github.com/thejoshwolfe/yauzl/issues/33
3876 if (self.decodeStrings) {
3877 for (var i = 0; i < entry.extraFields.length; i++) {
3878 var extraField = entry.extraFields[i];
3879 if (extraField.id === 0x7075) {
3880 if (extraField.data.length < 6) {
3881 // too short to be meaningful
3882 continue;
3883 }
3884 // Version 1 byte version of this extra field, currently 1
3885 if (extraField.data.readUInt8(0) !== 1) {
3886 // > Changes may not be backward compatible so this extra
3887 // > field should not be used if the version is not recognized.
3888 continue;
3889 }
3890 // NameCRC32 4 bytes File Name Field CRC32 Checksum
3891 var oldNameCrc32 = extraField.data.readUInt32LE(1);
3892 if (bufferCrc32.unsigned(buffer$$1.slice(0, entry.fileNameLength)) !== oldNameCrc32) {
3893 // > If the CRC check fails, this UTF-8 Path Extra Field should be
3894 // > ignored and the File Name field in the header should be used instead.
3895 continue;
3896 }
3897 // UnicodeName Variable UTF-8 version of the entry File Name
3898 entry.fileName = decodeBuffer(extraField.data, 5, extraField.data.length, true);
3899 break;
3900 }
3901 }
3902 }
3903
3904 // validate file size
3905 if (self.validateEntrySizes && entry.compressionMethod === 0) {
3906 var expectedCompressedSize = entry.uncompressedSize;
3907 if (entry.isEncrypted()) {
3908 // traditional encryption prefixes the file data with a header
3909 expectedCompressedSize += 12;
3910 }
3911 if (entry.compressedSize !== expectedCompressedSize) {
3912 var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
3913 return emitErrorAndAutoClose(self, new Error(msg));
3914 }
3915 }
3916
3917 if (self.decodeStrings) {
3918 if (!self.strictFileNames) {
3919 // allow backslash
3920 entry.fileName = entry.fileName.replace(/\\/g, "/");
3921 }
3922 var errorMessage = validateFileName(entry.fileName, self.validateFileNameOptions);
3923 if (errorMessage != null) return emitErrorAndAutoClose(self, new Error(errorMessage));
3924 }
3925 self.emit("entry", entry);
3926
3927 if (!self.lazyEntries) self._readEntry();
3928 });
3929 });
3930};
3931
3932ZipFile.prototype.openReadStream = function(entry, options, callback) {
3933 var self = this;
3934 // parameter validation
3935 var relativeStart = 0;
3936 var relativeEnd = entry.compressedSize;
3937 if (callback == null) {
3938 callback = options;
3939 options = {};
3940 } else {
3941 // validate options that the caller has no excuse to get wrong
3942 if (options.decrypt != null) {
3943 if (!entry.isEncrypted()) {
3944 throw new Error("options.decrypt can only be specified for encrypted entries");
3945 }
3946 if (options.decrypt !== false) throw new Error("invalid options.decrypt value: " + options.decrypt);
3947 if (entry.isCompressed()) {
3948 if (options.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false");
3949 }
3950 }
3951 if (options.decompress != null) {
3952 if (!entry.isCompressed()) {
3953 throw new Error("options.decompress can only be specified for compressed entries");
3954 }
3955 if (!(options.decompress === false || options.decompress === true)) {
3956 throw new Error("invalid options.decompress value: " + options.decompress);
3957 }
3958 }
3959 if (options.start != null || options.end != null) {
3960 if (entry.isCompressed() && options.decompress !== false) {
3961 throw new Error("start/end range not allowed for compressed entry without options.decompress === false");
3962 }
3963 if (entry.isEncrypted() && options.decrypt !== false) {
3964 throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false");
3965 }
3966 }
3967 if (options.start != null) {
3968 relativeStart = options.start;
3969 if (relativeStart < 0) throw new Error("options.start < 0");
3970 if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize");
3971 }
3972 if (options.end != null) {
3973 relativeEnd = options.end;
3974 if (relativeEnd < 0) throw new Error("options.end < 0");
3975 if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize");
3976 if (relativeEnd < relativeStart) throw new Error("options.end < options.start");
3977 }
3978 }
3979 // any further errors can either be caused by the zipfile,
3980 // or were introduced in a minor version of yauzl,
3981 // so should be passed to the client rather than thrown.
3982 if (!self.isOpen) return callback(new Error("closed"));
3983 if (entry.isEncrypted()) {
3984 if (options.decrypt !== false) return callback(new Error("entry is encrypted, and options.decrypt !== false"));
3985 }
3986 // make sure we don't lose the fd before we open the actual read stream
3987 self.reader.ref();
3988 var buffer$$1 = newBuffer(30);
3989 readAndAssertNoEof(self.reader, buffer$$1, 0, buffer$$1.length, entry.relativeOffsetOfLocalHeader, function(err) {
3990 try {
3991 if (err) return callback(err);
3992 // 0 - Local file header signature = 0x04034b50
3993 var signature = buffer$$1.readUInt32LE(0);
3994 if (signature !== 0x04034b50) {
3995 return callback(new Error("invalid local file header signature: 0x" + signature.toString(16)));
3996 }
3997 // all this should be redundant
3998 // 4 - Version needed to extract (minimum)
3999 // 6 - General purpose bit flag
4000 // 8 - Compression method
4001 // 10 - File last modification time
4002 // 12 - File last modification date
4003 // 14 - CRC-32
4004 // 18 - Compressed size
4005 // 22 - Uncompressed size
4006 // 26 - File name length (n)
4007 var fileNameLength = buffer$$1.readUInt16LE(26);
4008 // 28 - Extra field length (m)
4009 var extraFieldLength = buffer$$1.readUInt16LE(28);
4010 // 30 - File name
4011 // 30+n - Extra field
4012 var localFileHeaderEnd = entry.relativeOffsetOfLocalHeader + buffer$$1.length + fileNameLength + extraFieldLength;
4013 var decompress;
4014 if (entry.compressionMethod === 0) {
4015 // 0 - The file is stored (no compression)
4016 decompress = false;
4017 } else if (entry.compressionMethod === 8) {
4018 // 8 - The file is Deflated
4019 decompress = options.decompress != null ? options.decompress : true;
4020 } else {
4021 return callback(new Error("unsupported compression method: " + entry.compressionMethod));
4022 }
4023 var fileDataStart = localFileHeaderEnd;
4024 var fileDataEnd = fileDataStart + entry.compressedSize;
4025 if (entry.compressedSize !== 0) {
4026 // bounds check now, because the read streams will probably not complain loud enough.
4027 // since we're dealing with an unsigned offset plus an unsigned size,
4028 // we only have 1 thing to check for.
4029 if (fileDataEnd > self.fileSize) {
4030 return callback(new Error("file data overflows file bounds: " +
4031 fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize));
4032 }
4033 }
4034 var readStream = self.reader.createReadStream({
4035 start: fileDataStart + relativeStart,
4036 end: fileDataStart + relativeEnd,
4037 });
4038 var endpointStream = readStream;
4039 if (decompress) {
4040 var destroyed = false;
4041 var inflateFilter = zlib.createInflateRaw();
4042 readStream.on("error", function(err) {
4043 // setImmediate here because errors can be emitted during the first call to pipe()
4044 setImmediate(function() {
4045 if (!destroyed) inflateFilter.emit("error", err);
4046 });
4047 });
4048 readStream.pipe(inflateFilter);
4049
4050 if (self.validateEntrySizes) {
4051 endpointStream = new AssertByteCountStream(entry.uncompressedSize);
4052 inflateFilter.on("error", function(err) {
4053 // forward zlib errors to the client-visible stream
4054 setImmediate(function() {
4055 if (!destroyed) endpointStream.emit("error", err);
4056 });
4057 });
4058 inflateFilter.pipe(endpointStream);
4059 } else {
4060 // the zlib filter is the client-visible stream
4061 endpointStream = inflateFilter;
4062 }
4063 // this is part of yauzl's API, so implement this function on the client-visible stream
4064 endpointStream.destroy = function() {
4065 destroyed = true;
4066 if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
4067 readStream.unpipe(inflateFilter);
4068 // TODO: the inflateFilter may cause a memory leak. see Issue #27.
4069 readStream.destroy();
4070 };
4071 }
4072 callback(null, endpointStream);
4073 } finally {
4074 self.reader.unref();
4075 }
4076 });
4077};
4078
4079function Entry() {
4080}
4081Entry.prototype.getLastModDate = function() {
4082 return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime);
4083};
4084Entry.prototype.isEncrypted = function() {
4085 return (this.generalPurposeBitFlag & 0x1) !== 0;
4086};
4087Entry.prototype.isCompressed = function() {
4088 return this.compressionMethod === 8;
4089};
4090
4091function dosDateTimeToDate(date, time) {
4092 var day = date & 0x1f; // 1-31
4093 var month = (date >> 5 & 0xf) - 1; // 1-12, 0-11
4094 var year = (date >> 9 & 0x7f) + 1980; // 0-128, 1980-2108
4095
4096 var millisecond = 0;
4097 var second = (time & 0x1f) * 2; // 0-29, 0-58 (even numbers)
4098 var minute = time >> 5 & 0x3f; // 0-59
4099 var hour = time >> 11 & 0x1f; // 0-23
4100
4101 return new Date(year, month, day, hour, minute, second, millisecond);
4102}
4103
4104function validateFileName(fileName) {
4105 if (fileName.indexOf("\\") !== -1) {
4106 return "invalid characters in fileName: " + fileName;
4107 }
4108 if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) {
4109 return "absolute path: " + fileName;
4110 }
4111 if (fileName.split("/").indexOf("..") !== -1) {
4112 return "invalid relative path: " + fileName;
4113 }
4114 // all good
4115 return null;
4116}
4117
4118function readAndAssertNoEof(reader, buffer$$1, offset, length, position, callback) {
4119 if (length === 0) {
4120 // fs.read will throw an out-of-bounds error if you try to read 0 bytes from a 0 byte file
4121 return setImmediate(function() { callback(null, newBuffer(0)); });
4122 }
4123 reader.read(buffer$$1, offset, length, position, function(err, bytesRead) {
4124 if (err) return callback(err);
4125 if (bytesRead < length) {
4126 return callback(new Error("unexpected EOF"));
4127 }
4128 callback();
4129 });
4130}
4131
4132util.inherits(AssertByteCountStream, Transform$2);
4133function AssertByteCountStream(byteCount) {
4134 Transform$2.call(this);
4135 this.actualByteCount = 0;
4136 this.expectedByteCount = byteCount;
4137}
4138AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
4139 this.actualByteCount += chunk.length;
4140 if (this.actualByteCount > this.expectedByteCount) {
4141 var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
4142 return cb(new Error(msg));
4143 }
4144 cb(null, chunk);
4145};
4146AssertByteCountStream.prototype._flush = function(cb) {
4147 if (this.actualByteCount < this.expectedByteCount) {
4148 var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
4149 return cb(new Error(msg));
4150 }
4151 cb();
4152};
4153
4154util.inherits(RandomAccessReader, EventEmitter$1);
4155function RandomAccessReader() {
4156 EventEmitter$1.call(this);
4157 this.refCount = 0;
4158}
4159RandomAccessReader.prototype.ref = function() {
4160 this.refCount += 1;
4161};
4162RandomAccessReader.prototype.unref = function() {
4163 var self = this;
4164 self.refCount -= 1;
4165
4166 if (self.refCount > 0) return;
4167 if (self.refCount < 0) throw new Error("invalid unref");
4168
4169 self.close(onCloseDone);
4170
4171 function onCloseDone(err) {
4172 if (err) return self.emit('error', err);
4173 self.emit('close');
4174 }
4175};
4176RandomAccessReader.prototype.createReadStream = function(options) {
4177 var start = options.start;
4178 var end = options.end;
4179 if (start === end) {
4180 var emptyStream = new PassThrough$1();
4181 setImmediate(function() {
4182 emptyStream.end();
4183 });
4184 return emptyStream;
4185 }
4186 var stream$$1 = this._readStreamForRange(start, end);
4187
4188 var destroyed = false;
4189 var refUnrefFilter = new RefUnrefFilter(this);
4190 stream$$1.on("error", function(err) {
4191 setImmediate(function() {
4192 if (!destroyed) refUnrefFilter.emit("error", err);
4193 });
4194 });
4195 refUnrefFilter.destroy = function() {
4196 stream$$1.unpipe(refUnrefFilter);
4197 refUnrefFilter.unref();
4198 stream$$1.destroy();
4199 };
4200
4201 var byteCounter = new AssertByteCountStream(end - start);
4202 refUnrefFilter.on("error", function(err) {
4203 setImmediate(function() {
4204 if (!destroyed) byteCounter.emit("error", err);
4205 });
4206 });
4207 byteCounter.destroy = function() {
4208 destroyed = true;
4209 refUnrefFilter.unpipe(byteCounter);
4210 refUnrefFilter.destroy();
4211 };
4212
4213 return stream$$1.pipe(refUnrefFilter).pipe(byteCounter);
4214};
4215RandomAccessReader.prototype._readStreamForRange = function(start, end) {
4216 throw new Error("not implemented");
4217};
4218RandomAccessReader.prototype.read = function(buffer$$1, offset, length, position, callback) {
4219 var readStream = this.createReadStream({start: position, end: position + length});
4220 var writeStream = new Writable$2();
4221 var written = 0;
4222 writeStream._write = function(chunk, encoding, cb) {
4223 chunk.copy(buffer$$1, offset + written, 0, chunk.length);
4224 written += chunk.length;
4225 cb();
4226 };
4227 writeStream.on("finish", callback);
4228 readStream.on("error", function(error) {
4229 callback(error);
4230 });
4231 readStream.pipe(writeStream);
4232};
4233RandomAccessReader.prototype.close = function(callback) {
4234 setImmediate(callback);
4235};
4236
4237util.inherits(RefUnrefFilter, PassThrough$1);
4238function RefUnrefFilter(context) {
4239 PassThrough$1.call(this);
4240 this.context = context;
4241 this.context.ref();
4242 this.unreffedYet = false;
4243}
4244RefUnrefFilter.prototype._flush = function(cb) {
4245 this.unref();
4246 cb();
4247};
4248RefUnrefFilter.prototype.unref = function(cb) {
4249 if (this.unreffedYet) return;
4250 this.unreffedYet = true;
4251 this.context.unref();
4252};
4253
4254var cp437 = '\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ';
4255function decodeBuffer(buffer$$1, start, end, isUtf8) {
4256 if (isUtf8) {
4257 return buffer$$1.toString("utf8", start, end);
4258 } else {
4259 var result = "";
4260 for (var i = start; i < end; i++) {
4261 result += cp437[buffer$$1[i]];
4262 }
4263 return result;
4264 }
4265}
4266
4267function readUInt64LE(buffer$$1, offset) {
4268 // there is no native function for this, because we can't actually store 64-bit integers precisely.
4269 // after 53 bits, JavaScript's Number type (IEEE 754 double) can't store individual integers anymore.
4270 // but since 53 bits is a whole lot more than 32 bits, we do our best anyway.
4271 var lower32 = buffer$$1.readUInt32LE(offset);
4272 var upper32 = buffer$$1.readUInt32LE(offset + 4);
4273 // we can't use bitshifting here, because JavaScript bitshifting only works on 32-bit integers.
4274 return upper32 * 0x100000000 + lower32;
4275 // as long as we're bounds checking the result of this function against the total file size,
4276 // we'll catch any overflow errors, because we already made sure the total file size was within reason.
4277}
4278
4279// Node 10 deprecated new Buffer().
4280var newBuffer;
4281if (typeof Buffer.allocUnsafe === "function") {
4282 newBuffer = function(len) {
4283 return Buffer.allocUnsafe(len);
4284 };
4285} else {
4286 newBuffer = function(len) {
4287 return new Buffer(len);
4288 };
4289}
4290
4291function defaultCallback(err) {
4292 if (err) throw err;
4293}
4294
4295var yauzl = {
4296 open: open_1,
4297 fromFd: fromFd_1,
4298 fromBuffer: fromBuffer_1,
4299 fromRandomAccessReader: fromRandomAccessReader_1,
4300 dosDateTimeToDate: dosDateTimeToDate_1,
4301 validateFileName: validateFileName_1,
4302 ZipFile: ZipFile_1,
4303 Entry: Entry_1,
4304 RandomAccessReader: RandomAccessReader_1
4305};
4306
4307var _from = "got@^9.5.0";
4308var _id = "got@9.5.0";
4309var _inBundle = false;
4310var _integrity = "sha512-N+4kb6i9t1lauJ4NwLVVoFVLxZNa6i+iivtNzCSVw7+bVbTXoq0qXctdd8i9rj3lrI0zDk5NGzcO4bfpEP6Uuw==";
4311var _location = "/got";
4312var _phantomChildren = {
4313};
4314var _requested = {
4315 type: "range",
4316 registry: true,
4317 raw: "got@^9.5.0",
4318 name: "got",
4319 escapedName: "got",
4320 rawSpec: "^9.5.0",
4321 saveSpec: null,
4322 fetchSpec: "^9.5.0"
4323};
4324var _requiredBy = [
4325 "/gh-got"
4326];
4327var _resolved = "https://registry.npmjs.org/got/-/got-9.5.0.tgz";
4328var _shasum = "6fd0312c6b694c0a11d9119d95fd7daed174eb49";
4329var _spec = "got@^9.5.0";
4330var _where = "/Users/vladimyr/Projects/_private/get-deno/node_modules/gh-got";
4331var ava = {
4332 concurrency: 4
4333};
4334var browser = {
4335 "decompress-response": false,
4336 electron: false
4337};
4338var bugs$1 = {
4339 url: "https://github.com/sindresorhus/got/issues"
4340};
4341var bundleDependencies = false;
4342var dependencies$1 = {
4343 "@sindresorhus/is": "^0.14.0",
4344 "@szmarczak/http-timer": "^1.1.0",
4345 "cacheable-request": "^5.1.0",
4346 "decompress-response": "^3.3.0",
4347 duplexer3: "^0.1.4",
4348 "get-stream": "^4.1.0",
4349 "lowercase-keys": "^1.0.1",
4350 "mimic-response": "^1.0.1",
4351 "p-cancelable": "^1.0.0",
4352 "to-readable-stream": "^1.0.0",
4353 "url-parse-lax": "^3.0.0"
4354};
4355var deprecated = false;
4356var description$1 = "Simplified HTTP requests";
4357var devDependencies$1 = {
4358 ava: "^1.0.1",
4359 coveralls: "^3.0.0",
4360 delay: "^4.1.0",
4361 "form-data": "^2.3.3",
4362 "get-port": "^4.0.0",
4363 np: "^3.1.0",
4364 nyc: "^13.1.0",
4365 "p-event": "^2.1.0",
4366 pem: "^1.13.2",
4367 proxyquire: "^2.0.1",
4368 sinon: "^7.2.2",
4369 "slow-stream": "0.0.4",
4370 tempfile: "^2.0.0",
4371 tempy: "^0.2.1",
4372 "tough-cookie": "^2.4.3",
4373 xo: "^0.23.0"
4374};
4375var engines = {
4376 node: ">=8.6"
4377};
4378var files$1 = [
4379 "source"
4380];
4381var homepage$1 = "https://github.com/sindresorhus/got#readme";
4382var keywords$1 = [
4383 "http",
4384 "https",
4385 "get",
4386 "got",
4387 "url",
4388 "uri",
4389 "request",
4390 "util",
4391 "utility",
4392 "simple",
4393 "curl",
4394 "wget",
4395 "fetch",
4396 "net",
4397 "network",
4398 "electron"
4399];
4400var license$1 = "MIT";
4401var main = "source";
4402var name$1 = "got";
4403var repository$1 = {
4404 type: "git",
4405 url: "git+https://github.com/sindresorhus/got.git"
4406};
4407var scripts$1 = {
4408 release: "np",
4409 test: "xo && nyc ava"
4410};
4411var version$1 = "9.5.0";
4412var _package$2 = {
4413 _from: _from,
4414 _id: _id,
4415 _inBundle: _inBundle,
4416 _integrity: _integrity,
4417 _location: _location,
4418 _phantomChildren: _phantomChildren,
4419 _requested: _requested,
4420 _requiredBy: _requiredBy,
4421 _resolved: _resolved,
4422 _shasum: _shasum,
4423 _spec: _spec,
4424 _where: _where,
4425 ava: ava,
4426 browser: browser,
4427 bugs: bugs$1,
4428 bundleDependencies: bundleDependencies,
4429 dependencies: dependencies$1,
4430 deprecated: deprecated,
4431 description: description$1,
4432 devDependencies: devDependencies$1,
4433 engines: engines,
4434 files: files$1,
4435 homepage: homepage$1,
4436 keywords: keywords$1,
4437 license: license$1,
4438 main: main,
4439 name: name$1,
4440 repository: repository$1,
4441 scripts: scripts$1,
4442 version: version$1
4443};
4444
4445var _package$3 = /*#__PURE__*/Object.freeze({
4446 _from: _from,
4447 _id: _id,
4448 _inBundle: _inBundle,
4449 _integrity: _integrity,
4450 _location: _location,
4451 _phantomChildren: _phantomChildren,
4452 _requested: _requested,
4453 _requiredBy: _requiredBy,
4454 _resolved: _resolved,
4455 _shasum: _shasum,
4456 _spec: _spec,
4457 _where: _where,
4458 ava: ava,
4459 browser: browser,
4460 bugs: bugs$1,
4461 bundleDependencies: bundleDependencies,
4462 dependencies: dependencies$1,
4463 deprecated: deprecated,
4464 description: description$1,
4465 devDependencies: devDependencies$1,
4466 engines: engines,
4467 files: files$1,
4468 homepage: homepage$1,
4469 keywords: keywords$1,
4470 license: license$1,
4471 main: main,
4472 name: name$1,
4473 repository: repository$1,
4474 scripts: scripts$1,
4475 version: version$1,
4476 default: _package$2
4477});
4478
4479class CancelError extends Error {
4480 constructor(reason) {
4481 super(reason || 'Promise was canceled');
4482 this.name = 'CancelError';
4483 }
4484
4485 get isCanceled() {
4486 return true;
4487 }
4488}
4489
4490class PCancelable {
4491 static fn(userFn) {
4492 return (...args) => {
4493 return new PCancelable((resolve, reject, onCancel) => {
4494 args.push(onCancel);
4495 userFn(...args).then(resolve, reject);
4496 });
4497 };
4498 }
4499
4500 constructor(executor) {
4501 this._cancelHandlers = [];
4502 this._isPending = true;
4503 this._isCanceled = false;
4504 this._rejectOnCancel = true;
4505
4506 this._promise = new Promise((resolve, reject) => {
4507 this._reject = reject;
4508
4509 const onResolve = value => {
4510 this._isPending = false;
4511 resolve(value);
4512 };
4513
4514 const onReject = error => {
4515 this._isPending = false;
4516 reject(error);
4517 };
4518
4519 const onCancel = handler => {
4520 this._cancelHandlers.push(handler);
4521 };
4522
4523 Object.defineProperties(onCancel, {
4524 shouldReject: {
4525 get: () => this._rejectOnCancel,
4526 set: bool => {
4527 this._rejectOnCancel = bool;
4528 }
4529 }
4530 });
4531
4532 return executor(onResolve, onReject, onCancel);
4533 });
4534 }
4535
4536 then(onFulfilled, onRejected) {
4537 return this._promise.then(onFulfilled, onRejected);
4538 }
4539
4540 catch(onRejected) {
4541 return this._promise.catch(onRejected);
4542 }
4543
4544 finally(onFinally) {
4545 return this._promise.finally(onFinally);
4546 }
4547
4548 cancel(reason) {
4549 if (!this._isPending || this._isCanceled) {
4550 return;
4551 }
4552
4553 if (this._cancelHandlers.length > 0) {
4554 try {
4555 for (const handler of this._cancelHandlers) {
4556 handler();
4557 }
4558 } catch (error) {
4559 this._reject(error);
4560 }
4561 }
4562
4563 this._isCanceled = true;
4564 if (this._rejectOnCancel) {
4565 this._reject(new CancelError(reason));
4566 }
4567 }
4568
4569 get isCanceled() {
4570 return this._isCanceled;
4571 }
4572}
4573
4574Object.setPrototypeOf(PCancelable.prototype, Promise.prototype);
4575
4576var pCancelable = PCancelable;
4577var CancelError_1 = CancelError;
4578pCancelable.CancelError = CancelError_1;
4579
4580var dist = createCommonjsModule(function (module, exports) {
4581/// <reference lib="es2016"/>
4582/// <reference lib="es2017.sharedmemory"/>
4583/// <reference lib="esnext.asynciterable"/>
4584/// <reference lib="dom"/>
4585Object.defineProperty(exports, "__esModule", { value: true });
4586// TODO: Use the `URL` global when targeting Node.js 10
4587// tslint:disable-next-line
4588const URLGlobal = typeof URL === 'undefined' ? url.URL : URL;
4589const toString = Object.prototype.toString;
4590const isOfType = (type) => (value) => typeof value === type;
4591const isBuffer = (input) => !is.nullOrUndefined(input) && !is.nullOrUndefined(input.constructor) && is.function_(input.constructor.isBuffer) && input.constructor.isBuffer(input);
4592const getObjectType = (value) => {
4593 const objectName = toString.call(value).slice(8, -1);
4594 if (objectName) {
4595 return objectName;
4596 }
4597 return null;
4598};
4599const isObjectOfType = (type) => (value) => getObjectType(value) === type;
4600function is(value) {
4601 switch (value) {
4602 case null:
4603 return "null" /* null */;
4604 case true:
4605 case false:
4606 return "boolean" /* boolean */;
4607 default:
4608 }
4609 switch (typeof value) {
4610 case 'undefined':
4611 return "undefined" /* undefined */;
4612 case 'string':
4613 return "string" /* string */;
4614 case 'number':
4615 return "number" /* number */;
4616 case 'symbol':
4617 return "symbol" /* symbol */;
4618 default:
4619 }
4620 if (is.function_(value)) {
4621 return "Function" /* Function */;
4622 }
4623 if (is.observable(value)) {
4624 return "Observable" /* Observable */;
4625 }
4626 if (Array.isArray(value)) {
4627 return "Array" /* Array */;
4628 }
4629 if (isBuffer(value)) {
4630 return "Buffer" /* Buffer */;
4631 }
4632 const tagType = getObjectType(value);
4633 if (tagType) {
4634 return tagType;
4635 }
4636 if (value instanceof String || value instanceof Boolean || value instanceof Number) {
4637 throw new TypeError('Please don\'t use object wrappers for primitive types');
4638 }
4639 return "Object" /* Object */;
4640}
4641(function (is) {
4642 // tslint:disable-next-line:strict-type-predicates
4643 const isObject = (value) => typeof value === 'object';
4644 // tslint:disable:variable-name
4645 is.undefined = isOfType('undefined');
4646 is.string = isOfType('string');
4647 is.number = isOfType('number');
4648 is.function_ = isOfType('function');
4649 // tslint:disable-next-line:strict-type-predicates
4650 is.null_ = (value) => value === null;
4651 is.class_ = (value) => is.function_(value) && value.toString().startsWith('class ');
4652 is.boolean = (value) => value === true || value === false;
4653 is.symbol = isOfType('symbol');
4654 // tslint:enable:variable-name
4655 is.numericString = (value) => is.string(value) && value.length > 0 && !Number.isNaN(Number(value));
4656 is.array = Array.isArray;
4657 is.buffer = isBuffer;
4658 is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value);
4659 is.object = (value) => !is.nullOrUndefined(value) && (is.function_(value) || isObject(value));
4660 is.iterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.iterator]);
4661 is.asyncIterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.asyncIterator]);
4662 is.generator = (value) => is.iterable(value) && is.function_(value.next) && is.function_(value.throw);
4663 is.nativePromise = (value) => isObjectOfType("Promise" /* Promise */)(value);
4664 const hasPromiseAPI = (value) => !is.null_(value) &&
4665 isObject(value) &&
4666 is.function_(value.then) &&
4667 is.function_(value.catch);
4668 is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value);
4669 is.generatorFunction = isObjectOfType("GeneratorFunction" /* GeneratorFunction */);
4670 is.asyncFunction = isObjectOfType("AsyncFunction" /* AsyncFunction */);
4671 is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype');
4672 is.regExp = isObjectOfType("RegExp" /* RegExp */);
4673 is.date = isObjectOfType("Date" /* Date */);
4674 is.error = isObjectOfType("Error" /* Error */);
4675 is.map = (value) => isObjectOfType("Map" /* Map */)(value);
4676 is.set = (value) => isObjectOfType("Set" /* Set */)(value);
4677 is.weakMap = (value) => isObjectOfType("WeakMap" /* WeakMap */)(value);
4678 is.weakSet = (value) => isObjectOfType("WeakSet" /* WeakSet */)(value);
4679 is.int8Array = isObjectOfType("Int8Array" /* Int8Array */);
4680 is.uint8Array = isObjectOfType("Uint8Array" /* Uint8Array */);
4681 is.uint8ClampedArray = isObjectOfType("Uint8ClampedArray" /* Uint8ClampedArray */);
4682 is.int16Array = isObjectOfType("Int16Array" /* Int16Array */);
4683 is.uint16Array = isObjectOfType("Uint16Array" /* Uint16Array */);
4684 is.int32Array = isObjectOfType("Int32Array" /* Int32Array */);
4685 is.uint32Array = isObjectOfType("Uint32Array" /* Uint32Array */);
4686 is.float32Array = isObjectOfType("Float32Array" /* Float32Array */);
4687 is.float64Array = isObjectOfType("Float64Array" /* Float64Array */);
4688 is.arrayBuffer = isObjectOfType("ArrayBuffer" /* ArrayBuffer */);
4689 is.sharedArrayBuffer = isObjectOfType("SharedArrayBuffer" /* SharedArrayBuffer */);
4690 is.dataView = isObjectOfType("DataView" /* DataView */);
4691 is.directInstanceOf = (instance, klass) => Object.getPrototypeOf(instance) === klass.prototype;
4692 is.urlInstance = (value) => isObjectOfType("URL" /* URL */)(value);
4693 is.urlString = (value) => {
4694 if (!is.string(value)) {
4695 return false;
4696 }
4697 try {
4698 new URLGlobal(value); // tslint:disable-line no-unused-expression
4699 return true;
4700 }
4701 catch (_a) {
4702 return false;
4703 }
4704 };
4705 is.truthy = (value) => Boolean(value);
4706 is.falsy = (value) => !value;
4707 is.nan = (value) => Number.isNaN(value);
4708 const primitiveTypes = new Set([
4709 'undefined',
4710 'string',
4711 'number',
4712 'boolean',
4713 'symbol'
4714 ]);
4715 is.primitive = (value) => is.null_(value) || primitiveTypes.has(typeof value);
4716 is.integer = (value) => Number.isInteger(value);
4717 is.safeInteger = (value) => Number.isSafeInteger(value);
4718 is.plainObject = (value) => {
4719 // From: https://github.com/sindresorhus/is-plain-obj/blob/master/index.js
4720 let prototype;
4721 return getObjectType(value) === "Object" /* Object */ &&
4722 (prototype = Object.getPrototypeOf(value), prototype === null || // tslint:disable-line:ban-comma-operator
4723 prototype === Object.getPrototypeOf({}));
4724 };
4725 const typedArrayTypes = new Set([
4726 "Int8Array" /* Int8Array */,
4727 "Uint8Array" /* Uint8Array */,
4728 "Uint8ClampedArray" /* Uint8ClampedArray */,
4729 "Int16Array" /* Int16Array */,
4730 "Uint16Array" /* Uint16Array */,
4731 "Int32Array" /* Int32Array */,
4732 "Uint32Array" /* Uint32Array */,
4733 "Float32Array" /* Float32Array */,
4734 "Float64Array" /* Float64Array */
4735 ]);
4736 is.typedArray = (value) => {
4737 const objectType = getObjectType(value);
4738 if (objectType === null) {
4739 return false;
4740 }
4741 return typedArrayTypes.has(objectType);
4742 };
4743 const isValidLength = (value) => is.safeInteger(value) && value > -1;
4744 is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length);
4745 is.inRange = (value, range) => {
4746 if (is.number(range)) {
4747 return value >= Math.min(0, range) && value <= Math.max(range, 0);
4748 }
4749 if (is.array(range) && range.length === 2) {
4750 return value >= Math.min(...range) && value <= Math.max(...range);
4751 }
4752 throw new TypeError(`Invalid range: ${JSON.stringify(range)}`);
4753 };
4754 const NODE_TYPE_ELEMENT = 1;
4755 const DOM_PROPERTIES_TO_CHECK = [
4756 'innerHTML',
4757 'ownerDocument',
4758 'style',
4759 'attributes',
4760 'nodeValue'
4761 ];
4762 is.domElement = (value) => is.object(value) && value.nodeType === NODE_TYPE_ELEMENT && is.string(value.nodeName) &&
4763 !is.plainObject(value) && DOM_PROPERTIES_TO_CHECK.every(property => property in value);
4764 is.observable = (value) => {
4765 if (!value) {
4766 return false;
4767 }
4768 if (value[Symbol.observable] && value === value[Symbol.observable]()) {
4769 return true;
4770 }
4771 if (value['@@observable'] && value === value['@@observable']()) {
4772 return true;
4773 }
4774 return false;
4775 };
4776 is.nodeStream = (value) => !is.nullOrUndefined(value) && isObject(value) && is.function_(value.pipe) && !is.observable(value);
4777 is.infinite = (value) => value === Infinity || value === -Infinity;
4778 const isAbsoluteMod2 = (rem) => (value) => is.integer(value) && Math.abs(value % 2) === rem;
4779 is.even = isAbsoluteMod2(0);
4780 is.odd = isAbsoluteMod2(1);
4781 const isWhiteSpaceString = (value) => is.string(value) && /\S/.test(value) === false;
4782 is.emptyArray = (value) => is.array(value) && value.length === 0;
4783 is.nonEmptyArray = (value) => is.array(value) && value.length > 0;
4784 is.emptyString = (value) => is.string(value) && value.length === 0;
4785 is.nonEmptyString = (value) => is.string(value) && value.length > 0;
4786 is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value);
4787 is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0;
4788 is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0;
4789 is.emptySet = (value) => is.set(value) && value.size === 0;
4790 is.nonEmptySet = (value) => is.set(value) && value.size > 0;
4791 is.emptyMap = (value) => is.map(value) && value.size === 0;
4792 is.nonEmptyMap = (value) => is.map(value) && value.size > 0;
4793 const predicateOnArray = (method, predicate, values) => {
4794 if (is.function_(predicate) === false) {
4795 throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`);
4796 }
4797 if (values.length === 0) {
4798 throw new TypeError('Invalid number of values');
4799 }
4800 return method.call(values, predicate);
4801 };
4802 // tslint:disable variable-name
4803 is.any = (predicate, ...values) => predicateOnArray(Array.prototype.some, predicate, values);
4804 is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values);
4805 // tslint:enable variable-name
4806})(is || (is = {}));
4807// Some few keywords are reserved, but we'll populate them for Node.js users
4808// See https://github.com/Microsoft/TypeScript/issues/2536
4809Object.defineProperties(is, {
4810 class: {
4811 value: is.class_
4812 },
4813 function: {
4814 value: is.function_
4815 },
4816 null: {
4817 value: is.null_
4818 }
4819});
4820exports.default = is;
4821// For CommonJS default export support
4822module.exports = is;
4823module.exports.default = is;
4824
4825});
4826
4827unwrapExports(dist);
4828
4829class GotError extends Error {
4830 constructor(message, error, options) {
4831 super(message);
4832 Error.captureStackTrace(this, this.constructor);
4833 this.name = 'GotError';
4834
4835 if (!dist.undefined(error.code)) {
4836 this.code = error.code;
4837 }
4838
4839 Object.assign(this, {
4840 host: options.host,
4841 hostname: options.hostname,
4842 method: options.method,
4843 path: options.path,
4844 socketPath: options.socketPath,
4845 protocol: options.protocol,
4846 url: options.href,
4847 gotOptions: options
4848 });
4849 }
4850}
4851
4852var GotError_1 = GotError;
4853
4854var CacheError = class extends GotError {
4855 constructor(error, options) {
4856 super(error.message, error, options);
4857 this.name = 'CacheError';
4858 }
4859};
4860
4861var RequestError = class extends GotError {
4862 constructor(error, options) {
4863 super(error.message, error, options);
4864 this.name = 'RequestError';
4865 }
4866};
4867
4868var ReadError = class extends GotError {
4869 constructor(error, options) {
4870 super(error.message, error, options);
4871 this.name = 'ReadError';
4872 }
4873};
4874
4875var ParseError = class extends GotError {
4876 constructor(error, statusCode, options, data) {
4877 super(`${error.message} in "${url.format(options)}": \n${data.slice(0, 77)}...`, error, options);
4878 this.name = 'ParseError';
4879 this.statusCode = statusCode;
4880 this.statusMessage = http.STATUS_CODES[this.statusCode];
4881 }
4882};
4883
4884var HTTPError = class extends GotError {
4885 constructor(response, options) {
4886 const {statusCode} = response;
4887 let {statusMessage} = response;
4888
4889 if (statusMessage) {
4890 statusMessage = statusMessage.replace(/\r?\n/g, ' ').trim();
4891 } else {
4892 statusMessage = http.STATUS_CODES[statusCode];
4893 }
4894 super(`Response code ${statusCode} (${statusMessage})`, {}, options);
4895 this.name = 'HTTPError';
4896 this.statusCode = statusCode;
4897 this.statusMessage = statusMessage;
4898 this.headers = response.headers;
4899 this.body = response.body;
4900 }
4901};
4902
4903var MaxRedirectsError = class extends GotError {
4904 constructor(statusCode, redirectUrls, options) {
4905 super('Redirected 10 times. Aborting.', {}, options);
4906 this.name = 'MaxRedirectsError';
4907 this.statusCode = statusCode;
4908 this.statusMessage = http.STATUS_CODES[this.statusCode];
4909 this.redirectUrls = redirectUrls;
4910 }
4911};
4912
4913var UnsupportedProtocolError = class extends GotError {
4914 constructor(options) {
4915 super(`Unsupported protocol "${options.protocol}"`, {}, options);
4916 this.name = 'UnsupportedProtocolError';
4917 }
4918};
4919
4920var TimeoutError = class extends GotError {
4921 constructor(error, options) {
4922 super(error.message, {code: 'ETIMEDOUT'}, options);
4923 this.name = 'TimeoutError';
4924 this.event = error.event;
4925 }
4926};
4927
4928var CancelError$1 = pCancelable.CancelError;
4929
4930var errors = {
4931 GotError: GotError_1,
4932 CacheError: CacheError,
4933 RequestError: RequestError,
4934 ReadError: ReadError,
4935 ParseError: ParseError,
4936 HTTPError: HTTPError,
4937 MaxRedirectsError: MaxRedirectsError,
4938 UnsupportedProtocolError: UnsupportedProtocolError,
4939 TimeoutError: TimeoutError,
4940 CancelError: CancelError$1
4941};
4942
4943function DuplexWrapper(options, writable, readable) {
4944 if (typeof readable === "undefined") {
4945 readable = writable;
4946 writable = options;
4947 options = null;
4948 }
4949
4950 stream.Duplex.call(this, options);
4951
4952 if (typeof readable.read !== "function") {
4953 readable = (new stream.Readable(options)).wrap(readable);
4954 }
4955
4956 this._writable = writable;
4957 this._readable = readable;
4958 this._waiting = false;
4959
4960 var self = this;
4961
4962 writable.once("finish", function() {
4963 self.end();
4964 });
4965
4966 this.once("finish", function() {
4967 writable.end();
4968 });
4969
4970 readable.on("readable", function() {
4971 if (self._waiting) {
4972 self._waiting = false;
4973 self._read();
4974 }
4975 });
4976
4977 readable.once("end", function() {
4978 self.push(null);
4979 });
4980
4981 if (!options || typeof options.bubbleErrors === "undefined" || options.bubbleErrors) {
4982 writable.on("error", function(err) {
4983 self.emit("error", err);
4984 });
4985
4986 readable.on("error", function(err) {
4987 self.emit("error", err);
4988 });
4989 }
4990}
4991
4992DuplexWrapper.prototype = Object.create(stream.Duplex.prototype, {constructor: {value: DuplexWrapper}});
4993
4994DuplexWrapper.prototype._write = function _write(input, encoding, done) {
4995 this._writable.write(input, encoding, done);
4996};
4997
4998DuplexWrapper.prototype._read = function _read() {
4999 var buf;
5000 var reads = 0;
5001 while ((buf = this._readable.read()) !== null) {
5002 this.push(buf);
5003 reads++;
5004 }
5005 if (reads === 0) {
5006 this._waiting = true;
5007 }
5008};
5009
5010var duplexer3 = function duplex2(options, writable, readable) {
5011 return new DuplexWrapper(options, writable, readable);
5012};
5013
5014var DuplexWrapper_1 = DuplexWrapper;
5015duplexer3.DuplexWrapper = DuplexWrapper_1;
5016
5017// TODO: Use the `URL` global when targeting Node.js 10
5018const URLParser = typeof URL === 'undefined' ? url.URL : URL;
5019
5020const testParameter = (name, filters) => {
5021 return filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name);
5022};
5023
5024var normalizeUrl = (urlString, opts) => {
5025 opts = Object.assign({
5026 defaultProtocol: 'http:',
5027 normalizeProtocol: true,
5028 forceHttp: false,
5029 forceHttps: false,
5030 stripHash: true,
5031 stripWWW: true,
5032 removeQueryParameters: [/^utm_\w+/i],
5033 removeTrailingSlash: true,
5034 removeDirectoryIndex: false,
5035 sortQueryParameters: true
5036 }, opts);
5037
5038 // Backwards compatibility
5039 if (Reflect.has(opts, 'normalizeHttps')) {
5040 opts.forceHttp = opts.normalizeHttps;
5041 }
5042
5043 if (Reflect.has(opts, 'normalizeHttp')) {
5044 opts.forceHttps = opts.normalizeHttp;
5045 }
5046
5047 if (Reflect.has(opts, 'stripFragment')) {
5048 opts.stripHash = opts.stripFragment;
5049 }
5050
5051 urlString = urlString.trim();
5052
5053 const hasRelativeProtocol = urlString.startsWith('//');
5054 const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString);
5055
5056 // Prepend protocol
5057 if (!isRelativeUrl) {
5058 urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, opts.defaultProtocol);
5059 }
5060
5061 const urlObj = new URLParser(urlString);
5062
5063 if (opts.forceHttp && opts.forceHttps) {
5064 throw new Error('The `forceHttp` and `forceHttps` options cannot be used together');
5065 }
5066
5067 if (opts.forceHttp && urlObj.protocol === 'https:') {
5068 urlObj.protocol = 'http:';
5069 }
5070
5071 if (opts.forceHttps && urlObj.protocol === 'http:') {
5072 urlObj.protocol = 'https:';
5073 }
5074
5075 // Remove hash
5076 if (opts.stripHash) {
5077 urlObj.hash = '';
5078 }
5079
5080 // Remove duplicate slashes if not preceded by a protocol
5081 if (urlObj.pathname) {
5082 // TODO: Use the following instead when targeting Node.js 10
5083 // `urlObj.pathname = urlObj.pathname.replace(/(?<!https?:)\/{2,}/g, '/');`
5084 urlObj.pathname = urlObj.pathname.replace(/((?![https?:]).)\/{2,}/g, (_, p1) => {
5085 if (/^(?!\/)/g.test(p1)) {
5086 return `${p1}/`;
5087 }
5088 return '/';
5089 });
5090 }
5091
5092 // Decode URI octets
5093 if (urlObj.pathname) {
5094 urlObj.pathname = decodeURI(urlObj.pathname);
5095 }
5096
5097 // Remove directory index
5098 if (opts.removeDirectoryIndex === true) {
5099 opts.removeDirectoryIndex = [/^index\.[a-z]+$/];
5100 }
5101
5102 if (Array.isArray(opts.removeDirectoryIndex) && opts.removeDirectoryIndex.length > 0) {
5103 let pathComponents = urlObj.pathname.split('/');
5104 const lastComponent = pathComponents[pathComponents.length - 1];
5105
5106 if (testParameter(lastComponent, opts.removeDirectoryIndex)) {
5107 pathComponents = pathComponents.slice(0, pathComponents.length - 1);
5108 urlObj.pathname = pathComponents.slice(1).join('/') + '/';
5109 }
5110 }
5111
5112 if (urlObj.hostname) {
5113 // Remove trailing dot
5114 urlObj.hostname = urlObj.hostname.replace(/\.$/, '');
5115
5116 // Remove `www.`
5117 // eslint-disable-next-line no-useless-escape
5118 if (opts.stripWWW && /^www\.([a-z\-\d]{2,63})\.([a-z\.]{2,5})$/.test(urlObj.hostname)) {
5119 // Each label should be max 63 at length (min: 2).
5120 // The extension should be max 5 at length (min: 2).
5121 // Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
5122 urlObj.hostname = urlObj.hostname.replace(/^www\./, '');
5123 }
5124 }
5125
5126 // Remove query unwanted parameters
5127 if (Array.isArray(opts.removeQueryParameters)) {
5128 for (const key of [...urlObj.searchParams.keys()]) {
5129 if (testParameter(key, opts.removeQueryParameters)) {
5130 urlObj.searchParams.delete(key);
5131 }
5132 }
5133 }
5134
5135 // Sort query parameters
5136 if (opts.sortQueryParameters) {
5137 urlObj.searchParams.sort();
5138 }
5139
5140 // Take advantage of many of the Node `url` normalizations
5141 urlString = urlObj.toString();
5142
5143 // Remove ending `/`
5144 if (opts.removeTrailingSlash || urlObj.pathname === '/') {
5145 urlString = urlString.replace(/\/$/, '');
5146 }
5147
5148 // Restore relative protocol, if applicable
5149 if (hasRelativeProtocol && !opts.normalizeProtocol) {
5150 urlString = urlString.replace(/^http:\/\//, '//');
5151 }
5152
5153 return urlString;
5154};
5155
5156const {PassThrough: PassThrough$2} = stream;
5157
5158var bufferStream = options => {
5159 options = Object.assign({}, options);
5160
5161 const {array} = options;
5162 let {encoding} = options;
5163 const buffer$$1 = encoding === 'buffer';
5164 let objectMode = false;
5165
5166 if (array) {
5167 objectMode = !(encoding || buffer$$1);
5168 } else {
5169 encoding = encoding || 'utf8';
5170 }
5171
5172 if (buffer$$1) {
5173 encoding = null;
5174 }
5175
5176 let len = 0;
5177 const ret = [];
5178 const stream$$1 = new PassThrough$2({objectMode});
5179
5180 if (encoding) {
5181 stream$$1.setEncoding(encoding);
5182 }
5183
5184 stream$$1.on('data', chunk => {
5185 ret.push(chunk);
5186
5187 if (objectMode) {
5188 len = ret.length;
5189 } else {
5190 len += chunk.length;
5191 }
5192 });
5193
5194 stream$$1.getBufferedValue = () => {
5195 if (array) {
5196 return ret;
5197 }
5198
5199 return buffer$$1 ? Buffer.concat(ret, len) : ret.join('');
5200 };
5201
5202 stream$$1.getBufferedLength = () => len;
5203
5204 return stream$$1;
5205};
5206
5207class MaxBufferError extends Error {
5208 constructor() {
5209 super('maxBuffer exceeded');
5210 this.name = 'MaxBufferError';
5211 }
5212}
5213
5214function getStream(inputStream, options) {
5215 if (!inputStream) {
5216 return Promise.reject(new Error('Expected a stream'));
5217 }
5218
5219 options = Object.assign({maxBuffer: Infinity}, options);
5220
5221 const {maxBuffer} = options;
5222
5223 let stream$$1;
5224 return new Promise((resolve, reject) => {
5225 const rejectPromise = error => {
5226 if (error) { // A null check
5227 error.bufferedData = stream$$1.getBufferedValue();
5228 }
5229 reject(error);
5230 };
5231
5232 stream$$1 = pump_1(inputStream, bufferStream(options), error => {
5233 if (error) {
5234 rejectPromise(error);
5235 return;
5236 }
5237
5238 resolve();
5239 });
5240
5241 stream$$1.on('data', () => {
5242 if (stream$$1.getBufferedLength() > maxBuffer) {
5243 rejectPromise(new MaxBufferError());
5244 }
5245 });
5246 }).then(() => stream$$1.getBufferedValue());
5247}
5248
5249var getStream_1 = getStream;
5250var buffer$1 = (stream$$1, options) => getStream(stream$$1, Object.assign({}, options, {encoding: 'buffer'}));
5251var array = (stream$$1, options) => getStream(stream$$1, Object.assign({}, options, {array: true}));
5252var MaxBufferError_1 = MaxBufferError;
5253getStream_1.buffer = buffer$1;
5254getStream_1.array = array;
5255getStream_1.MaxBufferError = MaxBufferError_1;
5256
5257// rfc7231 6.1
5258const statusCodeCacheableByDefault = [200, 203, 204, 206, 300, 301, 404, 405, 410, 414, 501];
5259
5260// This implementation does not understand partial responses (206)
5261const understoodStatuses = [200, 203, 204, 300, 301, 302, 303, 307, 308, 404, 405, 410, 414, 501];
5262
5263const hopByHopHeaders = {
5264 'date': true, // included, because we add Age update Date
5265 'connection':true, 'keep-alive':true, 'proxy-authenticate':true, 'proxy-authorization':true, 'te':true, 'trailer':true, 'transfer-encoding':true, 'upgrade':true
5266};
5267const excludedFromRevalidationUpdate = {
5268 // Since the old body is reused, it doesn't make sense to change properties of the body
5269 'content-length': true, 'content-encoding': true, 'transfer-encoding': true,
5270 'content-range': true,
5271};
5272
5273function parseCacheControl(header) {
5274 const cc = {};
5275 if (!header) return cc;
5276
5277 // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives),
5278 // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale
5279 const parts = header.trim().split(/\s*,\s*/); // TODO: lame parsing
5280 for(const part of parts) {
5281 const [k,v] = part.split(/\s*=\s*/, 2);
5282 cc[k] = (v === undefined) ? true : v.replace(/^"|"$/g, ''); // TODO: lame unquoting
5283 }
5284
5285 return cc;
5286}
5287
5288function formatCacheControl(cc) {
5289 let parts = [];
5290 for(const k in cc) {
5291 const v = cc[k];
5292 parts.push(v === true ? k : k + '=' + v);
5293 }
5294 if (!parts.length) {
5295 return undefined;
5296 }
5297 return parts.join(', ');
5298}
5299
5300var httpCacheSemantics = class CachePolicy {
5301 constructor(req, res, {shared, cacheHeuristic, immutableMinTimeToLive, ignoreCargoCult, trustServerDate, _fromObject} = {}) {
5302 if (_fromObject) {
5303 this._fromObject(_fromObject);
5304 return;
5305 }
5306
5307 if (!res || !res.headers) {
5308 throw Error("Response headers missing");
5309 }
5310 this._assertRequestHasHeaders(req);
5311
5312 this._responseTime = this.now();
5313 this._isShared = shared !== false;
5314 this._trustServerDate = undefined !== trustServerDate ? trustServerDate : true;
5315 this._cacheHeuristic = undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE
5316 this._immutableMinTtl = undefined !== immutableMinTimeToLive ? immutableMinTimeToLive : 24*3600*1000;
5317
5318 this._status = 'status' in res ? res.status : 200;
5319 this._resHeaders = res.headers;
5320 this._rescc = parseCacheControl(res.headers['cache-control']);
5321 this._method = 'method' in req ? req.method : 'GET';
5322 this._url = req.url;
5323 this._host = req.headers.host;
5324 this._noAuthorization = !req.headers.authorization;
5325 this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used
5326 this._reqcc = parseCacheControl(req.headers['cache-control']);
5327
5328 // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching,
5329 // so there's no point stricly adhering to the blindly copy&pasted directives.
5330 if (ignoreCargoCult && "pre-check" in this._rescc && "post-check" in this._rescc) {
5331 delete this._rescc['pre-check'];
5332 delete this._rescc['post-check'];
5333 delete this._rescc['no-cache'];
5334 delete this._rescc['no-store'];
5335 delete this._rescc['must-revalidate'];
5336 this._resHeaders = Object.assign({}, this._resHeaders, {'cache-control': formatCacheControl(this._rescc)});
5337 delete this._resHeaders.expires;
5338 delete this._resHeaders.pragma;
5339 }
5340
5341 // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive
5342 // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1).
5343 if (!res.headers['cache-control'] && /no-cache/.test(res.headers.pragma)) {
5344 this._rescc['no-cache'] = true;
5345 }
5346 }
5347
5348 now() {
5349 return Date.now();
5350 }
5351
5352 storable() {
5353 // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it.
5354 return !!(!this._reqcc['no-store'] &&
5355 // A cache MUST NOT store a response to any request, unless:
5356 // The request method is understood by the cache and defined as being cacheable, and
5357 ('GET' === this._method || 'HEAD' === this._method || ('POST' === this._method && this._hasExplicitExpiration())) &&
5358 // the response status code is understood by the cache, and
5359 understoodStatuses.indexOf(this._status) !== -1 &&
5360 // the "no-store" cache directive does not appear in request or response header fields, and
5361 !this._rescc['no-store'] &&
5362 // the "private" response directive does not appear in the response, if the cache is shared, and
5363 (!this._isShared || !this._rescc.private) &&
5364 // the Authorization header field does not appear in the request, if the cache is shared,
5365 (!this._isShared || this._noAuthorization || this._allowsStoringAuthenticated()) &&
5366 // the response either:
5367 (
5368 // contains an Expires header field, or
5369 this._resHeaders.expires ||
5370 // contains a max-age response directive, or
5371 // contains a s-maxage response directive and the cache is shared, or
5372 // contains a public response directive.
5373 this._rescc.public || this._rescc['max-age'] || this._rescc['s-maxage'] ||
5374 // has a status code that is defined as cacheable by default
5375 statusCodeCacheableByDefault.indexOf(this._status) !== -1
5376 ));
5377 }
5378
5379 _hasExplicitExpiration() {
5380 // 4.2.1 Calculating Freshness Lifetime
5381 return (this._isShared && this._rescc['s-maxage']) ||
5382 this._rescc['max-age'] ||
5383 this._resHeaders.expires;
5384 }
5385
5386 _assertRequestHasHeaders(req) {
5387 if (!req || !req.headers) {
5388 throw Error("Request headers missing");
5389 }
5390 }
5391
5392 satisfiesWithoutRevalidation(req) {
5393 this._assertRequestHasHeaders(req);
5394
5395 // When presented with a request, a cache MUST NOT reuse a stored response, unless:
5396 // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive,
5397 // unless the stored response is successfully validated (Section 4.3), and
5398 const requestCC = parseCacheControl(req.headers['cache-control']);
5399 if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) {
5400 return false;
5401 }
5402
5403 if (requestCC['max-age'] && this.age() > requestCC['max-age']) {
5404 return false;
5405 }
5406
5407 if (requestCC['min-fresh'] && this.timeToLive() < 1000*requestCC['min-fresh']) {
5408 return false;
5409 }
5410
5411 // the stored response is either:
5412 // fresh, or allowed to be served stale
5413 if (this.stale()) {
5414 const allowsStale = requestCC['max-stale'] && !this._rescc['must-revalidate'] && (true === requestCC['max-stale'] || requestCC['max-stale'] > this.age() - this.maxAge());
5415 if (!allowsStale) {
5416 return false;
5417 }
5418 }
5419
5420 return this._requestMatches(req, false);
5421 }
5422
5423 _requestMatches(req, allowHeadMethod) {
5424 // The presented effective request URI and that of the stored response match, and
5425 return (!this._url || this._url === req.url) &&
5426 (this._host === req.headers.host) &&
5427 // the request method associated with the stored response allows it to be used for the presented request, and
5428 (!req.method || this._method === req.method || (allowHeadMethod && 'HEAD' === req.method)) &&
5429 // selecting header fields nominated by the stored response (if any) match those presented, and
5430 this._varyMatches(req);
5431 }
5432
5433 _allowsStoringAuthenticated() {
5434 // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage.
5435 return this._rescc['must-revalidate'] || this._rescc.public || this._rescc['s-maxage'];
5436 }
5437
5438 _varyMatches(req) {
5439 if (!this._resHeaders.vary) {
5440 return true;
5441 }
5442
5443 // A Vary header field-value of "*" always fails to match
5444 if (this._resHeaders.vary === '*') {
5445 return false;
5446 }
5447
5448 const fields = this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/);
5449 for(const name of fields) {
5450 if (req.headers[name] !== this._reqHeaders[name]) return false;
5451 }
5452 return true;
5453 }
5454
5455 _copyWithoutHopByHopHeaders(inHeaders) {
5456 const headers = {};
5457 for(const name in inHeaders) {
5458 if (hopByHopHeaders[name]) continue;
5459 headers[name] = inHeaders[name];
5460 }
5461 // 9.1. Connection
5462 if (inHeaders.connection) {
5463 const tokens = inHeaders.connection.trim().split(/\s*,\s*/);
5464 for(const name of tokens) {
5465 delete headers[name];
5466 }
5467 }
5468 if (headers.warning) {
5469 const warnings = headers.warning.split(/,/).filter(warning => {
5470 return !/^\s*1[0-9][0-9]/.test(warning);
5471 });
5472 if (!warnings.length) {
5473 delete headers.warning;
5474 } else {
5475 headers.warning = warnings.join(',').trim();
5476 }
5477 }
5478 return headers;
5479 }
5480
5481 responseHeaders() {
5482 const headers = this._copyWithoutHopByHopHeaders(this._resHeaders);
5483 const age = this.age();
5484
5485 // A cache SHOULD generate 113 warning if it heuristically chose a freshness
5486 // lifetime greater than 24 hours and the response's age is greater than 24 hours.
5487 if (age > 3600*24 && !this._hasExplicitExpiration() && this.maxAge() > 3600*24) {
5488 headers.warning = (headers.warning ? `${headers.warning}, ` : '') + '113 - "rfc7234 5.5.4"';
5489 }
5490 headers.age = `${Math.round(age)}`;
5491 headers.date = new Date(this.now()).toUTCString();
5492 return headers;
5493 }
5494
5495 /**
5496 * Value of the Date response header or current time if Date was demed invalid
5497 * @return timestamp
5498 */
5499 date() {
5500 if (this._trustServerDate) {
5501 return this._serverDate();
5502 }
5503 return this._responseTime;
5504 }
5505
5506 _serverDate() {
5507 const dateValue = Date.parse(this._resHeaders.date);
5508 if (isFinite(dateValue)) {
5509 const maxClockDrift = 8*3600*1000;
5510 const clockDrift = Math.abs(this._responseTime - dateValue);
5511 if (clockDrift < maxClockDrift) {
5512 return dateValue;
5513 }
5514 }
5515 return this._responseTime;
5516 }
5517
5518 /**
5519 * Value of the Age header, in seconds, updated for the current time.
5520 * May be fractional.
5521 *
5522 * @return Number
5523 */
5524 age() {
5525 let age = Math.max(0, (this._responseTime - this.date())/1000);
5526 if (this._resHeaders.age) {
5527 let ageValue = this._ageValue();
5528 if (ageValue > age) age = ageValue;
5529 }
5530
5531 const residentTime = (this.now() - this._responseTime)/1000;
5532 return age + residentTime;
5533 }
5534
5535 _ageValue() {
5536 const ageValue = parseInt(this._resHeaders.age);
5537 return isFinite(ageValue) ? ageValue : 0;
5538 }
5539
5540 /**
5541 * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`.
5542 *
5543 * For an up-to-date value, see `timeToLive()`.
5544 *
5545 * @return Number
5546 */
5547 maxAge() {
5548 if (!this.storable() || this._rescc['no-cache']) {
5549 return 0;
5550 }
5551
5552 // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default
5553 // so this implementation requires explicit opt-in via public header
5554 if (this._isShared && (this._resHeaders['set-cookie'] && !this._rescc.public && !this._rescc.immutable)) {
5555 return 0;
5556 }
5557
5558 if (this._resHeaders.vary === '*') {
5559 return 0;
5560 }
5561
5562 if (this._isShared) {
5563 if (this._rescc['proxy-revalidate']) {
5564 return 0;
5565 }
5566 // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field.
5567 if (this._rescc['s-maxage']) {
5568 return parseInt(this._rescc['s-maxage'], 10);
5569 }
5570 }
5571
5572 // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.
5573 if (this._rescc['max-age']) {
5574 return parseInt(this._rescc['max-age'], 10);
5575 }
5576
5577 const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;
5578
5579 const dateValue = this._serverDate();
5580 if (this._resHeaders.expires) {
5581 const expires = Date.parse(this._resHeaders.expires);
5582 // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired").
5583 if (Number.isNaN(expires) || expires < dateValue) {
5584 return 0;
5585 }
5586 return Math.max(defaultMinTtl, (expires - dateValue)/1000);
5587 }
5588
5589 if (this._resHeaders['last-modified']) {
5590 const lastModified = Date.parse(this._resHeaders['last-modified']);
5591 if (isFinite(lastModified) && dateValue > lastModified) {
5592 return Math.max(defaultMinTtl, (dateValue - lastModified)/1000 * this._cacheHeuristic);
5593 }
5594 }
5595
5596 return defaultMinTtl;
5597 }
5598
5599 timeToLive() {
5600 return Math.max(0, this.maxAge() - this.age())*1000;
5601 }
5602
5603 stale() {
5604 return this.maxAge() <= this.age();
5605 }
5606
5607 static fromObject(obj) {
5608 return new this(undefined, undefined, {_fromObject:obj});
5609 }
5610
5611 _fromObject(obj) {
5612 if (this._responseTime) throw Error("Reinitialized");
5613 if (!obj || obj.v !== 1) throw Error("Invalid serialization");
5614
5615 this._responseTime = obj.t;
5616 this._isShared = obj.sh;
5617 this._cacheHeuristic = obj.ch;
5618 this._immutableMinTtl = obj.imm !== undefined ? obj.imm : 24*3600*1000;
5619 this._status = obj.st;
5620 this._resHeaders = obj.resh;
5621 this._rescc = obj.rescc;
5622 this._method = obj.m;
5623 this._url = obj.u;
5624 this._host = obj.h;
5625 this._noAuthorization = obj.a;
5626 this._reqHeaders = obj.reqh;
5627 this._reqcc = obj.reqcc;
5628 }
5629
5630 toObject() {
5631 return {
5632 v:1,
5633 t: this._responseTime,
5634 sh: this._isShared,
5635 ch: this._cacheHeuristic,
5636 imm: this._immutableMinTtl,
5637 st: this._status,
5638 resh: this._resHeaders,
5639 rescc: this._rescc,
5640 m: this._method,
5641 u: this._url,
5642 h: this._host,
5643 a: this._noAuthorization,
5644 reqh: this._reqHeaders,
5645 reqcc: this._reqcc,
5646 };
5647 }
5648
5649 /**
5650 * Headers for sending to the origin server to revalidate stale response.
5651 * Allows server to return 304 to allow reuse of the previous response.
5652 *
5653 * Hop by hop headers are always stripped.
5654 * Revalidation headers may be added or removed, depending on request.
5655 */
5656 revalidationHeaders(incomingReq) {
5657 this._assertRequestHasHeaders(incomingReq);
5658 const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers);
5659
5660 // This implementation does not understand range requests
5661 delete headers['if-range'];
5662
5663 if (!this._requestMatches(incomingReq, true) || !this.storable()) { // revalidation allowed via HEAD
5664 // not for the same resource, or wasn't allowed to be cached anyway
5665 delete headers['if-none-match'];
5666 delete headers['if-modified-since'];
5667 return headers;
5668 }
5669
5670 /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */
5671 if (this._resHeaders.etag) {
5672 headers['if-none-match'] = headers['if-none-match'] ? `${headers['if-none-match']}, ${this._resHeaders.etag}` : this._resHeaders.etag;
5673 }
5674
5675 // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request.
5676 const forbidsWeakValidators = headers['accept-ranges'] || headers['if-match'] || headers['if-unmodified-since'] || (this._method && this._method != 'GET');
5677
5678 /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server.
5679 Note: This implementation does not understand partial responses (206) */
5680 if (forbidsWeakValidators) {
5681 delete headers['if-modified-since'];
5682
5683 if (headers['if-none-match']) {
5684 const etags = headers['if-none-match'].split(/,/).filter(etag => {
5685 return !/^\s*W\//.test(etag);
5686 });
5687 if (!etags.length) {
5688 delete headers['if-none-match'];
5689 } else {
5690 headers['if-none-match'] = etags.join(',').trim();
5691 }
5692 }
5693 } else if (this._resHeaders['last-modified'] && !headers['if-modified-since']) {
5694 headers['if-modified-since'] = this._resHeaders['last-modified'];
5695 }
5696
5697 return headers;
5698 }
5699
5700 /**
5701 * Creates new CachePolicy with information combined from the previews response,
5702 * and the new revalidation response.
5703 *
5704 * Returns {policy, modified} where modified is a boolean indicating
5705 * whether the response body has been modified, and old cached body can't be used.
5706 *
5707 * @return {Object} {policy: CachePolicy, modified: Boolean}
5708 */
5709 revalidatedPolicy(request, response) {
5710 this._assertRequestHasHeaders(request);
5711 if (!response || !response.headers) {
5712 throw Error("Response headers missing");
5713 }
5714
5715 // These aren't going to be supported exactly, since one CachePolicy object
5716 // doesn't know about all the other cached objects.
5717 let matches = false;
5718 if (response.status !== undefined && response.status != 304) {
5719 matches = false;
5720 } else if (response.headers.etag && !/^\s*W\//.test(response.headers.etag)) {
5721 // "All of the stored responses with the same strong validator are selected.
5722 // If none of the stored responses contain the same strong validator,
5723 // then the cache MUST NOT use the new response to update any stored responses."
5724 matches = this._resHeaders.etag && this._resHeaders.etag.replace(/^\s*W\//,'') === response.headers.etag;
5725 } else if (this._resHeaders.etag && response.headers.etag) {
5726 // "If the new response contains a weak validator and that validator corresponds
5727 // to one of the cache's stored responses,
5728 // then the most recent of those matching stored responses is selected for update."
5729 matches = this._resHeaders.etag.replace(/^\s*W\//,'') === response.headers.etag.replace(/^\s*W\//,'');
5730 } else if (this._resHeaders['last-modified']) {
5731 matches = this._resHeaders['last-modified'] === response.headers['last-modified'];
5732 } else {
5733 // If the new response does not include any form of validator (such as in the case where
5734 // a client generates an If-Modified-Since request from a source other than the Last-Modified
5735 // response header field), and there is only one stored response, and that stored response also
5736 // lacks a validator, then that stored response is selected for update.
5737 if (!this._resHeaders.etag && !this._resHeaders['last-modified'] &&
5738 !response.headers.etag && !response.headers['last-modified']) {
5739 matches = true;
5740 }
5741 }
5742
5743 if (!matches) {
5744 return {
5745 policy: new this.constructor(request, response),
5746 modified: true,
5747 }
5748 }
5749
5750 // use other header fields provided in the 304 (Not Modified) response to replace all instances
5751 // of the corresponding header fields in the stored response.
5752 const headers = {};
5753 for(const k in this._resHeaders) {
5754 headers[k] = k in response.headers && !excludedFromRevalidationUpdate[k] ? response.headers[k] : this._resHeaders[k];
5755 }
5756
5757 const newResponse = Object.assign({}, response, {
5758 status: this._status,
5759 method: this._method,
5760 headers,
5761 });
5762 return {
5763 policy: new this.constructor(request, newResponse, {shared: this._isShared, cacheHeuristic: this._cacheHeuristic, immutableMinTimeToLive: this._immutableMinTtl, trustServerDate: this._trustServerDate}),
5764 modified: false,
5765 };
5766 }
5767};
5768
5769var lowercaseKeys = function (obj) {
5770 var ret = {};
5771 var keys = Object.keys(Object(obj));
5772
5773 for (var i = 0; i < keys.length; i++) {
5774 ret[keys[i].toLowerCase()] = obj[keys[i]];
5775 }
5776
5777 return ret;
5778};
5779
5780const Readable$2 = stream.Readable;
5781
5782
5783class Response extends Readable$2 {
5784 constructor(statusCode, headers, body, url$$1) {
5785 if (typeof statusCode !== 'number') {
5786 throw new TypeError('Argument `statusCode` should be a number');
5787 }
5788 if (typeof headers !== 'object') {
5789 throw new TypeError('Argument `headers` should be an object');
5790 }
5791 if (!(body instanceof Buffer)) {
5792 throw new TypeError('Argument `body` should be a buffer');
5793 }
5794 if (typeof url$$1 !== 'string') {
5795 throw new TypeError('Argument `url` should be a string');
5796 }
5797
5798 super();
5799 this.statusCode = statusCode;
5800 this.headers = lowercaseKeys(headers);
5801 this.body = body;
5802 this.url = url$$1;
5803 }
5804
5805 _read() {
5806 this.push(this.body);
5807 this.push(null);
5808 }
5809}
5810
5811var src = Response;
5812
5813// We define these manually to ensure they're always copied
5814// even if they would move up the prototype chain
5815// https://nodejs.org/api/http.html#http_class_http_incomingmessage
5816const knownProps = [
5817 'destroy',
5818 'setTimeout',
5819 'socket',
5820 'headers',
5821 'trailers',
5822 'rawHeaders',
5823 'statusCode',
5824 'httpVersion',
5825 'httpVersionMinor',
5826 'httpVersionMajor',
5827 'rawTrailers',
5828 'statusMessage'
5829];
5830
5831var mimicResponse = (fromStream, toStream) => {
5832 const fromProps = new Set(Object.keys(fromStream).concat(knownProps));
5833
5834 for (const prop of fromProps) {
5835 // Don't overwrite existing properties
5836 if (prop in toStream) {
5837 continue;
5838 }
5839
5840 toStream[prop] = typeof fromStream[prop] === 'function' ? fromStream[prop].bind(fromStream) : fromStream[prop];
5841 }
5842};
5843
5844const PassThrough$3 = stream.PassThrough;
5845
5846
5847const cloneResponse = response => {
5848 if (!(response && response.pipe)) {
5849 throw new TypeError('Parameter `response` must be a response stream.');
5850 }
5851
5852 const clone = new PassThrough$3();
5853 mimicResponse(response, clone);
5854
5855 return response.pipe(clone);
5856};
5857
5858var src$1 = cloneResponse;
5859
5860//TODO: handle reviver/dehydrate function like normal
5861//and handle indentation, like normal.
5862//if anyone needs this... please send pull request.
5863
5864var stringify = function stringify (o) {
5865 if('undefined' == typeof o) return o
5866
5867 if(o && Buffer.isBuffer(o))
5868 return JSON.stringify(':base64:' + o.toString('base64'))
5869
5870 if(o && o.toJSON)
5871 o = o.toJSON();
5872
5873 if(o && 'object' === typeof o) {
5874 var s = '';
5875 var array = Array.isArray(o);
5876 s = array ? '[' : '{';
5877 var first = true;
5878
5879 for(var k in o) {
5880 var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k]);
5881 if(Object.hasOwnProperty.call(o, k) && !ignore) {
5882 if(!first)
5883 s += ',';
5884 first = false;
5885 if (array) {
5886 if(o[k] == undefined)
5887 s += 'null';
5888 else
5889 s += stringify(o[k]);
5890 } else if (o[k] !== void(0)) {
5891 s += stringify(k) + ':' + stringify(o[k]);
5892 }
5893 }
5894 }
5895
5896 s += array ? ']' : '}';
5897
5898 return s
5899 } else if ('string' === typeof o) {
5900 return JSON.stringify(/^:/.test(o) ? ':' + o : o)
5901 } else if ('undefined' === typeof o) {
5902 return 'null';
5903 } else
5904 return JSON.stringify(o)
5905};
5906
5907var parse$1 = function (s) {
5908 return JSON.parse(s, function (key, value) {
5909 if('string' === typeof value) {
5910 if(/^:base64:/.test(value))
5911 return new Buffer(value.substring(8), 'base64')
5912 else
5913 return /^:/.test(value) ? value.substring(1) : value
5914 }
5915 return value
5916 })
5917};
5918
5919var jsonBuffer = {
5920 stringify: stringify,
5921 parse: parse$1
5922};
5923
5924const loadStore = opts => {
5925 const adapters = {
5926 redis: '@keyv/redis',
5927 mongodb: '@keyv/mongo',
5928 mongo: '@keyv/mongo',
5929 sqlite: '@keyv/sqlite',
5930 postgresql: '@keyv/postgres',
5931 postgres: '@keyv/postgres',
5932 mysql: '@keyv/mysql'
5933 };
5934 if (opts.adapter || opts.uri) {
5935 const adapter = opts.adapter || /^[^:]*/.exec(opts.uri)[0];
5936 return new (commonjsRequire(adapters[adapter]))(opts);
5937 }
5938 return new Map();
5939};
5940
5941class Keyv extends events {
5942 constructor(uri, opts) {
5943 super();
5944 this.opts = Object.assign(
5945 {
5946 namespace: 'keyv',
5947 serialize: jsonBuffer.stringify,
5948 deserialize: jsonBuffer.parse
5949 },
5950 (typeof uri === 'string') ? { uri } : uri,
5951 opts
5952 );
5953
5954 if (!this.opts.store) {
5955 const adapterOpts = Object.assign({}, this.opts);
5956 this.opts.store = loadStore(adapterOpts);
5957 }
5958
5959 if (typeof this.opts.store.on === 'function') {
5960 this.opts.store.on('error', err => this.emit('error', err));
5961 }
5962
5963 this.opts.store.namespace = this.opts.namespace;
5964 }
5965
5966 _getKeyPrefix(key) {
5967 return `${this.opts.namespace}:${key}`;
5968 }
5969
5970 get(key) {
5971 key = this._getKeyPrefix(key);
5972 const store = this.opts.store;
5973 return Promise.resolve()
5974 .then(() => store.get(key))
5975 .then(data => {
5976 data = (typeof data === 'string') ? this.opts.deserialize(data) : data;
5977 if (data === undefined) {
5978 return undefined;
5979 }
5980 if (typeof data.expires === 'number' && Date.now() > data.expires) {
5981 this.delete(key);
5982 return undefined;
5983 }
5984 return data.value;
5985 });
5986 }
5987
5988 set(key, value, ttl) {
5989 key = this._getKeyPrefix(key);
5990 if (typeof ttl === 'undefined') {
5991 ttl = this.opts.ttl;
5992 }
5993 if (ttl === 0) {
5994 ttl = undefined;
5995 }
5996 const store = this.opts.store;
5997
5998 return Promise.resolve()
5999 .then(() => {
6000 const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null;
6001 value = { value, expires };
6002 return store.set(key, this.opts.serialize(value), ttl);
6003 })
6004 .then(() => true);
6005 }
6006
6007 delete(key) {
6008 key = this._getKeyPrefix(key);
6009 const store = this.opts.store;
6010 return Promise.resolve()
6011 .then(() => store.delete(key));
6012 }
6013
6014 clear() {
6015 const store = this.opts.store;
6016 return Promise.resolve()
6017 .then(() => store.clear());
6018 }
6019}
6020
6021var src$2 = Keyv;
6022
6023class CacheableRequest {
6024 constructor(request, cacheAdapter) {
6025 if (typeof request !== 'function') {
6026 throw new TypeError('Parameter `request` must be a function');
6027 }
6028
6029 this.cache = new src$2({
6030 uri: typeof cacheAdapter === 'string' && cacheAdapter,
6031 store: typeof cacheAdapter !== 'string' && cacheAdapter,
6032 namespace: 'cacheable-request'
6033 });
6034
6035 return this.createCacheableRequest(request);
6036 }
6037
6038 createCacheableRequest(request) {
6039 return (opts, cb) => {
6040 let url$$1;
6041 if (typeof opts === 'string') {
6042 url$$1 = normalizeUrlObject(url.parse(opts));
6043 opts = {};
6044 } else if (opts instanceof url.URL) {
6045 url$$1 = normalizeUrlObject(url.parse(opts.toString()));
6046 opts = {};
6047 } else {
6048 const [pathname, ...searchParts] = (opts.path || '').split('?');
6049 const search = searchParts.length > 0 ?
6050 `?${searchParts.join('?')}` :
6051 '';
6052 url$$1 = normalizeUrlObject({ ...opts, pathname, search });
6053 }
6054 opts = {
6055 headers: {},
6056 method: 'GET',
6057 cache: true,
6058 strictTtl: false,
6059 automaticFailover: false,
6060 ...opts,
6061 ...urlObjectToRequestOptions(url$$1)
6062 };
6063 opts.headers = lowercaseKeys(opts.headers);
6064
6065 const ee = new events();
6066 const normalizedUrlString = normalizeUrl(
6067 url.format(url$$1),
6068 {
6069 stripWWW: false,
6070 removeTrailingSlash: false
6071 }
6072 );
6073 const key = `${opts.method}:${normalizedUrlString}`;
6074 let revalidate = false;
6075 let madeRequest = false;
6076
6077 const makeRequest = opts => {
6078 madeRequest = true;
6079 let requestErrored = false;
6080 let requestErrorCallback;
6081
6082 const requestErrorPromise = new Promise(resolve => {
6083 requestErrorCallback = () => {
6084 requestErrored = true;
6085 resolve();
6086 };
6087 });
6088
6089 const handler = response => {
6090 if (revalidate && !opts.forceRefresh) {
6091 response.status = response.statusCode;
6092 const revalidatedPolicy = httpCacheSemantics.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response);
6093 if (!revalidatedPolicy.modified) {
6094 const headers = revalidatedPolicy.policy.responseHeaders();
6095 response = new src(response.statusCode, headers, revalidate.body, revalidate.url);
6096 response.cachePolicy = revalidatedPolicy.policy;
6097 response.fromCache = true;
6098 }
6099 }
6100
6101 if (!response.fromCache) {
6102 response.cachePolicy = new httpCacheSemantics(opts, response, opts);
6103 response.fromCache = false;
6104 }
6105
6106 let clonedResponse;
6107 if (opts.cache && response.cachePolicy.storable()) {
6108 clonedResponse = src$1(response);
6109
6110 (async () => {
6111 try {
6112 const bodyPromise = getStream_1.buffer(response);
6113
6114 await Promise.race([
6115 requestErrorPromise,
6116 new Promise(resolve => response.once('end', resolve))
6117 ]);
6118
6119 if (requestErrored) {
6120 return;
6121 }
6122
6123 const body = await bodyPromise;
6124
6125 const value = {
6126 cachePolicy: response.cachePolicy.toObject(),
6127 url: response.url,
6128 statusCode: response.fromCache ? revalidate.statusCode : response.statusCode,
6129 body
6130 };
6131
6132 let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined;
6133 if (opts.maxTtl) {
6134 ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl;
6135 }
6136
6137 await this.cache.set(key, value, ttl);
6138 } catch (err) {
6139 ee.emit('error', new CacheableRequest.CacheError(err));
6140 }
6141 })();
6142 } else if (opts.cache && revalidate) {
6143 (async () => {
6144 try {
6145 await this.cache.delete(key);
6146 } catch (err) {
6147 ee.emit('error', new CacheableRequest.CacheError(err));
6148 }
6149 })();
6150 }
6151
6152 ee.emit('response', clonedResponse || response);
6153 if (typeof cb === 'function') {
6154 cb(clonedResponse || response);
6155 }
6156 };
6157
6158 try {
6159 const req = request(opts, handler);
6160 req.once('error', requestErrorCallback);
6161 req.once('abort', requestErrorCallback);
6162 ee.emit('request', req);
6163 } catch (err) {
6164 ee.emit('error', new CacheableRequest.RequestError(err));
6165 }
6166 };
6167
6168 (async () => {
6169 const get = async opts => {
6170 await Promise.resolve();
6171
6172 const cacheEntry = opts.cache ? await this.cache.get(key) : undefined;
6173 if (typeof cacheEntry === 'undefined') {
6174 return makeRequest(opts);
6175 }
6176
6177 const policy = httpCacheSemantics.fromObject(cacheEntry.cachePolicy);
6178 if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) {
6179 const headers = policy.responseHeaders();
6180 const response = new src(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url);
6181 response.cachePolicy = policy;
6182 response.fromCache = true;
6183
6184 ee.emit('response', response);
6185 if (typeof cb === 'function') {
6186 cb(response);
6187 }
6188 } else {
6189 revalidate = cacheEntry;
6190 opts.headers = policy.revalidationHeaders(opts);
6191 makeRequest(opts);
6192 }
6193 };
6194
6195 this.cache.on('error', err => ee.emit('error', new CacheableRequest.CacheError(err)));
6196
6197 try {
6198 await get(opts);
6199 } catch (err) {
6200 if (opts.automaticFailover && !madeRequest) {
6201 makeRequest(opts);
6202 }
6203 ee.emit('error', new CacheableRequest.CacheError(err));
6204 }
6205 })();
6206
6207 return ee;
6208 };
6209 }
6210}
6211
6212function urlObjectToRequestOptions(url$$1) {
6213 const options = { ...url$$1 };
6214 options.path = `${url$$1.pathname || '/'}${url$$1.search || ''}`;
6215 delete options.pathname;
6216 delete options.search;
6217 return options;
6218}
6219
6220function normalizeUrlObject(url$$1) {
6221 // If url was parsed by url.parse or new URL:
6222 // - hostname will be set
6223 // - host will be hostname[:port]
6224 // - port will be set if it was explicit in the parsed string
6225 // Otherwise, url was from request options:
6226 // - hostname or host may be set
6227 // - host shall not have port encoded
6228 return {
6229 protocol: url$$1.protocol,
6230 auth: url$$1.auth,
6231 hostname: url$$1.hostname || url$$1.host || 'localhost',
6232 port: url$$1.port,
6233 pathname: url$$1.pathname,
6234 search: url$$1.search
6235 };
6236}
6237
6238CacheableRequest.RequestError = class extends Error {
6239 constructor(err) {
6240 super(err.message);
6241 this.name = 'RequestError';
6242 Object.assign(this, err);
6243 }
6244};
6245
6246CacheableRequest.CacheError = class extends Error {
6247 constructor(err) {
6248 super(err.message);
6249 this.name = 'CacheError';
6250 Object.assign(this, err);
6251 }
6252};
6253
6254var src$3 = CacheableRequest;
6255
6256const {Readable: Readable$3} = stream;
6257
6258var toReadableStream = input => (
6259 new Readable$3({
6260 read() {
6261 this.push(input);
6262 this.push(null);
6263 }
6264 })
6265);
6266
6267// Inspired by https://github.com/nodejs/node/blob/949e8851484c016c07f6cc9e5889f0f2e56baf2a/lib/_http_client.js#L706
6268var deferToConnect = (socket, method, ...args) => {
6269 let call;
6270 if (typeof method === 'function') {
6271 call = method;
6272 } else {
6273 call = () => socket[method](...args);
6274 }
6275
6276 if (socket.writable && !socket.connecting) {
6277 call();
6278 } else {
6279 socket.once('connect', call);
6280 }
6281};
6282
6283var source = request => {
6284 const timings = {
6285 start: Date.now(),
6286 socket: null,
6287 lookup: null,
6288 connect: null,
6289 upload: null,
6290 response: null,
6291 end: null,
6292 error: null,
6293 phases: {
6294 wait: null,
6295 dns: null,
6296 tcp: null,
6297 request: null,
6298 firstByte: null,
6299 download: null,
6300 total: null
6301 }
6302 };
6303
6304 const handleError = origin => {
6305 const emit = origin.emit.bind(origin);
6306 origin.emit = (event, ...args) => {
6307 // Catches the `error` event
6308 if (event === 'error') {
6309 timings.error = Date.now();
6310 timings.phases.total = timings.error - timings.start;
6311
6312 origin.emit = emit;
6313 }
6314
6315 // Saves the original behavior
6316 return emit(event, ...args);
6317 };
6318 };
6319
6320 let uploadFinished = false;
6321 const onUpload = () => {
6322 timings.upload = Date.now();
6323 timings.phases.request = timings.upload - timings.connect;
6324 };
6325
6326 handleError(request);
6327
6328 request.once('socket', socket => {
6329 timings.socket = Date.now();
6330 timings.phases.wait = timings.socket - timings.start;
6331
6332 const lookupListener = () => {
6333 timings.lookup = Date.now();
6334 timings.phases.dns = timings.lookup - timings.socket;
6335 };
6336
6337 socket.once('lookup', lookupListener);
6338
6339 deferToConnect(socket, () => {
6340 timings.connect = Date.now();
6341
6342 if (timings.lookup === null) {
6343 socket.removeListener('lookup', lookupListener);
6344 timings.lookup = timings.connect;
6345 timings.phases.dns = timings.lookup - timings.socket;
6346 }
6347
6348 timings.phases.tcp = timings.connect - timings.lookup;
6349
6350 if (uploadFinished && !timings.upload) {
6351 onUpload();
6352 }
6353 });
6354 });
6355
6356 request.once('finish', () => {
6357 uploadFinished = true;
6358
6359 if (timings.connect) {
6360 onUpload();
6361 }
6362 });
6363
6364 request.once('response', response => {
6365 timings.response = Date.now();
6366 timings.phases.firstByte = timings.response - timings.upload;
6367
6368 handleError(response);
6369
6370 response.once('end', () => {
6371 timings.end = Date.now();
6372 timings.phases.download = timings.end - timings.response;
6373 timings.phases.total = timings.end - timings.start;
6374 });
6375 });
6376
6377 return timings;
6378};
6379
6380class TimeoutError$1 extends Error {
6381 constructor(threshold, event) {
6382 super(`Timeout awaiting '${event}' for ${threshold}ms`);
6383 this.name = 'TimeoutError';
6384 this.code = 'ETIMEDOUT';
6385 this.event = event;
6386 }
6387}
6388
6389const reentry = Symbol('reentry');
6390
6391const noop$5 = () => {};
6392
6393var timedOut = (request, delays, options) => {
6394 /* istanbul ignore next: this makes sure timed-out isn't called twice */
6395 if (request[reentry]) {
6396 return;
6397 }
6398
6399 request[reentry] = true;
6400
6401 let stopNewTimeouts = false;
6402
6403 const addTimeout = (delay, callback, ...args) => {
6404 // An error had been thrown before. Going further would result in uncaught errors.
6405 // See https://github.com/sindresorhus/got/issues/631#issuecomment-435675051
6406 if (stopNewTimeouts) {
6407 return noop$5;
6408 }
6409
6410 // Event loop order is timers, poll, immediates.
6411 // The timed event may emit during the current tick poll phase, so
6412 // defer calling the handler until the poll phase completes.
6413 let immediate;
6414 const timeout = setTimeout(() => {
6415 immediate = setImmediate(callback, delay, ...args);
6416 /* istanbul ignore next: added in node v9.7.0 */
6417 if (immediate.unref) {
6418 immediate.unref();
6419 }
6420 }, delay);
6421
6422 /* istanbul ignore next: in order to support electron renderer */
6423 if (timeout.unref) {
6424 timeout.unref();
6425 }
6426
6427 const cancel = () => {
6428 clearTimeout(timeout);
6429 clearImmediate(immediate);
6430 };
6431
6432 cancelers.push(cancel);
6433
6434 return cancel;
6435 };
6436
6437 const {host, hostname} = options;
6438 const timeoutHandler = (delay, event) => {
6439 request.emit('error', new TimeoutError$1(delay, event));
6440 request.once('error', () => {}); // Ignore the `socket hung up` error made by request.abort()
6441
6442 request.abort();
6443 };
6444
6445 const cancelers = [];
6446 const cancelTimeouts = () => {
6447 stopNewTimeouts = true;
6448 cancelers.forEach(cancelTimeout => cancelTimeout());
6449 };
6450
6451 request.once('error', cancelTimeouts);
6452 request.once('response', response => {
6453 response.once('end', cancelTimeouts);
6454 });
6455
6456 if (delays.request !== undefined) {
6457 addTimeout(delays.request, timeoutHandler, 'request');
6458 }
6459
6460 if (delays.socket !== undefined) {
6461 request.setTimeout(delays.socket, () => {
6462 timeoutHandler(delays.socket, 'socket');
6463 });
6464
6465 cancelers.push(() => request.setTimeout(0));
6466 }
6467
6468 if (delays.lookup !== undefined && !request.socketPath && !net.isIP(hostname || host)) {
6469 request.once('socket', socket => {
6470 /* istanbul ignore next: hard to test */
6471 if (socket.connecting) {
6472 const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup');
6473 socket.once('lookup', cancelTimeout);
6474 }
6475 });
6476 }
6477
6478 if (delays.connect !== undefined) {
6479 request.once('socket', socket => {
6480 /* istanbul ignore next: hard to test */
6481 if (socket.connecting) {
6482 const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect');
6483
6484 if (request.socketPath || net.isIP(hostname || host)) {
6485 socket.once('connect', timeConnect());
6486 } else {
6487 socket.once('lookup', error => {
6488 if (error === null) {
6489 socket.once('connect', timeConnect());
6490 }
6491 });
6492 }
6493 }
6494 });
6495 }
6496
6497 if (delays.secureConnect !== undefined && options.protocol === 'https:') {
6498 request.once('socket', socket => {
6499 /* istanbul ignore next: hard to test */
6500 if (socket.connecting) {
6501 socket.once('connect', () => {
6502 const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect');
6503 socket.once('secureConnect', cancelTimeout);
6504 });
6505 }
6506 });
6507 }
6508
6509 if (delays.send !== undefined) {
6510 request.once('socket', socket => {
6511 const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send');
6512 /* istanbul ignore next: hard to test */
6513 if (socket.connecting) {
6514 socket.once('connect', () => {
6515 request.once('upload-complete', timeRequest());
6516 });
6517 } else {
6518 request.once('upload-complete', timeRequest());
6519 }
6520 });
6521 }
6522
6523 if (delays.response !== undefined) {
6524 request.once('upload-complete', () => {
6525 const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response');
6526 request.once('response', cancelTimeout);
6527 });
6528 }
6529};
6530
6531var TimeoutError_1 = TimeoutError$1;
6532timedOut.TimeoutError = TimeoutError_1;
6533
6534var isFormData = body => dist.nodeStream(body) && dist.function(body.getBoundary);
6535
6536var getBodySize = async options => {
6537 const {body} = options;
6538
6539 if (options.headers['content-length']) {
6540 return Number(options.headers['content-length']);
6541 }
6542
6543 if (!body && !options.stream) {
6544 return 0;
6545 }
6546
6547 if (dist.string(body)) {
6548 return Buffer.byteLength(body);
6549 }
6550
6551 if (isFormData(body)) {
6552 return util.promisify(body.getLength.bind(body))();
6553 }
6554
6555 if (body instanceof fs.ReadStream) {
6556 const {size} = await util.promisify(fs.stat)(body.path);
6557 return size;
6558 }
6559
6560 return null;
6561};
6562
6563const PassThrough$4 = stream.PassThrough;
6564
6565
6566
6567var decompressResponse = response => {
6568 // TODO: Use Array#includes when targeting Node.js 6
6569 if (['gzip', 'deflate'].indexOf(response.headers['content-encoding']) === -1) {
6570 return response;
6571 }
6572
6573 const unzip = zlib.createUnzip();
6574 const stream$$1 = new PassThrough$4();
6575
6576 mimicResponse(response, stream$$1);
6577
6578 unzip.on('error', err => {
6579 if (err.code === 'Z_BUF_ERROR') {
6580 stream$$1.end();
6581 return;
6582 }
6583
6584 stream$$1.emit('error', err);
6585 });
6586
6587 response.pipe(unzip).pipe(stream$$1);
6588
6589 return stream$$1;
6590};
6591
6592const {Transform: Transform$3} = stream;
6593
6594var progress = {
6595 download(response, emitter, downloadBodySize) {
6596 let downloaded = 0;
6597
6598 return new Transform$3({
6599 transform(chunk, encoding, callback) {
6600 downloaded += chunk.length;
6601
6602 const percent = downloadBodySize ? downloaded / downloadBodySize : 0;
6603
6604 // Let `flush()` be responsible for emitting the last event
6605 if (percent < 1) {
6606 emitter.emit('downloadProgress', {
6607 percent,
6608 transferred: downloaded,
6609 total: downloadBodySize
6610 });
6611 }
6612
6613 callback(null, chunk);
6614 },
6615
6616 flush(callback) {
6617 emitter.emit('downloadProgress', {
6618 percent: 1,
6619 transferred: downloaded,
6620 total: downloadBodySize
6621 });
6622
6623 callback();
6624 }
6625 });
6626 },
6627
6628 upload(request, emitter, uploadBodySize) {
6629 const uploadEventFrequency = 150;
6630 let uploaded = 0;
6631 let progressInterval;
6632
6633 emitter.emit('uploadProgress', {
6634 percent: 0,
6635 transferred: 0,
6636 total: uploadBodySize
6637 });
6638
6639 request.once('error', () => {
6640 clearInterval(progressInterval);
6641 });
6642
6643 request.once('response', () => {
6644 clearInterval(progressInterval);
6645
6646 emitter.emit('uploadProgress', {
6647 percent: 1,
6648 transferred: uploaded,
6649 total: uploadBodySize
6650 });
6651 });
6652
6653 request.once('socket', socket => {
6654 const onSocketConnect = () => {
6655 progressInterval = setInterval(() => {
6656 const lastUploaded = uploaded;
6657 /* istanbul ignore next: see #490 (occurs randomly!) */
6658 const headersSize = request._header ? Buffer.byteLength(request._header) : 0;
6659 uploaded = socket.bytesWritten - headersSize;
6660
6661 // Don't emit events with unchanged progress and
6662 // prevent last event from being emitted, because
6663 // it's emitted when `response` is emitted
6664 if (uploaded === lastUploaded || uploaded === uploadBodySize) {
6665 return;
6666 }
6667
6668 emitter.emit('uploadProgress', {
6669 percent: uploadBodySize ? uploaded / uploadBodySize : 0,
6670 transferred: uploaded,
6671 total: uploadBodySize
6672 });
6673 }, uploadEventFrequency);
6674 };
6675
6676 /* istanbul ignore next: hard to test */
6677 if (socket.connecting) {
6678 socket.once('connect', onSocketConnect);
6679 } else if (socket.writable) {
6680 // The socket is being reused from pool,
6681 // so the connect event will not be emitted
6682 onSocketConnect();
6683 }
6684 });
6685 }
6686};
6687
6688var getResponse = (response, options, emitter) => {
6689 const downloadBodySize = Number(response.headers['content-length']) || null;
6690
6691 const progressStream = progress.download(response, emitter, downloadBodySize);
6692
6693 mimicResponse(response, progressStream);
6694
6695 const newResponse = options.decompress === true &&
6696 dist.function(decompressResponse) &&
6697 options.method !== 'HEAD' ? decompressResponse(progressStream) : progressStream;
6698
6699 if (!options.decompress && ['gzip', 'deflate'].includes(response.headers['content-encoding'])) {
6700 options.encoding = null;
6701 }
6702
6703 emitter.emit('response', newResponse);
6704
6705 emitter.emit('downloadProgress', {
6706 percent: 0,
6707 transferred: 0,
6708 total: downloadBodySize
6709 });
6710
6711 response.pipe(progressStream);
6712};
6713
6714var urlToOptions = url$$1 => {
6715 const options = {
6716 protocol: url$$1.protocol,
6717 hostname: url$$1.hostname.startsWith('[') ? url$$1.hostname.slice(1, -1) : url$$1.hostname,
6718 hash: url$$1.hash,
6719 search: url$$1.search,
6720 pathname: url$$1.pathname,
6721 href: url$$1.href
6722 };
6723
6724 if (dist.string(url$$1.port) && url$$1.port.length > 0) {
6725 options.port = Number(url$$1.port);
6726 }
6727
6728 if (url$$1.username || url$$1.password) {
6729 options.auth = `${url$$1.username}:${url$$1.password}`;
6730 }
6731
6732 options.path = dist.null(url$$1.search) ? url$$1.pathname : `${url$$1.pathname}${url$$1.search}`;
6733
6734 return options;
6735};
6736
6737const {URL: URL$1} = url; // TODO: Use the `URL` global when targeting Node.js 10
6738
6739
6740
6741
6742const urlLib = url;
6743
6744
6745
6746
6747
6748
6749
6750
6751const {CacheError: CacheError$1, UnsupportedProtocolError: UnsupportedProtocolError$1, MaxRedirectsError: MaxRedirectsError$1, RequestError: RequestError$1, TimeoutError: TimeoutError$2} = errors;
6752
6753
6754const getMethodRedirectCodes = new Set([300, 301, 302, 303, 304, 305, 307, 308]);
6755const allMethodRedirectCodes = new Set([300, 303, 307, 308]);
6756
6757var requestAsEventEmitter = (options, input) => {
6758 const emitter = new events();
6759 const redirects = [];
6760 let currentRequest;
6761 let requestUrl;
6762 let redirectString;
6763 let uploadBodySize;
6764 let retryCount = 0;
6765 let shouldAbort = false;
6766
6767 const setCookie = options.cookieJar ? util.promisify(options.cookieJar.setCookie.bind(options.cookieJar)) : null;
6768 const getCookieString = options.cookieJar ? util.promisify(options.cookieJar.getCookieString.bind(options.cookieJar)) : null;
6769 const agents = dist.object(options.agent) ? options.agent : null;
6770
6771 const get = async options => {
6772 const currentUrl = redirectString || requestUrl;
6773
6774 if (options.protocol !== 'http:' && options.protocol !== 'https:') {
6775 throw new UnsupportedProtocolError$1(options);
6776 }
6777
6778 let fn;
6779 if (dist.function(options.request)) {
6780 fn = {request: options.request};
6781 } else {
6782 fn = options.protocol === 'https:' ? https : http;
6783 }
6784
6785 if (agents) {
6786 const protocolName = options.protocol === 'https:' ? 'https' : 'http';
6787 options.agent = agents[protocolName] || options.agent;
6788 }
6789
6790 /* istanbul ignore next: electron.net is broken */
6791 if (options.useElectronNet && process.versions.electron) {
6792 const r = ({x: commonjsRequire})['yx'.slice(1)]; // Trick webpack
6793 const electron = r('electron');
6794 fn = electron.net || electron.remote.net;
6795 }
6796
6797 if (options.cookieJar) {
6798 const cookieString = await getCookieString(currentUrl, {});
6799
6800 if (dist.nonEmptyString(cookieString)) {
6801 options.headers.cookie = cookieString;
6802 }
6803 }
6804
6805 let timings;
6806 const handleResponse = async response => {
6807 try {
6808 /* istanbul ignore next: fixes https://github.com/electron/electron/blob/cbb460d47628a7a146adf4419ed48550a98b2923/lib/browser/api/net.js#L59-L65 */
6809 if (options.useElectronNet) {
6810 response = new Proxy(response, {
6811 get: (target, name) => {
6812 if (name === 'trailers' || name === 'rawTrailers') {
6813 return [];
6814 }
6815
6816 const value = target[name];
6817 return dist.function(value) ? value.bind(target) : value;
6818 }
6819 });
6820 }
6821
6822 const {statusCode} = response;
6823 response.url = currentUrl;
6824 response.requestUrl = requestUrl;
6825 response.retryCount = retryCount;
6826 response.timings = timings;
6827 response.redirectUrls = redirects;
6828 response.request = {
6829 gotOptions: options
6830 };
6831
6832 const rawCookies = response.headers['set-cookie'];
6833 if (options.cookieJar && rawCookies) {
6834 await Promise.all(rawCookies.map(rawCookie => setCookie(rawCookie, response.url)));
6835 }
6836
6837 if (options.followRedirect && 'location' in response.headers) {
6838 if (allMethodRedirectCodes.has(statusCode) || (getMethodRedirectCodes.has(statusCode) && (options.method === 'GET' || options.method === 'HEAD'))) {
6839 response.resume(); // We're being redirected, we don't care about the response.
6840
6841 if (statusCode === 303) {
6842 // Server responded with "see other", indicating that the resource exists at another location,
6843 // and the client should request it from that location via GET or HEAD.
6844 options.method = 'GET';
6845 }
6846
6847 if (redirects.length >= 10) {
6848 throw new MaxRedirectsError$1(statusCode, redirects, options);
6849 }
6850
6851 // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604
6852 const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
6853 const redirectURL = new URL$1(redirectBuffer, currentUrl);
6854 redirectString = redirectURL.toString();
6855
6856 redirects.push(redirectString);
6857
6858 const redirectOptions = {
6859 ...options,
6860 ...urlToOptions(redirectURL)
6861 };
6862
6863 for (const hook of options.hooks.beforeRedirect) {
6864 // eslint-disable-next-line no-await-in-loop
6865 await hook(redirectOptions);
6866 }
6867
6868 emitter.emit('redirect', response, redirectOptions);
6869
6870 await get(redirectOptions);
6871 return;
6872 }
6873 }
6874
6875 getResponse(response, options, emitter);
6876 } catch (error) {
6877 emitter.emit('error', error);
6878 }
6879 };
6880
6881 const handleRequest = request => {
6882 if (shouldAbort) {
6883 request.once('error', () => {});
6884 request.abort();
6885 return;
6886 }
6887
6888 currentRequest = request;
6889
6890 request.once('error', error => {
6891 if (request.aborted) {
6892 return;
6893 }
6894
6895 if (error instanceof timedOut.TimeoutError) {
6896 error = new TimeoutError$2(error, options);
6897 } else {
6898 error = new RequestError$1(error, options);
6899 }
6900
6901 if (emitter.retry(error) === false) {
6902 emitter.emit('error', error);
6903 }
6904 });
6905
6906 timings = source(request);
6907
6908 progress.upload(request, emitter, uploadBodySize);
6909
6910 if (options.gotTimeout) {
6911 timedOut(request, options.gotTimeout, options);
6912 }
6913
6914 emitter.emit('request', request);
6915
6916 const uploadComplete = () => {
6917 request.emit('upload-complete');
6918 };
6919
6920 try {
6921 if (dist.nodeStream(options.body)) {
6922 options.body.once('end', uploadComplete);
6923 options.body.pipe(request);
6924 options.body = undefined;
6925 } else if (options.body) {
6926 request.end(options.body, uploadComplete);
6927 } else if (input && (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH')) {
6928 input.once('end', uploadComplete);
6929 input.pipe(request);
6930 } else {
6931 request.end(uploadComplete);
6932 }
6933 } catch (error) {
6934 emitter.emit('error', new RequestError$1(error, options));
6935 }
6936 };
6937
6938 if (options.cache) {
6939 const cacheableRequest = new src$3(fn.request, options.cache);
6940 const cacheRequest = cacheableRequest(options, handleResponse);
6941
6942 cacheRequest.once('error', error => {
6943 if (error instanceof src$3.RequestError) {
6944 emitter.emit('error', new RequestError$1(error, options));
6945 } else {
6946 emitter.emit('error', new CacheError$1(error, options));
6947 }
6948 });
6949
6950 cacheRequest.once('request', handleRequest);
6951 } else {
6952 // Catches errors thrown by calling fn.request(...)
6953 try {
6954 handleRequest(fn.request(options, handleResponse));
6955 } catch (error) {
6956 emitter.emit('error', new RequestError$1(error, options));
6957 }
6958 }
6959 };
6960
6961 emitter.retry = error => {
6962 let backoff;
6963
6964 try {
6965 backoff = options.retry.retries(++retryCount, error);
6966 } catch (error2) {
6967 emitter.emit('error', error2);
6968 return;
6969 }
6970
6971 if (backoff) {
6972 const retry = async options => {
6973 try {
6974 for (const hook of options.hooks.beforeRetry) {
6975 // eslint-disable-next-line no-await-in-loop
6976 await hook(options, error, retryCount);
6977 }
6978
6979 await get(options);
6980 } catch (error) {
6981 emitter.emit('error', error);
6982 }
6983 };
6984
6985 setTimeout(retry, backoff, {...options, forceRefresh: true});
6986 return true;
6987 }
6988
6989 return false;
6990 };
6991
6992 emitter.abort = () => {
6993 if (currentRequest) {
6994 currentRequest.once('error', () => {});
6995 currentRequest.abort();
6996 } else {
6997 shouldAbort = true;
6998 }
6999 };
7000
7001 setImmediate(async () => {
7002 try {
7003 // Convert buffer to stream to receive upload progress events (#322)
7004 const {body} = options;
7005 if (dist.buffer(body)) {
7006 options.body = toReadableStream(body);
7007 uploadBodySize = body.length;
7008 } else {
7009 uploadBodySize = await getBodySize(options);
7010 }
7011
7012 if (dist.undefined(options.headers['content-length']) && dist.undefined(options.headers['transfer-encoding'])) {
7013 if ((uploadBodySize > 0 || options.method === 'PUT') && !dist.null(uploadBodySize)) {
7014 options.headers['content-length'] = uploadBodySize;
7015 }
7016 }
7017
7018 for (const hook of options.hooks.beforeRequest) {
7019 // eslint-disable-next-line no-await-in-loop
7020 await hook(options);
7021 }
7022
7023 requestUrl = options.href || (new URL$1(options.path, urlLib.format(options))).toString();
7024
7025 await get(options);
7026 } catch (error) {
7027 emitter.emit('error', error);
7028 }
7029 });
7030
7031 return emitter;
7032};
7033
7034const {PassThrough: PassThrough$5} = stream;
7035
7036
7037const {HTTPError: HTTPError$1, ReadError: ReadError$1} = errors;
7038
7039var asStream = options => {
7040 const input = new PassThrough$5();
7041 const output = new PassThrough$5();
7042 const proxy = duplexer3(input, output);
7043 const piped = new Set();
7044 let isFinished = false;
7045
7046 options.retry.retries = () => 0;
7047
7048 if (options.body) {
7049 proxy.write = () => {
7050 throw new Error('Got\'s stream is not writable when the `body` option is used');
7051 };
7052 }
7053
7054 const emitter = requestAsEventEmitter(options, input);
7055
7056 // Cancels the request
7057 proxy._destroy = emitter.abort;
7058
7059 emitter.on('response', response => {
7060 const {statusCode} = response;
7061
7062 response.on('error', error => {
7063 proxy.emit('error', new ReadError$1(error, options));
7064 });
7065
7066 if (options.throwHttpErrors && statusCode !== 304 && (statusCode < 200 || statusCode > 299)) {
7067 proxy.emit('error', new HTTPError$1(response, options), null, response);
7068 return;
7069 }
7070
7071 isFinished = true;
7072
7073 response.pipe(output);
7074
7075 for (const destination of piped) {
7076 if (destination.headersSent) {
7077 continue;
7078 }
7079
7080 for (const [key, value] of Object.entries(response.headers)) {
7081 // Got gives *decompressed* data. Overriding `content-encoding` header would result in an error.
7082 // It's not possible to decompress already decompressed data, is it?
7083 const allowed = options.decompress ? key !== 'content-encoding' : true;
7084 if (allowed) {
7085 destination.setHeader(key, value);
7086 }
7087 }
7088
7089 destination.statusCode = response.statusCode;
7090 }
7091
7092 proxy.emit('response', response);
7093 });
7094
7095 [
7096 'error',
7097 'request',
7098 'redirect',
7099 'uploadProgress',
7100 'downloadProgress'
7101 ].forEach(event => emitter.on(event, (...args) => proxy.emit(event, ...args)));
7102
7103 const pipe = proxy.pipe.bind(proxy);
7104 const unpipe = proxy.unpipe.bind(proxy);
7105 proxy.pipe = (destination, options) => {
7106 if (isFinished) {
7107 throw new Error('Failed to pipe. The response has been emitted already.');
7108 }
7109
7110 const result = pipe(destination, options);
7111
7112 if (Reflect.has(destination, 'setHeader')) {
7113 piped.add(destination);
7114 }
7115
7116 return result;
7117 };
7118 proxy.unpipe = stream$$1 => {
7119 piped.delete(stream$$1);
7120 return unpipe(stream$$1);
7121 };
7122
7123 return proxy;
7124};
7125
7126var knownHookEvents = [
7127 'beforeRequest',
7128 'beforeRedirect',
7129 'beforeRetry',
7130 'afterResponse'
7131];
7132
7133const {URL: URL$2} = url;
7134
7135
7136
7137const merge = (target, ...sources) => {
7138 for (const source of sources) {
7139 for (const [key, sourceValue] of Object.entries(source)) {
7140 if (dist.undefined(sourceValue)) {
7141 continue;
7142 }
7143
7144 const targetValue = target[key];
7145 if (dist.urlInstance(targetValue) && (dist.urlInstance(sourceValue) || dist.string(sourceValue))) {
7146 target[key] = new URL$2(sourceValue, targetValue);
7147 } else if (dist.plainObject(sourceValue)) {
7148 if (dist.plainObject(targetValue)) {
7149 target[key] = merge({}, targetValue, sourceValue);
7150 } else {
7151 target[key] = merge({}, sourceValue);
7152 }
7153 } else if (dist.array(sourceValue)) {
7154 target[key] = merge([], sourceValue);
7155 } else {
7156 target[key] = sourceValue;
7157 }
7158 }
7159 }
7160
7161 return target;
7162};
7163
7164const mergeOptions = (...sources) => {
7165 sources = sources.map(source => source || {});
7166 const merged = merge({}, ...sources);
7167
7168 const hooks = {};
7169 for (const hook of knownHookEvents) {
7170 hooks[hook] = [];
7171 }
7172
7173 for (const source of sources) {
7174 if (source.hooks) {
7175 for (const hook of knownHookEvents) {
7176 hooks[hook] = hooks[hook].concat(source.hooks[hook]);
7177 }
7178 }
7179 }
7180
7181 merged.hooks = hooks;
7182
7183 return merged;
7184};
7185
7186const mergeInstances = (instances, methods) => {
7187 const handlers = instances.map(instance => instance.defaults.handler);
7188 const size = instances.length - 1;
7189
7190 return {
7191 methods,
7192 options: mergeOptions(...instances.map(instance => instance.defaults.options)),
7193 handler: (options, next) => {
7194 let iteration = -1;
7195 const iterate = options => handlers[++iteration](options, iteration === size ? next : iterate);
7196
7197 return iterate(options);
7198 }
7199 };
7200};
7201
7202var merge_1 = merge;
7203var options = mergeOptions;
7204var instances = mergeInstances;
7205merge_1.options = options;
7206merge_1.instances = instances;
7207
7208var prependHttp = (url$$1, opts) => {
7209 if (typeof url$$1 !== 'string') {
7210 throw new TypeError(`Expected \`url\` to be of type \`string\`, got \`${typeof url$$1}\``);
7211 }
7212
7213 url$$1 = url$$1.trim();
7214 opts = Object.assign({https: false}, opts);
7215
7216 if (/^\.*\/|^(?!localhost)\w+:/.test(url$$1)) {
7217 return url$$1;
7218 }
7219
7220 return url$$1.replace(/^(?!(?:\w+:)?\/\/)/, opts.https ? 'https://' : 'http://');
7221};
7222
7223var urlParseLax = (input, options) => {
7224 if (typeof input !== 'string') {
7225 throw new TypeError(`Expected \`url\` to be of type \`string\`, got \`${typeof input}\` instead.`);
7226 }
7227
7228 const finalUrl = prependHttp(input, Object.assign({https: true}, options));
7229 return url.parse(finalUrl);
7230};
7231
7232const {URL: URL$3, URLSearchParams} = url; // TODO: Use the `URL` global when targeting Node.js 10
7233const urlLib$1 = url;
7234
7235
7236
7237
7238
7239
7240
7241
7242const retryAfterStatusCodes = new Set([413, 429, 503]);
7243
7244// `preNormalize` handles static things (lowercasing headers; normalizing baseUrl, timeout, retry)
7245// While `normalize` does `preNormalize` + handles things which need to be reworked when user changes them
7246const preNormalize = (options, defaults) => {
7247 if (dist.nullOrUndefined(options.headers)) {
7248 options.headers = {};
7249 } else {
7250 options.headers = lowercaseKeys(options.headers);
7251 }
7252
7253 if (options.baseUrl && !options.baseUrl.toString().endsWith('/')) {
7254 options.baseUrl += '/';
7255 }
7256
7257 if (options.stream) {
7258 options.json = false;
7259 }
7260
7261 if (dist.nullOrUndefined(options.hooks)) {
7262 options.hooks = {};
7263 } else if (!dist.object(options.hooks)) {
7264 throw new TypeError(`Parameter \`hooks\` must be an object, not ${dist(options.hooks)}`);
7265 }
7266
7267 for (const event of knownHookEvents) {
7268 if (dist.nullOrUndefined(options.hooks[event])) {
7269 if (defaults) {
7270 options.hooks[event] = [...defaults.hooks[event]];
7271 } else {
7272 options.hooks[event] = [];
7273 }
7274 }
7275 }
7276
7277 if (dist.number(options.timeout)) {
7278 options.gotTimeout = {request: options.timeout};
7279 } else if (dist.object(options.timeout)) {
7280 options.gotTimeout = options.timeout;
7281 }
7282 delete options.timeout;
7283
7284 const {retry} = options;
7285 options.retry = {
7286 retries: 0,
7287 methods: [],
7288 statusCodes: [],
7289 errorCodes: []
7290 };
7291
7292 if (dist.nonEmptyObject(defaults) && retry !== false) {
7293 options.retry = {...defaults.retry};
7294 }
7295
7296 if (retry !== false) {
7297 if (dist.number(retry)) {
7298 options.retry.retries = retry;
7299 } else {
7300 options.retry = {...options.retry, ...retry};
7301 }
7302 }
7303
7304 if (options.gotTimeout) {
7305 options.retry.maxRetryAfter = Math.min(...[options.gotTimeout.request, options.gotTimeout.connection].filter(n => !dist.nullOrUndefined(n)));
7306 }
7307
7308 if (dist.array(options.retry.methods)) {
7309 options.retry.methods = new Set(options.retry.methods.map(method => method.toUpperCase()));
7310 }
7311
7312 if (dist.array(options.retry.statusCodes)) {
7313 options.retry.statusCodes = new Set(options.retry.statusCodes);
7314 }
7315
7316 if (dist.array(options.retry.errorCodes)) {
7317 options.retry.errorCodes = new Set(options.retry.errorCodes);
7318 }
7319
7320 return options;
7321};
7322
7323const normalize = (url$$1, options, defaults) => {
7324 if (dist.plainObject(url$$1)) {
7325 options = {...url$$1, ...options};
7326 url$$1 = options.url || {};
7327 delete options.url;
7328 }
7329
7330 if (defaults) {
7331 options = merge_1({}, defaults.options, options ? preNormalize(options, defaults.options) : {});
7332 } else {
7333 options = merge_1({}, preNormalize(options));
7334 }
7335
7336 if (!dist.string(url$$1) && !dist.object(url$$1)) {
7337 throw new TypeError(`Parameter \`url\` must be a string or object, not ${dist(url$$1)}`);
7338 }
7339
7340 if (dist.string(url$$1)) {
7341 if (options.baseUrl) {
7342 if (url$$1.toString().startsWith('/')) {
7343 url$$1 = url$$1.toString().slice(1);
7344 }
7345
7346 url$$1 = urlToOptions(new URL$3(url$$1, options.baseUrl));
7347 } else {
7348 url$$1 = url$$1.replace(/^unix:/, 'http://$&');
7349 url$$1 = urlParseLax(url$$1);
7350 }
7351 } else if (dist(url$$1) === 'URL') {
7352 url$$1 = urlToOptions(url$$1);
7353 }
7354
7355 // Override both null/undefined with default protocol
7356 options = merge_1({path: ''}, url$$1, {protocol: url$$1.protocol || 'https:'}, options);
7357
7358 const {baseUrl} = options;
7359 Object.defineProperty(options, 'baseUrl', {
7360 set: () => {
7361 throw new Error('Failed to set baseUrl. Options are normalized already.');
7362 },
7363 get: () => baseUrl
7364 });
7365
7366 const {query} = options;
7367 if (dist.nonEmptyString(query) || dist.nonEmptyObject(query) || query instanceof URLSearchParams) {
7368 if (!dist.string(query)) {
7369 options.query = (new URLSearchParams(query)).toString();
7370 }
7371 options.path = `${options.path.split('?')[0]}?${options.query}`;
7372 delete options.query;
7373 }
7374
7375 if (options.hostname === 'unix') {
7376 const matches = /(.+?):(.+)/.exec(options.path);
7377
7378 if (matches) {
7379 const [, socketPath, path$$1] = matches;
7380 options = {
7381 ...options,
7382 socketPath,
7383 path: path$$1,
7384 host: null
7385 };
7386 }
7387 }
7388
7389 const {headers} = options;
7390 for (const [key, value] of Object.entries(headers)) {
7391 if (dist.nullOrUndefined(value)) {
7392 delete headers[key];
7393 }
7394 }
7395
7396 if (options.json && dist.undefined(headers.accept)) {
7397 headers.accept = 'application/json';
7398 }
7399
7400 if (options.decompress && dist.undefined(headers['accept-encoding'])) {
7401 headers['accept-encoding'] = 'gzip, deflate';
7402 }
7403
7404 const {body} = options;
7405 if (dist.nullOrUndefined(body)) {
7406 options.method = options.method ? options.method.toUpperCase() : 'GET';
7407 } else {
7408 const isObject = dist.object(body) && !dist.buffer(body) && !dist.nodeStream(body);
7409 if (!dist.nodeStream(body) && !dist.string(body) && !dist.buffer(body) && !(options.form || options.json)) {
7410 throw new TypeError('The `body` option must be a stream.Readable, string or Buffer');
7411 }
7412
7413 if (options.json && !(isObject || dist.array(body))) {
7414 throw new TypeError('The `body` option must be an Object or Array when the `json` option is used');
7415 }
7416
7417 if (options.form && !isObject) {
7418 throw new TypeError('The `body` option must be an Object when the `form` option is used');
7419 }
7420
7421 if (isFormData(body)) {
7422 // Special case for https://github.com/form-data/form-data
7423 headers['content-type'] = headers['content-type'] || `multipart/form-data; boundary=${body.getBoundary()}`;
7424 } else if (options.form) {
7425 headers['content-type'] = headers['content-type'] || 'application/x-www-form-urlencoded';
7426 options.body = (new URLSearchParams(body)).toString();
7427 } else if (options.json) {
7428 headers['content-type'] = headers['content-type'] || 'application/json';
7429 options.body = JSON.stringify(body);
7430 }
7431
7432 options.method = options.method ? options.method.toUpperCase() : 'POST';
7433 }
7434
7435 if (!dist.function(options.retry.retries)) {
7436 const {retries} = options.retry;
7437
7438 options.retry.retries = (iteration, error) => {
7439 if (iteration > retries) {
7440 return 0;
7441 }
7442
7443 if ((!error || !options.retry.errorCodes.has(error.code)) && (!options.retry.methods.has(error.method) || !options.retry.statusCodes.has(error.statusCode))) {
7444 return 0;
7445 }
7446
7447 if (Reflect.has(error, 'headers') && Reflect.has(error.headers, 'retry-after') && retryAfterStatusCodes.has(error.statusCode)) {
7448 let after = Number(error.headers['retry-after']);
7449 if (dist.nan(after)) {
7450 after = Date.parse(error.headers['retry-after']) - Date.now();
7451 } else {
7452 after *= 1000;
7453 }
7454
7455 if (after > options.retry.maxRetryAfter) {
7456 return 0;
7457 }
7458
7459 return after;
7460 }
7461
7462 if (error.statusCode === 413) {
7463 return 0;
7464 }
7465
7466 const noise = Math.random() * 100;
7467 return ((2 ** (iteration - 1)) * 1000) + noise;
7468 };
7469 }
7470
7471 return options;
7472};
7473
7474const reNormalize = options => normalize(urlLib$1.format(options), options);
7475
7476var normalizeArguments = normalize;
7477var preNormalize_1 = preNormalize;
7478var reNormalize_1 = reNormalize;
7479normalizeArguments.preNormalize = preNormalize_1;
7480normalizeArguments.reNormalize = reNormalize_1;
7481
7482const {HTTPError: HTTPError$2, ParseError: ParseError$1, ReadError: ReadError$2} = errors;
7483const {options: mergeOptions$1} = merge_1;
7484const {reNormalize: reNormalize$1} = normalizeArguments;
7485
7486const asPromise = options => {
7487 const proxy = new events();
7488
7489 const promise = new pCancelable((resolve, reject, onCancel) => {
7490 const emitter = requestAsEventEmitter(options);
7491
7492 onCancel(emitter.abort);
7493
7494 emitter.on('response', async response => {
7495 proxy.emit('response', response);
7496
7497 const stream$$1 = dist.null(options.encoding) ? getStream_1.buffer(response) : getStream_1(response, options);
7498
7499 let data;
7500 try {
7501 data = await stream$$1;
7502 } catch (error) {
7503 reject(new ReadError$2(error, options));
7504 return;
7505 }
7506
7507 const limitStatusCode = options.followRedirect ? 299 : 399;
7508
7509 response.body = data;
7510
7511 try {
7512 for (const [index, hook] of Object.entries(options.hooks.afterResponse)) {
7513 // eslint-disable-next-line no-await-in-loop
7514 response = await hook(response, updatedOptions => {
7515 updatedOptions = reNormalize$1(mergeOptions$1(options, {
7516 ...updatedOptions,
7517 retry: 0,
7518 throwHttpErrors: false
7519 }));
7520
7521 // Remove any further hooks for that request, because we we'll call them anyway.
7522 // The loop continues. We don't want duplicates (asPromise recursion).
7523 updatedOptions.hooks.afterResponse = options.hooks.afterResponse.slice(0, index);
7524
7525 return asPromise(updatedOptions);
7526 });
7527 }
7528 } catch (error) {
7529 reject(error);
7530 return;
7531 }
7532
7533 const {statusCode} = response;
7534
7535 if (options.json && response.body) {
7536 try {
7537 response.body = JSON.parse(response.body);
7538 } catch (error) {
7539 if (statusCode >= 200 && statusCode < 300) {
7540 const parseError = new ParseError$1(error, statusCode, options, data);
7541 Object.defineProperty(parseError, 'response', {value: response});
7542 reject(parseError);
7543 return;
7544 }
7545 }
7546 }
7547
7548 if (statusCode !== 304 && (statusCode < 200 || statusCode > limitStatusCode)) {
7549 const error = new HTTPError$2(response, options);
7550 Object.defineProperty(error, 'response', {value: response});
7551 if (emitter.retry(error) === false) {
7552 if (options.throwHttpErrors) {
7553 reject(error);
7554 return;
7555 }
7556
7557 resolve(response);
7558 }
7559 return;
7560 }
7561
7562 resolve(response);
7563 });
7564
7565 emitter.once('error', reject);
7566 [
7567 'request',
7568 'redirect',
7569 'uploadProgress',
7570 'downloadProgress'
7571 ].forEach(event => emitter.on(event, (...args) => proxy.emit(event, ...args)));
7572 });
7573
7574 promise.on = (name, fn) => {
7575 proxy.on(name, fn);
7576 return promise;
7577 };
7578
7579 return promise;
7580};
7581
7582var asPromise_1 = asPromise;
7583
7584var deepFreeze = function deepFreeze(object) {
7585 for (const [key, value] of Object.entries(object)) {
7586 if (dist.plainObject(value) || dist.array(value)) {
7587 deepFreeze(object[key]);
7588 }
7589 }
7590
7591 return Object.freeze(object);
7592};
7593
7594const getPromiseOrStream = options => options.stream ? asStream(options) : asPromise_1(options);
7595
7596const aliases = [
7597 'get',
7598 'post',
7599 'put',
7600 'patch',
7601 'head',
7602 'delete'
7603];
7604
7605const create = defaults => {
7606 defaults = merge_1({}, defaults);
7607 normalizeArguments.preNormalize(defaults.options);
7608
7609 if (!defaults.handler) {
7610 // This can't be getPromiseOrStream, because when merging
7611 // the chain would stop at this point and no further handlers would be called.
7612 defaults.handler = (options, next) => next(options);
7613 }
7614
7615 function got(url$$1, options) {
7616 try {
7617 return defaults.handler(normalizeArguments(url$$1, options, defaults), getPromiseOrStream);
7618 } catch (error) {
7619 if (options && options.stream) {
7620 throw error;
7621 } else {
7622 return Promise.reject(error);
7623 }
7624 }
7625 }
7626
7627 got.create = create;
7628 got.extend = options => {
7629 let mutableDefaults;
7630 if (options && Reflect.has(options, 'mutableDefaults')) {
7631 mutableDefaults = options.mutableDefaults;
7632 delete options.mutableDefaults;
7633 } else {
7634 mutableDefaults = defaults.mutableDefaults;
7635 }
7636
7637 return create({
7638 options: merge_1.options(defaults.options, options),
7639 handler: defaults.handler,
7640 mutableDefaults
7641 });
7642 };
7643
7644 got.mergeInstances = (...args) => create(merge_1.instances(args));
7645
7646 got.stream = (url$$1, options) => got(url$$1, {...options, stream: true});
7647
7648 for (const method of aliases) {
7649 got[method] = (url$$1, options) => got(url$$1, {...options, method});
7650 got.stream[method] = (url$$1, options) => got.stream(url$$1, {...options, method});
7651 }
7652
7653 Object.assign(got, {...errors, mergeOptions: merge_1.options});
7654 Object.defineProperty(got, 'defaults', {
7655 value: defaults.mutableDefaults ? defaults : deepFreeze(defaults),
7656 writable: defaults.mutableDefaults,
7657 configurable: defaults.mutableDefaults,
7658 enumerable: true
7659 });
7660
7661 return got;
7662};
7663
7664var create_1 = create;
7665
7666var pkg = getCjsExportFromNamespace(_package$3);
7667
7668const defaults$1 = {
7669 options: {
7670 retry: {
7671 retries: 2,
7672 methods: [
7673 'GET',
7674 'PUT',
7675 'HEAD',
7676 'DELETE',
7677 'OPTIONS',
7678 'TRACE'
7679 ],
7680 statusCodes: [
7681 408,
7682 413,
7683 429,
7684 500,
7685 502,
7686 503,
7687 504
7688 ],
7689 errorCodes: [
7690 'ETIMEDOUT',
7691 'ECONNRESET',
7692 'EADDRINUSE',
7693 'ECONNREFUSED',
7694 'EPIPE',
7695 'ENOTFOUND',
7696 'ENETUNREACH',
7697 'EAI_AGAIN'
7698 ]
7699 },
7700 headers: {
7701 'user-agent': `${pkg.name}/${pkg.version} (https://github.com/sindresorhus/got)`
7702 },
7703 hooks: {
7704 beforeRequest: [],
7705 beforeRedirect: [],
7706 beforeRetry: [],
7707 afterResponse: []
7708 },
7709 decompress: true,
7710 throwHttpErrors: true,
7711 followRedirect: true,
7712 stream: false,
7713 form: false,
7714 json: false,
7715 cache: false,
7716 useElectronNet: false
7717 },
7718 mutableDefaults: false
7719};
7720
7721const got = create_1(defaults$1);
7722
7723var source$1 = got;
7724
7725var ghGot = createCommonjsModule(function (module) {
7726
7727
7728const getRateLimit = ({headers}) => ({
7729 limit: parseInt(headers['x-ratelimit-limit'], 10),
7730 remaining: parseInt(headers['x-ratelimit-remaining'], 10),
7731 reset: new Date(parseInt(headers['x-ratelimit-reset'], 10) * 1000)
7732});
7733
7734const create = () => source$1.create({
7735 options: source$1.mergeOptions(source$1.defaults.options, {
7736 json: true,
7737 token: process.env.GITHUB_TOKEN,
7738 baseUrl: process.env.GITHUB_ENDPOINT || 'https://api.github.com',
7739 headers: {
7740 accept: 'application/vnd.github.v3+json',
7741 'user-agent': 'https://github.com/sindresorhus/gh-got'
7742 }
7743 }),
7744
7745 methods: source$1.defaults.methods,
7746
7747 handler: (options, next) => {
7748 if (options.token) {
7749 options.headers.authorization = options.headers.authorization || `token ${options.token}`;
7750 }
7751
7752 if (options.stream) {
7753 return next(options);
7754 }
7755
7756 // TODO: Use async/await here when Got supports the `handler` being an async function
7757 return next(options)
7758 .then(response => { // eslint-disable-line promise/prefer-await-to-then
7759 response.rateLimit = getRateLimit(response);
7760 return response;
7761 })
7762 .catch(error => {
7763 const {response} = error;
7764
7765 if (response && response.body) {
7766 error.name = 'GitHubError';
7767 error.message = `${response.body.message} (${error.statusCode})`;
7768 }
7769
7770 if (response) {
7771 error.rateLimit = getRateLimit(response);
7772 }
7773
7774 throw error;
7775 });
7776 }
7777});
7778
7779module.exports = create();
7780
7781if (process.env.NODE_ENV === 'test') {
7782 module.exports.recreate = create;
7783}
7784});
7785var ghGot_1 = ghGot.recreate;
7786
7787var pkg$1 = getCjsExportFromNamespace(_package$1);
7788
7789const { promisify } = util;
7790const { extname } = path;
7791const debug = node('http');
7792
7793
7794
7795
7796const platform = os.platform();
7797
7798
7799
7800const ua = `${pkg$1.name}/${pkg$1.version}`;
7801const client = ghGot.extend({
7802 headers: { 'user-agent': ua }
7803});
7804
7805const castArray = arg => Array.isArray(arg) ? arg : [arg];
7806const isHttpError = err => err instanceof client.HTTPError;
7807const loadZip = promisify(yauzl.fromBuffer);
7808
7809class InstallationError extends Error {}
7810
7811var getDeno = {
7812 download,
7813 fetchRelease,
7814 listReleases,
7815 InstallationError
7816};
7817
7818async function download(version = 'latest', os$$1 = platform) {
7819 const release = await fetchRelease(version);
7820 debug('found release: %j', release);
7821 debug('available artifacts: %j', Array.from(release.files.keys()));
7822 const filename = pkg$1.config.artifacts[os$$1];
7823 if (!filename || !release.files.has(filename)) {
7824 throw new InstallationError(`Unsupported platform: ${platform}`);
7825 }
7826 const type = extname(filename).replace(/^\./, '');
7827 const { size, downloadUrl: url$$1 } = release.files.get(filename);
7828 debug('downloading binary from: url=%s [type=%s, size=%i]', url$$1, type, size);
7829 let unarchiver;
7830 if (type === 'gz') unarchiver = zlib.createGunzip();
7831 else if (type === 'zip') unarchiver = createUnzip();
7832 else throw new InstallationError(`Unsupported file type: ${filename}`);
7833 let downloadedSize = 0;
7834 const downloadStream = client.stream(url$$1, { token: null });
7835 const outputStream = mississippi.pipe(downloadStream, unarchiver);
7836 downloadStream.on('data', buf => {
7837 downloadedSize += Buffer.byteLength(buf);
7838 outputStream.emit('download:progress', downloadedSize / size, downloadedSize, size);
7839 });
7840 const metadata = { filename, size, url: url$$1, version: release.tag };
7841 return Object.assign(outputStream, { metadata });
7842}
7843
7844async function fetchRelease(version = 'latest') {
7845 debug('fetch single release: %s', version);
7846 try {
7847 const [release] = await listReleases(version);
7848 return release;
7849 } catch (reason) {
7850 if (!isHttpError(reason) || reason.statusCode !== 404) throw reason;
7851 const err = new InstallationError(`Release not found: ${version}`);
7852 err.reason = reason;
7853 throw err;
7854 }
7855}
7856
7857async function listReleases(version) {
7858 const releases = [];
7859 let url$$1 = `/repos/${pkg$1.config.repo}/releases`;
7860 if (version === 'latest') url$$1 += '/latest';
7861 else if (version) url$$1 += `/tags/${version}`;
7862 let finished = false;
7863 await pDoWhilst(async () => {
7864 debug('fetch releases: url=%s', url$$1);
7865 const resp = await client.get(url$$1);
7866 const link = githubParseLink(resp.headers.link);
7867 debug('`Link` header: %j', link);
7868 if (link.next) url$$1 = link.next;
7869 else finished = true;
7870 releases.push(...castArray(resp.body).map(it => processRelease(it)));
7871 }, () => !finished);
7872 return releases;
7873}
7874
7875function processRelease(release) {
7876 const files = new Map(release.assets.map(it => [
7877 it.name, {
7878 filename: it.name,
7879 size: it.size,
7880 downloadUrl: it.browser_download_url,
7881 ...getTimestamps(it)
7882 }
7883 ]));
7884 return {
7885 tag: release.tag_name,
7886 url: release.html_url,
7887 prerelase: release.prerelase,
7888 ...getTimestamps(release),
7889 files
7890 };
7891}
7892
7893function getTimestamps({ created_at: createdAt, published_at: publishedAt }) {
7894 return { createdAt, publishedAt };
7895}
7896
7897function createUnzip() {
7898 const debug = node('unzip');
7899 const writer = mississippi.through();
7900 const reader = mississippi.concat(async buf => {
7901 try {
7902 const zipfile = await loadZip(buf, { lazyEntries: true });
7903 const openReadStream = promisify(zipfile.openReadStream.bind(zipfile));
7904 zipfile.on('error', err => writer.emit('error', err));
7905 zipfile.on('entry', async entry => {
7906 debug('entry found: %s', entry.fileName);
7907 try {
7908 const stream$$1 = await openReadStream(entry);
7909 mississippi.pipe(stream$$1, writer);
7910 } catch (err) {
7911 writer.emit('error', err);
7912 }
7913 });
7914 zipfile.readEntry();
7915 } catch (err) {
7916 writer.emit('error', err);
7917 }
7918 });
7919 return mississippi.duplex(reader, writer);
7920}
7921
7922const callbacks = new Set();
7923let called = false;
7924
7925function exit(exit, signal) {
7926 if (called) {
7927 return;
7928 }
7929
7930 called = true;
7931
7932 for (const callback of callbacks) {
7933 callback();
7934 }
7935
7936 if (exit === true) {
7937 process.exit(128 + signal); // eslint-disable-line unicorn/no-process-exit
7938 }
7939}
7940
7941var exitHook = callback => {
7942 callbacks.add(callback);
7943
7944 if (callbacks.size === 1) {
7945 process.once('exit', exit);
7946 process.once('SIGINT', exit.bind(null, true, 2));
7947 process.once('SIGTERM', exit.bind(null, true, 15));
7948
7949 // PM2 Cluster shutdown message. Caught to support async handlers with pm2, needed because
7950 // explicitly calling process.exit() doesn't trigger the beforeExit event, and the exit
7951 // event cannot support async handlers, since the event loop is never called after it.
7952 process.on('message', message => {
7953 if (message === 'shutdown') {
7954 exit(true, -128);
7955 }
7956 });
7957 }
7958};
7959
7960// These tables borrowed from `ansi`
7961
7962var prefix = '\x1b[';
7963
7964var up = function up (num) {
7965 return prefix + (num || '') + 'A'
7966};
7967
7968var down = function down (num) {
7969 return prefix + (num || '') + 'B'
7970};
7971
7972var forward = function forward (num) {
7973 return prefix + (num || '') + 'C'
7974};
7975
7976var back = function back (num) {
7977 return prefix + (num || '') + 'D'
7978};
7979
7980var nextLine = function nextLine (num) {
7981 return prefix + (num || '') + 'E'
7982};
7983
7984var previousLine = function previousLine (num) {
7985 return prefix + (num || '') + 'F'
7986};
7987
7988var horizontalAbsolute = function horizontalAbsolute (num) {
7989 if (num == null) throw new Error('horizontalAboslute requires a column to position to')
7990 return prefix + num + 'G'
7991};
7992
7993var eraseData = function eraseData () {
7994 return prefix + 'J'
7995};
7996
7997var eraseLine = function eraseLine () {
7998 return prefix + 'K'
7999};
8000
8001var goto_1 = function (x, y) {
8002 return prefix + y + ';' + x + 'H'
8003};
8004
8005var gotoSOL = function () {
8006 return '\r'
8007};
8008
8009var beep = function () {
8010 return '\x07'
8011};
8012
8013var hideCursor = function hideCursor () {
8014 return prefix + '?25l'
8015};
8016
8017var showCursor = function showCursor () {
8018 return prefix + '?25h'
8019};
8020
8021var colors = {
8022 reset: 0,
8023// styles
8024 bold: 1,
8025 italic: 3,
8026 underline: 4,
8027 inverse: 7,
8028// resets
8029 stopBold: 22,
8030 stopItalic: 23,
8031 stopUnderline: 24,
8032 stopInverse: 27,
8033// colors
8034 white: 37,
8035 black: 30,
8036 blue: 34,
8037 cyan: 36,
8038 green: 32,
8039 magenta: 35,
8040 red: 31,
8041 yellow: 33,
8042 bgWhite: 47,
8043 bgBlack: 40,
8044 bgBlue: 44,
8045 bgCyan: 46,
8046 bgGreen: 42,
8047 bgMagenta: 45,
8048 bgRed: 41,
8049 bgYellow: 43,
8050
8051 grey: 90,
8052 brightBlack: 90,
8053 brightRed: 91,
8054 brightGreen: 92,
8055 brightYellow: 93,
8056 brightBlue: 94,
8057 brightMagenta: 95,
8058 brightCyan: 96,
8059 brightWhite: 97,
8060
8061 bgGrey: 100,
8062 bgBrightBlack: 100,
8063 bgBrightRed: 101,
8064 bgBrightGreen: 102,
8065 bgBrightYellow: 103,
8066 bgBrightBlue: 104,
8067 bgBrightMagenta: 105,
8068 bgBrightCyan: 106,
8069 bgBrightWhite: 107
8070};
8071
8072var color = function color (colorWith) {
8073 if (arguments.length !== 1 || !Array.isArray(colorWith)) {
8074 colorWith = Array.prototype.slice.call(arguments);
8075 }
8076 return prefix + colorWith.map(colorNameToCode).join(';') + 'm'
8077};
8078
8079function colorNameToCode (color) {
8080 if (colors[color] != null) return colors[color]
8081 throw new Error('Unknown color or style name: ' + color)
8082}
8083
8084var consoleControlStrings = {
8085 up: up,
8086 down: down,
8087 forward: forward,
8088 back: back,
8089 nextLine: nextLine,
8090 previousLine: previousLine,
8091 horizontalAbsolute: horizontalAbsolute,
8092 eraseData: eraseData,
8093 eraseLine: eraseLine,
8094 goto: goto_1,
8095 gotoSOL: gotoSOL,
8096 beep: beep,
8097 hideCursor: hideCursor,
8098 showCursor: showCursor,
8099 color: color
8100};
8101
8102var ansiRegex = () => {
8103 const pattern = [
8104 '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)',
8105 '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))'
8106 ].join('|');
8107
8108 return new RegExp(pattern, 'g');
8109};
8110
8111var stripAnsi = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input;
8112
8113/* eslint-disable yoda */
8114var isFullwidthCodePoint = x => {
8115 if (Number.isNaN(x)) {
8116 return false;
8117 }
8118
8119 // code points are derived from:
8120 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
8121 if (
8122 x >= 0x1100 && (
8123 x <= 0x115f || // Hangul Jamo
8124 x === 0x2329 || // LEFT-POINTING ANGLE BRACKET
8125 x === 0x232a || // RIGHT-POINTING ANGLE BRACKET
8126 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
8127 (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) ||
8128 // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
8129 (0x3250 <= x && x <= 0x4dbf) ||
8130 // CJK Unified Ideographs .. Yi Radicals
8131 (0x4e00 <= x && x <= 0xa4c6) ||
8132 // Hangul Jamo Extended-A
8133 (0xa960 <= x && x <= 0xa97c) ||
8134 // Hangul Syllables
8135 (0xac00 <= x && x <= 0xd7a3) ||
8136 // CJK Compatibility Ideographs
8137 (0xf900 <= x && x <= 0xfaff) ||
8138 // Vertical Forms
8139 (0xfe10 <= x && x <= 0xfe19) ||
8140 // CJK Compatibility Forms .. Small Form Variants
8141 (0xfe30 <= x && x <= 0xfe6b) ||
8142 // Halfwidth and Fullwidth Forms
8143 (0xff01 <= x && x <= 0xff60) ||
8144 (0xffe0 <= x && x <= 0xffe6) ||
8145 // Kana Supplement
8146 (0x1b000 <= x && x <= 0x1b001) ||
8147 // Enclosed Ideographic Supplement
8148 (0x1f200 <= x && x <= 0x1f251) ||
8149 // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
8150 (0x20000 <= x && x <= 0x3fffd)
8151 )
8152 ) {
8153 return true;
8154 }
8155
8156 return false;
8157};
8158
8159var stringWidth = str => {
8160 if (typeof str !== 'string' || str.length === 0) {
8161 return 0;
8162 }
8163
8164 str = stripAnsi(str);
8165
8166 let width = 0;
8167
8168 for (let i = 0; i < str.length; i++) {
8169 const code = str.codePointAt(i);
8170
8171 // Ignore control characters
8172 if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
8173 continue;
8174 }
8175
8176 // Ignore combining characters
8177 if (code >= 0x300 && code <= 0x36F) {
8178 continue;
8179 }
8180
8181 // Surrogates
8182 if (code > 0xFFFF) {
8183 i++;
8184 }
8185
8186 width += isFullwidthCodePoint(code) ? 2 : 1;
8187 }
8188
8189 return width;
8190};
8191
8192var center = alignCenter;
8193var left = alignLeft;
8194var right = alignRight;
8195
8196// lodash's way of generating pad characters.
8197
8198function createPadding (width) {
8199 var result = '';
8200 var string = ' ';
8201 var n = width;
8202 do {
8203 if (n % 2) {
8204 result += string;
8205 }
8206 n = Math.floor(n / 2);
8207 string += string;
8208 } while (n);
8209
8210 return result;
8211}
8212
8213function alignLeft (str, width) {
8214 var trimmed = str.trimRight();
8215 if (trimmed.length === 0 && str.length >= width) return str
8216 var padding = '';
8217 var strWidth = stringWidth(trimmed);
8218
8219 if (strWidth < width) {
8220 padding = createPadding(width - strWidth);
8221 }
8222
8223 return trimmed + padding
8224}
8225
8226function alignRight (str, width) {
8227 var trimmed = str.trimLeft();
8228 if (trimmed.length === 0 && str.length >= width) return str
8229 var padding = '';
8230 var strWidth = stringWidth(trimmed);
8231
8232 if (strWidth < width) {
8233 padding = createPadding(width - strWidth);
8234 }
8235
8236 return padding + trimmed
8237}
8238
8239function alignCenter (str, width) {
8240 var trimmed = str.trim();
8241 if (trimmed.length === 0 && str.length >= width) return str
8242 var padLeft = '';
8243 var padRight = '';
8244 var strWidth = stringWidth(trimmed);
8245
8246 if (strWidth < width) {
8247 var padLeftBy = parseInt((width - strWidth) / 2, 10);
8248 padLeft = createPadding(padLeftBy);
8249 padRight = createPadding(width - (strWidth + padLeftBy));
8250 }
8251
8252 return padLeft + trimmed + padRight
8253}
8254
8255var align = {
8256 center: center,
8257 left: left,
8258 right: right
8259};
8260
8261var aproba = createCommonjsModule(function (module) {
8262
8263function isArguments (thingy) {
8264 return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee')
8265}
8266
8267var types = {
8268 '*': {label: 'any', check: function () { return true }},
8269 A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }},
8270 S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }},
8271 N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }},
8272 F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }},
8273 O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }},
8274 B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }},
8275 E: {label: 'error', check: function (thingy) { return thingy instanceof Error }},
8276 Z: {label: 'null', check: function (thingy) { return thingy == null }}
8277};
8278
8279function addSchema (schema, arity) {
8280 var group = arity[schema.length] = arity[schema.length] || [];
8281 if (group.indexOf(schema) === -1) group.push(schema);
8282}
8283
8284var validate = module.exports = function (rawSchemas, args) {
8285 if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length)
8286 if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas')
8287 if (!args) throw missingRequiredArg(1, 'args')
8288 if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas)
8289 if (!types.A.check(args)) throw invalidType(1, ['array'], args)
8290 var schemas = rawSchemas.split('|');
8291 var arity = {};
8292
8293 schemas.forEach(function (schema) {
8294 for (var ii = 0; ii < schema.length; ++ii) {
8295 var type = schema[ii];
8296 if (!types[type]) throw unknownType(ii, type)
8297 }
8298 if (/E.*E/.test(schema)) throw moreThanOneError(schema)
8299 addSchema(schema, arity);
8300 if (/E/.test(schema)) {
8301 addSchema(schema.replace(/E.*$/, 'E'), arity);
8302 addSchema(schema.replace(/E/, 'Z'), arity);
8303 if (schema.length === 1) addSchema('', arity);
8304 }
8305 });
8306 var matching = arity[args.length];
8307 if (!matching) {
8308 throw wrongNumberOfArgs(Object.keys(arity), args.length)
8309 }
8310 for (var ii = 0; ii < args.length; ++ii) {
8311 var newMatching = matching.filter(function (schema) {
8312 var type = schema[ii];
8313 var typeCheck = types[type].check;
8314 return typeCheck(args[ii])
8315 });
8316 if (!newMatching.length) {
8317 var labels = matching.map(function (schema) {
8318 return types[schema[ii]].label
8319 }).filter(function (schema) { return schema != null });
8320 throw invalidType(ii, labels, args[ii])
8321 }
8322 matching = newMatching;
8323 }
8324};
8325
8326function missingRequiredArg (num) {
8327 return newException('EMISSINGARG', 'Missing required argument #' + (num + 1))
8328}
8329
8330function unknownType (num, type) {
8331 return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1))
8332}
8333
8334function invalidType (num, expectedTypes, value) {
8335 var valueType;
8336 Object.keys(types).forEach(function (typeCode) {
8337 if (types[typeCode].check(value)) valueType = types[typeCode].label;
8338 });
8339 return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' +
8340 englishList(expectedTypes) + ' but got ' + valueType)
8341}
8342
8343function englishList (list) {
8344 return list.join(', ').replace(/, ([^,]+)$/, ' or $1')
8345}
8346
8347function wrongNumberOfArgs (expected, got) {
8348 var english = englishList(expected);
8349 var args = expected.every(function (ex) { return ex.length === 1 })
8350 ? 'argument'
8351 : 'arguments';
8352 return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got)
8353}
8354
8355function moreThanOneError (schema) {
8356 return newException('ETOOMANYERRORTYPES',
8357 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"')
8358}
8359
8360function newException (code, msg) {
8361 var e = new Error(msg);
8362 e.code = code;
8363 if (Error.captureStackTrace) Error.captureStackTrace(e, validate);
8364 return e
8365}
8366});
8367
8368/*
8369object-assign
8370(c) Sindre Sorhus
8371@license MIT
8372*/
8373/* eslint-disable no-unused-vars */
8374var getOwnPropertySymbols = Object.getOwnPropertySymbols;
8375var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
8376var propIsEnumerable = Object.prototype.propertyIsEnumerable;
8377
8378function toObject(val) {
8379 if (val === null || val === undefined) {
8380 throw new TypeError('Object.assign cannot be called with null or undefined');
8381 }
8382
8383 return Object(val);
8384}
8385
8386function shouldUseNative() {
8387 try {
8388 if (!Object.assign) {
8389 return false;
8390 }
8391
8392 // Detect buggy property enumeration order in older V8 versions.
8393
8394 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
8395 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
8396 test1[5] = 'de';
8397 if (Object.getOwnPropertyNames(test1)[0] === '5') {
8398 return false;
8399 }
8400
8401 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
8402 var test2 = {};
8403 for (var i = 0; i < 10; i++) {
8404 test2['_' + String.fromCharCode(i)] = i;
8405 }
8406 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
8407 return test2[n];
8408 });
8409 if (order2.join('') !== '0123456789') {
8410 return false;
8411 }
8412
8413 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
8414 var test3 = {};
8415 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
8416 test3[letter] = letter;
8417 });
8418 if (Object.keys(Object.assign({}, test3)).join('') !==
8419 'abcdefghijklmnopqrst') {
8420 return false;
8421 }
8422
8423 return true;
8424 } catch (err) {
8425 // We don't expect any of the above to throw, but better to be safe.
8426 return false;
8427 }
8428}
8429
8430var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
8431 var from;
8432 var to = toObject(target);
8433 var symbols;
8434
8435 for (var s = 1; s < arguments.length; s++) {
8436 from = Object(arguments[s]);
8437
8438 for (var key in from) {
8439 if (hasOwnProperty$1.call(from, key)) {
8440 to[key] = from[key];
8441 }
8442 }
8443
8444 if (getOwnPropertySymbols) {
8445 symbols = getOwnPropertySymbols(from);
8446 for (var i = 0; i < symbols.length; i++) {
8447 if (propIsEnumerable.call(from, symbols[i])) {
8448 to[symbols[i]] = from[symbols[i]];
8449 }
8450 }
8451 }
8452 }
8453
8454 return to;
8455};
8456
8457var ansiRegex$1 = function () {
8458 return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g;
8459};
8460
8461var ansiRegex$2 = ansiRegex$1();
8462
8463var stripAnsi$1 = function (str) {
8464 return typeof str === 'string' ? str.replace(ansiRegex$2, '') : str;
8465};
8466
8467/* eslint-disable babel/new-cap, xo/throw-new-error */
8468var codePointAt = function (str, pos) {
8469 if (str === null || str === undefined) {
8470 throw TypeError();
8471 }
8472
8473 str = String(str);
8474
8475 var size = str.length;
8476 var i = pos ? Number(pos) : 0;
8477
8478 if (Number.isNaN(i)) {
8479 i = 0;
8480 }
8481
8482 if (i < 0 || i >= size) {
8483 return undefined;
8484 }
8485
8486 var first = str.charCodeAt(i);
8487
8488 if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) {
8489 var second = str.charCodeAt(i + 1);
8490
8491 if (second >= 0xDC00 && second <= 0xDFFF) {
8492 return ((first - 0xD800) * 0x400) + second - 0xDC00 + 0x10000;
8493 }
8494 }
8495
8496 return first;
8497};
8498
8499var numberIsNan = Number.isNaN || function (x) {
8500 return x !== x;
8501};
8502
8503var isFullwidthCodePoint$1 = function (x) {
8504 if (numberIsNan(x)) {
8505 return false;
8506 }
8507
8508 // https://github.com/nodejs/io.js/blob/cff7300a578be1b10001f2d967aaedc88aee6402/lib/readline.js#L1369
8509
8510 // code points are derived from:
8511 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
8512 if (x >= 0x1100 && (
8513 x <= 0x115f || // Hangul Jamo
8514 0x2329 === x || // LEFT-POINTING ANGLE BRACKET
8515 0x232a === x || // RIGHT-POINTING ANGLE BRACKET
8516 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
8517 (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) ||
8518 // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
8519 0x3250 <= x && x <= 0x4dbf ||
8520 // CJK Unified Ideographs .. Yi Radicals
8521 0x4e00 <= x && x <= 0xa4c6 ||
8522 // Hangul Jamo Extended-A
8523 0xa960 <= x && x <= 0xa97c ||
8524 // Hangul Syllables
8525 0xac00 <= x && x <= 0xd7a3 ||
8526 // CJK Compatibility Ideographs
8527 0xf900 <= x && x <= 0xfaff ||
8528 // Vertical Forms
8529 0xfe10 <= x && x <= 0xfe19 ||
8530 // CJK Compatibility Forms .. Small Form Variants
8531 0xfe30 <= x && x <= 0xfe6b ||
8532 // Halfwidth and Fullwidth Forms
8533 0xff01 <= x && x <= 0xff60 ||
8534 0xffe0 <= x && x <= 0xffe6 ||
8535 // Kana Supplement
8536 0x1b000 <= x && x <= 0x1b001 ||
8537 // Enclosed Ideographic Supplement
8538 0x1f200 <= x && x <= 0x1f251 ||
8539 // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
8540 0x20000 <= x && x <= 0x3fffd)) {
8541 return true;
8542 }
8543
8544 return false;
8545};
8546
8547// https://github.com/nodejs/io.js/blob/cff7300a578be1b10001f2d967aaedc88aee6402/lib/readline.js#L1345
8548var stringWidth$1 = function (str) {
8549 if (typeof str !== 'string' || str.length === 0) {
8550 return 0;
8551 }
8552
8553 var width = 0;
8554
8555 str = stripAnsi$1(str);
8556
8557 for (var i = 0; i < str.length; i++) {
8558 var code = codePointAt(str, i);
8559
8560 // ignore control characters
8561 if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
8562 continue;
8563 }
8564
8565 // surrogates
8566 if (code >= 0x10000) {
8567 i++;
8568 }
8569
8570 if (isFullwidthCodePoint$1(code)) {
8571 width += 2;
8572 } else {
8573 width++;
8574 }
8575 }
8576
8577 return width;
8578};
8579
8580var wideTruncate_1 = wideTruncate;
8581
8582function wideTruncate (str, target) {
8583 if (stringWidth$1(str) === 0) return str
8584 if (target <= 0) return ''
8585 if (stringWidth$1(str) <= target) return str
8586
8587 // We compute the number of bytes of ansi sequences here and add
8588 // that to our initial truncation to ensure that we don't slice one
8589 // that we want to keep in half.
8590 var noAnsi = stripAnsi$1(str);
8591 var ansiSize = str.length + noAnsi.length;
8592 var truncated = str.slice(0, target + ansiSize);
8593
8594 // we have to shrink the result to account for our ansi sequence buffer
8595 // (if an ansi sequence was truncated) and double width characters.
8596 while (stringWidth$1(truncated) > target) {
8597 truncated = truncated.slice(0, -1);
8598 }
8599 return truncated
8600}
8601
8602var error = createCommonjsModule(function (module, exports) {
8603
8604
8605var User = exports.User = function User (msg) {
8606 var err = new Error(msg);
8607 Error.captureStackTrace(err, User);
8608 err.code = 'EGAUGE';
8609 return err
8610};
8611
8612exports.MissingTemplateValue = function MissingTemplateValue (item, values) {
8613 var err = new User(util.format('Missing template value "%s"', item.type));
8614 Error.captureStackTrace(err, MissingTemplateValue);
8615 err.template = item;
8616 err.values = values;
8617 return err
8618};
8619
8620exports.Internal = function Internal (msg) {
8621 var err = new Error(msg);
8622 Error.captureStackTrace(err, Internal);
8623 err.code = 'EGAUGEINTERNAL';
8624 return err
8625};
8626});
8627var error_1 = error.User;
8628var error_2 = error.MissingTemplateValue;
8629var error_3 = error.Internal;
8630
8631var templateItem = TemplateItem;
8632
8633function isPercent (num) {
8634 if (typeof num !== 'string') return false
8635 return num.slice(-1) === '%'
8636}
8637
8638function percent (num) {
8639 return Number(num.slice(0, -1)) / 100
8640}
8641
8642function TemplateItem (values, outputLength) {
8643 this.overallOutputLength = outputLength;
8644 this.finished = false;
8645 this.type = null;
8646 this.value = null;
8647 this.length = null;
8648 this.maxLength = null;
8649 this.minLength = null;
8650 this.kerning = null;
8651 this.align = 'left';
8652 this.padLeft = 0;
8653 this.padRight = 0;
8654 this.index = null;
8655 this.first = null;
8656 this.last = null;
8657 if (typeof values === 'string') {
8658 this.value = values;
8659 } else {
8660 for (var prop in values) this[prop] = values[prop];
8661 }
8662 // Realize percents
8663 if (isPercent(this.length)) {
8664 this.length = Math.round(this.overallOutputLength * percent(this.length));
8665 }
8666 if (isPercent(this.minLength)) {
8667 this.minLength = Math.round(this.overallOutputLength * percent(this.minLength));
8668 }
8669 if (isPercent(this.maxLength)) {
8670 this.maxLength = Math.round(this.overallOutputLength * percent(this.maxLength));
8671 }
8672 return this
8673}
8674
8675TemplateItem.prototype = {};
8676
8677TemplateItem.prototype.getBaseLength = function () {
8678 var length = this.length;
8679 if (length == null && typeof this.value === 'string' && this.maxLength == null && this.minLength == null) {
8680 length = stringWidth$1(this.value);
8681 }
8682 return length
8683};
8684
8685TemplateItem.prototype.getLength = function () {
8686 var length = this.getBaseLength();
8687 if (length == null) return null
8688 return length + this.padLeft + this.padRight
8689};
8690
8691TemplateItem.prototype.getMaxLength = function () {
8692 if (this.maxLength == null) return null
8693 return this.maxLength + this.padLeft + this.padRight
8694};
8695
8696TemplateItem.prototype.getMinLength = function () {
8697 if (this.minLength == null) return null
8698 return this.minLength + this.padLeft + this.padRight
8699};
8700
8701var renderTemplate_1 = createCommonjsModule(function (module) {
8702
8703
8704
8705
8706
8707
8708
8709function renderValueWithValues (values) {
8710 return function (item) {
8711 return renderValue(item, values)
8712 }
8713}
8714
8715var renderTemplate = module.exports = function (width, template, values) {
8716 var items = prepareItems(width, template, values);
8717 var rendered = items.map(renderValueWithValues(values)).join('');
8718 return align.left(wideTruncate_1(rendered, width), width)
8719};
8720
8721function preType (item) {
8722 var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1);
8723 return 'pre' + cappedTypeName
8724}
8725
8726function postType (item) {
8727 var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1);
8728 return 'post' + cappedTypeName
8729}
8730
8731function hasPreOrPost (item, values) {
8732 if (!item.type) return
8733 return values[preType(item)] || values[postType(item)]
8734}
8735
8736function generatePreAndPost (baseItem, parentValues) {
8737 var item = objectAssign({}, baseItem);
8738 var values = Object.create(parentValues);
8739 var template = [];
8740 var pre = preType(item);
8741 var post = postType(item);
8742 if (values[pre]) {
8743 template.push({value: values[pre]});
8744 values[pre] = null;
8745 }
8746 item.minLength = null;
8747 item.length = null;
8748 item.maxLength = null;
8749 template.push(item);
8750 values[item.type] = values[item.type];
8751 if (values[post]) {
8752 template.push({value: values[post]});
8753 values[post] = null;
8754 }
8755 return function ($1, $2, length) {
8756 return renderTemplate(length, template, values)
8757 }
8758}
8759
8760function prepareItems (width, template, values) {
8761 function cloneAndObjectify (item, index, arr) {
8762 var cloned = new templateItem(item, width);
8763 var type = cloned.type;
8764 if (cloned.value == null) {
8765 if (!(type in values)) {
8766 if (cloned.default == null) {
8767 throw new error.MissingTemplateValue(cloned, values)
8768 } else {
8769 cloned.value = cloned.default;
8770 }
8771 } else {
8772 cloned.value = values[type];
8773 }
8774 }
8775 if (cloned.value == null || cloned.value === '') return null
8776 cloned.index = index;
8777 cloned.first = index === 0;
8778 cloned.last = index === arr.length - 1;
8779 if (hasPreOrPost(cloned, values)) cloned.value = generatePreAndPost(cloned, values);
8780 return cloned
8781 }
8782
8783 var output = template.map(cloneAndObjectify).filter(function (item) { return item != null });
8784 var remainingSpace = width;
8785 var variableCount = output.length;
8786
8787 function consumeSpace (length) {
8788 if (length > remainingSpace) length = remainingSpace;
8789 remainingSpace -= length;
8790 }
8791
8792 function finishSizing (item, length) {
8793 if (item.finished) throw new error.Internal('Tried to finish template item that was already finished')
8794 if (length === Infinity) throw new error.Internal('Length of template item cannot be infinity')
8795 if (length != null) item.length = length;
8796 item.minLength = null;
8797 item.maxLength = null;
8798 --variableCount;
8799 item.finished = true;
8800 if (item.length == null) item.length = item.getBaseLength();
8801 if (item.length == null) throw new error.Internal('Finished template items must have a length')
8802 consumeSpace(item.getLength());
8803 }
8804
8805 output.forEach(function (item) {
8806 if (!item.kerning) return
8807 var prevPadRight = item.first ? 0 : output[item.index - 1].padRight;
8808 if (!item.first && prevPadRight < item.kerning) item.padLeft = item.kerning - prevPadRight;
8809 if (!item.last) item.padRight = item.kerning;
8810 });
8811
8812 // Finish any that have a fixed (literal or intuited) length
8813 output.forEach(function (item) {
8814 if (item.getBaseLength() == null) return
8815 finishSizing(item);
8816 });
8817
8818 var resized = 0;
8819 var resizing;
8820 var hunkSize;
8821 do {
8822 resizing = false;
8823 hunkSize = Math.round(remainingSpace / variableCount);
8824 output.forEach(function (item) {
8825 if (item.finished) return
8826 if (!item.maxLength) return
8827 if (item.getMaxLength() < hunkSize) {
8828 finishSizing(item, item.maxLength);
8829 resizing = true;
8830 }
8831 });
8832 } while (resizing && resized++ < output.length)
8833 if (resizing) throw new error.Internal('Resize loop iterated too many times while determining maxLength')
8834
8835 resized = 0;
8836 do {
8837 resizing = false;
8838 hunkSize = Math.round(remainingSpace / variableCount);
8839 output.forEach(function (item) {
8840 if (item.finished) return
8841 if (!item.minLength) return
8842 if (item.getMinLength() >= hunkSize) {
8843 finishSizing(item, item.minLength);
8844 resizing = true;
8845 }
8846 });
8847 } while (resizing && resized++ < output.length)
8848 if (resizing) throw new error.Internal('Resize loop iterated too many times while determining minLength')
8849
8850 hunkSize = Math.round(remainingSpace / variableCount);
8851 output.forEach(function (item) {
8852 if (item.finished) return
8853 finishSizing(item, hunkSize);
8854 });
8855
8856 return output
8857}
8858
8859function renderFunction (item, values, length) {
8860 aproba('OON', arguments);
8861 if (item.type) {
8862 return item.value(values, values[item.type + 'Theme'] || {}, length)
8863 } else {
8864 return item.value(values, {}, length)
8865 }
8866}
8867
8868function renderValue (item, values) {
8869 var length = item.getBaseLength();
8870 var value = typeof item.value === 'function' ? renderFunction(item, values, length) : item.value;
8871 if (value == null || value === '') return ''
8872 var alignWith = align[item.align] || align.left;
8873 var leftPadding = item.padLeft ? align.left('', item.padLeft) : '';
8874 var rightPadding = item.padRight ? align.right('', item.padRight) : '';
8875 var truncated = wideTruncate_1(String(value), length);
8876 var aligned = alignWith(truncated, length);
8877 return leftPadding + aligned + rightPadding
8878}
8879});
8880
8881var plumbing = createCommonjsModule(function (module) {
8882
8883
8884
8885
8886var Plumbing = module.exports = function (theme, template, width) {
8887 if (!width) width = 80;
8888 aproba('OAN', [theme, template, width]);
8889 this.showing = false;
8890 this.theme = theme;
8891 this.width = width;
8892 this.template = template;
8893};
8894Plumbing.prototype = {};
8895
8896Plumbing.prototype.setTheme = function (theme) {
8897 aproba('O', [theme]);
8898 this.theme = theme;
8899};
8900
8901Plumbing.prototype.setTemplate = function (template) {
8902 aproba('A', [template]);
8903 this.template = template;
8904};
8905
8906Plumbing.prototype.setWidth = function (width) {
8907 aproba('N', [width]);
8908 this.width = width;
8909};
8910
8911Plumbing.prototype.hide = function () {
8912 return consoleControlStrings.gotoSOL() + consoleControlStrings.eraseLine()
8913};
8914
8915Plumbing.prototype.hideCursor = consoleControlStrings.hideCursor;
8916
8917Plumbing.prototype.showCursor = consoleControlStrings.showCursor;
8918
8919Plumbing.prototype.show = function (status) {
8920 var values = Object.create(this.theme);
8921 for (var key in status) {
8922 values[key] = status[key];
8923 }
8924
8925 return renderTemplate_1(this.width, this.template, values).trim() +
8926 consoleControlStrings.color('reset') +
8927 consoleControlStrings.eraseLine() + consoleControlStrings.gotoSOL()
8928};
8929});
8930
8931var hasUnicode_1 = createCommonjsModule(function (module) {
8932
8933
8934var hasUnicode = module.exports = function () {
8935 // Recent Win32 platforms (>XP) CAN support unicode in the console but
8936 // don't have to, and in non-english locales often use traditional local
8937 // code pages. There's no way, short of windows system calls or execing
8938 // the chcp command line program to figure this out. As such, we default
8939 // this to false and encourage your users to override it via config if
8940 // appropriate.
8941 if (os.type() == "Windows_NT") { return false }
8942
8943 var isUTF8 = /UTF-?8$/i;
8944 var ctype = process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG;
8945 return isUTF8.test(ctype)
8946};
8947});
8948
8949var hasColor = isWin32() || isColorTerm();
8950
8951function isWin32 () {
8952 return process.platform === 'win32'
8953}
8954
8955function isColorTerm () {
8956 var termHasColor = /^screen|^xterm|^vt100|color|ansi|cygwin|linux/i;
8957 return !!process.env.COLORTERM || termHasColor.test(process.env.TERM)
8958}
8959
8960var signals = createCommonjsModule(function (module) {
8961// This is not the set of all possible signals.
8962//
8963// It IS, however, the set of all signals that trigger
8964// an exit on either Linux or BSD systems. Linux is a
8965// superset of the signal names supported on BSD, and
8966// the unknown signals just fail to register, so we can
8967// catch that easily enough.
8968//
8969// Don't bother with SIGKILL. It's uncatchable, which
8970// means that we can't fire any callbacks anyway.
8971//
8972// If a user does happen to register a handler on a non-
8973// fatal signal like SIGWINCH or something, and then
8974// exit, it'll end up firing `process.emit('exit')`, so
8975// the handler will be fired anyway.
8976//
8977// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
8978// artificially, inherently leave the process in a
8979// state from which it is not safe to try and enter JS
8980// listeners.
8981module.exports = [
8982 'SIGABRT',
8983 'SIGALRM',
8984 'SIGHUP',
8985 'SIGINT',
8986 'SIGTERM'
8987];
8988
8989if (process.platform !== 'win32') {
8990 module.exports.push(
8991 'SIGVTALRM',
8992 'SIGXCPU',
8993 'SIGXFSZ',
8994 'SIGUSR2',
8995 'SIGTRAP',
8996 'SIGSYS',
8997 'SIGQUIT',
8998 'SIGIOT'
8999 // should detect profiler and enable/disable accordingly.
9000 // see #21
9001 // 'SIGPROF'
9002 );
9003}
9004
9005if (process.platform === 'linux') {
9006 module.exports.push(
9007 'SIGIO',
9008 'SIGPOLL',
9009 'SIGPWR',
9010 'SIGSTKFLT',
9011 'SIGUNUSED'
9012 );
9013}
9014});
9015
9016// Note: since nyc uses this module to output coverage, any lines
9017// that are in the direct sync flow of nyc's outputCoverage are
9018// ignored, since we can never get coverage for them.
9019
9020var signals$1 = signals;
9021
9022var EE = events;
9023/* istanbul ignore if */
9024if (typeof EE !== 'function') {
9025 EE = EE.EventEmitter;
9026}
9027
9028var emitter;
9029if (process.__signal_exit_emitter__) {
9030 emitter = process.__signal_exit_emitter__;
9031} else {
9032 emitter = process.__signal_exit_emitter__ = new EE();
9033 emitter.count = 0;
9034 emitter.emitted = {};
9035}
9036
9037// Because this emitter is a global, we have to check to see if a
9038// previous version of this library failed to enable infinite listeners.
9039// I know what you're about to say. But literally everything about
9040// signal-exit is a compromise with evil. Get used to it.
9041if (!emitter.infinite) {
9042 emitter.setMaxListeners(Infinity);
9043 emitter.infinite = true;
9044}
9045
9046var signalExit = function (cb, opts) {
9047 assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
9048
9049 if (loaded === false) {
9050 load();
9051 }
9052
9053 var ev = 'exit';
9054 if (opts && opts.alwaysLast) {
9055 ev = 'afterexit';
9056 }
9057
9058 var remove = function () {
9059 emitter.removeListener(ev, cb);
9060 if (emitter.listeners('exit').length === 0 &&
9061 emitter.listeners('afterexit').length === 0) {
9062 unload();
9063 }
9064 };
9065 emitter.on(ev, cb);
9066
9067 return remove
9068};
9069
9070var unload_1 = unload;
9071function unload () {
9072 if (!loaded) {
9073 return
9074 }
9075 loaded = false;
9076
9077 signals$1.forEach(function (sig) {
9078 try {
9079 process.removeListener(sig, sigListeners[sig]);
9080 } catch (er) {}
9081 });
9082 process.emit = originalProcessEmit;
9083 process.reallyExit = originalProcessReallyExit;
9084 emitter.count -= 1;
9085}
9086
9087function emit (event, code, signal) {
9088 if (emitter.emitted[event]) {
9089 return
9090 }
9091 emitter.emitted[event] = true;
9092 emitter.emit(event, code, signal);
9093}
9094
9095// { <signal>: <listener fn>, ... }
9096var sigListeners = {};
9097signals$1.forEach(function (sig) {
9098 sigListeners[sig] = function listener () {
9099 // If there are no other listeners, an exit is coming!
9100 // Simplest way: remove us and then re-send the signal.
9101 // We know that this will kill the process, so we can
9102 // safely emit now.
9103 var listeners = process.listeners(sig);
9104 if (listeners.length === emitter.count) {
9105 unload();
9106 emit('exit', null, sig);
9107 /* istanbul ignore next */
9108 emit('afterexit', null, sig);
9109 /* istanbul ignore next */
9110 process.kill(process.pid, sig);
9111 }
9112 };
9113});
9114
9115var signals_1 = function () {
9116 return signals$1
9117};
9118
9119var load_1 = load;
9120
9121var loaded = false;
9122
9123function load () {
9124 if (loaded) {
9125 return
9126 }
9127 loaded = true;
9128
9129 // This is the number of onSignalExit's that are in play.
9130 // It's important so that we can count the correct number of
9131 // listeners on signals, and don't wait for the other one to
9132 // handle it instead of us.
9133 emitter.count += 1;
9134
9135 signals$1 = signals$1.filter(function (sig) {
9136 try {
9137 process.on(sig, sigListeners[sig]);
9138 return true
9139 } catch (er) {
9140 return false
9141 }
9142 });
9143
9144 process.emit = processEmit;
9145 process.reallyExit = processReallyExit;
9146}
9147
9148var originalProcessReallyExit = process.reallyExit;
9149function processReallyExit (code) {
9150 process.exitCode = code || 0;
9151 emit('exit', process.exitCode, null);
9152 /* istanbul ignore next */
9153 emit('afterexit', process.exitCode, null);
9154 /* istanbul ignore next */
9155 originalProcessReallyExit.call(process, process.exitCode);
9156}
9157
9158var originalProcessEmit = process.emit;
9159function processEmit (ev, arg) {
9160 if (ev === 'exit') {
9161 if (arg !== undefined) {
9162 process.exitCode = arg;
9163 }
9164 var ret = originalProcessEmit.apply(this, arguments);
9165 emit('exit', process.exitCode, null);
9166 /* istanbul ignore next */
9167 emit('afterexit', process.exitCode, null);
9168 return ret
9169 } else {
9170 return originalProcessEmit.apply(this, arguments)
9171 }
9172}
9173signalExit.unload = unload_1;
9174signalExit.signals = signals_1;
9175signalExit.load = load_1;
9176
9177var spin = function spin (spinstr, spun) {
9178 return spinstr[spun % spinstr.length]
9179};
9180
9181var progressBar = function (theme, width, completed) {
9182 aproba('ONN', [theme, width, completed]);
9183 if (completed < 0) completed = 0;
9184 if (completed > 1) completed = 1;
9185 if (width <= 0) return ''
9186 var sofar = Math.round(width * completed);
9187 var rest = width - sofar;
9188 var template = [
9189 {type: 'complete', value: repeat(theme.complete, sofar), length: sofar},
9190 {type: 'remaining', value: repeat(theme.remaining, rest), length: rest}
9191 ];
9192 return renderTemplate_1(width, template, theme)
9193};
9194
9195// lodash's way of repeating
9196function repeat (string, width) {
9197 var result = '';
9198 var n = width;
9199 do {
9200 if (n % 2) {
9201 result += string;
9202 }
9203 n = Math.floor(n / 2);
9204 /*eslint no-self-assign: 0*/
9205 string += string;
9206 } while (n && stringWidth$1(result) < width)
9207
9208 return wideTruncate_1(result, width)
9209}
9210
9211var baseTheme = {
9212 activityIndicator: function (values, theme, width) {
9213 if (values.spun == null) return
9214 return spin(theme, values.spun)
9215 },
9216 progressbar: function (values, theme, width) {
9217 if (values.completed == null) return
9218 return progressBar(theme, width, values.completed)
9219 }
9220};
9221
9222var themeSet = function () {
9223 return ThemeSetProto.newThemeSet()
9224};
9225
9226var ThemeSetProto = {};
9227
9228ThemeSetProto.baseTheme = baseTheme;
9229
9230ThemeSetProto.newTheme = function (parent, theme) {
9231 if (!theme) {
9232 theme = parent;
9233 parent = this.baseTheme;
9234 }
9235 return objectAssign({}, parent, theme)
9236};
9237
9238ThemeSetProto.getThemeNames = function () {
9239 return Object.keys(this.themes)
9240};
9241
9242ThemeSetProto.addTheme = function (name, parent, theme) {
9243 this.themes[name] = this.newTheme(parent, theme);
9244};
9245
9246ThemeSetProto.addToAllThemes = function (theme) {
9247 var themes = this.themes;
9248 Object.keys(themes).forEach(function (name) {
9249 objectAssign(themes[name], theme);
9250 });
9251 objectAssign(this.baseTheme, theme);
9252};
9253
9254ThemeSetProto.getTheme = function (name) {
9255 if (!this.themes[name]) throw this.newMissingThemeError(name)
9256 return this.themes[name]
9257};
9258
9259ThemeSetProto.setDefault = function (opts, name) {
9260 if (name == null) {
9261 name = opts;
9262 opts = {};
9263 }
9264 var platform = opts.platform == null ? 'fallback' : opts.platform;
9265 var hasUnicode = !!opts.hasUnicode;
9266 var hasColor = !!opts.hasColor;
9267 if (!this.defaults[platform]) this.defaults[platform] = {true: {}, false: {}};
9268 this.defaults[platform][hasUnicode][hasColor] = name;
9269};
9270
9271ThemeSetProto.getDefault = function (opts) {
9272 if (!opts) opts = {};
9273 var platformName = opts.platform || process.platform;
9274 var platform = this.defaults[platformName] || this.defaults.fallback;
9275 var hasUnicode = !!opts.hasUnicode;
9276 var hasColor = !!opts.hasColor;
9277 if (!platform) throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor)
9278 if (!platform[hasUnicode][hasColor]) {
9279 if (hasUnicode && hasColor && platform[!hasUnicode][hasColor]) {
9280 hasUnicode = false;
9281 } else if (hasUnicode && hasColor && platform[hasUnicode][!hasColor]) {
9282 hasColor = false;
9283 } else if (hasUnicode && hasColor && platform[!hasUnicode][!hasColor]) {
9284 hasUnicode = false;
9285 hasColor = false;
9286 } else if (hasUnicode && !hasColor && platform[!hasUnicode][hasColor]) {
9287 hasUnicode = false;
9288 } else if (!hasUnicode && hasColor && platform[hasUnicode][!hasColor]) {
9289 hasColor = false;
9290 } else if (platform === this.defaults.fallback) {
9291 throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor)
9292 }
9293 }
9294 if (platform[hasUnicode][hasColor]) {
9295 return this.getTheme(platform[hasUnicode][hasColor])
9296 } else {
9297 return this.getDefault(objectAssign({}, opts, {platform: 'fallback'}))
9298 }
9299};
9300
9301ThemeSetProto.newMissingThemeError = function newMissingThemeError (name) {
9302 var err = new Error('Could not find a gauge theme named "' + name + '"');
9303 Error.captureStackTrace.call(err, newMissingThemeError);
9304 err.theme = name;
9305 err.code = 'EMISSINGTHEME';
9306 return err
9307};
9308
9309ThemeSetProto.newMissingDefaultThemeError = function newMissingDefaultThemeError (platformName, hasUnicode, hasColor) {
9310 var err = new Error(
9311 'Could not find a gauge theme for your platform/unicode/color use combo:\n' +
9312 ' platform = ' + platformName + '\n' +
9313 ' hasUnicode = ' + hasUnicode + '\n' +
9314 ' hasColor = ' + hasColor);
9315 Error.captureStackTrace.call(err, newMissingDefaultThemeError);
9316 err.platform = platformName;
9317 err.hasUnicode = hasUnicode;
9318 err.hasColor = hasColor;
9319 err.code = 'EMISSINGTHEME';
9320 return err
9321};
9322
9323ThemeSetProto.newThemeSet = function () {
9324 var themeset = function (opts) {
9325 return themeset.getDefault(opts)
9326 };
9327 return objectAssign(themeset, ThemeSetProto, {
9328 themes: objectAssign({}, this.themes),
9329 baseTheme: objectAssign({}, this.baseTheme),
9330 defaults: JSON.parse(JSON.stringify(this.defaults || {}))
9331 })
9332};
9333
9334var themes_1 = createCommonjsModule(function (module) {
9335
9336
9337
9338var themes = module.exports = new themeSet();
9339
9340themes.addTheme('ASCII', {
9341 preProgressbar: '[',
9342 postProgressbar: ']',
9343 progressbarTheme: {
9344 complete: '#',
9345 remaining: '.'
9346 },
9347 activityIndicatorTheme: '-\\|/',
9348 preSubsection: '>'
9349});
9350
9351themes.addTheme('colorASCII', themes.getTheme('ASCII'), {
9352 progressbarTheme: {
9353 preComplete: consoleControlStrings.color('inverse'),
9354 complete: ' ',
9355 postComplete: consoleControlStrings.color('stopInverse'),
9356 preRemaining: consoleControlStrings.color('brightBlack'),
9357 remaining: '.',
9358 postRemaining: consoleControlStrings.color('reset')
9359 }
9360});
9361
9362themes.addTheme('brailleSpinner', {
9363 preProgressbar: '⸨',
9364 postProgressbar: '⸩',
9365 progressbarTheme: {
9366 complete: '░',
9367 remaining: '⠂'
9368 },
9369 activityIndicatorTheme: '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏',
9370 preSubsection: '>'
9371});
9372
9373themes.addTheme('colorBrailleSpinner', themes.getTheme('brailleSpinner'), {
9374 progressbarTheme: {
9375 preComplete: consoleControlStrings.color('inverse'),
9376 complete: ' ',
9377 postComplete: consoleControlStrings.color('stopInverse'),
9378 preRemaining: consoleControlStrings.color('brightBlack'),
9379 remaining: '░',
9380 postRemaining: consoleControlStrings.color('reset')
9381 }
9382});
9383
9384themes.setDefault({}, 'ASCII');
9385themes.setDefault({hasColor: true}, 'colorASCII');
9386themes.setDefault({platform: 'darwin', hasUnicode: true}, 'brailleSpinner');
9387themes.setDefault({platform: 'darwin', hasUnicode: true, hasColor: true}, 'colorBrailleSpinner');
9388});
9389
9390// this exists so we can replace it during testing
9391var setInterval_1 = setInterval;
9392
9393// this exists so we can replace it during testing
9394var process_1 = process;
9395
9396var setImmediate_1 = createCommonjsModule(function (module) {
9397
9398try {
9399 module.exports = setImmediate;
9400} catch (ex) {
9401 module.exports = process_1.nextTick;
9402}
9403});
9404
9405var gauge = Gauge;
9406
9407function callWith (obj, method) {
9408 return function () {
9409 return method.call(obj)
9410 }
9411}
9412
9413function Gauge (arg1, arg2) {
9414 var options, writeTo;
9415 if (arg1 && arg1.write) {
9416 writeTo = arg1;
9417 options = arg2 || {};
9418 } else if (arg2 && arg2.write) {
9419 writeTo = arg2;
9420 options = arg1 || {};
9421 } else {
9422 writeTo = process_1.stderr;
9423 options = arg1 || arg2 || {};
9424 }
9425
9426 this._status = {
9427 spun: 0,
9428 section: '',
9429 subsection: ''
9430 };
9431 this._paused = false; // are we paused for back pressure?
9432 this._disabled = true; // are all progress bar updates disabled?
9433 this._showing = false; // do we WANT the progress bar on screen
9434 this._onScreen = false; // IS the progress bar on screen
9435 this._needsRedraw = false; // should we print something at next tick?
9436 this._hideCursor = options.hideCursor == null ? true : options.hideCursor;
9437 this._fixedFramerate = options.fixedFramerate == null
9438 ? !(/^v0\.8\./.test(process_1.version))
9439 : options.fixedFramerate;
9440 this._lastUpdateAt = null;
9441 this._updateInterval = options.updateInterval == null ? 50 : options.updateInterval;
9442
9443 this._themes = options.themes || themes_1;
9444 this._theme = options.theme;
9445 var theme = this._computeTheme(options.theme);
9446 var template = options.template || [
9447 {type: 'progressbar', length: 20},
9448 {type: 'activityIndicator', kerning: 1, length: 1},
9449 {type: 'section', kerning: 1, default: ''},
9450 {type: 'subsection', kerning: 1, default: ''}
9451 ];
9452 this.setWriteTo(writeTo, options.tty);
9453 var PlumbingClass = options.Plumbing || plumbing;
9454 this._gauge = new PlumbingClass(theme, template, this.getWidth());
9455
9456 this._$$doRedraw = callWith(this, this._doRedraw);
9457 this._$$handleSizeChange = callWith(this, this._handleSizeChange);
9458
9459 this._cleanupOnExit = options.cleanupOnExit == null || options.cleanupOnExit;
9460 this._removeOnExit = null;
9461
9462 if (options.enabled || (options.enabled == null && this._tty && this._tty.isTTY)) {
9463 this.enable();
9464 } else {
9465 this.disable();
9466 }
9467}
9468Gauge.prototype = {};
9469
9470Gauge.prototype.isEnabled = function () {
9471 return !this._disabled
9472};
9473
9474Gauge.prototype.setTemplate = function (template) {
9475 this._gauge.setTemplate(template);
9476 if (this._showing) this._requestRedraw();
9477};
9478
9479Gauge.prototype._computeTheme = function (theme) {
9480 if (!theme) theme = {};
9481 if (typeof theme === 'string') {
9482 theme = this._themes.getTheme(theme);
9483 } else if (theme && (Object.keys(theme).length === 0 || theme.hasUnicode != null || theme.hasColor != null)) {
9484 var useUnicode = theme.hasUnicode == null ? hasUnicode_1() : theme.hasUnicode;
9485 var useColor = theme.hasColor == null ? hasColor : theme.hasColor;
9486 theme = this._themes.getDefault({hasUnicode: useUnicode, hasColor: useColor, platform: theme.platform});
9487 }
9488 return theme
9489};
9490
9491Gauge.prototype.setThemeset = function (themes) {
9492 this._themes = themes;
9493 this.setTheme(this._theme);
9494};
9495
9496Gauge.prototype.setTheme = function (theme) {
9497 this._gauge.setTheme(this._computeTheme(theme));
9498 if (this._showing) this._requestRedraw();
9499 this._theme = theme;
9500};
9501
9502Gauge.prototype._requestRedraw = function () {
9503 this._needsRedraw = true;
9504 if (!this._fixedFramerate) this._doRedraw();
9505};
9506
9507Gauge.prototype.getWidth = function () {
9508 return ((this._tty && this._tty.columns) || 80) - 1
9509};
9510
9511Gauge.prototype.setWriteTo = function (writeTo, tty$$1) {
9512 var enabled = !this._disabled;
9513 if (enabled) this.disable();
9514 this._writeTo = writeTo;
9515 this._tty = tty$$1 ||
9516 (writeTo === process_1.stderr && process_1.stdout.isTTY && process_1.stdout) ||
9517 (writeTo.isTTY && writeTo) ||
9518 this._tty;
9519 if (this._gauge) this._gauge.setWidth(this.getWidth());
9520 if (enabled) this.enable();
9521};
9522
9523Gauge.prototype.enable = function () {
9524 if (!this._disabled) return
9525 this._disabled = false;
9526 if (this._tty) this._enableEvents();
9527 if (this._showing) this.show();
9528};
9529
9530Gauge.prototype.disable = function () {
9531 if (this._disabled) return
9532 if (this._showing) {
9533 this._lastUpdateAt = null;
9534 this._showing = false;
9535 this._doRedraw();
9536 this._showing = true;
9537 }
9538 this._disabled = true;
9539 if (this._tty) this._disableEvents();
9540};
9541
9542Gauge.prototype._enableEvents = function () {
9543 if (this._cleanupOnExit) {
9544 this._removeOnExit = signalExit(callWith(this, this.disable));
9545 }
9546 this._tty.on('resize', this._$$handleSizeChange);
9547 if (this._fixedFramerate) {
9548 this.redrawTracker = setInterval_1(this._$$doRedraw, this._updateInterval);
9549 if (this.redrawTracker.unref) this.redrawTracker.unref();
9550 }
9551};
9552
9553Gauge.prototype._disableEvents = function () {
9554 this._tty.removeListener('resize', this._$$handleSizeChange);
9555 if (this._fixedFramerate) clearInterval(this.redrawTracker);
9556 if (this._removeOnExit) this._removeOnExit();
9557};
9558
9559Gauge.prototype.hide = function (cb) {
9560 if (this._disabled) return cb && process_1.nextTick(cb)
9561 if (!this._showing) return cb && process_1.nextTick(cb)
9562 this._showing = false;
9563 this._doRedraw();
9564 cb && setImmediate_1(cb);
9565};
9566
9567Gauge.prototype.show = function (section, completed) {
9568 this._showing = true;
9569 if (typeof section === 'string') {
9570 this._status.section = section;
9571 } else if (typeof section === 'object') {
9572 var sectionKeys = Object.keys(section);
9573 for (var ii = 0; ii < sectionKeys.length; ++ii) {
9574 var key = sectionKeys[ii];
9575 this._status[key] = section[key];
9576 }
9577 }
9578 if (completed != null) this._status.completed = completed;
9579 if (this._disabled) return
9580 this._requestRedraw();
9581};
9582
9583Gauge.prototype.pulse = function (subsection) {
9584 this._status.subsection = subsection || '';
9585 this._status.spun ++;
9586 if (this._disabled) return
9587 if (!this._showing) return
9588 this._requestRedraw();
9589};
9590
9591Gauge.prototype._handleSizeChange = function () {
9592 this._gauge.setWidth(this._tty.columns - 1);
9593 this._requestRedraw();
9594};
9595
9596Gauge.prototype._doRedraw = function () {
9597 if (this._disabled || this._paused) return
9598 if (!this._fixedFramerate) {
9599 var now = Date.now();
9600 if (this._lastUpdateAt && now - this._lastUpdateAt < this._updateInterval) return
9601 this._lastUpdateAt = now;
9602 }
9603 if (!this._showing && this._onScreen) {
9604 this._onScreen = false;
9605 var result = this._gauge.hide();
9606 if (this._hideCursor) {
9607 result += this._gauge.showCursor();
9608 }
9609 return this._writeTo.write(result)
9610 }
9611 if (!this._showing && !this._onScreen) return
9612 if (this._showing && !this._onScreen) {
9613 this._onScreen = true;
9614 this._needsRedraw = true;
9615 if (this._hideCursor) {
9616 this._writeTo.write(this._gauge.hideCursor());
9617 }
9618 }
9619 if (!this._needsRedraw) return
9620 if (!this._writeTo.write(this._gauge.show(this._status))) {
9621 this._paused = true;
9622 this._writeTo.on('drain', callWith(this, function () {
9623 this._paused = false;
9624 this._doRedraw();
9625 }));
9626 }
9627};
9628
9629const { FORCE_COLOR, NODE_DISABLE_COLORS, TERM } = process.env;
9630
9631const $ = {
9632 enabled: !NODE_DISABLE_COLORS && TERM !== 'dumb' && FORCE_COLOR !== '0'
9633};
9634
9635const CODES = {
9636 // modifiers
9637 reset: code(0, 0),
9638 bold: code(1, 22),
9639 dim: code(2, 22),
9640 italic: code(3, 23),
9641 underline: code(4, 24),
9642 inverse: code(7, 27),
9643 hidden: code(8, 28),
9644 strikethrough: code(9, 29),
9645
9646 // colors
9647 black: code(30, 39),
9648 red: code(31, 39),
9649 green: code(32, 39),
9650 yellow: code(33, 39),
9651 blue: code(34, 39),
9652 magenta: code(35, 39),
9653 cyan: code(36, 39),
9654 white: code(37, 39),
9655 gray: code(90, 39),
9656
9657 // background colors
9658 bgBlack: code(40, 49),
9659 bgRed: code(41, 49),
9660 bgGreen: code(42, 49),
9661 bgYellow: code(43, 49),
9662 bgBlue: code(44, 49),
9663 bgMagenta: code(45, 49),
9664 bgCyan: code(46, 49),
9665 bgWhite: code(47, 49)
9666};
9667
9668function code(open, close) {
9669 return {
9670 open: `\x1b[${open}m`,
9671 close: `\x1b[${close}m`,
9672 rgx: new RegExp(`\\x1b\\[${close}m`, 'g')
9673 };
9674}
9675
9676function run(arr, str) {
9677 let i=0, tmp={};
9678 for (; i < arr.length;) {
9679 tmp = Reflect.get(CODES, arr[i++]);
9680 str = tmp.open + str.replace(tmp.rgx, tmp.open) + tmp.close;
9681 }
9682 return str;
9683}
9684
9685function chain(keys) {
9686 let ctx = { keys };
9687
9688 ctx.reset = $.reset.bind(ctx);
9689 ctx.bold = $.bold.bind(ctx);
9690 ctx.dim = $.dim.bind(ctx);
9691 ctx.italic = $.italic.bind(ctx);
9692 ctx.underline = $.underline.bind(ctx);
9693 ctx.inverse = $.inverse.bind(ctx);
9694 ctx.hidden = $.hidden.bind(ctx);
9695 ctx.strikethrough = $.strikethrough.bind(ctx);
9696
9697 ctx.black = $.black.bind(ctx);
9698 ctx.red = $.red.bind(ctx);
9699 ctx.green = $.green.bind(ctx);
9700 ctx.yellow = $.yellow.bind(ctx);
9701 ctx.blue = $.blue.bind(ctx);
9702 ctx.magenta = $.magenta.bind(ctx);
9703 ctx.cyan = $.cyan.bind(ctx);
9704 ctx.white = $.white.bind(ctx);
9705 ctx.gray = $.gray.bind(ctx);
9706
9707 ctx.bgBlack = $.bgBlack.bind(ctx);
9708 ctx.bgRed = $.bgRed.bind(ctx);
9709 ctx.bgGreen = $.bgGreen.bind(ctx);
9710 ctx.bgYellow = $.bgYellow.bind(ctx);
9711 ctx.bgBlue = $.bgBlue.bind(ctx);
9712 ctx.bgMagenta = $.bgMagenta.bind(ctx);
9713 ctx.bgCyan = $.bgCyan.bind(ctx);
9714 ctx.bgWhite = $.bgWhite.bind(ctx);
9715
9716 return ctx;
9717}
9718
9719function init(key) {
9720 return function (txt) {
9721 let isChain = !!this.keys;
9722 if (isChain) this.keys.includes(key) || this.keys.push(key);
9723 if (txt !== void 0) return $.enabled ? run(isChain ? this.keys : [key], txt+'') : txt+'';
9724 return isChain ? this : chain([key]);
9725 };
9726}
9727
9728for (let key in CODES) {
9729 Object.defineProperty($, key, {
9730 value: init(key),
9731 enumerable: true,
9732 writable: false
9733 });
9734}
9735
9736var kleur = $;
9737
9738const processFn = (fn, opts) => function () {
9739 const P = opts.promiseModule;
9740 const args = new Array(arguments.length);
9741
9742 for (let i = 0; i < arguments.length; i++) {
9743 args[i] = arguments[i];
9744 }
9745
9746 return new P((resolve, reject) => {
9747 if (opts.errorFirst) {
9748 args.push(function (err, result) {
9749 if (opts.multiArgs) {
9750 const results = new Array(arguments.length - 1);
9751
9752 for (let i = 1; i < arguments.length; i++) {
9753 results[i - 1] = arguments[i];
9754 }
9755
9756 if (err) {
9757 results.unshift(err);
9758 reject(results);
9759 } else {
9760 resolve(results);
9761 }
9762 } else if (err) {
9763 reject(err);
9764 } else {
9765 resolve(result);
9766 }
9767 });
9768 } else {
9769 args.push(function (result) {
9770 if (opts.multiArgs) {
9771 const results = new Array(arguments.length - 1);
9772
9773 for (let i = 0; i < arguments.length; i++) {
9774 results[i] = arguments[i];
9775 }
9776
9777 resolve(results);
9778 } else {
9779 resolve(result);
9780 }
9781 });
9782 }
9783
9784 fn.apply(this, args);
9785 });
9786};
9787
9788var pify = (obj, opts) => {
9789 opts = Object.assign({
9790 exclude: [/.+(Sync|Stream)$/],
9791 errorFirst: true,
9792 promiseModule: Promise
9793 }, opts);
9794
9795 const filter = key => {
9796 const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key);
9797 return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
9798 };
9799
9800 let ret;
9801 if (typeof obj === 'function') {
9802 ret = function () {
9803 if (opts.excludeMain) {
9804 return obj.apply(this, arguments);
9805 }
9806
9807 return processFn(obj, opts).apply(this, arguments);
9808 };
9809 } else {
9810 ret = Object.create(Object.getPrototypeOf(obj));
9811 }
9812
9813 for (const key in obj) { // eslint-disable-line guard-for-in
9814 const x = obj[key];
9815 ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x;
9816 }
9817
9818 return ret;
9819};
9820
9821const defaults$2 = {
9822 mode: 0o777 & (~process.umask()),
9823 fs
9824};
9825
9826// https://github.com/nodejs/node/issues/8987
9827// https://github.com/libuv/libuv/pull/1088
9828const checkPath = pth => {
9829 if (process.platform === 'win32') {
9830 const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, ''));
9831
9832 if (pathHasInvalidWinCharacters) {
9833 const err = new Error(`Path contains invalid characters: ${pth}`);
9834 err.code = 'EINVAL';
9835 throw err;
9836 }
9837 }
9838};
9839
9840var makeDir = (input, opts) => Promise.resolve().then(() => {
9841 checkPath(input);
9842 opts = Object.assign({}, defaults$2, opts);
9843
9844 const mkdir = pify(opts.fs.mkdir);
9845 const stat = pify(opts.fs.stat);
9846
9847 const make = pth => {
9848 return mkdir(pth, opts.mode)
9849 .then(() => pth)
9850 .catch(err => {
9851 if (err.code === 'ENOENT') {
9852 if (err.message.includes('null bytes') || path.dirname(pth) === pth) {
9853 throw err;
9854 }
9855
9856 return make(path.dirname(pth)).then(() => make(pth));
9857 }
9858
9859 return stat(pth)
9860 .then(stats => stats.isDirectory() ? pth : Promise.reject())
9861 .catch(() => {
9862 throw err;
9863 });
9864 });
9865 };
9866
9867 return make(path.resolve(input));
9868});
9869
9870var sync = (input, opts) => {
9871 checkPath(input);
9872 opts = Object.assign({}, defaults$2, opts);
9873
9874 const make = pth => {
9875 try {
9876 opts.fs.mkdirSync(pth, opts.mode);
9877 } catch (err) {
9878 if (err.code === 'ENOENT') {
9879 if (err.message.includes('null bytes') || path.dirname(pth) === pth) {
9880 throw err;
9881 }
9882
9883 make(path.dirname(pth));
9884 return make(pth);
9885 }
9886
9887 try {
9888 if (!opts.fs.statSync(pth).isDirectory()) {
9889 throw new Error('The path is not a directory');
9890 }
9891 } catch (_) {
9892 throw err;
9893 }
9894 }
9895
9896 return pth;
9897 };
9898
9899 return make(path.resolve(input));
9900};
9901makeDir.sync = sync;
9902
9903const UNITS = [
9904 'B',
9905 'kB',
9906 'MB',
9907 'GB',
9908 'TB',
9909 'PB',
9910 'EB',
9911 'ZB',
9912 'YB'
9913];
9914
9915/*
9916Formats the given number using `Number#toLocaleString`.
9917- If locale is a string, the value is expected to be a locale-key (for example: `de`).
9918- If locale is true, the system default locale is used for translation.
9919- If no value for locale is specified, the number is returned unmodified.
9920*/
9921const toLocaleString = (number, locale) => {
9922 let result = number;
9923 if (typeof locale === 'string') {
9924 result = number.toLocaleString(locale);
9925 } else if (locale === true) {
9926 result = number.toLocaleString();
9927 }
9928
9929 return result;
9930};
9931
9932var prettyBytes = (number, options) => {
9933 if (!Number.isFinite(number)) {
9934 throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
9935 }
9936
9937 options = Object.assign({}, options);
9938
9939 if (options.signed && number === 0) {
9940 return ' 0 B';
9941 }
9942
9943 const isNegative = number < 0;
9944 const prefix = isNegative ? '-' : (options.signed ? '+' : '');
9945
9946 if (isNegative) {
9947 number = -number;
9948 }
9949
9950 if (number < 1) {
9951 const numberString = toLocaleString(number, options.locale);
9952 return prefix + numberString + ' B';
9953 }
9954
9955 const exponent = Math.min(Math.floor(Math.log10(number) / 3), UNITS.length - 1);
9956 number = Number((number / Math.pow(1000, exponent)).toPrecision(3));
9957 const numberString = toLocaleString(number, options.locale);
9958
9959 const unit = UNITS[exponent];
9960
9961 return prefix + numberString + ' ' + unit;
9962};
9963
9964var semver = createCommonjsModule(function (module, exports) {
9965exports = module.exports = SemVer;
9966
9967// The debug function is excluded entirely from the minified version.
9968/* nomin */ var debug;
9969/* nomin */ if (typeof process === 'object' &&
9970 /* nomin */ process.env &&
9971 /* nomin */ process.env.NODE_DEBUG &&
9972 /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG))
9973 /* nomin */ debug = function() {
9974 /* nomin */ var args = Array.prototype.slice.call(arguments, 0);
9975 /* nomin */ args.unshift('SEMVER');
9976 /* nomin */ console.log.apply(console, args);
9977 /* nomin */ };
9978/* nomin */ else
9979 /* nomin */ debug = function() {};
9980
9981// Note: this is the semver.org version of the spec that it implements
9982// Not necessarily the package version of this code.
9983exports.SEMVER_SPEC_VERSION = '2.0.0';
9984
9985var MAX_LENGTH = 256;
9986var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
9987
9988// Max safe segment length for coercion.
9989var MAX_SAFE_COMPONENT_LENGTH = 16;
9990
9991// The actual regexps go on exports.re
9992var re = exports.re = [];
9993var src = exports.src = [];
9994var R = 0;
9995
9996// The following Regular Expressions can be used for tokenizing,
9997// validating, and parsing SemVer version strings.
9998
9999// ## Numeric Identifier
10000// A single `0`, or a non-zero digit followed by zero or more digits.
10001
10002var NUMERICIDENTIFIER = R++;
10003src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
10004var NUMERICIDENTIFIERLOOSE = R++;
10005src[NUMERICIDENTIFIERLOOSE] = '[0-9]+';
10006
10007
10008// ## Non-numeric Identifier
10009// Zero or more digits, followed by a letter or hyphen, and then zero or
10010// more letters, digits, or hyphens.
10011
10012var NONNUMERICIDENTIFIER = R++;
10013src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*';
10014
10015
10016// ## Main Version
10017// Three dot-separated numeric identifiers.
10018
10019var MAINVERSION = R++;
10020src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' +
10021 '(' + src[NUMERICIDENTIFIER] + ')\\.' +
10022 '(' + src[NUMERICIDENTIFIER] + ')';
10023
10024var MAINVERSIONLOOSE = R++;
10025src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
10026 '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
10027 '(' + src[NUMERICIDENTIFIERLOOSE] + ')';
10028
10029// ## Pre-release Version Identifier
10030// A numeric identifier, or a non-numeric identifier.
10031
10032var PRERELEASEIDENTIFIER = R++;
10033src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] +
10034 '|' + src[NONNUMERICIDENTIFIER] + ')';
10035
10036var PRERELEASEIDENTIFIERLOOSE = R++;
10037src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] +
10038 '|' + src[NONNUMERICIDENTIFIER] + ')';
10039
10040
10041// ## Pre-release Version
10042// Hyphen, followed by one or more dot-separated pre-release version
10043// identifiers.
10044
10045var PRERELEASE = R++;
10046src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] +
10047 '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
10048
10049var PRERELEASELOOSE = R++;
10050src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] +
10051 '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))';
10052
10053// ## Build Metadata Identifier
10054// Any combination of digits, letters, or hyphens.
10055
10056var BUILDIDENTIFIER = R++;
10057src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+';
10058
10059// ## Build Metadata
10060// Plus sign, followed by one or more period-separated build metadata
10061// identifiers.
10062
10063var BUILD = R++;
10064src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] +
10065 '(?:\\.' + src[BUILDIDENTIFIER] + ')*))';
10066
10067
10068// ## Full Version String
10069// A main version, followed optionally by a pre-release version and
10070// build metadata.
10071
10072// Note that the only major, minor, patch, and pre-release sections of
10073// the version string are capturing groups. The build metadata is not a
10074// capturing group, because it should not ever be used in version
10075// comparison.
10076
10077var FULL = R++;
10078var FULLPLAIN = 'v?' + src[MAINVERSION] +
10079 src[PRERELEASE] + '?' +
10080 src[BUILD] + '?';
10081
10082src[FULL] = '^' + FULLPLAIN + '$';
10083
10084// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
10085// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
10086// common in the npm registry.
10087var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] +
10088 src[PRERELEASELOOSE] + '?' +
10089 src[BUILD] + '?';
10090
10091var LOOSE = R++;
10092src[LOOSE] = '^' + LOOSEPLAIN + '$';
10093
10094var GTLT = R++;
10095src[GTLT] = '((?:<|>)?=?)';
10096
10097// Something like "2.*" or "1.2.x".
10098// Note that "x.x" is a valid xRange identifer, meaning "any version"
10099// Only the first item is strictly required.
10100var XRANGEIDENTIFIERLOOSE = R++;
10101src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
10102var XRANGEIDENTIFIER = R++;
10103src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
10104
10105var XRANGEPLAIN = R++;
10106src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' +
10107 '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
10108 '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
10109 '(?:' + src[PRERELEASE] + ')?' +
10110 src[BUILD] + '?' +
10111 ')?)?';
10112
10113var XRANGEPLAINLOOSE = R++;
10114src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
10115 '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
10116 '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
10117 '(?:' + src[PRERELEASELOOSE] + ')?' +
10118 src[BUILD] + '?' +
10119 ')?)?';
10120
10121var XRANGE = R++;
10122src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
10123var XRANGELOOSE = R++;
10124src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$';
10125
10126// Coercion.
10127// Extract anything that could conceivably be a part of a valid semver
10128var COERCE = R++;
10129src[COERCE] = '(?:^|[^\\d])' +
10130 '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +
10131 '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
10132 '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
10133 '(?:$|[^\\d])';
10134
10135// Tilde ranges.
10136// Meaning is "reasonably at or greater than"
10137var LONETILDE = R++;
10138src[LONETILDE] = '(?:~>?)';
10139
10140var TILDETRIM = R++;
10141src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
10142re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
10143var tildeTrimReplace = '$1~';
10144
10145var TILDE = R++;
10146src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
10147var TILDELOOSE = R++;
10148src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$';
10149
10150// Caret ranges.
10151// Meaning is "at least and backwards compatible with"
10152var LONECARET = R++;
10153src[LONECARET] = '(?:\\^)';
10154
10155var CARETTRIM = R++;
10156src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
10157re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
10158var caretTrimReplace = '$1^';
10159
10160var CARET = R++;
10161src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
10162var CARETLOOSE = R++;
10163src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$';
10164
10165// A simple gt/lt/eq thing, or just "" to indicate "any version"
10166var COMPARATORLOOSE = R++;
10167src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
10168var COMPARATOR = R++;
10169src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$';
10170
10171
10172// An expression to strip any whitespace between the gtlt and the thing
10173// it modifies, so that `> 1.2.3` ==> `>1.2.3`
10174var COMPARATORTRIM = R++;
10175src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] +
10176 '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')';
10177
10178// this one has to use the /g flag
10179re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
10180var comparatorTrimReplace = '$1$2$3';
10181
10182
10183// Something like `1.2.3 - 1.2.4`
10184// Note that these all use the loose form, because they'll be
10185// checked against either the strict or loose comparator form
10186// later.
10187var HYPHENRANGE = R++;
10188src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' +
10189 '\\s+-\\s+' +
10190 '(' + src[XRANGEPLAIN] + ')' +
10191 '\\s*$';
10192
10193var HYPHENRANGELOOSE = R++;
10194src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' +
10195 '\\s+-\\s+' +
10196 '(' + src[XRANGEPLAINLOOSE] + ')' +
10197 '\\s*$';
10198
10199// Star ranges basically just allow anything at all.
10200var STAR = R++;
10201src[STAR] = '(<|>)?=?\\s*\\*';
10202
10203// Compile to actual regexp objects.
10204// All are flag-free, unless they were created above with a flag.
10205for (var i = 0; i < R; i++) {
10206 debug(i, src[i]);
10207 if (!re[i])
10208 re[i] = new RegExp(src[i]);
10209}
10210
10211exports.parse = parse;
10212function parse(version, options) {
10213 if (!options || typeof options !== 'object')
10214 options = { loose: !!options, includePrerelease: false };
10215
10216 if (version instanceof SemVer)
10217 return version;
10218
10219 if (typeof version !== 'string')
10220 return null;
10221
10222 if (version.length > MAX_LENGTH)
10223 return null;
10224
10225 var r = options.loose ? re[LOOSE] : re[FULL];
10226 if (!r.test(version))
10227 return null;
10228
10229 try {
10230 return new SemVer(version, options);
10231 } catch (er) {
10232 return null;
10233 }
10234}
10235
10236exports.valid = valid;
10237function valid(version, options) {
10238 var v = parse(version, options);
10239 return v ? v.version : null;
10240}
10241
10242
10243exports.clean = clean;
10244function clean(version, options) {
10245 var s = parse(version.trim().replace(/^[=v]+/, ''), options);
10246 return s ? s.version : null;
10247}
10248
10249exports.SemVer = SemVer;
10250
10251function SemVer(version, options) {
10252 if (!options || typeof options !== 'object')
10253 options = { loose: !!options, includePrerelease: false };
10254 if (version instanceof SemVer) {
10255 if (version.loose === options.loose)
10256 return version;
10257 else
10258 version = version.version;
10259 } else if (typeof version !== 'string') {
10260 throw new TypeError('Invalid Version: ' + version);
10261 }
10262
10263 if (version.length > MAX_LENGTH)
10264 throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')
10265
10266 if (!(this instanceof SemVer))
10267 return new SemVer(version, options);
10268
10269 debug('SemVer', version, options);
10270 this.options = options;
10271 this.loose = !!options.loose;
10272
10273 var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]);
10274
10275 if (!m)
10276 throw new TypeError('Invalid Version: ' + version);
10277
10278 this.raw = version;
10279
10280 // these are actually numbers
10281 this.major = +m[1];
10282 this.minor = +m[2];
10283 this.patch = +m[3];
10284
10285 if (this.major > MAX_SAFE_INTEGER || this.major < 0)
10286 throw new TypeError('Invalid major version')
10287
10288 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0)
10289 throw new TypeError('Invalid minor version')
10290
10291 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0)
10292 throw new TypeError('Invalid patch version')
10293
10294 // numberify any prerelease numeric ids
10295 if (!m[4])
10296 this.prerelease = [];
10297 else
10298 this.prerelease = m[4].split('.').map(function(id) {
10299 if (/^[0-9]+$/.test(id)) {
10300 var num = +id;
10301 if (num >= 0 && num < MAX_SAFE_INTEGER)
10302 return num;
10303 }
10304 return id;
10305 });
10306
10307 this.build = m[5] ? m[5].split('.') : [];
10308 this.format();
10309}
10310
10311SemVer.prototype.format = function() {
10312 this.version = this.major + '.' + this.minor + '.' + this.patch;
10313 if (this.prerelease.length)
10314 this.version += '-' + this.prerelease.join('.');
10315 return this.version;
10316};
10317
10318SemVer.prototype.toString = function() {
10319 return this.version;
10320};
10321
10322SemVer.prototype.compare = function(other) {
10323 debug('SemVer.compare', this.version, this.options, other);
10324 if (!(other instanceof SemVer))
10325 other = new SemVer(other, this.options);
10326
10327 return this.compareMain(other) || this.comparePre(other);
10328};
10329
10330SemVer.prototype.compareMain = function(other) {
10331 if (!(other instanceof SemVer))
10332 other = new SemVer(other, this.options);
10333
10334 return compareIdentifiers(this.major, other.major) ||
10335 compareIdentifiers(this.minor, other.minor) ||
10336 compareIdentifiers(this.patch, other.patch);
10337};
10338
10339SemVer.prototype.comparePre = function(other) {
10340 if (!(other instanceof SemVer))
10341 other = new SemVer(other, this.options);
10342
10343 // NOT having a prerelease is > having one
10344 if (this.prerelease.length && !other.prerelease.length)
10345 return -1;
10346 else if (!this.prerelease.length && other.prerelease.length)
10347 return 1;
10348 else if (!this.prerelease.length && !other.prerelease.length)
10349 return 0;
10350
10351 var i = 0;
10352 do {
10353 var a = this.prerelease[i];
10354 var b = other.prerelease[i];
10355 debug('prerelease compare', i, a, b);
10356 if (a === undefined && b === undefined)
10357 return 0;
10358 else if (b === undefined)
10359 return 1;
10360 else if (a === undefined)
10361 return -1;
10362 else if (a === b)
10363 continue;
10364 else
10365 return compareIdentifiers(a, b);
10366 } while (++i);
10367};
10368
10369// preminor will bump the version up to the next minor release, and immediately
10370// down to pre-release. premajor and prepatch work the same way.
10371SemVer.prototype.inc = function(release, identifier) {
10372 switch (release) {
10373 case 'premajor':
10374 this.prerelease.length = 0;
10375 this.patch = 0;
10376 this.minor = 0;
10377 this.major++;
10378 this.inc('pre', identifier);
10379 break;
10380 case 'preminor':
10381 this.prerelease.length = 0;
10382 this.patch = 0;
10383 this.minor++;
10384 this.inc('pre', identifier);
10385 break;
10386 case 'prepatch':
10387 // If this is already a prerelease, it will bump to the next version
10388 // drop any prereleases that might already exist, since they are not
10389 // relevant at this point.
10390 this.prerelease.length = 0;
10391 this.inc('patch', identifier);
10392 this.inc('pre', identifier);
10393 break;
10394 // If the input is a non-prerelease version, this acts the same as
10395 // prepatch.
10396 case 'prerelease':
10397 if (this.prerelease.length === 0)
10398 this.inc('patch', identifier);
10399 this.inc('pre', identifier);
10400 break;
10401
10402 case 'major':
10403 // If this is a pre-major version, bump up to the same major version.
10404 // Otherwise increment major.
10405 // 1.0.0-5 bumps to 1.0.0
10406 // 1.1.0 bumps to 2.0.0
10407 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0)
10408 this.major++;
10409 this.minor = 0;
10410 this.patch = 0;
10411 this.prerelease = [];
10412 break;
10413 case 'minor':
10414 // If this is a pre-minor version, bump up to the same minor version.
10415 // Otherwise increment minor.
10416 // 1.2.0-5 bumps to 1.2.0
10417 // 1.2.1 bumps to 1.3.0
10418 if (this.patch !== 0 || this.prerelease.length === 0)
10419 this.minor++;
10420 this.patch = 0;
10421 this.prerelease = [];
10422 break;
10423 case 'patch':
10424 // If this is not a pre-release version, it will increment the patch.
10425 // If it is a pre-release it will bump up to the same patch version.
10426 // 1.2.0-5 patches to 1.2.0
10427 // 1.2.0 patches to 1.2.1
10428 if (this.prerelease.length === 0)
10429 this.patch++;
10430 this.prerelease = [];
10431 break;
10432 // This probably shouldn't be used publicly.
10433 // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
10434 case 'pre':
10435 if (this.prerelease.length === 0)
10436 this.prerelease = [0];
10437 else {
10438 var i = this.prerelease.length;
10439 while (--i >= 0) {
10440 if (typeof this.prerelease[i] === 'number') {
10441 this.prerelease[i]++;
10442 i = -2;
10443 }
10444 }
10445 if (i === -1) // didn't increment anything
10446 this.prerelease.push(0);
10447 }
10448 if (identifier) {
10449 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
10450 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
10451 if (this.prerelease[0] === identifier) {
10452 if (isNaN(this.prerelease[1]))
10453 this.prerelease = [identifier, 0];
10454 } else
10455 this.prerelease = [identifier, 0];
10456 }
10457 break;
10458
10459 default:
10460 throw new Error('invalid increment argument: ' + release);
10461 }
10462 this.format();
10463 this.raw = this.version;
10464 return this;
10465};
10466
10467exports.inc = inc;
10468function inc(version, release, loose, identifier) {
10469 if (typeof(loose) === 'string') {
10470 identifier = loose;
10471 loose = undefined;
10472 }
10473
10474 try {
10475 return new SemVer(version, loose).inc(release, identifier).version;
10476 } catch (er) {
10477 return null;
10478 }
10479}
10480
10481exports.diff = diff;
10482function diff(version1, version2) {
10483 if (eq(version1, version2)) {
10484 return null;
10485 } else {
10486 var v1 = parse(version1);
10487 var v2 = parse(version2);
10488 if (v1.prerelease.length || v2.prerelease.length) {
10489 for (var key in v1) {
10490 if (key === 'major' || key === 'minor' || key === 'patch') {
10491 if (v1[key] !== v2[key]) {
10492 return 'pre'+key;
10493 }
10494 }
10495 }
10496 return 'prerelease';
10497 }
10498 for (var key in v1) {
10499 if (key === 'major' || key === 'minor' || key === 'patch') {
10500 if (v1[key] !== v2[key]) {
10501 return key;
10502 }
10503 }
10504 }
10505 }
10506}
10507
10508exports.compareIdentifiers = compareIdentifiers;
10509
10510var numeric = /^[0-9]+$/;
10511function compareIdentifiers(a, b) {
10512 var anum = numeric.test(a);
10513 var bnum = numeric.test(b);
10514
10515 if (anum && bnum) {
10516 a = +a;
10517 b = +b;
10518 }
10519
10520 return (anum && !bnum) ? -1 :
10521 (bnum && !anum) ? 1 :
10522 a < b ? -1 :
10523 a > b ? 1 :
10524 0;
10525}
10526
10527exports.rcompareIdentifiers = rcompareIdentifiers;
10528function rcompareIdentifiers(a, b) {
10529 return compareIdentifiers(b, a);
10530}
10531
10532exports.major = major;
10533function major(a, loose) {
10534 return new SemVer(a, loose).major;
10535}
10536
10537exports.minor = minor;
10538function minor(a, loose) {
10539 return new SemVer(a, loose).minor;
10540}
10541
10542exports.patch = patch;
10543function patch(a, loose) {
10544 return new SemVer(a, loose).patch;
10545}
10546
10547exports.compare = compare;
10548function compare(a, b, loose) {
10549 return new SemVer(a, loose).compare(new SemVer(b, loose));
10550}
10551
10552exports.compareLoose = compareLoose;
10553function compareLoose(a, b) {
10554 return compare(a, b, true);
10555}
10556
10557exports.rcompare = rcompare;
10558function rcompare(a, b, loose) {
10559 return compare(b, a, loose);
10560}
10561
10562exports.sort = sort;
10563function sort(list, loose) {
10564 return list.sort(function(a, b) {
10565 return exports.compare(a, b, loose);
10566 });
10567}
10568
10569exports.rsort = rsort;
10570function rsort(list, loose) {
10571 return list.sort(function(a, b) {
10572 return exports.rcompare(a, b, loose);
10573 });
10574}
10575
10576exports.gt = gt;
10577function gt(a, b, loose) {
10578 return compare(a, b, loose) > 0;
10579}
10580
10581exports.lt = lt;
10582function lt(a, b, loose) {
10583 return compare(a, b, loose) < 0;
10584}
10585
10586exports.eq = eq;
10587function eq(a, b, loose) {
10588 return compare(a, b, loose) === 0;
10589}
10590
10591exports.neq = neq;
10592function neq(a, b, loose) {
10593 return compare(a, b, loose) !== 0;
10594}
10595
10596exports.gte = gte;
10597function gte(a, b, loose) {
10598 return compare(a, b, loose) >= 0;
10599}
10600
10601exports.lte = lte;
10602function lte(a, b, loose) {
10603 return compare(a, b, loose) <= 0;
10604}
10605
10606exports.cmp = cmp;
10607function cmp(a, op, b, loose) {
10608 var ret;
10609 switch (op) {
10610 case '===':
10611 if (typeof a === 'object') a = a.version;
10612 if (typeof b === 'object') b = b.version;
10613 ret = a === b;
10614 break;
10615 case '!==':
10616 if (typeof a === 'object') a = a.version;
10617 if (typeof b === 'object') b = b.version;
10618 ret = a !== b;
10619 break;
10620 case '': case '=': case '==': ret = eq(a, b, loose); break;
10621 case '!=': ret = neq(a, b, loose); break;
10622 case '>': ret = gt(a, b, loose); break;
10623 case '>=': ret = gte(a, b, loose); break;
10624 case '<': ret = lt(a, b, loose); break;
10625 case '<=': ret = lte(a, b, loose); break;
10626 default: throw new TypeError('Invalid operator: ' + op);
10627 }
10628 return ret;
10629}
10630
10631exports.Comparator = Comparator;
10632function Comparator(comp, options) {
10633 if (!options || typeof options !== 'object')
10634 options = { loose: !!options, includePrerelease: false };
10635
10636 if (comp instanceof Comparator) {
10637 if (comp.loose === !!options.loose)
10638 return comp;
10639 else
10640 comp = comp.value;
10641 }
10642
10643 if (!(this instanceof Comparator))
10644 return new Comparator(comp, options);
10645
10646 debug('comparator', comp, options);
10647 this.options = options;
10648 this.loose = !!options.loose;
10649 this.parse(comp);
10650
10651 if (this.semver === ANY)
10652 this.value = '';
10653 else
10654 this.value = this.operator + this.semver.version;
10655
10656 debug('comp', this);
10657}
10658
10659var ANY = {};
10660Comparator.prototype.parse = function(comp) {
10661 var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
10662 var m = comp.match(r);
10663
10664 if (!m)
10665 throw new TypeError('Invalid comparator: ' + comp);
10666
10667 this.operator = m[1];
10668 if (this.operator === '=')
10669 this.operator = '';
10670
10671 // if it literally is just '>' or '' then allow anything.
10672 if (!m[2])
10673 this.semver = ANY;
10674 else
10675 this.semver = new SemVer(m[2], this.options.loose);
10676};
10677
10678Comparator.prototype.toString = function() {
10679 return this.value;
10680};
10681
10682Comparator.prototype.test = function(version) {
10683 debug('Comparator.test', version, this.options.loose);
10684
10685 if (this.semver === ANY)
10686 return true;
10687
10688 if (typeof version === 'string')
10689 version = new SemVer(version, this.options);
10690
10691 return cmp(version, this.operator, this.semver, this.options);
10692};
10693
10694Comparator.prototype.intersects = function(comp, options) {
10695 if (!(comp instanceof Comparator)) {
10696 throw new TypeError('a Comparator is required');
10697 }
10698
10699 if (!options || typeof options !== 'object')
10700 options = { loose: !!options, includePrerelease: false };
10701
10702 var rangeTmp;
10703
10704 if (this.operator === '') {
10705 rangeTmp = new Range(comp.value, options);
10706 return satisfies(this.value, rangeTmp, options);
10707 } else if (comp.operator === '') {
10708 rangeTmp = new Range(this.value, options);
10709 return satisfies(comp.semver, rangeTmp, options);
10710 }
10711
10712 var sameDirectionIncreasing =
10713 (this.operator === '>=' || this.operator === '>') &&
10714 (comp.operator === '>=' || comp.operator === '>');
10715 var sameDirectionDecreasing =
10716 (this.operator === '<=' || this.operator === '<') &&
10717 (comp.operator === '<=' || comp.operator === '<');
10718 var sameSemVer = this.semver.version === comp.semver.version;
10719 var differentDirectionsInclusive =
10720 (this.operator === '>=' || this.operator === '<=') &&
10721 (comp.operator === '>=' || comp.operator === '<=');
10722 var oppositeDirectionsLessThan =
10723 cmp(this.semver, '<', comp.semver, options) &&
10724 ((this.operator === '>=' || this.operator === '>') &&
10725 (comp.operator === '<=' || comp.operator === '<'));
10726 var oppositeDirectionsGreaterThan =
10727 cmp(this.semver, '>', comp.semver, options) &&
10728 ((this.operator === '<=' || this.operator === '<') &&
10729 (comp.operator === '>=' || comp.operator === '>'));
10730
10731 return sameDirectionIncreasing || sameDirectionDecreasing ||
10732 (sameSemVer && differentDirectionsInclusive) ||
10733 oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
10734};
10735
10736
10737exports.Range = Range;
10738function Range(range, options) {
10739 if (!options || typeof options !== 'object')
10740 options = { loose: !!options, includePrerelease: false };
10741
10742 if (range instanceof Range) {
10743 if (range.loose === !!options.loose &&
10744 range.includePrerelease === !!options.includePrerelease) {
10745 return range;
10746 } else {
10747 return new Range(range.raw, options);
10748 }
10749 }
10750
10751 if (range instanceof Comparator) {
10752 return new Range(range.value, options);
10753 }
10754
10755 if (!(this instanceof Range))
10756 return new Range(range, options);
10757
10758 this.options = options;
10759 this.loose = !!options.loose;
10760 this.includePrerelease = !!options.includePrerelease;
10761
10762 // First, split based on boolean or ||
10763 this.raw = range;
10764 this.set = range.split(/\s*\|\|\s*/).map(function(range) {
10765 return this.parseRange(range.trim());
10766 }, this).filter(function(c) {
10767 // throw out any that are not relevant for whatever reason
10768 return c.length;
10769 });
10770
10771 if (!this.set.length) {
10772 throw new TypeError('Invalid SemVer Range: ' + range);
10773 }
10774
10775 this.format();
10776}
10777
10778Range.prototype.format = function() {
10779 this.range = this.set.map(function(comps) {
10780 return comps.join(' ').trim();
10781 }).join('||').trim();
10782 return this.range;
10783};
10784
10785Range.prototype.toString = function() {
10786 return this.range;
10787};
10788
10789Range.prototype.parseRange = function(range) {
10790 var loose = this.options.loose;
10791 range = range.trim();
10792 // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
10793 var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
10794 range = range.replace(hr, hyphenReplace);
10795 debug('hyphen replace', range);
10796 // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
10797 range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
10798 debug('comparator trim', range, re[COMPARATORTRIM]);
10799
10800 // `~ 1.2.3` => `~1.2.3`
10801 range = range.replace(re[TILDETRIM], tildeTrimReplace);
10802
10803 // `^ 1.2.3` => `^1.2.3`
10804 range = range.replace(re[CARETTRIM], caretTrimReplace);
10805
10806 // normalize spaces
10807 range = range.split(/\s+/).join(' ');
10808
10809 // At this point, the range is completely trimmed and
10810 // ready to be split into comparators.
10811
10812 var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
10813 var set = range.split(' ').map(function(comp) {
10814 return parseComparator(comp, this.options);
10815 }, this).join(' ').split(/\s+/);
10816 if (this.options.loose) {
10817 // in loose mode, throw out any that are not valid comparators
10818 set = set.filter(function(comp) {
10819 return !!comp.match(compRe);
10820 });
10821 }
10822 set = set.map(function(comp) {
10823 return new Comparator(comp, this.options);
10824 }, this);
10825
10826 return set;
10827};
10828
10829Range.prototype.intersects = function(range, options) {
10830 if (!(range instanceof Range)) {
10831 throw new TypeError('a Range is required');
10832 }
10833
10834 return this.set.some(function(thisComparators) {
10835 return thisComparators.every(function(thisComparator) {
10836 return range.set.some(function(rangeComparators) {
10837 return rangeComparators.every(function(rangeComparator) {
10838 return thisComparator.intersects(rangeComparator, options);
10839 });
10840 });
10841 });
10842 });
10843};
10844
10845// Mostly just for testing and legacy API reasons
10846exports.toComparators = toComparators;
10847function toComparators(range, options) {
10848 return new Range(range, options).set.map(function(comp) {
10849 return comp.map(function(c) {
10850 return c.value;
10851 }).join(' ').trim().split(' ');
10852 });
10853}
10854
10855// comprised of xranges, tildes, stars, and gtlt's at this point.
10856// already replaced the hyphen ranges
10857// turn into a set of JUST comparators.
10858function parseComparator(comp, options) {
10859 debug('comp', comp, options);
10860 comp = replaceCarets(comp, options);
10861 debug('caret', comp);
10862 comp = replaceTildes(comp, options);
10863 debug('tildes', comp);
10864 comp = replaceXRanges(comp, options);
10865 debug('xrange', comp);
10866 comp = replaceStars(comp, options);
10867 debug('stars', comp);
10868 return comp;
10869}
10870
10871function isX(id) {
10872 return !id || id.toLowerCase() === 'x' || id === '*';
10873}
10874
10875// ~, ~> --> * (any, kinda silly)
10876// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
10877// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
10878// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
10879// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
10880// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
10881function replaceTildes(comp, options) {
10882 return comp.trim().split(/\s+/).map(function(comp) {
10883 return replaceTilde(comp, options);
10884 }).join(' ');
10885}
10886
10887function replaceTilde(comp, options) {
10888 if (!options || typeof options !== 'object')
10889 options = { loose: !!options, includePrerelease: false };
10890 var r = options.loose ? re[TILDELOOSE] : re[TILDE];
10891 return comp.replace(r, function(_, M, m, p, pr) {
10892 debug('tilde', comp, _, M, m, p, pr);
10893 var ret;
10894
10895 if (isX(M))
10896 ret = '';
10897 else if (isX(m))
10898 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
10899 else if (isX(p))
10900 // ~1.2 == >=1.2.0 <1.3.0
10901 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
10902 else if (pr) {
10903 debug('replaceTilde pr', pr);
10904 if (pr.charAt(0) !== '-')
10905 pr = '-' + pr;
10906 ret = '>=' + M + '.' + m + '.' + p + pr +
10907 ' <' + M + '.' + (+m + 1) + '.0';
10908 } else
10909 // ~1.2.3 == >=1.2.3 <1.3.0
10910 ret = '>=' + M + '.' + m + '.' + p +
10911 ' <' + M + '.' + (+m + 1) + '.0';
10912
10913 debug('tilde return', ret);
10914 return ret;
10915 });
10916}
10917
10918// ^ --> * (any, kinda silly)
10919// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
10920// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
10921// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
10922// ^1.2.3 --> >=1.2.3 <2.0.0
10923// ^1.2.0 --> >=1.2.0 <2.0.0
10924function replaceCarets(comp, options) {
10925 return comp.trim().split(/\s+/).map(function(comp) {
10926 return replaceCaret(comp, options);
10927 }).join(' ');
10928}
10929
10930function replaceCaret(comp, options) {
10931 debug('caret', comp, options);
10932 if (!options || typeof options !== 'object')
10933 options = { loose: !!options, includePrerelease: false };
10934 var r = options.loose ? re[CARETLOOSE] : re[CARET];
10935 return comp.replace(r, function(_, M, m, p, pr) {
10936 debug('caret', comp, _, M, m, p, pr);
10937 var ret;
10938
10939 if (isX(M))
10940 ret = '';
10941 else if (isX(m))
10942 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
10943 else if (isX(p)) {
10944 if (M === '0')
10945 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
10946 else
10947 ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
10948 } else if (pr) {
10949 debug('replaceCaret pr', pr);
10950 if (pr.charAt(0) !== '-')
10951 pr = '-' + pr;
10952 if (M === '0') {
10953 if (m === '0')
10954 ret = '>=' + M + '.' + m + '.' + p + pr +
10955 ' <' + M + '.' + m + '.' + (+p + 1);
10956 else
10957 ret = '>=' + M + '.' + m + '.' + p + pr +
10958 ' <' + M + '.' + (+m + 1) + '.0';
10959 } else
10960 ret = '>=' + M + '.' + m + '.' + p + pr +
10961 ' <' + (+M + 1) + '.0.0';
10962 } else {
10963 debug('no pr');
10964 if (M === '0') {
10965 if (m === '0')
10966 ret = '>=' + M + '.' + m + '.' + p +
10967 ' <' + M + '.' + m + '.' + (+p + 1);
10968 else
10969 ret = '>=' + M + '.' + m + '.' + p +
10970 ' <' + M + '.' + (+m + 1) + '.0';
10971 } else
10972 ret = '>=' + M + '.' + m + '.' + p +
10973 ' <' + (+M + 1) + '.0.0';
10974 }
10975
10976 debug('caret return', ret);
10977 return ret;
10978 });
10979}
10980
10981function replaceXRanges(comp, options) {
10982 debug('replaceXRanges', comp, options);
10983 return comp.split(/\s+/).map(function(comp) {
10984 return replaceXRange(comp, options);
10985 }).join(' ');
10986}
10987
10988function replaceXRange(comp, options) {
10989 comp = comp.trim();
10990 if (!options || typeof options !== 'object')
10991 options = { loose: !!options, includePrerelease: false };
10992 var r = options.loose ? re[XRANGELOOSE] : re[XRANGE];
10993 return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
10994 debug('xRange', comp, ret, gtlt, M, m, p, pr);
10995 var xM = isX(M);
10996 var xm = xM || isX(m);
10997 var xp = xm || isX(p);
10998 var anyX = xp;
10999
11000 if (gtlt === '=' && anyX)
11001 gtlt = '';
11002
11003 if (xM) {
11004 if (gtlt === '>' || gtlt === '<') {
11005 // nothing is allowed
11006 ret = '<0.0.0';
11007 } else {
11008 // nothing is forbidden
11009 ret = '*';
11010 }
11011 } else if (gtlt && anyX) {
11012 // replace X with 0
11013 if (xm)
11014 m = 0;
11015 if (xp)
11016 p = 0;
11017
11018 if (gtlt === '>') {
11019 // >1 => >=2.0.0
11020 // >1.2 => >=1.3.0
11021 // >1.2.3 => >= 1.2.4
11022 gtlt = '>=';
11023 if (xm) {
11024 M = +M + 1;
11025 m = 0;
11026 p = 0;
11027 } else if (xp) {
11028 m = +m + 1;
11029 p = 0;
11030 }
11031 } else if (gtlt === '<=') {
11032 // <=0.7.x is actually <0.8.0, since any 0.7.x should
11033 // pass. Similarly, <=7.x is actually <8.0.0, etc.
11034 gtlt = '<';
11035 if (xm)
11036 M = +M + 1;
11037 else
11038 m = +m + 1;
11039 }
11040
11041 ret = gtlt + M + '.' + m + '.' + p;
11042 } else if (xm) {
11043 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
11044 } else if (xp) {
11045 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
11046 }
11047
11048 debug('xRange return', ret);
11049
11050 return ret;
11051 });
11052}
11053
11054// Because * is AND-ed with everything else in the comparator,
11055// and '' means "any version", just remove the *s entirely.
11056function replaceStars(comp, options) {
11057 debug('replaceStars', comp, options);
11058 // Looseness is ignored here. star is always as loose as it gets!
11059 return comp.trim().replace(re[STAR], '');
11060}
11061
11062// This function is passed to string.replace(re[HYPHENRANGE])
11063// M, m, patch, prerelease, build
11064// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
11065// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
11066// 1.2 - 3.4 => >=1.2.0 <3.5.0
11067function hyphenReplace($0,
11068 from, fM, fm, fp, fpr, fb,
11069 to, tM, tm, tp, tpr, tb) {
11070
11071 if (isX(fM))
11072 from = '';
11073 else if (isX(fm))
11074 from = '>=' + fM + '.0.0';
11075 else if (isX(fp))
11076 from = '>=' + fM + '.' + fm + '.0';
11077 else
11078 from = '>=' + from;
11079
11080 if (isX(tM))
11081 to = '';
11082 else if (isX(tm))
11083 to = '<' + (+tM + 1) + '.0.0';
11084 else if (isX(tp))
11085 to = '<' + tM + '.' + (+tm + 1) + '.0';
11086 else if (tpr)
11087 to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
11088 else
11089 to = '<=' + to;
11090
11091 return (from + ' ' + to).trim();
11092}
11093
11094
11095// if ANY of the sets match ALL of its comparators, then pass
11096Range.prototype.test = function(version) {
11097 if (!version)
11098 return false;
11099
11100 if (typeof version === 'string')
11101 version = new SemVer(version, this.options);
11102
11103 for (var i = 0; i < this.set.length; i++) {
11104 if (testSet(this.set[i], version, this.options))
11105 return true;
11106 }
11107 return false;
11108};
11109
11110function testSet(set, version, options) {
11111 for (var i = 0; i < set.length; i++) {
11112 if (!set[i].test(version))
11113 return false;
11114 }
11115
11116 if (!options)
11117 options = {};
11118
11119 if (version.prerelease.length && !options.includePrerelease) {
11120 // Find the set of versions that are allowed to have prereleases
11121 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
11122 // That should allow `1.2.3-pr.2` to pass.
11123 // However, `1.2.4-alpha.notready` should NOT be allowed,
11124 // even though it's within the range set by the comparators.
11125 for (var i = 0; i < set.length; i++) {
11126 debug(set[i].semver);
11127 if (set[i].semver === ANY)
11128 continue;
11129
11130 if (set[i].semver.prerelease.length > 0) {
11131 var allowed = set[i].semver;
11132 if (allowed.major === version.major &&
11133 allowed.minor === version.minor &&
11134 allowed.patch === version.patch)
11135 return true;
11136 }
11137 }
11138
11139 // Version has a -pre, but it's not one of the ones we like.
11140 return false;
11141 }
11142
11143 return true;
11144}
11145
11146exports.satisfies = satisfies;
11147function satisfies(version, range, options) {
11148 try {
11149 range = new Range(range, options);
11150 } catch (er) {
11151 return false;
11152 }
11153 return range.test(version);
11154}
11155
11156exports.maxSatisfying = maxSatisfying;
11157function maxSatisfying(versions, range, options) {
11158 var max = null;
11159 var maxSV = null;
11160 try {
11161 var rangeObj = new Range(range, options);
11162 } catch (er) {
11163 return null;
11164 }
11165 versions.forEach(function (v) {
11166 if (rangeObj.test(v)) { // satisfies(v, range, options)
11167 if (!max || maxSV.compare(v) === -1) { // compare(max, v, true)
11168 max = v;
11169 maxSV = new SemVer(max, options);
11170 }
11171 }
11172 });
11173 return max;
11174}
11175
11176exports.minSatisfying = minSatisfying;
11177function minSatisfying(versions, range, options) {
11178 var min = null;
11179 var minSV = null;
11180 try {
11181 var rangeObj = new Range(range, options);
11182 } catch (er) {
11183 return null;
11184 }
11185 versions.forEach(function (v) {
11186 if (rangeObj.test(v)) { // satisfies(v, range, options)
11187 if (!min || minSV.compare(v) === 1) { // compare(min, v, true)
11188 min = v;
11189 minSV = new SemVer(min, options);
11190 }
11191 }
11192 });
11193 return min;
11194}
11195
11196exports.validRange = validRange;
11197function validRange(range, options) {
11198 try {
11199 // Return '*' instead of '' so that truthiness works.
11200 // This will throw if it's invalid anyway
11201 return new Range(range, options).range || '*';
11202 } catch (er) {
11203 return null;
11204 }
11205}
11206
11207// Determine if version is less than all the versions possible in the range
11208exports.ltr = ltr;
11209function ltr(version, range, options) {
11210 return outside(version, range, '<', options);
11211}
11212
11213// Determine if version is greater than all the versions possible in the range.
11214exports.gtr = gtr;
11215function gtr(version, range, options) {
11216 return outside(version, range, '>', options);
11217}
11218
11219exports.outside = outside;
11220function outside(version, range, hilo, options) {
11221 version = new SemVer(version, options);
11222 range = new Range(range, options);
11223
11224 var gtfn, ltefn, ltfn, comp, ecomp;
11225 switch (hilo) {
11226 case '>':
11227 gtfn = gt;
11228 ltefn = lte;
11229 ltfn = lt;
11230 comp = '>';
11231 ecomp = '>=';
11232 break;
11233 case '<':
11234 gtfn = lt;
11235 ltefn = gte;
11236 ltfn = gt;
11237 comp = '<';
11238 ecomp = '<=';
11239 break;
11240 default:
11241 throw new TypeError('Must provide a hilo val of "<" or ">"');
11242 }
11243
11244 // If it satisifes the range it is not outside
11245 if (satisfies(version, range, options)) {
11246 return false;
11247 }
11248
11249 // From now on, variable terms are as if we're in "gtr" mode.
11250 // but note that everything is flipped for the "ltr" function.
11251
11252 for (var i = 0; i < range.set.length; ++i) {
11253 var comparators = range.set[i];
11254
11255 var high = null;
11256 var low = null;
11257
11258 comparators.forEach(function(comparator) {
11259 if (comparator.semver === ANY) {
11260 comparator = new Comparator('>=0.0.0');
11261 }
11262 high = high || comparator;
11263 low = low || comparator;
11264 if (gtfn(comparator.semver, high.semver, options)) {
11265 high = comparator;
11266 } else if (ltfn(comparator.semver, low.semver, options)) {
11267 low = comparator;
11268 }
11269 });
11270
11271 // If the edge version comparator has a operator then our version
11272 // isn't outside it
11273 if (high.operator === comp || high.operator === ecomp) {
11274 return false;
11275 }
11276
11277 // If the lowest version comparator has an operator and our version
11278 // is less than it then it isn't higher than the range
11279 if ((!low.operator || low.operator === comp) &&
11280 ltefn(version, low.semver)) {
11281 return false;
11282 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
11283 return false;
11284 }
11285 }
11286 return true;
11287}
11288
11289exports.prerelease = prerelease;
11290function prerelease(version, options) {
11291 var parsed = parse(version, options);
11292 return (parsed && parsed.prerelease.length) ? parsed.prerelease : null;
11293}
11294
11295exports.intersects = intersects;
11296function intersects(r1, r2, options) {
11297 r1 = new Range(r1, options);
11298 r2 = new Range(r2, options);
11299 return r1.intersects(r2)
11300}
11301
11302exports.coerce = coerce;
11303function coerce(version) {
11304 if (version instanceof SemVer)
11305 return version;
11306
11307 if (typeof version !== 'string')
11308 return null;
11309
11310 var match = version.match(re[COERCE]);
11311
11312 if (match == null)
11313 return null;
11314
11315 return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0'));
11316}
11317});
11318var semver_1 = semver.SEMVER_SPEC_VERSION;
11319var semver_2 = semver.re;
11320var semver_3 = semver.src;
11321var semver_4 = semver.parse;
11322var semver_5 = semver.valid;
11323var semver_6 = semver.clean;
11324var semver_7 = semver.SemVer;
11325var semver_8 = semver.inc;
11326var semver_9 = semver.diff;
11327var semver_10 = semver.compareIdentifiers;
11328var semver_11 = semver.rcompareIdentifiers;
11329var semver_12 = semver.major;
11330var semver_13 = semver.minor;
11331var semver_14 = semver.patch;
11332var semver_15 = semver.compare;
11333var semver_16 = semver.compareLoose;
11334var semver_17 = semver.rcompare;
11335var semver_18 = semver.sort;
11336var semver_19 = semver.rsort;
11337var semver_20 = semver.gt;
11338var semver_21 = semver.lt;
11339var semver_22 = semver.eq;
11340var semver_23 = semver.neq;
11341var semver_24 = semver.gte;
11342var semver_25 = semver.lte;
11343var semver_26 = semver.cmp;
11344var semver_27 = semver.Comparator;
11345var semver_28 = semver.Range;
11346var semver_29 = semver.toComparators;
11347var semver_30 = semver.satisfies;
11348var semver_31 = semver.maxSatisfying;
11349var semver_32 = semver.minSatisfying;
11350var semver_33 = semver.validRange;
11351var semver_34 = semver.ltr;
11352var semver_35 = semver.gtr;
11353var semver_36 = semver.outside;
11354var semver_37 = semver.prerelease;
11355var semver_38 = semver.intersects;
11356var semver_39 = semver.coerce;
11357
11358var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
11359
11360var escapeStringRegexp = function (str) {
11361 if (typeof str !== 'string') {
11362 throw new TypeError('Expected a string');
11363 }
11364
11365 return str.replace(matchOperatorsRe, '\\$&');
11366};
11367
11368var colorName = {
11369 "aliceblue": [240, 248, 255],
11370 "antiquewhite": [250, 235, 215],
11371 "aqua": [0, 255, 255],
11372 "aquamarine": [127, 255, 212],
11373 "azure": [240, 255, 255],
11374 "beige": [245, 245, 220],
11375 "bisque": [255, 228, 196],
11376 "black": [0, 0, 0],
11377 "blanchedalmond": [255, 235, 205],
11378 "blue": [0, 0, 255],
11379 "blueviolet": [138, 43, 226],
11380 "brown": [165, 42, 42],
11381 "burlywood": [222, 184, 135],
11382 "cadetblue": [95, 158, 160],
11383 "chartreuse": [127, 255, 0],
11384 "chocolate": [210, 105, 30],
11385 "coral": [255, 127, 80],
11386 "cornflowerblue": [100, 149, 237],
11387 "cornsilk": [255, 248, 220],
11388 "crimson": [220, 20, 60],
11389 "cyan": [0, 255, 255],
11390 "darkblue": [0, 0, 139],
11391 "darkcyan": [0, 139, 139],
11392 "darkgoldenrod": [184, 134, 11],
11393 "darkgray": [169, 169, 169],
11394 "darkgreen": [0, 100, 0],
11395 "darkgrey": [169, 169, 169],
11396 "darkkhaki": [189, 183, 107],
11397 "darkmagenta": [139, 0, 139],
11398 "darkolivegreen": [85, 107, 47],
11399 "darkorange": [255, 140, 0],
11400 "darkorchid": [153, 50, 204],
11401 "darkred": [139, 0, 0],
11402 "darksalmon": [233, 150, 122],
11403 "darkseagreen": [143, 188, 143],
11404 "darkslateblue": [72, 61, 139],
11405 "darkslategray": [47, 79, 79],
11406 "darkslategrey": [47, 79, 79],
11407 "darkturquoise": [0, 206, 209],
11408 "darkviolet": [148, 0, 211],
11409 "deeppink": [255, 20, 147],
11410 "deepskyblue": [0, 191, 255],
11411 "dimgray": [105, 105, 105],
11412 "dimgrey": [105, 105, 105],
11413 "dodgerblue": [30, 144, 255],
11414 "firebrick": [178, 34, 34],
11415 "floralwhite": [255, 250, 240],
11416 "forestgreen": [34, 139, 34],
11417 "fuchsia": [255, 0, 255],
11418 "gainsboro": [220, 220, 220],
11419 "ghostwhite": [248, 248, 255],
11420 "gold": [255, 215, 0],
11421 "goldenrod": [218, 165, 32],
11422 "gray": [128, 128, 128],
11423 "green": [0, 128, 0],
11424 "greenyellow": [173, 255, 47],
11425 "grey": [128, 128, 128],
11426 "honeydew": [240, 255, 240],
11427 "hotpink": [255, 105, 180],
11428 "indianred": [205, 92, 92],
11429 "indigo": [75, 0, 130],
11430 "ivory": [255, 255, 240],
11431 "khaki": [240, 230, 140],
11432 "lavender": [230, 230, 250],
11433 "lavenderblush": [255, 240, 245],
11434 "lawngreen": [124, 252, 0],
11435 "lemonchiffon": [255, 250, 205],
11436 "lightblue": [173, 216, 230],
11437 "lightcoral": [240, 128, 128],
11438 "lightcyan": [224, 255, 255],
11439 "lightgoldenrodyellow": [250, 250, 210],
11440 "lightgray": [211, 211, 211],
11441 "lightgreen": [144, 238, 144],
11442 "lightgrey": [211, 211, 211],
11443 "lightpink": [255, 182, 193],
11444 "lightsalmon": [255, 160, 122],
11445 "lightseagreen": [32, 178, 170],
11446 "lightskyblue": [135, 206, 250],
11447 "lightslategray": [119, 136, 153],
11448 "lightslategrey": [119, 136, 153],
11449 "lightsteelblue": [176, 196, 222],
11450 "lightyellow": [255, 255, 224],
11451 "lime": [0, 255, 0],
11452 "limegreen": [50, 205, 50],
11453 "linen": [250, 240, 230],
11454 "magenta": [255, 0, 255],
11455 "maroon": [128, 0, 0],
11456 "mediumaquamarine": [102, 205, 170],
11457 "mediumblue": [0, 0, 205],
11458 "mediumorchid": [186, 85, 211],
11459 "mediumpurple": [147, 112, 219],
11460 "mediumseagreen": [60, 179, 113],
11461 "mediumslateblue": [123, 104, 238],
11462 "mediumspringgreen": [0, 250, 154],
11463 "mediumturquoise": [72, 209, 204],
11464 "mediumvioletred": [199, 21, 133],
11465 "midnightblue": [25, 25, 112],
11466 "mintcream": [245, 255, 250],
11467 "mistyrose": [255, 228, 225],
11468 "moccasin": [255, 228, 181],
11469 "navajowhite": [255, 222, 173],
11470 "navy": [0, 0, 128],
11471 "oldlace": [253, 245, 230],
11472 "olive": [128, 128, 0],
11473 "olivedrab": [107, 142, 35],
11474 "orange": [255, 165, 0],
11475 "orangered": [255, 69, 0],
11476 "orchid": [218, 112, 214],
11477 "palegoldenrod": [238, 232, 170],
11478 "palegreen": [152, 251, 152],
11479 "paleturquoise": [175, 238, 238],
11480 "palevioletred": [219, 112, 147],
11481 "papayawhip": [255, 239, 213],
11482 "peachpuff": [255, 218, 185],
11483 "peru": [205, 133, 63],
11484 "pink": [255, 192, 203],
11485 "plum": [221, 160, 221],
11486 "powderblue": [176, 224, 230],
11487 "purple": [128, 0, 128],
11488 "rebeccapurple": [102, 51, 153],
11489 "red": [255, 0, 0],
11490 "rosybrown": [188, 143, 143],
11491 "royalblue": [65, 105, 225],
11492 "saddlebrown": [139, 69, 19],
11493 "salmon": [250, 128, 114],
11494 "sandybrown": [244, 164, 96],
11495 "seagreen": [46, 139, 87],
11496 "seashell": [255, 245, 238],
11497 "sienna": [160, 82, 45],
11498 "silver": [192, 192, 192],
11499 "skyblue": [135, 206, 235],
11500 "slateblue": [106, 90, 205],
11501 "slategray": [112, 128, 144],
11502 "slategrey": [112, 128, 144],
11503 "snow": [255, 250, 250],
11504 "springgreen": [0, 255, 127],
11505 "steelblue": [70, 130, 180],
11506 "tan": [210, 180, 140],
11507 "teal": [0, 128, 128],
11508 "thistle": [216, 191, 216],
11509 "tomato": [255, 99, 71],
11510 "turquoise": [64, 224, 208],
11511 "violet": [238, 130, 238],
11512 "wheat": [245, 222, 179],
11513 "white": [255, 255, 255],
11514 "whitesmoke": [245, 245, 245],
11515 "yellow": [255, 255, 0],
11516 "yellowgreen": [154, 205, 50]
11517};
11518
11519var conversions = createCommonjsModule(function (module) {
11520/* MIT license */
11521
11522
11523// NOTE: conversions should only return primitive values (i.e. arrays, or
11524// values that give correct `typeof` results).
11525// do not use box values types (i.e. Number(), String(), etc.)
11526
11527var reverseKeywords = {};
11528for (var key in colorName) {
11529 if (colorName.hasOwnProperty(key)) {
11530 reverseKeywords[colorName[key]] = key;
11531 }
11532}
11533
11534var convert = module.exports = {
11535 rgb: {channels: 3, labels: 'rgb'},
11536 hsl: {channels: 3, labels: 'hsl'},
11537 hsv: {channels: 3, labels: 'hsv'},
11538 hwb: {channels: 3, labels: 'hwb'},
11539 cmyk: {channels: 4, labels: 'cmyk'},
11540 xyz: {channels: 3, labels: 'xyz'},
11541 lab: {channels: 3, labels: 'lab'},
11542 lch: {channels: 3, labels: 'lch'},
11543 hex: {channels: 1, labels: ['hex']},
11544 keyword: {channels: 1, labels: ['keyword']},
11545 ansi16: {channels: 1, labels: ['ansi16']},
11546 ansi256: {channels: 1, labels: ['ansi256']},
11547 hcg: {channels: 3, labels: ['h', 'c', 'g']},
11548 apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
11549 gray: {channels: 1, labels: ['gray']}
11550};
11551
11552// hide .channels and .labels properties
11553for (var model in convert) {
11554 if (convert.hasOwnProperty(model)) {
11555 if (!('channels' in convert[model])) {
11556 throw new Error('missing channels property: ' + model);
11557 }
11558
11559 if (!('labels' in convert[model])) {
11560 throw new Error('missing channel labels property: ' + model);
11561 }
11562
11563 if (convert[model].labels.length !== convert[model].channels) {
11564 throw new Error('channel and label counts mismatch: ' + model);
11565 }
11566
11567 var channels = convert[model].channels;
11568 var labels = convert[model].labels;
11569 delete convert[model].channels;
11570 delete convert[model].labels;
11571 Object.defineProperty(convert[model], 'channels', {value: channels});
11572 Object.defineProperty(convert[model], 'labels', {value: labels});
11573 }
11574}
11575
11576convert.rgb.hsl = function (rgb) {
11577 var r = rgb[0] / 255;
11578 var g = rgb[1] / 255;
11579 var b = rgb[2] / 255;
11580 var min = Math.min(r, g, b);
11581 var max = Math.max(r, g, b);
11582 var delta = max - min;
11583 var h;
11584 var s;
11585 var l;
11586
11587 if (max === min) {
11588 h = 0;
11589 } else if (r === max) {
11590 h = (g - b) / delta;
11591 } else if (g === max) {
11592 h = 2 + (b - r) / delta;
11593 } else if (b === max) {
11594 h = 4 + (r - g) / delta;
11595 }
11596
11597 h = Math.min(h * 60, 360);
11598
11599 if (h < 0) {
11600 h += 360;
11601 }
11602
11603 l = (min + max) / 2;
11604
11605 if (max === min) {
11606 s = 0;
11607 } else if (l <= 0.5) {
11608 s = delta / (max + min);
11609 } else {
11610 s = delta / (2 - max - min);
11611 }
11612
11613 return [h, s * 100, l * 100];
11614};
11615
11616convert.rgb.hsv = function (rgb) {
11617 var rdif;
11618 var gdif;
11619 var bdif;
11620 var h;
11621 var s;
11622
11623 var r = rgb[0] / 255;
11624 var g = rgb[1] / 255;
11625 var b = rgb[2] / 255;
11626 var v = Math.max(r, g, b);
11627 var diff = v - Math.min(r, g, b);
11628 var diffc = function (c) {
11629 return (v - c) / 6 / diff + 1 / 2;
11630 };
11631
11632 if (diff === 0) {
11633 h = s = 0;
11634 } else {
11635 s = diff / v;
11636 rdif = diffc(r);
11637 gdif = diffc(g);
11638 bdif = diffc(b);
11639
11640 if (r === v) {
11641 h = bdif - gdif;
11642 } else if (g === v) {
11643 h = (1 / 3) + rdif - bdif;
11644 } else if (b === v) {
11645 h = (2 / 3) + gdif - rdif;
11646 }
11647 if (h < 0) {
11648 h += 1;
11649 } else if (h > 1) {
11650 h -= 1;
11651 }
11652 }
11653
11654 return [
11655 h * 360,
11656 s * 100,
11657 v * 100
11658 ];
11659};
11660
11661convert.rgb.hwb = function (rgb) {
11662 var r = rgb[0];
11663 var g = rgb[1];
11664 var b = rgb[2];
11665 var h = convert.rgb.hsl(rgb)[0];
11666 var w = 1 / 255 * Math.min(r, Math.min(g, b));
11667
11668 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
11669
11670 return [h, w * 100, b * 100];
11671};
11672
11673convert.rgb.cmyk = function (rgb) {
11674 var r = rgb[0] / 255;
11675 var g = rgb[1] / 255;
11676 var b = rgb[2] / 255;
11677 var c;
11678 var m;
11679 var y;
11680 var k;
11681
11682 k = Math.min(1 - r, 1 - g, 1 - b);
11683 c = (1 - r - k) / (1 - k) || 0;
11684 m = (1 - g - k) / (1 - k) || 0;
11685 y = (1 - b - k) / (1 - k) || 0;
11686
11687 return [c * 100, m * 100, y * 100, k * 100];
11688};
11689
11690/**
11691 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
11692 * */
11693function comparativeDistance(x, y) {
11694 return (
11695 Math.pow(x[0] - y[0], 2) +
11696 Math.pow(x[1] - y[1], 2) +
11697 Math.pow(x[2] - y[2], 2)
11698 );
11699}
11700
11701convert.rgb.keyword = function (rgb) {
11702 var reversed = reverseKeywords[rgb];
11703 if (reversed) {
11704 return reversed;
11705 }
11706
11707 var currentClosestDistance = Infinity;
11708 var currentClosestKeyword;
11709
11710 for (var keyword in colorName) {
11711 if (colorName.hasOwnProperty(keyword)) {
11712 var value = colorName[keyword];
11713
11714 // Compute comparative distance
11715 var distance = comparativeDistance(rgb, value);
11716
11717 // Check if its less, if so set as closest
11718 if (distance < currentClosestDistance) {
11719 currentClosestDistance = distance;
11720 currentClosestKeyword = keyword;
11721 }
11722 }
11723 }
11724
11725 return currentClosestKeyword;
11726};
11727
11728convert.keyword.rgb = function (keyword) {
11729 return colorName[keyword];
11730};
11731
11732convert.rgb.xyz = function (rgb) {
11733 var r = rgb[0] / 255;
11734 var g = rgb[1] / 255;
11735 var b = rgb[2] / 255;
11736
11737 // assume sRGB
11738 r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
11739 g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
11740 b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
11741
11742 var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
11743 var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
11744 var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
11745
11746 return [x * 100, y * 100, z * 100];
11747};
11748
11749convert.rgb.lab = function (rgb) {
11750 var xyz = convert.rgb.xyz(rgb);
11751 var x = xyz[0];
11752 var y = xyz[1];
11753 var z = xyz[2];
11754 var l;
11755 var a;
11756 var b;
11757
11758 x /= 95.047;
11759 y /= 100;
11760 z /= 108.883;
11761
11762 x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
11763 y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
11764 z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
11765
11766 l = (116 * y) - 16;
11767 a = 500 * (x - y);
11768 b = 200 * (y - z);
11769
11770 return [l, a, b];
11771};
11772
11773convert.hsl.rgb = function (hsl) {
11774 var h = hsl[0] / 360;
11775 var s = hsl[1] / 100;
11776 var l = hsl[2] / 100;
11777 var t1;
11778 var t2;
11779 var t3;
11780 var rgb;
11781 var val;
11782
11783 if (s === 0) {
11784 val = l * 255;
11785 return [val, val, val];
11786 }
11787
11788 if (l < 0.5) {
11789 t2 = l * (1 + s);
11790 } else {
11791 t2 = l + s - l * s;
11792 }
11793
11794 t1 = 2 * l - t2;
11795
11796 rgb = [0, 0, 0];
11797 for (var i = 0; i < 3; i++) {
11798 t3 = h + 1 / 3 * -(i - 1);
11799 if (t3 < 0) {
11800 t3++;
11801 }
11802 if (t3 > 1) {
11803 t3--;
11804 }
11805
11806 if (6 * t3 < 1) {
11807 val = t1 + (t2 - t1) * 6 * t3;
11808 } else if (2 * t3 < 1) {
11809 val = t2;
11810 } else if (3 * t3 < 2) {
11811 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
11812 } else {
11813 val = t1;
11814 }
11815
11816 rgb[i] = val * 255;
11817 }
11818
11819 return rgb;
11820};
11821
11822convert.hsl.hsv = function (hsl) {
11823 var h = hsl[0];
11824 var s = hsl[1] / 100;
11825 var l = hsl[2] / 100;
11826 var smin = s;
11827 var lmin = Math.max(l, 0.01);
11828 var sv;
11829 var v;
11830
11831 l *= 2;
11832 s *= (l <= 1) ? l : 2 - l;
11833 smin *= lmin <= 1 ? lmin : 2 - lmin;
11834 v = (l + s) / 2;
11835 sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
11836
11837 return [h, sv * 100, v * 100];
11838};
11839
11840convert.hsv.rgb = function (hsv) {
11841 var h = hsv[0] / 60;
11842 var s = hsv[1] / 100;
11843 var v = hsv[2] / 100;
11844 var hi = Math.floor(h) % 6;
11845
11846 var f = h - Math.floor(h);
11847 var p = 255 * v * (1 - s);
11848 var q = 255 * v * (1 - (s * f));
11849 var t = 255 * v * (1 - (s * (1 - f)));
11850 v *= 255;
11851
11852 switch (hi) {
11853 case 0:
11854 return [v, t, p];
11855 case 1:
11856 return [q, v, p];
11857 case 2:
11858 return [p, v, t];
11859 case 3:
11860 return [p, q, v];
11861 case 4:
11862 return [t, p, v];
11863 case 5:
11864 return [v, p, q];
11865 }
11866};
11867
11868convert.hsv.hsl = function (hsv) {
11869 var h = hsv[0];
11870 var s = hsv[1] / 100;
11871 var v = hsv[2] / 100;
11872 var vmin = Math.max(v, 0.01);
11873 var lmin;
11874 var sl;
11875 var l;
11876
11877 l = (2 - s) * v;
11878 lmin = (2 - s) * vmin;
11879 sl = s * vmin;
11880 sl /= (lmin <= 1) ? lmin : 2 - lmin;
11881 sl = sl || 0;
11882 l /= 2;
11883
11884 return [h, sl * 100, l * 100];
11885};
11886
11887// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
11888convert.hwb.rgb = function (hwb) {
11889 var h = hwb[0] / 360;
11890 var wh = hwb[1] / 100;
11891 var bl = hwb[2] / 100;
11892 var ratio = wh + bl;
11893 var i;
11894 var v;
11895 var f;
11896 var n;
11897
11898 // wh + bl cant be > 1
11899 if (ratio > 1) {
11900 wh /= ratio;
11901 bl /= ratio;
11902 }
11903
11904 i = Math.floor(6 * h);
11905 v = 1 - bl;
11906 f = 6 * h - i;
11907
11908 if ((i & 0x01) !== 0) {
11909 f = 1 - f;
11910 }
11911
11912 n = wh + f * (v - wh); // linear interpolation
11913
11914 var r;
11915 var g;
11916 var b;
11917 switch (i) {
11918 default:
11919 case 6:
11920 case 0: r = v; g = n; b = wh; break;
11921 case 1: r = n; g = v; b = wh; break;
11922 case 2: r = wh; g = v; b = n; break;
11923 case 3: r = wh; g = n; b = v; break;
11924 case 4: r = n; g = wh; b = v; break;
11925 case 5: r = v; g = wh; b = n; break;
11926 }
11927
11928 return [r * 255, g * 255, b * 255];
11929};
11930
11931convert.cmyk.rgb = function (cmyk) {
11932 var c = cmyk[0] / 100;
11933 var m = cmyk[1] / 100;
11934 var y = cmyk[2] / 100;
11935 var k = cmyk[3] / 100;
11936 var r;
11937 var g;
11938 var b;
11939
11940 r = 1 - Math.min(1, c * (1 - k) + k);
11941 g = 1 - Math.min(1, m * (1 - k) + k);
11942 b = 1 - Math.min(1, y * (1 - k) + k);
11943
11944 return [r * 255, g * 255, b * 255];
11945};
11946
11947convert.xyz.rgb = function (xyz) {
11948 var x = xyz[0] / 100;
11949 var y = xyz[1] / 100;
11950 var z = xyz[2] / 100;
11951 var r;
11952 var g;
11953 var b;
11954
11955 r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
11956 g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
11957 b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
11958
11959 // assume sRGB
11960 r = r > 0.0031308
11961 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
11962 : r * 12.92;
11963
11964 g = g > 0.0031308
11965 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
11966 : g * 12.92;
11967
11968 b = b > 0.0031308
11969 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
11970 : b * 12.92;
11971
11972 r = Math.min(Math.max(0, r), 1);
11973 g = Math.min(Math.max(0, g), 1);
11974 b = Math.min(Math.max(0, b), 1);
11975
11976 return [r * 255, g * 255, b * 255];
11977};
11978
11979convert.xyz.lab = function (xyz) {
11980 var x = xyz[0];
11981 var y = xyz[1];
11982 var z = xyz[2];
11983 var l;
11984 var a;
11985 var b;
11986
11987 x /= 95.047;
11988 y /= 100;
11989 z /= 108.883;
11990
11991 x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
11992 y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
11993 z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
11994
11995 l = (116 * y) - 16;
11996 a = 500 * (x - y);
11997 b = 200 * (y - z);
11998
11999 return [l, a, b];
12000};
12001
12002convert.lab.xyz = function (lab) {
12003 var l = lab[0];
12004 var a = lab[1];
12005 var b = lab[2];
12006 var x;
12007 var y;
12008 var z;
12009
12010 y = (l + 16) / 116;
12011 x = a / 500 + y;
12012 z = y - b / 200;
12013
12014 var y2 = Math.pow(y, 3);
12015 var x2 = Math.pow(x, 3);
12016 var z2 = Math.pow(z, 3);
12017 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
12018 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
12019 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
12020
12021 x *= 95.047;
12022 y *= 100;
12023 z *= 108.883;
12024
12025 return [x, y, z];
12026};
12027
12028convert.lab.lch = function (lab) {
12029 var l = lab[0];
12030 var a = lab[1];
12031 var b = lab[2];
12032 var hr;
12033 var h;
12034 var c;
12035
12036 hr = Math.atan2(b, a);
12037 h = hr * 360 / 2 / Math.PI;
12038
12039 if (h < 0) {
12040 h += 360;
12041 }
12042
12043 c = Math.sqrt(a * a + b * b);
12044
12045 return [l, c, h];
12046};
12047
12048convert.lch.lab = function (lch) {
12049 var l = lch[0];
12050 var c = lch[1];
12051 var h = lch[2];
12052 var a;
12053 var b;
12054 var hr;
12055
12056 hr = h / 360 * 2 * Math.PI;
12057 a = c * Math.cos(hr);
12058 b = c * Math.sin(hr);
12059
12060 return [l, a, b];
12061};
12062
12063convert.rgb.ansi16 = function (args) {
12064 var r = args[0];
12065 var g = args[1];
12066 var b = args[2];
12067 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
12068
12069 value = Math.round(value / 50);
12070
12071 if (value === 0) {
12072 return 30;
12073 }
12074
12075 var ansi = 30
12076 + ((Math.round(b / 255) << 2)
12077 | (Math.round(g / 255) << 1)
12078 | Math.round(r / 255));
12079
12080 if (value === 2) {
12081 ansi += 60;
12082 }
12083
12084 return ansi;
12085};
12086
12087convert.hsv.ansi16 = function (args) {
12088 // optimization here; we already know the value and don't need to get
12089 // it converted for us.
12090 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
12091};
12092
12093convert.rgb.ansi256 = function (args) {
12094 var r = args[0];
12095 var g = args[1];
12096 var b = args[2];
12097
12098 // we use the extended greyscale palette here, with the exception of
12099 // black and white. normal palette only has 4 greyscale shades.
12100 if (r === g && g === b) {
12101 if (r < 8) {
12102 return 16;
12103 }
12104
12105 if (r > 248) {
12106 return 231;
12107 }
12108
12109 return Math.round(((r - 8) / 247) * 24) + 232;
12110 }
12111
12112 var ansi = 16
12113 + (36 * Math.round(r / 255 * 5))
12114 + (6 * Math.round(g / 255 * 5))
12115 + Math.round(b / 255 * 5);
12116
12117 return ansi;
12118};
12119
12120convert.ansi16.rgb = function (args) {
12121 var color = args % 10;
12122
12123 // handle greyscale
12124 if (color === 0 || color === 7) {
12125 if (args > 50) {
12126 color += 3.5;
12127 }
12128
12129 color = color / 10.5 * 255;
12130
12131 return [color, color, color];
12132 }
12133
12134 var mult = (~~(args > 50) + 1) * 0.5;
12135 var r = ((color & 1) * mult) * 255;
12136 var g = (((color >> 1) & 1) * mult) * 255;
12137 var b = (((color >> 2) & 1) * mult) * 255;
12138
12139 return [r, g, b];
12140};
12141
12142convert.ansi256.rgb = function (args) {
12143 // handle greyscale
12144 if (args >= 232) {
12145 var c = (args - 232) * 10 + 8;
12146 return [c, c, c];
12147 }
12148
12149 args -= 16;
12150
12151 var rem;
12152 var r = Math.floor(args / 36) / 5 * 255;
12153 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
12154 var b = (rem % 6) / 5 * 255;
12155
12156 return [r, g, b];
12157};
12158
12159convert.rgb.hex = function (args) {
12160 var integer = ((Math.round(args[0]) & 0xFF) << 16)
12161 + ((Math.round(args[1]) & 0xFF) << 8)
12162 + (Math.round(args[2]) & 0xFF);
12163
12164 var string = integer.toString(16).toUpperCase();
12165 return '000000'.substring(string.length) + string;
12166};
12167
12168convert.hex.rgb = function (args) {
12169 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
12170 if (!match) {
12171 return [0, 0, 0];
12172 }
12173
12174 var colorString = match[0];
12175
12176 if (match[0].length === 3) {
12177 colorString = colorString.split('').map(function (char) {
12178 return char + char;
12179 }).join('');
12180 }
12181
12182 var integer = parseInt(colorString, 16);
12183 var r = (integer >> 16) & 0xFF;
12184 var g = (integer >> 8) & 0xFF;
12185 var b = integer & 0xFF;
12186
12187 return [r, g, b];
12188};
12189
12190convert.rgb.hcg = function (rgb) {
12191 var r = rgb[0] / 255;
12192 var g = rgb[1] / 255;
12193 var b = rgb[2] / 255;
12194 var max = Math.max(Math.max(r, g), b);
12195 var min = Math.min(Math.min(r, g), b);
12196 var chroma = (max - min);
12197 var grayscale;
12198 var hue;
12199
12200 if (chroma < 1) {
12201 grayscale = min / (1 - chroma);
12202 } else {
12203 grayscale = 0;
12204 }
12205
12206 if (chroma <= 0) {
12207 hue = 0;
12208 } else
12209 if (max === r) {
12210 hue = ((g - b) / chroma) % 6;
12211 } else
12212 if (max === g) {
12213 hue = 2 + (b - r) / chroma;
12214 } else {
12215 hue = 4 + (r - g) / chroma + 4;
12216 }
12217
12218 hue /= 6;
12219 hue %= 1;
12220
12221 return [hue * 360, chroma * 100, grayscale * 100];
12222};
12223
12224convert.hsl.hcg = function (hsl) {
12225 var s = hsl[1] / 100;
12226 var l = hsl[2] / 100;
12227 var c = 1;
12228 var f = 0;
12229
12230 if (l < 0.5) {
12231 c = 2.0 * s * l;
12232 } else {
12233 c = 2.0 * s * (1.0 - l);
12234 }
12235
12236 if (c < 1.0) {
12237 f = (l - 0.5 * c) / (1.0 - c);
12238 }
12239
12240 return [hsl[0], c * 100, f * 100];
12241};
12242
12243convert.hsv.hcg = function (hsv) {
12244 var s = hsv[1] / 100;
12245 var v = hsv[2] / 100;
12246
12247 var c = s * v;
12248 var f = 0;
12249
12250 if (c < 1.0) {
12251 f = (v - c) / (1 - c);
12252 }
12253
12254 return [hsv[0], c * 100, f * 100];
12255};
12256
12257convert.hcg.rgb = function (hcg) {
12258 var h = hcg[0] / 360;
12259 var c = hcg[1] / 100;
12260 var g = hcg[2] / 100;
12261
12262 if (c === 0.0) {
12263 return [g * 255, g * 255, g * 255];
12264 }
12265
12266 var pure = [0, 0, 0];
12267 var hi = (h % 1) * 6;
12268 var v = hi % 1;
12269 var w = 1 - v;
12270 var mg = 0;
12271
12272 switch (Math.floor(hi)) {
12273 case 0:
12274 pure[0] = 1; pure[1] = v; pure[2] = 0; break;
12275 case 1:
12276 pure[0] = w; pure[1] = 1; pure[2] = 0; break;
12277 case 2:
12278 pure[0] = 0; pure[1] = 1; pure[2] = v; break;
12279 case 3:
12280 pure[0] = 0; pure[1] = w; pure[2] = 1; break;
12281 case 4:
12282 pure[0] = v; pure[1] = 0; pure[2] = 1; break;
12283 default:
12284 pure[0] = 1; pure[1] = 0; pure[2] = w;
12285 }
12286
12287 mg = (1.0 - c) * g;
12288
12289 return [
12290 (c * pure[0] + mg) * 255,
12291 (c * pure[1] + mg) * 255,
12292 (c * pure[2] + mg) * 255
12293 ];
12294};
12295
12296convert.hcg.hsv = function (hcg) {
12297 var c = hcg[1] / 100;
12298 var g = hcg[2] / 100;
12299
12300 var v = c + g * (1.0 - c);
12301 var f = 0;
12302
12303 if (v > 0.0) {
12304 f = c / v;
12305 }
12306
12307 return [hcg[0], f * 100, v * 100];
12308};
12309
12310convert.hcg.hsl = function (hcg) {
12311 var c = hcg[1] / 100;
12312 var g = hcg[2] / 100;
12313
12314 var l = g * (1.0 - c) + 0.5 * c;
12315 var s = 0;
12316
12317 if (l > 0.0 && l < 0.5) {
12318 s = c / (2 * l);
12319 } else
12320 if (l >= 0.5 && l < 1.0) {
12321 s = c / (2 * (1 - l));
12322 }
12323
12324 return [hcg[0], s * 100, l * 100];
12325};
12326
12327convert.hcg.hwb = function (hcg) {
12328 var c = hcg[1] / 100;
12329 var g = hcg[2] / 100;
12330 var v = c + g * (1.0 - c);
12331 return [hcg[0], (v - c) * 100, (1 - v) * 100];
12332};
12333
12334convert.hwb.hcg = function (hwb) {
12335 var w = hwb[1] / 100;
12336 var b = hwb[2] / 100;
12337 var v = 1 - b;
12338 var c = v - w;
12339 var g = 0;
12340
12341 if (c < 1) {
12342 g = (v - c) / (1 - c);
12343 }
12344
12345 return [hwb[0], c * 100, g * 100];
12346};
12347
12348convert.apple.rgb = function (apple) {
12349 return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
12350};
12351
12352convert.rgb.apple = function (rgb) {
12353 return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
12354};
12355
12356convert.gray.rgb = function (args) {
12357 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
12358};
12359
12360convert.gray.hsl = convert.gray.hsv = function (args) {
12361 return [0, 0, args[0]];
12362};
12363
12364convert.gray.hwb = function (gray) {
12365 return [0, 100, gray[0]];
12366};
12367
12368convert.gray.cmyk = function (gray) {
12369 return [0, 0, 0, gray[0]];
12370};
12371
12372convert.gray.lab = function (gray) {
12373 return [gray[0], 0, 0];
12374};
12375
12376convert.gray.hex = function (gray) {
12377 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
12378 var integer = (val << 16) + (val << 8) + val;
12379
12380 var string = integer.toString(16).toUpperCase();
12381 return '000000'.substring(string.length) + string;
12382};
12383
12384convert.rgb.gray = function (rgb) {
12385 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
12386 return [val / 255 * 100];
12387};
12388});
12389var conversions_1 = conversions.rgb;
12390var conversions_2 = conversions.hsl;
12391var conversions_3 = conversions.hsv;
12392var conversions_4 = conversions.hwb;
12393var conversions_5 = conversions.cmyk;
12394var conversions_6 = conversions.xyz;
12395var conversions_7 = conversions.lab;
12396var conversions_8 = conversions.lch;
12397var conversions_9 = conversions.hex;
12398var conversions_10 = conversions.keyword;
12399var conversions_11 = conversions.ansi16;
12400var conversions_12 = conversions.ansi256;
12401var conversions_13 = conversions.hcg;
12402var conversions_14 = conversions.apple;
12403var conversions_15 = conversions.gray;
12404
12405/*
12406 this function routes a model to all other models.
12407
12408 all functions that are routed have a property `.conversion` attached
12409 to the returned synthetic function. This property is an array
12410 of strings, each with the steps in between the 'from' and 'to'
12411 color models (inclusive).
12412
12413 conversions that are not possible simply are not included.
12414*/
12415
12416function buildGraph() {
12417 var graph = {};
12418 // https://jsperf.com/object-keys-vs-for-in-with-closure/3
12419 var models = Object.keys(conversions);
12420
12421 for (var len = models.length, i = 0; i < len; i++) {
12422 graph[models[i]] = {
12423 // http://jsperf.com/1-vs-infinity
12424 // micro-opt, but this is simple.
12425 distance: -1,
12426 parent: null
12427 };
12428 }
12429
12430 return graph;
12431}
12432
12433// https://en.wikipedia.org/wiki/Breadth-first_search
12434function deriveBFS(fromModel) {
12435 var graph = buildGraph();
12436 var queue = [fromModel]; // unshift -> queue -> pop
12437
12438 graph[fromModel].distance = 0;
12439
12440 while (queue.length) {
12441 var current = queue.pop();
12442 var adjacents = Object.keys(conversions[current]);
12443
12444 for (var len = adjacents.length, i = 0; i < len; i++) {
12445 var adjacent = adjacents[i];
12446 var node = graph[adjacent];
12447
12448 if (node.distance === -1) {
12449 node.distance = graph[current].distance + 1;
12450 node.parent = current;
12451 queue.unshift(adjacent);
12452 }
12453 }
12454 }
12455
12456 return graph;
12457}
12458
12459function link(from, to) {
12460 return function (args) {
12461 return to(from(args));
12462 };
12463}
12464
12465function wrapConversion(toModel, graph) {
12466 var path$$1 = [graph[toModel].parent, toModel];
12467 var fn = conversions[graph[toModel].parent][toModel];
12468
12469 var cur = graph[toModel].parent;
12470 while (graph[cur].parent) {
12471 path$$1.unshift(graph[cur].parent);
12472 fn = link(conversions[graph[cur].parent][cur], fn);
12473 cur = graph[cur].parent;
12474 }
12475
12476 fn.conversion = path$$1;
12477 return fn;
12478}
12479
12480var route = function (fromModel) {
12481 var graph = deriveBFS(fromModel);
12482 var conversion = {};
12483
12484 var models = Object.keys(graph);
12485 for (var len = models.length, i = 0; i < len; i++) {
12486 var toModel = models[i];
12487 var node = graph[toModel];
12488
12489 if (node.parent === null) {
12490 // no possible conversion, or this node is the source model.
12491 continue;
12492 }
12493
12494 conversion[toModel] = wrapConversion(toModel, graph);
12495 }
12496
12497 return conversion;
12498};
12499
12500var convert = {};
12501
12502var models = Object.keys(conversions);
12503
12504function wrapRaw(fn) {
12505 var wrappedFn = function (args) {
12506 if (args === undefined || args === null) {
12507 return args;
12508 }
12509
12510 if (arguments.length > 1) {
12511 args = Array.prototype.slice.call(arguments);
12512 }
12513
12514 return fn(args);
12515 };
12516
12517 // preserve .conversion property if there is one
12518 if ('conversion' in fn) {
12519 wrappedFn.conversion = fn.conversion;
12520 }
12521
12522 return wrappedFn;
12523}
12524
12525function wrapRounded(fn) {
12526 var wrappedFn = function (args) {
12527 if (args === undefined || args === null) {
12528 return args;
12529 }
12530
12531 if (arguments.length > 1) {
12532 args = Array.prototype.slice.call(arguments);
12533 }
12534
12535 var result = fn(args);
12536
12537 // we're assuming the result is an array here.
12538 // see notice in conversions.js; don't use box types
12539 // in conversion functions.
12540 if (typeof result === 'object') {
12541 for (var len = result.length, i = 0; i < len; i++) {
12542 result[i] = Math.round(result[i]);
12543 }
12544 }
12545
12546 return result;
12547 };
12548
12549 // preserve .conversion property if there is one
12550 if ('conversion' in fn) {
12551 wrappedFn.conversion = fn.conversion;
12552 }
12553
12554 return wrappedFn;
12555}
12556
12557models.forEach(function (fromModel) {
12558 convert[fromModel] = {};
12559
12560 Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
12561 Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
12562
12563 var routes = route(fromModel);
12564 var routeModels = Object.keys(routes);
12565
12566 routeModels.forEach(function (toModel) {
12567 var fn = routes[toModel];
12568
12569 convert[fromModel][toModel] = wrapRounded(fn);
12570 convert[fromModel][toModel].raw = wrapRaw(fn);
12571 });
12572});
12573
12574var colorConvert = convert;
12575
12576var ansiStyles = createCommonjsModule(function (module) {
12577
12578
12579const wrapAnsi16 = (fn, offset) => function () {
12580 const code = fn.apply(colorConvert, arguments);
12581 return `\u001B[${code + offset}m`;
12582};
12583
12584const wrapAnsi256 = (fn, offset) => function () {
12585 const code = fn.apply(colorConvert, arguments);
12586 return `\u001B[${38 + offset};5;${code}m`;
12587};
12588
12589const wrapAnsi16m = (fn, offset) => function () {
12590 const rgb = fn.apply(colorConvert, arguments);
12591 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
12592};
12593
12594function assembleStyles() {
12595 const codes = new Map();
12596 const styles = {
12597 modifier: {
12598 reset: [0, 0],
12599 // 21 isn't widely supported and 22 does the same thing
12600 bold: [1, 22],
12601 dim: [2, 22],
12602 italic: [3, 23],
12603 underline: [4, 24],
12604 inverse: [7, 27],
12605 hidden: [8, 28],
12606 strikethrough: [9, 29]
12607 },
12608 color: {
12609 black: [30, 39],
12610 red: [31, 39],
12611 green: [32, 39],
12612 yellow: [33, 39],
12613 blue: [34, 39],
12614 magenta: [35, 39],
12615 cyan: [36, 39],
12616 white: [37, 39],
12617 gray: [90, 39],
12618
12619 // Bright color
12620 redBright: [91, 39],
12621 greenBright: [92, 39],
12622 yellowBright: [93, 39],
12623 blueBright: [94, 39],
12624 magentaBright: [95, 39],
12625 cyanBright: [96, 39],
12626 whiteBright: [97, 39]
12627 },
12628 bgColor: {
12629 bgBlack: [40, 49],
12630 bgRed: [41, 49],
12631 bgGreen: [42, 49],
12632 bgYellow: [43, 49],
12633 bgBlue: [44, 49],
12634 bgMagenta: [45, 49],
12635 bgCyan: [46, 49],
12636 bgWhite: [47, 49],
12637
12638 // Bright color
12639 bgBlackBright: [100, 49],
12640 bgRedBright: [101, 49],
12641 bgGreenBright: [102, 49],
12642 bgYellowBright: [103, 49],
12643 bgBlueBright: [104, 49],
12644 bgMagentaBright: [105, 49],
12645 bgCyanBright: [106, 49],
12646 bgWhiteBright: [107, 49]
12647 }
12648 };
12649
12650 // Fix humans
12651 styles.color.grey = styles.color.gray;
12652
12653 for (const groupName of Object.keys(styles)) {
12654 const group = styles[groupName];
12655
12656 for (const styleName of Object.keys(group)) {
12657 const style = group[styleName];
12658
12659 styles[styleName] = {
12660 open: `\u001B[${style[0]}m`,
12661 close: `\u001B[${style[1]}m`
12662 };
12663
12664 group[styleName] = styles[styleName];
12665
12666 codes.set(style[0], style[1]);
12667 }
12668
12669 Object.defineProperty(styles, groupName, {
12670 value: group,
12671 enumerable: false
12672 });
12673
12674 Object.defineProperty(styles, 'codes', {
12675 value: codes,
12676 enumerable: false
12677 });
12678 }
12679
12680 const ansi2ansi = n => n;
12681 const rgb2rgb = (r, g, b) => [r, g, b];
12682
12683 styles.color.close = '\u001B[39m';
12684 styles.bgColor.close = '\u001B[49m';
12685
12686 styles.color.ansi = {
12687 ansi: wrapAnsi16(ansi2ansi, 0)
12688 };
12689 styles.color.ansi256 = {
12690 ansi256: wrapAnsi256(ansi2ansi, 0)
12691 };
12692 styles.color.ansi16m = {
12693 rgb: wrapAnsi16m(rgb2rgb, 0)
12694 };
12695
12696 styles.bgColor.ansi = {
12697 ansi: wrapAnsi16(ansi2ansi, 10)
12698 };
12699 styles.bgColor.ansi256 = {
12700 ansi256: wrapAnsi256(ansi2ansi, 10)
12701 };
12702 styles.bgColor.ansi16m = {
12703 rgb: wrapAnsi16m(rgb2rgb, 10)
12704 };
12705
12706 for (let key of Object.keys(colorConvert)) {
12707 if (typeof colorConvert[key] !== 'object') {
12708 continue;
12709 }
12710
12711 const suite = colorConvert[key];
12712
12713 if (key === 'ansi16') {
12714 key = 'ansi';
12715 }
12716
12717 if ('ansi16' in suite) {
12718 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
12719 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
12720 }
12721
12722 if ('ansi256' in suite) {
12723 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
12724 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
12725 }
12726
12727 if ('rgb' in suite) {
12728 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
12729 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
12730 }
12731 }
12732
12733 return styles;
12734}
12735
12736// Make the export immutable
12737Object.defineProperty(module, 'exports', {
12738 enumerable: true,
12739 get: assembleStyles
12740});
12741});
12742
12743const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
12744const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
12745const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
12746const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
12747
12748const ESCAPES = new Map([
12749 ['n', '\n'],
12750 ['r', '\r'],
12751 ['t', '\t'],
12752 ['b', '\b'],
12753 ['f', '\f'],
12754 ['v', '\v'],
12755 ['0', '\0'],
12756 ['\\', '\\'],
12757 ['e', '\u001B'],
12758 ['a', '\u0007']
12759]);
12760
12761function unescape(c) {
12762 if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
12763 return String.fromCharCode(parseInt(c.slice(1), 16));
12764 }
12765
12766 return ESCAPES.get(c) || c;
12767}
12768
12769function parseArguments(name, args) {
12770 const results = [];
12771 const chunks = args.trim().split(/\s*,\s*/g);
12772 let matches;
12773
12774 for (const chunk of chunks) {
12775 if (!isNaN(chunk)) {
12776 results.push(Number(chunk));
12777 } else if ((matches = chunk.match(STRING_REGEX))) {
12778 results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
12779 } else {
12780 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
12781 }
12782 }
12783
12784 return results;
12785}
12786
12787function parseStyle(style) {
12788 STYLE_REGEX.lastIndex = 0;
12789
12790 const results = [];
12791 let matches;
12792
12793 while ((matches = STYLE_REGEX.exec(style)) !== null) {
12794 const name = matches[1];
12795
12796 if (matches[2]) {
12797 const args = parseArguments(name, matches[2]);
12798 results.push([name].concat(args));
12799 } else {
12800 results.push([name]);
12801 }
12802 }
12803
12804 return results;
12805}
12806
12807function buildStyle(chalk, styles) {
12808 const enabled = {};
12809
12810 for (const layer of styles) {
12811 for (const style of layer.styles) {
12812 enabled[style[0]] = layer.inverse ? null : style.slice(1);
12813 }
12814 }
12815
12816 let current = chalk;
12817 for (const styleName of Object.keys(enabled)) {
12818 if (Array.isArray(enabled[styleName])) {
12819 if (!(styleName in current)) {
12820 throw new Error(`Unknown Chalk style: ${styleName}`);
12821 }
12822
12823 if (enabled[styleName].length > 0) {
12824 current = current[styleName].apply(current, enabled[styleName]);
12825 } else {
12826 current = current[styleName];
12827 }
12828 }
12829 }
12830
12831 return current;
12832}
12833
12834var templates = (chalk, tmp) => {
12835 const styles = [];
12836 const chunks = [];
12837 let chunk = [];
12838
12839 // eslint-disable-next-line max-params
12840 tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
12841 if (escapeChar) {
12842 chunk.push(unescape(escapeChar));
12843 } else if (style) {
12844 const str = chunk.join('');
12845 chunk = [];
12846 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
12847 styles.push({inverse, styles: parseStyle(style)});
12848 } else if (close) {
12849 if (styles.length === 0) {
12850 throw new Error('Found extraneous } in Chalk template literal');
12851 }
12852
12853 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
12854 chunk = [];
12855 styles.pop();
12856 } else {
12857 chunk.push(chr);
12858 }
12859 });
12860
12861 chunks.push(chunk.join(''));
12862
12863 if (styles.length > 0) {
12864 const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
12865 throw new Error(errMsg);
12866 }
12867
12868 return chunks.join('');
12869};
12870
12871var chalk = createCommonjsModule(function (module) {
12872
12873
12874const stdoutColor = supportsColor_1.stdout;
12875
12876
12877
12878const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
12879
12880// `supportsColor.level` → `ansiStyles.color[name]` mapping
12881const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
12882
12883// `color-convert` models to exclude from the Chalk API due to conflicts and such
12884const skipModels = new Set(['gray']);
12885
12886const styles = Object.create(null);
12887
12888function applyOptions(obj, options) {
12889 options = options || {};
12890
12891 // Detect level if not set manually
12892 const scLevel = stdoutColor ? stdoutColor.level : 0;
12893 obj.level = options.level === undefined ? scLevel : options.level;
12894 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
12895}
12896
12897function Chalk(options) {
12898 // We check for this.template here since calling `chalk.constructor()`
12899 // by itself will have a `this` of a previously constructed chalk object
12900 if (!this || !(this instanceof Chalk) || this.template) {
12901 const chalk = {};
12902 applyOptions(chalk, options);
12903
12904 chalk.template = function () {
12905 const args = [].slice.call(arguments);
12906 return chalkTag.apply(null, [chalk.template].concat(args));
12907 };
12908
12909 Object.setPrototypeOf(chalk, Chalk.prototype);
12910 Object.setPrototypeOf(chalk.template, chalk);
12911
12912 chalk.template.constructor = Chalk;
12913
12914 return chalk.template;
12915 }
12916
12917 applyOptions(this, options);
12918}
12919
12920// Use bright blue on Windows as the normal blue color is illegible
12921if (isSimpleWindowsTerm) {
12922 ansiStyles.blue.open = '\u001B[94m';
12923}
12924
12925for (const key of Object.keys(ansiStyles)) {
12926 ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
12927
12928 styles[key] = {
12929 get() {
12930 const codes = ansiStyles[key];
12931 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
12932 }
12933 };
12934}
12935
12936styles.visible = {
12937 get() {
12938 return build.call(this, this._styles || [], true, 'visible');
12939 }
12940};
12941
12942ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
12943for (const model of Object.keys(ansiStyles.color.ansi)) {
12944 if (skipModels.has(model)) {
12945 continue;
12946 }
12947
12948 styles[model] = {
12949 get() {
12950 const level = this.level;
12951 return function () {
12952 const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
12953 const codes = {
12954 open,
12955 close: ansiStyles.color.close,
12956 closeRe: ansiStyles.color.closeRe
12957 };
12958 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
12959 };
12960 }
12961 };
12962}
12963
12964ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
12965for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
12966 if (skipModels.has(model)) {
12967 continue;
12968 }
12969
12970 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
12971 styles[bgModel] = {
12972 get() {
12973 const level = this.level;
12974 return function () {
12975 const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
12976 const codes = {
12977 open,
12978 close: ansiStyles.bgColor.close,
12979 closeRe: ansiStyles.bgColor.closeRe
12980 };
12981 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
12982 };
12983 }
12984 };
12985}
12986
12987const proto = Object.defineProperties(() => {}, styles);
12988
12989function build(_styles, _empty, key) {
12990 const builder = function () {
12991 return applyStyle.apply(builder, arguments);
12992 };
12993
12994 builder._styles = _styles;
12995 builder._empty = _empty;
12996
12997 const self = this;
12998
12999 Object.defineProperty(builder, 'level', {
13000 enumerable: true,
13001 get() {
13002 return self.level;
13003 },
13004 set(level) {
13005 self.level = level;
13006 }
13007 });
13008
13009 Object.defineProperty(builder, 'enabled', {
13010 enumerable: true,
13011 get() {
13012 return self.enabled;
13013 },
13014 set(enabled) {
13015 self.enabled = enabled;
13016 }
13017 });
13018
13019 // See below for fix regarding invisible grey/dim combination on Windows
13020 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
13021
13022 // `__proto__` is used because we must return a function, but there is
13023 // no way to create a function with a different prototype
13024 builder.__proto__ = proto; // eslint-disable-line no-proto
13025
13026 return builder;
13027}
13028
13029function applyStyle() {
13030 // Support varags, but simply cast to string in case there's only one arg
13031 const args = arguments;
13032 const argsLen = args.length;
13033 let str = String(arguments[0]);
13034
13035 if (argsLen === 0) {
13036 return '';
13037 }
13038
13039 if (argsLen > 1) {
13040 // Don't slice `arguments`, it prevents V8 optimizations
13041 for (let a = 1; a < argsLen; a++) {
13042 str += ' ' + args[a];
13043 }
13044 }
13045
13046 if (!this.enabled || this.level <= 0 || !str) {
13047 return this._empty ? '' : str;
13048 }
13049
13050 // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
13051 // see https://github.com/chalk/chalk/issues/58
13052 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
13053 const originalDim = ansiStyles.dim.open;
13054 if (isSimpleWindowsTerm && this.hasGrey) {
13055 ansiStyles.dim.open = '';
13056 }
13057
13058 for (const code of this._styles.slice().reverse()) {
13059 // Replace any instances already present with a re-opening code
13060 // otherwise only the part of the string until said closing code
13061 // will be colored, and the rest will simply be 'plain'.
13062 str = code.open + str.replace(code.closeRe, code.open) + code.close;
13063
13064 // Close the styling before a linebreak and reopen
13065 // after next line to fix a bleed issue on macOS
13066 // https://github.com/chalk/chalk/pull/92
13067 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
13068 }
13069
13070 // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
13071 ansiStyles.dim.open = originalDim;
13072
13073 return str;
13074}
13075
13076function chalkTag(chalk, strings) {
13077 if (!Array.isArray(strings)) {
13078 // If chalk() was called by itself or with a string,
13079 // return the string itself as a string.
13080 return [].slice.call(arguments, 1).join(' ');
13081 }
13082
13083 const args = [].slice.call(arguments, 2);
13084 const parts = [strings.raw[0]];
13085
13086 for (let i = 1; i < strings.length; i++) {
13087 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
13088 parts.push(String(strings.raw[i]));
13089 }
13090
13091 return templates(chalk, parts.join(''));
13092}
13093
13094Object.defineProperties(Chalk.prototype, styles);
13095
13096module.exports = Chalk(); // eslint-disable-line new-cap
13097module.exports.supportsColor = stdoutColor;
13098module.exports.default = module.exports; // For TypeScript
13099});
13100var chalk_1 = chalk.supportsColor;
13101
13102var mimicFn = (to, from) => {
13103 // TODO: use `Reflect.ownKeys()` when targeting Node.js 6
13104 for (const prop of Object.getOwnPropertyNames(from).concat(Object.getOwnPropertySymbols(from))) {
13105 Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
13106 }
13107
13108 return to;
13109};
13110
13111var onetime = (fn, opts) => {
13112 // TODO: Remove this in v3
13113 if (opts === true) {
13114 throw new TypeError('The second argument is now an options object');
13115 }
13116
13117 if (typeof fn !== 'function') {
13118 throw new TypeError('Expected a function');
13119 }
13120
13121 opts = opts || {};
13122
13123 let ret;
13124 let called = false;
13125 const fnName = fn.displayName || fn.name || '<anonymous>';
13126
13127 const onetime = function () {
13128 if (called) {
13129 if (opts.throw === true) {
13130 throw new Error(`Function \`${fnName}\` can only be called once`);
13131 }
13132
13133 return ret;
13134 }
13135
13136 called = true;
13137 ret = fn.apply(this, arguments);
13138 fn = null;
13139
13140 return ret;
13141 };
13142
13143 mimicFn(onetime, fn);
13144
13145 return onetime;
13146};
13147
13148var restoreCursor = onetime(() => {
13149 signalExit(() => {
13150 process.stderr.write('\u001b[?25h');
13151 }, {alwaysLast: true});
13152});
13153
13154var cliCursor = createCommonjsModule(function (module, exports) {
13155
13156
13157let hidden = false;
13158
13159exports.show = stream$$1 => {
13160 const s = stream$$1 || process.stderr;
13161
13162 if (!s.isTTY) {
13163 return;
13164 }
13165
13166 hidden = false;
13167 s.write('\u001b[?25h');
13168};
13169
13170exports.hide = stream$$1 => {
13171 const s = stream$$1 || process.stderr;
13172
13173 if (!s.isTTY) {
13174 return;
13175 }
13176
13177 restoreCursor();
13178 hidden = true;
13179 s.write('\u001b[?25l');
13180};
13181
13182exports.toggle = (force, stream$$1) => {
13183 if (force !== undefined) {
13184 hidden = force;
13185 }
13186
13187 if (hidden) {
13188 exports.show(stream$$1);
13189 } else {
13190 exports.hide(stream$$1);
13191 }
13192};
13193});
13194var cliCursor_1 = cliCursor.show;
13195var cliCursor_2 = cliCursor.hide;
13196var cliCursor_3 = cliCursor.toggle;
13197
13198var dots = {
13199 interval: 80,
13200 frames: [
13201 "⠋",
13202 "⠙",
13203 "⠹",
13204 "⠸",
13205 "⠼",
13206 "⠴",
13207 "⠦",
13208 "⠧",
13209 "⠇",
13210 "⠏"
13211 ]
13212};
13213var dots2 = {
13214 interval: 80,
13215 frames: [
13216 "⣾",
13217 "⣽",
13218 "⣻",
13219 "⢿",
13220 "⡿",
13221 "⣟",
13222 "⣯",
13223 "⣷"
13224 ]
13225};
13226var dots3 = {
13227 interval: 80,
13228 frames: [
13229 "⠋",
13230 "⠙",
13231 "⠚",
13232 "⠞",
13233 "⠖",
13234 "⠦",
13235 "⠴",
13236 "⠲",
13237 "⠳",
13238 "⠓"
13239 ]
13240};
13241var dots4 = {
13242 interval: 80,
13243 frames: [
13244 "⠄",
13245 "⠆",
13246 "⠇",
13247 "⠋",
13248 "⠙",
13249 "⠸",
13250 "⠰",
13251 "⠠",
13252 "⠰",
13253 "⠸",
13254 "⠙",
13255 "⠋",
13256 "⠇",
13257 "⠆"
13258 ]
13259};
13260var dots5 = {
13261 interval: 80,
13262 frames: [
13263 "⠋",
13264 "⠙",
13265 "⠚",
13266 "⠒",
13267 "⠂",
13268 "⠂",
13269 "⠒",
13270 "⠲",
13271 "⠴",
13272 "⠦",
13273 "⠖",
13274 "⠒",
13275 "⠐",
13276 "⠐",
13277 "⠒",
13278 "⠓",
13279 "⠋"
13280 ]
13281};
13282var dots6 = {
13283 interval: 80,
13284 frames: [
13285 "⠁",
13286 "⠉",
13287 "⠙",
13288 "⠚",
13289 "⠒",
13290 "⠂",
13291 "⠂",
13292 "⠒",
13293 "⠲",
13294 "⠴",
13295 "⠤",
13296 "⠄",
13297 "⠄",
13298 "⠤",
13299 "⠴",
13300 "⠲",
13301 "⠒",
13302 "⠂",
13303 "⠂",
13304 "⠒",
13305 "⠚",
13306 "⠙",
13307 "⠉",
13308 "⠁"
13309 ]
13310};
13311var dots7 = {
13312 interval: 80,
13313 frames: [
13314 "⠈",
13315 "⠉",
13316 "⠋",
13317 "⠓",
13318 "⠒",
13319 "⠐",
13320 "⠐",
13321 "⠒",
13322 "⠖",
13323 "⠦",
13324 "⠤",
13325 "⠠",
13326 "⠠",
13327 "⠤",
13328 "⠦",
13329 "⠖",
13330 "⠒",
13331 "⠐",
13332 "⠐",
13333 "⠒",
13334 "⠓",
13335 "⠋",
13336 "⠉",
13337 "⠈"
13338 ]
13339};
13340var dots8 = {
13341 interval: 80,
13342 frames: [
13343 "⠁",
13344 "⠁",
13345 "⠉",
13346 "⠙",
13347 "⠚",
13348 "⠒",
13349 "⠂",
13350 "⠂",
13351 "⠒",
13352 "⠲",
13353 "⠴",
13354 "⠤",
13355 "⠄",
13356 "⠄",
13357 "⠤",
13358 "⠠",
13359 "⠠",
13360 "⠤",
13361 "⠦",
13362 "⠖",
13363 "⠒",
13364 "⠐",
13365 "⠐",
13366 "⠒",
13367 "⠓",
13368 "⠋",
13369 "⠉",
13370 "⠈",
13371 "⠈"
13372 ]
13373};
13374var dots9 = {
13375 interval: 80,
13376 frames: [
13377 "⢹",
13378 "⢺",
13379 "⢼",
13380 "⣸",
13381 "⣇",
13382 "⡧",
13383 "⡗",
13384 "⡏"
13385 ]
13386};
13387var dots10 = {
13388 interval: 80,
13389 frames: [
13390 "⢄",
13391 "⢂",
13392 "⢁",
13393 "⡁",
13394 "⡈",
13395 "⡐",
13396 "⡠"
13397 ]
13398};
13399var dots11 = {
13400 interval: 100,
13401 frames: [
13402 "⠁",
13403 "⠂",
13404 "⠄",
13405 "⡀",
13406 "⢀",
13407 "⠠",
13408 "⠐",
13409 "⠈"
13410 ]
13411};
13412var dots12 = {
13413 interval: 80,
13414 frames: [
13415 "⢀⠀",
13416 "⡀⠀",
13417 "⠄⠀",
13418 "⢂⠀",
13419 "⡂⠀",
13420 "⠅⠀",
13421 "⢃⠀",
13422 "⡃⠀",
13423 "⠍⠀",
13424 "⢋⠀",
13425 "⡋⠀",
13426 "⠍⠁",
13427 "⢋⠁",
13428 "⡋⠁",
13429 "⠍⠉",
13430 "⠋⠉",
13431 "⠋⠉",
13432 "⠉⠙",
13433 "⠉⠙",
13434 "⠉⠩",
13435 "⠈⢙",
13436 "⠈⡙",
13437 "⢈⠩",
13438 "⡀⢙",
13439 "⠄⡙",
13440 "⢂⠩",
13441 "⡂⢘",
13442 "⠅⡘",
13443 "⢃⠨",
13444 "⡃⢐",
13445 "⠍⡐",
13446 "⢋⠠",
13447 "⡋⢀",
13448 "⠍⡁",
13449 "⢋⠁",
13450 "⡋⠁",
13451 "⠍⠉",
13452 "⠋⠉",
13453 "⠋⠉",
13454 "⠉⠙",
13455 "⠉⠙",
13456 "⠉⠩",
13457 "⠈⢙",
13458 "⠈⡙",
13459 "⠈⠩",
13460 "⠀⢙",
13461 "⠀⡙",
13462 "⠀⠩",
13463 "⠀⢘",
13464 "⠀⡘",
13465 "⠀⠨",
13466 "⠀⢐",
13467 "⠀⡐",
13468 "⠀⠠",
13469 "⠀⢀",
13470 "⠀⡀"
13471 ]
13472};
13473var line = {
13474 interval: 130,
13475 frames: [
13476 "-",
13477 "\\",
13478 "|",
13479 "/"
13480 ]
13481};
13482var line2 = {
13483 interval: 100,
13484 frames: [
13485 "⠂",
13486 "-",
13487 "–",
13488 "—",
13489 "–",
13490 "-"
13491 ]
13492};
13493var pipe$3 = {
13494 interval: 100,
13495 frames: [
13496 "┤",
13497 "┘",
13498 "┴",
13499 "└",
13500 "├",
13501 "┌",
13502 "┬",
13503 "┐"
13504 ]
13505};
13506var simpleDots = {
13507 interval: 400,
13508 frames: [
13509 ". ",
13510 ".. ",
13511 "...",
13512 " "
13513 ]
13514};
13515var simpleDotsScrolling = {
13516 interval: 200,
13517 frames: [
13518 ". ",
13519 ".. ",
13520 "...",
13521 " ..",
13522 " .",
13523 " "
13524 ]
13525};
13526var star = {
13527 interval: 70,
13528 frames: [
13529 "✶",
13530 "✸",
13531 "✹",
13532 "✺",
13533 "✹",
13534 "✷"
13535 ]
13536};
13537var star2 = {
13538 interval: 80,
13539 frames: [
13540 "+",
13541 "x",
13542 "*"
13543 ]
13544};
13545var flip = {
13546 interval: 70,
13547 frames: [
13548 "_",
13549 "_",
13550 "_",
13551 "-",
13552 "`",
13553 "`",
13554 "'",
13555 "´",
13556 "-",
13557 "_",
13558 "_",
13559 "_"
13560 ]
13561};
13562var hamburger = {
13563 interval: 100,
13564 frames: [
13565 "☱",
13566 "☲",
13567 "☴"
13568 ]
13569};
13570var growVertical = {
13571 interval: 120,
13572 frames: [
13573 "▁",
13574 "▃",
13575 "▄",
13576 "▅",
13577 "▆",
13578 "▇",
13579 "▆",
13580 "▅",
13581 "▄",
13582 "▃"
13583 ]
13584};
13585var growHorizontal = {
13586 interval: 120,
13587 frames: [
13588 "▏",
13589 "▎",
13590 "▍",
13591 "▌",
13592 "▋",
13593 "▊",
13594 "▉",
13595 "▊",
13596 "▋",
13597 "▌",
13598 "▍",
13599 "▎"
13600 ]
13601};
13602var balloon = {
13603 interval: 140,
13604 frames: [
13605 " ",
13606 ".",
13607 "o",
13608 "O",
13609 "@",
13610 "*",
13611 " "
13612 ]
13613};
13614var balloon2 = {
13615 interval: 120,
13616 frames: [
13617 ".",
13618 "o",
13619 "O",
13620 "°",
13621 "O",
13622 "o",
13623 "."
13624 ]
13625};
13626var noise = {
13627 interval: 100,
13628 frames: [
13629 "▓",
13630 "▒",
13631 "░"
13632 ]
13633};
13634var bounce = {
13635 interval: 120,
13636 frames: [
13637 "⠁",
13638 "⠂",
13639 "⠄",
13640 "⠂"
13641 ]
13642};
13643var boxBounce = {
13644 interval: 120,
13645 frames: [
13646 "▖",
13647 "▘",
13648 "▝",
13649 "▗"
13650 ]
13651};
13652var boxBounce2 = {
13653 interval: 100,
13654 frames: [
13655 "▌",
13656 "▀",
13657 "▐",
13658 "▄"
13659 ]
13660};
13661var triangle = {
13662 interval: 50,
13663 frames: [
13664 "◢",
13665 "◣",
13666 "◤",
13667 "◥"
13668 ]
13669};
13670var arc = {
13671 interval: 100,
13672 frames: [
13673 "◜",
13674 "◠",
13675 "◝",
13676 "◞",
13677 "◡",
13678 "◟"
13679 ]
13680};
13681var circle = {
13682 interval: 120,
13683 frames: [
13684 "◡",
13685 "⊙",
13686 "◠"
13687 ]
13688};
13689var squareCorners = {
13690 interval: 180,
13691 frames: [
13692 "◰",
13693 "◳",
13694 "◲",
13695 "◱"
13696 ]
13697};
13698var circleQuarters = {
13699 interval: 120,
13700 frames: [
13701 "◴",
13702 "◷",
13703 "◶",
13704 "◵"
13705 ]
13706};
13707var circleHalves = {
13708 interval: 50,
13709 frames: [
13710 "◐",
13711 "◓",
13712 "◑",
13713 "◒"
13714 ]
13715};
13716var squish = {
13717 interval: 100,
13718 frames: [
13719 "╫",
13720 "╪"
13721 ]
13722};
13723var toggle = {
13724 interval: 250,
13725 frames: [
13726 "⊶",
13727 "⊷"
13728 ]
13729};
13730var toggle2 = {
13731 interval: 80,
13732 frames: [
13733 "▫",
13734 "▪"
13735 ]
13736};
13737var toggle3 = {
13738 interval: 120,
13739 frames: [
13740 "□",
13741 "■"
13742 ]
13743};
13744var toggle4 = {
13745 interval: 100,
13746 frames: [
13747 "■",
13748 "□",
13749 "▪",
13750 "▫"
13751 ]
13752};
13753var toggle5 = {
13754 interval: 100,
13755 frames: [
13756 "▮",
13757 "▯"
13758 ]
13759};
13760var toggle6 = {
13761 interval: 300,
13762 frames: [
13763 "ဝ",
13764 "၀"
13765 ]
13766};
13767var toggle7 = {
13768 interval: 80,
13769 frames: [
13770 "⦾",
13771 "⦿"
13772 ]
13773};
13774var toggle8 = {
13775 interval: 100,
13776 frames: [
13777 "◍",
13778 "◌"
13779 ]
13780};
13781var toggle9 = {
13782 interval: 100,
13783 frames: [
13784 "◉",
13785 "◎"
13786 ]
13787};
13788var toggle10 = {
13789 interval: 100,
13790 frames: [
13791 "㊂",
13792 "㊀",
13793 "㊁"
13794 ]
13795};
13796var toggle11 = {
13797 interval: 50,
13798 frames: [
13799 "⧇",
13800 "⧆"
13801 ]
13802};
13803var toggle12 = {
13804 interval: 120,
13805 frames: [
13806 "☗",
13807 "☖"
13808 ]
13809};
13810var toggle13 = {
13811 interval: 80,
13812 frames: [
13813 "=",
13814 "*",
13815 "-"
13816 ]
13817};
13818var arrow = {
13819 interval: 100,
13820 frames: [
13821 "←",
13822 "↖",
13823 "↑",
13824 "↗",
13825 "→",
13826 "↘",
13827 "↓",
13828 "↙"
13829 ]
13830};
13831var arrow2 = {
13832 interval: 80,
13833 frames: [
13834 "⬆️ ",
13835 "↗️ ",
13836 "➡️ ",
13837 "↘️ ",
13838 "⬇️ ",
13839 "↙️ ",
13840 "⬅️ ",
13841 "↖️ "
13842 ]
13843};
13844var arrow3 = {
13845 interval: 120,
13846 frames: [
13847 "▹▹▹▹▹",
13848 "▸▹▹▹▹",
13849 "▹▸▹▹▹",
13850 "▹▹▸▹▹",
13851 "▹▹▹▸▹",
13852 "▹▹▹▹▸"
13853 ]
13854};
13855var bouncingBar = {
13856 interval: 80,
13857 frames: [
13858 "[ ]",
13859 "[= ]",
13860 "[== ]",
13861 "[=== ]",
13862 "[ ===]",
13863 "[ ==]",
13864 "[ =]",
13865 "[ ]",
13866 "[ =]",
13867 "[ ==]",
13868 "[ ===]",
13869 "[====]",
13870 "[=== ]",
13871 "[== ]",
13872 "[= ]"
13873 ]
13874};
13875var bouncingBall = {
13876 interval: 80,
13877 frames: [
13878 "( ● )",
13879 "( ● )",
13880 "( ● )",
13881 "( ● )",
13882 "( ●)",
13883 "( ● )",
13884 "( ● )",
13885 "( ● )",
13886 "( ● )",
13887 "(● )"
13888 ]
13889};
13890var smiley = {
13891 interval: 200,
13892 frames: [
13893 "😄 ",
13894 "😝 "
13895 ]
13896};
13897var monkey = {
13898 interval: 300,
13899 frames: [
13900 "🙈 ",
13901 "🙈 ",
13902 "🙉 ",
13903 "🙊 "
13904 ]
13905};
13906var hearts = {
13907 interval: 100,
13908 frames: [
13909 "💛 ",
13910 "💙 ",
13911 "💜 ",
13912 "💚 ",
13913 "❤️ "
13914 ]
13915};
13916var clock = {
13917 interval: 100,
13918 frames: [
13919 "🕛 ",
13920 "🕐 ",
13921 "🕑 ",
13922 "🕒 ",
13923 "🕓 ",
13924 "🕔 ",
13925 "🕕 ",
13926 "🕖 ",
13927 "🕗 ",
13928 "🕘 ",
13929 "🕙 ",
13930 "🕚 "
13931 ]
13932};
13933var earth = {
13934 interval: 180,
13935 frames: [
13936 "🌍 ",
13937 "🌎 ",
13938 "🌏 "
13939 ]
13940};
13941var moon = {
13942 interval: 80,
13943 frames: [
13944 "🌑 ",
13945 "🌒 ",
13946 "🌓 ",
13947 "🌔 ",
13948 "🌕 ",
13949 "🌖 ",
13950 "🌗 ",
13951 "🌘 "
13952 ]
13953};
13954var runner = {
13955 interval: 140,
13956 frames: [
13957 "🚶 ",
13958 "🏃 "
13959 ]
13960};
13961var pong = {
13962 interval: 80,
13963 frames: [
13964 "▐⠂ ▌",
13965 "▐⠈ ▌",
13966 "▐ ⠂ ▌",
13967 "▐ ⠠ ▌",
13968 "▐ ⡀ ▌",
13969 "▐ ⠠ ▌",
13970 "▐ ⠂ ▌",
13971 "▐ ⠈ ▌",
13972 "▐ ⠂ ▌",
13973 "▐ ⠠ ▌",
13974 "▐ ⡀ ▌",
13975 "▐ ⠠ ▌",
13976 "▐ ⠂ ▌",
13977 "▐ ⠈ ▌",
13978 "▐ ⠂▌",
13979 "▐ ⠠▌",
13980 "▐ ⡀▌",
13981 "▐ ⠠ ▌",
13982 "▐ ⠂ ▌",
13983 "▐ ⠈ ▌",
13984 "▐ ⠂ ▌",
13985 "▐ ⠠ ▌",
13986 "▐ ⡀ ▌",
13987 "▐ ⠠ ▌",
13988 "▐ ⠂ ▌",
13989 "▐ ⠈ ▌",
13990 "▐ ⠂ ▌",
13991 "▐ ⠠ ▌",
13992 "▐ ⡀ ▌",
13993 "▐⠠ ▌"
13994 ]
13995};
13996var shark = {
13997 interval: 120,
13998 frames: [
13999 "▐|\\____________▌",
14000 "▐_|\\___________▌",
14001 "▐__|\\__________▌",
14002 "▐___|\\_________▌",
14003 "▐____|\\________▌",
14004 "▐_____|\\_______▌",
14005 "▐______|\\______▌",
14006 "▐_______|\\_____▌",
14007 "▐________|\\____▌",
14008 "▐_________|\\___▌",
14009 "▐__________|\\__▌",
14010 "▐___________|\\_▌",
14011 "▐____________|\\▌",
14012 "▐____________/|▌",
14013 "▐___________/|_▌",
14014 "▐__________/|__▌",
14015 "▐_________/|___▌",
14016 "▐________/|____▌",
14017 "▐_______/|_____▌",
14018 "▐______/|______▌",
14019 "▐_____/|_______▌",
14020 "▐____/|________▌",
14021 "▐___/|_________▌",
14022 "▐__/|__________▌",
14023 "▐_/|___________▌",
14024 "▐/|____________▌"
14025 ]
14026};
14027var dqpb = {
14028 interval: 100,
14029 frames: [
14030 "d",
14031 "q",
14032 "p",
14033 "b"
14034 ]
14035};
14036var weather = {
14037 interval: 100,
14038 frames: [
14039 "☀️ ",
14040 "☀️ ",
14041 "☀️ ",
14042 "🌤 ",
14043 "⛅️ ",
14044 "🌥 ",
14045 "☁️ ",
14046 "🌧 ",
14047 "🌨 ",
14048 "🌧 ",
14049 "🌨 ",
14050 "🌧 ",
14051 "🌨 ",
14052 "⛈ ",
14053 "🌨 ",
14054 "🌧 ",
14055 "🌨 ",
14056 "☁️ ",
14057 "🌥 ",
14058 "⛅️ ",
14059 "🌤 ",
14060 "☀️ ",
14061 "☀️ "
14062 ]
14063};
14064var christmas = {
14065 interval: 400,
14066 frames: [
14067 "🌲",
14068 "🎄"
14069 ]
14070};
14071var grenade = {
14072 interval: 80,
14073 frames: [
14074 "، ",
14075 "′ ",
14076 " ´ ",
14077 " ‾ ",
14078 " ⸌",
14079 " ⸊",
14080 " |",
14081 " ⁎",
14082 " ⁕",
14083 " ෴ ",
14084 " ⁓",
14085 " ",
14086 " ",
14087 " "
14088 ]
14089};
14090var point = {
14091 interval: 125,
14092 frames: [
14093 "∙∙∙",
14094 "●∙∙",
14095 "∙●∙",
14096 "∙∙●",
14097 "∙∙∙"
14098 ]
14099};
14100var layer = {
14101 interval: 150,
14102 frames: [
14103 "-",
14104 "=",
14105 "≡"
14106 ]
14107};
14108var spinners = {
14109 dots: dots,
14110 dots2: dots2,
14111 dots3: dots3,
14112 dots4: dots4,
14113 dots5: dots5,
14114 dots6: dots6,
14115 dots7: dots7,
14116 dots8: dots8,
14117 dots9: dots9,
14118 dots10: dots10,
14119 dots11: dots11,
14120 dots12: dots12,
14121 line: line,
14122 line2: line2,
14123 pipe: pipe$3,
14124 simpleDots: simpleDots,
14125 simpleDotsScrolling: simpleDotsScrolling,
14126 star: star,
14127 star2: star2,
14128 flip: flip,
14129 hamburger: hamburger,
14130 growVertical: growVertical,
14131 growHorizontal: growHorizontal,
14132 balloon: balloon,
14133 balloon2: balloon2,
14134 noise: noise,
14135 bounce: bounce,
14136 boxBounce: boxBounce,
14137 boxBounce2: boxBounce2,
14138 triangle: triangle,
14139 arc: arc,
14140 circle: circle,
14141 squareCorners: squareCorners,
14142 circleQuarters: circleQuarters,
14143 circleHalves: circleHalves,
14144 squish: squish,
14145 toggle: toggle,
14146 toggle2: toggle2,
14147 toggle3: toggle3,
14148 toggle4: toggle4,
14149 toggle5: toggle5,
14150 toggle6: toggle6,
14151 toggle7: toggle7,
14152 toggle8: toggle8,
14153 toggle9: toggle9,
14154 toggle10: toggle10,
14155 toggle11: toggle11,
14156 toggle12: toggle12,
14157 toggle13: toggle13,
14158 arrow: arrow,
14159 arrow2: arrow2,
14160 arrow3: arrow3,
14161 bouncingBar: bouncingBar,
14162 bouncingBall: bouncingBall,
14163 smiley: smiley,
14164 monkey: monkey,
14165 hearts: hearts,
14166 clock: clock,
14167 earth: earth,
14168 moon: moon,
14169 runner: runner,
14170 pong: pong,
14171 shark: shark,
14172 dqpb: dqpb,
14173 weather: weather,
14174 christmas: christmas,
14175 grenade: grenade,
14176 point: point,
14177 layer: layer
14178};
14179
14180var spinners$1 = /*#__PURE__*/Object.freeze({
14181 dots: dots,
14182 dots2: dots2,
14183 dots3: dots3,
14184 dots4: dots4,
14185 dots5: dots5,
14186 dots6: dots6,
14187 dots7: dots7,
14188 dots8: dots8,
14189 dots9: dots9,
14190 dots10: dots10,
14191 dots11: dots11,
14192 dots12: dots12,
14193 line: line,
14194 line2: line2,
14195 pipe: pipe$3,
14196 simpleDots: simpleDots,
14197 simpleDotsScrolling: simpleDotsScrolling,
14198 star: star,
14199 star2: star2,
14200 flip: flip,
14201 hamburger: hamburger,
14202 growVertical: growVertical,
14203 growHorizontal: growHorizontal,
14204 balloon: balloon,
14205 balloon2: balloon2,
14206 noise: noise,
14207 bounce: bounce,
14208 boxBounce: boxBounce,
14209 boxBounce2: boxBounce2,
14210 triangle: triangle,
14211 arc: arc,
14212 circle: circle,
14213 squareCorners: squareCorners,
14214 circleQuarters: circleQuarters,
14215 circleHalves: circleHalves,
14216 squish: squish,
14217 toggle: toggle,
14218 toggle2: toggle2,
14219 toggle3: toggle3,
14220 toggle4: toggle4,
14221 toggle5: toggle5,
14222 toggle6: toggle6,
14223 toggle7: toggle7,
14224 toggle8: toggle8,
14225 toggle9: toggle9,
14226 toggle10: toggle10,
14227 toggle11: toggle11,
14228 toggle12: toggle12,
14229 toggle13: toggle13,
14230 arrow: arrow,
14231 arrow2: arrow2,
14232 arrow3: arrow3,
14233 bouncingBar: bouncingBar,
14234 bouncingBall: bouncingBall,
14235 smiley: smiley,
14236 monkey: monkey,
14237 hearts: hearts,
14238 clock: clock,
14239 earth: earth,
14240 moon: moon,
14241 runner: runner,
14242 pong: pong,
14243 shark: shark,
14244 dqpb: dqpb,
14245 weather: weather,
14246 christmas: christmas,
14247 grenade: grenade,
14248 point: point,
14249 layer: layer,
14250 default: spinners
14251});
14252
14253var require$$0 = getCjsExportFromNamespace(spinners$1);
14254
14255var cliSpinners = require$$0;
14256
14257const isSupported = process.platform !== 'win32' || process.env.CI || process.env.TERM === 'xterm-256color';
14258
14259const main$1 = {
14260 info: chalk.blue('ℹ'),
14261 success: chalk.green('✔'),
14262 warning: chalk.yellow('⚠'),
14263 error: chalk.red('✖')
14264};
14265
14266const fallbacks = {
14267 info: chalk.blue('i'),
14268 success: chalk.green('√'),
14269 warning: chalk.yellow('‼'),
14270 error: chalk.red('×')
14271};
14272
14273var logSymbols = isSupported ? main$1 : fallbacks;
14274
14275var clone_1 = createCommonjsModule(function (module) {
14276var clone = (function() {
14277
14278/**
14279 * Clones (copies) an Object using deep copying.
14280 *
14281 * This function supports circular references by default, but if you are certain
14282 * there are no circular references in your object, you can save some CPU time
14283 * by calling clone(obj, false).
14284 *
14285 * Caution: if `circular` is false and `parent` contains circular references,
14286 * your program may enter an infinite loop and crash.
14287 *
14288 * @param `parent` - the object to be cloned
14289 * @param `circular` - set to true if the object to be cloned may contain
14290 * circular references. (optional - true by default)
14291 * @param `depth` - set to a number if the object is only to be cloned to
14292 * a particular depth. (optional - defaults to Infinity)
14293 * @param `prototype` - sets the prototype to be used when cloning an object.
14294 * (optional - defaults to parent prototype).
14295*/
14296function clone(parent, circular, depth, prototype) {
14297 var filter;
14298 if (typeof circular === 'object') {
14299 depth = circular.depth;
14300 prototype = circular.prototype;
14301 filter = circular.filter;
14302 circular = circular.circular;
14303 }
14304 // maintain two arrays for circular references, where corresponding parents
14305 // and children have the same index
14306 var allParents = [];
14307 var allChildren = [];
14308
14309 var useBuffer = typeof Buffer != 'undefined';
14310
14311 if (typeof circular == 'undefined')
14312 circular = true;
14313
14314 if (typeof depth == 'undefined')
14315 depth = Infinity;
14316
14317 // recurse this function so we don't reset allParents and allChildren
14318 function _clone(parent, depth) {
14319 // cloning null always returns null
14320 if (parent === null)
14321 return null;
14322
14323 if (depth == 0)
14324 return parent;
14325
14326 var child;
14327 var proto;
14328 if (typeof parent != 'object') {
14329 return parent;
14330 }
14331
14332 if (clone.__isArray(parent)) {
14333 child = [];
14334 } else if (clone.__isRegExp(parent)) {
14335 child = new RegExp(parent.source, __getRegExpFlags(parent));
14336 if (parent.lastIndex) child.lastIndex = parent.lastIndex;
14337 } else if (clone.__isDate(parent)) {
14338 child = new Date(parent.getTime());
14339 } else if (useBuffer && Buffer.isBuffer(parent)) {
14340 if (Buffer.allocUnsafe) {
14341 // Node.js >= 4.5.0
14342 child = Buffer.allocUnsafe(parent.length);
14343 } else {
14344 // Older Node.js versions
14345 child = new Buffer(parent.length);
14346 }
14347 parent.copy(child);
14348 return child;
14349 } else {
14350 if (typeof prototype == 'undefined') {
14351 proto = Object.getPrototypeOf(parent);
14352 child = Object.create(proto);
14353 }
14354 else {
14355 child = Object.create(prototype);
14356 proto = prototype;
14357 }
14358 }
14359
14360 if (circular) {
14361 var index = allParents.indexOf(parent);
14362
14363 if (index != -1) {
14364 return allChildren[index];
14365 }
14366 allParents.push(parent);
14367 allChildren.push(child);
14368 }
14369
14370 for (var i in parent) {
14371 var attrs;
14372 if (proto) {
14373 attrs = Object.getOwnPropertyDescriptor(proto, i);
14374 }
14375
14376 if (attrs && attrs.set == null) {
14377 continue;
14378 }
14379 child[i] = _clone(parent[i], depth - 1);
14380 }
14381
14382 return child;
14383 }
14384
14385 return _clone(parent, depth);
14386}
14387
14388/**
14389 * Simple flat clone using prototype, accepts only objects, usefull for property
14390 * override on FLAT configuration object (no nested props).
14391 *
14392 * USE WITH CAUTION! This may not behave as you wish if you do not know how this
14393 * works.
14394 */
14395clone.clonePrototype = function clonePrototype(parent) {
14396 if (parent === null)
14397 return null;
14398
14399 var c = function () {};
14400 c.prototype = parent;
14401 return new c();
14402};
14403
14404// private utility functions
14405
14406function __objToStr(o) {
14407 return Object.prototype.toString.call(o);
14408}clone.__objToStr = __objToStr;
14409
14410function __isDate(o) {
14411 return typeof o === 'object' && __objToStr(o) === '[object Date]';
14412}clone.__isDate = __isDate;
14413
14414function __isArray(o) {
14415 return typeof o === 'object' && __objToStr(o) === '[object Array]';
14416}clone.__isArray = __isArray;
14417
14418function __isRegExp(o) {
14419 return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
14420}clone.__isRegExp = __isRegExp;
14421
14422function __getRegExpFlags(re) {
14423 var flags = '';
14424 if (re.global) flags += 'g';
14425 if (re.ignoreCase) flags += 'i';
14426 if (re.multiline) flags += 'm';
14427 return flags;
14428}clone.__getRegExpFlags = __getRegExpFlags;
14429
14430return clone;
14431})();
14432
14433if (module.exports) {
14434 module.exports = clone;
14435}
14436});
14437
14438var defaults$3 = function(options, defaults) {
14439 options = options || {};
14440
14441 Object.keys(defaults).forEach(function(key) {
14442 if (typeof options[key] === 'undefined') {
14443 options[key] = clone_1(defaults[key]);
14444 }
14445 });
14446
14447 return options;
14448};
14449
14450var combining = [
14451 [ 0x0300, 0x036F ], [ 0x0483, 0x0486 ], [ 0x0488, 0x0489 ],
14452 [ 0x0591, 0x05BD ], [ 0x05BF, 0x05BF ], [ 0x05C1, 0x05C2 ],
14453 [ 0x05C4, 0x05C5 ], [ 0x05C7, 0x05C7 ], [ 0x0600, 0x0603 ],
14454 [ 0x0610, 0x0615 ], [ 0x064B, 0x065E ], [ 0x0670, 0x0670 ],
14455 [ 0x06D6, 0x06E4 ], [ 0x06E7, 0x06E8 ], [ 0x06EA, 0x06ED ],
14456 [ 0x070F, 0x070F ], [ 0x0711, 0x0711 ], [ 0x0730, 0x074A ],
14457 [ 0x07A6, 0x07B0 ], [ 0x07EB, 0x07F3 ], [ 0x0901, 0x0902 ],
14458 [ 0x093C, 0x093C ], [ 0x0941, 0x0948 ], [ 0x094D, 0x094D ],
14459 [ 0x0951, 0x0954 ], [ 0x0962, 0x0963 ], [ 0x0981, 0x0981 ],
14460 [ 0x09BC, 0x09BC ], [ 0x09C1, 0x09C4 ], [ 0x09CD, 0x09CD ],
14461 [ 0x09E2, 0x09E3 ], [ 0x0A01, 0x0A02 ], [ 0x0A3C, 0x0A3C ],
14462 [ 0x0A41, 0x0A42 ], [ 0x0A47, 0x0A48 ], [ 0x0A4B, 0x0A4D ],
14463 [ 0x0A70, 0x0A71 ], [ 0x0A81, 0x0A82 ], [ 0x0ABC, 0x0ABC ],
14464 [ 0x0AC1, 0x0AC5 ], [ 0x0AC7, 0x0AC8 ], [ 0x0ACD, 0x0ACD ],
14465 [ 0x0AE2, 0x0AE3 ], [ 0x0B01, 0x0B01 ], [ 0x0B3C, 0x0B3C ],
14466 [ 0x0B3F, 0x0B3F ], [ 0x0B41, 0x0B43 ], [ 0x0B4D, 0x0B4D ],
14467 [ 0x0B56, 0x0B56 ], [ 0x0B82, 0x0B82 ], [ 0x0BC0, 0x0BC0 ],
14468 [ 0x0BCD, 0x0BCD ], [ 0x0C3E, 0x0C40 ], [ 0x0C46, 0x0C48 ],
14469 [ 0x0C4A, 0x0C4D ], [ 0x0C55, 0x0C56 ], [ 0x0CBC, 0x0CBC ],
14470 [ 0x0CBF, 0x0CBF ], [ 0x0CC6, 0x0CC6 ], [ 0x0CCC, 0x0CCD ],
14471 [ 0x0CE2, 0x0CE3 ], [ 0x0D41, 0x0D43 ], [ 0x0D4D, 0x0D4D ],
14472 [ 0x0DCA, 0x0DCA ], [ 0x0DD2, 0x0DD4 ], [ 0x0DD6, 0x0DD6 ],
14473 [ 0x0E31, 0x0E31 ], [ 0x0E34, 0x0E3A ], [ 0x0E47, 0x0E4E ],
14474 [ 0x0EB1, 0x0EB1 ], [ 0x0EB4, 0x0EB9 ], [ 0x0EBB, 0x0EBC ],
14475 [ 0x0EC8, 0x0ECD ], [ 0x0F18, 0x0F19 ], [ 0x0F35, 0x0F35 ],
14476 [ 0x0F37, 0x0F37 ], [ 0x0F39, 0x0F39 ], [ 0x0F71, 0x0F7E ],
14477 [ 0x0F80, 0x0F84 ], [ 0x0F86, 0x0F87 ], [ 0x0F90, 0x0F97 ],
14478 [ 0x0F99, 0x0FBC ], [ 0x0FC6, 0x0FC6 ], [ 0x102D, 0x1030 ],
14479 [ 0x1032, 0x1032 ], [ 0x1036, 0x1037 ], [ 0x1039, 0x1039 ],
14480 [ 0x1058, 0x1059 ], [ 0x1160, 0x11FF ], [ 0x135F, 0x135F ],
14481 [ 0x1712, 0x1714 ], [ 0x1732, 0x1734 ], [ 0x1752, 0x1753 ],
14482 [ 0x1772, 0x1773 ], [ 0x17B4, 0x17B5 ], [ 0x17B7, 0x17BD ],
14483 [ 0x17C6, 0x17C6 ], [ 0x17C9, 0x17D3 ], [ 0x17DD, 0x17DD ],
14484 [ 0x180B, 0x180D ], [ 0x18A9, 0x18A9 ], [ 0x1920, 0x1922 ],
14485 [ 0x1927, 0x1928 ], [ 0x1932, 0x1932 ], [ 0x1939, 0x193B ],
14486 [ 0x1A17, 0x1A18 ], [ 0x1B00, 0x1B03 ], [ 0x1B34, 0x1B34 ],
14487 [ 0x1B36, 0x1B3A ], [ 0x1B3C, 0x1B3C ], [ 0x1B42, 0x1B42 ],
14488 [ 0x1B6B, 0x1B73 ], [ 0x1DC0, 0x1DCA ], [ 0x1DFE, 0x1DFF ],
14489 [ 0x200B, 0x200F ], [ 0x202A, 0x202E ], [ 0x2060, 0x2063 ],
14490 [ 0x206A, 0x206F ], [ 0x20D0, 0x20EF ], [ 0x302A, 0x302F ],
14491 [ 0x3099, 0x309A ], [ 0xA806, 0xA806 ], [ 0xA80B, 0xA80B ],
14492 [ 0xA825, 0xA826 ], [ 0xFB1E, 0xFB1E ], [ 0xFE00, 0xFE0F ],
14493 [ 0xFE20, 0xFE23 ], [ 0xFEFF, 0xFEFF ], [ 0xFFF9, 0xFFFB ],
14494 [ 0x10A01, 0x10A03 ], [ 0x10A05, 0x10A06 ], [ 0x10A0C, 0x10A0F ],
14495 [ 0x10A38, 0x10A3A ], [ 0x10A3F, 0x10A3F ], [ 0x1D167, 0x1D169 ],
14496 [ 0x1D173, 0x1D182 ], [ 0x1D185, 0x1D18B ], [ 0x1D1AA, 0x1D1AD ],
14497 [ 0x1D242, 0x1D244 ], [ 0xE0001, 0xE0001 ], [ 0xE0020, 0xE007F ],
14498 [ 0xE0100, 0xE01EF ]
14499];
14500
14501var DEFAULTS = {
14502 nul: 0,
14503 control: 0
14504};
14505
14506var wcwidth_1 = function wcwidth(str) {
14507 return wcswidth(str, DEFAULTS)
14508};
14509
14510var config$1 = function(opts) {
14511 opts = defaults$3(opts || {}, DEFAULTS);
14512 return function wcwidth(str) {
14513 return wcswidth(str, opts)
14514 }
14515};
14516
14517/*
14518 * The following functions define the column width of an ISO 10646
14519 * character as follows:
14520 * - The null character (U+0000) has a column width of 0.
14521 * - Other C0/C1 control characters and DEL will lead to a return value
14522 * of -1.
14523 * - Non-spacing and enclosing combining characters (general category
14524 * code Mn or Me in the
14525 * Unicode database) have a column width of 0.
14526 * - SOFT HYPHEN (U+00AD) has a column width of 1.
14527 * - Other format characters (general category code Cf in the Unicode
14528 * database) and ZERO WIDTH
14529 * SPACE (U+200B) have a column width of 0.
14530 * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF)
14531 * have a column width of 0.
14532 * - Spacing characters in the East Asian Wide (W) or East Asian
14533 * Full-width (F) category as
14534 * defined in Unicode Technical Report #11 have a column width of 2.
14535 * - All remaining characters (including all printable ISO 8859-1 and
14536 * WGL4 characters, Unicode control characters, etc.) have a column
14537 * width of 1.
14538 * This implementation assumes that characters are encoded in ISO 10646.
14539*/
14540
14541function wcswidth(str, opts) {
14542 if (typeof str !== 'string') return wcwidth(str, opts)
14543
14544 var s = 0;
14545 for (var i = 0; i < str.length; i++) {
14546 var n = wcwidth(str.charCodeAt(i), opts);
14547 if (n < 0) return -1
14548 s += n;
14549 }
14550
14551 return s
14552}
14553
14554function wcwidth(ucs, opts) {
14555 // test for 8-bit control characters
14556 if (ucs === 0) return opts.nul
14557 if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) return opts.control
14558
14559 // binary search in table of non-spacing characters
14560 if (bisearch(ucs)) return 0
14561
14562 // if we arrive here, ucs is not a combining or C0/C1 control character
14563 return 1 +
14564 (ucs >= 0x1100 &&
14565 (ucs <= 0x115f || // Hangul Jamo init. consonants
14566 ucs == 0x2329 || ucs == 0x232a ||
14567 (ucs >= 0x2e80 && ucs <= 0xa4cf &&
14568 ucs != 0x303f) || // CJK ... Yi
14569 (ucs >= 0xac00 && ucs <= 0xd7a3) || // Hangul Syllables
14570 (ucs >= 0xf900 && ucs <= 0xfaff) || // CJK Compatibility Ideographs
14571 (ucs >= 0xfe10 && ucs <= 0xfe19) || // Vertical forms
14572 (ucs >= 0xfe30 && ucs <= 0xfe6f) || // CJK Compatibility Forms
14573 (ucs >= 0xff00 && ucs <= 0xff60) || // Fullwidth Forms
14574 (ucs >= 0xffe0 && ucs <= 0xffe6) ||
14575 (ucs >= 0x20000 && ucs <= 0x2fffd) ||
14576 (ucs >= 0x30000 && ucs <= 0x3fffd)));
14577}
14578
14579function bisearch(ucs) {
14580 var min = 0;
14581 var max = combining.length - 1;
14582 var mid;
14583
14584 if (ucs < combining[0][0] || ucs > combining[max][1]) return false
14585
14586 while (max >= min) {
14587 mid = Math.floor((min + max) / 2);
14588 if (ucs > combining[mid][1]) min = mid + 1;
14589 else if (ucs < combining[mid][0]) max = mid - 1;
14590 else return true
14591 }
14592
14593 return false
14594}
14595wcwidth_1.config = config$1;
14596
14597const TEXT = Symbol('text');
14598
14599class Ora {
14600 constructor(options) {
14601 if (typeof options === 'string') {
14602 options = {
14603 text: options
14604 };
14605 }
14606
14607 this.options = Object.assign({
14608 text: '',
14609 color: 'cyan',
14610 stream: process.stderr
14611 }, options);
14612
14613 const sp = this.options.spinner;
14614 this.spinner = typeof sp === 'object' ? sp : (process.platform === 'win32' ? cliSpinners.line : (cliSpinners[sp] || cliSpinners.dots)); // eslint-disable-line no-nested-ternary
14615
14616 if (this.spinner.frames === undefined) {
14617 throw new Error('Spinner must define `frames`');
14618 }
14619
14620 this.color = this.options.color;
14621 this.hideCursor = this.options.hideCursor !== false;
14622 this.interval = this.options.interval || this.spinner.interval || 100;
14623 this.stream = this.options.stream;
14624 this.id = null;
14625 this.frameIndex = 0;
14626 this.isEnabled = typeof this.options.isEnabled === 'boolean' ? this.options.isEnabled : ((this.stream && this.stream.isTTY) && !process.env.CI);
14627
14628 // Set *after* `this.stream`
14629 this.text = this.options.text;
14630 this.linesToClear = 0;
14631 }
14632
14633 get text() {
14634 return this[TEXT];
14635 }
14636
14637 get isSpinning() {
14638 return this.id !== null;
14639 }
14640
14641 set text(value) {
14642 this[TEXT] = value;
14643 const columns = this.stream.columns || 80;
14644 this.lineCount = stripAnsi('--' + value).split('\n').reduce((count, line) => {
14645 return count + Math.max(1, Math.ceil(wcwidth_1(line) / columns));
14646 }, 0);
14647 }
14648
14649 frame() {
14650 const {frames} = this.spinner;
14651 let frame = frames[this.frameIndex];
14652
14653 if (this.color) {
14654 frame = chalk[this.color](frame);
14655 }
14656
14657 this.frameIndex = ++this.frameIndex % frames.length;
14658
14659 return frame + ' ' + this.text;
14660 }
14661
14662 clear() {
14663 if (!this.isEnabled || !this.stream.isTTY) {
14664 return this;
14665 }
14666
14667 for (let i = 0; i < this.linesToClear; i++) {
14668 if (i > 0) {
14669 this.stream.moveCursor(0, -1);
14670 }
14671 this.stream.clearLine();
14672 this.stream.cursorTo(0);
14673 }
14674 this.linesToClear = 0;
14675
14676 return this;
14677 }
14678
14679 render() {
14680 this.clear();
14681 this.stream.write(this.frame());
14682 this.linesToClear = this.lineCount;
14683
14684 return this;
14685 }
14686
14687 start(text) {
14688 if (text) {
14689 this.text = text;
14690 }
14691
14692 if (!this.isEnabled) {
14693 this.stream.write(`- ${this.text}\n`);
14694 return this;
14695 }
14696
14697 if (this.isSpinning) {
14698 return this;
14699 }
14700
14701 if (this.hideCursor) {
14702 cliCursor.hide(this.stream);
14703 }
14704
14705 this.render();
14706 this.id = setInterval(this.render.bind(this), this.interval);
14707
14708 return this;
14709 }
14710
14711 stop() {
14712 if (!this.isEnabled) {
14713 return this;
14714 }
14715
14716 clearInterval(this.id);
14717 this.id = null;
14718 this.frameIndex = 0;
14719 this.clear();
14720 if (this.hideCursor) {
14721 cliCursor.show(this.stream);
14722 }
14723
14724 return this;
14725 }
14726
14727 succeed(text) {
14728 return this.stopAndPersist({symbol: logSymbols.success, text});
14729 }
14730
14731 fail(text) {
14732 return this.stopAndPersist({symbol: logSymbols.error, text});
14733 }
14734
14735 warn(text) {
14736 return this.stopAndPersist({symbol: logSymbols.warning, text});
14737 }
14738
14739 info(text) {
14740 return this.stopAndPersist({symbol: logSymbols.info, text});
14741 }
14742
14743 stopAndPersist(options = {}) {
14744 this.stop();
14745 this.stream.write(`${options.symbol || ' '} ${options.text || this.text}\n`);
14746
14747 return this;
14748 }
14749}
14750
14751var ora = function (opts) {
14752 return new Ora(opts);
14753};
14754
14755var promise = (action, options) => {
14756 if (typeof action.then !== 'function') {
14757 throw new TypeError('Parameter `action` must be a Promise');
14758 }
14759
14760 const spinner = new Ora(options);
14761 spinner.start();
14762
14763 action.then(
14764 () => {
14765 spinner.succeed();
14766 },
14767 () => {
14768 spinner.fail();
14769 }
14770 );
14771
14772 return spinner;
14773};
14774ora.promise = promise;
14775
14776var toString$1 = Object.prototype.toString;
14777
14778var isPlainObj = function (x) {
14779 var prototype;
14780 return toString$1.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({}));
14781};
14782
14783var arrify = function (val) {
14784 if (val === null || val === undefined) {
14785 return [];
14786 }
14787
14788 return Array.isArray(val) ? val : [val];
14789};
14790
14791const push = (obj, prop, value) => {
14792 if (!obj[prop]) {
14793 obj[prop] = [];
14794 }
14795
14796 obj[prop].push(value);
14797};
14798
14799const insert = (obj, prop, key, value) => {
14800 if (!obj[prop]) {
14801 obj[prop] = {};
14802 }
14803
14804 obj[prop][key] = value;
14805};
14806
14807const passthroughOptions = ['stopEarly', 'unknown', '--'];
14808
14809var minimistOptions = options => {
14810 options = options || {};
14811
14812 const result = {};
14813
14814 passthroughOptions.forEach(key => {
14815 if (options[key]) {
14816 result[key] = options[key];
14817 }
14818 });
14819
14820 Object.keys(options).forEach(key => {
14821 let value = options[key];
14822
14823 if (key === 'arguments') {
14824 key = '_';
14825 }
14826
14827 // If short form is used
14828 // convert it to long form
14829 // e.g. { 'name': 'string' }
14830 if (typeof value === 'string') {
14831 value = {type: value};
14832 }
14833
14834 if (isPlainObj(value)) {
14835 const props = value;
14836
14837 if (props.type) {
14838 const type = props.type;
14839
14840 if (type === 'string') {
14841 push(result, 'string', key);
14842 }
14843
14844 if (type === 'boolean') {
14845 push(result, 'boolean', key);
14846 }
14847 }
14848
14849 const aliases = arrify(props.alias);
14850
14851 aliases.forEach(alias => {
14852 insert(result, 'alias', alias, key);
14853 });
14854
14855 if ({}.hasOwnProperty.call(props, 'default')) {
14856 insert(result, 'default', key, props.default);
14857 }
14858 }
14859 });
14860
14861 return result;
14862};
14863
14864var minimist = function (args, opts) {
14865 if (!opts) opts = {};
14866
14867 var flags = { bools : {}, strings : {}, unknownFn: null };
14868
14869 if (typeof opts['unknown'] === 'function') {
14870 flags.unknownFn = opts['unknown'];
14871 }
14872
14873 if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
14874 flags.allBools = true;
14875 } else {
14876 [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
14877 flags.bools[key] = true;
14878 });
14879 }
14880
14881 var aliases = {};
14882 Object.keys(opts.alias || {}).forEach(function (key) {
14883 aliases[key] = [].concat(opts.alias[key]);
14884 aliases[key].forEach(function (x) {
14885 aliases[x] = [key].concat(aliases[key].filter(function (y) {
14886 return x !== y;
14887 }));
14888 });
14889 });
14890
14891 [].concat(opts.string).filter(Boolean).forEach(function (key) {
14892 flags.strings[key] = true;
14893 if (aliases[key]) {
14894 flags.strings[aliases[key]] = true;
14895 }
14896 });
14897
14898 var defaults = opts['default'] || {};
14899
14900 var argv = { _ : [] };
14901 Object.keys(flags.bools).forEach(function (key) {
14902 setArg(key, defaults[key] === undefined ? false : defaults[key]);
14903 });
14904
14905 var notFlags = [];
14906
14907 if (args.indexOf('--') !== -1) {
14908 notFlags = args.slice(args.indexOf('--')+1);
14909 args = args.slice(0, args.indexOf('--'));
14910 }
14911
14912 function argDefined(key, arg) {
14913 return (flags.allBools && /^--[^=]+$/.test(arg)) ||
14914 flags.strings[key] || flags.bools[key] || aliases[key];
14915 }
14916
14917 function setArg (key, val, arg) {
14918 if (arg && flags.unknownFn && !argDefined(key, arg)) {
14919 if (flags.unknownFn(arg) === false) return;
14920 }
14921
14922 var value = !flags.strings[key] && isNumber(val)
14923 ? Number(val) : val
14924 ;
14925 setKey(argv, key.split('.'), value);
14926
14927 (aliases[key] || []).forEach(function (x) {
14928 setKey(argv, x.split('.'), value);
14929 });
14930 }
14931
14932 function setKey (obj, keys, value) {
14933 var o = obj;
14934 keys.slice(0,-1).forEach(function (key) {
14935 if (o[key] === undefined) o[key] = {};
14936 o = o[key];
14937 });
14938
14939 var key = keys[keys.length - 1];
14940 if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
14941 o[key] = value;
14942 }
14943 else if (Array.isArray(o[key])) {
14944 o[key].push(value);
14945 }
14946 else {
14947 o[key] = [ o[key], value ];
14948 }
14949 }
14950
14951 function aliasIsBoolean(key) {
14952 return aliases[key].some(function (x) {
14953 return flags.bools[x];
14954 });
14955 }
14956
14957 for (var i = 0; i < args.length; i++) {
14958 var arg = args[i];
14959
14960 if (/^--.+=/.test(arg)) {
14961 // Using [\s\S] instead of . because js doesn't support the
14962 // 'dotall' regex modifier. See:
14963 // http://stackoverflow.com/a/1068308/13216
14964 var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
14965 var key = m[1];
14966 var value = m[2];
14967 if (flags.bools[key]) {
14968 value = value !== 'false';
14969 }
14970 setArg(key, value, arg);
14971 }
14972 else if (/^--no-.+/.test(arg)) {
14973 var key = arg.match(/^--no-(.+)/)[1];
14974 setArg(key, false, arg);
14975 }
14976 else if (/^--.+/.test(arg)) {
14977 var key = arg.match(/^--(.+)/)[1];
14978 var next = args[i + 1];
14979 if (next !== undefined && !/^-/.test(next)
14980 && !flags.bools[key]
14981 && !flags.allBools
14982 && (aliases[key] ? !aliasIsBoolean(key) : true)) {
14983 setArg(key, next, arg);
14984 i++;
14985 }
14986 else if (/^(true|false)$/.test(next)) {
14987 setArg(key, next === 'true', arg);
14988 i++;
14989 }
14990 else {
14991 setArg(key, flags.strings[key] ? '' : true, arg);
14992 }
14993 }
14994 else if (/^-[^-]+/.test(arg)) {
14995 var letters = arg.slice(1,-1).split('');
14996
14997 var broken = false;
14998 for (var j = 0; j < letters.length; j++) {
14999 var next = arg.slice(j+2);
15000
15001 if (next === '-') {
15002 setArg(letters[j], next, arg);
15003 continue;
15004 }
15005
15006 if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
15007 setArg(letters[j], next.split('=')[1], arg);
15008 broken = true;
15009 break;
15010 }
15011
15012 if (/[A-Za-z]/.test(letters[j])
15013 && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
15014 setArg(letters[j], next, arg);
15015 broken = true;
15016 break;
15017 }
15018
15019 if (letters[j+1] && letters[j+1].match(/\W/)) {
15020 setArg(letters[j], arg.slice(j+2), arg);
15021 broken = true;
15022 break;
15023 }
15024 else {
15025 setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
15026 }
15027 }
15028
15029 var key = arg.slice(-1)[0];
15030 if (!broken && key !== '-') {
15031 if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
15032 && !flags.bools[key]
15033 && (aliases[key] ? !aliasIsBoolean(key) : true)) {
15034 setArg(key, args[i+1], arg);
15035 i++;
15036 }
15037 else if (args[i+1] && /true|false/.test(args[i+1])) {
15038 setArg(key, args[i+1] === 'true', arg);
15039 i++;
15040 }
15041 else {
15042 setArg(key, flags.strings[key] ? '' : true, arg);
15043 }
15044 }
15045 }
15046 else {
15047 if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
15048 argv._.push(
15049 flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
15050 );
15051 }
15052 if (opts.stopEarly) {
15053 argv._.push.apply(argv._, args.slice(i + 1));
15054 break;
15055 }
15056 }
15057 }
15058
15059 Object.keys(defaults).forEach(function (key) {
15060 if (!hasKey(argv, key.split('.'))) {
15061 setKey(argv, key.split('.'), defaults[key]);
15062
15063 (aliases[key] || []).forEach(function (x) {
15064 setKey(argv, x.split('.'), defaults[key]);
15065 });
15066 }
15067 });
15068
15069 if (opts['--']) {
15070 argv['--'] = new Array();
15071 notFlags.forEach(function(key) {
15072 argv['--'].push(key);
15073 });
15074 }
15075 else {
15076 notFlags.forEach(function(key) {
15077 argv._.push(key);
15078 });
15079 }
15080
15081 return argv;
15082};
15083
15084function hasKey (obj, keys) {
15085 var o = obj;
15086 keys.slice(0,-1).forEach(function (key) {
15087 o = (o[key] || {});
15088 });
15089
15090 var key = keys[keys.length - 1];
15091 return key in o;
15092}
15093
15094function isNumber (x) {
15095 if (typeof x === 'number') return true;
15096 if (/^0x[0-9a-f]+$/i.test(x)) return true;
15097 return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
15098}
15099
15100const { promisify: promisify$1 } = util;
15101const { createWriteStream, renameSync, unlinkSync } = fs;
15102const { download: download$1, listReleases: listReleases$1, InstallationError: InstallationError$1 } = getDeno;
15103const debug$1 = node('cli');
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114const spinner = ora();
15115
15116kleur.enabled = Boolean(process.stdout.isTTY);
15117
15118// NOTE: Copied from bili (by @egoist): https://git.io/fxupU
15119const supportsEmoji = process.platform !== 'win32' ||
15120 process.env.TERM === 'xterm-256color';
15121
15122const isWindows = () => /^win/i.test(os.platform());
15123const formatDate = str => str.split('T')[0];
15124const formatError = msg => msg.replace(/^\w*Error:\s+/, match => kleur.red().bold(match));
15125const pipe$4 = promisify$1(mississippi.pipe);
15126
15127const options$1 = minimistOptions({
15128 help: { type: 'boolean', alias: 'h' },
15129 version: { type: 'boolean', alias: 'v' },
15130 'list-releases': { type: 'boolean', alias: 'l' }
15131});
15132options$1.unknown = option => fail(`Error: Unknown option \`${option}\``, -1);
15133const argv = minimist(process.argv.slice(2), options$1);
15134
15135const help = `
15136 ${kleur.bold(pkg$1.name)} v${pkg$1.version}
15137
15138 Usage:
15139 $ ${pkg$1.name} [version] # install specified version, defaults to latest
15140
15141 Options:
15142 -l, --list-releases List deno releases
15143 -h, --help Show help
15144 -v, --version Show version number
15145
15146 Homepage: ${kleur.green(pkg$1.homepage)}
15147 Report issue: ${kleur.green(pkg$1.bugs.url)}
15148`;
15149
15150program(argv._, argv).catch(err => {
15151 spinner.stop().clear();
15152 console.error(formatError(err.stack));
15153});
15154
15155async function program([input], flags) {
15156 if (flags.version) return console.log(pkg$1.version);
15157 if (flags.help) return console.log(help);
15158 input = input && `${input}`;
15159 if (flags['list-releases']) {
15160 const range = semver.validRange(input) || '*';
15161 debug$1('list releases inside range=`%s`', range);
15162 return printReleases(range);
15163 }
15164 let version = semver.valid(semver.coerce(input));
15165 if (input && !version) {
15166 fail('Error: Invalid version provided.', 2);
15167 }
15168 version = version ? `v${version}` : 'latest';
15169 debug$1('install version `%s`', version);
15170 try {
15171 await install(version);
15172 } catch (err) {
15173 if (!(err instanceof InstallationError$1)) throw err;
15174 fail(`Error: ${err.message}`);
15175 }
15176}
15177
15178async function install(version) {
15179 const gauge$$1 = new gauge();
15180 spinner.start(`Querying ${kleur.bold(pkg$1.config.repo)} for version: ${kleur.cyan(version)}...`);
15181
15182 const dest = await makeDir(path.join(os.homedir(), '/.deno/bin/'));
15183 const stream$$1 = await download$1(version);
15184 stream$$1.on('download:progress', (value, downloaded, total) => {
15185 const stats = `${prettyBytes(downloaded)}/${kleur.bold(prettyBytes(total))}`;
15186 gauge$$1.show(stats, value);
15187 gauge$$1.pulse();
15188 });
15189 exitHook(() => {
15190 try {
15191 unlinkSync(`${binary}.download`);
15192 } catch (err) {
15193 if (err.code !== 'ENOENT') throw err;
15194 }
15195 });
15196
15197 version = stream$$1.metadata.version.replace(/^v/, '');
15198 spinner.text = `Downloading ${kleur.bold().cyan(`deno@${version}`)} from ${kleur.gray(stream$$1.metadata.url)}`;
15199 spinner.stopAndPersist({ symbol: supportsEmoji && '📦 ' });
15200
15201 const binary = path.join(dest, isWindows() ? 'deno.exe' : 'deno');
15202 await pipe$4(stream$$1, createWriteStream(`${binary}.download`, { mode: pkg$1.config.umask }));
15203 gauge$$1.hide();
15204 clearSpinner(spinner);
15205
15206 renameSync(`${binary}.download`, binary);
15207 spinner.succeed(`${kleur.bold().cyan(`deno@${version}`)} is successfully installed!`);
15208}
15209
15210async function printReleases(range) {
15211 spinner.start(`Querying ${kleur.bold(pkg$1.config.repo)} for available releases...`);
15212 const releases = await listReleases$1();
15213 if (!releases || releases.length <= 0) {
15214 fail('Error: No releases found.', 3);
15215 }
15216 const matches = releases.reduce((acc, it) => {
15217 const version = semver.coerce(it.tag);
15218 if (!semver.satisfies(version, range)) return acc;
15219 acc.push([it.tag.padEnd(10), kleur.gray(formatDate(it.publishedAt))].join(''));
15220 return acc;
15221 }, []);
15222 if (matches.length <= 0) {
15223 fail('Error: There are no releases satisfying given range.', 4);
15224 }
15225 spinner.stop().clear();
15226 console.log(matches.join('\n'));
15227}
15228
15229function fail(message, code = 1) {
15230 message = formatError(message);
15231 if (spinner.isSpinning) spinner.fail(message);
15232 else console.error(message);
15233 process.exit(code);
15234}
15235
15236function clearSpinner(spinner) {
15237 let line = 0;
15238 while (line < spinner.lineCount) {
15239 spinner.stream.moveCursor(0, -1);
15240 spinner.stream.clearLine();
15241 spinner.stream.cursorTo(0);
15242 line += 1;
15243 }
15244}
15245
15246var cli = {
15247
15248};
15249
15250module.exports = cli;
15251//# sourceMappingURL=cli.compact.js.map