UNPKG

775 kBJavaScriptView Raw
1var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2
3function unwrapExports (x) {
4 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
5}
6
7function createCommonjsModule(fn, module) {
8 return module = { exports: {} }, fn(module, module.exports), module.exports;
9}
10
11function getCjsExportFromNamespace (n) {
12 return n && n['default'] || n;
13}
14
15var domain;
16
17// This constructor is used to store event handlers. Instantiating this is
18// faster than explicitly calling `Object.create(null)` to get a "clean" empty
19// object (tested with v8 v4.9).
20function EventHandlers() {}
21EventHandlers.prototype = Object.create(null);
22
23function EventEmitter() {
24 EventEmitter.init.call(this);
25}
26
27// nodejs oddity
28// require('events') === require('events').EventEmitter
29EventEmitter.EventEmitter = EventEmitter;
30
31EventEmitter.usingDomains = false;
32
33EventEmitter.prototype.domain = undefined;
34EventEmitter.prototype._events = undefined;
35EventEmitter.prototype._maxListeners = undefined;
36
37// By default EventEmitters will print a warning if more than 10 listeners are
38// added to it. This is a useful default which helps finding memory leaks.
39EventEmitter.defaultMaxListeners = 10;
40
41EventEmitter.init = function() {
42 this.domain = null;
43 if (EventEmitter.usingDomains) {
44 // if there is an active domain, then attach to it.
45 if (domain.active ) ;
46 }
47
48 if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
49 this._events = new EventHandlers();
50 this._eventsCount = 0;
51 }
52
53 this._maxListeners = this._maxListeners || undefined;
54};
55
56// Obviously not all Emitters should be limited to 10. This function allows
57// that to be increased. Set to zero for unlimited.
58EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
59 if (typeof n !== 'number' || n < 0 || isNaN(n))
60 throw new TypeError('"n" argument must be a positive number');
61 this._maxListeners = n;
62 return this;
63};
64
65function $getMaxListeners(that) {
66 if (that._maxListeners === undefined)
67 return EventEmitter.defaultMaxListeners;
68 return that._maxListeners;
69}
70
71EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
72 return $getMaxListeners(this);
73};
74
75// These standalone emit* functions are used to optimize calling of event
76// handlers for fast cases because emit() itself often has a variable number of
77// arguments and can be deoptimized because of that. These functions always have
78// the same number of arguments and thus do not get deoptimized, so the code
79// inside them can execute faster.
80function emitNone(handler, isFn, self) {
81 if (isFn)
82 handler.call(self);
83 else {
84 var len = handler.length;
85 var listeners = arrayClone(handler, len);
86 for (var i = 0; i < len; ++i)
87 listeners[i].call(self);
88 }
89}
90function emitOne(handler, isFn, self, arg1) {
91 if (isFn)
92 handler.call(self, arg1);
93 else {
94 var len = handler.length;
95 var listeners = arrayClone(handler, len);
96 for (var i = 0; i < len; ++i)
97 listeners[i].call(self, arg1);
98 }
99}
100function emitTwo(handler, isFn, self, arg1, arg2) {
101 if (isFn)
102 handler.call(self, arg1, arg2);
103 else {
104 var len = handler.length;
105 var listeners = arrayClone(handler, len);
106 for (var i = 0; i < len; ++i)
107 listeners[i].call(self, arg1, arg2);
108 }
109}
110function emitThree(handler, isFn, self, arg1, arg2, arg3) {
111 if (isFn)
112 handler.call(self, arg1, arg2, arg3);
113 else {
114 var len = handler.length;
115 var listeners = arrayClone(handler, len);
116 for (var i = 0; i < len; ++i)
117 listeners[i].call(self, arg1, arg2, arg3);
118 }
119}
120
121function emitMany(handler, isFn, self, args) {
122 if (isFn)
123 handler.apply(self, args);
124 else {
125 var len = handler.length;
126 var listeners = arrayClone(handler, len);
127 for (var i = 0; i < len; ++i)
128 listeners[i].apply(self, args);
129 }
130}
131
132EventEmitter.prototype.emit = function emit(type) {
133 var er, handler, len, args, i, events, domain;
134 var doError = (type === 'error');
135
136 events = this._events;
137 if (events)
138 doError = (doError && events.error == null);
139 else if (!doError)
140 return false;
141
142 domain = this.domain;
143
144 // If there is no 'error' event listener then throw.
145 if (doError) {
146 er = arguments[1];
147 if (domain) {
148 if (!er)
149 er = new Error('Uncaught, unspecified "error" event');
150 er.domainEmitter = this;
151 er.domain = domain;
152 er.domainThrown = false;
153 domain.emit('error', er);
154 } else if (er instanceof Error) {
155 throw er; // Unhandled 'error' event
156 } else {
157 // At least give some kind of context to the user
158 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
159 err.context = er;
160 throw err;
161 }
162 return false;
163 }
164
165 handler = events[type];
166
167 if (!handler)
168 return false;
169
170 var isFn = typeof handler === 'function';
171 len = arguments.length;
172 switch (len) {
173 // fast cases
174 case 1:
175 emitNone(handler, isFn, this);
176 break;
177 case 2:
178 emitOne(handler, isFn, this, arguments[1]);
179 break;
180 case 3:
181 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
182 break;
183 case 4:
184 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
185 break;
186 // slower
187 default:
188 args = new Array(len - 1);
189 for (i = 1; i < len; i++)
190 args[i - 1] = arguments[i];
191 emitMany(handler, isFn, this, args);
192 }
193
194 return true;
195};
196
197function _addListener(target, type, listener, prepend) {
198 var m;
199 var events;
200 var existing;
201
202 if (typeof listener !== 'function')
203 throw new TypeError('"listener" argument must be a function');
204
205 events = target._events;
206 if (!events) {
207 events = target._events = new EventHandlers();
208 target._eventsCount = 0;
209 } else {
210 // To avoid recursion in the case that type === "newListener"! Before
211 // adding it to the listeners, first emit "newListener".
212 if (events.newListener) {
213 target.emit('newListener', type,
214 listener.listener ? listener.listener : listener);
215
216 // Re-assign `events` because a newListener handler could have caused the
217 // this._events to be assigned to a new object
218 events = target._events;
219 }
220 existing = events[type];
221 }
222
223 if (!existing) {
224 // Optimize the case of one listener. Don't need the extra array object.
225 existing = events[type] = listener;
226 ++target._eventsCount;
227 } else {
228 if (typeof existing === 'function') {
229 // Adding the second element, need to change to array.
230 existing = events[type] = prepend ? [listener, existing] :
231 [existing, listener];
232 } else {
233 // If we've already got an array, just append.
234 if (prepend) {
235 existing.unshift(listener);
236 } else {
237 existing.push(listener);
238 }
239 }
240
241 // Check for listener leak
242 if (!existing.warned) {
243 m = $getMaxListeners(target);
244 if (m && m > 0 && existing.length > m) {
245 existing.warned = true;
246 var w = new Error('Possible EventEmitter memory leak detected. ' +
247 existing.length + ' ' + type + ' listeners added. ' +
248 'Use emitter.setMaxListeners() to increase limit');
249 w.name = 'MaxListenersExceededWarning';
250 w.emitter = target;
251 w.type = type;
252 w.count = existing.length;
253 emitWarning(w);
254 }
255 }
256 }
257
258 return target;
259}
260function emitWarning(e) {
261 typeof console.warn === 'function' ? console.warn(e) : console.log(e);
262}
263EventEmitter.prototype.addListener = function addListener(type, listener) {
264 return _addListener(this, type, listener, false);
265};
266
267EventEmitter.prototype.on = EventEmitter.prototype.addListener;
268
269EventEmitter.prototype.prependListener =
270 function prependListener(type, listener) {
271 return _addListener(this, type, listener, true);
272 };
273
274function _onceWrap(target, type, listener) {
275 var fired = false;
276 function g() {
277 target.removeListener(type, g);
278 if (!fired) {
279 fired = true;
280 listener.apply(target, arguments);
281 }
282 }
283 g.listener = listener;
284 return g;
285}
286
287EventEmitter.prototype.once = function once(type, listener) {
288 if (typeof listener !== 'function')
289 throw new TypeError('"listener" argument must be a function');
290 this.on(type, _onceWrap(this, type, listener));
291 return this;
292};
293
294EventEmitter.prototype.prependOnceListener =
295 function prependOnceListener(type, listener) {
296 if (typeof listener !== 'function')
297 throw new TypeError('"listener" argument must be a function');
298 this.prependListener(type, _onceWrap(this, type, listener));
299 return this;
300 };
301
302// emits a 'removeListener' event iff the listener was removed
303EventEmitter.prototype.removeListener =
304 function removeListener(type, listener) {
305 var list, events, position, i, originalListener;
306
307 if (typeof listener !== 'function')
308 throw new TypeError('"listener" argument must be a function');
309
310 events = this._events;
311 if (!events)
312 return this;
313
314 list = events[type];
315 if (!list)
316 return this;
317
318 if (list === listener || (list.listener && list.listener === listener)) {
319 if (--this._eventsCount === 0)
320 this._events = new EventHandlers();
321 else {
322 delete events[type];
323 if (events.removeListener)
324 this.emit('removeListener', type, list.listener || listener);
325 }
326 } else if (typeof list !== 'function') {
327 position = -1;
328
329 for (i = list.length; i-- > 0;) {
330 if (list[i] === listener ||
331 (list[i].listener && list[i].listener === listener)) {
332 originalListener = list[i].listener;
333 position = i;
334 break;
335 }
336 }
337
338 if (position < 0)
339 return this;
340
341 if (list.length === 1) {
342 list[0] = undefined;
343 if (--this._eventsCount === 0) {
344 this._events = new EventHandlers();
345 return this;
346 } else {
347 delete events[type];
348 }
349 } else {
350 spliceOne(list, position);
351 }
352
353 if (events.removeListener)
354 this.emit('removeListener', type, originalListener || listener);
355 }
356
357 return this;
358 };
359
360EventEmitter.prototype.removeAllListeners =
361 function removeAllListeners(type) {
362 var listeners, events;
363
364 events = this._events;
365 if (!events)
366 return this;
367
368 // not listening for removeListener, no need to emit
369 if (!events.removeListener) {
370 if (arguments.length === 0) {
371 this._events = new EventHandlers();
372 this._eventsCount = 0;
373 } else if (events[type]) {
374 if (--this._eventsCount === 0)
375 this._events = new EventHandlers();
376 else
377 delete events[type];
378 }
379 return this;
380 }
381
382 // emit removeListener for all listeners on all events
383 if (arguments.length === 0) {
384 var keys = Object.keys(events);
385 for (var i = 0, key; i < keys.length; ++i) {
386 key = keys[i];
387 if (key === 'removeListener') continue;
388 this.removeAllListeners(key);
389 }
390 this.removeAllListeners('removeListener');
391 this._events = new EventHandlers();
392 this._eventsCount = 0;
393 return this;
394 }
395
396 listeners = events[type];
397
398 if (typeof listeners === 'function') {
399 this.removeListener(type, listeners);
400 } else if (listeners) {
401 // LIFO order
402 do {
403 this.removeListener(type, listeners[listeners.length - 1]);
404 } while (listeners[0]);
405 }
406
407 return this;
408 };
409
410EventEmitter.prototype.listeners = function listeners(type) {
411 var evlistener;
412 var ret;
413 var events = this._events;
414
415 if (!events)
416 ret = [];
417 else {
418 evlistener = events[type];
419 if (!evlistener)
420 ret = [];
421 else if (typeof evlistener === 'function')
422 ret = [evlistener.listener || evlistener];
423 else
424 ret = unwrapListeners(evlistener);
425 }
426
427 return ret;
428};
429
430EventEmitter.listenerCount = function(emitter, type) {
431 if (typeof emitter.listenerCount === 'function') {
432 return emitter.listenerCount(type);
433 } else {
434 return listenerCount.call(emitter, type);
435 }
436};
437
438EventEmitter.prototype.listenerCount = listenerCount;
439function listenerCount(type) {
440 var events = this._events;
441
442 if (events) {
443 var evlistener = events[type];
444
445 if (typeof evlistener === 'function') {
446 return 1;
447 } else if (evlistener) {
448 return evlistener.length;
449 }
450 }
451
452 return 0;
453}
454
455EventEmitter.prototype.eventNames = function eventNames() {
456 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
457};
458
459// About 1.5x faster than the two-arg version of Array#splice().
460function spliceOne(list, index) {
461 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
462 list[i] = list[k];
463 list.pop();
464}
465
466function arrayClone(arr, i) {
467 var copy = new Array(i);
468 while (i--)
469 copy[i] = arr[i];
470 return copy;
471}
472
473function unwrapListeners(arr) {
474 var ret = new Array(arr.length);
475 for (var i = 0; i < ret.length; ++i) {
476 ret[i] = arr[i].listener || arr[i];
477 }
478 return ret;
479}
480
481var global$1 = (typeof global !== "undefined" ? global :
482 typeof self !== "undefined" ? self :
483 typeof window !== "undefined" ? window : {});
484
485var lookup = [];
486var revLookup = [];
487var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
488var inited = false;
489function init () {
490 inited = true;
491 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
492 for (var i = 0, len = code.length; i < len; ++i) {
493 lookup[i] = code[i];
494 revLookup[code.charCodeAt(i)] = i;
495 }
496
497 revLookup['-'.charCodeAt(0)] = 62;
498 revLookup['_'.charCodeAt(0)] = 63;
499}
500
501function toByteArray (b64) {
502 if (!inited) {
503 init();
504 }
505 var i, j, l, tmp, placeHolders, arr;
506 var len = b64.length;
507
508 if (len % 4 > 0) {
509 throw new Error('Invalid string. Length must be a multiple of 4')
510 }
511
512 // the number of equal signs (place holders)
513 // if there are two placeholders, than the two characters before it
514 // represent one byte
515 // if there is only one, then the three characters before it represent 2 bytes
516 // this is just a cheap hack to not do indexOf twice
517 placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
518
519 // base64 is 4/3 + up to two characters of the original data
520 arr = new Arr(len * 3 / 4 - placeHolders);
521
522 // if there are placeholders, only get up to the last complete 4 chars
523 l = placeHolders > 0 ? len - 4 : len;
524
525 var L = 0;
526
527 for (i = 0, j = 0; i < l; i += 4, j += 3) {
528 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
529 arr[L++] = (tmp >> 16) & 0xFF;
530 arr[L++] = (tmp >> 8) & 0xFF;
531 arr[L++] = tmp & 0xFF;
532 }
533
534 if (placeHolders === 2) {
535 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
536 arr[L++] = tmp & 0xFF;
537 } else if (placeHolders === 1) {
538 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
539 arr[L++] = (tmp >> 8) & 0xFF;
540 arr[L++] = tmp & 0xFF;
541 }
542
543 return arr
544}
545
546function tripletToBase64 (num) {
547 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
548}
549
550function encodeChunk (uint8, start, end) {
551 var tmp;
552 var output = [];
553 for (var i = start; i < end; i += 3) {
554 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
555 output.push(tripletToBase64(tmp));
556 }
557 return output.join('')
558}
559
560function fromByteArray (uint8) {
561 if (!inited) {
562 init();
563 }
564 var tmp;
565 var len = uint8.length;
566 var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
567 var output = '';
568 var parts = [];
569 var maxChunkLength = 16383; // must be multiple of 3
570
571 // go through the array every three bytes, we'll deal with trailing stuff later
572 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
573 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
574 }
575
576 // pad the end with zeros, but make sure to not forget the extra bytes
577 if (extraBytes === 1) {
578 tmp = uint8[len - 1];
579 output += lookup[tmp >> 2];
580 output += lookup[(tmp << 4) & 0x3F];
581 output += '==';
582 } else if (extraBytes === 2) {
583 tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
584 output += lookup[tmp >> 10];
585 output += lookup[(tmp >> 4) & 0x3F];
586 output += lookup[(tmp << 2) & 0x3F];
587 output += '=';
588 }
589
590 parts.push(output);
591
592 return parts.join('')
593}
594
595function read (buffer, offset, isLE, mLen, nBytes) {
596 var e, m;
597 var eLen = nBytes * 8 - mLen - 1;
598 var eMax = (1 << eLen) - 1;
599 var eBias = eMax >> 1;
600 var nBits = -7;
601 var i = isLE ? (nBytes - 1) : 0;
602 var d = isLE ? -1 : 1;
603 var s = buffer[offset + i];
604
605 i += d;
606
607 e = s & ((1 << (-nBits)) - 1);
608 s >>= (-nBits);
609 nBits += eLen;
610 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
611
612 m = e & ((1 << (-nBits)) - 1);
613 e >>= (-nBits);
614 nBits += mLen;
615 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
616
617 if (e === 0) {
618 e = 1 - eBias;
619 } else if (e === eMax) {
620 return m ? NaN : ((s ? -1 : 1) * Infinity)
621 } else {
622 m = m + Math.pow(2, mLen);
623 e = e - eBias;
624 }
625 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
626}
627
628function write (buffer, value, offset, isLE, mLen, nBytes) {
629 var e, m, c;
630 var eLen = nBytes * 8 - mLen - 1;
631 var eMax = (1 << eLen) - 1;
632 var eBias = eMax >> 1;
633 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
634 var i = isLE ? 0 : (nBytes - 1);
635 var d = isLE ? 1 : -1;
636 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
637
638 value = Math.abs(value);
639
640 if (isNaN(value) || value === Infinity) {
641 m = isNaN(value) ? 1 : 0;
642 e = eMax;
643 } else {
644 e = Math.floor(Math.log(value) / Math.LN2);
645 if (value * (c = Math.pow(2, -e)) < 1) {
646 e--;
647 c *= 2;
648 }
649 if (e + eBias >= 1) {
650 value += rt / c;
651 } else {
652 value += rt * Math.pow(2, 1 - eBias);
653 }
654 if (value * c >= 2) {
655 e++;
656 c /= 2;
657 }
658
659 if (e + eBias >= eMax) {
660 m = 0;
661 e = eMax;
662 } else if (e + eBias >= 1) {
663 m = (value * c - 1) * Math.pow(2, mLen);
664 e = e + eBias;
665 } else {
666 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
667 e = 0;
668 }
669 }
670
671 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
672
673 e = (e << mLen) | m;
674 eLen += mLen;
675 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
676
677 buffer[offset + i - d] |= s * 128;
678}
679
680var toString = {}.toString;
681
682var isArray = Array.isArray || function (arr) {
683 return toString.call(arr) == '[object Array]';
684};
685
686var INSPECT_MAX_BYTES = 50;
687
688/**
689 * If `Buffer.TYPED_ARRAY_SUPPORT`:
690 * === true Use Uint8Array implementation (fastest)
691 * === false Use Object implementation (most compatible, even IE6)
692 *
693 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
694 * Opera 11.6+, iOS 4.2+.
695 *
696 * Due to various browser bugs, sometimes the Object implementation will be used even
697 * when the browser supports typed arrays.
698 *
699 * Note:
700 *
701 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
702 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
703 *
704 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
705 *
706 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
707 * incorrect length in some situations.
708
709 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
710 * get the Object implementation, which is slower but behaves correctly.
711 */
712Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
713 ? global$1.TYPED_ARRAY_SUPPORT
714 : true;
715
716function kMaxLength () {
717 return Buffer$1.TYPED_ARRAY_SUPPORT
718 ? 0x7fffffff
719 : 0x3fffffff
720}
721
722function createBuffer (that, length) {
723 if (kMaxLength() < length) {
724 throw new RangeError('Invalid typed array length')
725 }
726 if (Buffer$1.TYPED_ARRAY_SUPPORT) {
727 // Return an augmented `Uint8Array` instance, for best performance
728 that = new Uint8Array(length);
729 that.__proto__ = Buffer$1.prototype;
730 } else {
731 // Fallback: Return an object instance of the Buffer class
732 if (that === null) {
733 that = new Buffer$1(length);
734 }
735 that.length = length;
736 }
737
738 return that
739}
740
741/**
742 * The Buffer constructor returns instances of `Uint8Array` that have their
743 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
744 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
745 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
746 * returns a single octet.
747 *
748 * The `Uint8Array` prototype remains unmodified.
749 */
750
751function Buffer$1 (arg, encodingOrOffset, length) {
752 if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) {
753 return new Buffer$1(arg, encodingOrOffset, length)
754 }
755
756 // Common case.
757 if (typeof arg === 'number') {
758 if (typeof encodingOrOffset === 'string') {
759 throw new Error(
760 'If encoding is specified then the first argument must be a string'
761 )
762 }
763 return allocUnsafe(this, arg)
764 }
765 return from(this, arg, encodingOrOffset, length)
766}
767
768Buffer$1.poolSize = 8192; // not used by this implementation
769
770// TODO: Legacy, not needed anymore. Remove in next major version.
771Buffer$1._augment = function (arr) {
772 arr.__proto__ = Buffer$1.prototype;
773 return arr
774};
775
776function from (that, value, encodingOrOffset, length) {
777 if (typeof value === 'number') {
778 throw new TypeError('"value" argument must not be a number')
779 }
780
781 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
782 return fromArrayBuffer(that, value, encodingOrOffset, length)
783 }
784
785 if (typeof value === 'string') {
786 return fromString(that, value, encodingOrOffset)
787 }
788
789 return fromObject(that, value)
790}
791
792/**
793 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
794 * if value is a number.
795 * Buffer.from(str[, encoding])
796 * Buffer.from(array)
797 * Buffer.from(buffer)
798 * Buffer.from(arrayBuffer[, byteOffset[, length]])
799 **/
800Buffer$1.from = function (value, encodingOrOffset, length) {
801 return from(null, value, encodingOrOffset, length)
802};
803
804if (Buffer$1.TYPED_ARRAY_SUPPORT) {
805 Buffer$1.prototype.__proto__ = Uint8Array.prototype;
806 Buffer$1.__proto__ = Uint8Array;
807}
808
809function assertSize (size) {
810 if (typeof size !== 'number') {
811 throw new TypeError('"size" argument must be a number')
812 } else if (size < 0) {
813 throw new RangeError('"size" argument must not be negative')
814 }
815}
816
817function alloc (that, size, fill, encoding) {
818 assertSize(size);
819 if (size <= 0) {
820 return createBuffer(that, size)
821 }
822 if (fill !== undefined) {
823 // Only pay attention to encoding if it's a string. This
824 // prevents accidentally sending in a number that would
825 // be interpretted as a start offset.
826 return typeof encoding === 'string'
827 ? createBuffer(that, size).fill(fill, encoding)
828 : createBuffer(that, size).fill(fill)
829 }
830 return createBuffer(that, size)
831}
832
833/**
834 * Creates a new filled Buffer instance.
835 * alloc(size[, fill[, encoding]])
836 **/
837Buffer$1.alloc = function (size, fill, encoding) {
838 return alloc(null, size, fill, encoding)
839};
840
841function allocUnsafe (that, size) {
842 assertSize(size);
843 that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
844 if (!Buffer$1.TYPED_ARRAY_SUPPORT) {
845 for (var i = 0; i < size; ++i) {
846 that[i] = 0;
847 }
848 }
849 return that
850}
851
852/**
853 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
854 * */
855Buffer$1.allocUnsafe = function (size) {
856 return allocUnsafe(null, size)
857};
858/**
859 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
860 */
861Buffer$1.allocUnsafeSlow = function (size) {
862 return allocUnsafe(null, size)
863};
864
865function fromString (that, string, encoding) {
866 if (typeof encoding !== 'string' || encoding === '') {
867 encoding = 'utf8';
868 }
869
870 if (!Buffer$1.isEncoding(encoding)) {
871 throw new TypeError('"encoding" must be a valid string encoding')
872 }
873
874 var length = byteLength(string, encoding) | 0;
875 that = createBuffer(that, length);
876
877 var actual = that.write(string, encoding);
878
879 if (actual !== length) {
880 // Writing a hex string, for example, that contains invalid characters will
881 // cause everything after the first invalid character to be ignored. (e.g.
882 // 'abxxcd' will be treated as 'ab')
883 that = that.slice(0, actual);
884 }
885
886 return that
887}
888
889function fromArrayLike (that, array) {
890 var length = array.length < 0 ? 0 : checked(array.length) | 0;
891 that = createBuffer(that, length);
892 for (var i = 0; i < length; i += 1) {
893 that[i] = array[i] & 255;
894 }
895 return that
896}
897
898function fromArrayBuffer (that, array, byteOffset, length) {
899 array.byteLength; // this throws if `array` is not a valid ArrayBuffer
900
901 if (byteOffset < 0 || array.byteLength < byteOffset) {
902 throw new RangeError('\'offset\' is out of bounds')
903 }
904
905 if (array.byteLength < byteOffset + (length || 0)) {
906 throw new RangeError('\'length\' is out of bounds')
907 }
908
909 if (byteOffset === undefined && length === undefined) {
910 array = new Uint8Array(array);
911 } else if (length === undefined) {
912 array = new Uint8Array(array, byteOffset);
913 } else {
914 array = new Uint8Array(array, byteOffset, length);
915 }
916
917 if (Buffer$1.TYPED_ARRAY_SUPPORT) {
918 // Return an augmented `Uint8Array` instance, for best performance
919 that = array;
920 that.__proto__ = Buffer$1.prototype;
921 } else {
922 // Fallback: Return an object instance of the Buffer class
923 that = fromArrayLike(that, array);
924 }
925 return that
926}
927
928function fromObject (that, obj) {
929 if (internalIsBuffer(obj)) {
930 var len = checked(obj.length) | 0;
931 that = createBuffer(that, len);
932
933 if (that.length === 0) {
934 return that
935 }
936
937 obj.copy(that, 0, 0, len);
938 return that
939 }
940
941 if (obj) {
942 if ((typeof ArrayBuffer !== 'undefined' &&
943 obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
944 if (typeof obj.length !== 'number' || isnan(obj.length)) {
945 return createBuffer(that, 0)
946 }
947 return fromArrayLike(that, obj)
948 }
949
950 if (obj.type === 'Buffer' && isArray(obj.data)) {
951 return fromArrayLike(that, obj.data)
952 }
953 }
954
955 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
956}
957
958function checked (length) {
959 // Note: cannot use `length < kMaxLength()` here because that fails when
960 // length is NaN (which is otherwise coerced to zero.)
961 if (length >= kMaxLength()) {
962 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
963 'size: 0x' + kMaxLength().toString(16) + ' bytes')
964 }
965 return length | 0
966}
967Buffer$1.isBuffer = isBuffer;
968function internalIsBuffer (b) {
969 return !!(b != null && b._isBuffer)
970}
971
972Buffer$1.compare = function compare (a, b) {
973 if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
974 throw new TypeError('Arguments must be Buffers')
975 }
976
977 if (a === b) return 0
978
979 var x = a.length;
980 var y = b.length;
981
982 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
983 if (a[i] !== b[i]) {
984 x = a[i];
985 y = b[i];
986 break
987 }
988 }
989
990 if (x < y) return -1
991 if (y < x) return 1
992 return 0
993};
994
995Buffer$1.isEncoding = function isEncoding (encoding) {
996 switch (String(encoding).toLowerCase()) {
997 case 'hex':
998 case 'utf8':
999 case 'utf-8':
1000 case 'ascii':
1001 case 'latin1':
1002 case 'binary':
1003 case 'base64':
1004 case 'ucs2':
1005 case 'ucs-2':
1006 case 'utf16le':
1007 case 'utf-16le':
1008 return true
1009 default:
1010 return false
1011 }
1012};
1013
1014Buffer$1.concat = function concat (list, length) {
1015 if (!isArray(list)) {
1016 throw new TypeError('"list" argument must be an Array of Buffers')
1017 }
1018
1019 if (list.length === 0) {
1020 return Buffer$1.alloc(0)
1021 }
1022
1023 var i;
1024 if (length === undefined) {
1025 length = 0;
1026 for (i = 0; i < list.length; ++i) {
1027 length += list[i].length;
1028 }
1029 }
1030
1031 var buffer = Buffer$1.allocUnsafe(length);
1032 var pos = 0;
1033 for (i = 0; i < list.length; ++i) {
1034 var buf = list[i];
1035 if (!internalIsBuffer(buf)) {
1036 throw new TypeError('"list" argument must be an Array of Buffers')
1037 }
1038 buf.copy(buffer, pos);
1039 pos += buf.length;
1040 }
1041 return buffer
1042};
1043
1044function byteLength (string, encoding) {
1045 if (internalIsBuffer(string)) {
1046 return string.length
1047 }
1048 if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
1049 (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
1050 return string.byteLength
1051 }
1052 if (typeof string !== 'string') {
1053 string = '' + string;
1054 }
1055
1056 var len = string.length;
1057 if (len === 0) return 0
1058
1059 // Use a for loop to avoid recursion
1060 var loweredCase = false;
1061 for (;;) {
1062 switch (encoding) {
1063 case 'ascii':
1064 case 'latin1':
1065 case 'binary':
1066 return len
1067 case 'utf8':
1068 case 'utf-8':
1069 case undefined:
1070 return utf8ToBytes(string).length
1071 case 'ucs2':
1072 case 'ucs-2':
1073 case 'utf16le':
1074 case 'utf-16le':
1075 return len * 2
1076 case 'hex':
1077 return len >>> 1
1078 case 'base64':
1079 return base64ToBytes(string).length
1080 default:
1081 if (loweredCase) return utf8ToBytes(string).length // assume utf8
1082 encoding = ('' + encoding).toLowerCase();
1083 loweredCase = true;
1084 }
1085 }
1086}
1087Buffer$1.byteLength = byteLength;
1088
1089function slowToString (encoding, start, end) {
1090 var loweredCase = false;
1091
1092 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1093 // property of a typed array.
1094
1095 // This behaves neither like String nor Uint8Array in that we set start/end
1096 // to their upper/lower bounds if the value passed is out of range.
1097 // undefined is handled specially as per ECMA-262 6th Edition,
1098 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1099 if (start === undefined || start < 0) {
1100 start = 0;
1101 }
1102 // Return early if start > this.length. Done here to prevent potential uint32
1103 // coercion fail below.
1104 if (start > this.length) {
1105 return ''
1106 }
1107
1108 if (end === undefined || end > this.length) {
1109 end = this.length;
1110 }
1111
1112 if (end <= 0) {
1113 return ''
1114 }
1115
1116 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1117 end >>>= 0;
1118 start >>>= 0;
1119
1120 if (end <= start) {
1121 return ''
1122 }
1123
1124 if (!encoding) encoding = 'utf8';
1125
1126 while (true) {
1127 switch (encoding) {
1128 case 'hex':
1129 return hexSlice(this, start, end)
1130
1131 case 'utf8':
1132 case 'utf-8':
1133 return utf8Slice(this, start, end)
1134
1135 case 'ascii':
1136 return asciiSlice(this, start, end)
1137
1138 case 'latin1':
1139 case 'binary':
1140 return latin1Slice(this, start, end)
1141
1142 case 'base64':
1143 return base64Slice(this, start, end)
1144
1145 case 'ucs2':
1146 case 'ucs-2':
1147 case 'utf16le':
1148 case 'utf-16le':
1149 return utf16leSlice(this, start, end)
1150
1151 default:
1152 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1153 encoding = (encoding + '').toLowerCase();
1154 loweredCase = true;
1155 }
1156 }
1157}
1158
1159// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
1160// Buffer instances.
1161Buffer$1.prototype._isBuffer = true;
1162
1163function swap (b, n, m) {
1164 var i = b[n];
1165 b[n] = b[m];
1166 b[m] = i;
1167}
1168
1169Buffer$1.prototype.swap16 = function swap16 () {
1170 var len = this.length;
1171 if (len % 2 !== 0) {
1172 throw new RangeError('Buffer size must be a multiple of 16-bits')
1173 }
1174 for (var i = 0; i < len; i += 2) {
1175 swap(this, i, i + 1);
1176 }
1177 return this
1178};
1179
1180Buffer$1.prototype.swap32 = function swap32 () {
1181 var len = this.length;
1182 if (len % 4 !== 0) {
1183 throw new RangeError('Buffer size must be a multiple of 32-bits')
1184 }
1185 for (var i = 0; i < len; i += 4) {
1186 swap(this, i, i + 3);
1187 swap(this, i + 1, i + 2);
1188 }
1189 return this
1190};
1191
1192Buffer$1.prototype.swap64 = function swap64 () {
1193 var len = this.length;
1194 if (len % 8 !== 0) {
1195 throw new RangeError('Buffer size must be a multiple of 64-bits')
1196 }
1197 for (var i = 0; i < len; i += 8) {
1198 swap(this, i, i + 7);
1199 swap(this, i + 1, i + 6);
1200 swap(this, i + 2, i + 5);
1201 swap(this, i + 3, i + 4);
1202 }
1203 return this
1204};
1205
1206Buffer$1.prototype.toString = function toString () {
1207 var length = this.length | 0;
1208 if (length === 0) return ''
1209 if (arguments.length === 0) return utf8Slice(this, 0, length)
1210 return slowToString.apply(this, arguments)
1211};
1212
1213Buffer$1.prototype.equals = function equals (b) {
1214 if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
1215 if (this === b) return true
1216 return Buffer$1.compare(this, b) === 0
1217};
1218
1219Buffer$1.prototype.inspect = function inspect () {
1220 var str = '';
1221 var max = INSPECT_MAX_BYTES;
1222 if (this.length > 0) {
1223 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
1224 if (this.length > max) str += ' ... ';
1225 }
1226 return '<Buffer ' + str + '>'
1227};
1228
1229Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1230 if (!internalIsBuffer(target)) {
1231 throw new TypeError('Argument must be a Buffer')
1232 }
1233
1234 if (start === undefined) {
1235 start = 0;
1236 }
1237 if (end === undefined) {
1238 end = target ? target.length : 0;
1239 }
1240 if (thisStart === undefined) {
1241 thisStart = 0;
1242 }
1243 if (thisEnd === undefined) {
1244 thisEnd = this.length;
1245 }
1246
1247 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1248 throw new RangeError('out of range index')
1249 }
1250
1251 if (thisStart >= thisEnd && start >= end) {
1252 return 0
1253 }
1254 if (thisStart >= thisEnd) {
1255 return -1
1256 }
1257 if (start >= end) {
1258 return 1
1259 }
1260
1261 start >>>= 0;
1262 end >>>= 0;
1263 thisStart >>>= 0;
1264 thisEnd >>>= 0;
1265
1266 if (this === target) return 0
1267
1268 var x = thisEnd - thisStart;
1269 var y = end - start;
1270 var len = Math.min(x, y);
1271
1272 var thisCopy = this.slice(thisStart, thisEnd);
1273 var targetCopy = target.slice(start, end);
1274
1275 for (var i = 0; i < len; ++i) {
1276 if (thisCopy[i] !== targetCopy[i]) {
1277 x = thisCopy[i];
1278 y = targetCopy[i];
1279 break
1280 }
1281 }
1282
1283 if (x < y) return -1
1284 if (y < x) return 1
1285 return 0
1286};
1287
1288// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1289// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1290//
1291// Arguments:
1292// - buffer - a Buffer to search
1293// - val - a string, Buffer, or number
1294// - byteOffset - an index into `buffer`; will be clamped to an int32
1295// - encoding - an optional encoding, relevant is val is a string
1296// - dir - true for indexOf, false for lastIndexOf
1297function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1298 // Empty buffer means no match
1299 if (buffer.length === 0) return -1
1300
1301 // Normalize byteOffset
1302 if (typeof byteOffset === 'string') {
1303 encoding = byteOffset;
1304 byteOffset = 0;
1305 } else if (byteOffset > 0x7fffffff) {
1306 byteOffset = 0x7fffffff;
1307 } else if (byteOffset < -0x80000000) {
1308 byteOffset = -0x80000000;
1309 }
1310 byteOffset = +byteOffset; // Coerce to Number.
1311 if (isNaN(byteOffset)) {
1312 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1313 byteOffset = dir ? 0 : (buffer.length - 1);
1314 }
1315
1316 // Normalize byteOffset: negative offsets start from the end of the buffer
1317 if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
1318 if (byteOffset >= buffer.length) {
1319 if (dir) return -1
1320 else byteOffset = buffer.length - 1;
1321 } else if (byteOffset < 0) {
1322 if (dir) byteOffset = 0;
1323 else return -1
1324 }
1325
1326 // Normalize val
1327 if (typeof val === 'string') {
1328 val = Buffer$1.from(val, encoding);
1329 }
1330
1331 // Finally, search either indexOf (if dir is true) or lastIndexOf
1332 if (internalIsBuffer(val)) {
1333 // Special case: looking for empty string/buffer always fails
1334 if (val.length === 0) {
1335 return -1
1336 }
1337 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1338 } else if (typeof val === 'number') {
1339 val = val & 0xFF; // Search for a byte value [0-255]
1340 if (Buffer$1.TYPED_ARRAY_SUPPORT &&
1341 typeof Uint8Array.prototype.indexOf === 'function') {
1342 if (dir) {
1343 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1344 } else {
1345 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1346 }
1347 }
1348 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
1349 }
1350
1351 throw new TypeError('val must be string, number or Buffer')
1352}
1353
1354function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1355 var indexSize = 1;
1356 var arrLength = arr.length;
1357 var valLength = val.length;
1358
1359 if (encoding !== undefined) {
1360 encoding = String(encoding).toLowerCase();
1361 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1362 encoding === 'utf16le' || encoding === 'utf-16le') {
1363 if (arr.length < 2 || val.length < 2) {
1364 return -1
1365 }
1366 indexSize = 2;
1367 arrLength /= 2;
1368 valLength /= 2;
1369 byteOffset /= 2;
1370 }
1371 }
1372
1373 function read (buf, i) {
1374 if (indexSize === 1) {
1375 return buf[i]
1376 } else {
1377 return buf.readUInt16BE(i * indexSize)
1378 }
1379 }
1380
1381 var i;
1382 if (dir) {
1383 var foundIndex = -1;
1384 for (i = byteOffset; i < arrLength; i++) {
1385 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1386 if (foundIndex === -1) foundIndex = i;
1387 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1388 } else {
1389 if (foundIndex !== -1) i -= i - foundIndex;
1390 foundIndex = -1;
1391 }
1392 }
1393 } else {
1394 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
1395 for (i = byteOffset; i >= 0; i--) {
1396 var found = true;
1397 for (var j = 0; j < valLength; j++) {
1398 if (read(arr, i + j) !== read(val, j)) {
1399 found = false;
1400 break
1401 }
1402 }
1403 if (found) return i
1404 }
1405 }
1406
1407 return -1
1408}
1409
1410Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) {
1411 return this.indexOf(val, byteOffset, encoding) !== -1
1412};
1413
1414Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1415 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1416};
1417
1418Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1419 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1420};
1421
1422function hexWrite (buf, string, offset, length) {
1423 offset = Number(offset) || 0;
1424 var remaining = buf.length - offset;
1425 if (!length) {
1426 length = remaining;
1427 } else {
1428 length = Number(length);
1429 if (length > remaining) {
1430 length = remaining;
1431 }
1432 }
1433
1434 // must be an even number of digits
1435 var strLen = string.length;
1436 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1437
1438 if (length > strLen / 2) {
1439 length = strLen / 2;
1440 }
1441 for (var i = 0; i < length; ++i) {
1442 var parsed = parseInt(string.substr(i * 2, 2), 16);
1443 if (isNaN(parsed)) return i
1444 buf[offset + i] = parsed;
1445 }
1446 return i
1447}
1448
1449function utf8Write (buf, string, offset, length) {
1450 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1451}
1452
1453function asciiWrite (buf, string, offset, length) {
1454 return blitBuffer(asciiToBytes(string), buf, offset, length)
1455}
1456
1457function latin1Write (buf, string, offset, length) {
1458 return asciiWrite(buf, string, offset, length)
1459}
1460
1461function base64Write (buf, string, offset, length) {
1462 return blitBuffer(base64ToBytes(string), buf, offset, length)
1463}
1464
1465function ucs2Write (buf, string, offset, length) {
1466 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1467}
1468
1469Buffer$1.prototype.write = function write (string, offset, length, encoding) {
1470 // Buffer#write(string)
1471 if (offset === undefined) {
1472 encoding = 'utf8';
1473 length = this.length;
1474 offset = 0;
1475 // Buffer#write(string, encoding)
1476 } else if (length === undefined && typeof offset === 'string') {
1477 encoding = offset;
1478 length = this.length;
1479 offset = 0;
1480 // Buffer#write(string, offset[, length][, encoding])
1481 } else if (isFinite(offset)) {
1482 offset = offset | 0;
1483 if (isFinite(length)) {
1484 length = length | 0;
1485 if (encoding === undefined) encoding = 'utf8';
1486 } else {
1487 encoding = length;
1488 length = undefined;
1489 }
1490 // legacy write(string, encoding, offset, length) - remove in v0.13
1491 } else {
1492 throw new Error(
1493 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1494 )
1495 }
1496
1497 var remaining = this.length - offset;
1498 if (length === undefined || length > remaining) length = remaining;
1499
1500 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1501 throw new RangeError('Attempt to write outside buffer bounds')
1502 }
1503
1504 if (!encoding) encoding = 'utf8';
1505
1506 var loweredCase = false;
1507 for (;;) {
1508 switch (encoding) {
1509 case 'hex':
1510 return hexWrite(this, string, offset, length)
1511
1512 case 'utf8':
1513 case 'utf-8':
1514 return utf8Write(this, string, offset, length)
1515
1516 case 'ascii':
1517 return asciiWrite(this, string, offset, length)
1518
1519 case 'latin1':
1520 case 'binary':
1521 return latin1Write(this, string, offset, length)
1522
1523 case 'base64':
1524 // Warning: maxLength not taken into account in base64Write
1525 return base64Write(this, string, offset, length)
1526
1527 case 'ucs2':
1528 case 'ucs-2':
1529 case 'utf16le':
1530 case 'utf-16le':
1531 return ucs2Write(this, string, offset, length)
1532
1533 default:
1534 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1535 encoding = ('' + encoding).toLowerCase();
1536 loweredCase = true;
1537 }
1538 }
1539};
1540
1541Buffer$1.prototype.toJSON = function toJSON () {
1542 return {
1543 type: 'Buffer',
1544 data: Array.prototype.slice.call(this._arr || this, 0)
1545 }
1546};
1547
1548function base64Slice (buf, start, end) {
1549 if (start === 0 && end === buf.length) {
1550 return fromByteArray(buf)
1551 } else {
1552 return fromByteArray(buf.slice(start, end))
1553 }
1554}
1555
1556function utf8Slice (buf, start, end) {
1557 end = Math.min(buf.length, end);
1558 var res = [];
1559
1560 var i = start;
1561 while (i < end) {
1562 var firstByte = buf[i];
1563 var codePoint = null;
1564 var bytesPerSequence = (firstByte > 0xEF) ? 4
1565 : (firstByte > 0xDF) ? 3
1566 : (firstByte > 0xBF) ? 2
1567 : 1;
1568
1569 if (i + bytesPerSequence <= end) {
1570 var secondByte, thirdByte, fourthByte, tempCodePoint;
1571
1572 switch (bytesPerSequence) {
1573 case 1:
1574 if (firstByte < 0x80) {
1575 codePoint = firstByte;
1576 }
1577 break
1578 case 2:
1579 secondByte = buf[i + 1];
1580 if ((secondByte & 0xC0) === 0x80) {
1581 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
1582 if (tempCodePoint > 0x7F) {
1583 codePoint = tempCodePoint;
1584 }
1585 }
1586 break
1587 case 3:
1588 secondByte = buf[i + 1];
1589 thirdByte = buf[i + 2];
1590 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1591 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
1592 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1593 codePoint = tempCodePoint;
1594 }
1595 }
1596 break
1597 case 4:
1598 secondByte = buf[i + 1];
1599 thirdByte = buf[i + 2];
1600 fourthByte = buf[i + 3];
1601 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1602 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
1603 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1604 codePoint = tempCodePoint;
1605 }
1606 }
1607 }
1608 }
1609
1610 if (codePoint === null) {
1611 // we did not generate a valid codePoint so insert a
1612 // replacement char (U+FFFD) and advance only 1 byte
1613 codePoint = 0xFFFD;
1614 bytesPerSequence = 1;
1615 } else if (codePoint > 0xFFFF) {
1616 // encode to utf16 (surrogate pair dance)
1617 codePoint -= 0x10000;
1618 res.push(codePoint >>> 10 & 0x3FF | 0xD800);
1619 codePoint = 0xDC00 | codePoint & 0x3FF;
1620 }
1621
1622 res.push(codePoint);
1623 i += bytesPerSequence;
1624 }
1625
1626 return decodeCodePointsArray(res)
1627}
1628
1629// Based on http://stackoverflow.com/a/22747272/680742, the browser with
1630// the lowest limit is Chrome, with 0x10000 args.
1631// We go 1 magnitude less, for safety
1632var MAX_ARGUMENTS_LENGTH = 0x1000;
1633
1634function decodeCodePointsArray (codePoints) {
1635 var len = codePoints.length;
1636 if (len <= MAX_ARGUMENTS_LENGTH) {
1637 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1638 }
1639
1640 // Decode in chunks to avoid "call stack size exceeded".
1641 var res = '';
1642 var i = 0;
1643 while (i < len) {
1644 res += String.fromCharCode.apply(
1645 String,
1646 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1647 );
1648 }
1649 return res
1650}
1651
1652function asciiSlice (buf, start, end) {
1653 var ret = '';
1654 end = Math.min(buf.length, end);
1655
1656 for (var i = start; i < end; ++i) {
1657 ret += String.fromCharCode(buf[i] & 0x7F);
1658 }
1659 return ret
1660}
1661
1662function latin1Slice (buf, start, end) {
1663 var ret = '';
1664 end = Math.min(buf.length, end);
1665
1666 for (var i = start; i < end; ++i) {
1667 ret += String.fromCharCode(buf[i]);
1668 }
1669 return ret
1670}
1671
1672function hexSlice (buf, start, end) {
1673 var len = buf.length;
1674
1675 if (!start || start < 0) start = 0;
1676 if (!end || end < 0 || end > len) end = len;
1677
1678 var out = '';
1679 for (var i = start; i < end; ++i) {
1680 out += toHex(buf[i]);
1681 }
1682 return out
1683}
1684
1685function utf16leSlice (buf, start, end) {
1686 var bytes = buf.slice(start, end);
1687 var res = '';
1688 for (var i = 0; i < bytes.length; i += 2) {
1689 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
1690 }
1691 return res
1692}
1693
1694Buffer$1.prototype.slice = function slice (start, end) {
1695 var len = this.length;
1696 start = ~~start;
1697 end = end === undefined ? len : ~~end;
1698
1699 if (start < 0) {
1700 start += len;
1701 if (start < 0) start = 0;
1702 } else if (start > len) {
1703 start = len;
1704 }
1705
1706 if (end < 0) {
1707 end += len;
1708 if (end < 0) end = 0;
1709 } else if (end > len) {
1710 end = len;
1711 }
1712
1713 if (end < start) end = start;
1714
1715 var newBuf;
1716 if (Buffer$1.TYPED_ARRAY_SUPPORT) {
1717 newBuf = this.subarray(start, end);
1718 newBuf.__proto__ = Buffer$1.prototype;
1719 } else {
1720 var sliceLen = end - start;
1721 newBuf = new Buffer$1(sliceLen, undefined);
1722 for (var i = 0; i < sliceLen; ++i) {
1723 newBuf[i] = this[i + start];
1724 }
1725 }
1726
1727 return newBuf
1728};
1729
1730/*
1731 * Need to make sure that buffer isn't trying to write out of bounds.
1732 */
1733function checkOffset (offset, ext, length) {
1734 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1735 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1736}
1737
1738Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1739 offset = offset | 0;
1740 byteLength = byteLength | 0;
1741 if (!noAssert) checkOffset(offset, byteLength, this.length);
1742
1743 var val = this[offset];
1744 var mul = 1;
1745 var i = 0;
1746 while (++i < byteLength && (mul *= 0x100)) {
1747 val += this[offset + i] * mul;
1748 }
1749
1750 return val
1751};
1752
1753Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1754 offset = offset | 0;
1755 byteLength = byteLength | 0;
1756 if (!noAssert) {
1757 checkOffset(offset, byteLength, this.length);
1758 }
1759
1760 var val = this[offset + --byteLength];
1761 var mul = 1;
1762 while (byteLength > 0 && (mul *= 0x100)) {
1763 val += this[offset + --byteLength] * mul;
1764 }
1765
1766 return val
1767};
1768
1769Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1770 if (!noAssert) checkOffset(offset, 1, this.length);
1771 return this[offset]
1772};
1773
1774Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1775 if (!noAssert) checkOffset(offset, 2, this.length);
1776 return this[offset] | (this[offset + 1] << 8)
1777};
1778
1779Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1780 if (!noAssert) checkOffset(offset, 2, this.length);
1781 return (this[offset] << 8) | this[offset + 1]
1782};
1783
1784Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1785 if (!noAssert) checkOffset(offset, 4, this.length);
1786
1787 return ((this[offset]) |
1788 (this[offset + 1] << 8) |
1789 (this[offset + 2] << 16)) +
1790 (this[offset + 3] * 0x1000000)
1791};
1792
1793Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1794 if (!noAssert) checkOffset(offset, 4, this.length);
1795
1796 return (this[offset] * 0x1000000) +
1797 ((this[offset + 1] << 16) |
1798 (this[offset + 2] << 8) |
1799 this[offset + 3])
1800};
1801
1802Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1803 offset = offset | 0;
1804 byteLength = byteLength | 0;
1805 if (!noAssert) checkOffset(offset, byteLength, this.length);
1806
1807 var val = this[offset];
1808 var mul = 1;
1809 var i = 0;
1810 while (++i < byteLength && (mul *= 0x100)) {
1811 val += this[offset + i] * mul;
1812 }
1813 mul *= 0x80;
1814
1815 if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1816
1817 return val
1818};
1819
1820Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1821 offset = offset | 0;
1822 byteLength = byteLength | 0;
1823 if (!noAssert) checkOffset(offset, byteLength, this.length);
1824
1825 var i = byteLength;
1826 var mul = 1;
1827 var val = this[offset + --i];
1828 while (i > 0 && (mul *= 0x100)) {
1829 val += this[offset + --i] * mul;
1830 }
1831 mul *= 0x80;
1832
1833 if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1834
1835 return val
1836};
1837
1838Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) {
1839 if (!noAssert) checkOffset(offset, 1, this.length);
1840 if (!(this[offset] & 0x80)) return (this[offset])
1841 return ((0xff - this[offset] + 1) * -1)
1842};
1843
1844Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1845 if (!noAssert) checkOffset(offset, 2, this.length);
1846 var val = this[offset] | (this[offset + 1] << 8);
1847 return (val & 0x8000) ? val | 0xFFFF0000 : val
1848};
1849
1850Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1851 if (!noAssert) checkOffset(offset, 2, this.length);
1852 var val = this[offset + 1] | (this[offset] << 8);
1853 return (val & 0x8000) ? val | 0xFFFF0000 : val
1854};
1855
1856Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1857 if (!noAssert) checkOffset(offset, 4, this.length);
1858
1859 return (this[offset]) |
1860 (this[offset + 1] << 8) |
1861 (this[offset + 2] << 16) |
1862 (this[offset + 3] << 24)
1863};
1864
1865Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1866 if (!noAssert) checkOffset(offset, 4, this.length);
1867
1868 return (this[offset] << 24) |
1869 (this[offset + 1] << 16) |
1870 (this[offset + 2] << 8) |
1871 (this[offset + 3])
1872};
1873
1874Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1875 if (!noAssert) checkOffset(offset, 4, this.length);
1876 return read(this, offset, true, 23, 4)
1877};
1878
1879Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1880 if (!noAssert) checkOffset(offset, 4, this.length);
1881 return read(this, offset, false, 23, 4)
1882};
1883
1884Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1885 if (!noAssert) checkOffset(offset, 8, this.length);
1886 return read(this, offset, true, 52, 8)
1887};
1888
1889Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1890 if (!noAssert) checkOffset(offset, 8, this.length);
1891 return read(this, offset, false, 52, 8)
1892};
1893
1894function checkInt (buf, value, offset, ext, max, min) {
1895 if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1896 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1897 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1898}
1899
1900Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1901 value = +value;
1902 offset = offset | 0;
1903 byteLength = byteLength | 0;
1904 if (!noAssert) {
1905 var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1906 checkInt(this, value, offset, byteLength, maxBytes, 0);
1907 }
1908
1909 var mul = 1;
1910 var i = 0;
1911 this[offset] = value & 0xFF;
1912 while (++i < byteLength && (mul *= 0x100)) {
1913 this[offset + i] = (value / mul) & 0xFF;
1914 }
1915
1916 return offset + byteLength
1917};
1918
1919Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1920 value = +value;
1921 offset = offset | 0;
1922 byteLength = byteLength | 0;
1923 if (!noAssert) {
1924 var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1925 checkInt(this, value, offset, byteLength, maxBytes, 0);
1926 }
1927
1928 var i = byteLength - 1;
1929 var mul = 1;
1930 this[offset + i] = value & 0xFF;
1931 while (--i >= 0 && (mul *= 0x100)) {
1932 this[offset + i] = (value / mul) & 0xFF;
1933 }
1934
1935 return offset + byteLength
1936};
1937
1938Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1939 value = +value;
1940 offset = offset | 0;
1941 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
1942 if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
1943 this[offset] = (value & 0xff);
1944 return offset + 1
1945};
1946
1947function objectWriteUInt16 (buf, value, offset, littleEndian) {
1948 if (value < 0) value = 0xffff + value + 1;
1949 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
1950 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1951 (littleEndian ? i : 1 - i) * 8;
1952 }
1953}
1954
1955Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1956 value = +value;
1957 offset = offset | 0;
1958 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1959 if (Buffer$1.TYPED_ARRAY_SUPPORT) {
1960 this[offset] = (value & 0xff);
1961 this[offset + 1] = (value >>> 8);
1962 } else {
1963 objectWriteUInt16(this, value, offset, true);
1964 }
1965 return offset + 2
1966};
1967
1968Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1969 value = +value;
1970 offset = offset | 0;
1971 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1972 if (Buffer$1.TYPED_ARRAY_SUPPORT) {
1973 this[offset] = (value >>> 8);
1974 this[offset + 1] = (value & 0xff);
1975 } else {
1976 objectWriteUInt16(this, value, offset, false);
1977 }
1978 return offset + 2
1979};
1980
1981function objectWriteUInt32 (buf, value, offset, littleEndian) {
1982 if (value < 0) value = 0xffffffff + value + 1;
1983 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
1984 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
1985 }
1986}
1987
1988Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1989 value = +value;
1990 offset = offset | 0;
1991 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
1992 if (Buffer$1.TYPED_ARRAY_SUPPORT) {
1993 this[offset + 3] = (value >>> 24);
1994 this[offset + 2] = (value >>> 16);
1995 this[offset + 1] = (value >>> 8);
1996 this[offset] = (value & 0xff);
1997 } else {
1998 objectWriteUInt32(this, value, offset, true);
1999 }
2000 return offset + 4
2001};
2002
2003Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2004 value = +value;
2005 offset = offset | 0;
2006 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
2007 if (Buffer$1.TYPED_ARRAY_SUPPORT) {
2008 this[offset] = (value >>> 24);
2009 this[offset + 1] = (value >>> 16);
2010 this[offset + 2] = (value >>> 8);
2011 this[offset + 3] = (value & 0xff);
2012 } else {
2013 objectWriteUInt32(this, value, offset, false);
2014 }
2015 return offset + 4
2016};
2017
2018Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2019 value = +value;
2020 offset = offset | 0;
2021 if (!noAssert) {
2022 var limit = Math.pow(2, 8 * byteLength - 1);
2023
2024 checkInt(this, value, offset, byteLength, limit - 1, -limit);
2025 }
2026
2027 var i = 0;
2028 var mul = 1;
2029 var sub = 0;
2030 this[offset] = value & 0xFF;
2031 while (++i < byteLength && (mul *= 0x100)) {
2032 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2033 sub = 1;
2034 }
2035 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
2036 }
2037
2038 return offset + byteLength
2039};
2040
2041Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2042 value = +value;
2043 offset = offset | 0;
2044 if (!noAssert) {
2045 var limit = Math.pow(2, 8 * byteLength - 1);
2046
2047 checkInt(this, value, offset, byteLength, limit - 1, -limit);
2048 }
2049
2050 var i = byteLength - 1;
2051 var mul = 1;
2052 var sub = 0;
2053 this[offset + i] = value & 0xFF;
2054 while (--i >= 0 && (mul *= 0x100)) {
2055 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2056 sub = 1;
2057 }
2058 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
2059 }
2060
2061 return offset + byteLength
2062};
2063
2064Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2065 value = +value;
2066 offset = offset | 0;
2067 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
2068 if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
2069 if (value < 0) value = 0xff + value + 1;
2070 this[offset] = (value & 0xff);
2071 return offset + 1
2072};
2073
2074Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2075 value = +value;
2076 offset = offset | 0;
2077 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
2078 if (Buffer$1.TYPED_ARRAY_SUPPORT) {
2079 this[offset] = (value & 0xff);
2080 this[offset + 1] = (value >>> 8);
2081 } else {
2082 objectWriteUInt16(this, value, offset, true);
2083 }
2084 return offset + 2
2085};
2086
2087Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2088 value = +value;
2089 offset = offset | 0;
2090 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
2091 if (Buffer$1.TYPED_ARRAY_SUPPORT) {
2092 this[offset] = (value >>> 8);
2093 this[offset + 1] = (value & 0xff);
2094 } else {
2095 objectWriteUInt16(this, value, offset, false);
2096 }
2097 return offset + 2
2098};
2099
2100Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2101 value = +value;
2102 offset = offset | 0;
2103 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
2104 if (Buffer$1.TYPED_ARRAY_SUPPORT) {
2105 this[offset] = (value & 0xff);
2106 this[offset + 1] = (value >>> 8);
2107 this[offset + 2] = (value >>> 16);
2108 this[offset + 3] = (value >>> 24);
2109 } else {
2110 objectWriteUInt32(this, value, offset, true);
2111 }
2112 return offset + 4
2113};
2114
2115Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2116 value = +value;
2117 offset = offset | 0;
2118 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
2119 if (value < 0) value = 0xffffffff + value + 1;
2120 if (Buffer$1.TYPED_ARRAY_SUPPORT) {
2121 this[offset] = (value >>> 24);
2122 this[offset + 1] = (value >>> 16);
2123 this[offset + 2] = (value >>> 8);
2124 this[offset + 3] = (value & 0xff);
2125 } else {
2126 objectWriteUInt32(this, value, offset, false);
2127 }
2128 return offset + 4
2129};
2130
2131function checkIEEE754 (buf, value, offset, ext, max, min) {
2132 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2133 if (offset < 0) throw new RangeError('Index out of range')
2134}
2135
2136function writeFloat (buf, value, offset, littleEndian, noAssert) {
2137 if (!noAssert) {
2138 checkIEEE754(buf, value, offset, 4);
2139 }
2140 write(buf, value, offset, littleEndian, 23, 4);
2141 return offset + 4
2142}
2143
2144Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2145 return writeFloat(this, value, offset, true, noAssert)
2146};
2147
2148Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2149 return writeFloat(this, value, offset, false, noAssert)
2150};
2151
2152function writeDouble (buf, value, offset, littleEndian, noAssert) {
2153 if (!noAssert) {
2154 checkIEEE754(buf, value, offset, 8);
2155 }
2156 write(buf, value, offset, littleEndian, 52, 8);
2157 return offset + 8
2158}
2159
2160Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2161 return writeDouble(this, value, offset, true, noAssert)
2162};
2163
2164Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2165 return writeDouble(this, value, offset, false, noAssert)
2166};
2167
2168// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2169Buffer$1.prototype.copy = function copy (target, targetStart, start, end) {
2170 if (!start) start = 0;
2171 if (!end && end !== 0) end = this.length;
2172 if (targetStart >= target.length) targetStart = target.length;
2173 if (!targetStart) targetStart = 0;
2174 if (end > 0 && end < start) end = start;
2175
2176 // Copy 0 bytes; we're done
2177 if (end === start) return 0
2178 if (target.length === 0 || this.length === 0) return 0
2179
2180 // Fatal error conditions
2181 if (targetStart < 0) {
2182 throw new RangeError('targetStart out of bounds')
2183 }
2184 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
2185 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2186
2187 // Are we oob?
2188 if (end > this.length) end = this.length;
2189 if (target.length - targetStart < end - start) {
2190 end = target.length - targetStart + start;
2191 }
2192
2193 var len = end - start;
2194 var i;
2195
2196 if (this === target && start < targetStart && targetStart < end) {
2197 // descending copy from end
2198 for (i = len - 1; i >= 0; --i) {
2199 target[i + targetStart] = this[i + start];
2200 }
2201 } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) {
2202 // ascending copy from start
2203 for (i = 0; i < len; ++i) {
2204 target[i + targetStart] = this[i + start];
2205 }
2206 } else {
2207 Uint8Array.prototype.set.call(
2208 target,
2209 this.subarray(start, start + len),
2210 targetStart
2211 );
2212 }
2213
2214 return len
2215};
2216
2217// Usage:
2218// buffer.fill(number[, offset[, end]])
2219// buffer.fill(buffer[, offset[, end]])
2220// buffer.fill(string[, offset[, end]][, encoding])
2221Buffer$1.prototype.fill = function fill (val, start, end, encoding) {
2222 // Handle string cases:
2223 if (typeof val === 'string') {
2224 if (typeof start === 'string') {
2225 encoding = start;
2226 start = 0;
2227 end = this.length;
2228 } else if (typeof end === 'string') {
2229 encoding = end;
2230 end = this.length;
2231 }
2232 if (val.length === 1) {
2233 var code = val.charCodeAt(0);
2234 if (code < 256) {
2235 val = code;
2236 }
2237 }
2238 if (encoding !== undefined && typeof encoding !== 'string') {
2239 throw new TypeError('encoding must be a string')
2240 }
2241 if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) {
2242 throw new TypeError('Unknown encoding: ' + encoding)
2243 }
2244 } else if (typeof val === 'number') {
2245 val = val & 255;
2246 }
2247
2248 // Invalid ranges are not set to a default, so can range check early.
2249 if (start < 0 || this.length < start || this.length < end) {
2250 throw new RangeError('Out of range index')
2251 }
2252
2253 if (end <= start) {
2254 return this
2255 }
2256
2257 start = start >>> 0;
2258 end = end === undefined ? this.length : end >>> 0;
2259
2260 if (!val) val = 0;
2261
2262 var i;
2263 if (typeof val === 'number') {
2264 for (i = start; i < end; ++i) {
2265 this[i] = val;
2266 }
2267 } else {
2268 var bytes = internalIsBuffer(val)
2269 ? val
2270 : utf8ToBytes(new Buffer$1(val, encoding).toString());
2271 var len = bytes.length;
2272 for (i = 0; i < end - start; ++i) {
2273 this[i + start] = bytes[i % len];
2274 }
2275 }
2276
2277 return this
2278};
2279
2280// HELPER FUNCTIONS
2281// ================
2282
2283var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
2284
2285function base64clean (str) {
2286 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2287 str = stringtrim(str).replace(INVALID_BASE64_RE, '');
2288 // Node converts strings with length < 2 to ''
2289 if (str.length < 2) return ''
2290 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2291 while (str.length % 4 !== 0) {
2292 str = str + '=';
2293 }
2294 return str
2295}
2296
2297function stringtrim (str) {
2298 if (str.trim) return str.trim()
2299 return str.replace(/^\s+|\s+$/g, '')
2300}
2301
2302function toHex (n) {
2303 if (n < 16) return '0' + n.toString(16)
2304 return n.toString(16)
2305}
2306
2307function utf8ToBytes (string, units) {
2308 units = units || Infinity;
2309 var codePoint;
2310 var length = string.length;
2311 var leadSurrogate = null;
2312 var bytes = [];
2313
2314 for (var i = 0; i < length; ++i) {
2315 codePoint = string.charCodeAt(i);
2316
2317 // is surrogate component
2318 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2319 // last char was a lead
2320 if (!leadSurrogate) {
2321 // no lead yet
2322 if (codePoint > 0xDBFF) {
2323 // unexpected trail
2324 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
2325 continue
2326 } else if (i + 1 === length) {
2327 // unpaired lead
2328 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
2329 continue
2330 }
2331
2332 // valid lead
2333 leadSurrogate = codePoint;
2334
2335 continue
2336 }
2337
2338 // 2 leads in a row
2339 if (codePoint < 0xDC00) {
2340 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
2341 leadSurrogate = codePoint;
2342 continue
2343 }
2344
2345 // valid surrogate pair
2346 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
2347 } else if (leadSurrogate) {
2348 // valid bmp char, but last char was a lead
2349 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
2350 }
2351
2352 leadSurrogate = null;
2353
2354 // encode utf8
2355 if (codePoint < 0x80) {
2356 if ((units -= 1) < 0) break
2357 bytes.push(codePoint);
2358 } else if (codePoint < 0x800) {
2359 if ((units -= 2) < 0) break
2360 bytes.push(
2361 codePoint >> 0x6 | 0xC0,
2362 codePoint & 0x3F | 0x80
2363 );
2364 } else if (codePoint < 0x10000) {
2365 if ((units -= 3) < 0) break
2366 bytes.push(
2367 codePoint >> 0xC | 0xE0,
2368 codePoint >> 0x6 & 0x3F | 0x80,
2369 codePoint & 0x3F | 0x80
2370 );
2371 } else if (codePoint < 0x110000) {
2372 if ((units -= 4) < 0) break
2373 bytes.push(
2374 codePoint >> 0x12 | 0xF0,
2375 codePoint >> 0xC & 0x3F | 0x80,
2376 codePoint >> 0x6 & 0x3F | 0x80,
2377 codePoint & 0x3F | 0x80
2378 );
2379 } else {
2380 throw new Error('Invalid code point')
2381 }
2382 }
2383
2384 return bytes
2385}
2386
2387function asciiToBytes (str) {
2388 var byteArray = [];
2389 for (var i = 0; i < str.length; ++i) {
2390 // Node's code seems to be doing this and not & 0x7F..
2391 byteArray.push(str.charCodeAt(i) & 0xFF);
2392 }
2393 return byteArray
2394}
2395
2396function utf16leToBytes (str, units) {
2397 var c, hi, lo;
2398 var byteArray = [];
2399 for (var i = 0; i < str.length; ++i) {
2400 if ((units -= 2) < 0) break
2401
2402 c = str.charCodeAt(i);
2403 hi = c >> 8;
2404 lo = c % 256;
2405 byteArray.push(lo);
2406 byteArray.push(hi);
2407 }
2408
2409 return byteArray
2410}
2411
2412
2413function base64ToBytes (str) {
2414 return toByteArray(base64clean(str))
2415}
2416
2417function blitBuffer (src, dst, offset, length) {
2418 for (var i = 0; i < length; ++i) {
2419 if ((i + offset >= dst.length) || (i >= src.length)) break
2420 dst[i + offset] = src[i];
2421 }
2422 return i
2423}
2424
2425function isnan (val) {
2426 return val !== val // eslint-disable-line no-self-compare
2427}
2428
2429
2430// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
2431// The _isBuffer check is for Safari 5-7 support, because it's missing
2432// Object.prototype.constructor. Remove this eventually
2433function isBuffer(obj) {
2434 return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
2435}
2436
2437function isFastBuffer (obj) {
2438 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
2439}
2440
2441// For Node v0.10 support. Remove this eventually.
2442function isSlowBuffer (obj) {
2443 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
2444}
2445
2446// shim for using process in browser
2447// based off https://github.com/defunctzombie/node-process/blob/master/browser.js
2448
2449function defaultSetTimout() {
2450 throw new Error('setTimeout has not been defined');
2451}
2452function defaultClearTimeout () {
2453 throw new Error('clearTimeout has not been defined');
2454}
2455var cachedSetTimeout = defaultSetTimout;
2456var cachedClearTimeout = defaultClearTimeout;
2457if (typeof global$1.setTimeout === 'function') {
2458 cachedSetTimeout = setTimeout;
2459}
2460if (typeof global$1.clearTimeout === 'function') {
2461 cachedClearTimeout = clearTimeout;
2462}
2463
2464function runTimeout(fun) {
2465 if (cachedSetTimeout === setTimeout) {
2466 //normal enviroments in sane situations
2467 return setTimeout(fun, 0);
2468 }
2469 // if setTimeout wasn't available but was latter defined
2470 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
2471 cachedSetTimeout = setTimeout;
2472 return setTimeout(fun, 0);
2473 }
2474 try {
2475 // when when somebody has screwed with setTimeout but no I.E. maddness
2476 return cachedSetTimeout(fun, 0);
2477 } catch(e){
2478 try {
2479 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
2480 return cachedSetTimeout.call(null, fun, 0);
2481 } catch(e){
2482 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
2483 return cachedSetTimeout.call(this, fun, 0);
2484 }
2485 }
2486
2487
2488}
2489function runClearTimeout(marker) {
2490 if (cachedClearTimeout === clearTimeout) {
2491 //normal enviroments in sane situations
2492 return clearTimeout(marker);
2493 }
2494 // if clearTimeout wasn't available but was latter defined
2495 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
2496 cachedClearTimeout = clearTimeout;
2497 return clearTimeout(marker);
2498 }
2499 try {
2500 // when when somebody has screwed with setTimeout but no I.E. maddness
2501 return cachedClearTimeout(marker);
2502 } catch (e){
2503 try {
2504 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
2505 return cachedClearTimeout.call(null, marker);
2506 } catch (e){
2507 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
2508 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
2509 return cachedClearTimeout.call(this, marker);
2510 }
2511 }
2512
2513
2514
2515}
2516var queue = [];
2517var draining = false;
2518var currentQueue;
2519var queueIndex = -1;
2520
2521function cleanUpNextTick() {
2522 if (!draining || !currentQueue) {
2523 return;
2524 }
2525 draining = false;
2526 if (currentQueue.length) {
2527 queue = currentQueue.concat(queue);
2528 } else {
2529 queueIndex = -1;
2530 }
2531 if (queue.length) {
2532 drainQueue();
2533 }
2534}
2535
2536function drainQueue() {
2537 if (draining) {
2538 return;
2539 }
2540 var timeout = runTimeout(cleanUpNextTick);
2541 draining = true;
2542
2543 var len = queue.length;
2544 while(len) {
2545 currentQueue = queue;
2546 queue = [];
2547 while (++queueIndex < len) {
2548 if (currentQueue) {
2549 currentQueue[queueIndex].run();
2550 }
2551 }
2552 queueIndex = -1;
2553 len = queue.length;
2554 }
2555 currentQueue = null;
2556 draining = false;
2557 runClearTimeout(timeout);
2558}
2559function nextTick(fun) {
2560 var args = new Array(arguments.length - 1);
2561 if (arguments.length > 1) {
2562 for (var i = 1; i < arguments.length; i++) {
2563 args[i - 1] = arguments[i];
2564 }
2565 }
2566 queue.push(new Item(fun, args));
2567 if (queue.length === 1 && !draining) {
2568 runTimeout(drainQueue);
2569 }
2570}
2571// v8 likes predictible objects
2572function Item(fun, array) {
2573 this.fun = fun;
2574 this.array = array;
2575}
2576Item.prototype.run = function () {
2577 this.fun.apply(null, this.array);
2578};
2579var title = 'browser';
2580var platform = 'browser';
2581var browser = true;
2582var env = {};
2583var argv = [];
2584var version = ''; // empty string to avoid regexp issues
2585var versions = {};
2586var release = {};
2587var config = {};
2588
2589function noop() {}
2590
2591var on = noop;
2592var addListener = noop;
2593var once = noop;
2594var off = noop;
2595var removeListener = noop;
2596var removeAllListeners = noop;
2597var emit = noop;
2598
2599function binding(name) {
2600 throw new Error('process.binding is not supported');
2601}
2602
2603function cwd () { return '/' }
2604function chdir (dir) {
2605 throw new Error('process.chdir is not supported');
2606}function umask() { return 0; }
2607
2608// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
2609var performance = global$1.performance || {};
2610var performanceNow =
2611 performance.now ||
2612 performance.mozNow ||
2613 performance.msNow ||
2614 performance.oNow ||
2615 performance.webkitNow ||
2616 function(){ return (new Date()).getTime() };
2617
2618// generate timestamp or delta
2619// see http://nodejs.org/api/process.html#process_process_hrtime
2620function hrtime(previousTimestamp){
2621 var clocktime = performanceNow.call(performance)*1e-3;
2622 var seconds = Math.floor(clocktime);
2623 var nanoseconds = Math.floor((clocktime%1)*1e9);
2624 if (previousTimestamp) {
2625 seconds = seconds - previousTimestamp[0];
2626 nanoseconds = nanoseconds - previousTimestamp[1];
2627 if (nanoseconds<0) {
2628 seconds--;
2629 nanoseconds += 1e9;
2630 }
2631 }
2632 return [seconds,nanoseconds]
2633}
2634
2635var startTime = new Date();
2636function uptime() {
2637 var currentTime = new Date();
2638 var dif = currentTime - startTime;
2639 return dif / 1000;
2640}
2641
2642var process = {
2643 nextTick: nextTick,
2644 title: title,
2645 browser: browser,
2646 env: env,
2647 argv: argv,
2648 version: version,
2649 versions: versions,
2650 on: on,
2651 addListener: addListener,
2652 once: once,
2653 off: off,
2654 removeListener: removeListener,
2655 removeAllListeners: removeAllListeners,
2656 emit: emit,
2657 binding: binding,
2658 cwd: cwd,
2659 chdir: chdir,
2660 umask: umask,
2661 hrtime: hrtime,
2662 platform: platform,
2663 release: release,
2664 config: config,
2665 uptime: uptime
2666};
2667
2668var inherits;
2669if (typeof Object.create === 'function'){
2670 inherits = function inherits(ctor, superCtor) {
2671 // implementation from standard node.js 'util' module
2672 ctor.super_ = superCtor;
2673 ctor.prototype = Object.create(superCtor.prototype, {
2674 constructor: {
2675 value: ctor,
2676 enumerable: false,
2677 writable: true,
2678 configurable: true
2679 }
2680 });
2681 };
2682} else {
2683 inherits = function inherits(ctor, superCtor) {
2684 ctor.super_ = superCtor;
2685 var TempCtor = function () {};
2686 TempCtor.prototype = superCtor.prototype;
2687 ctor.prototype = new TempCtor();
2688 ctor.prototype.constructor = ctor;
2689 };
2690}
2691var inherits$1 = inherits;
2692
2693var formatRegExp = /%[sdj%]/g;
2694function format(f) {
2695 if (!isString(f)) {
2696 var objects = [];
2697 for (var i = 0; i < arguments.length; i++) {
2698 objects.push(inspect(arguments[i]));
2699 }
2700 return objects.join(' ');
2701 }
2702
2703 var i = 1;
2704 var args = arguments;
2705 var len = args.length;
2706 var str = String(f).replace(formatRegExp, function(x) {
2707 if (x === '%%') return '%';
2708 if (i >= len) return x;
2709 switch (x) {
2710 case '%s': return String(args[i++]);
2711 case '%d': return Number(args[i++]);
2712 case '%j':
2713 try {
2714 return JSON.stringify(args[i++]);
2715 } catch (_) {
2716 return '[Circular]';
2717 }
2718 default:
2719 return x;
2720 }
2721 });
2722 for (var x = args[i]; i < len; x = args[++i]) {
2723 if (isNull(x) || !isObject(x)) {
2724 str += ' ' + x;
2725 } else {
2726 str += ' ' + inspect(x);
2727 }
2728 }
2729 return str;
2730}
2731
2732// Mark that a method should not be used.
2733// Returns a modified function which warns once by default.
2734// If --no-deprecation is set, then it is a no-op.
2735function deprecate(fn, msg) {
2736 // Allow for deprecating things in the process of starting up.
2737 if (isUndefined(global$1.process)) {
2738 return function() {
2739 return deprecate(fn, msg).apply(this, arguments);
2740 };
2741 }
2742
2743 var warned = false;
2744 function deprecated() {
2745 if (!warned) {
2746 {
2747 console.error(msg);
2748 }
2749 warned = true;
2750 }
2751 return fn.apply(this, arguments);
2752 }
2753
2754 return deprecated;
2755}
2756
2757var debugs = {};
2758var debugEnviron;
2759function debuglog(set) {
2760 if (isUndefined(debugEnviron))
2761 debugEnviron = process.env.NODE_DEBUG || '';
2762 set = set.toUpperCase();
2763 if (!debugs[set]) {
2764 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
2765 var pid = 0;
2766 debugs[set] = function() {
2767 var msg = format.apply(null, arguments);
2768 console.error('%s %d: %s', set, pid, msg);
2769 };
2770 } else {
2771 debugs[set] = function() {};
2772 }
2773 }
2774 return debugs[set];
2775}
2776
2777/**
2778 * Echos the value of a value. Trys to print the value out
2779 * in the best way possible given the different types.
2780 *
2781 * @param {Object} obj The object to print out.
2782 * @param {Object} opts Optional options object that alters the output.
2783 */
2784/* legacy: obj, showHidden, depth, colors*/
2785function inspect(obj, opts) {
2786 // default options
2787 var ctx = {
2788 seen: [],
2789 stylize: stylizeNoColor
2790 };
2791 // legacy...
2792 if (arguments.length >= 3) ctx.depth = arguments[2];
2793 if (arguments.length >= 4) ctx.colors = arguments[3];
2794 if (isBoolean(opts)) {
2795 // legacy...
2796 ctx.showHidden = opts;
2797 } else if (opts) {
2798 // got an "options" object
2799 _extend(ctx, opts);
2800 }
2801 // set default options
2802 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
2803 if (isUndefined(ctx.depth)) ctx.depth = 2;
2804 if (isUndefined(ctx.colors)) ctx.colors = false;
2805 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
2806 if (ctx.colors) ctx.stylize = stylizeWithColor;
2807 return formatValue(ctx, obj, ctx.depth);
2808}
2809
2810// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
2811inspect.colors = {
2812 'bold' : [1, 22],
2813 'italic' : [3, 23],
2814 'underline' : [4, 24],
2815 'inverse' : [7, 27],
2816 'white' : [37, 39],
2817 'grey' : [90, 39],
2818 'black' : [30, 39],
2819 'blue' : [34, 39],
2820 'cyan' : [36, 39],
2821 'green' : [32, 39],
2822 'magenta' : [35, 39],
2823 'red' : [31, 39],
2824 'yellow' : [33, 39]
2825};
2826
2827// Don't use 'blue' not visible on cmd.exe
2828inspect.styles = {
2829 'special': 'cyan',
2830 'number': 'yellow',
2831 'boolean': 'yellow',
2832 'undefined': 'grey',
2833 'null': 'bold',
2834 'string': 'green',
2835 'date': 'magenta',
2836 // "name": intentionally not styling
2837 'regexp': 'red'
2838};
2839
2840
2841function stylizeWithColor(str, styleType) {
2842 var style = inspect.styles[styleType];
2843
2844 if (style) {
2845 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
2846 '\u001b[' + inspect.colors[style][1] + 'm';
2847 } else {
2848 return str;
2849 }
2850}
2851
2852
2853function stylizeNoColor(str, styleType) {
2854 return str;
2855}
2856
2857
2858function arrayToHash(array) {
2859 var hash = {};
2860
2861 array.forEach(function(val, idx) {
2862 hash[val] = true;
2863 });
2864
2865 return hash;
2866}
2867
2868
2869function formatValue(ctx, value, recurseTimes) {
2870 // Provide a hook for user-specified inspect functions.
2871 // Check that value is an object with an inspect function on it
2872 if (ctx.customInspect &&
2873 value &&
2874 isFunction(value.inspect) &&
2875 // Filter out the util module, it's inspect function is special
2876 value.inspect !== inspect &&
2877 // Also filter out any prototype objects using the circular check.
2878 !(value.constructor && value.constructor.prototype === value)) {
2879 var ret = value.inspect(recurseTimes, ctx);
2880 if (!isString(ret)) {
2881 ret = formatValue(ctx, ret, recurseTimes);
2882 }
2883 return ret;
2884 }
2885
2886 // Primitive types cannot have properties
2887 var primitive = formatPrimitive(ctx, value);
2888 if (primitive) {
2889 return primitive;
2890 }
2891
2892 // Look up the keys of the object.
2893 var keys = Object.keys(value);
2894 var visibleKeys = arrayToHash(keys);
2895
2896 if (ctx.showHidden) {
2897 keys = Object.getOwnPropertyNames(value);
2898 }
2899
2900 // IE doesn't make error fields non-enumerable
2901 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
2902 if (isError(value)
2903 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
2904 return formatError(value);
2905 }
2906
2907 // Some type of object without properties can be shortcutted.
2908 if (keys.length === 0) {
2909 if (isFunction(value)) {
2910 var name = value.name ? ': ' + value.name : '';
2911 return ctx.stylize('[Function' + name + ']', 'special');
2912 }
2913 if (isRegExp(value)) {
2914 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
2915 }
2916 if (isDate(value)) {
2917 return ctx.stylize(Date.prototype.toString.call(value), 'date');
2918 }
2919 if (isError(value)) {
2920 return formatError(value);
2921 }
2922 }
2923
2924 var base = '', array = false, braces = ['{', '}'];
2925
2926 // Make Array say that they are Array
2927 if (isArray$1(value)) {
2928 array = true;
2929 braces = ['[', ']'];
2930 }
2931
2932 // Make functions say that they are functions
2933 if (isFunction(value)) {
2934 var n = value.name ? ': ' + value.name : '';
2935 base = ' [Function' + n + ']';
2936 }
2937
2938 // Make RegExps say that they are RegExps
2939 if (isRegExp(value)) {
2940 base = ' ' + RegExp.prototype.toString.call(value);
2941 }
2942
2943 // Make dates with properties first say the date
2944 if (isDate(value)) {
2945 base = ' ' + Date.prototype.toUTCString.call(value);
2946 }
2947
2948 // Make error with message first say the error
2949 if (isError(value)) {
2950 base = ' ' + formatError(value);
2951 }
2952
2953 if (keys.length === 0 && (!array || value.length == 0)) {
2954 return braces[0] + base + braces[1];
2955 }
2956
2957 if (recurseTimes < 0) {
2958 if (isRegExp(value)) {
2959 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
2960 } else {
2961 return ctx.stylize('[Object]', 'special');
2962 }
2963 }
2964
2965 ctx.seen.push(value);
2966
2967 var output;
2968 if (array) {
2969 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
2970 } else {
2971 output = keys.map(function(key) {
2972 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
2973 });
2974 }
2975
2976 ctx.seen.pop();
2977
2978 return reduceToSingleString(output, base, braces);
2979}
2980
2981
2982function formatPrimitive(ctx, value) {
2983 if (isUndefined(value))
2984 return ctx.stylize('undefined', 'undefined');
2985 if (isString(value)) {
2986 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
2987 .replace(/'/g, "\\'")
2988 .replace(/\\"/g, '"') + '\'';
2989 return ctx.stylize(simple, 'string');
2990 }
2991 if (isNumber(value))
2992 return ctx.stylize('' + value, 'number');
2993 if (isBoolean(value))
2994 return ctx.stylize('' + value, 'boolean');
2995 // For some reason typeof null is "object", so special case here.
2996 if (isNull(value))
2997 return ctx.stylize('null', 'null');
2998}
2999
3000
3001function formatError(value) {
3002 return '[' + Error.prototype.toString.call(value) + ']';
3003}
3004
3005
3006function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
3007 var output = [];
3008 for (var i = 0, l = value.length; i < l; ++i) {
3009 if (hasOwnProperty(value, String(i))) {
3010 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
3011 String(i), true));
3012 } else {
3013 output.push('');
3014 }
3015 }
3016 keys.forEach(function(key) {
3017 if (!key.match(/^\d+$/)) {
3018 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
3019 key, true));
3020 }
3021 });
3022 return output;
3023}
3024
3025
3026function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
3027 var name, str, desc;
3028 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
3029 if (desc.get) {
3030 if (desc.set) {
3031 str = ctx.stylize('[Getter/Setter]', 'special');
3032 } else {
3033 str = ctx.stylize('[Getter]', 'special');
3034 }
3035 } else {
3036 if (desc.set) {
3037 str = ctx.stylize('[Setter]', 'special');
3038 }
3039 }
3040 if (!hasOwnProperty(visibleKeys, key)) {
3041 name = '[' + key + ']';
3042 }
3043 if (!str) {
3044 if (ctx.seen.indexOf(desc.value) < 0) {
3045 if (isNull(recurseTimes)) {
3046 str = formatValue(ctx, desc.value, null);
3047 } else {
3048 str = formatValue(ctx, desc.value, recurseTimes - 1);
3049 }
3050 if (str.indexOf('\n') > -1) {
3051 if (array) {
3052 str = str.split('\n').map(function(line) {
3053 return ' ' + line;
3054 }).join('\n').substr(2);
3055 } else {
3056 str = '\n' + str.split('\n').map(function(line) {
3057 return ' ' + line;
3058 }).join('\n');
3059 }
3060 }
3061 } else {
3062 str = ctx.stylize('[Circular]', 'special');
3063 }
3064 }
3065 if (isUndefined(name)) {
3066 if (array && key.match(/^\d+$/)) {
3067 return str;
3068 }
3069 name = JSON.stringify('' + key);
3070 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
3071 name = name.substr(1, name.length - 2);
3072 name = ctx.stylize(name, 'name');
3073 } else {
3074 name = name.replace(/'/g, "\\'")
3075 .replace(/\\"/g, '"')
3076 .replace(/(^"|"$)/g, "'");
3077 name = ctx.stylize(name, 'string');
3078 }
3079 }
3080
3081 return name + ': ' + str;
3082}
3083
3084
3085function reduceToSingleString(output, base, braces) {
3086 var length = output.reduce(function(prev, cur) {
3087 if (cur.indexOf('\n') >= 0) ;
3088 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
3089 }, 0);
3090
3091 if (length > 60) {
3092 return braces[0] +
3093 (base === '' ? '' : base + '\n ') +
3094 ' ' +
3095 output.join(',\n ') +
3096 ' ' +
3097 braces[1];
3098 }
3099
3100 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
3101}
3102
3103
3104// NOTE: These type checking functions intentionally don't use `instanceof`
3105// because it is fragile and can be easily faked with `Object.create()`.
3106function isArray$1(ar) {
3107 return Array.isArray(ar);
3108}
3109
3110function isBoolean(arg) {
3111 return typeof arg === 'boolean';
3112}
3113
3114function isNull(arg) {
3115 return arg === null;
3116}
3117
3118function isNullOrUndefined(arg) {
3119 return arg == null;
3120}
3121
3122function isNumber(arg) {
3123 return typeof arg === 'number';
3124}
3125
3126function isString(arg) {
3127 return typeof arg === 'string';
3128}
3129
3130function isSymbol(arg) {
3131 return typeof arg === 'symbol';
3132}
3133
3134function isUndefined(arg) {
3135 return arg === void 0;
3136}
3137
3138function isRegExp(re) {
3139 return isObject(re) && objectToString(re) === '[object RegExp]';
3140}
3141
3142function isObject(arg) {
3143 return typeof arg === 'object' && arg !== null;
3144}
3145
3146function isDate(d) {
3147 return isObject(d) && objectToString(d) === '[object Date]';
3148}
3149
3150function isError(e) {
3151 return isObject(e) &&
3152 (objectToString(e) === '[object Error]' || e instanceof Error);
3153}
3154
3155function isFunction(arg) {
3156 return typeof arg === 'function';
3157}
3158
3159function isPrimitive(arg) {
3160 return arg === null ||
3161 typeof arg === 'boolean' ||
3162 typeof arg === 'number' ||
3163 typeof arg === 'string' ||
3164 typeof arg === 'symbol' || // ES6 symbol
3165 typeof arg === 'undefined';
3166}
3167
3168function isBuffer$1(maybeBuf) {
3169 return isBuffer(maybeBuf);
3170}
3171
3172function objectToString(o) {
3173 return Object.prototype.toString.call(o);
3174}
3175
3176
3177function pad(n) {
3178 return n < 10 ? '0' + n.toString(10) : n.toString(10);
3179}
3180
3181
3182var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
3183 'Oct', 'Nov', 'Dec'];
3184
3185// 26 Feb 16:19:34
3186function timestamp() {
3187 var d = new Date();
3188 var time = [pad(d.getHours()),
3189 pad(d.getMinutes()),
3190 pad(d.getSeconds())].join(':');
3191 return [d.getDate(), months[d.getMonth()], time].join(' ');
3192}
3193
3194
3195// log is just a thin wrapper to console.log that prepends a timestamp
3196function log() {
3197 console.log('%s - %s', timestamp(), format.apply(null, arguments));
3198}
3199
3200function _extend(origin, add) {
3201 // Don't do anything if add isn't an object
3202 if (!add || !isObject(add)) return origin;
3203
3204 var keys = Object.keys(add);
3205 var i = keys.length;
3206 while (i--) {
3207 origin[keys[i]] = add[keys[i]];
3208 }
3209 return origin;
3210}
3211function hasOwnProperty(obj, prop) {
3212 return Object.prototype.hasOwnProperty.call(obj, prop);
3213}
3214
3215var util = {
3216 inherits: inherits$1,
3217 _extend: _extend,
3218 log: log,
3219 isBuffer: isBuffer$1,
3220 isPrimitive: isPrimitive,
3221 isFunction: isFunction,
3222 isError: isError,
3223 isDate: isDate,
3224 isObject: isObject,
3225 isRegExp: isRegExp,
3226 isUndefined: isUndefined,
3227 isSymbol: isSymbol,
3228 isString: isString,
3229 isNumber: isNumber,
3230 isNullOrUndefined: isNullOrUndefined,
3231 isNull: isNull,
3232 isBoolean: isBoolean,
3233 isArray: isArray$1,
3234 inspect: inspect,
3235 deprecate: deprecate,
3236 format: format,
3237 debuglog: debuglog
3238};
3239
3240function BufferList() {
3241 this.head = null;
3242 this.tail = null;
3243 this.length = 0;
3244}
3245
3246BufferList.prototype.push = function (v) {
3247 var entry = { data: v, next: null };
3248 if (this.length > 0) this.tail.next = entry;else this.head = entry;
3249 this.tail = entry;
3250 ++this.length;
3251};
3252
3253BufferList.prototype.unshift = function (v) {
3254 var entry = { data: v, next: this.head };
3255 if (this.length === 0) this.tail = entry;
3256 this.head = entry;
3257 ++this.length;
3258};
3259
3260BufferList.prototype.shift = function () {
3261 if (this.length === 0) return;
3262 var ret = this.head.data;
3263 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
3264 --this.length;
3265 return ret;
3266};
3267
3268BufferList.prototype.clear = function () {
3269 this.head = this.tail = null;
3270 this.length = 0;
3271};
3272
3273BufferList.prototype.join = function (s) {
3274 if (this.length === 0) return '';
3275 var p = this.head;
3276 var ret = '' + p.data;
3277 while (p = p.next) {
3278 ret += s + p.data;
3279 }return ret;
3280};
3281
3282BufferList.prototype.concat = function (n) {
3283 if (this.length === 0) return Buffer$1.alloc(0);
3284 if (this.length === 1) return this.head.data;
3285 var ret = Buffer$1.allocUnsafe(n >>> 0);
3286 var p = this.head;
3287 var i = 0;
3288 while (p) {
3289 p.data.copy(ret, i);
3290 i += p.data.length;
3291 p = p.next;
3292 }
3293 return ret;
3294};
3295
3296// Copyright Joyent, Inc. and other Node contributors.
3297var isBufferEncoding = Buffer$1.isEncoding
3298 || function(encoding) {
3299 switch (encoding && encoding.toLowerCase()) {
3300 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
3301 default: return false;
3302 }
3303 };
3304
3305
3306function assertEncoding(encoding) {
3307 if (encoding && !isBufferEncoding(encoding)) {
3308 throw new Error('Unknown encoding: ' + encoding);
3309 }
3310}
3311
3312// StringDecoder provides an interface for efficiently splitting a series of
3313// buffers into a series of JS strings without breaking apart multi-byte
3314// characters. CESU-8 is handled as part of the UTF-8 encoding.
3315//
3316// @TODO Handling all encodings inside a single object makes it very difficult
3317// to reason about this code, so it should be split up in the future.
3318// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
3319// points as used by CESU-8.
3320function StringDecoder(encoding) {
3321 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
3322 assertEncoding(encoding);
3323 switch (this.encoding) {
3324 case 'utf8':
3325 // CESU-8 represents each of Surrogate Pair by 3-bytes
3326 this.surrogateSize = 3;
3327 break;
3328 case 'ucs2':
3329 case 'utf16le':
3330 // UTF-16 represents each of Surrogate Pair by 2-bytes
3331 this.surrogateSize = 2;
3332 this.detectIncompleteChar = utf16DetectIncompleteChar;
3333 break;
3334 case 'base64':
3335 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
3336 this.surrogateSize = 3;
3337 this.detectIncompleteChar = base64DetectIncompleteChar;
3338 break;
3339 default:
3340 this.write = passThroughWrite;
3341 return;
3342 }
3343
3344 // Enough space to store all bytes of a single character. UTF-8 needs 4
3345 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
3346 this.charBuffer = new Buffer$1(6);
3347 // Number of bytes received for the current incomplete multi-byte character.
3348 this.charReceived = 0;
3349 // Number of bytes expected for the current incomplete multi-byte character.
3350 this.charLength = 0;
3351}
3352
3353// write decodes the given buffer and returns it as JS string that is
3354// guaranteed to not contain any partial multi-byte characters. Any partial
3355// character found at the end of the buffer is buffered up, and will be
3356// returned when calling write again with the remaining bytes.
3357//
3358// Note: Converting a Buffer containing an orphan surrogate to a String
3359// currently works, but converting a String to a Buffer (via `new Buffer`, or
3360// Buffer#write) will replace incomplete surrogates with the unicode
3361// replacement character. See https://codereview.chromium.org/121173009/ .
3362StringDecoder.prototype.write = function(buffer) {
3363 var charStr = '';
3364 // if our last write ended with an incomplete multibyte character
3365 while (this.charLength) {
3366 // determine how many remaining bytes this buffer has to offer for this char
3367 var available = (buffer.length >= this.charLength - this.charReceived) ?
3368 this.charLength - this.charReceived :
3369 buffer.length;
3370
3371 // add the new bytes to the char buffer
3372 buffer.copy(this.charBuffer, this.charReceived, 0, available);
3373 this.charReceived += available;
3374
3375 if (this.charReceived < this.charLength) {
3376 // still not enough chars in this buffer? wait for more ...
3377 return '';
3378 }
3379
3380 // remove bytes belonging to the current character from the buffer
3381 buffer = buffer.slice(available, buffer.length);
3382
3383 // get the character that was split
3384 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
3385
3386 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
3387 var charCode = charStr.charCodeAt(charStr.length - 1);
3388 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
3389 this.charLength += this.surrogateSize;
3390 charStr = '';
3391 continue;
3392 }
3393 this.charReceived = this.charLength = 0;
3394
3395 // if there are no more bytes in this buffer, just emit our char
3396 if (buffer.length === 0) {
3397 return charStr;
3398 }
3399 break;
3400 }
3401
3402 // determine and set charLength / charReceived
3403 this.detectIncompleteChar(buffer);
3404
3405 var end = buffer.length;
3406 if (this.charLength) {
3407 // buffer the incomplete character bytes we got
3408 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
3409 end -= this.charReceived;
3410 }
3411
3412 charStr += buffer.toString(this.encoding, 0, end);
3413
3414 var end = charStr.length - 1;
3415 var charCode = charStr.charCodeAt(end);
3416 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
3417 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
3418 var size = this.surrogateSize;
3419 this.charLength += size;
3420 this.charReceived += size;
3421 this.charBuffer.copy(this.charBuffer, size, 0, size);
3422 buffer.copy(this.charBuffer, 0, 0, size);
3423 return charStr.substring(0, end);
3424 }
3425
3426 // or just emit the charStr
3427 return charStr;
3428};
3429
3430// detectIncompleteChar determines if there is an incomplete UTF-8 character at
3431// the end of the given buffer. If so, it sets this.charLength to the byte
3432// length that character, and sets this.charReceived to the number of bytes
3433// that are available for this character.
3434StringDecoder.prototype.detectIncompleteChar = function(buffer) {
3435 // determine how many bytes we have to check at the end of this buffer
3436 var i = (buffer.length >= 3) ? 3 : buffer.length;
3437
3438 // Figure out if one of the last i bytes of our buffer announces an
3439 // incomplete char.
3440 for (; i > 0; i--) {
3441 var c = buffer[buffer.length - i];
3442
3443 // See http://en.wikipedia.org/wiki/UTF-8#Description
3444
3445 // 110XXXXX
3446 if (i == 1 && c >> 5 == 0x06) {
3447 this.charLength = 2;
3448 break;
3449 }
3450
3451 // 1110XXXX
3452 if (i <= 2 && c >> 4 == 0x0E) {
3453 this.charLength = 3;
3454 break;
3455 }
3456
3457 // 11110XXX
3458 if (i <= 3 && c >> 3 == 0x1E) {
3459 this.charLength = 4;
3460 break;
3461 }
3462 }
3463 this.charReceived = i;
3464};
3465
3466StringDecoder.prototype.end = function(buffer) {
3467 var res = '';
3468 if (buffer && buffer.length)
3469 res = this.write(buffer);
3470
3471 if (this.charReceived) {
3472 var cr = this.charReceived;
3473 var buf = this.charBuffer;
3474 var enc = this.encoding;
3475 res += buf.slice(0, cr).toString(enc);
3476 }
3477
3478 return res;
3479};
3480
3481function passThroughWrite(buffer) {
3482 return buffer.toString(this.encoding);
3483}
3484
3485function utf16DetectIncompleteChar(buffer) {
3486 this.charReceived = buffer.length % 2;
3487 this.charLength = this.charReceived ? 2 : 0;
3488}
3489
3490function base64DetectIncompleteChar(buffer) {
3491 this.charReceived = buffer.length % 3;
3492 this.charLength = this.charReceived ? 3 : 0;
3493}
3494
3495Readable.ReadableState = ReadableState;
3496
3497var debug = debuglog('stream');
3498inherits$1(Readable, EventEmitter);
3499
3500function prependListener(emitter, event, fn) {
3501 // Sadly this is not cacheable as some libraries bundle their own
3502 // event emitter implementation with them.
3503 if (typeof emitter.prependListener === 'function') {
3504 return emitter.prependListener(event, fn);
3505 } else {
3506 // This is a hack to make sure that our error handler is attached before any
3507 // userland ones. NEVER DO THIS. This is here only because this code needs
3508 // to continue to work with older versions of Node.js that do not include
3509 // the prependListener() method. The goal is to eventually remove this hack.
3510 if (!emitter._events || !emitter._events[event])
3511 emitter.on(event, fn);
3512 else if (Array.isArray(emitter._events[event]))
3513 emitter._events[event].unshift(fn);
3514 else
3515 emitter._events[event] = [fn, emitter._events[event]];
3516 }
3517}
3518function listenerCount$1 (emitter, type) {
3519 return emitter.listeners(type).length;
3520}
3521function ReadableState(options, stream) {
3522
3523 options = options || {};
3524
3525 // object stream flag. Used to make read(n) ignore n and to
3526 // make all the buffer merging and length checks go away
3527 this.objectMode = !!options.objectMode;
3528
3529 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
3530
3531 // the point at which it stops calling _read() to fill the buffer
3532 // Note: 0 is a valid value, means "don't call _read preemptively ever"
3533 var hwm = options.highWaterMark;
3534 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
3535 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
3536
3537 // cast to ints.
3538 this.highWaterMark = ~ ~this.highWaterMark;
3539
3540 // A linked list is used to store data chunks instead of an array because the
3541 // linked list can remove elements from the beginning faster than
3542 // array.shift()
3543 this.buffer = new BufferList();
3544 this.length = 0;
3545 this.pipes = null;
3546 this.pipesCount = 0;
3547 this.flowing = null;
3548 this.ended = false;
3549 this.endEmitted = false;
3550 this.reading = false;
3551
3552 // a flag to be able to tell if the onwrite cb is called immediately,
3553 // or on a later tick. We set this to true at first, because any
3554 // actions that shouldn't happen until "later" should generally also
3555 // not happen before the first write call.
3556 this.sync = true;
3557
3558 // whenever we return null, then we set a flag to say
3559 // that we're awaiting a 'readable' event emission.
3560 this.needReadable = false;
3561 this.emittedReadable = false;
3562 this.readableListening = false;
3563 this.resumeScheduled = false;
3564
3565 // Crypto is kind of old and crusty. Historically, its default string
3566 // encoding is 'binary' so we have to make this configurable.
3567 // Everything else in the universe uses 'utf8', though.
3568 this.defaultEncoding = options.defaultEncoding || 'utf8';
3569
3570 // when piping, we only care about 'readable' events that happen
3571 // after read()ing all the bytes and not getting any pushback.
3572 this.ranOut = false;
3573
3574 // the number of writers that are awaiting a drain event in .pipe()s
3575 this.awaitDrain = 0;
3576
3577 // if true, a maybeReadMore has been scheduled
3578 this.readingMore = false;
3579
3580 this.decoder = null;
3581 this.encoding = null;
3582 if (options.encoding) {
3583 this.decoder = new StringDecoder(options.encoding);
3584 this.encoding = options.encoding;
3585 }
3586}
3587function Readable(options) {
3588
3589 if (!(this instanceof Readable)) return new Readable(options);
3590
3591 this._readableState = new ReadableState(options, this);
3592
3593 // legacy
3594 this.readable = true;
3595
3596 if (options && typeof options.read === 'function') this._read = options.read;
3597
3598 EventEmitter.call(this);
3599}
3600
3601// Manually shove something into the read() buffer.
3602// This returns true if the highWaterMark has not been hit yet,
3603// similar to how Writable.write() returns true if you should
3604// write() some more.
3605Readable.prototype.push = function (chunk, encoding) {
3606 var state = this._readableState;
3607
3608 if (!state.objectMode && typeof chunk === 'string') {
3609 encoding = encoding || state.defaultEncoding;
3610 if (encoding !== state.encoding) {
3611 chunk = Buffer$1.from(chunk, encoding);
3612 encoding = '';
3613 }
3614 }
3615
3616 return readableAddChunk(this, state, chunk, encoding, false);
3617};
3618
3619// Unshift should *always* be something directly out of read()
3620Readable.prototype.unshift = function (chunk) {
3621 var state = this._readableState;
3622 return readableAddChunk(this, state, chunk, '', true);
3623};
3624
3625Readable.prototype.isPaused = function () {
3626 return this._readableState.flowing === false;
3627};
3628
3629function readableAddChunk(stream, state, chunk, encoding, addToFront) {
3630 var er = chunkInvalid(state, chunk);
3631 if (er) {
3632 stream.emit('error', er);
3633 } else if (chunk === null) {
3634 state.reading = false;
3635 onEofChunk(stream, state);
3636 } else if (state.objectMode || chunk && chunk.length > 0) {
3637 if (state.ended && !addToFront) {
3638 var e = new Error('stream.push() after EOF');
3639 stream.emit('error', e);
3640 } else if (state.endEmitted && addToFront) {
3641 var _e = new Error('stream.unshift() after end event');
3642 stream.emit('error', _e);
3643 } else {
3644 var skipAdd;
3645 if (state.decoder && !addToFront && !encoding) {
3646 chunk = state.decoder.write(chunk);
3647 skipAdd = !state.objectMode && chunk.length === 0;
3648 }
3649
3650 if (!addToFront) state.reading = false;
3651
3652 // Don't add to the buffer if we've decoded to an empty string chunk and
3653 // we're not in object mode
3654 if (!skipAdd) {
3655 // if we want the data now, just emit it.
3656 if (state.flowing && state.length === 0 && !state.sync) {
3657 stream.emit('data', chunk);
3658 stream.read(0);
3659 } else {
3660 // update the buffer info.
3661 state.length += state.objectMode ? 1 : chunk.length;
3662 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
3663
3664 if (state.needReadable) emitReadable(stream);
3665 }
3666 }
3667
3668 maybeReadMore(stream, state);
3669 }
3670 } else if (!addToFront) {
3671 state.reading = false;
3672 }
3673
3674 return needMoreData(state);
3675}
3676
3677// if it's past the high water mark, we can push in some more.
3678// Also, if we have no data yet, we can stand some
3679// more bytes. This is to work around cases where hwm=0,
3680// such as the repl. Also, if the push() triggered a
3681// readable event, and the user called read(largeNumber) such that
3682// needReadable was set, then we ought to push more, so that another
3683// 'readable' event will be triggered.
3684function needMoreData(state) {
3685 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
3686}
3687
3688// backwards compatibility.
3689Readable.prototype.setEncoding = function (enc) {
3690 this._readableState.decoder = new StringDecoder(enc);
3691 this._readableState.encoding = enc;
3692 return this;
3693};
3694
3695// Don't raise the hwm > 8MB
3696var MAX_HWM = 0x800000;
3697function computeNewHighWaterMark(n) {
3698 if (n >= MAX_HWM) {
3699 n = MAX_HWM;
3700 } else {
3701 // Get the next highest power of 2 to prevent increasing hwm excessively in
3702 // tiny amounts
3703 n--;
3704 n |= n >>> 1;
3705 n |= n >>> 2;
3706 n |= n >>> 4;
3707 n |= n >>> 8;
3708 n |= n >>> 16;
3709 n++;
3710 }
3711 return n;
3712}
3713
3714// This function is designed to be inlinable, so please take care when making
3715// changes to the function body.
3716function howMuchToRead(n, state) {
3717 if (n <= 0 || state.length === 0 && state.ended) return 0;
3718 if (state.objectMode) return 1;
3719 if (n !== n) {
3720 // Only flow one buffer at a time
3721 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
3722 }
3723 // If we're asking for more than the current hwm, then raise the hwm.
3724 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
3725 if (n <= state.length) return n;
3726 // Don't have enough
3727 if (!state.ended) {
3728 state.needReadable = true;
3729 return 0;
3730 }
3731 return state.length;
3732}
3733
3734// you can override either this method, or the async _read(n) below.
3735Readable.prototype.read = function (n) {
3736 debug('read', n);
3737 n = parseInt(n, 10);
3738 var state = this._readableState;
3739 var nOrig = n;
3740
3741 if (n !== 0) state.emittedReadable = false;
3742
3743 // if we're doing read(0) to trigger a readable event, but we
3744 // already have a bunch of data in the buffer, then just trigger
3745 // the 'readable' event and move on.
3746 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
3747 debug('read: emitReadable', state.length, state.ended);
3748 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
3749 return null;
3750 }
3751
3752 n = howMuchToRead(n, state);
3753
3754 // if we've ended, and we're now clear, then finish it up.
3755 if (n === 0 && state.ended) {
3756 if (state.length === 0) endReadable(this);
3757 return null;
3758 }
3759
3760 // All the actual chunk generation logic needs to be
3761 // *below* the call to _read. The reason is that in certain
3762 // synthetic stream cases, such as passthrough streams, _read
3763 // may be a completely synchronous operation which may change
3764 // the state of the read buffer, providing enough data when
3765 // before there was *not* enough.
3766 //
3767 // So, the steps are:
3768 // 1. Figure out what the state of things will be after we do
3769 // a read from the buffer.
3770 //
3771 // 2. If that resulting state will trigger a _read, then call _read.
3772 // Note that this may be asynchronous, or synchronous. Yes, it is
3773 // deeply ugly to write APIs this way, but that still doesn't mean
3774 // that the Readable class should behave improperly, as streams are
3775 // designed to be sync/async agnostic.
3776 // Take note if the _read call is sync or async (ie, if the read call
3777 // has returned yet), so that we know whether or not it's safe to emit
3778 // 'readable' etc.
3779 //
3780 // 3. Actually pull the requested chunks out of the buffer and return.
3781
3782 // if we need a readable event, then we need to do some reading.
3783 var doRead = state.needReadable;
3784 debug('need readable', doRead);
3785
3786 // if we currently have less than the highWaterMark, then also read some
3787 if (state.length === 0 || state.length - n < state.highWaterMark) {
3788 doRead = true;
3789 debug('length less than watermark', doRead);
3790 }
3791
3792 // however, if we've ended, then there's no point, and if we're already
3793 // reading, then it's unnecessary.
3794 if (state.ended || state.reading) {
3795 doRead = false;
3796 debug('reading or ended', doRead);
3797 } else if (doRead) {
3798 debug('do read');
3799 state.reading = true;
3800 state.sync = true;
3801 // if the length is currently zero, then we *need* a readable event.
3802 if (state.length === 0) state.needReadable = true;
3803 // call internal read method
3804 this._read(state.highWaterMark);
3805 state.sync = false;
3806 // If _read pushed data synchronously, then `reading` will be false,
3807 // and we need to re-evaluate how much data we can return to the user.
3808 if (!state.reading) n = howMuchToRead(nOrig, state);
3809 }
3810
3811 var ret;
3812 if (n > 0) ret = fromList(n, state);else ret = null;
3813
3814 if (ret === null) {
3815 state.needReadable = true;
3816 n = 0;
3817 } else {
3818 state.length -= n;
3819 }
3820
3821 if (state.length === 0) {
3822 // If we have nothing in the buffer, then we want to know
3823 // as soon as we *do* get something into the buffer.
3824 if (!state.ended) state.needReadable = true;
3825
3826 // If we tried to read() past the EOF, then emit end on the next tick.
3827 if (nOrig !== n && state.ended) endReadable(this);
3828 }
3829
3830 if (ret !== null) this.emit('data', ret);
3831
3832 return ret;
3833};
3834
3835function chunkInvalid(state, chunk) {
3836 var er = null;
3837 if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
3838 er = new TypeError('Invalid non-string/buffer chunk');
3839 }
3840 return er;
3841}
3842
3843function onEofChunk(stream, state) {
3844 if (state.ended) return;
3845 if (state.decoder) {
3846 var chunk = state.decoder.end();
3847 if (chunk && chunk.length) {
3848 state.buffer.push(chunk);
3849 state.length += state.objectMode ? 1 : chunk.length;
3850 }
3851 }
3852 state.ended = true;
3853
3854 // emit 'readable' now to make sure it gets picked up.
3855 emitReadable(stream);
3856}
3857
3858// Don't emit readable right away in sync mode, because this can trigger
3859// another read() call => stack overflow. This way, it might trigger
3860// a nextTick recursion warning, but that's not so bad.
3861function emitReadable(stream) {
3862 var state = stream._readableState;
3863 state.needReadable = false;
3864 if (!state.emittedReadable) {
3865 debug('emitReadable', state.flowing);
3866 state.emittedReadable = true;
3867 if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream);
3868 }
3869}
3870
3871function emitReadable_(stream) {
3872 debug('emit readable');
3873 stream.emit('readable');
3874 flow(stream);
3875}
3876
3877// at this point, the user has presumably seen the 'readable' event,
3878// and called read() to consume some data. that may have triggered
3879// in turn another _read(n) call, in which case reading = true if
3880// it's in progress.
3881// However, if we're not ended, or reading, and the length < hwm,
3882// then go ahead and try to read some more preemptively.
3883function maybeReadMore(stream, state) {
3884 if (!state.readingMore) {
3885 state.readingMore = true;
3886 nextTick(maybeReadMore_, stream, state);
3887 }
3888}
3889
3890function maybeReadMore_(stream, state) {
3891 var len = state.length;
3892 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
3893 debug('maybeReadMore read 0');
3894 stream.read(0);
3895 if (len === state.length)
3896 // didn't get any data, stop spinning.
3897 break;else len = state.length;
3898 }
3899 state.readingMore = false;
3900}
3901
3902// abstract method. to be overridden in specific implementation classes.
3903// call cb(er, data) where data is <= n in length.
3904// for virtual (non-string, non-buffer) streams, "length" is somewhat
3905// arbitrary, and perhaps not very meaningful.
3906Readable.prototype._read = function (n) {
3907 this.emit('error', new Error('not implemented'));
3908};
3909
3910Readable.prototype.pipe = function (dest, pipeOpts) {
3911 var src = this;
3912 var state = this._readableState;
3913
3914 switch (state.pipesCount) {
3915 case 0:
3916 state.pipes = dest;
3917 break;
3918 case 1:
3919 state.pipes = [state.pipes, dest];
3920 break;
3921 default:
3922 state.pipes.push(dest);
3923 break;
3924 }
3925 state.pipesCount += 1;
3926 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
3927
3928 var doEnd = (!pipeOpts || pipeOpts.end !== false);
3929
3930 var endFn = doEnd ? onend : cleanup;
3931 if (state.endEmitted) nextTick(endFn);else src.once('end', endFn);
3932
3933 dest.on('unpipe', onunpipe);
3934 function onunpipe(readable) {
3935 debug('onunpipe');
3936 if (readable === src) {
3937 cleanup();
3938 }
3939 }
3940
3941 function onend() {
3942 debug('onend');
3943 dest.end();
3944 }
3945
3946 // when the dest drains, it reduces the awaitDrain counter
3947 // on the source. This would be more elegant with a .once()
3948 // handler in flow(), but adding and removing repeatedly is
3949 // too slow.
3950 var ondrain = pipeOnDrain(src);
3951 dest.on('drain', ondrain);
3952
3953 var cleanedUp = false;
3954 function cleanup() {
3955 debug('cleanup');
3956 // cleanup event handlers once the pipe is broken
3957 dest.removeListener('close', onclose);
3958 dest.removeListener('finish', onfinish);
3959 dest.removeListener('drain', ondrain);
3960 dest.removeListener('error', onerror);
3961 dest.removeListener('unpipe', onunpipe);
3962 src.removeListener('end', onend);
3963 src.removeListener('end', cleanup);
3964 src.removeListener('data', ondata);
3965
3966 cleanedUp = true;
3967
3968 // if the reader is waiting for a drain event from this
3969 // specific writer, then it would cause it to never start
3970 // flowing again.
3971 // So, if this is awaiting a drain, then we just call it now.
3972 // If we don't know, then assume that we are waiting for one.
3973 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
3974 }
3975
3976 // If the user pushes more data while we're writing to dest then we'll end up
3977 // in ondata again. However, we only want to increase awaitDrain once because
3978 // dest will only emit one 'drain' event for the multiple writes.
3979 // => Introduce a guard on increasing awaitDrain.
3980 var increasedAwaitDrain = false;
3981 src.on('data', ondata);
3982 function ondata(chunk) {
3983 debug('ondata');
3984 increasedAwaitDrain = false;
3985 var ret = dest.write(chunk);
3986 if (false === ret && !increasedAwaitDrain) {
3987 // If the user unpiped during `dest.write()`, it is possible
3988 // to get stuck in a permanently paused state if that write
3989 // also returned false.
3990 // => Check whether `dest` is still a piping destination.
3991 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
3992 debug('false write response, pause', src._readableState.awaitDrain);
3993 src._readableState.awaitDrain++;
3994 increasedAwaitDrain = true;
3995 }
3996 src.pause();
3997 }
3998 }
3999
4000 // if the dest has an error, then stop piping into it.
4001 // however, don't suppress the throwing behavior for this.
4002 function onerror(er) {
4003 debug('onerror', er);
4004 unpipe();
4005 dest.removeListener('error', onerror);
4006 if (listenerCount$1(dest, 'error') === 0) dest.emit('error', er);
4007 }
4008
4009 // Make sure our error handler is attached before userland ones.
4010 prependListener(dest, 'error', onerror);
4011
4012 // Both close and finish should trigger unpipe, but only once.
4013 function onclose() {
4014 dest.removeListener('finish', onfinish);
4015 unpipe();
4016 }
4017 dest.once('close', onclose);
4018 function onfinish() {
4019 debug('onfinish');
4020 dest.removeListener('close', onclose);
4021 unpipe();
4022 }
4023 dest.once('finish', onfinish);
4024
4025 function unpipe() {
4026 debug('unpipe');
4027 src.unpipe(dest);
4028 }
4029
4030 // tell the dest that it's being piped to
4031 dest.emit('pipe', src);
4032
4033 // start the flow if it hasn't been started already.
4034 if (!state.flowing) {
4035 debug('pipe resume');
4036 src.resume();
4037 }
4038
4039 return dest;
4040};
4041
4042function pipeOnDrain(src) {
4043 return function () {
4044 var state = src._readableState;
4045 debug('pipeOnDrain', state.awaitDrain);
4046 if (state.awaitDrain) state.awaitDrain--;
4047 if (state.awaitDrain === 0 && src.listeners('data').length) {
4048 state.flowing = true;
4049 flow(src);
4050 }
4051 };
4052}
4053
4054Readable.prototype.unpipe = function (dest) {
4055 var state = this._readableState;
4056
4057 // if we're not piping anywhere, then do nothing.
4058 if (state.pipesCount === 0) return this;
4059
4060 // just one destination. most common case.
4061 if (state.pipesCount === 1) {
4062 // passed in one, but it's not the right one.
4063 if (dest && dest !== state.pipes) return this;
4064
4065 if (!dest) dest = state.pipes;
4066
4067 // got a match.
4068 state.pipes = null;
4069 state.pipesCount = 0;
4070 state.flowing = false;
4071 if (dest) dest.emit('unpipe', this);
4072 return this;
4073 }
4074
4075 // slow case. multiple pipe destinations.
4076
4077 if (!dest) {
4078 // remove all.
4079 var dests = state.pipes;
4080 var len = state.pipesCount;
4081 state.pipes = null;
4082 state.pipesCount = 0;
4083 state.flowing = false;
4084
4085 for (var _i = 0; _i < len; _i++) {
4086 dests[_i].emit('unpipe', this);
4087 }return this;
4088 }
4089
4090 // try to find the right one.
4091 var i = indexOf(state.pipes, dest);
4092 if (i === -1) return this;
4093
4094 state.pipes.splice(i, 1);
4095 state.pipesCount -= 1;
4096 if (state.pipesCount === 1) state.pipes = state.pipes[0];
4097
4098 dest.emit('unpipe', this);
4099
4100 return this;
4101};
4102
4103// set up data events if they are asked for
4104// Ensure readable listeners eventually get something
4105Readable.prototype.on = function (ev, fn) {
4106 var res = EventEmitter.prototype.on.call(this, ev, fn);
4107
4108 if (ev === 'data') {
4109 // Start flowing on next tick if stream isn't explicitly paused
4110 if (this._readableState.flowing !== false) this.resume();
4111 } else if (ev === 'readable') {
4112 var state = this._readableState;
4113 if (!state.endEmitted && !state.readableListening) {
4114 state.readableListening = state.needReadable = true;
4115 state.emittedReadable = false;
4116 if (!state.reading) {
4117 nextTick(nReadingNextTick, this);
4118 } else if (state.length) {
4119 emitReadable(this);
4120 }
4121 }
4122 }
4123
4124 return res;
4125};
4126Readable.prototype.addListener = Readable.prototype.on;
4127
4128function nReadingNextTick(self) {
4129 debug('readable nexttick read 0');
4130 self.read(0);
4131}
4132
4133// pause() and resume() are remnants of the legacy readable stream API
4134// If the user uses them, then switch into old mode.
4135Readable.prototype.resume = function () {
4136 var state = this._readableState;
4137 if (!state.flowing) {
4138 debug('resume');
4139 state.flowing = true;
4140 resume(this, state);
4141 }
4142 return this;
4143};
4144
4145function resume(stream, state) {
4146 if (!state.resumeScheduled) {
4147 state.resumeScheduled = true;
4148 nextTick(resume_, stream, state);
4149 }
4150}
4151
4152function resume_(stream, state) {
4153 if (!state.reading) {
4154 debug('resume read 0');
4155 stream.read(0);
4156 }
4157
4158 state.resumeScheduled = false;
4159 state.awaitDrain = 0;
4160 stream.emit('resume');
4161 flow(stream);
4162 if (state.flowing && !state.reading) stream.read(0);
4163}
4164
4165Readable.prototype.pause = function () {
4166 debug('call pause flowing=%j', this._readableState.flowing);
4167 if (false !== this._readableState.flowing) {
4168 debug('pause');
4169 this._readableState.flowing = false;
4170 this.emit('pause');
4171 }
4172 return this;
4173};
4174
4175function flow(stream) {
4176 var state = stream._readableState;
4177 debug('flow', state.flowing);
4178 while (state.flowing && stream.read() !== null) {}
4179}
4180
4181// wrap an old-style stream as the async data source.
4182// This is *not* part of the readable stream interface.
4183// It is an ugly unfortunate mess of history.
4184Readable.prototype.wrap = function (stream) {
4185 var state = this._readableState;
4186 var paused = false;
4187
4188 var self = this;
4189 stream.on('end', function () {
4190 debug('wrapped end');
4191 if (state.decoder && !state.ended) {
4192 var chunk = state.decoder.end();
4193 if (chunk && chunk.length) self.push(chunk);
4194 }
4195
4196 self.push(null);
4197 });
4198
4199 stream.on('data', function (chunk) {
4200 debug('wrapped data');
4201 if (state.decoder) chunk = state.decoder.write(chunk);
4202
4203 // don't skip over falsy values in objectMode
4204 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
4205
4206 var ret = self.push(chunk);
4207 if (!ret) {
4208 paused = true;
4209 stream.pause();
4210 }
4211 });
4212
4213 // proxy all the other methods.
4214 // important when wrapping filters and duplexes.
4215 for (var i in stream) {
4216 if (this[i] === undefined && typeof stream[i] === 'function') {
4217 this[i] = function (method) {
4218 return function () {
4219 return stream[method].apply(stream, arguments);
4220 };
4221 }(i);
4222 }
4223 }
4224
4225 // proxy certain important events.
4226 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
4227 forEach(events, function (ev) {
4228 stream.on(ev, self.emit.bind(self, ev));
4229 });
4230
4231 // when we try to consume some more bytes, simply unpause the
4232 // underlying stream.
4233 self._read = function (n) {
4234 debug('wrapped _read', n);
4235 if (paused) {
4236 paused = false;
4237 stream.resume();
4238 }
4239 };
4240
4241 return self;
4242};
4243
4244// exposed for testing purposes only.
4245Readable._fromList = fromList;
4246
4247// Pluck off n bytes from an array of buffers.
4248// Length is the combined lengths of all the buffers in the list.
4249// This function is designed to be inlinable, so please take care when making
4250// changes to the function body.
4251function fromList(n, state) {
4252 // nothing buffered
4253 if (state.length === 0) return null;
4254
4255 var ret;
4256 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
4257 // read it all, truncate the list
4258 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
4259 state.buffer.clear();
4260 } else {
4261 // read part of list
4262 ret = fromListPartial(n, state.buffer, state.decoder);
4263 }
4264
4265 return ret;
4266}
4267
4268// Extracts only enough buffered data to satisfy the amount requested.
4269// This function is designed to be inlinable, so please take care when making
4270// changes to the function body.
4271function fromListPartial(n, list, hasStrings) {
4272 var ret;
4273 if (n < list.head.data.length) {
4274 // slice is the same for buffers and strings
4275 ret = list.head.data.slice(0, n);
4276 list.head.data = list.head.data.slice(n);
4277 } else if (n === list.head.data.length) {
4278 // first chunk is a perfect match
4279 ret = list.shift();
4280 } else {
4281 // result spans more than one buffer
4282 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
4283 }
4284 return ret;
4285}
4286
4287// Copies a specified amount of characters from the list of buffered data
4288// chunks.
4289// This function is designed to be inlinable, so please take care when making
4290// changes to the function body.
4291function copyFromBufferString(n, list) {
4292 var p = list.head;
4293 var c = 1;
4294 var ret = p.data;
4295 n -= ret.length;
4296 while (p = p.next) {
4297 var str = p.data;
4298 var nb = n > str.length ? str.length : n;
4299 if (nb === str.length) ret += str;else ret += str.slice(0, n);
4300 n -= nb;
4301 if (n === 0) {
4302 if (nb === str.length) {
4303 ++c;
4304 if (p.next) list.head = p.next;else list.head = list.tail = null;
4305 } else {
4306 list.head = p;
4307 p.data = str.slice(nb);
4308 }
4309 break;
4310 }
4311 ++c;
4312 }
4313 list.length -= c;
4314 return ret;
4315}
4316
4317// Copies a specified amount of bytes from the list of buffered data chunks.
4318// This function is designed to be inlinable, so please take care when making
4319// changes to the function body.
4320function copyFromBuffer(n, list) {
4321 var ret = Buffer$1.allocUnsafe(n);
4322 var p = list.head;
4323 var c = 1;
4324 p.data.copy(ret);
4325 n -= p.data.length;
4326 while (p = p.next) {
4327 var buf = p.data;
4328 var nb = n > buf.length ? buf.length : n;
4329 buf.copy(ret, ret.length - n, 0, nb);
4330 n -= nb;
4331 if (n === 0) {
4332 if (nb === buf.length) {
4333 ++c;
4334 if (p.next) list.head = p.next;else list.head = list.tail = null;
4335 } else {
4336 list.head = p;
4337 p.data = buf.slice(nb);
4338 }
4339 break;
4340 }
4341 ++c;
4342 }
4343 list.length -= c;
4344 return ret;
4345}
4346
4347function endReadable(stream) {
4348 var state = stream._readableState;
4349
4350 // If we get here before consuming all the bytes, then that is a
4351 // bug in node. Should never happen.
4352 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
4353
4354 if (!state.endEmitted) {
4355 state.ended = true;
4356 nextTick(endReadableNT, state, stream);
4357 }
4358}
4359
4360function endReadableNT(state, stream) {
4361 // Check that we didn't get one last unshift.
4362 if (!state.endEmitted && state.length === 0) {
4363 state.endEmitted = true;
4364 stream.readable = false;
4365 stream.emit('end');
4366 }
4367}
4368
4369function forEach(xs, f) {
4370 for (var i = 0, l = xs.length; i < l; i++) {
4371 f(xs[i], i);
4372 }
4373}
4374
4375function indexOf(xs, x) {
4376 for (var i = 0, l = xs.length; i < l; i++) {
4377 if (xs[i] === x) return i;
4378 }
4379 return -1;
4380}
4381
4382// A bit simpler than readable streams.
4383Writable.WritableState = WritableState;
4384inherits$1(Writable, EventEmitter);
4385
4386function nop() {}
4387
4388function WriteReq(chunk, encoding, cb) {
4389 this.chunk = chunk;
4390 this.encoding = encoding;
4391 this.callback = cb;
4392 this.next = null;
4393}
4394
4395function WritableState(options, stream) {
4396 Object.defineProperty(this, 'buffer', {
4397 get: deprecate(function () {
4398 return this.getBuffer();
4399 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
4400 });
4401 options = options || {};
4402
4403 // object stream flag to indicate whether or not this stream
4404 // contains buffers or objects.
4405 this.objectMode = !!options.objectMode;
4406
4407 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
4408
4409 // the point at which write() starts returning false
4410 // Note: 0 is a valid value, means that we always return false if
4411 // the entire buffer is not flushed immediately on write()
4412 var hwm = options.highWaterMark;
4413 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
4414 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
4415
4416 // cast to ints.
4417 this.highWaterMark = ~ ~this.highWaterMark;
4418
4419 this.needDrain = false;
4420 // at the start of calling end()
4421 this.ending = false;
4422 // when end() has been called, and returned
4423 this.ended = false;
4424 // when 'finish' is emitted
4425 this.finished = false;
4426
4427 // should we decode strings into buffers before passing to _write?
4428 // this is here so that some node-core streams can optimize string
4429 // handling at a lower level.
4430 var noDecode = options.decodeStrings === false;
4431 this.decodeStrings = !noDecode;
4432
4433 // Crypto is kind of old and crusty. Historically, its default string
4434 // encoding is 'binary' so we have to make this configurable.
4435 // Everything else in the universe uses 'utf8', though.
4436 this.defaultEncoding = options.defaultEncoding || 'utf8';
4437
4438 // not an actual buffer we keep track of, but a measurement
4439 // of how much we're waiting to get pushed to some underlying
4440 // socket or file.
4441 this.length = 0;
4442
4443 // a flag to see when we're in the middle of a write.
4444 this.writing = false;
4445
4446 // when true all writes will be buffered until .uncork() call
4447 this.corked = 0;
4448
4449 // a flag to be able to tell if the onwrite cb is called immediately,
4450 // or on a later tick. We set this to true at first, because any
4451 // actions that shouldn't happen until "later" should generally also
4452 // not happen before the first write call.
4453 this.sync = true;
4454
4455 // a flag to know if we're processing previously buffered items, which
4456 // may call the _write() callback in the same tick, so that we don't
4457 // end up in an overlapped onwrite situation.
4458 this.bufferProcessing = false;
4459
4460 // the callback that's passed to _write(chunk,cb)
4461 this.onwrite = function (er) {
4462 onwrite(stream, er);
4463 };
4464
4465 // the callback that the user supplies to write(chunk,encoding,cb)
4466 this.writecb = null;
4467
4468 // the amount that is being written when _write is called.
4469 this.writelen = 0;
4470
4471 this.bufferedRequest = null;
4472 this.lastBufferedRequest = null;
4473
4474 // number of pending user-supplied write callbacks
4475 // this must be 0 before 'finish' can be emitted
4476 this.pendingcb = 0;
4477
4478 // emit prefinish if the only thing we're waiting for is _write cbs
4479 // This is relevant for synchronous Transform streams
4480 this.prefinished = false;
4481
4482 // True if the error was already emitted and should not be thrown again
4483 this.errorEmitted = false;
4484
4485 // count buffered requests
4486 this.bufferedRequestCount = 0;
4487
4488 // allocate the first CorkedRequest, there is always
4489 // one allocated and free to use, and we maintain at most two
4490 this.corkedRequestsFree = new CorkedRequest(this);
4491}
4492
4493WritableState.prototype.getBuffer = function writableStateGetBuffer() {
4494 var current = this.bufferedRequest;
4495 var out = [];
4496 while (current) {
4497 out.push(current);
4498 current = current.next;
4499 }
4500 return out;
4501};
4502function Writable(options) {
4503
4504 // Writable ctor is applied to Duplexes, though they're not
4505 // instanceof Writable, they're instanceof Readable.
4506 if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);
4507
4508 this._writableState = new WritableState(options, this);
4509
4510 // legacy.
4511 this.writable = true;
4512
4513 if (options) {
4514 if (typeof options.write === 'function') this._write = options.write;
4515
4516 if (typeof options.writev === 'function') this._writev = options.writev;
4517 }
4518
4519 EventEmitter.call(this);
4520}
4521
4522// Otherwise people can pipe Writable streams, which is just wrong.
4523Writable.prototype.pipe = function () {
4524 this.emit('error', new Error('Cannot pipe, not readable'));
4525};
4526
4527function writeAfterEnd(stream, cb) {
4528 var er = new Error('write after end');
4529 // TODO: defer error events consistently everywhere, not just the cb
4530 stream.emit('error', er);
4531 nextTick(cb, er);
4532}
4533
4534// If we get something that is not a buffer, string, null, or undefined,
4535// and we're not in objectMode, then that's an error.
4536// Otherwise stream chunks are all considered to be of length=1, and the
4537// watermarks determine how many objects to keep in the buffer, rather than
4538// how many bytes or characters.
4539function validChunk(stream, state, chunk, cb) {
4540 var valid = true;
4541 var er = false;
4542 // Always throw error if a null is written
4543 // if we are not in object mode then throw
4544 // if it is not a buffer, string, or undefined.
4545 if (chunk === null) {
4546 er = new TypeError('May not write null values to stream');
4547 } else if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
4548 er = new TypeError('Invalid non-string/buffer chunk');
4549 }
4550 if (er) {
4551 stream.emit('error', er);
4552 nextTick(cb, er);
4553 valid = false;
4554 }
4555 return valid;
4556}
4557
4558Writable.prototype.write = function (chunk, encoding, cb) {
4559 var state = this._writableState;
4560 var ret = false;
4561
4562 if (typeof encoding === 'function') {
4563 cb = encoding;
4564 encoding = null;
4565 }
4566
4567 if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
4568
4569 if (typeof cb !== 'function') cb = nop;
4570
4571 if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {
4572 state.pendingcb++;
4573 ret = writeOrBuffer(this, state, chunk, encoding, cb);
4574 }
4575
4576 return ret;
4577};
4578
4579Writable.prototype.cork = function () {
4580 var state = this._writableState;
4581
4582 state.corked++;
4583};
4584
4585Writable.prototype.uncork = function () {
4586 var state = this._writableState;
4587
4588 if (state.corked) {
4589 state.corked--;
4590
4591 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
4592 }
4593};
4594
4595Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
4596 // node::ParseEncoding() requires lower case.
4597 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
4598 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
4599 this._writableState.defaultEncoding = encoding;
4600 return this;
4601};
4602
4603function decodeChunk(state, chunk, encoding) {
4604 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
4605 chunk = Buffer$1.from(chunk, encoding);
4606 }
4607 return chunk;
4608}
4609
4610// if we're already writing something, then just put this
4611// in the queue, and wait our turn. Otherwise, call _write
4612// If we return false, then we need a drain event, so set that flag.
4613function writeOrBuffer(stream, state, chunk, encoding, cb) {
4614 chunk = decodeChunk(state, chunk, encoding);
4615
4616 if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';
4617 var len = state.objectMode ? 1 : chunk.length;
4618
4619 state.length += len;
4620
4621 var ret = state.length < state.highWaterMark;
4622 // we must ensure that previous needDrain will not be reset to false.
4623 if (!ret) state.needDrain = true;
4624
4625 if (state.writing || state.corked) {
4626 var last = state.lastBufferedRequest;
4627 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
4628 if (last) {
4629 last.next = state.lastBufferedRequest;
4630 } else {
4631 state.bufferedRequest = state.lastBufferedRequest;
4632 }
4633 state.bufferedRequestCount += 1;
4634 } else {
4635 doWrite(stream, state, false, len, chunk, encoding, cb);
4636 }
4637
4638 return ret;
4639}
4640
4641function doWrite(stream, state, writev, len, chunk, encoding, cb) {
4642 state.writelen = len;
4643 state.writecb = cb;
4644 state.writing = true;
4645 state.sync = true;
4646 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
4647 state.sync = false;
4648}
4649
4650function onwriteError(stream, state, sync, er, cb) {
4651 --state.pendingcb;
4652 if (sync) nextTick(cb, er);else cb(er);
4653
4654 stream._writableState.errorEmitted = true;
4655 stream.emit('error', er);
4656}
4657
4658function onwriteStateUpdate(state) {
4659 state.writing = false;
4660 state.writecb = null;
4661 state.length -= state.writelen;
4662 state.writelen = 0;
4663}
4664
4665function onwrite(stream, er) {
4666 var state = stream._writableState;
4667 var sync = state.sync;
4668 var cb = state.writecb;
4669
4670 onwriteStateUpdate(state);
4671
4672 if (er) onwriteError(stream, state, sync, er, cb);else {
4673 // Check if we're actually ready to finish, but don't emit yet
4674 var finished = needFinish(state);
4675
4676 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
4677 clearBuffer(stream, state);
4678 }
4679
4680 if (sync) {
4681 /*<replacement>*/
4682 nextTick(afterWrite, stream, state, finished, cb);
4683 /*</replacement>*/
4684 } else {
4685 afterWrite(stream, state, finished, cb);
4686 }
4687 }
4688}
4689
4690function afterWrite(stream, state, finished, cb) {
4691 if (!finished) onwriteDrain(stream, state);
4692 state.pendingcb--;
4693 cb();
4694 finishMaybe(stream, state);
4695}
4696
4697// Must force callback to be called on nextTick, so that we don't
4698// emit 'drain' before the write() consumer gets the 'false' return
4699// value, and has a chance to attach a 'drain' listener.
4700function onwriteDrain(stream, state) {
4701 if (state.length === 0 && state.needDrain) {
4702 state.needDrain = false;
4703 stream.emit('drain');
4704 }
4705}
4706
4707// if there's something in the buffer waiting, then process it
4708function clearBuffer(stream, state) {
4709 state.bufferProcessing = true;
4710 var entry = state.bufferedRequest;
4711
4712 if (stream._writev && entry && entry.next) {
4713 // Fast case, write everything using _writev()
4714 var l = state.bufferedRequestCount;
4715 var buffer = new Array(l);
4716 var holder = state.corkedRequestsFree;
4717 holder.entry = entry;
4718
4719 var count = 0;
4720 while (entry) {
4721 buffer[count] = entry;
4722 entry = entry.next;
4723 count += 1;
4724 }
4725
4726 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
4727
4728 // doWrite is almost always async, defer these to save a bit of time
4729 // as the hot path ends with doWrite
4730 state.pendingcb++;
4731 state.lastBufferedRequest = null;
4732 if (holder.next) {
4733 state.corkedRequestsFree = holder.next;
4734 holder.next = null;
4735 } else {
4736 state.corkedRequestsFree = new CorkedRequest(state);
4737 }
4738 } else {
4739 // Slow case, write chunks one-by-one
4740 while (entry) {
4741 var chunk = entry.chunk;
4742 var encoding = entry.encoding;
4743 var cb = entry.callback;
4744 var len = state.objectMode ? 1 : chunk.length;
4745
4746 doWrite(stream, state, false, len, chunk, encoding, cb);
4747 entry = entry.next;
4748 // if we didn't call the onwrite immediately, then
4749 // it means that we need to wait until it does.
4750 // also, that means that the chunk and cb are currently
4751 // being processed, so move the buffer counter past them.
4752 if (state.writing) {
4753 break;
4754 }
4755 }
4756
4757 if (entry === null) state.lastBufferedRequest = null;
4758 }
4759
4760 state.bufferedRequestCount = 0;
4761 state.bufferedRequest = entry;
4762 state.bufferProcessing = false;
4763}
4764
4765Writable.prototype._write = function (chunk, encoding, cb) {
4766 cb(new Error('not implemented'));
4767};
4768
4769Writable.prototype._writev = null;
4770
4771Writable.prototype.end = function (chunk, encoding, cb) {
4772 var state = this._writableState;
4773
4774 if (typeof chunk === 'function') {
4775 cb = chunk;
4776 chunk = null;
4777 encoding = null;
4778 } else if (typeof encoding === 'function') {
4779 cb = encoding;
4780 encoding = null;
4781 }
4782
4783 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
4784
4785 // .end() fully uncorks
4786 if (state.corked) {
4787 state.corked = 1;
4788 this.uncork();
4789 }
4790
4791 // ignore unnecessary end() calls.
4792 if (!state.ending && !state.finished) endWritable(this, state, cb);
4793};
4794
4795function needFinish(state) {
4796 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
4797}
4798
4799function prefinish(stream, state) {
4800 if (!state.prefinished) {
4801 state.prefinished = true;
4802 stream.emit('prefinish');
4803 }
4804}
4805
4806function finishMaybe(stream, state) {
4807 var need = needFinish(state);
4808 if (need) {
4809 if (state.pendingcb === 0) {
4810 prefinish(stream, state);
4811 state.finished = true;
4812 stream.emit('finish');
4813 } else {
4814 prefinish(stream, state);
4815 }
4816 }
4817 return need;
4818}
4819
4820function endWritable(stream, state, cb) {
4821 state.ending = true;
4822 finishMaybe(stream, state);
4823 if (cb) {
4824 if (state.finished) nextTick(cb);else stream.once('finish', cb);
4825 }
4826 state.ended = true;
4827 stream.writable = false;
4828}
4829
4830// It seems a linked list but it is not
4831// there will be only 2 of these for each stream
4832function CorkedRequest(state) {
4833 var _this = this;
4834
4835 this.next = null;
4836 this.entry = null;
4837
4838 this.finish = function (err) {
4839 var entry = _this.entry;
4840 _this.entry = null;
4841 while (entry) {
4842 var cb = entry.callback;
4843 state.pendingcb--;
4844 cb(err);
4845 entry = entry.next;
4846 }
4847 if (state.corkedRequestsFree) {
4848 state.corkedRequestsFree.next = _this;
4849 } else {
4850 state.corkedRequestsFree = _this;
4851 }
4852 };
4853}
4854
4855inherits$1(Duplex, Readable);
4856
4857var keys = Object.keys(Writable.prototype);
4858for (var v = 0; v < keys.length; v++) {
4859 var method = keys[v];
4860 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
4861}
4862function Duplex(options) {
4863 if (!(this instanceof Duplex)) return new Duplex(options);
4864
4865 Readable.call(this, options);
4866 Writable.call(this, options);
4867
4868 if (options && options.readable === false) this.readable = false;
4869
4870 if (options && options.writable === false) this.writable = false;
4871
4872 this.allowHalfOpen = true;
4873 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
4874
4875 this.once('end', onend);
4876}
4877
4878// the no-half-open enforcer
4879function onend() {
4880 // if we allow half-open state, or if the writable side ended,
4881 // then we're ok.
4882 if (this.allowHalfOpen || this._writableState.ended) return;
4883
4884 // no more data can be written.
4885 // But allow more writes to happen in this tick.
4886 nextTick(onEndNT, this);
4887}
4888
4889function onEndNT(self) {
4890 self.end();
4891}
4892
4893// a transform stream is a readable/writable stream where you do
4894inherits$1(Transform, Duplex);
4895
4896function TransformState(stream) {
4897 this.afterTransform = function (er, data) {
4898 return afterTransform(stream, er, data);
4899 };
4900
4901 this.needTransform = false;
4902 this.transforming = false;
4903 this.writecb = null;
4904 this.writechunk = null;
4905 this.writeencoding = null;
4906}
4907
4908function afterTransform(stream, er, data) {
4909 var ts = stream._transformState;
4910 ts.transforming = false;
4911
4912 var cb = ts.writecb;
4913
4914 if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
4915
4916 ts.writechunk = null;
4917 ts.writecb = null;
4918
4919 if (data !== null && data !== undefined) stream.push(data);
4920
4921 cb(er);
4922
4923 var rs = stream._readableState;
4924 rs.reading = false;
4925 if (rs.needReadable || rs.length < rs.highWaterMark) {
4926 stream._read(rs.highWaterMark);
4927 }
4928}
4929function Transform(options) {
4930 if (!(this instanceof Transform)) return new Transform(options);
4931
4932 Duplex.call(this, options);
4933
4934 this._transformState = new TransformState(this);
4935
4936 // when the writable side finishes, then flush out anything remaining.
4937 var stream = this;
4938
4939 // start out asking for a readable event once data is transformed.
4940 this._readableState.needReadable = true;
4941
4942 // we have implemented the _read method, and done the other things
4943 // that Readable wants before the first _read call, so unset the
4944 // sync guard flag.
4945 this._readableState.sync = false;
4946
4947 if (options) {
4948 if (typeof options.transform === 'function') this._transform = options.transform;
4949
4950 if (typeof options.flush === 'function') this._flush = options.flush;
4951 }
4952
4953 this.once('prefinish', function () {
4954 if (typeof this._flush === 'function') this._flush(function (er) {
4955 done(stream, er);
4956 });else done(stream);
4957 });
4958}
4959
4960Transform.prototype.push = function (chunk, encoding) {
4961 this._transformState.needTransform = false;
4962 return Duplex.prototype.push.call(this, chunk, encoding);
4963};
4964
4965// This is the part where you do stuff!
4966// override this function in implementation classes.
4967// 'chunk' is an input chunk.
4968//
4969// Call `push(newChunk)` to pass along transformed output
4970// to the readable side. You may call 'push' zero or more times.
4971//
4972// Call `cb(err)` when you are done with this chunk. If you pass
4973// an error, then that'll put the hurt on the whole operation. If you
4974// never call cb(), then you'll never get another chunk.
4975Transform.prototype._transform = function (chunk, encoding, cb) {
4976 throw new Error('Not implemented');
4977};
4978
4979Transform.prototype._write = function (chunk, encoding, cb) {
4980 var ts = this._transformState;
4981 ts.writecb = cb;
4982 ts.writechunk = chunk;
4983 ts.writeencoding = encoding;
4984 if (!ts.transforming) {
4985 var rs = this._readableState;
4986 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
4987 }
4988};
4989
4990// Doesn't matter what the args are here.
4991// _transform does all the work.
4992// That we got here means that the readable side wants more data.
4993Transform.prototype._read = function (n) {
4994 var ts = this._transformState;
4995
4996 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
4997 ts.transforming = true;
4998 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
4999 } else {
5000 // mark that we need a transform, so that any data that comes in
5001 // will get processed, now that we've asked for it.
5002 ts.needTransform = true;
5003 }
5004};
5005
5006function done(stream, er) {
5007 if (er) return stream.emit('error', er);
5008
5009 // if there's nothing in the write buffer, then that means
5010 // that nothing more will ever be provided
5011 var ws = stream._writableState;
5012 var ts = stream._transformState;
5013
5014 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
5015
5016 if (ts.transforming) throw new Error('Calling transform done when still transforming');
5017
5018 return stream.push(null);
5019}
5020
5021inherits$1(PassThrough, Transform);
5022function PassThrough(options) {
5023 if (!(this instanceof PassThrough)) return new PassThrough(options);
5024
5025 Transform.call(this, options);
5026}
5027
5028PassThrough.prototype._transform = function (chunk, encoding, cb) {
5029 cb(null, chunk);
5030};
5031
5032inherits$1(Stream, EventEmitter);
5033Stream.Readable = Readable;
5034Stream.Writable = Writable;
5035Stream.Duplex = Duplex;
5036Stream.Transform = Transform;
5037Stream.PassThrough = PassThrough;
5038
5039// Backwards-compat with node 0.4.x
5040Stream.Stream = Stream;
5041
5042// old-style streams. Note that the pipe method (the only relevant
5043// part of this class) is overridden in the Readable class.
5044
5045function Stream() {
5046 EventEmitter.call(this);
5047}
5048
5049Stream.prototype.pipe = function(dest, options) {
5050 var source = this;
5051
5052 function ondata(chunk) {
5053 if (dest.writable) {
5054 if (false === dest.write(chunk) && source.pause) {
5055 source.pause();
5056 }
5057 }
5058 }
5059
5060 source.on('data', ondata);
5061
5062 function ondrain() {
5063 if (source.readable && source.resume) {
5064 source.resume();
5065 }
5066 }
5067
5068 dest.on('drain', ondrain);
5069
5070 // If the 'end' option is not supplied, dest.end() will be called when
5071 // source gets the 'end' or 'close' events. Only dest.end() once.
5072 if (!dest._isStdio && (!options || options.end !== false)) {
5073 source.on('end', onend);
5074 source.on('close', onclose);
5075 }
5076
5077 var didOnEnd = false;
5078 function onend() {
5079 if (didOnEnd) return;
5080 didOnEnd = true;
5081
5082 dest.end();
5083 }
5084
5085
5086 function onclose() {
5087 if (didOnEnd) return;
5088 didOnEnd = true;
5089
5090 if (typeof dest.destroy === 'function') dest.destroy();
5091 }
5092
5093 // don't leave dangling pipes when there are errors.
5094 function onerror(er) {
5095 cleanup();
5096 if (EventEmitter.listenerCount(this, 'error') === 0) {
5097 throw er; // Unhandled stream error in pipe.
5098 }
5099 }
5100
5101 source.on('error', onerror);
5102 dest.on('error', onerror);
5103
5104 // remove all the event listeners that were added.
5105 function cleanup() {
5106 source.removeListener('data', ondata);
5107 dest.removeListener('drain', ondrain);
5108
5109 source.removeListener('end', onend);
5110 source.removeListener('close', onclose);
5111
5112 source.removeListener('error', onerror);
5113 dest.removeListener('error', onerror);
5114
5115 source.removeListener('end', cleanup);
5116 source.removeListener('close', cleanup);
5117
5118 dest.removeListener('close', cleanup);
5119 }
5120
5121 source.on('end', cleanup);
5122 source.on('close', cleanup);
5123
5124 dest.on('close', cleanup);
5125
5126 dest.emit('pipe', source);
5127
5128 // Allow for unix-like usage: A.pipe(B).pipe(C)
5129 return dest;
5130};
5131
5132var hasFetch = isFunction$1(global$1.fetch) && isFunction$1(global$1.ReadableStream);
5133
5134var _blobConstructor;
5135function blobConstructor() {
5136 if (typeof _blobConstructor !== 'undefined') {
5137 return _blobConstructor;
5138 }
5139 try {
5140 new global$1.Blob([new ArrayBuffer(1)]);
5141 _blobConstructor = true;
5142 } catch (e) {
5143 _blobConstructor = false;
5144 }
5145 return _blobConstructor
5146}
5147var xhr;
5148
5149function checkTypeSupport(type) {
5150 if (!xhr) {
5151 xhr = new global$1.XMLHttpRequest();
5152 // If location.host is empty, e.g. if this page/worker was loaded
5153 // from a Blob, then use example.com to avoid an error
5154 xhr.open('GET', global$1.location.host ? '/' : 'https://example.com');
5155 }
5156 try {
5157 xhr.responseType = type;
5158 return xhr.responseType === type
5159 } catch (e) {
5160 return false
5161 }
5162
5163}
5164
5165// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'.
5166// Safari 7.1 appears to have fixed this bug.
5167var haveArrayBuffer = typeof global$1.ArrayBuffer !== 'undefined';
5168var haveSlice = haveArrayBuffer && isFunction$1(global$1.ArrayBuffer.prototype.slice);
5169
5170var arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer');
5171 // These next two tests unavoidably show warnings in Chrome. Since fetch will always
5172 // be used if it's available, just return false for these to avoid the warnings.
5173var msstream = !hasFetch && haveSlice && checkTypeSupport('ms-stream');
5174var mozchunkedarraybuffer = !hasFetch && haveArrayBuffer &&
5175 checkTypeSupport('moz-chunked-arraybuffer');
5176var overrideMimeType = isFunction$1(xhr.overrideMimeType);
5177var vbArray = isFunction$1(global$1.VBArray);
5178
5179function isFunction$1(value) {
5180 return typeof value === 'function'
5181}
5182
5183xhr = null; // Help gc
5184
5185var rStates = {
5186 UNSENT: 0,
5187 OPENED: 1,
5188 HEADERS_RECEIVED: 2,
5189 LOADING: 3,
5190 DONE: 4
5191};
5192function IncomingMessage(xhr, response, mode) {
5193 var self = this;
5194 Readable.call(self);
5195
5196 self._mode = mode;
5197 self.headers = {};
5198 self.rawHeaders = [];
5199 self.trailers = {};
5200 self.rawTrailers = [];
5201
5202 // Fake the 'close' event, but only once 'end' fires
5203 self.on('end', function() {
5204 // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
5205 nextTick(function() {
5206 self.emit('close');
5207 });
5208 });
5209 var read;
5210 if (mode === 'fetch') {
5211 self._fetchResponse = response;
5212
5213 self.url = response.url;
5214 self.statusCode = response.status;
5215 self.statusMessage = response.statusText;
5216 // backwards compatible version of for (<item> of <iterable>):
5217 // for (var <item>,_i,_it = <iterable>[Symbol.iterator](); <item> = (_i = _it.next()).value,!_i.done;)
5218 for (var header, _i, _it = response.headers[Symbol.iterator](); header = (_i = _it.next()).value, !_i.done;) {
5219 self.headers[header[0].toLowerCase()] = header[1];
5220 self.rawHeaders.push(header[0], header[1]);
5221 }
5222
5223 // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed
5224 var reader = response.body.getReader();
5225
5226 read = function () {
5227 reader.read().then(function(result) {
5228 if (self._destroyed)
5229 return
5230 if (result.done) {
5231 self.push(null);
5232 return
5233 }
5234 self.push(new Buffer$1(result.value));
5235 read();
5236 });
5237 };
5238 read();
5239
5240 } else {
5241 self._xhr = xhr;
5242 self._pos = 0;
5243
5244 self.url = xhr.responseURL;
5245 self.statusCode = xhr.status;
5246 self.statusMessage = xhr.statusText;
5247 var headers = xhr.getAllResponseHeaders().split(/\r?\n/);
5248 headers.forEach(function(header) {
5249 var matches = header.match(/^([^:]+):\s*(.*)/);
5250 if (matches) {
5251 var key = matches[1].toLowerCase();
5252 if (key === 'set-cookie') {
5253 if (self.headers[key] === undefined) {
5254 self.headers[key] = [];
5255 }
5256 self.headers[key].push(matches[2]);
5257 } else if (self.headers[key] !== undefined) {
5258 self.headers[key] += ', ' + matches[2];
5259 } else {
5260 self.headers[key] = matches[2];
5261 }
5262 self.rawHeaders.push(matches[1], matches[2]);
5263 }
5264 });
5265
5266 self._charset = 'x-user-defined';
5267 if (!overrideMimeType) {
5268 var mimeType = self.rawHeaders['mime-type'];
5269 if (mimeType) {
5270 var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/);
5271 if (charsetMatch) {
5272 self._charset = charsetMatch[1].toLowerCase();
5273 }
5274 }
5275 if (!self._charset)
5276 self._charset = 'utf-8'; // best guess
5277 }
5278 }
5279}
5280
5281inherits$1(IncomingMessage, Readable);
5282
5283IncomingMessage.prototype._read = function() {};
5284
5285IncomingMessage.prototype._onXHRProgress = function() {
5286 var self = this;
5287
5288 var xhr = self._xhr;
5289
5290 var response = null;
5291 switch (self._mode) {
5292 case 'text:vbarray': // For IE9
5293 if (xhr.readyState !== rStates.DONE)
5294 break
5295 try {
5296 // This fails in IE8
5297 response = new global$1.VBArray(xhr.responseBody).toArray();
5298 } catch (e) {
5299 // pass
5300 }
5301 if (response !== null) {
5302 self.push(new Buffer$1(response));
5303 break
5304 }
5305 // Falls through in IE8
5306 case 'text':
5307 try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4
5308 response = xhr.responseText;
5309 } catch (e) {
5310 self._mode = 'text:vbarray';
5311 break
5312 }
5313 if (response.length > self._pos) {
5314 var newData = response.substr(self._pos);
5315 if (self._charset === 'x-user-defined') {
5316 var buffer = new Buffer$1(newData.length);
5317 for (var i = 0; i < newData.length; i++)
5318 buffer[i] = newData.charCodeAt(i) & 0xff;
5319
5320 self.push(buffer);
5321 } else {
5322 self.push(newData, self._charset);
5323 }
5324 self._pos = response.length;
5325 }
5326 break
5327 case 'arraybuffer':
5328 if (xhr.readyState !== rStates.DONE || !xhr.response)
5329 break
5330 response = xhr.response;
5331 self.push(new Buffer$1(new Uint8Array(response)));
5332 break
5333 case 'moz-chunked-arraybuffer': // take whole
5334 response = xhr.response;
5335 if (xhr.readyState !== rStates.LOADING || !response)
5336 break
5337 self.push(new Buffer$1(new Uint8Array(response)));
5338 break
5339 case 'ms-stream':
5340 response = xhr.response;
5341 if (xhr.readyState !== rStates.LOADING)
5342 break
5343 var reader = new global$1.MSStreamReader();
5344 reader.onprogress = function() {
5345 if (reader.result.byteLength > self._pos) {
5346 self.push(new Buffer$1(new Uint8Array(reader.result.slice(self._pos))));
5347 self._pos = reader.result.byteLength;
5348 }
5349 };
5350 reader.onload = function() {
5351 self.push(null);
5352 };
5353 // reader.onerror = ??? // TODO: this
5354 reader.readAsArrayBuffer(response);
5355 break
5356 }
5357
5358 // The ms-stream case handles end separately in reader.onload()
5359 if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
5360 self.push(null);
5361 }
5362};
5363
5364// from https://github.com/jhiesey/to-arraybuffer/blob/6502d9850e70ba7935a7df4ad86b358fc216f9f0/index.js
5365function toArrayBuffer (buf) {
5366 // If the buffer is backed by a Uint8Array, a faster version will work
5367 if (buf instanceof Uint8Array) {
5368 // If the buffer isn't a subarray, return the underlying ArrayBuffer
5369 if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
5370 return buf.buffer
5371 } else if (typeof buf.buffer.slice === 'function') {
5372 // Otherwise we need to get a proper copy
5373 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
5374 }
5375 }
5376
5377 if (isBuffer(buf)) {
5378 // This is the slow version that will work with any Buffer
5379 // implementation (even in old browsers)
5380 var arrayCopy = new Uint8Array(buf.length);
5381 var len = buf.length;
5382 for (var i = 0; i < len; i++) {
5383 arrayCopy[i] = buf[i];
5384 }
5385 return arrayCopy.buffer
5386 } else {
5387 throw new Error('Argument must be a Buffer')
5388 }
5389}
5390
5391function decideMode(preferBinary, useFetch) {
5392 if (hasFetch && useFetch) {
5393 return 'fetch'
5394 } else if (mozchunkedarraybuffer) {
5395 return 'moz-chunked-arraybuffer'
5396 } else if (msstream) {
5397 return 'ms-stream'
5398 } else if (arraybuffer && preferBinary) {
5399 return 'arraybuffer'
5400 } else if (vbArray && preferBinary) {
5401 return 'text:vbarray'
5402 } else {
5403 return 'text'
5404 }
5405}
5406
5407function ClientRequest(opts) {
5408 var self = this;
5409 Writable.call(self);
5410
5411 self._opts = opts;
5412 self._body = [];
5413 self._headers = {};
5414 if (opts.auth)
5415 self.setHeader('Authorization', 'Basic ' + new Buffer$1(opts.auth).toString('base64'));
5416 Object.keys(opts.headers).forEach(function(name) {
5417 self.setHeader(name, opts.headers[name]);
5418 });
5419
5420 var preferBinary;
5421 var useFetch = true;
5422 if (opts.mode === 'disable-fetch') {
5423 // If the use of XHR should be preferred and includes preserving the 'content-type' header
5424 useFetch = false;
5425 preferBinary = true;
5426 } else if (opts.mode === 'prefer-streaming') {
5427 // If streaming is a high priority but binary compatibility and
5428 // the accuracy of the 'content-type' header aren't
5429 preferBinary = false;
5430 } else if (opts.mode === 'allow-wrong-content-type') {
5431 // If streaming is more important than preserving the 'content-type' header
5432 preferBinary = !overrideMimeType;
5433 } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
5434 // Use binary if text streaming may corrupt data or the content-type header, or for speed
5435 preferBinary = true;
5436 } else {
5437 throw new Error('Invalid value for opts.mode')
5438 }
5439 self._mode = decideMode(preferBinary, useFetch);
5440
5441 self.on('finish', function() {
5442 self._onFinish();
5443 });
5444}
5445
5446inherits$1(ClientRequest, Writable);
5447// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
5448var unsafeHeaders = [
5449 'accept-charset',
5450 'accept-encoding',
5451 'access-control-request-headers',
5452 'access-control-request-method',
5453 'connection',
5454 'content-length',
5455 'cookie',
5456 'cookie2',
5457 'date',
5458 'dnt',
5459 'expect',
5460 'host',
5461 'keep-alive',
5462 'origin',
5463 'referer',
5464 'te',
5465 'trailer',
5466 'transfer-encoding',
5467 'upgrade',
5468 'user-agent',
5469 'via'
5470];
5471ClientRequest.prototype.setHeader = function(name, value) {
5472 var self = this;
5473 var lowerName = name.toLowerCase();
5474 // This check is not necessary, but it prevents warnings from browsers about setting unsafe
5475 // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
5476 // http-browserify did it, so I will too.
5477 if (unsafeHeaders.indexOf(lowerName) !== -1)
5478 return
5479
5480 self._headers[lowerName] = {
5481 name: name,
5482 value: value
5483 };
5484};
5485
5486ClientRequest.prototype.getHeader = function(name) {
5487 var self = this;
5488 return self._headers[name.toLowerCase()].value
5489};
5490
5491ClientRequest.prototype.removeHeader = function(name) {
5492 var self = this;
5493 delete self._headers[name.toLowerCase()];
5494};
5495
5496ClientRequest.prototype._onFinish = function() {
5497 var self = this;
5498
5499 if (self._destroyed)
5500 return
5501 var opts = self._opts;
5502
5503 var headersObj = self._headers;
5504 var body;
5505 if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') {
5506 if (blobConstructor()) {
5507 body = new global$1.Blob(self._body.map(function(buffer) {
5508 return toArrayBuffer(buffer)
5509 }), {
5510 type: (headersObj['content-type'] || {}).value || ''
5511 });
5512 } else {
5513 // get utf8 string
5514 body = Buffer$1.concat(self._body).toString();
5515 }
5516 }
5517
5518 if (self._mode === 'fetch') {
5519 var headers = Object.keys(headersObj).map(function(name) {
5520 return [headersObj[name].name, headersObj[name].value]
5521 });
5522
5523 global$1.fetch(self._opts.url, {
5524 method: self._opts.method,
5525 headers: headers,
5526 body: body,
5527 mode: 'cors',
5528 credentials: opts.withCredentials ? 'include' : 'same-origin'
5529 }).then(function(response) {
5530 self._fetchResponse = response;
5531 self._connect();
5532 }, function(reason) {
5533 self.emit('error', reason);
5534 });
5535 } else {
5536 var xhr = self._xhr = new global$1.XMLHttpRequest();
5537 try {
5538 xhr.open(self._opts.method, self._opts.url, true);
5539 } catch (err) {
5540 nextTick(function() {
5541 self.emit('error', err);
5542 });
5543 return
5544 }
5545
5546 // Can't set responseType on really old browsers
5547 if ('responseType' in xhr)
5548 xhr.responseType = self._mode.split(':')[0];
5549
5550 if ('withCredentials' in xhr)
5551 xhr.withCredentials = !!opts.withCredentials;
5552
5553 if (self._mode === 'text' && 'overrideMimeType' in xhr)
5554 xhr.overrideMimeType('text/plain; charset=x-user-defined');
5555
5556 Object.keys(headersObj).forEach(function(name) {
5557 xhr.setRequestHeader(headersObj[name].name, headersObj[name].value);
5558 });
5559
5560 self._response = null;
5561 xhr.onreadystatechange = function() {
5562 switch (xhr.readyState) {
5563 case rStates.LOADING:
5564 case rStates.DONE:
5565 self._onXHRProgress();
5566 break
5567 }
5568 };
5569 // Necessary for streaming in Firefox, since xhr.response is ONLY defined
5570 // in onprogress, not in onreadystatechange with xhr.readyState = 3
5571 if (self._mode === 'moz-chunked-arraybuffer') {
5572 xhr.onprogress = function() {
5573 self._onXHRProgress();
5574 };
5575 }
5576
5577 xhr.onerror = function() {
5578 if (self._destroyed)
5579 return
5580 self.emit('error', new Error('XHR error'));
5581 };
5582
5583 try {
5584 xhr.send(body);
5585 } catch (err) {
5586 nextTick(function() {
5587 self.emit('error', err);
5588 });
5589 return
5590 }
5591 }
5592};
5593
5594/**
5595 * Checks if xhr.status is readable and non-zero, indicating no error.
5596 * Even though the spec says it should be available in readyState 3,
5597 * accessing it throws an exception in IE8
5598 */
5599function statusValid(xhr) {
5600 try {
5601 var status = xhr.status;
5602 return (status !== null && status !== 0)
5603 } catch (e) {
5604 return false
5605 }
5606}
5607
5608ClientRequest.prototype._onXHRProgress = function() {
5609 var self = this;
5610
5611 if (!statusValid(self._xhr) || self._destroyed)
5612 return
5613
5614 if (!self._response)
5615 self._connect();
5616
5617 self._response._onXHRProgress();
5618};
5619
5620ClientRequest.prototype._connect = function() {
5621 var self = this;
5622
5623 if (self._destroyed)
5624 return
5625
5626 self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode);
5627 self.emit('response', self._response);
5628};
5629
5630ClientRequest.prototype._write = function(chunk, encoding, cb) {
5631 var self = this;
5632
5633 self._body.push(chunk);
5634 cb();
5635};
5636
5637ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function() {
5638 var self = this;
5639 self._destroyed = true;
5640 if (self._response)
5641 self._response._destroyed = true;
5642 if (self._xhr)
5643 self._xhr.abort();
5644 // Currently, there isn't a way to truly abort a fetch.
5645 // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27
5646};
5647
5648ClientRequest.prototype.end = function(data, encoding, cb) {
5649 var self = this;
5650 if (typeof data === 'function') {
5651 cb = data;
5652 data = undefined;
5653 }
5654
5655 Writable.prototype.end.call(self, data, encoding, cb);
5656};
5657
5658ClientRequest.prototype.flushHeaders = function() {};
5659ClientRequest.prototype.setTimeout = function() {};
5660ClientRequest.prototype.setNoDelay = function() {};
5661ClientRequest.prototype.setSocketKeepAlive = function() {};
5662
5663/*! https://mths.be/punycode v1.4.1 by @mathias */
5664
5665
5666/** Highest positive signed 32-bit float value */
5667var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
5668
5669/** Bootstring parameters */
5670var base = 36;
5671var tMin = 1;
5672var tMax = 26;
5673var skew = 38;
5674var damp = 700;
5675var initialBias = 72;
5676var initialN = 128; // 0x80
5677var delimiter = '-'; // '\x2D'
5678
5679/** Regular expressions */
5680var regexPunycode = /^xn--/;
5681var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars
5682var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
5683
5684/** Error messages */
5685var errors = {
5686 'overflow': 'Overflow: input needs wider integers to process',
5687 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
5688 'invalid-input': 'Invalid input'
5689};
5690
5691/** Convenience shortcuts */
5692var baseMinusTMin = base - tMin;
5693var floor = Math.floor;
5694var stringFromCharCode = String.fromCharCode;
5695
5696/*--------------------------------------------------------------------------*/
5697
5698/**
5699 * A generic error utility function.
5700 * @private
5701 * @param {String} type The error type.
5702 * @returns {Error} Throws a `RangeError` with the applicable error message.
5703 */
5704function error(type) {
5705 throw new RangeError(errors[type]);
5706}
5707
5708/**
5709 * A generic `Array#map` utility function.
5710 * @private
5711 * @param {Array} array The array to iterate over.
5712 * @param {Function} callback The function that gets called for every array
5713 * item.
5714 * @returns {Array} A new array of values returned by the callback function.
5715 */
5716function map(array, fn) {
5717 var length = array.length;
5718 var result = [];
5719 while (length--) {
5720 result[length] = fn(array[length]);
5721 }
5722 return result;
5723}
5724
5725/**
5726 * A simple `Array#map`-like wrapper to work with domain name strings or email
5727 * addresses.
5728 * @private
5729 * @param {String} domain The domain name or email address.
5730 * @param {Function} callback The function that gets called for every
5731 * character.
5732 * @returns {Array} A new string of characters returned by the callback
5733 * function.
5734 */
5735function mapDomain(string, fn) {
5736 var parts = string.split('@');
5737 var result = '';
5738 if (parts.length > 1) {
5739 // In email addresses, only the domain name should be punycoded. Leave
5740 // the local part (i.e. everything up to `@`) intact.
5741 result = parts[0] + '@';
5742 string = parts[1];
5743 }
5744 // Avoid `split(regex)` for IE8 compatibility. See #17.
5745 string = string.replace(regexSeparators, '\x2E');
5746 var labels = string.split('.');
5747 var encoded = map(labels, fn).join('.');
5748 return result + encoded;
5749}
5750
5751/**
5752 * Creates an array containing the numeric code points of each Unicode
5753 * character in the string. While JavaScript uses UCS-2 internally,
5754 * this function will convert a pair of surrogate halves (each of which
5755 * UCS-2 exposes as separate characters) into a single code point,
5756 * matching UTF-16.
5757 * @see `punycode.ucs2.encode`
5758 * @see <https://mathiasbynens.be/notes/javascript-encoding>
5759 * @memberOf punycode.ucs2
5760 * @name decode
5761 * @param {String} string The Unicode input string (UCS-2).
5762 * @returns {Array} The new array of code points.
5763 */
5764function ucs2decode(string) {
5765 var output = [],
5766 counter = 0,
5767 length = string.length,
5768 value,
5769 extra;
5770 while (counter < length) {
5771 value = string.charCodeAt(counter++);
5772 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
5773 // high surrogate, and there is a next character
5774 extra = string.charCodeAt(counter++);
5775 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
5776 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
5777 } else {
5778 // unmatched surrogate; only append this code unit, in case the next
5779 // code unit is the high surrogate of a surrogate pair
5780 output.push(value);
5781 counter--;
5782 }
5783 } else {
5784 output.push(value);
5785 }
5786 }
5787 return output;
5788}
5789
5790/**
5791 * Creates a string based on an array of numeric code points.
5792 * @see `punycode.ucs2.decode`
5793 * @memberOf punycode.ucs2
5794 * @name encode
5795 * @param {Array} codePoints The array of numeric code points.
5796 * @returns {String} The new Unicode string (UCS-2).
5797 */
5798function ucs2encode(array) {
5799 return map(array, function(value) {
5800 var output = '';
5801 if (value > 0xFFFF) {
5802 value -= 0x10000;
5803 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
5804 value = 0xDC00 | value & 0x3FF;
5805 }
5806 output += stringFromCharCode(value);
5807 return output;
5808 }).join('');
5809}
5810
5811/**
5812 * Converts a basic code point into a digit/integer.
5813 * @see `digitToBasic()`
5814 * @private
5815 * @param {Number} codePoint The basic numeric code point value.
5816 * @returns {Number} The numeric value of a basic code point (for use in
5817 * representing integers) in the range `0` to `base - 1`, or `base` if
5818 * the code point does not represent a value.
5819 */
5820function basicToDigit(codePoint) {
5821 if (codePoint - 48 < 10) {
5822 return codePoint - 22;
5823 }
5824 if (codePoint - 65 < 26) {
5825 return codePoint - 65;
5826 }
5827 if (codePoint - 97 < 26) {
5828 return codePoint - 97;
5829 }
5830 return base;
5831}
5832
5833/**
5834 * Converts a digit/integer into a basic code point.
5835 * @see `basicToDigit()`
5836 * @private
5837 * @param {Number} digit The numeric value of a basic code point.
5838 * @returns {Number} The basic code point whose value (when used for
5839 * representing integers) is `digit`, which needs to be in the range
5840 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
5841 * used; else, the lowercase form is used. The behavior is undefined
5842 * if `flag` is non-zero and `digit` has no uppercase form.
5843 */
5844function digitToBasic(digit, flag) {
5845 // 0..25 map to ASCII a..z or A..Z
5846 // 26..35 map to ASCII 0..9
5847 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
5848}
5849
5850/**
5851 * Bias adaptation function as per section 3.4 of RFC 3492.
5852 * https://tools.ietf.org/html/rfc3492#section-3.4
5853 * @private
5854 */
5855function adapt(delta, numPoints, firstTime) {
5856 var k = 0;
5857 delta = firstTime ? floor(delta / damp) : delta >> 1;
5858 delta += floor(delta / numPoints);
5859 for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {
5860 delta = floor(delta / baseMinusTMin);
5861 }
5862 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
5863}
5864
5865/**
5866 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
5867 * symbols.
5868 * @memberOf punycode
5869 * @param {String} input The Punycode string of ASCII-only symbols.
5870 * @returns {String} The resulting string of Unicode symbols.
5871 */
5872function decode(input) {
5873 // Don't use UCS-2
5874 var output = [],
5875 inputLength = input.length,
5876 out,
5877 i = 0,
5878 n = initialN,
5879 bias = initialBias,
5880 basic,
5881 j,
5882 index,
5883 oldi,
5884 w,
5885 k,
5886 digit,
5887 t,
5888 /** Cached calculation results */
5889 baseMinusT;
5890
5891 // Handle the basic code points: let `basic` be the number of input code
5892 // points before the last delimiter, or `0` if there is none, then copy
5893 // the first basic code points to the output.
5894
5895 basic = input.lastIndexOf(delimiter);
5896 if (basic < 0) {
5897 basic = 0;
5898 }
5899
5900 for (j = 0; j < basic; ++j) {
5901 // if it's not a basic code point
5902 if (input.charCodeAt(j) >= 0x80) {
5903 error('not-basic');
5904 }
5905 output.push(input.charCodeAt(j));
5906 }
5907
5908 // Main decoding loop: start just after the last delimiter if any basic code
5909 // points were copied; start at the beginning otherwise.
5910
5911 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */ ) {
5912
5913 // `index` is the index of the next character to be consumed.
5914 // Decode a generalized variable-length integer into `delta`,
5915 // which gets added to `i`. The overflow checking is easier
5916 // if we increase `i` as we go, then subtract off its starting
5917 // value at the end to obtain `delta`.
5918 for (oldi = i, w = 1, k = base; /* no condition */ ; k += base) {
5919
5920 if (index >= inputLength) {
5921 error('invalid-input');
5922 }
5923
5924 digit = basicToDigit(input.charCodeAt(index++));
5925
5926 if (digit >= base || digit > floor((maxInt - i) / w)) {
5927 error('overflow');
5928 }
5929
5930 i += digit * w;
5931 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
5932
5933 if (digit < t) {
5934 break;
5935 }
5936
5937 baseMinusT = base - t;
5938 if (w > floor(maxInt / baseMinusT)) {
5939 error('overflow');
5940 }
5941
5942 w *= baseMinusT;
5943
5944 }
5945
5946 out = output.length + 1;
5947 bias = adapt(i - oldi, out, oldi == 0);
5948
5949 // `i` was supposed to wrap around from `out` to `0`,
5950 // incrementing `n` each time, so we'll fix that now:
5951 if (floor(i / out) > maxInt - n) {
5952 error('overflow');
5953 }
5954
5955 n += floor(i / out);
5956 i %= out;
5957
5958 // Insert `n` at position `i` of the output
5959 output.splice(i++, 0, n);
5960
5961 }
5962
5963 return ucs2encode(output);
5964}
5965
5966/**
5967 * Converts a string of Unicode symbols (e.g. a domain name label) to a
5968 * Punycode string of ASCII-only symbols.
5969 * @memberOf punycode
5970 * @param {String} input The string of Unicode symbols.
5971 * @returns {String} The resulting Punycode string of ASCII-only symbols.
5972 */
5973function encode(input) {
5974 var n,
5975 delta,
5976 handledCPCount,
5977 basicLength,
5978 bias,
5979 j,
5980 m,
5981 q,
5982 k,
5983 t,
5984 currentValue,
5985 output = [],
5986 /** `inputLength` will hold the number of code points in `input`. */
5987 inputLength,
5988 /** Cached calculation results */
5989 handledCPCountPlusOne,
5990 baseMinusT,
5991 qMinusT;
5992
5993 // Convert the input in UCS-2 to Unicode
5994 input = ucs2decode(input);
5995
5996 // Cache the length
5997 inputLength = input.length;
5998
5999 // Initialize the state
6000 n = initialN;
6001 delta = 0;
6002 bias = initialBias;
6003
6004 // Handle the basic code points
6005 for (j = 0; j < inputLength; ++j) {
6006 currentValue = input[j];
6007 if (currentValue < 0x80) {
6008 output.push(stringFromCharCode(currentValue));
6009 }
6010 }
6011
6012 handledCPCount = basicLength = output.length;
6013
6014 // `handledCPCount` is the number of code points that have been handled;
6015 // `basicLength` is the number of basic code points.
6016
6017 // Finish the basic string - if it is not empty - with a delimiter
6018 if (basicLength) {
6019 output.push(delimiter);
6020 }
6021
6022 // Main encoding loop:
6023 while (handledCPCount < inputLength) {
6024
6025 // All non-basic code points < n have been handled already. Find the next
6026 // larger one:
6027 for (m = maxInt, j = 0; j < inputLength; ++j) {
6028 currentValue = input[j];
6029 if (currentValue >= n && currentValue < m) {
6030 m = currentValue;
6031 }
6032 }
6033
6034 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
6035 // but guard against overflow
6036 handledCPCountPlusOne = handledCPCount + 1;
6037 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
6038 error('overflow');
6039 }
6040
6041 delta += (m - n) * handledCPCountPlusOne;
6042 n = m;
6043
6044 for (j = 0; j < inputLength; ++j) {
6045 currentValue = input[j];
6046
6047 if (currentValue < n && ++delta > maxInt) {
6048 error('overflow');
6049 }
6050
6051 if (currentValue == n) {
6052 // Represent delta as a generalized variable-length integer
6053 for (q = delta, k = base; /* no condition */ ; k += base) {
6054 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
6055 if (q < t) {
6056 break;
6057 }
6058 qMinusT = q - t;
6059 baseMinusT = base - t;
6060 output.push(
6061 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
6062 );
6063 q = floor(qMinusT / baseMinusT);
6064 }
6065
6066 output.push(stringFromCharCode(digitToBasic(q, 0)));
6067 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
6068 delta = 0;
6069 ++handledCPCount;
6070 }
6071 }
6072
6073 ++delta;
6074 ++n;
6075
6076 }
6077 return output.join('');
6078}
6079
6080/**
6081 * Converts a Punycode string representing a domain name or an email address
6082 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
6083 * it doesn't matter if you call it on a string that has already been
6084 * converted to Unicode.
6085 * @memberOf punycode
6086 * @param {String} input The Punycoded domain name or email address to
6087 * convert to Unicode.
6088 * @returns {String} The Unicode representation of the given Punycode
6089 * string.
6090 */
6091function toUnicode(input) {
6092 return mapDomain(input, function(string) {
6093 return regexPunycode.test(string) ?
6094 decode(string.slice(4).toLowerCase()) :
6095 string;
6096 });
6097}
6098
6099/**
6100 * Converts a Unicode string representing a domain name or an email address to
6101 * Punycode. Only the non-ASCII parts of the domain name will be converted,
6102 * i.e. it doesn't matter if you call it with a domain that's already in
6103 * ASCII.
6104 * @memberOf punycode
6105 * @param {String} input The domain name or email address to convert, as a
6106 * Unicode string.
6107 * @returns {String} The Punycode representation of the given domain name or
6108 * email address.
6109 */
6110function toASCII(input) {
6111 return mapDomain(input, function(string) {
6112 return regexNonASCII.test(string) ?
6113 'xn--' + encode(string) :
6114 string;
6115 });
6116}
6117var version$1 = '1.4.1';
6118/**
6119 * An object of methods to convert from JavaScript's internal character
6120 * representation (UCS-2) to Unicode code points, and back.
6121 * @see <https://mathiasbynens.be/notes/javascript-encoding>
6122 * @memberOf punycode
6123 * @type Object
6124 */
6125
6126var ucs2 = {
6127 decode: ucs2decode,
6128 encode: ucs2encode
6129};
6130var punycode = {
6131 version: version$1,
6132 ucs2: ucs2,
6133 toASCII: toASCII,
6134 toUnicode: toUnicode,
6135 encode: encode,
6136 decode: decode
6137};
6138
6139// Copyright Joyent, Inc. and other Node contributors.
6140//
6141// Permission is hereby granted, free of charge, to any person obtaining a
6142// copy of this software and associated documentation files (the
6143// "Software"), to deal in the Software without restriction, including
6144// without limitation the rights to use, copy, modify, merge, publish,
6145// distribute, sublicense, and/or sell copies of the Software, and to permit
6146// persons to whom the Software is furnished to do so, subject to the
6147// following conditions:
6148//
6149// The above copyright notice and this permission notice shall be included
6150// in all copies or substantial portions of the Software.
6151//
6152// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6153// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6154// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6155// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6156// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6157// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6158// USE OR OTHER DEALINGS IN THE SOFTWARE.
6159
6160
6161// If obj.hasOwnProperty has been overridden, then calling
6162// obj.hasOwnProperty(prop) will break.
6163// See: https://github.com/joyent/node/issues/1707
6164function hasOwnProperty$1(obj, prop) {
6165 return Object.prototype.hasOwnProperty.call(obj, prop);
6166}
6167var isArray$2 = Array.isArray || function (xs) {
6168 return Object.prototype.toString.call(xs) === '[object Array]';
6169};
6170function stringifyPrimitive(v) {
6171 switch (typeof v) {
6172 case 'string':
6173 return v;
6174
6175 case 'boolean':
6176 return v ? 'true' : 'false';
6177
6178 case 'number':
6179 return isFinite(v) ? v : '';
6180
6181 default:
6182 return '';
6183 }
6184}
6185
6186function stringify (obj, sep, eq, name) {
6187 sep = sep || '&';
6188 eq = eq || '=';
6189 if (obj === null) {
6190 obj = undefined;
6191 }
6192
6193 if (typeof obj === 'object') {
6194 return map$1(objectKeys(obj), function(k) {
6195 var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
6196 if (isArray$2(obj[k])) {
6197 return map$1(obj[k], function(v) {
6198 return ks + encodeURIComponent(stringifyPrimitive(v));
6199 }).join(sep);
6200 } else {
6201 return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
6202 }
6203 }).join(sep);
6204
6205 }
6206
6207 if (!name) return '';
6208 return encodeURIComponent(stringifyPrimitive(name)) + eq +
6209 encodeURIComponent(stringifyPrimitive(obj));
6210}
6211function map$1 (xs, f) {
6212 if (xs.map) return xs.map(f);
6213 var res = [];
6214 for (var i = 0; i < xs.length; i++) {
6215 res.push(f(xs[i], i));
6216 }
6217 return res;
6218}
6219
6220var objectKeys = Object.keys || function (obj) {
6221 var res = [];
6222 for (var key in obj) {
6223 if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
6224 }
6225 return res;
6226};
6227
6228function parse(qs, sep, eq, options) {
6229 sep = sep || '&';
6230 eq = eq || '=';
6231 var obj = {};
6232
6233 if (typeof qs !== 'string' || qs.length === 0) {
6234 return obj;
6235 }
6236
6237 var regexp = /\+/g;
6238 qs = qs.split(sep);
6239
6240 var maxKeys = 1000;
6241 if (options && typeof options.maxKeys === 'number') {
6242 maxKeys = options.maxKeys;
6243 }
6244
6245 var len = qs.length;
6246 // maxKeys <= 0 means that we should not limit keys count
6247 if (maxKeys > 0 && len > maxKeys) {
6248 len = maxKeys;
6249 }
6250
6251 for (var i = 0; i < len; ++i) {
6252 var x = qs[i].replace(regexp, '%20'),
6253 idx = x.indexOf(eq),
6254 kstr, vstr, k, v;
6255
6256 if (idx >= 0) {
6257 kstr = x.substr(0, idx);
6258 vstr = x.substr(idx + 1);
6259 } else {
6260 kstr = x;
6261 vstr = '';
6262 }
6263
6264 k = decodeURIComponent(kstr);
6265 v = decodeURIComponent(vstr);
6266
6267 if (!hasOwnProperty$1(obj, k)) {
6268 obj[k] = v;
6269 } else if (isArray$2(obj[k])) {
6270 obj[k].push(v);
6271 } else {
6272 obj[k] = [obj[k], v];
6273 }
6274 }
6275
6276 return obj;
6277}var querystring = {
6278 encode: stringify,
6279 stringify: stringify,
6280 decode: parse,
6281 parse: parse
6282};
6283
6284// Copyright Joyent, Inc. and other Node contributors.
6285var Url = {
6286 parse: urlParse,
6287 resolve: urlResolve,
6288 resolveObject: urlResolveObject,
6289 format: urlFormat,
6290 Url: Url$1
6291};
6292function Url$1() {
6293 this.protocol = null;
6294 this.slashes = null;
6295 this.auth = null;
6296 this.host = null;
6297 this.port = null;
6298 this.hostname = null;
6299 this.hash = null;
6300 this.search = null;
6301 this.query = null;
6302 this.pathname = null;
6303 this.path = null;
6304 this.href = null;
6305}
6306
6307// Reference: RFC 3986, RFC 1808, RFC 2396
6308
6309// define these here so at least they only have to be
6310// compiled once on the first module load.
6311var protocolPattern = /^([a-z0-9.+-]+:)/i,
6312 portPattern = /:[0-9]*$/,
6313
6314 // Special case for a simple path URL
6315 simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
6316
6317 // RFC 2396: characters reserved for delimiting URLs.
6318 // We actually just auto-escape these.
6319 delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
6320
6321 // RFC 2396: characters not allowed for various reasons.
6322 unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
6323
6324 // Allowed by RFCs, but cause of XSS attacks. Always escape these.
6325 autoEscape = ['\''].concat(unwise),
6326 // Characters that are never ever allowed in a hostname.
6327 // Note that any invalid chars are also handled, but these
6328 // are the ones that are *expected* to be seen, so we fast-path
6329 // them.
6330 nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
6331 hostEndingChars = ['/', '?', '#'],
6332 hostnameMaxLen = 255,
6333 hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
6334 hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
6335 // protocols that can allow "unsafe" and "unwise" chars.
6336 unsafeProtocol = {
6337 'javascript': true,
6338 'javascript:': true
6339 },
6340 // protocols that never have a hostname.
6341 hostlessProtocol = {
6342 'javascript': true,
6343 'javascript:': true
6344 },
6345 // protocols that always contain a // bit.
6346 slashedProtocol = {
6347 'http': true,
6348 'https': true,
6349 'ftp': true,
6350 'gopher': true,
6351 'file': true,
6352 'http:': true,
6353 'https:': true,
6354 'ftp:': true,
6355 'gopher:': true,
6356 'file:': true
6357 };
6358
6359function urlParse(url, parseQueryString, slashesDenoteHost) {
6360 if (url && isObject(url) && url instanceof Url$1) return url;
6361
6362 var u = new Url$1;
6363 u.parse(url, parseQueryString, slashesDenoteHost);
6364 return u;
6365}
6366Url$1.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
6367 return parse$1(this, url, parseQueryString, slashesDenoteHost);
6368};
6369
6370function parse$1(self, url, parseQueryString, slashesDenoteHost) {
6371 if (!isString(url)) {
6372 throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url);
6373 }
6374
6375 // Copy chrome, IE, opera backslash-handling behavior.
6376 // Back slashes before the query string get converted to forward slashes
6377 // See: https://code.google.com/p/chromium/issues/detail?id=25916
6378 var queryIndex = url.indexOf('?'),
6379 splitter =
6380 (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
6381 uSplit = url.split(splitter),
6382 slashRegex = /\\/g;
6383 uSplit[0] = uSplit[0].replace(slashRegex, '/');
6384 url = uSplit.join(splitter);
6385
6386 var rest = url;
6387
6388 // trim before proceeding.
6389 // This is to support parse stuff like " http://foo.com \n"
6390 rest = rest.trim();
6391
6392 if (!slashesDenoteHost && url.split('#').length === 1) {
6393 // Try fast path regexp
6394 var simplePath = simplePathPattern.exec(rest);
6395 if (simplePath) {
6396 self.path = rest;
6397 self.href = rest;
6398 self.pathname = simplePath[1];
6399 if (simplePath[2]) {
6400 self.search = simplePath[2];
6401 if (parseQueryString) {
6402 self.query = parse(self.search.substr(1));
6403 } else {
6404 self.query = self.search.substr(1);
6405 }
6406 } else if (parseQueryString) {
6407 self.search = '';
6408 self.query = {};
6409 }
6410 return self;
6411 }
6412 }
6413
6414 var proto = protocolPattern.exec(rest);
6415 if (proto) {
6416 proto = proto[0];
6417 var lowerProto = proto.toLowerCase();
6418 self.protocol = lowerProto;
6419 rest = rest.substr(proto.length);
6420 }
6421
6422 // figure out if it's got a host
6423 // user@server is *always* interpreted as a hostname, and url
6424 // resolution will treat //foo/bar as host=foo,path=bar because that's
6425 // how the browser resolves relative URLs.
6426 if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
6427 var slashes = rest.substr(0, 2) === '//';
6428 if (slashes && !(proto && hostlessProtocol[proto])) {
6429 rest = rest.substr(2);
6430 self.slashes = true;
6431 }
6432 }
6433 var i, hec, l, p;
6434 if (!hostlessProtocol[proto] &&
6435 (slashes || (proto && !slashedProtocol[proto]))) {
6436
6437 // there's a hostname.
6438 // the first instance of /, ?, ;, or # ends the host.
6439 //
6440 // If there is an @ in the hostname, then non-host chars *are* allowed
6441 // to the left of the last @ sign, unless some host-ending character
6442 // comes *before* the @-sign.
6443 // URLs are obnoxious.
6444 //
6445 // ex:
6446 // http://a@b@c/ => user:a@b host:c
6447 // http://a@b?@c => user:a host:c path:/?@c
6448
6449 // v0.12 TODO(isaacs): This is not quite how Chrome does things.
6450 // Review our test case against browsers more comprehensively.
6451
6452 // find the first instance of any hostEndingChars
6453 var hostEnd = -1;
6454 for (i = 0; i < hostEndingChars.length; i++) {
6455 hec = rest.indexOf(hostEndingChars[i]);
6456 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
6457 hostEnd = hec;
6458 }
6459
6460 // at this point, either we have an explicit point where the
6461 // auth portion cannot go past, or the last @ char is the decider.
6462 var auth, atSign;
6463 if (hostEnd === -1) {
6464 // atSign can be anywhere.
6465 atSign = rest.lastIndexOf('@');
6466 } else {
6467 // atSign must be in auth portion.
6468 // http://a@b/c@d => host:b auth:a path:/c@d
6469 atSign = rest.lastIndexOf('@', hostEnd);
6470 }
6471
6472 // Now we have a portion which is definitely the auth.
6473 // Pull that off.
6474 if (atSign !== -1) {
6475 auth = rest.slice(0, atSign);
6476 rest = rest.slice(atSign + 1);
6477 self.auth = decodeURIComponent(auth);
6478 }
6479
6480 // the host is the remaining to the left of the first non-host char
6481 hostEnd = -1;
6482 for (i = 0; i < nonHostChars.length; i++) {
6483 hec = rest.indexOf(nonHostChars[i]);
6484 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
6485 hostEnd = hec;
6486 }
6487 // if we still have not hit it, then the entire thing is a host.
6488 if (hostEnd === -1)
6489 hostEnd = rest.length;
6490
6491 self.host = rest.slice(0, hostEnd);
6492 rest = rest.slice(hostEnd);
6493
6494 // pull out port.
6495 parseHost(self);
6496
6497 // we've indicated that there is a hostname,
6498 // so even if it's empty, it has to be present.
6499 self.hostname = self.hostname || '';
6500
6501 // if hostname begins with [ and ends with ]
6502 // assume that it's an IPv6 address.
6503 var ipv6Hostname = self.hostname[0] === '[' &&
6504 self.hostname[self.hostname.length - 1] === ']';
6505
6506 // validate a little.
6507 if (!ipv6Hostname) {
6508 var hostparts = self.hostname.split(/\./);
6509 for (i = 0, l = hostparts.length; i < l; i++) {
6510 var part = hostparts[i];
6511 if (!part) continue;
6512 if (!part.match(hostnamePartPattern)) {
6513 var newpart = '';
6514 for (var j = 0, k = part.length; j < k; j++) {
6515 if (part.charCodeAt(j) > 127) {
6516 // we replace non-ASCII char with a temporary placeholder
6517 // we need this to make sure size of hostname is not
6518 // broken by replacing non-ASCII by nothing
6519 newpart += 'x';
6520 } else {
6521 newpart += part[j];
6522 }
6523 }
6524 // we test again with ASCII char only
6525 if (!newpart.match(hostnamePartPattern)) {
6526 var validParts = hostparts.slice(0, i);
6527 var notHost = hostparts.slice(i + 1);
6528 var bit = part.match(hostnamePartStart);
6529 if (bit) {
6530 validParts.push(bit[1]);
6531 notHost.unshift(bit[2]);
6532 }
6533 if (notHost.length) {
6534 rest = '/' + notHost.join('.') + rest;
6535 }
6536 self.hostname = validParts.join('.');
6537 break;
6538 }
6539 }
6540 }
6541 }
6542
6543 if (self.hostname.length > hostnameMaxLen) {
6544 self.hostname = '';
6545 } else {
6546 // hostnames are always lower case.
6547 self.hostname = self.hostname.toLowerCase();
6548 }
6549
6550 if (!ipv6Hostname) {
6551 // IDNA Support: Returns a punycoded representation of "domain".
6552 // It only converts parts of the domain name that
6553 // have non-ASCII characters, i.e. it doesn't matter if
6554 // you call it with a domain that already is ASCII-only.
6555 self.hostname = toASCII(self.hostname);
6556 }
6557
6558 p = self.port ? ':' + self.port : '';
6559 var h = self.hostname || '';
6560 self.host = h + p;
6561 self.href += self.host;
6562
6563 // strip [ and ] from the hostname
6564 // the host field still retains them, though
6565 if (ipv6Hostname) {
6566 self.hostname = self.hostname.substr(1, self.hostname.length - 2);
6567 if (rest[0] !== '/') {
6568 rest = '/' + rest;
6569 }
6570 }
6571 }
6572
6573 // now rest is set to the post-host stuff.
6574 // chop off any delim chars.
6575 if (!unsafeProtocol[lowerProto]) {
6576
6577 // First, make 100% sure that any "autoEscape" chars get
6578 // escaped, even if encodeURIComponent doesn't think they
6579 // need to be.
6580 for (i = 0, l = autoEscape.length; i < l; i++) {
6581 var ae = autoEscape[i];
6582 if (rest.indexOf(ae) === -1)
6583 continue;
6584 var esc = encodeURIComponent(ae);
6585 if (esc === ae) {
6586 esc = escape(ae);
6587 }
6588 rest = rest.split(ae).join(esc);
6589 }
6590 }
6591
6592
6593 // chop off from the tail first.
6594 var hash = rest.indexOf('#');
6595 if (hash !== -1) {
6596 // got a fragment string.
6597 self.hash = rest.substr(hash);
6598 rest = rest.slice(0, hash);
6599 }
6600 var qm = rest.indexOf('?');
6601 if (qm !== -1) {
6602 self.search = rest.substr(qm);
6603 self.query = rest.substr(qm + 1);
6604 if (parseQueryString) {
6605 self.query = parse(self.query);
6606 }
6607 rest = rest.slice(0, qm);
6608 } else if (parseQueryString) {
6609 // no query string, but parseQueryString still requested
6610 self.search = '';
6611 self.query = {};
6612 }
6613 if (rest) self.pathname = rest;
6614 if (slashedProtocol[lowerProto] &&
6615 self.hostname && !self.pathname) {
6616 self.pathname = '/';
6617 }
6618
6619 //to support http.request
6620 if (self.pathname || self.search) {
6621 p = self.pathname || '';
6622 var s = self.search || '';
6623 self.path = p + s;
6624 }
6625
6626 // finally, reconstruct the href based on what has been validated.
6627 self.href = format$1(self);
6628 return self;
6629}
6630
6631// format a parsed object into a url string
6632function urlFormat(obj) {
6633 // ensure it's an object, and not a string url.
6634 // If it's an obj, this is a no-op.
6635 // this way, you can call url_format() on strings
6636 // to clean up potentially wonky urls.
6637 if (isString(obj)) obj = parse$1({}, obj);
6638 return format$1(obj);
6639}
6640
6641function format$1(self) {
6642 var auth = self.auth || '';
6643 if (auth) {
6644 auth = encodeURIComponent(auth);
6645 auth = auth.replace(/%3A/i, ':');
6646 auth += '@';
6647 }
6648
6649 var protocol = self.protocol || '',
6650 pathname = self.pathname || '',
6651 hash = self.hash || '',
6652 host = false,
6653 query = '';
6654
6655 if (self.host) {
6656 host = auth + self.host;
6657 } else if (self.hostname) {
6658 host = auth + (self.hostname.indexOf(':') === -1 ?
6659 self.hostname :
6660 '[' + this.hostname + ']');
6661 if (self.port) {
6662 host += ':' + self.port;
6663 }
6664 }
6665
6666 if (self.query &&
6667 isObject(self.query) &&
6668 Object.keys(self.query).length) {
6669 query = stringify(self.query);
6670 }
6671
6672 var search = self.search || (query && ('?' + query)) || '';
6673
6674 if (protocol && protocol.substr(-1) !== ':') protocol += ':';
6675
6676 // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
6677 // unless they had them to begin with.
6678 if (self.slashes ||
6679 (!protocol || slashedProtocol[protocol]) && host !== false) {
6680 host = '//' + (host || '');
6681 if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
6682 } else if (!host) {
6683 host = '';
6684 }
6685
6686 if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
6687 if (search && search.charAt(0) !== '?') search = '?' + search;
6688
6689 pathname = pathname.replace(/[?#]/g, function(match) {
6690 return encodeURIComponent(match);
6691 });
6692 search = search.replace('#', '%23');
6693
6694 return protocol + host + pathname + search + hash;
6695}
6696
6697Url$1.prototype.format = function() {
6698 return format$1(this);
6699};
6700
6701function urlResolve(source, relative) {
6702 return urlParse(source, false, true).resolve(relative);
6703}
6704
6705Url$1.prototype.resolve = function(relative) {
6706 return this.resolveObject(urlParse(relative, false, true)).format();
6707};
6708
6709function urlResolveObject(source, relative) {
6710 if (!source) return relative;
6711 return urlParse(source, false, true).resolveObject(relative);
6712}
6713
6714Url$1.prototype.resolveObject = function(relative) {
6715 if (isString(relative)) {
6716 var rel = new Url$1();
6717 rel.parse(relative, false, true);
6718 relative = rel;
6719 }
6720
6721 var result = new Url$1();
6722 var tkeys = Object.keys(this);
6723 for (var tk = 0; tk < tkeys.length; tk++) {
6724 var tkey = tkeys[tk];
6725 result[tkey] = this[tkey];
6726 }
6727
6728 // hash is always overridden, no matter what.
6729 // even href="" will remove it.
6730 result.hash = relative.hash;
6731
6732 // if the relative url is empty, then there's nothing left to do here.
6733 if (relative.href === '') {
6734 result.href = result.format();
6735 return result;
6736 }
6737
6738 // hrefs like //foo/bar always cut to the protocol.
6739 if (relative.slashes && !relative.protocol) {
6740 // take everything except the protocol from relative
6741 var rkeys = Object.keys(relative);
6742 for (var rk = 0; rk < rkeys.length; rk++) {
6743 var rkey = rkeys[rk];
6744 if (rkey !== 'protocol')
6745 result[rkey] = relative[rkey];
6746 }
6747
6748 //urlParse appends trailing / to urls like http://www.example.com
6749 if (slashedProtocol[result.protocol] &&
6750 result.hostname && !result.pathname) {
6751 result.path = result.pathname = '/';
6752 }
6753
6754 result.href = result.format();
6755 return result;
6756 }
6757 var relPath;
6758 if (relative.protocol && relative.protocol !== result.protocol) {
6759 // if it's a known url protocol, then changing
6760 // the protocol does weird things
6761 // first, if it's not file:, then we MUST have a host,
6762 // and if there was a path
6763 // to begin with, then we MUST have a path.
6764 // if it is file:, then the host is dropped,
6765 // because that's known to be hostless.
6766 // anything else is assumed to be absolute.
6767 if (!slashedProtocol[relative.protocol]) {
6768 var keys = Object.keys(relative);
6769 for (var v = 0; v < keys.length; v++) {
6770 var k = keys[v];
6771 result[k] = relative[k];
6772 }
6773 result.href = result.format();
6774 return result;
6775 }
6776
6777 result.protocol = relative.protocol;
6778 if (!relative.host && !hostlessProtocol[relative.protocol]) {
6779 relPath = (relative.pathname || '').split('/');
6780 while (relPath.length && !(relative.host = relPath.shift()));
6781 if (!relative.host) relative.host = '';
6782 if (!relative.hostname) relative.hostname = '';
6783 if (relPath[0] !== '') relPath.unshift('');
6784 if (relPath.length < 2) relPath.unshift('');
6785 result.pathname = relPath.join('/');
6786 } else {
6787 result.pathname = relative.pathname;
6788 }
6789 result.search = relative.search;
6790 result.query = relative.query;
6791 result.host = relative.host || '';
6792 result.auth = relative.auth;
6793 result.hostname = relative.hostname || relative.host;
6794 result.port = relative.port;
6795 // to support http.request
6796 if (result.pathname || result.search) {
6797 var p = result.pathname || '';
6798 var s = result.search || '';
6799 result.path = p + s;
6800 }
6801 result.slashes = result.slashes || relative.slashes;
6802 result.href = result.format();
6803 return result;
6804 }
6805
6806 var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
6807 isRelAbs = (
6808 relative.host ||
6809 relative.pathname && relative.pathname.charAt(0) === '/'
6810 ),
6811 mustEndAbs = (isRelAbs || isSourceAbs ||
6812 (result.host && relative.pathname)),
6813 removeAllDots = mustEndAbs,
6814 srcPath = result.pathname && result.pathname.split('/') || [],
6815 psychotic = result.protocol && !slashedProtocol[result.protocol];
6816 relPath = relative.pathname && relative.pathname.split('/') || [];
6817 // if the url is a non-slashed url, then relative
6818 // links like ../.. should be able
6819 // to crawl up to the hostname, as well. This is strange.
6820 // result.protocol has already been set by now.
6821 // Later on, put the first path part into the host field.
6822 if (psychotic) {
6823 result.hostname = '';
6824 result.port = null;
6825 if (result.host) {
6826 if (srcPath[0] === '') srcPath[0] = result.host;
6827 else srcPath.unshift(result.host);
6828 }
6829 result.host = '';
6830 if (relative.protocol) {
6831 relative.hostname = null;
6832 relative.port = null;
6833 if (relative.host) {
6834 if (relPath[0] === '') relPath[0] = relative.host;
6835 else relPath.unshift(relative.host);
6836 }
6837 relative.host = null;
6838 }
6839 mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
6840 }
6841 var authInHost;
6842 if (isRelAbs) {
6843 // it's absolute.
6844 result.host = (relative.host || relative.host === '') ?
6845 relative.host : result.host;
6846 result.hostname = (relative.hostname || relative.hostname === '') ?
6847 relative.hostname : result.hostname;
6848 result.search = relative.search;
6849 result.query = relative.query;
6850 srcPath = relPath;
6851 // fall through to the dot-handling below.
6852 } else if (relPath.length) {
6853 // it's relative
6854 // throw away the existing file, and take the new path instead.
6855 if (!srcPath) srcPath = [];
6856 srcPath.pop();
6857 srcPath = srcPath.concat(relPath);
6858 result.search = relative.search;
6859 result.query = relative.query;
6860 } else if (!isNullOrUndefined(relative.search)) {
6861 // just pull out the search.
6862 // like href='?foo'.
6863 // Put this after the other two cases because it simplifies the booleans
6864 if (psychotic) {
6865 result.hostname = result.host = srcPath.shift();
6866 //occationaly the auth can get stuck only in host
6867 //this especially happens in cases like
6868 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
6869 authInHost = result.host && result.host.indexOf('@') > 0 ?
6870 result.host.split('@') : false;
6871 if (authInHost) {
6872 result.auth = authInHost.shift();
6873 result.host = result.hostname = authInHost.shift();
6874 }
6875 }
6876 result.search = relative.search;
6877 result.query = relative.query;
6878 //to support http.request
6879 if (!isNull(result.pathname) || !isNull(result.search)) {
6880 result.path = (result.pathname ? result.pathname : '') +
6881 (result.search ? result.search : '');
6882 }
6883 result.href = result.format();
6884 return result;
6885 }
6886
6887 if (!srcPath.length) {
6888 // no path at all. easy.
6889 // we've already handled the other stuff above.
6890 result.pathname = null;
6891 //to support http.request
6892 if (result.search) {
6893 result.path = '/' + result.search;
6894 } else {
6895 result.path = null;
6896 }
6897 result.href = result.format();
6898 return result;
6899 }
6900
6901 // if a url ENDs in . or .., then it must get a trailing slash.
6902 // however, if it ends in anything else non-slashy,
6903 // then it must NOT get a trailing slash.
6904 var last = srcPath.slice(-1)[0];
6905 var hasTrailingSlash = (
6906 (result.host || relative.host || srcPath.length > 1) &&
6907 (last === '.' || last === '..') || last === '');
6908
6909 // strip single dots, resolve double dots to parent dir
6910 // if the path tries to go above the root, `up` ends up > 0
6911 var up = 0;
6912 for (var i = srcPath.length; i >= 0; i--) {
6913 last = srcPath[i];
6914 if (last === '.') {
6915 srcPath.splice(i, 1);
6916 } else if (last === '..') {
6917 srcPath.splice(i, 1);
6918 up++;
6919 } else if (up) {
6920 srcPath.splice(i, 1);
6921 up--;
6922 }
6923 }
6924
6925 // if the path is allowed to go above the root, restore leading ..s
6926 if (!mustEndAbs && !removeAllDots) {
6927 for (; up--; up) {
6928 srcPath.unshift('..');
6929 }
6930 }
6931
6932 if (mustEndAbs && srcPath[0] !== '' &&
6933 (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
6934 srcPath.unshift('');
6935 }
6936
6937 if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
6938 srcPath.push('');
6939 }
6940
6941 var isAbsolute = srcPath[0] === '' ||
6942 (srcPath[0] && srcPath[0].charAt(0) === '/');
6943
6944 // put the host back
6945 if (psychotic) {
6946 result.hostname = result.host = isAbsolute ? '' :
6947 srcPath.length ? srcPath.shift() : '';
6948 //occationaly the auth can get stuck only in host
6949 //this especially happens in cases like
6950 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
6951 authInHost = result.host && result.host.indexOf('@') > 0 ?
6952 result.host.split('@') : false;
6953 if (authInHost) {
6954 result.auth = authInHost.shift();
6955 result.host = result.hostname = authInHost.shift();
6956 }
6957 }
6958
6959 mustEndAbs = mustEndAbs || (result.host && srcPath.length);
6960
6961 if (mustEndAbs && !isAbsolute) {
6962 srcPath.unshift('');
6963 }
6964
6965 if (!srcPath.length) {
6966 result.pathname = null;
6967 result.path = null;
6968 } else {
6969 result.pathname = srcPath.join('/');
6970 }
6971
6972 //to support request.http
6973 if (!isNull(result.pathname) || !isNull(result.search)) {
6974 result.path = (result.pathname ? result.pathname : '') +
6975 (result.search ? result.search : '');
6976 }
6977 result.auth = relative.auth || result.auth;
6978 result.slashes = result.slashes || relative.slashes;
6979 result.href = result.format();
6980 return result;
6981};
6982
6983Url$1.prototype.parseHost = function() {
6984 return parseHost(this);
6985};
6986
6987function parseHost(self) {
6988 var host = self.host;
6989 var port = portPattern.exec(host);
6990 if (port) {
6991 port = port[0];
6992 if (port !== ':') {
6993 self.port = port.substr(1);
6994 }
6995 host = host.substr(0, host.length - port.length);
6996 }
6997 if (host) self.hostname = host;
6998}
6999
7000function request(opts, cb) {
7001 if (typeof opts === 'string')
7002 opts = urlParse(opts);
7003
7004
7005 // Normally, the page is loaded from http or https, so not specifying a protocol
7006 // will result in a (valid) protocol-relative url. However, this won't work if
7007 // the protocol is something else, like 'file:'
7008 var defaultProtocol = global$1.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '';
7009
7010 var protocol = opts.protocol || defaultProtocol;
7011 var host = opts.hostname || opts.host;
7012 var port = opts.port;
7013 var path = opts.path || '/';
7014
7015 // Necessary for IPv6 addresses
7016 if (host && host.indexOf(':') !== -1)
7017 host = '[' + host + ']';
7018
7019 // This may be a relative url. The browser should always be able to interpret it correctly.
7020 opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path;
7021 opts.method = (opts.method || 'GET').toUpperCase();
7022 opts.headers = opts.headers || {};
7023
7024 // Also valid opts.auth, opts.mode
7025
7026 var req = new ClientRequest(opts);
7027 if (cb)
7028 req.on('response', cb);
7029 return req
7030}
7031
7032function get(opts, cb) {
7033 var req = request(opts, cb);
7034 req.end();
7035 return req
7036}
7037
7038function Agent() {}
7039Agent.defaultMaxSockets = 4;
7040
7041var METHODS = [
7042 'CHECKOUT',
7043 'CONNECT',
7044 'COPY',
7045 'DELETE',
7046 'GET',
7047 'HEAD',
7048 'LOCK',
7049 'M-SEARCH',
7050 'MERGE',
7051 'MKACTIVITY',
7052 'MKCOL',
7053 'MOVE',
7054 'NOTIFY',
7055 'OPTIONS',
7056 'PATCH',
7057 'POST',
7058 'PROPFIND',
7059 'PROPPATCH',
7060 'PURGE',
7061 'PUT',
7062 'REPORT',
7063 'SEARCH',
7064 'SUBSCRIBE',
7065 'TRACE',
7066 'UNLOCK',
7067 'UNSUBSCRIBE'
7068];
7069var STATUS_CODES = {
7070 100: 'Continue',
7071 101: 'Switching Protocols',
7072 102: 'Processing', // RFC 2518, obsoleted by RFC 4918
7073 200: 'OK',
7074 201: 'Created',
7075 202: 'Accepted',
7076 203: 'Non-Authoritative Information',
7077 204: 'No Content',
7078 205: 'Reset Content',
7079 206: 'Partial Content',
7080 207: 'Multi-Status', // RFC 4918
7081 300: 'Multiple Choices',
7082 301: 'Moved Permanently',
7083 302: 'Moved Temporarily',
7084 303: 'See Other',
7085 304: 'Not Modified',
7086 305: 'Use Proxy',
7087 307: 'Temporary Redirect',
7088 400: 'Bad Request',
7089 401: 'Unauthorized',
7090 402: 'Payment Required',
7091 403: 'Forbidden',
7092 404: 'Not Found',
7093 405: 'Method Not Allowed',
7094 406: 'Not Acceptable',
7095 407: 'Proxy Authentication Required',
7096 408: 'Request Time-out',
7097 409: 'Conflict',
7098 410: 'Gone',
7099 411: 'Length Required',
7100 412: 'Precondition Failed',
7101 413: 'Request Entity Too Large',
7102 414: 'Request-URI Too Large',
7103 415: 'Unsupported Media Type',
7104 416: 'Requested Range Not Satisfiable',
7105 417: 'Expectation Failed',
7106 418: 'I\'m a teapot', // RFC 2324
7107 422: 'Unprocessable Entity', // RFC 4918
7108 423: 'Locked', // RFC 4918
7109 424: 'Failed Dependency', // RFC 4918
7110 425: 'Unordered Collection', // RFC 4918
7111 426: 'Upgrade Required', // RFC 2817
7112 428: 'Precondition Required', // RFC 6585
7113 429: 'Too Many Requests', // RFC 6585
7114 431: 'Request Header Fields Too Large', // RFC 6585
7115 500: 'Internal Server Error',
7116 501: 'Not Implemented',
7117 502: 'Bad Gateway',
7118 503: 'Service Unavailable',
7119 504: 'Gateway Time-out',
7120 505: 'HTTP Version Not Supported',
7121 506: 'Variant Also Negotiates', // RFC 2295
7122 507: 'Insufficient Storage', // RFC 4918
7123 509: 'Bandwidth Limit Exceeded',
7124 510: 'Not Extended', // RFC 2774
7125 511: 'Network Authentication Required' // RFC 6585
7126};
7127
7128var http = {
7129 request,
7130 get,
7131 Agent,
7132 METHODS,
7133 STATUS_CODES
7134};
7135
7136var msg = {
7137 2: 'need dictionary', /* Z_NEED_DICT 2 */
7138 1: 'stream end', /* Z_STREAM_END 1 */
7139 0: '', /* Z_OK 0 */
7140 '-1': 'file error', /* Z_ERRNO (-1) */
7141 '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
7142 '-3': 'data error', /* Z_DATA_ERROR (-3) */
7143 '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
7144 '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
7145 '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
7146};
7147
7148function ZStream() {
7149 /* next input byte */
7150 this.input = null; // JS specific, because we have no pointers
7151 this.next_in = 0;
7152 /* number of bytes available at input */
7153 this.avail_in = 0;
7154 /* total number of input bytes read so far */
7155 this.total_in = 0;
7156 /* next output byte should be put there */
7157 this.output = null; // JS specific, because we have no pointers
7158 this.next_out = 0;
7159 /* remaining free space at output */
7160 this.avail_out = 0;
7161 /* total number of bytes output so far */
7162 this.total_out = 0;
7163 /* last error message, NULL if no error */
7164 this.msg = ''/*Z_NULL*/;
7165 /* not visible by applications */
7166 this.state = null;
7167 /* best guess about the data type: binary or text */
7168 this.data_type = 2/*Z_UNKNOWN*/;
7169 /* adler32 value of the uncompressed data */
7170 this.adler = 0;
7171}
7172
7173function arraySet(dest, src, src_offs, len, dest_offs) {
7174 if (src.subarray && dest.subarray) {
7175 dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
7176 return;
7177 }
7178 // Fallback to ordinary array
7179 for (var i = 0; i < len; i++) {
7180 dest[dest_offs + i] = src[src_offs + i];
7181 }
7182}
7183
7184
7185var Buf8 = Uint8Array;
7186var Buf16 = Uint16Array;
7187var Buf32 = Int32Array;
7188// Enable/Disable typed arrays use, for testing
7189//
7190
7191/* Public constants ==========================================================*/
7192/* ===========================================================================*/
7193
7194
7195//var Z_FILTERED = 1;
7196//var Z_HUFFMAN_ONLY = 2;
7197//var Z_RLE = 3;
7198var Z_FIXED = 4;
7199//var Z_DEFAULT_STRATEGY = 0;
7200
7201/* Possible values of the data_type field (though see inflate()) */
7202var Z_BINARY = 0;
7203var Z_TEXT = 1;
7204//var Z_ASCII = 1; // = Z_TEXT
7205var Z_UNKNOWN = 2;
7206
7207/*============================================================================*/
7208
7209
7210function zero(buf) {
7211 var len = buf.length;
7212 while (--len >= 0) {
7213 buf[len] = 0;
7214 }
7215}
7216
7217// From zutil.h
7218
7219var STORED_BLOCK = 0;
7220var STATIC_TREES = 1;
7221var DYN_TREES = 2;
7222/* The three kinds of block type */
7223
7224var MIN_MATCH = 3;
7225var MAX_MATCH = 258;
7226/* The minimum and maximum match lengths */
7227
7228// From deflate.h
7229/* ===========================================================================
7230 * Internal compression state.
7231 */
7232
7233var LENGTH_CODES = 29;
7234/* number of length codes, not counting the special END_BLOCK code */
7235
7236var LITERALS = 256;
7237/* number of literal bytes 0..255 */
7238
7239var L_CODES = LITERALS + 1 + LENGTH_CODES;
7240/* number of Literal or Length codes, including the END_BLOCK code */
7241
7242var D_CODES = 30;
7243/* number of distance codes */
7244
7245var BL_CODES = 19;
7246/* number of codes used to transfer the bit lengths */
7247
7248var HEAP_SIZE = 2 * L_CODES + 1;
7249/* maximum heap size */
7250
7251var MAX_BITS = 15;
7252/* All codes must not exceed MAX_BITS bits */
7253
7254var Buf_size = 16;
7255/* size of bit buffer in bi_buf */
7256
7257
7258/* ===========================================================================
7259 * Constants
7260 */
7261
7262var MAX_BL_BITS = 7;
7263/* Bit length codes must not exceed MAX_BL_BITS bits */
7264
7265var END_BLOCK = 256;
7266/* end of block literal code */
7267
7268var REP_3_6 = 16;
7269/* repeat previous bit length 3-6 times (2 bits of repeat count) */
7270
7271var REPZ_3_10 = 17;
7272/* repeat a zero length 3-10 times (3 bits of repeat count) */
7273
7274var REPZ_11_138 = 18;
7275/* repeat a zero length 11-138 times (7 bits of repeat count) */
7276
7277/* eslint-disable comma-spacing,array-bracket-spacing */
7278var extra_lbits = /* extra bits for each length code */ [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
7279
7280var extra_dbits = /* extra bits for each distance code */ [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
7281
7282var extra_blbits = /* extra bits for each bit length code */ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7];
7283
7284var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
7285/* eslint-enable comma-spacing,array-bracket-spacing */
7286
7287/* The lengths of the bit length codes are sent in order of decreasing
7288 * probability, to avoid transmitting the lengths for unused bit length codes.
7289 */
7290
7291/* ===========================================================================
7292 * Local data. These are initialized only once.
7293 */
7294
7295// We pre-fill arrays with 0 to avoid uninitialized gaps
7296
7297var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
7298
7299// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
7300var static_ltree = new Array((L_CODES + 2) * 2);
7301zero(static_ltree);
7302/* The static literal tree. Since the bit lengths are imposed, there is no
7303 * need for the L_CODES extra codes used during heap construction. However
7304 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
7305 * below).
7306 */
7307
7308var static_dtree = new Array(D_CODES * 2);
7309zero(static_dtree);
7310/* The static distance tree. (Actually a trivial tree since all codes use
7311 * 5 bits.)
7312 */
7313
7314var _dist_code = new Array(DIST_CODE_LEN);
7315zero(_dist_code);
7316/* Distance codes. The first 256 values correspond to the distances
7317 * 3 .. 258, the last 256 values correspond to the top 8 bits of
7318 * the 15 bit distances.
7319 */
7320
7321var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
7322zero(_length_code);
7323/* length code for each normalized match length (0 == MIN_MATCH) */
7324
7325var base_length = new Array(LENGTH_CODES);
7326zero(base_length);
7327/* First normalized length for each code (0 = MIN_MATCH) */
7328
7329var base_dist = new Array(D_CODES);
7330zero(base_dist);
7331/* First normalized distance for each code (0 = distance of 1) */
7332
7333
7334function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
7335
7336 this.static_tree = static_tree; /* static tree or NULL */
7337 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
7338 this.extra_base = extra_base; /* base index for extra_bits */
7339 this.elems = elems; /* max number of elements in the tree */
7340 this.max_length = max_length; /* max bit length for the codes */
7341
7342 // show if `static_tree` has data or dummy - needed for monomorphic objects
7343 this.has_stree = static_tree && static_tree.length;
7344}
7345
7346
7347var static_l_desc;
7348var static_d_desc;
7349var static_bl_desc;
7350
7351
7352function TreeDesc(dyn_tree, stat_desc) {
7353 this.dyn_tree = dyn_tree; /* the dynamic tree */
7354 this.max_code = 0; /* largest code with non zero frequency */
7355 this.stat_desc = stat_desc; /* the corresponding static tree */
7356}
7357
7358
7359
7360function d_code(dist) {
7361 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
7362}
7363
7364
7365/* ===========================================================================
7366 * Output a short LSB first on the stream.
7367 * IN assertion: there is enough room in pendingBuf.
7368 */
7369function put_short(s, w) {
7370 // put_byte(s, (uch)((w) & 0xff));
7371 // put_byte(s, (uch)((ush)(w) >> 8));
7372 s.pending_buf[s.pending++] = (w) & 0xff;
7373 s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
7374}
7375
7376
7377/* ===========================================================================
7378 * Send a value on a given number of bits.
7379 * IN assertion: length <= 16 and value fits in length bits.
7380 */
7381function send_bits(s, value, length) {
7382 if (s.bi_valid > (Buf_size - length)) {
7383 s.bi_buf |= (value << s.bi_valid) & 0xffff;
7384 put_short(s, s.bi_buf);
7385 s.bi_buf = value >> (Buf_size - s.bi_valid);
7386 s.bi_valid += length - Buf_size;
7387 } else {
7388 s.bi_buf |= (value << s.bi_valid) & 0xffff;
7389 s.bi_valid += length;
7390 }
7391}
7392
7393
7394function send_code(s, c, tree) {
7395 send_bits(s, tree[c * 2] /*.Code*/ , tree[c * 2 + 1] /*.Len*/ );
7396}
7397
7398
7399/* ===========================================================================
7400 * Reverse the first len bits of a code, using straightforward code (a faster
7401 * method would use a table)
7402 * IN assertion: 1 <= len <= 15
7403 */
7404function bi_reverse(code, len) {
7405 var res = 0;
7406 do {
7407 res |= code & 1;
7408 code >>>= 1;
7409 res <<= 1;
7410 } while (--len > 0);
7411 return res >>> 1;
7412}
7413
7414
7415/* ===========================================================================
7416 * Flush the bit buffer, keeping at most 7 bits in it.
7417 */
7418function bi_flush(s) {
7419 if (s.bi_valid === 16) {
7420 put_short(s, s.bi_buf);
7421 s.bi_buf = 0;
7422 s.bi_valid = 0;
7423
7424 } else if (s.bi_valid >= 8) {
7425 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
7426 s.bi_buf >>= 8;
7427 s.bi_valid -= 8;
7428 }
7429}
7430
7431
7432/* ===========================================================================
7433 * Compute the optimal bit lengths for a tree and update the total bit length
7434 * for the current block.
7435 * IN assertion: the fields freq and dad are set, heap[heap_max] and
7436 * above are the tree nodes sorted by increasing frequency.
7437 * OUT assertions: the field len is set to the optimal bit length, the
7438 * array bl_count contains the frequencies for each bit length.
7439 * The length opt_len is updated; static_len is also updated if stree is
7440 * not null.
7441 */
7442function gen_bitlen(s, desc) {
7443// deflate_state *s;
7444// tree_desc *desc; /* the tree descriptor */
7445 var tree = desc.dyn_tree;
7446 var max_code = desc.max_code;
7447 var stree = desc.stat_desc.static_tree;
7448 var has_stree = desc.stat_desc.has_stree;
7449 var extra = desc.stat_desc.extra_bits;
7450 var base = desc.stat_desc.extra_base;
7451 var max_length = desc.stat_desc.max_length;
7452 var h; /* heap index */
7453 var n, m; /* iterate over the tree elements */
7454 var bits; /* bit length */
7455 var xbits; /* extra bits */
7456 var f; /* frequency */
7457 var overflow = 0; /* number of elements with bit length too large */
7458
7459 for (bits = 0; bits <= MAX_BITS; bits++) {
7460 s.bl_count[bits] = 0;
7461 }
7462
7463 /* In a first pass, compute the optimal bit lengths (which may
7464 * overflow in the case of the bit length tree).
7465 */
7466 tree[s.heap[s.heap_max] * 2 + 1] /*.Len*/ = 0; /* root of the heap */
7467
7468 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
7469 n = s.heap[h];
7470 bits = tree[tree[n * 2 + 1] /*.Dad*/ * 2 + 1] /*.Len*/ + 1;
7471 if (bits > max_length) {
7472 bits = max_length;
7473 overflow++;
7474 }
7475 tree[n * 2 + 1] /*.Len*/ = bits;
7476 /* We overwrite tree[n].Dad which is no longer needed */
7477
7478 if (n > max_code) {
7479 continue;
7480 } /* not a leaf node */
7481
7482 s.bl_count[bits]++;
7483 xbits = 0;
7484 if (n >= base) {
7485 xbits = extra[n - base];
7486 }
7487 f = tree[n * 2] /*.Freq*/ ;
7488 s.opt_len += f * (bits + xbits);
7489 if (has_stree) {
7490 s.static_len += f * (stree[n * 2 + 1] /*.Len*/ + xbits);
7491 }
7492 }
7493 if (overflow === 0) {
7494 return;
7495 }
7496
7497 // Trace((stderr,"\nbit length overflow\n"));
7498 /* This happens for example on obj2 and pic of the Calgary corpus */
7499
7500 /* Find the first bit length which could increase: */
7501 do {
7502 bits = max_length - 1;
7503 while (s.bl_count[bits] === 0) {
7504 bits--;
7505 }
7506 s.bl_count[bits]--; /* move one leaf down the tree */
7507 s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
7508 s.bl_count[max_length]--;
7509 /* The brother of the overflow item also moves one step up,
7510 * but this does not affect bl_count[max_length]
7511 */
7512 overflow -= 2;
7513 } while (overflow > 0);
7514
7515 /* Now recompute all bit lengths, scanning in increasing frequency.
7516 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
7517 * lengths instead of fixing only the wrong ones. This idea is taken
7518 * from 'ar' written by Haruhiko Okumura.)
7519 */
7520 for (bits = max_length; bits !== 0; bits--) {
7521 n = s.bl_count[bits];
7522 while (n !== 0) {
7523 m = s.heap[--h];
7524 if (m > max_code) {
7525 continue;
7526 }
7527 if (tree[m * 2 + 1] /*.Len*/ !== bits) {
7528 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
7529 s.opt_len += (bits - tree[m * 2 + 1] /*.Len*/ ) * tree[m * 2] /*.Freq*/ ;
7530 tree[m * 2 + 1] /*.Len*/ = bits;
7531 }
7532 n--;
7533 }
7534 }
7535}
7536
7537
7538/* ===========================================================================
7539 * Generate the codes for a given tree and bit counts (which need not be
7540 * optimal).
7541 * IN assertion: the array bl_count contains the bit length statistics for
7542 * the given tree and the field len is set for all tree elements.
7543 * OUT assertion: the field code is set for all tree elements of non
7544 * zero code length.
7545 */
7546function gen_codes(tree, max_code, bl_count) {
7547// ct_data *tree; /* the tree to decorate */
7548// int max_code; /* largest code with non zero frequency */
7549// ushf *bl_count; /* number of codes at each bit length */
7550
7551 var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
7552 var code = 0; /* running code value */
7553 var bits; /* bit index */
7554 var n; /* code index */
7555
7556 /* The distribution counts are first used to generate the code values
7557 * without bit reversal.
7558 */
7559 for (bits = 1; bits <= MAX_BITS; bits++) {
7560 next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
7561 }
7562 /* Check that the bit counts in bl_count are consistent. The last code
7563 * must be all ones.
7564 */
7565 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
7566 // "inconsistent bit counts");
7567 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
7568
7569 for (n = 0; n <= max_code; n++) {
7570 var len = tree[n * 2 + 1] /*.Len*/ ;
7571 if (len === 0) {
7572 continue;
7573 }
7574 /* Now reverse the bits */
7575 tree[n * 2] /*.Code*/ = bi_reverse(next_code[len]++, len);
7576
7577 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
7578 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
7579 }
7580}
7581
7582
7583/* ===========================================================================
7584 * Initialize the various 'constant' tables.
7585 */
7586function tr_static_init() {
7587 var n; /* iterates over tree elements */
7588 var bits; /* bit counter */
7589 var length; /* length value */
7590 var code; /* code value */
7591 var dist; /* distance index */
7592 var bl_count = new Array(MAX_BITS + 1);
7593 /* number of codes at each bit length for an optimal tree */
7594
7595 // do check in _tr_init()
7596 //if (static_init_done) return;
7597
7598 /* For some embedded targets, global variables are not initialized: */
7599 /*#ifdef NO_INIT_GLOBAL_POINTERS
7600 static_l_desc.static_tree = static_ltree;
7601 static_l_desc.extra_bits = extra_lbits;
7602 static_d_desc.static_tree = static_dtree;
7603 static_d_desc.extra_bits = extra_dbits;
7604 static_bl_desc.extra_bits = extra_blbits;
7605 #endif*/
7606
7607 /* Initialize the mapping length (0..255) -> length code (0..28) */
7608 length = 0;
7609 for (code = 0; code < LENGTH_CODES - 1; code++) {
7610 base_length[code] = length;
7611 for (n = 0; n < (1 << extra_lbits[code]); n++) {
7612 _length_code[length++] = code;
7613 }
7614 }
7615 //Assert (length == 256, "tr_static_init: length != 256");
7616 /* Note that the length 255 (match length 258) can be represented
7617 * in two different ways: code 284 + 5 bits or code 285, so we
7618 * overwrite length_code[255] to use the best encoding:
7619 */
7620 _length_code[length - 1] = code;
7621
7622 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
7623 dist = 0;
7624 for (code = 0; code < 16; code++) {
7625 base_dist[code] = dist;
7626 for (n = 0; n < (1 << extra_dbits[code]); n++) {
7627 _dist_code[dist++] = code;
7628 }
7629 }
7630 //Assert (dist == 256, "tr_static_init: dist != 256");
7631 dist >>= 7; /* from now on, all distances are divided by 128 */
7632 for (; code < D_CODES; code++) {
7633 base_dist[code] = dist << 7;
7634 for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
7635 _dist_code[256 + dist++] = code;
7636 }
7637 }
7638 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
7639
7640 /* Construct the codes of the static literal tree */
7641 for (bits = 0; bits <= MAX_BITS; bits++) {
7642 bl_count[bits] = 0;
7643 }
7644
7645 n = 0;
7646 while (n <= 143) {
7647 static_ltree[n * 2 + 1] /*.Len*/ = 8;
7648 n++;
7649 bl_count[8]++;
7650 }
7651 while (n <= 255) {
7652 static_ltree[n * 2 + 1] /*.Len*/ = 9;
7653 n++;
7654 bl_count[9]++;
7655 }
7656 while (n <= 279) {
7657 static_ltree[n * 2 + 1] /*.Len*/ = 7;
7658 n++;
7659 bl_count[7]++;
7660 }
7661 while (n <= 287) {
7662 static_ltree[n * 2 + 1] /*.Len*/ = 8;
7663 n++;
7664 bl_count[8]++;
7665 }
7666 /* Codes 286 and 287 do not exist, but we must include them in the
7667 * tree construction to get a canonical Huffman tree (longest code
7668 * all ones)
7669 */
7670 gen_codes(static_ltree, L_CODES + 1, bl_count);
7671
7672 /* The static distance tree is trivial: */
7673 for (n = 0; n < D_CODES; n++) {
7674 static_dtree[n * 2 + 1] /*.Len*/ = 5;
7675 static_dtree[n * 2] /*.Code*/ = bi_reverse(n, 5);
7676 }
7677
7678 // Now data ready and we can init static trees
7679 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
7680 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
7681 static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
7682
7683 //static_init_done = true;
7684}
7685
7686
7687/* ===========================================================================
7688 * Initialize a new block.
7689 */
7690function init_block(s) {
7691 var n; /* iterates over tree elements */
7692
7693 /* Initialize the trees. */
7694 for (n = 0; n < L_CODES; n++) {
7695 s.dyn_ltree[n * 2] /*.Freq*/ = 0;
7696 }
7697 for (n = 0; n < D_CODES; n++) {
7698 s.dyn_dtree[n * 2] /*.Freq*/ = 0;
7699 }
7700 for (n = 0; n < BL_CODES; n++) {
7701 s.bl_tree[n * 2] /*.Freq*/ = 0;
7702 }
7703
7704 s.dyn_ltree[END_BLOCK * 2] /*.Freq*/ = 1;
7705 s.opt_len = s.static_len = 0;
7706 s.last_lit = s.matches = 0;
7707}
7708
7709
7710/* ===========================================================================
7711 * Flush the bit buffer and align the output on a byte boundary
7712 */
7713function bi_windup(s) {
7714 if (s.bi_valid > 8) {
7715 put_short(s, s.bi_buf);
7716 } else if (s.bi_valid > 0) {
7717 //put_byte(s, (Byte)s->bi_buf);
7718 s.pending_buf[s.pending++] = s.bi_buf;
7719 }
7720 s.bi_buf = 0;
7721 s.bi_valid = 0;
7722}
7723
7724/* ===========================================================================
7725 * Copy a stored block, storing first the length and its
7726 * one's complement if requested.
7727 */
7728function copy_block(s, buf, len, header) {
7729//DeflateState *s;
7730//charf *buf; /* the input data */
7731//unsigned len; /* its length */
7732//int header; /* true if block header must be written */
7733
7734 bi_windup(s); /* align on byte boundary */
7735
7736 if (header) {
7737 put_short(s, len);
7738 put_short(s, ~len);
7739 }
7740 // while (len--) {
7741 // put_byte(s, *buf++);
7742 // }
7743 arraySet(s.pending_buf, s.window, buf, len, s.pending);
7744 s.pending += len;
7745}
7746
7747/* ===========================================================================
7748 * Compares to subtrees, using the tree depth as tie breaker when
7749 * the subtrees have equal frequency. This minimizes the worst case length.
7750 */
7751function smaller(tree, n, m, depth) {
7752 var _n2 = n * 2;
7753 var _m2 = m * 2;
7754 return (tree[_n2] /*.Freq*/ < tree[_m2] /*.Freq*/ ||
7755 (tree[_n2] /*.Freq*/ === tree[_m2] /*.Freq*/ && depth[n] <= depth[m]));
7756}
7757
7758/* ===========================================================================
7759 * Restore the heap property by moving down the tree starting at node k,
7760 * exchanging a node with the smallest of its two sons if necessary, stopping
7761 * when the heap property is re-established (each father smaller than its
7762 * two sons).
7763 */
7764function pqdownheap(s, tree, k)
7765// deflate_state *s;
7766// ct_data *tree; /* the tree to restore */
7767// int k; /* node to move down */
7768{
7769 var v = s.heap[k];
7770 var j = k << 1; /* left son of k */
7771 while (j <= s.heap_len) {
7772 /* Set j to the smallest of the two sons: */
7773 if (j < s.heap_len &&
7774 smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
7775 j++;
7776 }
7777 /* Exit if v is smaller than both sons */
7778 if (smaller(tree, v, s.heap[j], s.depth)) {
7779 break;
7780 }
7781
7782 /* Exchange v with the smallest son */
7783 s.heap[k] = s.heap[j];
7784 k = j;
7785
7786 /* And continue down the tree, setting j to the left son of k */
7787 j <<= 1;
7788 }
7789 s.heap[k] = v;
7790}
7791
7792
7793// inlined manually
7794// var SMALLEST = 1;
7795
7796/* ===========================================================================
7797 * Send the block data compressed using the given Huffman trees
7798 */
7799function compress_block(s, ltree, dtree)
7800// deflate_state *s;
7801// const ct_data *ltree; /* literal tree */
7802// const ct_data *dtree; /* distance tree */
7803{
7804 var dist; /* distance of matched string */
7805 var lc; /* match length or unmatched char (if dist == 0) */
7806 var lx = 0; /* running index in l_buf */
7807 var code; /* the code to send */
7808 var extra; /* number of extra bits to send */
7809
7810 if (s.last_lit !== 0) {
7811 do {
7812 dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
7813 lc = s.pending_buf[s.l_buf + lx];
7814 lx++;
7815
7816 if (dist === 0) {
7817 send_code(s, lc, ltree); /* send a literal byte */
7818 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
7819 } else {
7820 /* Here, lc is the match length - MIN_MATCH */
7821 code = _length_code[lc];
7822 send_code(s, code + LITERALS + 1, ltree); /* send the length code */
7823 extra = extra_lbits[code];
7824 if (extra !== 0) {
7825 lc -= base_length[code];
7826 send_bits(s, lc, extra); /* send the extra length bits */
7827 }
7828 dist--; /* dist is now the match distance - 1 */
7829 code = d_code(dist);
7830 //Assert (code < D_CODES, "bad d_code");
7831
7832 send_code(s, code, dtree); /* send the distance code */
7833 extra = extra_dbits[code];
7834 if (extra !== 0) {
7835 dist -= base_dist[code];
7836 send_bits(s, dist, extra); /* send the extra distance bits */
7837 }
7838 } /* literal or match pair ? */
7839
7840 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
7841 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
7842 // "pendingBuf overflow");
7843
7844 } while (lx < s.last_lit);
7845 }
7846
7847 send_code(s, END_BLOCK, ltree);
7848}
7849
7850
7851/* ===========================================================================
7852 * Construct one Huffman tree and assigns the code bit strings and lengths.
7853 * Update the total bit length for the current block.
7854 * IN assertion: the field freq is set for all tree elements.
7855 * OUT assertions: the fields len and code are set to the optimal bit length
7856 * and corresponding code. The length opt_len is updated; static_len is
7857 * also updated if stree is not null. The field max_code is set.
7858 */
7859function build_tree(s, desc)
7860// deflate_state *s;
7861// tree_desc *desc; /* the tree descriptor */
7862{
7863 var tree = desc.dyn_tree;
7864 var stree = desc.stat_desc.static_tree;
7865 var has_stree = desc.stat_desc.has_stree;
7866 var elems = desc.stat_desc.elems;
7867 var n, m; /* iterate over heap elements */
7868 var max_code = -1; /* largest code with non zero frequency */
7869 var node; /* new node being created */
7870
7871 /* Construct the initial heap, with least frequent element in
7872 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
7873 * heap[0] is not used.
7874 */
7875 s.heap_len = 0;
7876 s.heap_max = HEAP_SIZE;
7877
7878 for (n = 0; n < elems; n++) {
7879 if (tree[n * 2] /*.Freq*/ !== 0) {
7880 s.heap[++s.heap_len] = max_code = n;
7881 s.depth[n] = 0;
7882
7883 } else {
7884 tree[n * 2 + 1] /*.Len*/ = 0;
7885 }
7886 }
7887
7888 /* The pkzip format requires that at least one distance code exists,
7889 * and that at least one bit should be sent even if there is only one
7890 * possible code. So to avoid special checks later on we force at least
7891 * two codes of non zero frequency.
7892 */
7893 while (s.heap_len < 2) {
7894 node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
7895 tree[node * 2] /*.Freq*/ = 1;
7896 s.depth[node] = 0;
7897 s.opt_len--;
7898
7899 if (has_stree) {
7900 s.static_len -= stree[node * 2 + 1] /*.Len*/ ;
7901 }
7902 /* node is 0 or 1 so it does not have extra bits */
7903 }
7904 desc.max_code = max_code;
7905
7906 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
7907 * establish sub-heaps of increasing lengths:
7908 */
7909 for (n = (s.heap_len >> 1 /*int /2*/ ); n >= 1; n--) {
7910 pqdownheap(s, tree, n);
7911 }
7912
7913 /* Construct the Huffman tree by repeatedly combining the least two
7914 * frequent nodes.
7915 */
7916 node = elems; /* next internal node of the tree */
7917 do {
7918 //pqremove(s, tree, n); /* n = node of least frequency */
7919 /*** pqremove ***/
7920 n = s.heap[1 /*SMALLEST*/ ];
7921 s.heap[1 /*SMALLEST*/ ] = s.heap[s.heap_len--];
7922 pqdownheap(s, tree, 1 /*SMALLEST*/ );
7923 /***/
7924
7925 m = s.heap[1 /*SMALLEST*/ ]; /* m = node of next least frequency */
7926
7927 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
7928 s.heap[--s.heap_max] = m;
7929
7930 /* Create a new node father of n and m */
7931 tree[node * 2] /*.Freq*/ = tree[n * 2] /*.Freq*/ + tree[m * 2] /*.Freq*/ ;
7932 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
7933 tree[n * 2 + 1] /*.Dad*/ = tree[m * 2 + 1] /*.Dad*/ = node;
7934
7935 /* and insert the new node in the heap */
7936 s.heap[1 /*SMALLEST*/ ] = node++;
7937 pqdownheap(s, tree, 1 /*SMALLEST*/ );
7938
7939 } while (s.heap_len >= 2);
7940
7941 s.heap[--s.heap_max] = s.heap[1 /*SMALLEST*/ ];
7942
7943 /* At this point, the fields freq and dad are set. We can now
7944 * generate the bit lengths.
7945 */
7946 gen_bitlen(s, desc);
7947
7948 /* The field len is now set, we can generate the bit codes */
7949 gen_codes(tree, max_code, s.bl_count);
7950}
7951
7952
7953/* ===========================================================================
7954 * Scan a literal or distance tree to determine the frequencies of the codes
7955 * in the bit length tree.
7956 */
7957function scan_tree(s, tree, max_code)
7958// deflate_state *s;
7959// ct_data *tree; /* the tree to be scanned */
7960// int max_code; /* and its largest code of non zero frequency */
7961{
7962 var n; /* iterates over all tree elements */
7963 var prevlen = -1; /* last emitted length */
7964 var curlen; /* length of current code */
7965
7966 var nextlen = tree[0 * 2 + 1] /*.Len*/ ; /* length of next code */
7967
7968 var count = 0; /* repeat count of the current code */
7969 var max_count = 7; /* max repeat count */
7970 var min_count = 4; /* min repeat count */
7971
7972 if (nextlen === 0) {
7973 max_count = 138;
7974 min_count = 3;
7975 }
7976 tree[(max_code + 1) * 2 + 1] /*.Len*/ = 0xffff; /* guard */
7977
7978 for (n = 0; n <= max_code; n++) {
7979 curlen = nextlen;
7980 nextlen = tree[(n + 1) * 2 + 1] /*.Len*/ ;
7981
7982 if (++count < max_count && curlen === nextlen) {
7983 continue;
7984
7985 } else if (count < min_count) {
7986 s.bl_tree[curlen * 2] /*.Freq*/ += count;
7987
7988 } else if (curlen !== 0) {
7989
7990 if (curlen !== prevlen) {
7991 s.bl_tree[curlen * 2] /*.Freq*/ ++;
7992 }
7993 s.bl_tree[REP_3_6 * 2] /*.Freq*/ ++;
7994
7995 } else if (count <= 10) {
7996 s.bl_tree[REPZ_3_10 * 2] /*.Freq*/ ++;
7997
7998 } else {
7999 s.bl_tree[REPZ_11_138 * 2] /*.Freq*/ ++;
8000 }
8001
8002 count = 0;
8003 prevlen = curlen;
8004
8005 if (nextlen === 0) {
8006 max_count = 138;
8007 min_count = 3;
8008
8009 } else if (curlen === nextlen) {
8010 max_count = 6;
8011 min_count = 3;
8012
8013 } else {
8014 max_count = 7;
8015 min_count = 4;
8016 }
8017 }
8018}
8019
8020
8021/* ===========================================================================
8022 * Send a literal or distance tree in compressed form, using the codes in
8023 * bl_tree.
8024 */
8025function send_tree(s, tree, max_code)
8026// deflate_state *s;
8027// ct_data *tree; /* the tree to be scanned */
8028// int max_code; /* and its largest code of non zero frequency */
8029{
8030 var n; /* iterates over all tree elements */
8031 var prevlen = -1; /* last emitted length */
8032 var curlen; /* length of current code */
8033
8034 var nextlen = tree[0 * 2 + 1] /*.Len*/ ; /* length of next code */
8035
8036 var count = 0; /* repeat count of the current code */
8037 var max_count = 7; /* max repeat count */
8038 var min_count = 4; /* min repeat count */
8039
8040 /* tree[max_code+1].Len = -1; */
8041 /* guard already set */
8042 if (nextlen === 0) {
8043 max_count = 138;
8044 min_count = 3;
8045 }
8046
8047 for (n = 0; n <= max_code; n++) {
8048 curlen = nextlen;
8049 nextlen = tree[(n + 1) * 2 + 1] /*.Len*/ ;
8050
8051 if (++count < max_count && curlen === nextlen) {
8052 continue;
8053
8054 } else if (count < min_count) {
8055 do {
8056 send_code(s, curlen, s.bl_tree);
8057 } while (--count !== 0);
8058
8059 } else if (curlen !== 0) {
8060 if (curlen !== prevlen) {
8061 send_code(s, curlen, s.bl_tree);
8062 count--;
8063 }
8064 //Assert(count >= 3 && count <= 6, " 3_6?");
8065 send_code(s, REP_3_6, s.bl_tree);
8066 send_bits(s, count - 3, 2);
8067
8068 } else if (count <= 10) {
8069 send_code(s, REPZ_3_10, s.bl_tree);
8070 send_bits(s, count - 3, 3);
8071
8072 } else {
8073 send_code(s, REPZ_11_138, s.bl_tree);
8074 send_bits(s, count - 11, 7);
8075 }
8076
8077 count = 0;
8078 prevlen = curlen;
8079 if (nextlen === 0) {
8080 max_count = 138;
8081 min_count = 3;
8082
8083 } else if (curlen === nextlen) {
8084 max_count = 6;
8085 min_count = 3;
8086
8087 } else {
8088 max_count = 7;
8089 min_count = 4;
8090 }
8091 }
8092}
8093
8094
8095/* ===========================================================================
8096 * Construct the Huffman tree for the bit lengths and return the index in
8097 * bl_order of the last bit length code to send.
8098 */
8099function build_bl_tree(s) {
8100 var max_blindex; /* index of last bit length code of non zero freq */
8101
8102 /* Determine the bit length frequencies for literal and distance trees */
8103 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
8104 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
8105
8106 /* Build the bit length tree: */
8107 build_tree(s, s.bl_desc);
8108 /* opt_len now includes the length of the tree representations, except
8109 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
8110 */
8111
8112 /* Determine the number of bit length codes to send. The pkzip format
8113 * requires that at least 4 bit length codes be sent. (appnote.txt says
8114 * 3 but the actual value used is 4.)
8115 */
8116 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
8117 if (s.bl_tree[bl_order[max_blindex] * 2 + 1] /*.Len*/ !== 0) {
8118 break;
8119 }
8120 }
8121 /* Update opt_len to include the bit length tree and counts */
8122 s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
8123 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
8124 // s->opt_len, s->static_len));
8125
8126 return max_blindex;
8127}
8128
8129
8130/* ===========================================================================
8131 * Send the header for a block using dynamic Huffman trees: the counts, the
8132 * lengths of the bit length codes, the literal tree and the distance tree.
8133 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
8134 */
8135function send_all_trees(s, lcodes, dcodes, blcodes)
8136// deflate_state *s;
8137// int lcodes, dcodes, blcodes; /* number of codes for each tree */
8138{
8139 var rank; /* index in bl_order */
8140
8141 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
8142 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
8143 // "too many codes");
8144 //Tracev((stderr, "\nbl counts: "));
8145 send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
8146 send_bits(s, dcodes - 1, 5);
8147 send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
8148 for (rank = 0; rank < blcodes; rank++) {
8149 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
8150 send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1] /*.Len*/ , 3);
8151 }
8152 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
8153
8154 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
8155 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
8156
8157 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
8158 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
8159}
8160
8161
8162/* ===========================================================================
8163 * Check if the data type is TEXT or BINARY, using the following algorithm:
8164 * - TEXT if the two conditions below are satisfied:
8165 * a) There are no non-portable control characters belonging to the
8166 * "black list" (0..6, 14..25, 28..31).
8167 * b) There is at least one printable character belonging to the
8168 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
8169 * - BINARY otherwise.
8170 * - The following partially-portable control characters form a
8171 * "gray list" that is ignored in this detection algorithm:
8172 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
8173 * IN assertion: the fields Freq of dyn_ltree are set.
8174 */
8175function detect_data_type(s) {
8176 /* black_mask is the bit mask of black-listed bytes
8177 * set bits 0..6, 14..25, and 28..31
8178 * 0xf3ffc07f = binary 11110011111111111100000001111111
8179 */
8180 var black_mask = 0xf3ffc07f;
8181 var n;
8182
8183 /* Check for non-textual ("black-listed") bytes. */
8184 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
8185 if ((black_mask & 1) && (s.dyn_ltree[n * 2] /*.Freq*/ !== 0)) {
8186 return Z_BINARY;
8187 }
8188 }
8189
8190 /* Check for textual ("white-listed") bytes. */
8191 if (s.dyn_ltree[9 * 2] /*.Freq*/ !== 0 || s.dyn_ltree[10 * 2] /*.Freq*/ !== 0 ||
8192 s.dyn_ltree[13 * 2] /*.Freq*/ !== 0) {
8193 return Z_TEXT;
8194 }
8195 for (n = 32; n < LITERALS; n++) {
8196 if (s.dyn_ltree[n * 2] /*.Freq*/ !== 0) {
8197 return Z_TEXT;
8198 }
8199 }
8200
8201 /* There are no "black-listed" or "white-listed" bytes:
8202 * this stream either is empty or has tolerated ("gray-listed") bytes only.
8203 */
8204 return Z_BINARY;
8205}
8206
8207
8208var static_init_done = false;
8209
8210/* ===========================================================================
8211 * Initialize the tree data structures for a new zlib stream.
8212 */
8213function _tr_init(s) {
8214
8215 if (!static_init_done) {
8216 tr_static_init();
8217 static_init_done = true;
8218 }
8219
8220 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
8221 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
8222 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
8223
8224 s.bi_buf = 0;
8225 s.bi_valid = 0;
8226
8227 /* Initialize the first block of the first file: */
8228 init_block(s);
8229}
8230
8231
8232/* ===========================================================================
8233 * Send a stored block
8234 */
8235function _tr_stored_block(s, buf, stored_len, last)
8236//DeflateState *s;
8237//charf *buf; /* input block */
8238//ulg stored_len; /* length of input block */
8239//int last; /* one if this is the last block for a file */
8240{
8241 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
8242 copy_block(s, buf, stored_len, true); /* with header */
8243}
8244
8245
8246/* ===========================================================================
8247 * Send one empty static block to give enough lookahead for inflate.
8248 * This takes 10 bits, of which 7 may remain in the bit buffer.
8249 */
8250function _tr_align(s) {
8251 send_bits(s, STATIC_TREES << 1, 3);
8252 send_code(s, END_BLOCK, static_ltree);
8253 bi_flush(s);
8254}
8255
8256
8257/* ===========================================================================
8258 * Determine the best encoding for the current block: dynamic trees, static
8259 * trees or store, and output the encoded block to the zip file.
8260 */
8261function _tr_flush_block(s, buf, stored_len, last)
8262//DeflateState *s;
8263//charf *buf; /* input block, or NULL if too old */
8264//ulg stored_len; /* length of input block */
8265//int last; /* one if this is the last block for a file */
8266{
8267 var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
8268 var max_blindex = 0; /* index of last bit length code of non zero freq */
8269
8270 /* Build the Huffman trees unless a stored block is forced */
8271 if (s.level > 0) {
8272
8273 /* Check if the file is binary or text */
8274 if (s.strm.data_type === Z_UNKNOWN) {
8275 s.strm.data_type = detect_data_type(s);
8276 }
8277
8278 /* Construct the literal and distance trees */
8279 build_tree(s, s.l_desc);
8280 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
8281 // s->static_len));
8282
8283 build_tree(s, s.d_desc);
8284 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
8285 // s->static_len));
8286 /* At this point, opt_len and static_len are the total bit lengths of
8287 * the compressed block data, excluding the tree representations.
8288 */
8289
8290 /* Build the bit length tree for the above two trees, and get the index
8291 * in bl_order of the last bit length code to send.
8292 */
8293 max_blindex = build_bl_tree(s);
8294
8295 /* Determine the best encoding. Compute the block lengths in bytes. */
8296 opt_lenb = (s.opt_len + 3 + 7) >>> 3;
8297 static_lenb = (s.static_len + 3 + 7) >>> 3;
8298
8299 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
8300 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
8301 // s->last_lit));
8302
8303 if (static_lenb <= opt_lenb) {
8304 opt_lenb = static_lenb;
8305 }
8306
8307 } else {
8308 // Assert(buf != (char*)0, "lost buf");
8309 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
8310 }
8311
8312 if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
8313 /* 4: two words for the lengths */
8314
8315 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
8316 * Otherwise we can't have processed more than WSIZE input bytes since
8317 * the last block flush, because compression would have been
8318 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
8319 * transform a block into a stored block.
8320 */
8321 _tr_stored_block(s, buf, stored_len, last);
8322
8323 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
8324
8325 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
8326 compress_block(s, static_ltree, static_dtree);
8327
8328 } else {
8329 send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
8330 send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
8331 compress_block(s, s.dyn_ltree, s.dyn_dtree);
8332 }
8333 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
8334 /* The above check is made mod 2^32, for files larger than 512 MB
8335 * and uLong implemented on 32 bits.
8336 */
8337 init_block(s);
8338
8339 if (last) {
8340 bi_windup(s);
8341 }
8342 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
8343 // s->compressed_len-7*last));
8344}
8345
8346/* ===========================================================================
8347 * Save the match info and tally the frequency counts. Return true if
8348 * the current block must be flushed.
8349 */
8350function _tr_tally(s, dist, lc)
8351// deflate_state *s;
8352// unsigned dist; /* distance of matched string */
8353// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
8354{
8355 //var out_length, in_length, dcode;
8356
8357 s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
8358 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
8359
8360 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
8361 s.last_lit++;
8362
8363 if (dist === 0) {
8364 /* lc is the unmatched char */
8365 s.dyn_ltree[lc * 2] /*.Freq*/ ++;
8366 } else {
8367 s.matches++;
8368 /* Here, lc is the match length - MIN_MATCH */
8369 dist--; /* dist = match distance - 1 */
8370 //Assert((ush)dist < (ush)MAX_DIST(s) &&
8371 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
8372 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
8373
8374 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2] /*.Freq*/ ++;
8375 s.dyn_dtree[d_code(dist) * 2] /*.Freq*/ ++;
8376 }
8377
8378 // (!) This block is disabled in zlib defailts,
8379 // don't enable it for binary compatibility
8380
8381 //#ifdef TRUNCATE_BLOCK
8382 // /* Try to guess if it is profitable to stop the current block here */
8383 // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
8384 // /* Compute an upper bound for the compressed length */
8385 // out_length = s.last_lit*8;
8386 // in_length = s.strstart - s.block_start;
8387 //
8388 // for (dcode = 0; dcode < D_CODES; dcode++) {
8389 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
8390 // }
8391 // out_length >>>= 3;
8392 // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
8393 // // s->last_lit, in_length, out_length,
8394 // // 100L - out_length*100L/in_length));
8395 // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
8396 // return true;
8397 // }
8398 // }
8399 //#endif
8400
8401 return (s.last_lit === s.lit_bufsize - 1);
8402 /* We avoid equality with lit_bufsize because of wraparound at 64K
8403 * on 16 bit machines and because stored blocks are restricted to
8404 * 64K-1 bytes.
8405 */
8406}
8407
8408// Note: adler32 takes 12% for level 0 and 2% for level 6.
8409// It doesn't worth to make additional optimizationa as in original.
8410// Small size is preferable.
8411
8412function adler32(adler, buf, len, pos) {
8413 var s1 = (adler & 0xffff) |0,
8414 s2 = ((adler >>> 16) & 0xffff) |0,
8415 n = 0;
8416
8417 while (len !== 0) {
8418 // Set limit ~ twice less than 5552, to keep
8419 // s2 in 31-bits, because we force signed ints.
8420 // in other case %= will fail.
8421 n = len > 2000 ? 2000 : len;
8422 len -= n;
8423
8424 do {
8425 s1 = (s1 + buf[pos++]) |0;
8426 s2 = (s2 + s1) |0;
8427 } while (--n);
8428
8429 s1 %= 65521;
8430 s2 %= 65521;
8431 }
8432
8433 return (s1 | (s2 << 16)) |0;
8434}
8435
8436// Note: we can't get significant speed boost here.
8437// So write code to minimize size - no pregenerated tables
8438// and array tools dependencies.
8439
8440
8441// Use ordinary array, since untyped makes no boost here
8442function makeTable() {
8443 var c, table = [];
8444
8445 for (var n = 0; n < 256; n++) {
8446 c = n;
8447 for (var k = 0; k < 8; k++) {
8448 c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
8449 }
8450 table[n] = c;
8451 }
8452
8453 return table;
8454}
8455
8456// Create table on load. Just 255 signed longs. Not a problem.
8457var crcTable = makeTable();
8458
8459
8460function crc32(crc, buf, len, pos) {
8461 var t = crcTable,
8462 end = pos + len;
8463
8464 crc ^= -1;
8465
8466 for (var i = pos; i < end; i++) {
8467 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
8468 }
8469
8470 return (crc ^ (-1)); // >>> 0;
8471}
8472
8473/* Public constants ==========================================================*/
8474/* ===========================================================================*/
8475
8476
8477/* Allowed flush values; see deflate() and inflate() below for details */
8478var Z_NO_FLUSH = 0;
8479var Z_PARTIAL_FLUSH = 1;
8480//var Z_SYNC_FLUSH = 2;
8481var Z_FULL_FLUSH = 3;
8482var Z_FINISH = 4;
8483var Z_BLOCK = 5;
8484//var Z_TREES = 6;
8485
8486
8487/* Return codes for the compression/decompression functions. Negative values
8488 * are errors, positive values are used for special but normal events.
8489 */
8490var Z_OK = 0;
8491var Z_STREAM_END = 1;
8492//var Z_NEED_DICT = 2;
8493//var Z_ERRNO = -1;
8494var Z_STREAM_ERROR = -2;
8495var Z_DATA_ERROR = -3;
8496//var Z_MEM_ERROR = -4;
8497var Z_BUF_ERROR = -5;
8498//var Z_VERSION_ERROR = -6;
8499
8500
8501/* compression levels */
8502//var Z_NO_COMPRESSION = 0;
8503//var Z_BEST_SPEED = 1;
8504//var Z_BEST_COMPRESSION = 9;
8505var Z_DEFAULT_COMPRESSION = -1;
8506
8507
8508var Z_FILTERED = 1;
8509var Z_HUFFMAN_ONLY = 2;
8510var Z_RLE = 3;
8511var Z_FIXED$1 = 4;
8512
8513/* Possible values of the data_type field (though see inflate()) */
8514//var Z_BINARY = 0;
8515//var Z_TEXT = 1;
8516//var Z_ASCII = 1; // = Z_TEXT
8517var Z_UNKNOWN$1 = 2;
8518
8519
8520/* The deflate compression method */
8521var Z_DEFLATED = 8;
8522
8523/*============================================================================*/
8524
8525
8526var MAX_MEM_LEVEL = 9;
8527
8528
8529var LENGTH_CODES$1 = 29;
8530/* number of length codes, not counting the special END_BLOCK code */
8531var LITERALS$1 = 256;
8532/* number of literal bytes 0..255 */
8533var L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
8534/* number of Literal or Length codes, including the END_BLOCK code */
8535var D_CODES$1 = 30;
8536/* number of distance codes */
8537var BL_CODES$1 = 19;
8538/* number of codes used to transfer the bit lengths */
8539var HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
8540/* maximum heap size */
8541var MAX_BITS$1 = 15;
8542/* All codes must not exceed MAX_BITS bits */
8543
8544var MIN_MATCH$1 = 3;
8545var MAX_MATCH$1 = 258;
8546var MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1);
8547
8548var PRESET_DICT = 0x20;
8549
8550var INIT_STATE = 42;
8551var EXTRA_STATE = 69;
8552var NAME_STATE = 73;
8553var COMMENT_STATE = 91;
8554var HCRC_STATE = 103;
8555var BUSY_STATE = 113;
8556var FINISH_STATE = 666;
8557
8558var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
8559var BS_BLOCK_DONE = 2; /* block flush performed */
8560var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
8561var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
8562
8563var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
8564
8565function err(strm, errorCode) {
8566 strm.msg = msg[errorCode];
8567 return errorCode;
8568}
8569
8570function rank(f) {
8571 return ((f) << 1) - ((f) > 4 ? 9 : 0);
8572}
8573
8574function zero$1(buf) {
8575 var len = buf.length;
8576 while (--len >= 0) {
8577 buf[len] = 0;
8578 }
8579}
8580
8581
8582/* =========================================================================
8583 * Flush as much pending output as possible. All deflate() output goes
8584 * through this function so some applications may wish to modify it
8585 * to avoid allocating a large strm->output buffer and copying into it.
8586 * (See also read_buf()).
8587 */
8588function flush_pending(strm) {
8589 var s = strm.state;
8590
8591 //_tr_flush_bits(s);
8592 var len = s.pending;
8593 if (len > strm.avail_out) {
8594 len = strm.avail_out;
8595 }
8596 if (len === 0) {
8597 return;
8598 }
8599
8600 arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
8601 strm.next_out += len;
8602 s.pending_out += len;
8603 strm.total_out += len;
8604 strm.avail_out -= len;
8605 s.pending -= len;
8606 if (s.pending === 0) {
8607 s.pending_out = 0;
8608 }
8609}
8610
8611
8612function flush_block_only(s, last) {
8613 _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
8614 s.block_start = s.strstart;
8615 flush_pending(s.strm);
8616}
8617
8618
8619function put_byte(s, b) {
8620 s.pending_buf[s.pending++] = b;
8621}
8622
8623
8624/* =========================================================================
8625 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
8626 * IN assertion: the stream state is correct and there is enough room in
8627 * pending_buf.
8628 */
8629function putShortMSB(s, b) {
8630 // put_byte(s, (Byte)(b >> 8));
8631 // put_byte(s, (Byte)(b & 0xff));
8632 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
8633 s.pending_buf[s.pending++] = b & 0xff;
8634}
8635
8636
8637/* ===========================================================================
8638 * Read a new buffer from the current input stream, update the adler32
8639 * and total number of bytes read. All deflate() input goes through
8640 * this function so some applications may wish to modify it to avoid
8641 * allocating a large strm->input buffer and copying from it.
8642 * (See also flush_pending()).
8643 */
8644function read_buf(strm, buf, start, size) {
8645 var len = strm.avail_in;
8646
8647 if (len > size) {
8648 len = size;
8649 }
8650 if (len === 0) {
8651 return 0;
8652 }
8653
8654 strm.avail_in -= len;
8655
8656 // zmemcpy(buf, strm->next_in, len);
8657 arraySet(buf, strm.input, strm.next_in, len, start);
8658 if (strm.state.wrap === 1) {
8659 strm.adler = adler32(strm.adler, buf, len, start);
8660 } else if (strm.state.wrap === 2) {
8661 strm.adler = crc32(strm.adler, buf, len, start);
8662 }
8663
8664 strm.next_in += len;
8665 strm.total_in += len;
8666
8667 return len;
8668}
8669
8670
8671/* ===========================================================================
8672 * Set match_start to the longest match starting at the given string and
8673 * return its length. Matches shorter or equal to prev_length are discarded,
8674 * in which case the result is equal to prev_length and match_start is
8675 * garbage.
8676 * IN assertions: cur_match is the head of the hash chain for the current
8677 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
8678 * OUT assertion: the match length is not greater than s->lookahead.
8679 */
8680function longest_match(s, cur_match) {
8681 var chain_length = s.max_chain_length; /* max hash chain length */
8682 var scan = s.strstart; /* current string */
8683 var match; /* matched string */
8684 var len; /* length of current match */
8685 var best_len = s.prev_length; /* best match length so far */
8686 var nice_match = s.nice_match; /* stop if match long enough */
8687 var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
8688 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0 /*NIL*/ ;
8689
8690 var _win = s.window; // shortcut
8691
8692 var wmask = s.w_mask;
8693 var prev = s.prev;
8694
8695 /* Stop when cur_match becomes <= limit. To simplify the code,
8696 * we prevent matches with the string of window index 0.
8697 */
8698
8699 var strend = s.strstart + MAX_MATCH$1;
8700 var scan_end1 = _win[scan + best_len - 1];
8701 var scan_end = _win[scan + best_len];
8702
8703 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
8704 * It is easy to get rid of this optimization if necessary.
8705 */
8706 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
8707
8708 /* Do not waste too much time if we already have a good match: */
8709 if (s.prev_length >= s.good_match) {
8710 chain_length >>= 2;
8711 }
8712 /* Do not look for matches beyond the end of the input. This is necessary
8713 * to make deflate deterministic.
8714 */
8715 if (nice_match > s.lookahead) {
8716 nice_match = s.lookahead;
8717 }
8718
8719 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
8720
8721 do {
8722 // Assert(cur_match < s->strstart, "no future");
8723 match = cur_match;
8724
8725 /* Skip to next match if the match length cannot increase
8726 * or if the match length is less than 2. Note that the checks below
8727 * for insufficient lookahead only occur occasionally for performance
8728 * reasons. Therefore uninitialized memory will be accessed, and
8729 * conditional jumps will be made that depend on those values.
8730 * However the length of the match is limited to the lookahead, so
8731 * the output of deflate is not affected by the uninitialized values.
8732 */
8733
8734 if (_win[match + best_len] !== scan_end ||
8735 _win[match + best_len - 1] !== scan_end1 ||
8736 _win[match] !== _win[scan] ||
8737 _win[++match] !== _win[scan + 1]) {
8738 continue;
8739 }
8740
8741 /* The check at best_len-1 can be removed because it will be made
8742 * again later. (This heuristic is not always a win.)
8743 * It is not necessary to compare scan[2] and match[2] since they
8744 * are always equal when the other bytes match, given that
8745 * the hash keys are equal and that HASH_BITS >= 8.
8746 */
8747 scan += 2;
8748 match++;
8749 // Assert(*scan == *match, "match[2]?");
8750
8751 /* We check for insufficient lookahead only every 8th comparison;
8752 * the 256th check will be made at strstart+258.
8753 */
8754 do {
8755 /*jshint noempty:false*/
8756 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
8757 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
8758 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
8759 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
8760 scan < strend);
8761
8762 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
8763
8764 len = MAX_MATCH$1 - (strend - scan);
8765 scan = strend - MAX_MATCH$1;
8766
8767 if (len > best_len) {
8768 s.match_start = cur_match;
8769 best_len = len;
8770 if (len >= nice_match) {
8771 break;
8772 }
8773 scan_end1 = _win[scan + best_len - 1];
8774 scan_end = _win[scan + best_len];
8775 }
8776 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
8777
8778 if (best_len <= s.lookahead) {
8779 return best_len;
8780 }
8781 return s.lookahead;
8782}
8783
8784
8785/* ===========================================================================
8786 * Fill the window when the lookahead becomes insufficient.
8787 * Updates strstart and lookahead.
8788 *
8789 * IN assertion: lookahead < MIN_LOOKAHEAD
8790 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
8791 * At least one byte has been read, or avail_in == 0; reads are
8792 * performed for at least two bytes (required for the zip translate_eol
8793 * option -- not supported here).
8794 */
8795function fill_window(s) {
8796 var _w_size = s.w_size;
8797 var p, n, m, more, str;
8798
8799 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
8800
8801 do {
8802 more = s.window_size - s.lookahead - s.strstart;
8803
8804 // JS ints have 32 bit, block below not needed
8805 /* Deal with !@#$% 64K limit: */
8806 //if (sizeof(int) <= 2) {
8807 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
8808 // more = wsize;
8809 //
8810 // } else if (more == (unsigned)(-1)) {
8811 // /* Very unlikely, but possible on 16 bit machine if
8812 // * strstart == 0 && lookahead == 1 (input done a byte at time)
8813 // */
8814 // more--;
8815 // }
8816 //}
8817
8818
8819 /* If the window is almost full and there is insufficient lookahead,
8820 * move the upper half to the lower one to make room in the upper half.
8821 */
8822 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
8823
8824 arraySet(s.window, s.window, _w_size, _w_size, 0);
8825 s.match_start -= _w_size;
8826 s.strstart -= _w_size;
8827 /* we now have strstart >= MAX_DIST */
8828 s.block_start -= _w_size;
8829
8830 /* Slide the hash table (could be avoided with 32 bit values
8831 at the expense of memory usage). We slide even when level == 0
8832 to keep the hash table consistent if we switch back to level > 0
8833 later. (Using level 0 permanently is not an optimal usage of
8834 zlib, so we don't care about this pathological case.)
8835 */
8836
8837 n = s.hash_size;
8838 p = n;
8839 do {
8840 m = s.head[--p];
8841 s.head[p] = (m >= _w_size ? m - _w_size : 0);
8842 } while (--n);
8843
8844 n = _w_size;
8845 p = n;
8846 do {
8847 m = s.prev[--p];
8848 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
8849 /* If n is not on any hash chain, prev[n] is garbage but
8850 * its value will never be used.
8851 */
8852 } while (--n);
8853
8854 more += _w_size;
8855 }
8856 if (s.strm.avail_in === 0) {
8857 break;
8858 }
8859
8860 /* If there was no sliding:
8861 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
8862 * more == window_size - lookahead - strstart
8863 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
8864 * => more >= window_size - 2*WSIZE + 2
8865 * In the BIG_MEM or MMAP case (not yet supported),
8866 * window_size == input_size + MIN_LOOKAHEAD &&
8867 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
8868 * Otherwise, window_size == 2*WSIZE so more >= 2.
8869 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
8870 */
8871 //Assert(more >= 2, "more < 2");
8872 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
8873 s.lookahead += n;
8874
8875 /* Initialize the hash value now that we have some input: */
8876 if (s.lookahead + s.insert >= MIN_MATCH$1) {
8877 str = s.strstart - s.insert;
8878 s.ins_h = s.window[str];
8879
8880 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
8881 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
8882 //#if MIN_MATCH != 3
8883 // Call update_hash() MIN_MATCH-3 more times
8884 //#endif
8885 while (s.insert) {
8886 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
8887 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;
8888
8889 s.prev[str & s.w_mask] = s.head[s.ins_h];
8890 s.head[s.ins_h] = str;
8891 str++;
8892 s.insert--;
8893 if (s.lookahead + s.insert < MIN_MATCH$1) {
8894 break;
8895 }
8896 }
8897 }
8898 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
8899 * but this is not important since only literal bytes will be emitted.
8900 */
8901
8902 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
8903
8904 /* If the WIN_INIT bytes after the end of the current data have never been
8905 * written, then zero those bytes in order to avoid memory check reports of
8906 * the use of uninitialized (or uninitialised as Julian writes) bytes by
8907 * the longest match routines. Update the high water mark for the next
8908 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
8909 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
8910 */
8911 // if (s.high_water < s.window_size) {
8912 // var curr = s.strstart + s.lookahead;
8913 // var init = 0;
8914 //
8915 // if (s.high_water < curr) {
8916 // /* Previous high water mark below current data -- zero WIN_INIT
8917 // * bytes or up to end of window, whichever is less.
8918 // */
8919 // init = s.window_size - curr;
8920 // if (init > WIN_INIT)
8921 // init = WIN_INIT;
8922 // zmemzero(s->window + curr, (unsigned)init);
8923 // s->high_water = curr + init;
8924 // }
8925 // else if (s->high_water < (ulg)curr + WIN_INIT) {
8926 // /* High water mark at or above current data, but below current data
8927 // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
8928 // * to end of window, whichever is less.
8929 // */
8930 // init = (ulg)curr + WIN_INIT - s->high_water;
8931 // if (init > s->window_size - s->high_water)
8932 // init = s->window_size - s->high_water;
8933 // zmemzero(s->window + s->high_water, (unsigned)init);
8934 // s->high_water += init;
8935 // }
8936 // }
8937 //
8938 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
8939 // "not enough room for search");
8940}
8941
8942/* ===========================================================================
8943 * Copy without compression as much as possible from the input stream, return
8944 * the current block state.
8945 * This function does not insert new strings in the dictionary since
8946 * uncompressible data is probably not useful. This function is used
8947 * only for the level=0 compression option.
8948 * NOTE: this function should be optimized to avoid extra copying from
8949 * window to pending_buf.
8950 */
8951function deflate_stored(s, flush) {
8952 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
8953 * to pending_buf_size, and each stored block has a 5 byte header:
8954 */
8955 var max_block_size = 0xffff;
8956
8957 if (max_block_size > s.pending_buf_size - 5) {
8958 max_block_size = s.pending_buf_size - 5;
8959 }
8960
8961 /* Copy as much as possible from input to output: */
8962 for (;;) {
8963 /* Fill the window as much as possible: */
8964 if (s.lookahead <= 1) {
8965
8966 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
8967 // s->block_start >= (long)s->w_size, "slide too late");
8968 // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
8969 // s.block_start >= s.w_size)) {
8970 // throw new Error("slide too late");
8971 // }
8972
8973 fill_window(s);
8974 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
8975 return BS_NEED_MORE;
8976 }
8977
8978 if (s.lookahead === 0) {
8979 break;
8980 }
8981 /* flush the current block */
8982 }
8983 //Assert(s->block_start >= 0L, "block gone");
8984 // if (s.block_start < 0) throw new Error("block gone");
8985
8986 s.strstart += s.lookahead;
8987 s.lookahead = 0;
8988
8989 /* Emit a stored block if pending_buf will be full: */
8990 var max_start = s.block_start + max_block_size;
8991
8992 if (s.strstart === 0 || s.strstart >= max_start) {
8993 /* strstart == 0 is possible when wraparound on 16-bit machine */
8994 s.lookahead = s.strstart - max_start;
8995 s.strstart = max_start;
8996 /*** FLUSH_BLOCK(s, 0); ***/
8997 flush_block_only(s, false);
8998 if (s.strm.avail_out === 0) {
8999 return BS_NEED_MORE;
9000 }
9001 /***/
9002
9003
9004 }
9005 /* Flush if we may have to slide, otherwise block_start may become
9006 * negative and the data will be gone:
9007 */
9008 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
9009 /*** FLUSH_BLOCK(s, 0); ***/
9010 flush_block_only(s, false);
9011 if (s.strm.avail_out === 0) {
9012 return BS_NEED_MORE;
9013 }
9014 /***/
9015 }
9016 }
9017
9018 s.insert = 0;
9019
9020 if (flush === Z_FINISH) {
9021 /*** FLUSH_BLOCK(s, 1); ***/
9022 flush_block_only(s, true);
9023 if (s.strm.avail_out === 0) {
9024 return BS_FINISH_STARTED;
9025 }
9026 /***/
9027 return BS_FINISH_DONE;
9028 }
9029
9030 if (s.strstart > s.block_start) {
9031 /*** FLUSH_BLOCK(s, 0); ***/
9032 flush_block_only(s, false);
9033 if (s.strm.avail_out === 0) {
9034 return BS_NEED_MORE;
9035 }
9036 /***/
9037 }
9038
9039 return BS_NEED_MORE;
9040}
9041
9042/* ===========================================================================
9043 * Compress as much as possible from the input stream, return the current
9044 * block state.
9045 * This function does not perform lazy evaluation of matches and inserts
9046 * new strings in the dictionary only for unmatched strings or for short
9047 * matches. It is used only for the fast compression options.
9048 */
9049function deflate_fast(s, flush) {
9050 var hash_head; /* head of the hash chain */
9051 var bflush; /* set if current block must be flushed */
9052
9053 for (;;) {
9054 /* Make sure that we always have enough lookahead, except
9055 * at the end of the input file. We need MAX_MATCH bytes
9056 * for the next match, plus MIN_MATCH bytes to insert the
9057 * string following the next match.
9058 */
9059 if (s.lookahead < MIN_LOOKAHEAD) {
9060 fill_window(s);
9061 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
9062 return BS_NEED_MORE;
9063 }
9064 if (s.lookahead === 0) {
9065 break; /* flush the current block */
9066 }
9067 }
9068
9069 /* Insert the string window[strstart .. strstart+2] in the
9070 * dictionary, and set hash_head to the head of the hash chain:
9071 */
9072 hash_head = 0 /*NIL*/ ;
9073 if (s.lookahead >= MIN_MATCH$1) {
9074 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
9075 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
9076 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
9077 s.head[s.ins_h] = s.strstart;
9078 /***/
9079 }
9080
9081 /* Find the longest match, discarding those <= prev_length.
9082 * At this point we have always match_length < MIN_MATCH
9083 */
9084 if (hash_head !== 0 /*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
9085 /* To simplify the code, we prevent matches with the string
9086 * of window index 0 (in particular we have to avoid a match
9087 * of the string with itself at the start of the input file).
9088 */
9089 s.match_length = longest_match(s, hash_head);
9090 /* longest_match() sets match_start */
9091 }
9092 if (s.match_length >= MIN_MATCH$1) {
9093 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
9094
9095 /*** _tr_tally_dist(s, s.strstart - s.match_start,
9096 s.match_length - MIN_MATCH, bflush); ***/
9097 bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);
9098
9099 s.lookahead -= s.match_length;
9100
9101 /* Insert new strings in the hash table only if the match length
9102 * is not too large. This saves time but degrades compression.
9103 */
9104 if (s.match_length <= s.max_lazy_match /*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) {
9105 s.match_length--; /* string at strstart already in table */
9106 do {
9107 s.strstart++;
9108 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
9109 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
9110 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
9111 s.head[s.ins_h] = s.strstart;
9112 /***/
9113 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
9114 * always MIN_MATCH bytes ahead.
9115 */
9116 } while (--s.match_length !== 0);
9117 s.strstart++;
9118 } else {
9119 s.strstart += s.match_length;
9120 s.match_length = 0;
9121 s.ins_h = s.window[s.strstart];
9122 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
9123 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
9124
9125 //#if MIN_MATCH != 3
9126 // Call UPDATE_HASH() MIN_MATCH-3 more times
9127 //#endif
9128 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
9129 * matter since it will be recomputed at next deflate call.
9130 */
9131 }
9132 } else {
9133 /* No match, output a literal byte */
9134 //Tracevv((stderr,"%c", s.window[s.strstart]));
9135 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
9136 bflush = _tr_tally(s, 0, s.window[s.strstart]);
9137
9138 s.lookahead--;
9139 s.strstart++;
9140 }
9141 if (bflush) {
9142 /*** FLUSH_BLOCK(s, 0); ***/
9143 flush_block_only(s, false);
9144 if (s.strm.avail_out === 0) {
9145 return BS_NEED_MORE;
9146 }
9147 /***/
9148 }
9149 }
9150 s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1);
9151 if (flush === Z_FINISH) {
9152 /*** FLUSH_BLOCK(s, 1); ***/
9153 flush_block_only(s, true);
9154 if (s.strm.avail_out === 0) {
9155 return BS_FINISH_STARTED;
9156 }
9157 /***/
9158 return BS_FINISH_DONE;
9159 }
9160 if (s.last_lit) {
9161 /*** FLUSH_BLOCK(s, 0); ***/
9162 flush_block_only(s, false);
9163 if (s.strm.avail_out === 0) {
9164 return BS_NEED_MORE;
9165 }
9166 /***/
9167 }
9168 return BS_BLOCK_DONE;
9169}
9170
9171/* ===========================================================================
9172 * Same as above, but achieves better compression. We use a lazy
9173 * evaluation for matches: a match is finally adopted only if there is
9174 * no better match at the next window position.
9175 */
9176function deflate_slow(s, flush) {
9177 var hash_head; /* head of hash chain */
9178 var bflush; /* set if current block must be flushed */
9179
9180 var max_insert;
9181
9182 /* Process the input block. */
9183 for (;;) {
9184 /* Make sure that we always have enough lookahead, except
9185 * at the end of the input file. We need MAX_MATCH bytes
9186 * for the next match, plus MIN_MATCH bytes to insert the
9187 * string following the next match.
9188 */
9189 if (s.lookahead < MIN_LOOKAHEAD) {
9190 fill_window(s);
9191 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
9192 return BS_NEED_MORE;
9193 }
9194 if (s.lookahead === 0) {
9195 break;
9196 } /* flush the current block */
9197 }
9198
9199 /* Insert the string window[strstart .. strstart+2] in the
9200 * dictionary, and set hash_head to the head of the hash chain:
9201 */
9202 hash_head = 0 /*NIL*/ ;
9203 if (s.lookahead >= MIN_MATCH$1) {
9204 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
9205 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
9206 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
9207 s.head[s.ins_h] = s.strstart;
9208 /***/
9209 }
9210
9211 /* Find the longest match, discarding those <= prev_length.
9212 */
9213 s.prev_length = s.match_length;
9214 s.prev_match = s.match_start;
9215 s.match_length = MIN_MATCH$1 - 1;
9216
9217 if (hash_head !== 0 /*NIL*/ && s.prev_length < s.max_lazy_match &&
9218 s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD) /*MAX_DIST(s)*/ ) {
9219 /* To simplify the code, we prevent matches with the string
9220 * of window index 0 (in particular we have to avoid a match
9221 * of the string with itself at the start of the input file).
9222 */
9223 s.match_length = longest_match(s, hash_head);
9224 /* longest_match() sets match_start */
9225
9226 if (s.match_length <= 5 &&
9227 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096 /*TOO_FAR*/ ))) {
9228
9229 /* If prev_match is also MIN_MATCH, match_start is garbage
9230 * but we will ignore the current match anyway.
9231 */
9232 s.match_length = MIN_MATCH$1 - 1;
9233 }
9234 }
9235 /* If there was a match at the previous step and the current
9236 * match is not better, output the previous match:
9237 */
9238 if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {
9239 max_insert = s.strstart + s.lookahead - MIN_MATCH$1;
9240 /* Do not insert strings in hash table beyond this. */
9241
9242 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
9243
9244 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
9245 s.prev_length - MIN_MATCH, bflush);***/
9246 bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);
9247 /* Insert in hash table all strings up to the end of the match.
9248 * strstart-1 and strstart are already inserted. If there is not
9249 * enough lookahead, the last two strings are not inserted in
9250 * the hash table.
9251 */
9252 s.lookahead -= s.prev_length - 1;
9253 s.prev_length -= 2;
9254 do {
9255 if (++s.strstart <= max_insert) {
9256 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
9257 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
9258 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
9259 s.head[s.ins_h] = s.strstart;
9260 /***/
9261 }
9262 } while (--s.prev_length !== 0);
9263 s.match_available = 0;
9264 s.match_length = MIN_MATCH$1 - 1;
9265 s.strstart++;
9266
9267 if (bflush) {
9268 /*** FLUSH_BLOCK(s, 0); ***/
9269 flush_block_only(s, false);
9270 if (s.strm.avail_out === 0) {
9271 return BS_NEED_MORE;
9272 }
9273 /***/
9274 }
9275
9276 } else if (s.match_available) {
9277 /* If there was no match at the previous position, output a
9278 * single literal. If there was a match but the current match
9279 * is longer, truncate the previous match to a single literal.
9280 */
9281 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
9282 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
9283 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
9284
9285 if (bflush) {
9286 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
9287 flush_block_only(s, false);
9288 /***/
9289 }
9290 s.strstart++;
9291 s.lookahead--;
9292 if (s.strm.avail_out === 0) {
9293 return BS_NEED_MORE;
9294 }
9295 } else {
9296 /* There is no previous match to compare with, wait for
9297 * the next step to decide.
9298 */
9299 s.match_available = 1;
9300 s.strstart++;
9301 s.lookahead--;
9302 }
9303 }
9304 //Assert (flush != Z_NO_FLUSH, "no flush?");
9305 if (s.match_available) {
9306 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
9307 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
9308 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
9309
9310 s.match_available = 0;
9311 }
9312 s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;
9313 if (flush === Z_FINISH) {
9314 /*** FLUSH_BLOCK(s, 1); ***/
9315 flush_block_only(s, true);
9316 if (s.strm.avail_out === 0) {
9317 return BS_FINISH_STARTED;
9318 }
9319 /***/
9320 return BS_FINISH_DONE;
9321 }
9322 if (s.last_lit) {
9323 /*** FLUSH_BLOCK(s, 0); ***/
9324 flush_block_only(s, false);
9325 if (s.strm.avail_out === 0) {
9326 return BS_NEED_MORE;
9327 }
9328 /***/
9329 }
9330
9331 return BS_BLOCK_DONE;
9332}
9333
9334
9335/* ===========================================================================
9336 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
9337 * one. Do not maintain a hash table. (It will be regenerated if this run of
9338 * deflate switches away from Z_RLE.)
9339 */
9340function deflate_rle(s, flush) {
9341 var bflush; /* set if current block must be flushed */
9342 var prev; /* byte at distance one to match */
9343 var scan, strend; /* scan goes up to strend for length of run */
9344
9345 var _win = s.window;
9346
9347 for (;;) {
9348 /* Make sure that we always have enough lookahead, except
9349 * at the end of the input file. We need MAX_MATCH bytes
9350 * for the longest run, plus one for the unrolled loop.
9351 */
9352 if (s.lookahead <= MAX_MATCH$1) {
9353 fill_window(s);
9354 if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {
9355 return BS_NEED_MORE;
9356 }
9357 if (s.lookahead === 0) {
9358 break;
9359 } /* flush the current block */
9360 }
9361
9362 /* See how many times the previous byte repeats */
9363 s.match_length = 0;
9364 if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {
9365 scan = s.strstart - 1;
9366 prev = _win[scan];
9367 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
9368 strend = s.strstart + MAX_MATCH$1;
9369 do {
9370 /*jshint noempty:false*/
9371 } while (prev === _win[++scan] && prev === _win[++scan] &&
9372 prev === _win[++scan] && prev === _win[++scan] &&
9373 prev === _win[++scan] && prev === _win[++scan] &&
9374 prev === _win[++scan] && prev === _win[++scan] &&
9375 scan < strend);
9376 s.match_length = MAX_MATCH$1 - (strend - scan);
9377 if (s.match_length > s.lookahead) {
9378 s.match_length = s.lookahead;
9379 }
9380 }
9381 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
9382 }
9383
9384 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
9385 if (s.match_length >= MIN_MATCH$1) {
9386 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
9387
9388 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
9389 bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1);
9390
9391 s.lookahead -= s.match_length;
9392 s.strstart += s.match_length;
9393 s.match_length = 0;
9394 } else {
9395 /* No match, output a literal byte */
9396 //Tracevv((stderr,"%c", s->window[s->strstart]));
9397 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
9398 bflush = _tr_tally(s, 0, s.window[s.strstart]);
9399
9400 s.lookahead--;
9401 s.strstart++;
9402 }
9403 if (bflush) {
9404 /*** FLUSH_BLOCK(s, 0); ***/
9405 flush_block_only(s, false);
9406 if (s.strm.avail_out === 0) {
9407 return BS_NEED_MORE;
9408 }
9409 /***/
9410 }
9411 }
9412 s.insert = 0;
9413 if (flush === Z_FINISH) {
9414 /*** FLUSH_BLOCK(s, 1); ***/
9415 flush_block_only(s, true);
9416 if (s.strm.avail_out === 0) {
9417 return BS_FINISH_STARTED;
9418 }
9419 /***/
9420 return BS_FINISH_DONE;
9421 }
9422 if (s.last_lit) {
9423 /*** FLUSH_BLOCK(s, 0); ***/
9424 flush_block_only(s, false);
9425 if (s.strm.avail_out === 0) {
9426 return BS_NEED_MORE;
9427 }
9428 /***/
9429 }
9430 return BS_BLOCK_DONE;
9431}
9432
9433/* ===========================================================================
9434 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
9435 * (It will be regenerated if this run of deflate switches away from Huffman.)
9436 */
9437function deflate_huff(s, flush) {
9438 var bflush; /* set if current block must be flushed */
9439
9440 for (;;) {
9441 /* Make sure that we have a literal to write. */
9442 if (s.lookahead === 0) {
9443 fill_window(s);
9444 if (s.lookahead === 0) {
9445 if (flush === Z_NO_FLUSH) {
9446 return BS_NEED_MORE;
9447 }
9448 break; /* flush the current block */
9449 }
9450 }
9451
9452 /* Output a literal byte */
9453 s.match_length = 0;
9454 //Tracevv((stderr,"%c", s->window[s->strstart]));
9455 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
9456 bflush = _tr_tally(s, 0, s.window[s.strstart]);
9457 s.lookahead--;
9458 s.strstart++;
9459 if (bflush) {
9460 /*** FLUSH_BLOCK(s, 0); ***/
9461 flush_block_only(s, false);
9462 if (s.strm.avail_out === 0) {
9463 return BS_NEED_MORE;
9464 }
9465 /***/
9466 }
9467 }
9468 s.insert = 0;
9469 if (flush === Z_FINISH) {
9470 /*** FLUSH_BLOCK(s, 1); ***/
9471 flush_block_only(s, true);
9472 if (s.strm.avail_out === 0) {
9473 return BS_FINISH_STARTED;
9474 }
9475 /***/
9476 return BS_FINISH_DONE;
9477 }
9478 if (s.last_lit) {
9479 /*** FLUSH_BLOCK(s, 0); ***/
9480 flush_block_only(s, false);
9481 if (s.strm.avail_out === 0) {
9482 return BS_NEED_MORE;
9483 }
9484 /***/
9485 }
9486 return BS_BLOCK_DONE;
9487}
9488
9489/* Values for max_lazy_match, good_match and max_chain_length, depending on
9490 * the desired pack level (0..9). The values given below have been tuned to
9491 * exclude worst case performance for pathological files. Better values may be
9492 * found for specific files.
9493 */
9494function Config(good_length, max_lazy, nice_length, max_chain, func) {
9495 this.good_length = good_length;
9496 this.max_lazy = max_lazy;
9497 this.nice_length = nice_length;
9498 this.max_chain = max_chain;
9499 this.func = func;
9500}
9501
9502var configuration_table;
9503
9504configuration_table = [
9505 /* good lazy nice chain */
9506 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
9507 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
9508 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
9509 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
9510
9511 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
9512 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
9513 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
9514 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
9515 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
9516 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
9517];
9518
9519
9520/* ===========================================================================
9521 * Initialize the "longest match" routines for a new zlib stream
9522 */
9523function lm_init(s) {
9524 s.window_size = 2 * s.w_size;
9525
9526 /*** CLEAR_HASH(s); ***/
9527 zero$1(s.head); // Fill with NIL (= 0);
9528
9529 /* Set the default configuration parameters:
9530 */
9531 s.max_lazy_match = configuration_table[s.level].max_lazy;
9532 s.good_match = configuration_table[s.level].good_length;
9533 s.nice_match = configuration_table[s.level].nice_length;
9534 s.max_chain_length = configuration_table[s.level].max_chain;
9535
9536 s.strstart = 0;
9537 s.block_start = 0;
9538 s.lookahead = 0;
9539 s.insert = 0;
9540 s.match_length = s.prev_length = MIN_MATCH$1 - 1;
9541 s.match_available = 0;
9542 s.ins_h = 0;
9543}
9544
9545
9546function DeflateState() {
9547 this.strm = null; /* pointer back to this zlib stream */
9548 this.status = 0; /* as the name implies */
9549 this.pending_buf = null; /* output still pending */
9550 this.pending_buf_size = 0; /* size of pending_buf */
9551 this.pending_out = 0; /* next pending byte to output to the stream */
9552 this.pending = 0; /* nb of bytes in the pending buffer */
9553 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
9554 this.gzhead = null; /* gzip header information to write */
9555 this.gzindex = 0; /* where in extra, name, or comment */
9556 this.method = Z_DEFLATED; /* can only be DEFLATED */
9557 this.last_flush = -1; /* value of flush param for previous deflate call */
9558
9559 this.w_size = 0; /* LZ77 window size (32K by default) */
9560 this.w_bits = 0; /* log2(w_size) (8..16) */
9561 this.w_mask = 0; /* w_size - 1 */
9562
9563 this.window = null;
9564 /* Sliding window. Input bytes are read into the second half of the window,
9565 * and move to the first half later to keep a dictionary of at least wSize
9566 * bytes. With this organization, matches are limited to a distance of
9567 * wSize-MAX_MATCH bytes, but this ensures that IO is always
9568 * performed with a length multiple of the block size.
9569 */
9570
9571 this.window_size = 0;
9572 /* Actual size of window: 2*wSize, except when the user input buffer
9573 * is directly used as sliding window.
9574 */
9575
9576 this.prev = null;
9577 /* Link to older string with same hash index. To limit the size of this
9578 * array to 64K, this link is maintained only for the last 32K strings.
9579 * An index in this array is thus a window index modulo 32K.
9580 */
9581
9582 this.head = null; /* Heads of the hash chains or NIL. */
9583
9584 this.ins_h = 0; /* hash index of string to be inserted */
9585 this.hash_size = 0; /* number of elements in hash table */
9586 this.hash_bits = 0; /* log2(hash_size) */
9587 this.hash_mask = 0; /* hash_size-1 */
9588
9589 this.hash_shift = 0;
9590 /* Number of bits by which ins_h must be shifted at each input
9591 * step. It must be such that after MIN_MATCH steps, the oldest
9592 * byte no longer takes part in the hash key, that is:
9593 * hash_shift * MIN_MATCH >= hash_bits
9594 */
9595
9596 this.block_start = 0;
9597 /* Window position at the beginning of the current output block. Gets
9598 * negative when the window is moved backwards.
9599 */
9600
9601 this.match_length = 0; /* length of best match */
9602 this.prev_match = 0; /* previous match */
9603 this.match_available = 0; /* set if previous match exists */
9604 this.strstart = 0; /* start of string to insert */
9605 this.match_start = 0; /* start of matching string */
9606 this.lookahead = 0; /* number of valid bytes ahead in window */
9607
9608 this.prev_length = 0;
9609 /* Length of the best match at previous step. Matches not greater than this
9610 * are discarded. This is used in the lazy match evaluation.
9611 */
9612
9613 this.max_chain_length = 0;
9614 /* To speed up deflation, hash chains are never searched beyond this
9615 * length. A higher limit improves compression ratio but degrades the
9616 * speed.
9617 */
9618
9619 this.max_lazy_match = 0;
9620 /* Attempt to find a better match only when the current match is strictly
9621 * smaller than this value. This mechanism is used only for compression
9622 * levels >= 4.
9623 */
9624 // That's alias to max_lazy_match, don't use directly
9625 //this.max_insert_length = 0;
9626 /* Insert new strings in the hash table only if the match length is not
9627 * greater than this length. This saves time but degrades compression.
9628 * max_insert_length is used only for compression levels <= 3.
9629 */
9630
9631 this.level = 0; /* compression level (1..9) */
9632 this.strategy = 0; /* favor or force Huffman coding*/
9633
9634 this.good_match = 0;
9635 /* Use a faster search when the previous match is longer than this */
9636
9637 this.nice_match = 0; /* Stop searching when current match exceeds this */
9638
9639 /* used by c: */
9640
9641 /* Didn't use ct_data typedef below to suppress compiler warning */
9642
9643 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
9644 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
9645 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
9646
9647 // Use flat array of DOUBLE size, with interleaved fata,
9648 // because JS does not support effective
9649 this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2);
9650 this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2);
9651 this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2);
9652 zero$1(this.dyn_ltree);
9653 zero$1(this.dyn_dtree);
9654 zero$1(this.bl_tree);
9655
9656 this.l_desc = null; /* desc. for literal tree */
9657 this.d_desc = null; /* desc. for distance tree */
9658 this.bl_desc = null; /* desc. for bit length tree */
9659
9660 //ush bl_count[MAX_BITS+1];
9661 this.bl_count = new Buf16(MAX_BITS$1 + 1);
9662 /* number of codes at each bit length for an optimal tree */
9663
9664 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
9665 this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */
9666 zero$1(this.heap);
9667
9668 this.heap_len = 0; /* number of elements in the heap */
9669 this.heap_max = 0; /* element of largest frequency */
9670 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
9671 * The same heap array is used to build all
9672 */
9673
9674 this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];
9675 zero$1(this.depth);
9676 /* Depth of each subtree used as tie breaker for trees of equal frequency
9677 */
9678
9679 this.l_buf = 0; /* buffer index for literals or lengths */
9680
9681 this.lit_bufsize = 0;
9682 /* Size of match buffer for literals/lengths. There are 4 reasons for
9683 * limiting lit_bufsize to 64K:
9684 * - frequencies can be kept in 16 bit counters
9685 * - if compression is not successful for the first block, all input
9686 * data is still in the window so we can still emit a stored block even
9687 * when input comes from standard input. (This can also be done for
9688 * all blocks if lit_bufsize is not greater than 32K.)
9689 * - if compression is not successful for a file smaller than 64K, we can
9690 * even emit a stored file instead of a stored block (saving 5 bytes).
9691 * This is applicable only for zip (not gzip or zlib).
9692 * - creating new Huffman trees less frequently may not provide fast
9693 * adaptation to changes in the input data statistics. (Take for
9694 * example a binary file with poorly compressible code followed by
9695 * a highly compressible string table.) Smaller buffer sizes give
9696 * fast adaptation but have of course the overhead of transmitting
9697 * trees more frequently.
9698 * - I can't count above 4
9699 */
9700
9701 this.last_lit = 0; /* running index in l_buf */
9702
9703 this.d_buf = 0;
9704 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
9705 * the same number of elements. To use different lengths, an extra flag
9706 * array would be necessary.
9707 */
9708
9709 this.opt_len = 0; /* bit length of current block with optimal trees */
9710 this.static_len = 0; /* bit length of current block with static trees */
9711 this.matches = 0; /* number of string matches in current block */
9712 this.insert = 0; /* bytes at end of window left to insert */
9713
9714
9715 this.bi_buf = 0;
9716 /* Output buffer. bits are inserted starting at the bottom (least
9717 * significant bits).
9718 */
9719 this.bi_valid = 0;
9720 /* Number of valid bits in bi_buf. All bits above the last valid bit
9721 * are always zero.
9722 */
9723
9724 // Used for window memory init. We safely ignore it for JS. That makes
9725 // sense only for pointers and memory check tools.
9726 //this.high_water = 0;
9727 /* High water mark offset in window for initialized bytes -- bytes above
9728 * this are set to zero in order to avoid memory check warnings when
9729 * longest match routines access bytes past the input. This is then
9730 * updated to the new high water mark.
9731 */
9732}
9733
9734
9735function deflateResetKeep(strm) {
9736 var s;
9737
9738 if (!strm || !strm.state) {
9739 return err(strm, Z_STREAM_ERROR);
9740 }
9741
9742 strm.total_in = strm.total_out = 0;
9743 strm.data_type = Z_UNKNOWN$1;
9744
9745 s = strm.state;
9746 s.pending = 0;
9747 s.pending_out = 0;
9748
9749 if (s.wrap < 0) {
9750 s.wrap = -s.wrap;
9751 /* was made negative by deflate(..., Z_FINISH); */
9752 }
9753 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
9754 strm.adler = (s.wrap === 2) ?
9755 0 // crc32(0, Z_NULL, 0)
9756 :
9757 1; // adler32(0, Z_NULL, 0)
9758 s.last_flush = Z_NO_FLUSH;
9759 _tr_init(s);
9760 return Z_OK;
9761}
9762
9763
9764function deflateReset(strm) {
9765 var ret = deflateResetKeep(strm);
9766 if (ret === Z_OK) {
9767 lm_init(strm.state);
9768 }
9769 return ret;
9770}
9771
9772
9773function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
9774 if (!strm) { // === Z_NULL
9775 return Z_STREAM_ERROR;
9776 }
9777 var wrap = 1;
9778
9779 if (level === Z_DEFAULT_COMPRESSION) {
9780 level = 6;
9781 }
9782
9783 if (windowBits < 0) { /* suppress zlib wrapper */
9784 wrap = 0;
9785 windowBits = -windowBits;
9786 } else if (windowBits > 15) {
9787 wrap = 2; /* write gzip wrapper instead */
9788 windowBits -= 16;
9789 }
9790
9791
9792 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
9793 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
9794 strategy < 0 || strategy > Z_FIXED$1) {
9795 return err(strm, Z_STREAM_ERROR);
9796 }
9797
9798
9799 if (windowBits === 8) {
9800 windowBits = 9;
9801 }
9802 /* until 256-byte window bug fixed */
9803
9804 var s = new DeflateState();
9805
9806 strm.state = s;
9807 s.strm = strm;
9808
9809 s.wrap = wrap;
9810 s.gzhead = null;
9811 s.w_bits = windowBits;
9812 s.w_size = 1 << s.w_bits;
9813 s.w_mask = s.w_size - 1;
9814
9815 s.hash_bits = memLevel + 7;
9816 s.hash_size = 1 << s.hash_bits;
9817 s.hash_mask = s.hash_size - 1;
9818 s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);
9819
9820 s.window = new Buf8(s.w_size * 2);
9821 s.head = new Buf16(s.hash_size);
9822 s.prev = new Buf16(s.w_size);
9823
9824 // Don't need mem init magic for JS.
9825 //s.high_water = 0; /* nothing written to s->window yet */
9826
9827 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
9828
9829 s.pending_buf_size = s.lit_bufsize * 4;
9830
9831 //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
9832 //s->pending_buf = (uchf *) overlay;
9833 s.pending_buf = new Buf8(s.pending_buf_size);
9834
9835 // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
9836 //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
9837 s.d_buf = 1 * s.lit_bufsize;
9838
9839 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
9840 s.l_buf = (1 + 2) * s.lit_bufsize;
9841
9842 s.level = level;
9843 s.strategy = strategy;
9844 s.method = method;
9845
9846 return deflateReset(strm);
9847}
9848
9849
9850function deflate(strm, flush) {
9851 var old_flush, s;
9852 var beg, val; // for gzip header write only
9853
9854 if (!strm || !strm.state ||
9855 flush > Z_BLOCK || flush < 0) {
9856 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
9857 }
9858
9859 s = strm.state;
9860
9861 if (!strm.output ||
9862 (!strm.input && strm.avail_in !== 0) ||
9863 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
9864 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
9865 }
9866
9867 s.strm = strm; /* just in case */
9868 old_flush = s.last_flush;
9869 s.last_flush = flush;
9870
9871 /* Write the header */
9872 if (s.status === INIT_STATE) {
9873 if (s.wrap === 2) {
9874 // GZIP header
9875 strm.adler = 0; //crc32(0L, Z_NULL, 0);
9876 put_byte(s, 31);
9877 put_byte(s, 139);
9878 put_byte(s, 8);
9879 if (!s.gzhead) { // s->gzhead == Z_NULL
9880 put_byte(s, 0);
9881 put_byte(s, 0);
9882 put_byte(s, 0);
9883 put_byte(s, 0);
9884 put_byte(s, 0);
9885 put_byte(s, s.level === 9 ? 2 :
9886 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
9887 4 : 0));
9888 put_byte(s, OS_CODE);
9889 s.status = BUSY_STATE;
9890 } else {
9891 put_byte(s, (s.gzhead.text ? 1 : 0) +
9892 (s.gzhead.hcrc ? 2 : 0) +
9893 (!s.gzhead.extra ? 0 : 4) +
9894 (!s.gzhead.name ? 0 : 8) +
9895 (!s.gzhead.comment ? 0 : 16)
9896 );
9897 put_byte(s, s.gzhead.time & 0xff);
9898 put_byte(s, (s.gzhead.time >> 8) & 0xff);
9899 put_byte(s, (s.gzhead.time >> 16) & 0xff);
9900 put_byte(s, (s.gzhead.time >> 24) & 0xff);
9901 put_byte(s, s.level === 9 ? 2 :
9902 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
9903 4 : 0));
9904 put_byte(s, s.gzhead.os & 0xff);
9905 if (s.gzhead.extra && s.gzhead.extra.length) {
9906 put_byte(s, s.gzhead.extra.length & 0xff);
9907 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
9908 }
9909 if (s.gzhead.hcrc) {
9910 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
9911 }
9912 s.gzindex = 0;
9913 s.status = EXTRA_STATE;
9914 }
9915 } else // DEFLATE header
9916 {
9917 var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
9918 var level_flags = -1;
9919
9920 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
9921 level_flags = 0;
9922 } else if (s.level < 6) {
9923 level_flags = 1;
9924 } else if (s.level === 6) {
9925 level_flags = 2;
9926 } else {
9927 level_flags = 3;
9928 }
9929 header |= (level_flags << 6);
9930 if (s.strstart !== 0) {
9931 header |= PRESET_DICT;
9932 }
9933 header += 31 - (header % 31);
9934
9935 s.status = BUSY_STATE;
9936 putShortMSB(s, header);
9937
9938 /* Save the adler32 of the preset dictionary: */
9939 if (s.strstart !== 0) {
9940 putShortMSB(s, strm.adler >>> 16);
9941 putShortMSB(s, strm.adler & 0xffff);
9942 }
9943 strm.adler = 1; // adler32(0L, Z_NULL, 0);
9944 }
9945 }
9946
9947 //#ifdef GZIP
9948 if (s.status === EXTRA_STATE) {
9949 if (s.gzhead.extra /* != Z_NULL*/ ) {
9950 beg = s.pending; /* start of bytes to update crc */
9951
9952 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
9953 if (s.pending === s.pending_buf_size) {
9954 if (s.gzhead.hcrc && s.pending > beg) {
9955 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9956 }
9957 flush_pending(strm);
9958 beg = s.pending;
9959 if (s.pending === s.pending_buf_size) {
9960 break;
9961 }
9962 }
9963 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
9964 s.gzindex++;
9965 }
9966 if (s.gzhead.hcrc && s.pending > beg) {
9967 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9968 }
9969 if (s.gzindex === s.gzhead.extra.length) {
9970 s.gzindex = 0;
9971 s.status = NAME_STATE;
9972 }
9973 } else {
9974 s.status = NAME_STATE;
9975 }
9976 }
9977 if (s.status === NAME_STATE) {
9978 if (s.gzhead.name /* != Z_NULL*/ ) {
9979 beg = s.pending; /* start of bytes to update crc */
9980 //int val;
9981
9982 do {
9983 if (s.pending === s.pending_buf_size) {
9984 if (s.gzhead.hcrc && s.pending > beg) {
9985 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9986 }
9987 flush_pending(strm);
9988 beg = s.pending;
9989 if (s.pending === s.pending_buf_size) {
9990 val = 1;
9991 break;
9992 }
9993 }
9994 // JS specific: little magic to add zero terminator to end of string
9995 if (s.gzindex < s.gzhead.name.length) {
9996 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
9997 } else {
9998 val = 0;
9999 }
10000 put_byte(s, val);
10001 } while (val !== 0);
10002
10003 if (s.gzhead.hcrc && s.pending > beg) {
10004 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
10005 }
10006 if (val === 0) {
10007 s.gzindex = 0;
10008 s.status = COMMENT_STATE;
10009 }
10010 } else {
10011 s.status = COMMENT_STATE;
10012 }
10013 }
10014 if (s.status === COMMENT_STATE) {
10015 if (s.gzhead.comment /* != Z_NULL*/ ) {
10016 beg = s.pending; /* start of bytes to update crc */
10017 //int val;
10018
10019 do {
10020 if (s.pending === s.pending_buf_size) {
10021 if (s.gzhead.hcrc && s.pending > beg) {
10022 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
10023 }
10024 flush_pending(strm);
10025 beg = s.pending;
10026 if (s.pending === s.pending_buf_size) {
10027 val = 1;
10028 break;
10029 }
10030 }
10031 // JS specific: little magic to add zero terminator to end of string
10032 if (s.gzindex < s.gzhead.comment.length) {
10033 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
10034 } else {
10035 val = 0;
10036 }
10037 put_byte(s, val);
10038 } while (val !== 0);
10039
10040 if (s.gzhead.hcrc && s.pending > beg) {
10041 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
10042 }
10043 if (val === 0) {
10044 s.status = HCRC_STATE;
10045 }
10046 } else {
10047 s.status = HCRC_STATE;
10048 }
10049 }
10050 if (s.status === HCRC_STATE) {
10051 if (s.gzhead.hcrc) {
10052 if (s.pending + 2 > s.pending_buf_size) {
10053 flush_pending(strm);
10054 }
10055 if (s.pending + 2 <= s.pending_buf_size) {
10056 put_byte(s, strm.adler & 0xff);
10057 put_byte(s, (strm.adler >> 8) & 0xff);
10058 strm.adler = 0; //crc32(0L, Z_NULL, 0);
10059 s.status = BUSY_STATE;
10060 }
10061 } else {
10062 s.status = BUSY_STATE;
10063 }
10064 }
10065 //#endif
10066
10067 /* Flush as much pending output as possible */
10068 if (s.pending !== 0) {
10069 flush_pending(strm);
10070 if (strm.avail_out === 0) {
10071 /* Since avail_out is 0, deflate will be called again with
10072 * more output space, but possibly with both pending and
10073 * avail_in equal to zero. There won't be anything to do,
10074 * but this is not an error situation so make sure we
10075 * return OK instead of BUF_ERROR at next call of deflate:
10076 */
10077 s.last_flush = -1;
10078 return Z_OK;
10079 }
10080
10081 /* Make sure there is something to do and avoid duplicate consecutive
10082 * flushes. For repeated and useless calls with Z_FINISH, we keep
10083 * returning Z_STREAM_END instead of Z_BUF_ERROR.
10084 */
10085 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
10086 flush !== Z_FINISH) {
10087 return err(strm, Z_BUF_ERROR);
10088 }
10089
10090 /* User must not provide more input after the first FINISH: */
10091 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
10092 return err(strm, Z_BUF_ERROR);
10093 }
10094
10095 /* Start a new block or continue the current one.
10096 */
10097 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
10098 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
10099 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
10100 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
10101 configuration_table[s.level].func(s, flush));
10102
10103 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
10104 s.status = FINISH_STATE;
10105 }
10106 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
10107 if (strm.avail_out === 0) {
10108 s.last_flush = -1;
10109 /* avoid BUF_ERROR next call, see above */
10110 }
10111 return Z_OK;
10112 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
10113 * of deflate should use the same flush parameter to make sure
10114 * that the flush is complete. So we don't have to output an
10115 * empty block here, this will be done at next call. This also
10116 * ensures that for a very small output buffer, we emit at most
10117 * one empty block.
10118 */
10119 }
10120 if (bstate === BS_BLOCK_DONE) {
10121 if (flush === Z_PARTIAL_FLUSH) {
10122 _tr_align(s);
10123 } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
10124
10125 _tr_stored_block(s, 0, 0, false);
10126 /* For a full flush, this empty block will be recognized
10127 * as a special marker by inflate_sync().
10128 */
10129 if (flush === Z_FULL_FLUSH) {
10130 /*** CLEAR_HASH(s); ***/
10131 /* forget history */
10132 zero$1(s.head); // Fill with NIL (= 0);
10133
10134 if (s.lookahead === 0) {
10135 s.strstart = 0;
10136 s.block_start = 0;
10137 s.insert = 0;
10138 }
10139 }
10140 }
10141 flush_pending(strm);
10142 if (strm.avail_out === 0) {
10143 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
10144 return Z_OK;
10145 }
10146 }
10147 }
10148 //Assert(strm->avail_out > 0, "bug2");
10149 //if (strm.avail_out <= 0) { throw new Error("bug2");}
10150
10151 if (flush !== Z_FINISH) {
10152 return Z_OK;
10153 }
10154 if (s.wrap <= 0) {
10155 return Z_STREAM_END;
10156 }
10157
10158 /* Write the trailer */
10159 if (s.wrap === 2) {
10160 put_byte(s, strm.adler & 0xff);
10161 put_byte(s, (strm.adler >> 8) & 0xff);
10162 put_byte(s, (strm.adler >> 16) & 0xff);
10163 put_byte(s, (strm.adler >> 24) & 0xff);
10164 put_byte(s, strm.total_in & 0xff);
10165 put_byte(s, (strm.total_in >> 8) & 0xff);
10166 put_byte(s, (strm.total_in >> 16) & 0xff);
10167 put_byte(s, (strm.total_in >> 24) & 0xff);
10168 } else {
10169 putShortMSB(s, strm.adler >>> 16);
10170 putShortMSB(s, strm.adler & 0xffff);
10171 }
10172
10173 flush_pending(strm);
10174 /* If avail_out is zero, the application will call deflate again
10175 * to flush the rest.
10176 */
10177 if (s.wrap > 0) {
10178 s.wrap = -s.wrap;
10179 }
10180 /* write the trailer only once! */
10181 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
10182}
10183
10184function deflateEnd(strm) {
10185 var status;
10186
10187 if (!strm /*== Z_NULL*/ || !strm.state /*== Z_NULL*/ ) {
10188 return Z_STREAM_ERROR;
10189 }
10190
10191 status = strm.state.status;
10192 if (status !== INIT_STATE &&
10193 status !== EXTRA_STATE &&
10194 status !== NAME_STATE &&
10195 status !== COMMENT_STATE &&
10196 status !== HCRC_STATE &&
10197 status !== BUSY_STATE &&
10198 status !== FINISH_STATE
10199 ) {
10200 return err(strm, Z_STREAM_ERROR);
10201 }
10202
10203 strm.state = null;
10204
10205 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
10206}
10207
10208/* Not implemented
10209exports.deflateBound = deflateBound;
10210exports.deflateCopy = deflateCopy;
10211exports.deflateParams = deflateParams;
10212exports.deflatePending = deflatePending;
10213exports.deflatePrime = deflatePrime;
10214exports.deflateTune = deflateTune;
10215*/
10216
10217// See state defs from inflate.js
10218var BAD = 30; /* got a data error -- remain here until reset */
10219var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
10220
10221/*
10222 Decode literal, length, and distance codes and write out the resulting
10223 literal and match bytes until either not enough input or output is
10224 available, an end-of-block is encountered, or a data error is encountered.
10225 When large enough input and output buffers are supplied to inflate(), for
10226 example, a 16K input buffer and a 64K output buffer, more than 95% of the
10227 inflate execution time is spent in this routine.
10228
10229 Entry assumptions:
10230
10231 state.mode === LEN
10232 strm.avail_in >= 6
10233 strm.avail_out >= 258
10234 start >= strm.avail_out
10235 state.bits < 8
10236
10237 On return, state.mode is one of:
10238
10239 LEN -- ran out of enough output space or enough available input
10240 TYPE -- reached end of block code, inflate() to interpret next block
10241 BAD -- error in block data
10242
10243 Notes:
10244
10245 - The maximum input bits used by a length/distance pair is 15 bits for the
10246 length code, 5 bits for the length extra, 15 bits for the distance code,
10247 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
10248 Therefore if strm.avail_in >= 6, then there is enough input to avoid
10249 checking for available input while decoding.
10250
10251 - The maximum bytes that a single length/distance pair can output is 258
10252 bytes, which is the maximum length that can be coded. inflate_fast()
10253 requires strm.avail_out >= 258 for each loop to avoid checking for
10254 output space.
10255 */
10256function inflate_fast(strm, start) {
10257 var state;
10258 var _in; /* local strm.input */
10259 var last; /* have enough input while in < last */
10260 var _out; /* local strm.output */
10261 var beg; /* inflate()'s initial strm.output */
10262 var end; /* while out < end, enough space available */
10263//#ifdef INFLATE_STRICT
10264 var dmax; /* maximum distance from zlib header */
10265//#endif
10266 var wsize; /* window size or zero if not using window */
10267 var whave; /* valid bytes in the window */
10268 var wnext; /* window write index */
10269 // Use `s_window` instead `window`, avoid conflict with instrumentation tools
10270 var s_window; /* allocated sliding window, if wsize != 0 */
10271 var hold; /* local strm.hold */
10272 var bits; /* local strm.bits */
10273 var lcode; /* local strm.lencode */
10274 var dcode; /* local strm.distcode */
10275 var lmask; /* mask for first level of length codes */
10276 var dmask; /* mask for first level of distance codes */
10277 var here; /* retrieved table entry */
10278 var op; /* code bits, operation, extra bits, or */
10279 /* window position, window bytes to copy */
10280 var len; /* match length, unused bytes */
10281 var dist; /* match distance */
10282 var from; /* where to copy match from */
10283 var from_source;
10284
10285
10286 var input, output; // JS specific, because we have no pointers
10287
10288 /* copy state to local variables */
10289 state = strm.state;
10290 //here = state.here;
10291 _in = strm.next_in;
10292 input = strm.input;
10293 last = _in + (strm.avail_in - 5);
10294 _out = strm.next_out;
10295 output = strm.output;
10296 beg = _out - (start - strm.avail_out);
10297 end = _out + (strm.avail_out - 257);
10298//#ifdef INFLATE_STRICT
10299 dmax = state.dmax;
10300//#endif
10301 wsize = state.wsize;
10302 whave = state.whave;
10303 wnext = state.wnext;
10304 s_window = state.window;
10305 hold = state.hold;
10306 bits = state.bits;
10307 lcode = state.lencode;
10308 dcode = state.distcode;
10309 lmask = (1 << state.lenbits) - 1;
10310 dmask = (1 << state.distbits) - 1;
10311
10312
10313 /* decode literals and length/distances until end-of-block or not enough
10314 input data or output space */
10315
10316 top:
10317 do {
10318 if (bits < 15) {
10319 hold += input[_in++] << bits;
10320 bits += 8;
10321 hold += input[_in++] << bits;
10322 bits += 8;
10323 }
10324
10325 here = lcode[hold & lmask];
10326
10327 dolen:
10328 for (;;) { // Goto emulation
10329 op = here >>> 24/*here.bits*/;
10330 hold >>>= op;
10331 bits -= op;
10332 op = (here >>> 16) & 0xff/*here.op*/;
10333 if (op === 0) { /* literal */
10334 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
10335 // "inflate: literal '%c'\n" :
10336 // "inflate: literal 0x%02x\n", here.val));
10337 output[_out++] = here & 0xffff/*here.val*/;
10338 }
10339 else if (op & 16) { /* length base */
10340 len = here & 0xffff/*here.val*/;
10341 op &= 15; /* number of extra bits */
10342 if (op) {
10343 if (bits < op) {
10344 hold += input[_in++] << bits;
10345 bits += 8;
10346 }
10347 len += hold & ((1 << op) - 1);
10348 hold >>>= op;
10349 bits -= op;
10350 }
10351 //Tracevv((stderr, "inflate: length %u\n", len));
10352 if (bits < 15) {
10353 hold += input[_in++] << bits;
10354 bits += 8;
10355 hold += input[_in++] << bits;
10356 bits += 8;
10357 }
10358 here = dcode[hold & dmask];
10359
10360 dodist:
10361 for (;;) { // goto emulation
10362 op = here >>> 24/*here.bits*/;
10363 hold >>>= op;
10364 bits -= op;
10365 op = (here >>> 16) & 0xff/*here.op*/;
10366
10367 if (op & 16) { /* distance base */
10368 dist = here & 0xffff/*here.val*/;
10369 op &= 15; /* number of extra bits */
10370 if (bits < op) {
10371 hold += input[_in++] << bits;
10372 bits += 8;
10373 if (bits < op) {
10374 hold += input[_in++] << bits;
10375 bits += 8;
10376 }
10377 }
10378 dist += hold & ((1 << op) - 1);
10379//#ifdef INFLATE_STRICT
10380 if (dist > dmax) {
10381 strm.msg = 'invalid distance too far back';
10382 state.mode = BAD;
10383 break top;
10384 }
10385//#endif
10386 hold >>>= op;
10387 bits -= op;
10388 //Tracevv((stderr, "inflate: distance %u\n", dist));
10389 op = _out - beg; /* max distance in output */
10390 if (dist > op) { /* see if copy from window */
10391 op = dist - op; /* distance back in window */
10392 if (op > whave) {
10393 if (state.sane) {
10394 strm.msg = 'invalid distance too far back';
10395 state.mode = BAD;
10396 break top;
10397 }
10398
10399// (!) This block is disabled in zlib defailts,
10400// don't enable it for binary compatibility
10401//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
10402// if (len <= op - whave) {
10403// do {
10404// output[_out++] = 0;
10405// } while (--len);
10406// continue top;
10407// }
10408// len -= op - whave;
10409// do {
10410// output[_out++] = 0;
10411// } while (--op > whave);
10412// if (op === 0) {
10413// from = _out - dist;
10414// do {
10415// output[_out++] = output[from++];
10416// } while (--len);
10417// continue top;
10418// }
10419//#endif
10420 }
10421 from = 0; // window index
10422 from_source = s_window;
10423 if (wnext === 0) { /* very common case */
10424 from += wsize - op;
10425 if (op < len) { /* some from window */
10426 len -= op;
10427 do {
10428 output[_out++] = s_window[from++];
10429 } while (--op);
10430 from = _out - dist; /* rest from output */
10431 from_source = output;
10432 }
10433 }
10434 else if (wnext < op) { /* wrap around window */
10435 from += wsize + wnext - op;
10436 op -= wnext;
10437 if (op < len) { /* some from end of window */
10438 len -= op;
10439 do {
10440 output[_out++] = s_window[from++];
10441 } while (--op);
10442 from = 0;
10443 if (wnext < len) { /* some from start of window */
10444 op = wnext;
10445 len -= op;
10446 do {
10447 output[_out++] = s_window[from++];
10448 } while (--op);
10449 from = _out - dist; /* rest from output */
10450 from_source = output;
10451 }
10452 }
10453 }
10454 else { /* contiguous in window */
10455 from += wnext - op;
10456 if (op < len) { /* some from window */
10457 len -= op;
10458 do {
10459 output[_out++] = s_window[from++];
10460 } while (--op);
10461 from = _out - dist; /* rest from output */
10462 from_source = output;
10463 }
10464 }
10465 while (len > 2) {
10466 output[_out++] = from_source[from++];
10467 output[_out++] = from_source[from++];
10468 output[_out++] = from_source[from++];
10469 len -= 3;
10470 }
10471 if (len) {
10472 output[_out++] = from_source[from++];
10473 if (len > 1) {
10474 output[_out++] = from_source[from++];
10475 }
10476 }
10477 }
10478 else {
10479 from = _out - dist; /* copy direct from output */
10480 do { /* minimum length is three */
10481 output[_out++] = output[from++];
10482 output[_out++] = output[from++];
10483 output[_out++] = output[from++];
10484 len -= 3;
10485 } while (len > 2);
10486 if (len) {
10487 output[_out++] = output[from++];
10488 if (len > 1) {
10489 output[_out++] = output[from++];
10490 }
10491 }
10492 }
10493 }
10494 else if ((op & 64) === 0) { /* 2nd level distance code */
10495 here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
10496 continue dodist;
10497 }
10498 else {
10499 strm.msg = 'invalid distance code';
10500 state.mode = BAD;
10501 break top;
10502 }
10503
10504 break; // need to emulate goto via "continue"
10505 }
10506 }
10507 else if ((op & 64) === 0) { /* 2nd level length code */
10508 here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
10509 continue dolen;
10510 }
10511 else if (op & 32) { /* end-of-block */
10512 //Tracevv((stderr, "inflate: end of block\n"));
10513 state.mode = TYPE;
10514 break top;
10515 }
10516 else {
10517 strm.msg = 'invalid literal/length code';
10518 state.mode = BAD;
10519 break top;
10520 }
10521
10522 break; // need to emulate goto via "continue"
10523 }
10524 } while (_in < last && _out < end);
10525
10526 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
10527 len = bits >> 3;
10528 _in -= len;
10529 bits -= len << 3;
10530 hold &= (1 << bits) - 1;
10531
10532 /* update state and return */
10533 strm.next_in = _in;
10534 strm.next_out = _out;
10535 strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
10536 strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
10537 state.hold = hold;
10538 state.bits = bits;
10539 return;
10540}
10541
10542var MAXBITS = 15;
10543var ENOUGH_LENS = 852;
10544var ENOUGH_DISTS = 592;
10545//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
10546
10547var CODES = 0;
10548var LENS = 1;
10549var DISTS = 2;
10550
10551var lbase = [ /* Length codes 257..285 base */
10552 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
10553 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
10554];
10555
10556var lext = [ /* Length codes 257..285 extra */
10557 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
10558 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
10559];
10560
10561var dbase = [ /* Distance codes 0..29 base */
10562 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
10563 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
10564 8193, 12289, 16385, 24577, 0, 0
10565];
10566
10567var dext = [ /* Distance codes 0..29 extra */
10568 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
10569 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
10570 28, 28, 29, 29, 64, 64
10571];
10572
10573function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
10574 var bits = opts.bits;
10575 //here = opts.here; /* table entry for duplication */
10576
10577 var len = 0; /* a code's length in bits */
10578 var sym = 0; /* index of code symbols */
10579 var min = 0,
10580 max = 0; /* minimum and maximum code lengths */
10581 var root = 0; /* number of index bits for root table */
10582 var curr = 0; /* number of index bits for current table */
10583 var drop = 0; /* code bits to drop for sub-table */
10584 var left = 0; /* number of prefix codes available */
10585 var used = 0; /* code entries in table used */
10586 var huff = 0; /* Huffman code */
10587 var incr; /* for incrementing code, index */
10588 var fill; /* index for replicating entries */
10589 var low; /* low bits for current root entry */
10590 var mask; /* mask for low root bits */
10591 var next; /* next available space in table */
10592 var base = null; /* base value table to use */
10593 var base_index = 0;
10594 // var shoextra; /* extra bits table to use */
10595 var end; /* use base and extra for symbol > end */
10596 var count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
10597 var offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
10598 var extra = null;
10599 var extra_index = 0;
10600
10601 var here_bits, here_op, here_val;
10602
10603 /*
10604 Process a set of code lengths to create a canonical Huffman code. The
10605 code lengths are lens[0..codes-1]. Each length corresponds to the
10606 symbols 0..codes-1. The Huffman code is generated by first sorting the
10607 symbols by length from short to long, and retaining the symbol order
10608 for codes with equal lengths. Then the code starts with all zero bits
10609 for the first code of the shortest length, and the codes are integer
10610 increments for the same length, and zeros are appended as the length
10611 increases. For the deflate format, these bits are stored backwards
10612 from their more natural integer increment ordering, and so when the
10613 decoding tables are built in the large loop below, the integer codes
10614 are incremented backwards.
10615
10616 This routine assumes, but does not check, that all of the entries in
10617 lens[] are in the range 0..MAXBITS. The caller must assure this.
10618 1..MAXBITS is interpreted as that code length. zero means that that
10619 symbol does not occur in this code.
10620
10621 The codes are sorted by computing a count of codes for each length,
10622 creating from that a table of starting indices for each length in the
10623 sorted table, and then entering the symbols in order in the sorted
10624 table. The sorted table is work[], with that space being provided by
10625 the caller.
10626
10627 The length counts are used for other purposes as well, i.e. finding
10628 the minimum and maximum length codes, determining if there are any
10629 codes at all, checking for a valid set of lengths, and looking ahead
10630 at length counts to determine sub-table sizes when building the
10631 decoding tables.
10632 */
10633
10634 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
10635 for (len = 0; len <= MAXBITS; len++) {
10636 count[len] = 0;
10637 }
10638 for (sym = 0; sym < codes; sym++) {
10639 count[lens[lens_index + sym]]++;
10640 }
10641
10642 /* bound code lengths, force root to be within code lengths */
10643 root = bits;
10644 for (max = MAXBITS; max >= 1; max--) {
10645 if (count[max] !== 0) {
10646 break;
10647 }
10648 }
10649 if (root > max) {
10650 root = max;
10651 }
10652 if (max === 0) { /* no symbols to code at all */
10653 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
10654 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
10655 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
10656 table[table_index++] = (1 << 24) | (64 << 16) | 0;
10657
10658
10659 //table.op[opts.table_index] = 64;
10660 //table.bits[opts.table_index] = 1;
10661 //table.val[opts.table_index++] = 0;
10662 table[table_index++] = (1 << 24) | (64 << 16) | 0;
10663
10664 opts.bits = 1;
10665 return 0; /* no symbols, but wait for decoding to report error */
10666 }
10667 for (min = 1; min < max; min++) {
10668 if (count[min] !== 0) {
10669 break;
10670 }
10671 }
10672 if (root < min) {
10673 root = min;
10674 }
10675
10676 /* check for an over-subscribed or incomplete set of lengths */
10677 left = 1;
10678 for (len = 1; len <= MAXBITS; len++) {
10679 left <<= 1;
10680 left -= count[len];
10681 if (left < 0) {
10682 return -1;
10683 } /* over-subscribed */
10684 }
10685 if (left > 0 && (type === CODES || max !== 1)) {
10686 return -1; /* incomplete set */
10687 }
10688
10689 /* generate offsets into symbol table for each length for sorting */
10690 offs[1] = 0;
10691 for (len = 1; len < MAXBITS; len++) {
10692 offs[len + 1] = offs[len] + count[len];
10693 }
10694
10695 /* sort symbols by length, by symbol order within each length */
10696 for (sym = 0; sym < codes; sym++) {
10697 if (lens[lens_index + sym] !== 0) {
10698 work[offs[lens[lens_index + sym]]++] = sym;
10699 }
10700 }
10701
10702 /*
10703 Create and fill in decoding tables. In this loop, the table being
10704 filled is at next and has curr index bits. The code being used is huff
10705 with length len. That code is converted to an index by dropping drop
10706 bits off of the bottom. For codes where len is less than drop + curr,
10707 those top drop + curr - len bits are incremented through all values to
10708 fill the table with replicated entries.
10709
10710 root is the number of index bits for the root table. When len exceeds
10711 root, sub-tables are created pointed to by the root entry with an index
10712 of the low root bits of huff. This is saved in low to check for when a
10713 new sub-table should be started. drop is zero when the root table is
10714 being filled, and drop is root when sub-tables are being filled.
10715
10716 When a new sub-table is needed, it is necessary to look ahead in the
10717 code lengths to determine what size sub-table is needed. The length
10718 counts are used for this, and so count[] is decremented as codes are
10719 entered in the tables.
10720
10721 used keeps track of how many table entries have been allocated from the
10722 provided *table space. It is checked for LENS and DIST tables against
10723 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
10724 the initial root table size constants. See the comments in inftrees.h
10725 for more information.
10726
10727 sym increments through all symbols, and the loop terminates when
10728 all codes of length max, i.e. all codes, have been processed. This
10729 routine permits incomplete codes, so another loop after this one fills
10730 in the rest of the decoding tables with invalid code markers.
10731 */
10732
10733 /* set up for code type */
10734 // poor man optimization - use if-else instead of switch,
10735 // to avoid deopts in old v8
10736 if (type === CODES) {
10737 base = extra = work; /* dummy value--not used */
10738 end = 19;
10739
10740 } else if (type === LENS) {
10741 base = lbase;
10742 base_index -= 257;
10743 extra = lext;
10744 extra_index -= 257;
10745 end = 256;
10746
10747 } else { /* DISTS */
10748 base = dbase;
10749 extra = dext;
10750 end = -1;
10751 }
10752
10753 /* initialize opts for loop */
10754 huff = 0; /* starting code */
10755 sym = 0; /* starting code symbol */
10756 len = min; /* starting code length */
10757 next = table_index; /* current table to fill in */
10758 curr = root; /* current table index bits */
10759 drop = 0; /* current bits to drop from code for index */
10760 low = -1; /* trigger new sub-table when len > root */
10761 used = 1 << root; /* use root table entries */
10762 mask = used - 1; /* mask for comparing low */
10763
10764 /* check available table space */
10765 if ((type === LENS && used > ENOUGH_LENS) ||
10766 (type === DISTS && used > ENOUGH_DISTS)) {
10767 return 1;
10768 }
10769 /* process all codes and make table entries */
10770 for (;;) {
10771 /* create table entry */
10772 here_bits = len - drop;
10773 if (work[sym] < end) {
10774 here_op = 0;
10775 here_val = work[sym];
10776 } else if (work[sym] > end) {
10777 here_op = extra[extra_index + work[sym]];
10778 here_val = base[base_index + work[sym]];
10779 } else {
10780 here_op = 32 + 64; /* end of block */
10781 here_val = 0;
10782 }
10783
10784 /* replicate for those indices with low len bits equal to huff */
10785 incr = 1 << (len - drop);
10786 fill = 1 << curr;
10787 min = fill; /* save offset to next table */
10788 do {
10789 fill -= incr;
10790 table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val | 0;
10791 } while (fill !== 0);
10792
10793 /* backwards increment the len-bit code huff */
10794 incr = 1 << (len - 1);
10795 while (huff & incr) {
10796 incr >>= 1;
10797 }
10798 if (incr !== 0) {
10799 huff &= incr - 1;
10800 huff += incr;
10801 } else {
10802 huff = 0;
10803 }
10804
10805 /* go to next symbol, update count, len */
10806 sym++;
10807 if (--count[len] === 0) {
10808 if (len === max) {
10809 break;
10810 }
10811 len = lens[lens_index + work[sym]];
10812 }
10813
10814 /* create new sub-table if needed */
10815 if (len > root && (huff & mask) !== low) {
10816 /* if first time, transition to sub-tables */
10817 if (drop === 0) {
10818 drop = root;
10819 }
10820
10821 /* increment past last table */
10822 next += min; /* here min is 1 << curr */
10823
10824 /* determine length of next table */
10825 curr = len - drop;
10826 left = 1 << curr;
10827 while (curr + drop < max) {
10828 left -= count[curr + drop];
10829 if (left <= 0) {
10830 break;
10831 }
10832 curr++;
10833 left <<= 1;
10834 }
10835
10836 /* check for enough space */
10837 used += 1 << curr;
10838 if ((type === LENS && used > ENOUGH_LENS) ||
10839 (type === DISTS && used > ENOUGH_DISTS)) {
10840 return 1;
10841 }
10842
10843 /* point entry in root table to sub-table */
10844 low = huff & mask;
10845 /*table.op[low] = curr;
10846 table.bits[low] = root;
10847 table.val[low] = next - opts.table_index;*/
10848 table[low] = (root << 24) | (curr << 16) | (next - table_index) | 0;
10849 }
10850 }
10851
10852 /* fill in remaining table entry if code is incomplete (guaranteed to have
10853 at most one remaining entry, since if the code is incomplete, the
10854 maximum code length that was allowed to get this far is one bit) */
10855 if (huff !== 0) {
10856 //table.op[next + huff] = 64; /* invalid code marker */
10857 //table.bits[next + huff] = len - drop;
10858 //table.val[next + huff] = 0;
10859 table[next + huff] = ((len - drop) << 24) | (64 << 16) | 0;
10860 }
10861
10862 /* set return parameters */
10863 //opts.table_index += used;
10864 opts.bits = root;
10865 return 0;
10866}
10867
10868var CODES$1 = 0;
10869var LENS$1 = 1;
10870var DISTS$1 = 2;
10871
10872/* Public constants ==========================================================*/
10873/* ===========================================================================*/
10874
10875
10876/* Allowed flush values; see deflate() and inflate() below for details */
10877//var Z_NO_FLUSH = 0;
10878//var Z_PARTIAL_FLUSH = 1;
10879//var Z_SYNC_FLUSH = 2;
10880//var Z_FULL_FLUSH = 3;
10881var Z_FINISH$1 = 4;
10882var Z_BLOCK$1 = 5;
10883var Z_TREES = 6;
10884
10885
10886/* Return codes for the compression/decompression functions. Negative values
10887 * are errors, positive values are used for special but normal events.
10888 */
10889var Z_OK$1 = 0;
10890var Z_STREAM_END$1 = 1;
10891var Z_NEED_DICT = 2;
10892//var Z_ERRNO = -1;
10893var Z_STREAM_ERROR$1 = -2;
10894var Z_DATA_ERROR$1 = -3;
10895var Z_MEM_ERROR = -4;
10896var Z_BUF_ERROR$1 = -5;
10897//var Z_VERSION_ERROR = -6;
10898
10899/* The deflate compression method */
10900var Z_DEFLATED$1 = 8;
10901
10902
10903/* STATES ====================================================================*/
10904/* ===========================================================================*/
10905
10906
10907var HEAD = 1; /* i: waiting for magic header */
10908var FLAGS = 2; /* i: waiting for method and flags (gzip) */
10909var TIME = 3; /* i: waiting for modification time (gzip) */
10910var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
10911var EXLEN = 5; /* i: waiting for extra length (gzip) */
10912var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
10913var NAME = 7; /* i: waiting for end of file name (gzip) */
10914var COMMENT = 8; /* i: waiting for end of comment (gzip) */
10915var HCRC = 9; /* i: waiting for header crc (gzip) */
10916var DICTID = 10; /* i: waiting for dictionary check value */
10917var DICT = 11; /* waiting for inflateSetDictionary() call */
10918var TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */
10919var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
10920var STORED = 14; /* i: waiting for stored size (length and complement) */
10921var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
10922var COPY = 16; /* i/o: waiting for input or output to copy stored block */
10923var TABLE = 17; /* i: waiting for dynamic block table lengths */
10924var LENLENS = 18; /* i: waiting for code length code lengths */
10925var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
10926var LEN_ = 20; /* i: same as LEN below, but only first time in */
10927var LEN = 21; /* i: waiting for length/lit/eob code */
10928var LENEXT = 22; /* i: waiting for length extra bits */
10929var DIST = 23; /* i: waiting for distance code */
10930var DISTEXT = 24; /* i: waiting for distance extra bits */
10931var MATCH = 25; /* o: waiting for output space to copy string */
10932var LIT = 26; /* o: waiting for output space to write literal */
10933var CHECK = 27; /* i: waiting for 32-bit check value */
10934var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
10935var DONE = 29; /* finished check, done -- remain here until reset */
10936var BAD$1 = 30; /* got a data error -- remain here until reset */
10937var MEM = 31; /* got an inflate() memory error -- remain here until reset */
10938var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
10939
10940/* ===========================================================================*/
10941
10942
10943
10944var ENOUGH_LENS$1 = 852;
10945var ENOUGH_DISTS$1 = 592;
10946
10947
10948function zswap32(q) {
10949 return (((q >>> 24) & 0xff) +
10950 ((q >>> 8) & 0xff00) +
10951 ((q & 0xff00) << 8) +
10952 ((q & 0xff) << 24));
10953}
10954
10955
10956function InflateState() {
10957 this.mode = 0; /* current inflate mode */
10958 this.last = false; /* true if processing last block */
10959 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
10960 this.havedict = false; /* true if dictionary provided */
10961 this.flags = 0; /* gzip header method and flags (0 if zlib) */
10962 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
10963 this.check = 0; /* protected copy of check value */
10964 this.total = 0; /* protected copy of output count */
10965 // TODO: may be {}
10966 this.head = null; /* where to save gzip header information */
10967
10968 /* sliding window */
10969 this.wbits = 0; /* log base 2 of requested window size */
10970 this.wsize = 0; /* window size or zero if not using window */
10971 this.whave = 0; /* valid bytes in the window */
10972 this.wnext = 0; /* window write index */
10973 this.window = null; /* allocated sliding window, if needed */
10974
10975 /* bit accumulator */
10976 this.hold = 0; /* input bit accumulator */
10977 this.bits = 0; /* number of bits in "in" */
10978
10979 /* for string and stored block copying */
10980 this.length = 0; /* literal or length of data to copy */
10981 this.offset = 0; /* distance back to copy string from */
10982
10983 /* for table and code decoding */
10984 this.extra = 0; /* extra bits needed */
10985
10986 /* fixed and dynamic code tables */
10987 this.lencode = null; /* starting table for length/literal codes */
10988 this.distcode = null; /* starting table for distance codes */
10989 this.lenbits = 0; /* index bits for lencode */
10990 this.distbits = 0; /* index bits for distcode */
10991
10992 /* dynamic table building */
10993 this.ncode = 0; /* number of code length code lengths */
10994 this.nlen = 0; /* number of length code lengths */
10995 this.ndist = 0; /* number of distance code lengths */
10996 this.have = 0; /* number of code lengths in lens[] */
10997 this.next = null; /* next available space in codes[] */
10998
10999 this.lens = new Buf16(320); /* temporary storage for code lengths */
11000 this.work = new Buf16(288); /* work area for code table building */
11001
11002 /*
11003 because we don't have pointers in js, we use lencode and distcode directly
11004 as buffers so we don't need codes
11005 */
11006 //this.codes = new Buf32(ENOUGH); /* space for code tables */
11007 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
11008 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
11009 this.sane = 0; /* if false, allow invalid distance too far */
11010 this.back = 0; /* bits back of last unprocessed length/lit */
11011 this.was = 0; /* initial length of match */
11012}
11013
11014function inflateResetKeep(strm) {
11015 var state;
11016
11017 if (!strm || !strm.state) {
11018 return Z_STREAM_ERROR$1;
11019 }
11020 state = strm.state;
11021 strm.total_in = strm.total_out = state.total = 0;
11022 strm.msg = ''; /*Z_NULL*/
11023 if (state.wrap) { /* to support ill-conceived Java test suite */
11024 strm.adler = state.wrap & 1;
11025 }
11026 state.mode = HEAD;
11027 state.last = 0;
11028 state.havedict = 0;
11029 state.dmax = 32768;
11030 state.head = null /*Z_NULL*/ ;
11031 state.hold = 0;
11032 state.bits = 0;
11033 //state.lencode = state.distcode = state.next = state.codes;
11034 state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1);
11035 state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1);
11036
11037 state.sane = 1;
11038 state.back = -1;
11039 //Tracev((stderr, "inflate: reset\n"));
11040 return Z_OK$1;
11041}
11042
11043function inflateReset(strm) {
11044 var state;
11045
11046 if (!strm || !strm.state) {
11047 return Z_STREAM_ERROR$1;
11048 }
11049 state = strm.state;
11050 state.wsize = 0;
11051 state.whave = 0;
11052 state.wnext = 0;
11053 return inflateResetKeep(strm);
11054
11055}
11056
11057function inflateReset2(strm, windowBits) {
11058 var wrap;
11059 var state;
11060
11061 /* get the state */
11062 if (!strm || !strm.state) {
11063 return Z_STREAM_ERROR$1;
11064 }
11065 state = strm.state;
11066
11067 /* extract wrap request from windowBits parameter */
11068 if (windowBits < 0) {
11069 wrap = 0;
11070 windowBits = -windowBits;
11071 } else {
11072 wrap = (windowBits >> 4) + 1;
11073 if (windowBits < 48) {
11074 windowBits &= 15;
11075 }
11076 }
11077
11078 /* set number of window bits, free window if different */
11079 if (windowBits && (windowBits < 8 || windowBits > 15)) {
11080 return Z_STREAM_ERROR$1;
11081 }
11082 if (state.window !== null && state.wbits !== windowBits) {
11083 state.window = null;
11084 }
11085
11086 /* update state and reset the rest of it */
11087 state.wrap = wrap;
11088 state.wbits = windowBits;
11089 return inflateReset(strm);
11090}
11091
11092function inflateInit2(strm, windowBits) {
11093 var ret;
11094 var state;
11095
11096 if (!strm) {
11097 return Z_STREAM_ERROR$1;
11098 }
11099 //strm.msg = Z_NULL; /* in case we return an error */
11100
11101 state = new InflateState();
11102
11103 //if (state === Z_NULL) return Z_MEM_ERROR;
11104 //Tracev((stderr, "inflate: allocated\n"));
11105 strm.state = state;
11106 state.window = null /*Z_NULL*/ ;
11107 ret = inflateReset2(strm, windowBits);
11108 if (ret !== Z_OK$1) {
11109 strm.state = null /*Z_NULL*/ ;
11110 }
11111 return ret;
11112}
11113
11114
11115/*
11116 Return state with length and distance decoding tables and index sizes set to
11117 fixed code decoding. Normally this returns fixed tables from inffixed.h.
11118 If BUILDFIXED is defined, then instead this routine builds the tables the
11119 first time it's called, and returns those tables the first time and
11120 thereafter. This reduces the size of the code by about 2K bytes, in
11121 exchange for a little execution time. However, BUILDFIXED should not be
11122 used for threaded applications, since the rewriting of the tables and virgin
11123 may not be thread-safe.
11124 */
11125var virgin = true;
11126
11127var lenfix, distfix; // We have no pointers in JS, so keep tables separate
11128
11129function fixedtables(state) {
11130 /* build fixed huffman tables if first call (may not be thread safe) */
11131 if (virgin) {
11132 var sym;
11133
11134 lenfix = new Buf32(512);
11135 distfix = new Buf32(32);
11136
11137 /* literal/length table */
11138 sym = 0;
11139 while (sym < 144) {
11140 state.lens[sym++] = 8;
11141 }
11142 while (sym < 256) {
11143 state.lens[sym++] = 9;
11144 }
11145 while (sym < 280) {
11146 state.lens[sym++] = 7;
11147 }
11148 while (sym < 288) {
11149 state.lens[sym++] = 8;
11150 }
11151
11152 inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, {
11153 bits: 9
11154 });
11155
11156 /* distance table */
11157 sym = 0;
11158 while (sym < 32) {
11159 state.lens[sym++] = 5;
11160 }
11161
11162 inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, {
11163 bits: 5
11164 });
11165
11166 /* do this just once */
11167 virgin = false;
11168 }
11169
11170 state.lencode = lenfix;
11171 state.lenbits = 9;
11172 state.distcode = distfix;
11173 state.distbits = 5;
11174}
11175
11176
11177/*
11178 Update the window with the last wsize (normally 32K) bytes written before
11179 returning. If window does not exist yet, create it. This is only called
11180 when a window is already in use, or when output has been written during this
11181 inflate call, but the end of the deflate stream has not been reached yet.
11182 It is also called to create a window for dictionary data when a dictionary
11183 is loaded.
11184
11185 Providing output buffers larger than 32K to inflate() should provide a speed
11186 advantage, since only the last 32K of output is copied to the sliding window
11187 upon return from inflate(), and since all distances after the first 32K of
11188 output will fall in the output data, making match copies simpler and faster.
11189 The advantage may be dependent on the size of the processor's data caches.
11190 */
11191function updatewindow(strm, src, end, copy) {
11192 var dist;
11193 var state = strm.state;
11194
11195 /* if it hasn't been done already, allocate space for the window */
11196 if (state.window === null) {
11197 state.wsize = 1 << state.wbits;
11198 state.wnext = 0;
11199 state.whave = 0;
11200
11201 state.window = new Buf8(state.wsize);
11202 }
11203
11204 /* copy state->wsize or less output bytes into the circular window */
11205 if (copy >= state.wsize) {
11206 arraySet(state.window, src, end - state.wsize, state.wsize, 0);
11207 state.wnext = 0;
11208 state.whave = state.wsize;
11209 } else {
11210 dist = state.wsize - state.wnext;
11211 if (dist > copy) {
11212 dist = copy;
11213 }
11214 //zmemcpy(state->window + state->wnext, end - copy, dist);
11215 arraySet(state.window, src, end - copy, dist, state.wnext);
11216 copy -= dist;
11217 if (copy) {
11218 //zmemcpy(state->window, end - copy, copy);
11219 arraySet(state.window, src, end - copy, copy, 0);
11220 state.wnext = copy;
11221 state.whave = state.wsize;
11222 } else {
11223 state.wnext += dist;
11224 if (state.wnext === state.wsize) {
11225 state.wnext = 0;
11226 }
11227 if (state.whave < state.wsize) {
11228 state.whave += dist;
11229 }
11230 }
11231 }
11232 return 0;
11233}
11234
11235function inflate(strm, flush) {
11236 var state;
11237 var input, output; // input/output buffers
11238 var next; /* next input INDEX */
11239 var put; /* next output INDEX */
11240 var have, left; /* available input and output */
11241 var hold; /* bit buffer */
11242 var bits; /* bits in bit buffer */
11243 var _in, _out; /* save starting available input and output */
11244 var copy; /* number of stored or match bytes to copy */
11245 var from; /* where to copy match bytes from */
11246 var from_source;
11247 var here = 0; /* current decoding table entry */
11248 var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
11249 //var last; /* parent table entry */
11250 var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
11251 var len; /* length to copy for repeats, bits to drop */
11252 var ret; /* return code */
11253 var hbuf = new Buf8(4); /* buffer for gzip header crc calculation */
11254 var opts;
11255
11256 var n; // temporary var for NEED_BITS
11257
11258 var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
11259
11260
11261 if (!strm || !strm.state || !strm.output ||
11262 (!strm.input && strm.avail_in !== 0)) {
11263 return Z_STREAM_ERROR$1;
11264 }
11265
11266 state = strm.state;
11267 if (state.mode === TYPE$1) {
11268 state.mode = TYPEDO;
11269 } /* skip check */
11270
11271
11272 //--- LOAD() ---
11273 put = strm.next_out;
11274 output = strm.output;
11275 left = strm.avail_out;
11276 next = strm.next_in;
11277 input = strm.input;
11278 have = strm.avail_in;
11279 hold = state.hold;
11280 bits = state.bits;
11281 //---
11282
11283 _in = have;
11284 _out = left;
11285 ret = Z_OK$1;
11286
11287 inf_leave: // goto emulation
11288 for (;;) {
11289 switch (state.mode) {
11290 case HEAD:
11291 if (state.wrap === 0) {
11292 state.mode = TYPEDO;
11293 break;
11294 }
11295 //=== NEEDBITS(16);
11296 while (bits < 16) {
11297 if (have === 0) {
11298 break inf_leave;
11299 }
11300 have--;
11301 hold += input[next++] << bits;
11302 bits += 8;
11303 }
11304 //===//
11305 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
11306 state.check = 0 /*crc32(0L, Z_NULL, 0)*/ ;
11307 //=== CRC2(state.check, hold);
11308 hbuf[0] = hold & 0xff;
11309 hbuf[1] = (hold >>> 8) & 0xff;
11310 state.check = crc32(state.check, hbuf, 2, 0);
11311 //===//
11312
11313 //=== INITBITS();
11314 hold = 0;
11315 bits = 0;
11316 //===//
11317 state.mode = FLAGS;
11318 break;
11319 }
11320 state.flags = 0; /* expect zlib header */
11321 if (state.head) {
11322 state.head.done = false;
11323 }
11324 if (!(state.wrap & 1) || /* check if zlib header allowed */
11325 (((hold & 0xff) /*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
11326 strm.msg = 'incorrect header check';
11327 state.mode = BAD$1;
11328 break;
11329 }
11330 if ((hold & 0x0f) /*BITS(4)*/ !== Z_DEFLATED$1) {
11331 strm.msg = 'unknown compression method';
11332 state.mode = BAD$1;
11333 break;
11334 }
11335 //--- DROPBITS(4) ---//
11336 hold >>>= 4;
11337 bits -= 4;
11338 //---//
11339 len = (hold & 0x0f) /*BITS(4)*/ + 8;
11340 if (state.wbits === 0) {
11341 state.wbits = len;
11342 } else if (len > state.wbits) {
11343 strm.msg = 'invalid window size';
11344 state.mode = BAD$1;
11345 break;
11346 }
11347 state.dmax = 1 << len;
11348 //Tracev((stderr, "inflate: zlib header ok\n"));
11349 strm.adler = state.check = 1 /*adler32(0L, Z_NULL, 0)*/ ;
11350 state.mode = hold & 0x200 ? DICTID : TYPE$1;
11351 //=== INITBITS();
11352 hold = 0;
11353 bits = 0;
11354 //===//
11355 break;
11356 case FLAGS:
11357 //=== NEEDBITS(16); */
11358 while (bits < 16) {
11359 if (have === 0) {
11360 break inf_leave;
11361 }
11362 have--;
11363 hold += input[next++] << bits;
11364 bits += 8;
11365 }
11366 //===//
11367 state.flags = hold;
11368 if ((state.flags & 0xff) !== Z_DEFLATED$1) {
11369 strm.msg = 'unknown compression method';
11370 state.mode = BAD$1;
11371 break;
11372 }
11373 if (state.flags & 0xe000) {
11374 strm.msg = 'unknown header flags set';
11375 state.mode = BAD$1;
11376 break;
11377 }
11378 if (state.head) {
11379 state.head.text = ((hold >> 8) & 1);
11380 }
11381 if (state.flags & 0x0200) {
11382 //=== CRC2(state.check, hold);
11383 hbuf[0] = hold & 0xff;
11384 hbuf[1] = (hold >>> 8) & 0xff;
11385 state.check = crc32(state.check, hbuf, 2, 0);
11386 //===//
11387 }
11388 //=== INITBITS();
11389 hold = 0;
11390 bits = 0;
11391 //===//
11392 state.mode = TIME;
11393 /* falls through */
11394 case TIME:
11395 //=== NEEDBITS(32); */
11396 while (bits < 32) {
11397 if (have === 0) {
11398 break inf_leave;
11399 }
11400 have--;
11401 hold += input[next++] << bits;
11402 bits += 8;
11403 }
11404 //===//
11405 if (state.head) {
11406 state.head.time = hold;
11407 }
11408 if (state.flags & 0x0200) {
11409 //=== CRC4(state.check, hold)
11410 hbuf[0] = hold & 0xff;
11411 hbuf[1] = (hold >>> 8) & 0xff;
11412 hbuf[2] = (hold >>> 16) & 0xff;
11413 hbuf[3] = (hold >>> 24) & 0xff;
11414 state.check = crc32(state.check, hbuf, 4, 0);
11415 //===
11416 }
11417 //=== INITBITS();
11418 hold = 0;
11419 bits = 0;
11420 //===//
11421 state.mode = OS;
11422 /* falls through */
11423 case OS:
11424 //=== NEEDBITS(16); */
11425 while (bits < 16) {
11426 if (have === 0) {
11427 break inf_leave;
11428 }
11429 have--;
11430 hold += input[next++] << bits;
11431 bits += 8;
11432 }
11433 //===//
11434 if (state.head) {
11435 state.head.xflags = (hold & 0xff);
11436 state.head.os = (hold >> 8);
11437 }
11438 if (state.flags & 0x0200) {
11439 //=== CRC2(state.check, hold);
11440 hbuf[0] = hold & 0xff;
11441 hbuf[1] = (hold >>> 8) & 0xff;
11442 state.check = crc32(state.check, hbuf, 2, 0);
11443 //===//
11444 }
11445 //=== INITBITS();
11446 hold = 0;
11447 bits = 0;
11448 //===//
11449 state.mode = EXLEN;
11450 /* falls through */
11451 case EXLEN:
11452 if (state.flags & 0x0400) {
11453 //=== NEEDBITS(16); */
11454 while (bits < 16) {
11455 if (have === 0) {
11456 break inf_leave;
11457 }
11458 have--;
11459 hold += input[next++] << bits;
11460 bits += 8;
11461 }
11462 //===//
11463 state.length = hold;
11464 if (state.head) {
11465 state.head.extra_len = hold;
11466 }
11467 if (state.flags & 0x0200) {
11468 //=== CRC2(state.check, hold);
11469 hbuf[0] = hold & 0xff;
11470 hbuf[1] = (hold >>> 8) & 0xff;
11471 state.check = crc32(state.check, hbuf, 2, 0);
11472 //===//
11473 }
11474 //=== INITBITS();
11475 hold = 0;
11476 bits = 0;
11477 //===//
11478 } else if (state.head) {
11479 state.head.extra = null /*Z_NULL*/ ;
11480 }
11481 state.mode = EXTRA;
11482 /* falls through */
11483 case EXTRA:
11484 if (state.flags & 0x0400) {
11485 copy = state.length;
11486 if (copy > have) {
11487 copy = have;
11488 }
11489 if (copy) {
11490 if (state.head) {
11491 len = state.head.extra_len - state.length;
11492 if (!state.head.extra) {
11493 // Use untyped array for more conveniend processing later
11494 state.head.extra = new Array(state.head.extra_len);
11495 }
11496 arraySet(
11497 state.head.extra,
11498 input,
11499 next,
11500 // extra field is limited to 65536 bytes
11501 // - no need for additional size check
11502 copy,
11503 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
11504 len
11505 );
11506 //zmemcpy(state.head.extra + len, next,
11507 // len + copy > state.head.extra_max ?
11508 // state.head.extra_max - len : copy);
11509 }
11510 if (state.flags & 0x0200) {
11511 state.check = crc32(state.check, input, copy, next);
11512 }
11513 have -= copy;
11514 next += copy;
11515 state.length -= copy;
11516 }
11517 if (state.length) {
11518 break inf_leave;
11519 }
11520 }
11521 state.length = 0;
11522 state.mode = NAME;
11523 /* falls through */
11524 case NAME:
11525 if (state.flags & 0x0800) {
11526 if (have === 0) {
11527 break inf_leave;
11528 }
11529 copy = 0;
11530 do {
11531 // TODO: 2 or 1 bytes?
11532 len = input[next + copy++];
11533 /* use constant limit because in js we should not preallocate memory */
11534 if (state.head && len &&
11535 (state.length < 65536 /*state.head.name_max*/ )) {
11536 state.head.name += String.fromCharCode(len);
11537 }
11538 } while (len && copy < have);
11539
11540 if (state.flags & 0x0200) {
11541 state.check = crc32(state.check, input, copy, next);
11542 }
11543 have -= copy;
11544 next += copy;
11545 if (len) {
11546 break inf_leave;
11547 }
11548 } else if (state.head) {
11549 state.head.name = null;
11550 }
11551 state.length = 0;
11552 state.mode = COMMENT;
11553 /* falls through */
11554 case COMMENT:
11555 if (state.flags & 0x1000) {
11556 if (have === 0) {
11557 break inf_leave;
11558 }
11559 copy = 0;
11560 do {
11561 len = input[next + copy++];
11562 /* use constant limit because in js we should not preallocate memory */
11563 if (state.head && len &&
11564 (state.length < 65536 /*state.head.comm_max*/ )) {
11565 state.head.comment += String.fromCharCode(len);
11566 }
11567 } while (len && copy < have);
11568 if (state.flags & 0x0200) {
11569 state.check = crc32(state.check, input, copy, next);
11570 }
11571 have -= copy;
11572 next += copy;
11573 if (len) {
11574 break inf_leave;
11575 }
11576 } else if (state.head) {
11577 state.head.comment = null;
11578 }
11579 state.mode = HCRC;
11580 /* falls through */
11581 case HCRC:
11582 if (state.flags & 0x0200) {
11583 //=== NEEDBITS(16); */
11584 while (bits < 16) {
11585 if (have === 0) {
11586 break inf_leave;
11587 }
11588 have--;
11589 hold += input[next++] << bits;
11590 bits += 8;
11591 }
11592 //===//
11593 if (hold !== (state.check & 0xffff)) {
11594 strm.msg = 'header crc mismatch';
11595 state.mode = BAD$1;
11596 break;
11597 }
11598 //=== INITBITS();
11599 hold = 0;
11600 bits = 0;
11601 //===//
11602 }
11603 if (state.head) {
11604 state.head.hcrc = ((state.flags >> 9) & 1);
11605 state.head.done = true;
11606 }
11607 strm.adler = state.check = 0;
11608 state.mode = TYPE$1;
11609 break;
11610 case DICTID:
11611 //=== NEEDBITS(32); */
11612 while (bits < 32) {
11613 if (have === 0) {
11614 break inf_leave;
11615 }
11616 have--;
11617 hold += input[next++] << bits;
11618 bits += 8;
11619 }
11620 //===//
11621 strm.adler = state.check = zswap32(hold);
11622 //=== INITBITS();
11623 hold = 0;
11624 bits = 0;
11625 //===//
11626 state.mode = DICT;
11627 /* falls through */
11628 case DICT:
11629 if (state.havedict === 0) {
11630 //--- RESTORE() ---
11631 strm.next_out = put;
11632 strm.avail_out = left;
11633 strm.next_in = next;
11634 strm.avail_in = have;
11635 state.hold = hold;
11636 state.bits = bits;
11637 //---
11638 return Z_NEED_DICT;
11639 }
11640 strm.adler = state.check = 1 /*adler32(0L, Z_NULL, 0)*/ ;
11641 state.mode = TYPE$1;
11642 /* falls through */
11643 case TYPE$1:
11644 if (flush === Z_BLOCK$1 || flush === Z_TREES) {
11645 break inf_leave;
11646 }
11647 /* falls through */
11648 case TYPEDO:
11649 if (state.last) {
11650 //--- BYTEBITS() ---//
11651 hold >>>= bits & 7;
11652 bits -= bits & 7;
11653 //---//
11654 state.mode = CHECK;
11655 break;
11656 }
11657 //=== NEEDBITS(3); */
11658 while (bits < 3) {
11659 if (have === 0) {
11660 break inf_leave;
11661 }
11662 have--;
11663 hold += input[next++] << bits;
11664 bits += 8;
11665 }
11666 //===//
11667 state.last = (hold & 0x01) /*BITS(1)*/ ;
11668 //--- DROPBITS(1) ---//
11669 hold >>>= 1;
11670 bits -= 1;
11671 //---//
11672
11673 switch ((hold & 0x03) /*BITS(2)*/ ) {
11674 case 0:
11675 /* stored block */
11676 //Tracev((stderr, "inflate: stored block%s\n",
11677 // state.last ? " (last)" : ""));
11678 state.mode = STORED;
11679 break;
11680 case 1:
11681 /* fixed block */
11682 fixedtables(state);
11683 //Tracev((stderr, "inflate: fixed codes block%s\n",
11684 // state.last ? " (last)" : ""));
11685 state.mode = LEN_; /* decode codes */
11686 if (flush === Z_TREES) {
11687 //--- DROPBITS(2) ---//
11688 hold >>>= 2;
11689 bits -= 2;
11690 //---//
11691 break inf_leave;
11692 }
11693 break;
11694 case 2:
11695 /* dynamic block */
11696 //Tracev((stderr, "inflate: dynamic codes block%s\n",
11697 // state.last ? " (last)" : ""));
11698 state.mode = TABLE;
11699 break;
11700 case 3:
11701 strm.msg = 'invalid block type';
11702 state.mode = BAD$1;
11703 }
11704 //--- DROPBITS(2) ---//
11705 hold >>>= 2;
11706 bits -= 2;
11707 //---//
11708 break;
11709 case STORED:
11710 //--- BYTEBITS() ---// /* go to byte boundary */
11711 hold >>>= bits & 7;
11712 bits -= bits & 7;
11713 //---//
11714 //=== NEEDBITS(32); */
11715 while (bits < 32) {
11716 if (have === 0) {
11717 break inf_leave;
11718 }
11719 have--;
11720 hold += input[next++] << bits;
11721 bits += 8;
11722 }
11723 //===//
11724 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
11725 strm.msg = 'invalid stored block lengths';
11726 state.mode = BAD$1;
11727 break;
11728 }
11729 state.length = hold & 0xffff;
11730 //Tracev((stderr, "inflate: stored length %u\n",
11731 // state.length));
11732 //=== INITBITS();
11733 hold = 0;
11734 bits = 0;
11735 //===//
11736 state.mode = COPY_;
11737 if (flush === Z_TREES) {
11738 break inf_leave;
11739 }
11740 /* falls through */
11741 case COPY_:
11742 state.mode = COPY;
11743 /* falls through */
11744 case COPY:
11745 copy = state.length;
11746 if (copy) {
11747 if (copy > have) {
11748 copy = have;
11749 }
11750 if (copy > left) {
11751 copy = left;
11752 }
11753 if (copy === 0) {
11754 break inf_leave;
11755 }
11756 //--- zmemcpy(put, next, copy); ---
11757 arraySet(output, input, next, copy, put);
11758 //---//
11759 have -= copy;
11760 next += copy;
11761 left -= copy;
11762 put += copy;
11763 state.length -= copy;
11764 break;
11765 }
11766 //Tracev((stderr, "inflate: stored end\n"));
11767 state.mode = TYPE$1;
11768 break;
11769 case TABLE:
11770 //=== NEEDBITS(14); */
11771 while (bits < 14) {
11772 if (have === 0) {
11773 break inf_leave;
11774 }
11775 have--;
11776 hold += input[next++] << bits;
11777 bits += 8;
11778 }
11779 //===//
11780 state.nlen = (hold & 0x1f) /*BITS(5)*/ + 257;
11781 //--- DROPBITS(5) ---//
11782 hold >>>= 5;
11783 bits -= 5;
11784 //---//
11785 state.ndist = (hold & 0x1f) /*BITS(5)*/ + 1;
11786 //--- DROPBITS(5) ---//
11787 hold >>>= 5;
11788 bits -= 5;
11789 //---//
11790 state.ncode = (hold & 0x0f) /*BITS(4)*/ + 4;
11791 //--- DROPBITS(4) ---//
11792 hold >>>= 4;
11793 bits -= 4;
11794 //---//
11795 //#ifndef PKZIP_BUG_WORKAROUND
11796 if (state.nlen > 286 || state.ndist > 30) {
11797 strm.msg = 'too many length or distance symbols';
11798 state.mode = BAD$1;
11799 break;
11800 }
11801 //#endif
11802 //Tracev((stderr, "inflate: table sizes ok\n"));
11803 state.have = 0;
11804 state.mode = LENLENS;
11805 /* falls through */
11806 case LENLENS:
11807 while (state.have < state.ncode) {
11808 //=== NEEDBITS(3);
11809 while (bits < 3) {
11810 if (have === 0) {
11811 break inf_leave;
11812 }
11813 have--;
11814 hold += input[next++] << bits;
11815 bits += 8;
11816 }
11817 //===//
11818 state.lens[order[state.have++]] = (hold & 0x07); //BITS(3);
11819 //--- DROPBITS(3) ---//
11820 hold >>>= 3;
11821 bits -= 3;
11822 //---//
11823 }
11824 while (state.have < 19) {
11825 state.lens[order[state.have++]] = 0;
11826 }
11827 // We have separate tables & no pointers. 2 commented lines below not needed.
11828 //state.next = state.codes;
11829 //state.lencode = state.next;
11830 // Switch to use dynamic table
11831 state.lencode = state.lendyn;
11832 state.lenbits = 7;
11833
11834 opts = {
11835 bits: state.lenbits
11836 };
11837 ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);
11838 state.lenbits = opts.bits;
11839
11840 if (ret) {
11841 strm.msg = 'invalid code lengths set';
11842 state.mode = BAD$1;
11843 break;
11844 }
11845 //Tracev((stderr, "inflate: code lengths ok\n"));
11846 state.have = 0;
11847 state.mode = CODELENS;
11848 /* falls through */
11849 case CODELENS:
11850 while (state.have < state.nlen + state.ndist) {
11851 for (;;) {
11852 here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
11853 here_bits = here >>> 24;
11854 here_op = (here >>> 16) & 0xff;
11855 here_val = here & 0xffff;
11856
11857 if ((here_bits) <= bits) {
11858 break;
11859 }
11860 //--- PULLBYTE() ---//
11861 if (have === 0) {
11862 break inf_leave;
11863 }
11864 have--;
11865 hold += input[next++] << bits;
11866 bits += 8;
11867 //---//
11868 }
11869 if (here_val < 16) {
11870 //--- DROPBITS(here.bits) ---//
11871 hold >>>= here_bits;
11872 bits -= here_bits;
11873 //---//
11874 state.lens[state.have++] = here_val;
11875 } else {
11876 if (here_val === 16) {
11877 //=== NEEDBITS(here.bits + 2);
11878 n = here_bits + 2;
11879 while (bits < n) {
11880 if (have === 0) {
11881 break inf_leave;
11882 }
11883 have--;
11884 hold += input[next++] << bits;
11885 bits += 8;
11886 }
11887 //===//
11888 //--- DROPBITS(here.bits) ---//
11889 hold >>>= here_bits;
11890 bits -= here_bits;
11891 //---//
11892 if (state.have === 0) {
11893 strm.msg = 'invalid bit length repeat';
11894 state.mode = BAD$1;
11895 break;
11896 }
11897 len = state.lens[state.have - 1];
11898 copy = 3 + (hold & 0x03); //BITS(2);
11899 //--- DROPBITS(2) ---//
11900 hold >>>= 2;
11901 bits -= 2;
11902 //---//
11903 } else if (here_val === 17) {
11904 //=== NEEDBITS(here.bits + 3);
11905 n = here_bits + 3;
11906 while (bits < n) {
11907 if (have === 0) {
11908 break inf_leave;
11909 }
11910 have--;
11911 hold += input[next++] << bits;
11912 bits += 8;
11913 }
11914 //===//
11915 //--- DROPBITS(here.bits) ---//
11916 hold >>>= here_bits;
11917 bits -= here_bits;
11918 //---//
11919 len = 0;
11920 copy = 3 + (hold & 0x07); //BITS(3);
11921 //--- DROPBITS(3) ---//
11922 hold >>>= 3;
11923 bits -= 3;
11924 //---//
11925 } else {
11926 //=== NEEDBITS(here.bits + 7);
11927 n = here_bits + 7;
11928 while (bits < n) {
11929 if (have === 0) {
11930 break inf_leave;
11931 }
11932 have--;
11933 hold += input[next++] << bits;
11934 bits += 8;
11935 }
11936 //===//
11937 //--- DROPBITS(here.bits) ---//
11938 hold >>>= here_bits;
11939 bits -= here_bits;
11940 //---//
11941 len = 0;
11942 copy = 11 + (hold & 0x7f); //BITS(7);
11943 //--- DROPBITS(7) ---//
11944 hold >>>= 7;
11945 bits -= 7;
11946 //---//
11947 }
11948 if (state.have + copy > state.nlen + state.ndist) {
11949 strm.msg = 'invalid bit length repeat';
11950 state.mode = BAD$1;
11951 break;
11952 }
11953 while (copy--) {
11954 state.lens[state.have++] = len;
11955 }
11956 }
11957 }
11958
11959 /* handle error breaks in while */
11960 if (state.mode === BAD$1) {
11961 break;
11962 }
11963
11964 /* check for end-of-block code (better have one) */
11965 if (state.lens[256] === 0) {
11966 strm.msg = 'invalid code -- missing end-of-block';
11967 state.mode = BAD$1;
11968 break;
11969 }
11970
11971 /* build code tables -- note: do not change the lenbits or distbits
11972 values here (9 and 6) without reading the comments in inftrees.h
11973 concerning the ENOUGH constants, which depend on those values */
11974 state.lenbits = 9;
11975
11976 opts = {
11977 bits: state.lenbits
11978 };
11979 ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
11980 // We have separate tables & no pointers. 2 commented lines below not needed.
11981 // state.next_index = opts.table_index;
11982 state.lenbits = opts.bits;
11983 // state.lencode = state.next;
11984
11985 if (ret) {
11986 strm.msg = 'invalid literal/lengths set';
11987 state.mode = BAD$1;
11988 break;
11989 }
11990
11991 state.distbits = 6;
11992 //state.distcode.copy(state.codes);
11993 // Switch to use dynamic table
11994 state.distcode = state.distdyn;
11995 opts = {
11996 bits: state.distbits
11997 };
11998 ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
11999 // We have separate tables & no pointers. 2 commented lines below not needed.
12000 // state.next_index = opts.table_index;
12001 state.distbits = opts.bits;
12002 // state.distcode = state.next;
12003
12004 if (ret) {
12005 strm.msg = 'invalid distances set';
12006 state.mode = BAD$1;
12007 break;
12008 }
12009 //Tracev((stderr, 'inflate: codes ok\n'));
12010 state.mode = LEN_;
12011 if (flush === Z_TREES) {
12012 break inf_leave;
12013 }
12014 /* falls through */
12015 case LEN_:
12016 state.mode = LEN;
12017 /* falls through */
12018 case LEN:
12019 if (have >= 6 && left >= 258) {
12020 //--- RESTORE() ---
12021 strm.next_out = put;
12022 strm.avail_out = left;
12023 strm.next_in = next;
12024 strm.avail_in = have;
12025 state.hold = hold;
12026 state.bits = bits;
12027 //---
12028 inflate_fast(strm, _out);
12029 //--- LOAD() ---
12030 put = strm.next_out;
12031 output = strm.output;
12032 left = strm.avail_out;
12033 next = strm.next_in;
12034 input = strm.input;
12035 have = strm.avail_in;
12036 hold = state.hold;
12037 bits = state.bits;
12038 //---
12039
12040 if (state.mode === TYPE$1) {
12041 state.back = -1;
12042 }
12043 break;
12044 }
12045 state.back = 0;
12046 for (;;) {
12047 here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
12048 here_bits = here >>> 24;
12049 here_op = (here >>> 16) & 0xff;
12050 here_val = here & 0xffff;
12051
12052 if (here_bits <= bits) {
12053 break;
12054 }
12055 //--- PULLBYTE() ---//
12056 if (have === 0) {
12057 break inf_leave;
12058 }
12059 have--;
12060 hold += input[next++] << bits;
12061 bits += 8;
12062 //---//
12063 }
12064 if (here_op && (here_op & 0xf0) === 0) {
12065 last_bits = here_bits;
12066 last_op = here_op;
12067 last_val = here_val;
12068 for (;;) {
12069 here = state.lencode[last_val +
12070 ((hold & ((1 << (last_bits + last_op)) - 1)) /*BITS(last.bits + last.op)*/ >> last_bits)];
12071 here_bits = here >>> 24;
12072 here_op = (here >>> 16) & 0xff;
12073 here_val = here & 0xffff;
12074
12075 if ((last_bits + here_bits) <= bits) {
12076 break;
12077 }
12078 //--- PULLBYTE() ---//
12079 if (have === 0) {
12080 break inf_leave;
12081 }
12082 have--;
12083 hold += input[next++] << bits;
12084 bits += 8;
12085 //---//
12086 }
12087 //--- DROPBITS(last.bits) ---//
12088 hold >>>= last_bits;
12089 bits -= last_bits;
12090 //---//
12091 state.back += last_bits;
12092 }
12093 //--- DROPBITS(here.bits) ---//
12094 hold >>>= here_bits;
12095 bits -= here_bits;
12096 //---//
12097 state.back += here_bits;
12098 state.length = here_val;
12099 if (here_op === 0) {
12100 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
12101 // "inflate: literal '%c'\n" :
12102 // "inflate: literal 0x%02x\n", here.val));
12103 state.mode = LIT;
12104 break;
12105 }
12106 if (here_op & 32) {
12107 //Tracevv((stderr, "inflate: end of block\n"));
12108 state.back = -1;
12109 state.mode = TYPE$1;
12110 break;
12111 }
12112 if (here_op & 64) {
12113 strm.msg = 'invalid literal/length code';
12114 state.mode = BAD$1;
12115 break;
12116 }
12117 state.extra = here_op & 15;
12118 state.mode = LENEXT;
12119 /* falls through */
12120 case LENEXT:
12121 if (state.extra) {
12122 //=== NEEDBITS(state.extra);
12123 n = state.extra;
12124 while (bits < n) {
12125 if (have === 0) {
12126 break inf_leave;
12127 }
12128 have--;
12129 hold += input[next++] << bits;
12130 bits += 8;
12131 }
12132 //===//
12133 state.length += hold & ((1 << state.extra) - 1) /*BITS(state.extra)*/ ;
12134 //--- DROPBITS(state.extra) ---//
12135 hold >>>= state.extra;
12136 bits -= state.extra;
12137 //---//
12138 state.back += state.extra;
12139 }
12140 //Tracevv((stderr, "inflate: length %u\n", state.length));
12141 state.was = state.length;
12142 state.mode = DIST;
12143 /* falls through */
12144 case DIST:
12145 for (;;) {
12146 here = state.distcode[hold & ((1 << state.distbits) - 1)]; /*BITS(state.distbits)*/
12147 here_bits = here >>> 24;
12148 here_op = (here >>> 16) & 0xff;
12149 here_val = here & 0xffff;
12150
12151 if ((here_bits) <= bits) {
12152 break;
12153 }
12154 //--- PULLBYTE() ---//
12155 if (have === 0) {
12156 break inf_leave;
12157 }
12158 have--;
12159 hold += input[next++] << bits;
12160 bits += 8;
12161 //---//
12162 }
12163 if ((here_op & 0xf0) === 0) {
12164 last_bits = here_bits;
12165 last_op = here_op;
12166 last_val = here_val;
12167 for (;;) {
12168 here = state.distcode[last_val +
12169 ((hold & ((1 << (last_bits + last_op)) - 1)) /*BITS(last.bits + last.op)*/ >> last_bits)];
12170 here_bits = here >>> 24;
12171 here_op = (here >>> 16) & 0xff;
12172 here_val = here & 0xffff;
12173
12174 if ((last_bits + here_bits) <= bits) {
12175 break;
12176 }
12177 //--- PULLBYTE() ---//
12178 if (have === 0) {
12179 break inf_leave;
12180 }
12181 have--;
12182 hold += input[next++] << bits;
12183 bits += 8;
12184 //---//
12185 }
12186 //--- DROPBITS(last.bits) ---//
12187 hold >>>= last_bits;
12188 bits -= last_bits;
12189 //---//
12190 state.back += last_bits;
12191 }
12192 //--- DROPBITS(here.bits) ---//
12193 hold >>>= here_bits;
12194 bits -= here_bits;
12195 //---//
12196 state.back += here_bits;
12197 if (here_op & 64) {
12198 strm.msg = 'invalid distance code';
12199 state.mode = BAD$1;
12200 break;
12201 }
12202 state.offset = here_val;
12203 state.extra = (here_op) & 15;
12204 state.mode = DISTEXT;
12205 /* falls through */
12206 case DISTEXT:
12207 if (state.extra) {
12208 //=== NEEDBITS(state.extra);
12209 n = state.extra;
12210 while (bits < n) {
12211 if (have === 0) {
12212 break inf_leave;
12213 }
12214 have--;
12215 hold += input[next++] << bits;
12216 bits += 8;
12217 }
12218 //===//
12219 state.offset += hold & ((1 << state.extra) - 1) /*BITS(state.extra)*/ ;
12220 //--- DROPBITS(state.extra) ---//
12221 hold >>>= state.extra;
12222 bits -= state.extra;
12223 //---//
12224 state.back += state.extra;
12225 }
12226 //#ifdef INFLATE_STRICT
12227 if (state.offset > state.dmax) {
12228 strm.msg = 'invalid distance too far back';
12229 state.mode = BAD$1;
12230 break;
12231 }
12232 //#endif
12233 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
12234 state.mode = MATCH;
12235 /* falls through */
12236 case MATCH:
12237 if (left === 0) {
12238 break inf_leave;
12239 }
12240 copy = _out - left;
12241 if (state.offset > copy) { /* copy from window */
12242 copy = state.offset - copy;
12243 if (copy > state.whave) {
12244 if (state.sane) {
12245 strm.msg = 'invalid distance too far back';
12246 state.mode = BAD$1;
12247 break;
12248 }
12249 // (!) This block is disabled in zlib defailts,
12250 // don't enable it for binary compatibility
12251 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
12252 // Trace((stderr, "inflate.c too far\n"));
12253 // copy -= state.whave;
12254 // if (copy > state.length) { copy = state.length; }
12255 // if (copy > left) { copy = left; }
12256 // left -= copy;
12257 // state.length -= copy;
12258 // do {
12259 // output[put++] = 0;
12260 // } while (--copy);
12261 // if (state.length === 0) { state.mode = LEN; }
12262 // break;
12263 //#endif
12264 }
12265 if (copy > state.wnext) {
12266 copy -= state.wnext;
12267 from = state.wsize - copy;
12268 } else {
12269 from = state.wnext - copy;
12270 }
12271 if (copy > state.length) {
12272 copy = state.length;
12273 }
12274 from_source = state.window;
12275 } else { /* copy from output */
12276 from_source = output;
12277 from = put - state.offset;
12278 copy = state.length;
12279 }
12280 if (copy > left) {
12281 copy = left;
12282 }
12283 left -= copy;
12284 state.length -= copy;
12285 do {
12286 output[put++] = from_source[from++];
12287 } while (--copy);
12288 if (state.length === 0) {
12289 state.mode = LEN;
12290 }
12291 break;
12292 case LIT:
12293 if (left === 0) {
12294 break inf_leave;
12295 }
12296 output[put++] = state.length;
12297 left--;
12298 state.mode = LEN;
12299 break;
12300 case CHECK:
12301 if (state.wrap) {
12302 //=== NEEDBITS(32);
12303 while (bits < 32) {
12304 if (have === 0) {
12305 break inf_leave;
12306 }
12307 have--;
12308 // Use '|' insdead of '+' to make sure that result is signed
12309 hold |= input[next++] << bits;
12310 bits += 8;
12311 }
12312 //===//
12313 _out -= left;
12314 strm.total_out += _out;
12315 state.total += _out;
12316 if (_out) {
12317 strm.adler = state.check =
12318 /*UPDATE(state.check, put - _out, _out);*/
12319 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
12320
12321 }
12322 _out = left;
12323 // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
12324 if ((state.flags ? hold : zswap32(hold)) !== state.check) {
12325 strm.msg = 'incorrect data check';
12326 state.mode = BAD$1;
12327 break;
12328 }
12329 //=== INITBITS();
12330 hold = 0;
12331 bits = 0;
12332 //===//
12333 //Tracev((stderr, "inflate: check matches trailer\n"));
12334 }
12335 state.mode = LENGTH;
12336 /* falls through */
12337 case LENGTH:
12338 if (state.wrap && state.flags) {
12339 //=== NEEDBITS(32);
12340 while (bits < 32) {
12341 if (have === 0) {
12342 break inf_leave;
12343 }
12344 have--;
12345 hold += input[next++] << bits;
12346 bits += 8;
12347 }
12348 //===//
12349 if (hold !== (state.total & 0xffffffff)) {
12350 strm.msg = 'incorrect length check';
12351 state.mode = BAD$1;
12352 break;
12353 }
12354 //=== INITBITS();
12355 hold = 0;
12356 bits = 0;
12357 //===//
12358 //Tracev((stderr, "inflate: length matches trailer\n"));
12359 }
12360 state.mode = DONE;
12361 /* falls through */
12362 case DONE:
12363 ret = Z_STREAM_END$1;
12364 break inf_leave;
12365 case BAD$1:
12366 ret = Z_DATA_ERROR$1;
12367 break inf_leave;
12368 case MEM:
12369 return Z_MEM_ERROR;
12370 case SYNC:
12371 /* falls through */
12372 default:
12373 return Z_STREAM_ERROR$1;
12374 }
12375 }
12376
12377 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
12378
12379 /*
12380 Return from inflate(), updating the total counts and the check value.
12381 If there was no progress during the inflate() call, return a buffer
12382 error. Call updatewindow() to create and/or update the window state.
12383 Note: a memory error from inflate() is non-recoverable.
12384 */
12385
12386 //--- RESTORE() ---
12387 strm.next_out = put;
12388 strm.avail_out = left;
12389 strm.next_in = next;
12390 strm.avail_in = have;
12391 state.hold = hold;
12392 state.bits = bits;
12393 //---
12394
12395 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 &&
12396 (state.mode < CHECK || flush !== Z_FINISH$1))) {
12397 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
12398 }
12399 _in -= strm.avail_in;
12400 _out -= strm.avail_out;
12401 strm.total_in += _in;
12402 strm.total_out += _out;
12403 state.total += _out;
12404 if (state.wrap && _out) {
12405 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
12406 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
12407 }
12408 strm.data_type = state.bits + (state.last ? 64 : 0) +
12409 (state.mode === TYPE$1 ? 128 : 0) +
12410 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
12411 if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {
12412 ret = Z_BUF_ERROR$1;
12413 }
12414 return ret;
12415}
12416
12417function inflateEnd(strm) {
12418
12419 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/ ) {
12420 return Z_STREAM_ERROR$1;
12421 }
12422
12423 var state = strm.state;
12424 if (state.window) {
12425 state.window = null;
12426 }
12427 strm.state = null;
12428 return Z_OK$1;
12429}
12430
12431/* Not implemented
12432exports.inflateCopy = inflateCopy;
12433exports.inflateGetDictionary = inflateGetDictionary;
12434exports.inflateMark = inflateMark;
12435exports.inflatePrime = inflatePrime;
12436exports.inflateSync = inflateSync;
12437exports.inflateSyncPoint = inflateSyncPoint;
12438exports.inflateUndermine = inflateUndermine;
12439*/
12440
12441// import constants from './constants';
12442
12443
12444// zlib modes
12445var NONE = 0;
12446var DEFLATE = 1;
12447var INFLATE = 2;
12448var GZIP = 3;
12449var GUNZIP = 4;
12450var DEFLATERAW = 5;
12451var INFLATERAW = 6;
12452var UNZIP = 7;
12453var Z_NO_FLUSH$1= 0,
12454 Z_PARTIAL_FLUSH$1= 1,
12455 Z_SYNC_FLUSH= 2,
12456 Z_FULL_FLUSH$1= 3,
12457 Z_FINISH$2= 4,
12458 Z_BLOCK$2= 5,
12459 Z_TREES$1= 6,
12460
12461 /* Return codes for the compression/decompression functions. Negative values
12462 * are errors, positive values are used for special but normal events.
12463 */
12464 Z_OK$2= 0,
12465 Z_STREAM_END$2= 1,
12466 Z_NEED_DICT$1= 2,
12467 Z_ERRNO= -1,
12468 Z_STREAM_ERROR$2= -2,
12469 Z_DATA_ERROR$2= -3,
12470 //Z_MEM_ERROR: -4,
12471 Z_BUF_ERROR$2= -5,
12472 //Z_VERSION_ERROR: -6,
12473
12474 /* compression levels */
12475 Z_NO_COMPRESSION= 0,
12476 Z_BEST_SPEED= 1,
12477 Z_BEST_COMPRESSION= 9,
12478 Z_DEFAULT_COMPRESSION$1= -1,
12479
12480
12481 Z_FILTERED$1= 1,
12482 Z_HUFFMAN_ONLY$1= 2,
12483 Z_RLE$1= 3,
12484 Z_FIXED$2= 4,
12485 Z_DEFAULT_STRATEGY= 0,
12486
12487 /* Possible values of the data_type field (though see inflate()) */
12488 Z_BINARY$1= 0,
12489 Z_TEXT$1= 1,
12490 //Z_ASCII: 1, // = Z_TEXT (deprecated)
12491 Z_UNKNOWN$2= 2,
12492
12493 /* The deflate compression method */
12494 Z_DEFLATED$2= 8;
12495function Zlib(mode) {
12496 if (mode < DEFLATE || mode > UNZIP)
12497 throw new TypeError('Bad argument');
12498
12499 this.mode = mode;
12500 this.init_done = false;
12501 this.write_in_progress = false;
12502 this.pending_close = false;
12503 this.windowBits = 0;
12504 this.level = 0;
12505 this.memLevel = 0;
12506 this.strategy = 0;
12507 this.dictionary = null;
12508}
12509
12510Zlib.prototype.init = function(windowBits, level, memLevel, strategy, dictionary) {
12511 this.windowBits = windowBits;
12512 this.level = level;
12513 this.memLevel = memLevel;
12514 this.strategy = strategy;
12515 // dictionary not supported.
12516
12517 if (this.mode === GZIP || this.mode === GUNZIP)
12518 this.windowBits += 16;
12519
12520 if (this.mode === UNZIP)
12521 this.windowBits += 32;
12522
12523 if (this.mode === DEFLATERAW || this.mode === INFLATERAW)
12524 this.windowBits = -this.windowBits;
12525
12526 this.strm = new ZStream();
12527 var status;
12528 switch (this.mode) {
12529 case DEFLATE:
12530 case GZIP:
12531 case DEFLATERAW:
12532 status = deflateInit2(
12533 this.strm,
12534 this.level,
12535 Z_DEFLATED$2,
12536 this.windowBits,
12537 this.memLevel,
12538 this.strategy
12539 );
12540 break;
12541 case INFLATE:
12542 case GUNZIP:
12543 case INFLATERAW:
12544 case UNZIP:
12545 status = inflateInit2(
12546 this.strm,
12547 this.windowBits
12548 );
12549 break;
12550 default:
12551 throw new Error('Unknown mode ' + this.mode);
12552 }
12553
12554 if (status !== Z_OK$2) {
12555 this._error(status);
12556 return;
12557 }
12558
12559 this.write_in_progress = false;
12560 this.init_done = true;
12561};
12562
12563Zlib.prototype.params = function() {
12564 throw new Error('deflateParams Not supported');
12565};
12566
12567Zlib.prototype._writeCheck = function() {
12568 if (!this.init_done)
12569 throw new Error('write before init');
12570
12571 if (this.mode === NONE)
12572 throw new Error('already finalized');
12573
12574 if (this.write_in_progress)
12575 throw new Error('write already in progress');
12576
12577 if (this.pending_close)
12578 throw new Error('close is pending');
12579};
12580
12581Zlib.prototype.write = function(flush, input, in_off, in_len, out, out_off, out_len) {
12582 this._writeCheck();
12583 this.write_in_progress = true;
12584
12585 var self = this;
12586 nextTick(function() {
12587 self.write_in_progress = false;
12588 var res = self._write(flush, input, in_off, in_len, out, out_off, out_len);
12589 self.callback(res[0], res[1]);
12590
12591 if (self.pending_close)
12592 self.close();
12593 });
12594
12595 return this;
12596};
12597
12598// set method for Node buffers, used by pako
12599function bufferSet(data, offset) {
12600 for (var i = 0; i < data.length; i++) {
12601 this[offset + i] = data[i];
12602 }
12603}
12604
12605Zlib.prototype.writeSync = function(flush, input, in_off, in_len, out, out_off, out_len) {
12606 this._writeCheck();
12607 return this._write(flush, input, in_off, in_len, out, out_off, out_len);
12608};
12609
12610Zlib.prototype._write = function(flush, input, in_off, in_len, out, out_off, out_len) {
12611 this.write_in_progress = true;
12612
12613 if (flush !== Z_NO_FLUSH$1 &&
12614 flush !== Z_PARTIAL_FLUSH$1 &&
12615 flush !== Z_SYNC_FLUSH &&
12616 flush !== Z_FULL_FLUSH$1 &&
12617 flush !== Z_FINISH$2 &&
12618 flush !== Z_BLOCK$2) {
12619 throw new Error('Invalid flush value');
12620 }
12621
12622 if (input == null) {
12623 input = new Buffer$1(0);
12624 in_len = 0;
12625 in_off = 0;
12626 }
12627
12628 if (out._set)
12629 out.set = out._set;
12630 else
12631 out.set = bufferSet;
12632
12633 var strm = this.strm;
12634 strm.avail_in = in_len;
12635 strm.input = input;
12636 strm.next_in = in_off;
12637 strm.avail_out = out_len;
12638 strm.output = out;
12639 strm.next_out = out_off;
12640 var status;
12641 switch (this.mode) {
12642 case DEFLATE:
12643 case GZIP:
12644 case DEFLATERAW:
12645 status = deflate(strm, flush);
12646 break;
12647 case UNZIP:
12648 case INFLATE:
12649 case GUNZIP:
12650 case INFLATERAW:
12651 status = inflate(strm, flush);
12652 break;
12653 default:
12654 throw new Error('Unknown mode ' + this.mode);
12655 }
12656
12657 if (status !== Z_STREAM_END$2 && status !== Z_OK$2) {
12658 this._error(status);
12659 }
12660
12661 this.write_in_progress = false;
12662 return [strm.avail_in, strm.avail_out];
12663};
12664
12665Zlib.prototype.close = function() {
12666 if (this.write_in_progress) {
12667 this.pending_close = true;
12668 return;
12669 }
12670
12671 this.pending_close = false;
12672
12673 if (this.mode === DEFLATE || this.mode === GZIP || this.mode === DEFLATERAW) {
12674 deflateEnd(this.strm);
12675 } else {
12676 inflateEnd(this.strm);
12677 }
12678
12679 this.mode = NONE;
12680};
12681var status;
12682Zlib.prototype.reset = function() {
12683 switch (this.mode) {
12684 case DEFLATE:
12685 case DEFLATERAW:
12686 status = deflateReset(this.strm);
12687 break;
12688 case INFLATE:
12689 case INFLATERAW:
12690 status = inflateReset(this.strm);
12691 break;
12692 }
12693
12694 if (status !== Z_OK$2) {
12695 this._error(status);
12696 }
12697};
12698
12699Zlib.prototype._error = function(status) {
12700 this.onerror(msg[status] + ': ' + this.strm.msg, status);
12701
12702 this.write_in_progress = false;
12703 if (this.pending_close)
12704 this.close();
12705};
12706
12707var _binding = /*#__PURE__*/Object.freeze({
12708 __proto__: null,
12709 NONE: NONE,
12710 DEFLATE: DEFLATE,
12711 INFLATE: INFLATE,
12712 GZIP: GZIP,
12713 GUNZIP: GUNZIP,
12714 DEFLATERAW: DEFLATERAW,
12715 INFLATERAW: INFLATERAW,
12716 UNZIP: UNZIP,
12717 Z_NO_FLUSH: Z_NO_FLUSH$1,
12718 Z_PARTIAL_FLUSH: Z_PARTIAL_FLUSH$1,
12719 Z_SYNC_FLUSH: Z_SYNC_FLUSH,
12720 Z_FULL_FLUSH: Z_FULL_FLUSH$1,
12721 Z_FINISH: Z_FINISH$2,
12722 Z_BLOCK: Z_BLOCK$2,
12723 Z_TREES: Z_TREES$1,
12724 Z_OK: Z_OK$2,
12725 Z_STREAM_END: Z_STREAM_END$2,
12726 Z_NEED_DICT: Z_NEED_DICT$1,
12727 Z_ERRNO: Z_ERRNO,
12728 Z_STREAM_ERROR: Z_STREAM_ERROR$2,
12729 Z_DATA_ERROR: Z_DATA_ERROR$2,
12730 Z_BUF_ERROR: Z_BUF_ERROR$2,
12731 Z_NO_COMPRESSION: Z_NO_COMPRESSION,
12732 Z_BEST_SPEED: Z_BEST_SPEED,
12733 Z_BEST_COMPRESSION: Z_BEST_COMPRESSION,
12734 Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,
12735 Z_FILTERED: Z_FILTERED$1,
12736 Z_HUFFMAN_ONLY: Z_HUFFMAN_ONLY$1,
12737 Z_RLE: Z_RLE$1,
12738 Z_FIXED: Z_FIXED$2,
12739 Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY,
12740 Z_BINARY: Z_BINARY$1,
12741 Z_TEXT: Z_TEXT$1,
12742 Z_UNKNOWN: Z_UNKNOWN$2,
12743 Z_DEFLATED: Z_DEFLATED$2,
12744 Zlib: Zlib
12745});
12746
12747function assert (a, msg) {
12748 if (!a) {
12749 throw new Error(msg);
12750 }
12751}
12752var binding$1 = {};
12753Object.keys(_binding).forEach(function (key) {
12754 binding$1[key] = _binding[key];
12755});
12756// zlib doesn't provide these, so kludge them in following the same
12757// const naming scheme zlib uses.
12758binding$1.Z_MIN_WINDOWBITS = 8;
12759binding$1.Z_MAX_WINDOWBITS = 15;
12760binding$1.Z_DEFAULT_WINDOWBITS = 15;
12761
12762// fewer than 64 bytes per chunk is stupid.
12763// technically it could work with as few as 8, but even 64 bytes
12764// is absurdly low. Usually a MB or more is best.
12765binding$1.Z_MIN_CHUNK = 64;
12766binding$1.Z_MAX_CHUNK = Infinity;
12767binding$1.Z_DEFAULT_CHUNK = (16 * 1024);
12768
12769binding$1.Z_MIN_MEMLEVEL = 1;
12770binding$1.Z_MAX_MEMLEVEL = 9;
12771binding$1.Z_DEFAULT_MEMLEVEL = 8;
12772
12773binding$1.Z_MIN_LEVEL = -1;
12774binding$1.Z_MAX_LEVEL = 9;
12775binding$1.Z_DEFAULT_LEVEL = binding$1.Z_DEFAULT_COMPRESSION;
12776
12777
12778// translation table for return codes.
12779var codes = {
12780 Z_OK: binding$1.Z_OK,
12781 Z_STREAM_END: binding$1.Z_STREAM_END,
12782 Z_NEED_DICT: binding$1.Z_NEED_DICT,
12783 Z_ERRNO: binding$1.Z_ERRNO,
12784 Z_STREAM_ERROR: binding$1.Z_STREAM_ERROR,
12785 Z_DATA_ERROR: binding$1.Z_DATA_ERROR,
12786 Z_MEM_ERROR: binding$1.Z_MEM_ERROR,
12787 Z_BUF_ERROR: binding$1.Z_BUF_ERROR,
12788 Z_VERSION_ERROR: binding$1.Z_VERSION_ERROR
12789};
12790
12791Object.keys(codes).forEach(function(k) {
12792 codes[codes[k]] = k;
12793});
12794
12795function createDeflate(o) {
12796 return new Deflate(o);
12797}
12798
12799function createInflate(o) {
12800 return new Inflate(o);
12801}
12802
12803function createDeflateRaw(o) {
12804 return new DeflateRaw(o);
12805}
12806
12807function createInflateRaw(o) {
12808 return new InflateRaw(o);
12809}
12810
12811function createGzip(o) {
12812 return new Gzip(o);
12813}
12814
12815function createGunzip(o) {
12816 return new Gunzip(o);
12817}
12818
12819function createUnzip(o) {
12820 return new Unzip(o);
12821}
12822
12823
12824// Convenience methods.
12825// compress/decompress a string or buffer in one step.
12826function deflate$1(buffer, opts, callback) {
12827 if (typeof opts === 'function') {
12828 callback = opts;
12829 opts = {};
12830 }
12831 return zlibBuffer(new Deflate(opts), buffer, callback);
12832}
12833
12834function deflateSync(buffer, opts) {
12835 return zlibBufferSync(new Deflate(opts), buffer);
12836}
12837
12838function gzip(buffer, opts, callback) {
12839 if (typeof opts === 'function') {
12840 callback = opts;
12841 opts = {};
12842 }
12843 return zlibBuffer(new Gzip(opts), buffer, callback);
12844}
12845
12846function gzipSync(buffer, opts) {
12847 return zlibBufferSync(new Gzip(opts), buffer);
12848}
12849
12850function deflateRaw(buffer, opts, callback) {
12851 if (typeof opts === 'function') {
12852 callback = opts;
12853 opts = {};
12854 }
12855 return zlibBuffer(new DeflateRaw(opts), buffer, callback);
12856}
12857
12858function deflateRawSync(buffer, opts) {
12859 return zlibBufferSync(new DeflateRaw(opts), buffer);
12860}
12861
12862function unzip(buffer, opts, callback) {
12863 if (typeof opts === 'function') {
12864 callback = opts;
12865 opts = {};
12866 }
12867 return zlibBuffer(new Unzip(opts), buffer, callback);
12868}
12869
12870function unzipSync(buffer, opts) {
12871 return zlibBufferSync(new Unzip(opts), buffer);
12872}
12873
12874function inflate$1(buffer, opts, callback) {
12875 if (typeof opts === 'function') {
12876 callback = opts;
12877 opts = {};
12878 }
12879 return zlibBuffer(new Inflate(opts), buffer, callback);
12880}
12881
12882function inflateSync(buffer, opts) {
12883 return zlibBufferSync(new Inflate(opts), buffer);
12884}
12885
12886function gunzip(buffer, opts, callback) {
12887 if (typeof opts === 'function') {
12888 callback = opts;
12889 opts = {};
12890 }
12891 return zlibBuffer(new Gunzip(opts), buffer, callback);
12892}
12893
12894function gunzipSync(buffer, opts) {
12895 return zlibBufferSync(new Gunzip(opts), buffer);
12896}
12897
12898function inflateRaw(buffer, opts, callback) {
12899 if (typeof opts === 'function') {
12900 callback = opts;
12901 opts = {};
12902 }
12903 return zlibBuffer(new InflateRaw(opts), buffer, callback);
12904}
12905
12906function inflateRawSync(buffer, opts) {
12907 return zlibBufferSync(new InflateRaw(opts), buffer);
12908}
12909
12910function zlibBuffer(engine, buffer, callback) {
12911 var buffers = [];
12912 var nread = 0;
12913
12914 engine.on('error', onError);
12915 engine.on('end', onEnd);
12916
12917 engine.end(buffer);
12918 flow();
12919
12920 function flow() {
12921 var chunk;
12922 while (null !== (chunk = engine.read())) {
12923 buffers.push(chunk);
12924 nread += chunk.length;
12925 }
12926 engine.once('readable', flow);
12927 }
12928
12929 function onError(err) {
12930 engine.removeListener('end', onEnd);
12931 engine.removeListener('readable', flow);
12932 callback(err);
12933 }
12934
12935 function onEnd() {
12936 var buf = Buffer$1.concat(buffers, nread);
12937 buffers = [];
12938 callback(null, buf);
12939 engine.close();
12940 }
12941}
12942
12943function zlibBufferSync(engine, buffer) {
12944 if (typeof buffer === 'string')
12945 buffer = new Buffer$1(buffer);
12946 if (!isBuffer(buffer))
12947 throw new TypeError('Not a string or buffer');
12948
12949 var flushFlag = binding$1.Z_FINISH;
12950
12951 return engine._processChunk(buffer, flushFlag);
12952}
12953
12954// generic zlib
12955// minimal 2-byte header
12956function Deflate(opts) {
12957 if (!(this instanceof Deflate)) return new Deflate(opts);
12958 Zlib$1.call(this, opts, binding$1.DEFLATE);
12959}
12960
12961function Inflate(opts) {
12962 if (!(this instanceof Inflate)) return new Inflate(opts);
12963 Zlib$1.call(this, opts, binding$1.INFLATE);
12964}
12965
12966
12967
12968// gzip - bigger header, same deflate compression
12969function Gzip(opts) {
12970 if (!(this instanceof Gzip)) return new Gzip(opts);
12971 Zlib$1.call(this, opts, binding$1.GZIP);
12972}
12973
12974function Gunzip(opts) {
12975 if (!(this instanceof Gunzip)) return new Gunzip(opts);
12976 Zlib$1.call(this, opts, binding$1.GUNZIP);
12977}
12978
12979
12980
12981// raw - no header
12982function DeflateRaw(opts) {
12983 if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
12984 Zlib$1.call(this, opts, binding$1.DEFLATERAW);
12985}
12986
12987function InflateRaw(opts) {
12988 if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
12989 Zlib$1.call(this, opts, binding$1.INFLATERAW);
12990}
12991
12992
12993// auto-detect header.
12994function Unzip(opts) {
12995 if (!(this instanceof Unzip)) return new Unzip(opts);
12996 Zlib$1.call(this, opts, binding$1.UNZIP);
12997}
12998
12999
13000// the Zlib class they all inherit from
13001// This thing manages the queue of requests, and returns
13002// true or false if there is anything in the queue when
13003// you call the .write() method.
13004
13005function Zlib$1(opts, mode) {
13006 this._opts = opts = opts || {};
13007 this._chunkSize = opts.chunkSize || binding$1.Z_DEFAULT_CHUNK;
13008
13009 Transform.call(this, opts);
13010
13011 if (opts.flush) {
13012 if (opts.flush !== binding$1.Z_NO_FLUSH &&
13013 opts.flush !== binding$1.Z_PARTIAL_FLUSH &&
13014 opts.flush !== binding$1.Z_SYNC_FLUSH &&
13015 opts.flush !== binding$1.Z_FULL_FLUSH &&
13016 opts.flush !== binding$1.Z_FINISH &&
13017 opts.flush !== binding$1.Z_BLOCK) {
13018 throw new Error('Invalid flush flag: ' + opts.flush);
13019 }
13020 }
13021 this._flushFlag = opts.flush || binding$1.Z_NO_FLUSH;
13022
13023 if (opts.chunkSize) {
13024 if (opts.chunkSize < binding$1.Z_MIN_CHUNK ||
13025 opts.chunkSize > binding$1.Z_MAX_CHUNK) {
13026 throw new Error('Invalid chunk size: ' + opts.chunkSize);
13027 }
13028 }
13029
13030 if (opts.windowBits) {
13031 if (opts.windowBits < binding$1.Z_MIN_WINDOWBITS ||
13032 opts.windowBits > binding$1.Z_MAX_WINDOWBITS) {
13033 throw new Error('Invalid windowBits: ' + opts.windowBits);
13034 }
13035 }
13036
13037 if (opts.level) {
13038 if (opts.level < binding$1.Z_MIN_LEVEL ||
13039 opts.level > binding$1.Z_MAX_LEVEL) {
13040 throw new Error('Invalid compression level: ' + opts.level);
13041 }
13042 }
13043
13044 if (opts.memLevel) {
13045 if (opts.memLevel < binding$1.Z_MIN_MEMLEVEL ||
13046 opts.memLevel > binding$1.Z_MAX_MEMLEVEL) {
13047 throw new Error('Invalid memLevel: ' + opts.memLevel);
13048 }
13049 }
13050
13051 if (opts.strategy) {
13052 if (opts.strategy != binding$1.Z_FILTERED &&
13053 opts.strategy != binding$1.Z_HUFFMAN_ONLY &&
13054 opts.strategy != binding$1.Z_RLE &&
13055 opts.strategy != binding$1.Z_FIXED &&
13056 opts.strategy != binding$1.Z_DEFAULT_STRATEGY) {
13057 throw new Error('Invalid strategy: ' + opts.strategy);
13058 }
13059 }
13060
13061 if (opts.dictionary) {
13062 if (!isBuffer(opts.dictionary)) {
13063 throw new Error('Invalid dictionary: it should be a Buffer instance');
13064 }
13065 }
13066
13067 this._binding = new binding$1.Zlib(mode);
13068
13069 var self = this;
13070 this._hadError = false;
13071 this._binding.onerror = function(message, errno) {
13072 // there is no way to cleanly recover.
13073 // continuing only obscures problems.
13074 self._binding = null;
13075 self._hadError = true;
13076
13077 var error = new Error(message);
13078 error.errno = errno;
13079 error.code = binding$1.codes[errno];
13080 self.emit('error', error);
13081 };
13082
13083 var level = binding$1.Z_DEFAULT_COMPRESSION;
13084 if (typeof opts.level === 'number') level = opts.level;
13085
13086 var strategy = binding$1.Z_DEFAULT_STRATEGY;
13087 if (typeof opts.strategy === 'number') strategy = opts.strategy;
13088
13089 this._binding.init(opts.windowBits || binding$1.Z_DEFAULT_WINDOWBITS,
13090 level,
13091 opts.memLevel || binding$1.Z_DEFAULT_MEMLEVEL,
13092 strategy,
13093 opts.dictionary);
13094
13095 this._buffer = new Buffer$1(this._chunkSize);
13096 this._offset = 0;
13097 this._closed = false;
13098 this._level = level;
13099 this._strategy = strategy;
13100
13101 this.once('end', this.close);
13102}
13103
13104inherits$1(Zlib$1, Transform);
13105
13106Zlib$1.prototype.params = function(level, strategy, callback) {
13107 if (level < binding$1.Z_MIN_LEVEL ||
13108 level > binding$1.Z_MAX_LEVEL) {
13109 throw new RangeError('Invalid compression level: ' + level);
13110 }
13111 if (strategy != binding$1.Z_FILTERED &&
13112 strategy != binding$1.Z_HUFFMAN_ONLY &&
13113 strategy != binding$1.Z_RLE &&
13114 strategy != binding$1.Z_FIXED &&
13115 strategy != binding$1.Z_DEFAULT_STRATEGY) {
13116 throw new TypeError('Invalid strategy: ' + strategy);
13117 }
13118
13119 if (this._level !== level || this._strategy !== strategy) {
13120 var self = this;
13121 this.flush(binding$1.Z_SYNC_FLUSH, function() {
13122 self._binding.params(level, strategy);
13123 if (!self._hadError) {
13124 self._level = level;
13125 self._strategy = strategy;
13126 if (callback) callback();
13127 }
13128 });
13129 } else {
13130 nextTick(callback);
13131 }
13132};
13133
13134Zlib$1.prototype.reset = function() {
13135 return this._binding.reset();
13136};
13137
13138// This is the _flush function called by the transform class,
13139// internally, when the last chunk has been written.
13140Zlib$1.prototype._flush = function(callback) {
13141 this._transform(new Buffer$1(0), '', callback);
13142};
13143
13144Zlib$1.prototype.flush = function(kind, callback) {
13145 var ws = this._writableState;
13146
13147 if (typeof kind === 'function' || (kind === void 0 && !callback)) {
13148 callback = kind;
13149 kind = binding$1.Z_FULL_FLUSH;
13150 }
13151
13152 if (ws.ended) {
13153 if (callback)
13154 nextTick(callback);
13155 } else if (ws.ending) {
13156 if (callback)
13157 this.once('end', callback);
13158 } else if (ws.needDrain) {
13159 var self = this;
13160 this.once('drain', function() {
13161 self.flush(callback);
13162 });
13163 } else {
13164 this._flushFlag = kind;
13165 this.write(new Buffer$1(0), '', callback);
13166 }
13167};
13168
13169Zlib$1.prototype.close = function(callback) {
13170 if (callback)
13171 nextTick(callback);
13172
13173 if (this._closed)
13174 return;
13175
13176 this._closed = true;
13177
13178 this._binding.close();
13179
13180 var self = this;
13181 nextTick(function() {
13182 self.emit('close');
13183 });
13184};
13185
13186Zlib$1.prototype._transform = function(chunk, encoding, cb) {
13187 var flushFlag;
13188 var ws = this._writableState;
13189 var ending = ws.ending || ws.ended;
13190 var last = ending && (!chunk || ws.length === chunk.length);
13191
13192 if (!chunk === null && !isBuffer(chunk))
13193 return cb(new Error('invalid input'));
13194
13195 // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.
13196 // If it's explicitly flushing at some other time, then we use
13197 // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
13198 // goodness.
13199 if (last)
13200 flushFlag = binding$1.Z_FINISH;
13201 else {
13202 flushFlag = this._flushFlag;
13203 // once we've flushed the last of the queue, stop flushing and
13204 // go back to the normal behavior.
13205 if (chunk.length >= ws.length) {
13206 this._flushFlag = this._opts.flush || binding$1.Z_NO_FLUSH;
13207 }
13208 }
13209
13210 this._processChunk(chunk, flushFlag, cb);
13211};
13212
13213Zlib$1.prototype._processChunk = function(chunk, flushFlag, cb) {
13214 var availInBefore = chunk && chunk.length;
13215 var availOutBefore = this._chunkSize - this._offset;
13216 var inOff = 0;
13217
13218 var self = this;
13219
13220 var async = typeof cb === 'function';
13221
13222 if (!async) {
13223 var buffers = [];
13224 var nread = 0;
13225
13226 var error;
13227 this.on('error', function(er) {
13228 error = er;
13229 });
13230
13231 do {
13232 var res = this._binding.writeSync(flushFlag,
13233 chunk, // in
13234 inOff, // in_off
13235 availInBefore, // in_len
13236 this._buffer, // out
13237 this._offset, //out_off
13238 availOutBefore); // out_len
13239 } while (!this._hadError && callback(res[0], res[1]));
13240
13241 if (this._hadError) {
13242 throw error;
13243 }
13244
13245 var buf = Buffer$1.concat(buffers, nread);
13246 this.close();
13247
13248 return buf;
13249 }
13250
13251 var req = this._binding.write(flushFlag,
13252 chunk, // in
13253 inOff, // in_off
13254 availInBefore, // in_len
13255 this._buffer, // out
13256 this._offset, //out_off
13257 availOutBefore); // out_len
13258
13259 req.buffer = chunk;
13260 req.callback = callback;
13261
13262 function callback(availInAfter, availOutAfter) {
13263 if (self._hadError)
13264 return;
13265
13266 var have = availOutBefore - availOutAfter;
13267 assert(have >= 0, 'have should not go down');
13268
13269 if (have > 0) {
13270 var out = self._buffer.slice(self._offset, self._offset + have);
13271 self._offset += have;
13272 // serve some output to the consumer.
13273 if (async) {
13274 self.push(out);
13275 } else {
13276 buffers.push(out);
13277 nread += out.length;
13278 }
13279 }
13280
13281 // exhausted the output buffer, or used all the input create a new one.
13282 if (availOutAfter === 0 || self._offset >= self._chunkSize) {
13283 availOutBefore = self._chunkSize;
13284 self._offset = 0;
13285 self._buffer = new Buffer$1(self._chunkSize);
13286 }
13287
13288 if (availOutAfter === 0) {
13289 // Not actually done. Need to reprocess.
13290 // Also, update the availInBefore to the availInAfter value,
13291 // so that if we have to hit it a third (fourth, etc.) time,
13292 // it'll have the correct byte counts.
13293 inOff += (availInBefore - availInAfter);
13294 availInBefore = availInAfter;
13295
13296 if (!async)
13297 return true;
13298
13299 var newReq = self._binding.write(flushFlag,
13300 chunk,
13301 inOff,
13302 availInBefore,
13303 self._buffer,
13304 self._offset,
13305 self._chunkSize);
13306 newReq.callback = callback; // this same function
13307 newReq.buffer = chunk;
13308 return;
13309 }
13310
13311 if (!async)
13312 return false;
13313
13314 // finished with the chunk.
13315 cb();
13316 }
13317};
13318
13319inherits$1(Deflate, Zlib$1);
13320inherits$1(Inflate, Zlib$1);
13321inherits$1(Gzip, Zlib$1);
13322inherits$1(Gunzip, Zlib$1);
13323inherits$1(DeflateRaw, Zlib$1);
13324inherits$1(InflateRaw, Zlib$1);
13325inherits$1(Unzip, Zlib$1);
13326var zlib = {
13327 codes: codes,
13328 createDeflate: createDeflate,
13329 createInflate: createInflate,
13330 createDeflateRaw: createDeflateRaw,
13331 createInflateRaw: createInflateRaw,
13332 createGzip: createGzip,
13333 createGunzip: createGunzip,
13334 createUnzip: createUnzip,
13335 deflate: deflate$1,
13336 deflateSync: deflateSync,
13337 gzip: gzip,
13338 gzipSync: gzipSync,
13339 deflateRaw: deflateRaw,
13340 deflateRawSync: deflateRawSync,
13341 unzip: unzip,
13342 unzipSync: unzipSync,
13343 inflate: inflate$1,
13344 inflateSync: inflateSync,
13345 gunzip: gunzip,
13346 gunzipSync: gunzipSync,
13347 inflateRaw: inflateRaw,
13348 inflateRawSync: inflateRawSync,
13349 Deflate: Deflate,
13350 Inflate: Inflate,
13351 Gzip: Gzip,
13352 Gunzip: Gunzip,
13353 DeflateRaw: DeflateRaw,
13354 InflateRaw: InflateRaw,
13355 Unzip: Unzip,
13356 Zlib: Zlib$1
13357};
13358
13359// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
13360
13361// fix for "Readable" isn't a named export issue
13362const Readable$1 = Stream.Readable;
13363
13364const BUFFER = Symbol('buffer');
13365const TYPE$2 = Symbol('type');
13366
13367class Blob {
13368 constructor() {
13369 this[TYPE$2] = '';
13370
13371 const blobParts = arguments[0];
13372 const options = arguments[1];
13373
13374 const buffers = [];
13375 let size = 0;
13376
13377 if (blobParts) {
13378 const a = blobParts;
13379 const length = Number(a.length);
13380 for (let i = 0; i < length; i++) {
13381 const element = a[i];
13382 let buffer;
13383 if (element instanceof Buffer) {
13384 buffer = element;
13385 } else if (ArrayBuffer.isView(element)) {
13386 buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
13387 } else if (element instanceof ArrayBuffer) {
13388 buffer = Buffer.from(element);
13389 } else if (element instanceof Blob) {
13390 buffer = element[BUFFER];
13391 } else {
13392 buffer = Buffer.from(typeof element === 'string' ? element : String(element));
13393 }
13394 size += buffer.length;
13395 buffers.push(buffer);
13396 }
13397 }
13398
13399 this[BUFFER] = Buffer.concat(buffers);
13400
13401 let type = options && options.type !== undefined && String(options.type).toLowerCase();
13402 if (type && !/[^\u0020-\u007E]/.test(type)) {
13403 this[TYPE$2] = type;
13404 }
13405 }
13406 get size() {
13407 return this[BUFFER].length;
13408 }
13409 get type() {
13410 return this[TYPE$2];
13411 }
13412 text() {
13413 return Promise.resolve(this[BUFFER].toString());
13414 }
13415 arrayBuffer() {
13416 const buf = this[BUFFER];
13417 const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
13418 return Promise.resolve(ab);
13419 }
13420 stream() {
13421 const readable = new Readable$1();
13422 readable._read = function () {};
13423 readable.push(this[BUFFER]);
13424 readable.push(null);
13425 return readable;
13426 }
13427 toString() {
13428 return '[object Blob]';
13429 }
13430 slice() {
13431 const size = this.size;
13432
13433 const start = arguments[0];
13434 const end = arguments[1];
13435 let relativeStart, relativeEnd;
13436 if (start === undefined) {
13437 relativeStart = 0;
13438 } else if (start < 0) {
13439 relativeStart = Math.max(size + start, 0);
13440 } else {
13441 relativeStart = Math.min(start, size);
13442 }
13443 if (end === undefined) {
13444 relativeEnd = size;
13445 } else if (end < 0) {
13446 relativeEnd = Math.max(size + end, 0);
13447 } else {
13448 relativeEnd = Math.min(end, size);
13449 }
13450 const span = Math.max(relativeEnd - relativeStart, 0);
13451
13452 const buffer = this[BUFFER];
13453 const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
13454 const blob = new Blob([], { type: arguments[2] });
13455 blob[BUFFER] = slicedBuffer;
13456 return blob;
13457 }
13458}
13459
13460Object.defineProperties(Blob.prototype, {
13461 size: { enumerable: true },
13462 type: { enumerable: true },
13463 slice: { enumerable: true }
13464});
13465
13466Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
13467 value: 'Blob',
13468 writable: false,
13469 enumerable: false,
13470 configurable: true
13471});
13472
13473/**
13474 * fetch-error.js
13475 *
13476 * FetchError interface for operational errors
13477 */
13478
13479/**
13480 * Create FetchError instance
13481 *
13482 * @param String message Error message for human
13483 * @param String type Error type for machine
13484 * @param String systemError For Node.js system error
13485 * @return FetchError
13486 */
13487function FetchError(message, type, systemError) {
13488 Error.call(this, message);
13489
13490 this.message = message;
13491 this.type = type;
13492
13493 // when err.type is `system`, err.code contains system error code
13494 if (systemError) {
13495 this.code = this.errno = systemError.code;
13496 }
13497
13498 // hide custom error implementation details from end-users
13499 Error.captureStackTrace(this, this.constructor);
13500}
13501
13502FetchError.prototype = Object.create(Error.prototype);
13503FetchError.prototype.constructor = FetchError;
13504FetchError.prototype.name = 'FetchError';
13505
13506let convert;
13507try {
13508 convert = require('encoding').convert;
13509} catch (e) {}
13510
13511const INTERNALS = Symbol('Body internals');
13512
13513// fix an issue where "PassThrough" isn't a named export for node <10
13514const PassThrough$1 = Stream.PassThrough;
13515
13516/**
13517 * Body mixin
13518 *
13519 * Ref: https://fetch.spec.whatwg.org/#body
13520 *
13521 * @param Stream body Readable stream
13522 * @param Object opts Response options
13523 * @return Void
13524 */
13525function Body(body) {
13526 var _this = this;
13527
13528 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
13529 _ref$size = _ref.size;
13530
13531 let size = _ref$size === undefined ? 0 : _ref$size;
13532 var _ref$timeout = _ref.timeout;
13533 let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
13534
13535 if (body == null) {
13536 // body is undefined or null
13537 body = null;
13538 } else if (isURLSearchParams(body)) {
13539 // body is a URLSearchParams
13540 body = Buffer.from(body.toString());
13541 } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
13542 // body is ArrayBuffer
13543 body = Buffer.from(body);
13544 } else if (ArrayBuffer.isView(body)) {
13545 // body is ArrayBufferView
13546 body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
13547 } else if (body instanceof Stream) ; else {
13548 // none of the above
13549 // coerce to string then buffer
13550 body = Buffer.from(String(body));
13551 }
13552 this[INTERNALS] = {
13553 body,
13554 disturbed: false,
13555 error: null
13556 };
13557 this.size = size;
13558 this.timeout = timeout;
13559
13560 if (body instanceof Stream) {
13561 body.on('error', function (err) {
13562 const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
13563 _this[INTERNALS].error = error;
13564 });
13565 }
13566}
13567
13568Body.prototype = {
13569 get body() {
13570 return this[INTERNALS].body;
13571 },
13572
13573 get bodyUsed() {
13574 return this[INTERNALS].disturbed;
13575 },
13576
13577 /**
13578 * Decode response as ArrayBuffer
13579 *
13580 * @return Promise
13581 */
13582 arrayBuffer() {
13583 return consumeBody.call(this).then(function (buf) {
13584 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
13585 });
13586 },
13587
13588 /**
13589 * Return raw response as Blob
13590 *
13591 * @return Promise
13592 */
13593 blob() {
13594 let ct = this.headers && this.headers.get('content-type') || '';
13595 return consumeBody.call(this).then(function (buf) {
13596 return Object.assign(
13597 // Prevent copying
13598 new Blob([], {
13599 type: ct.toLowerCase()
13600 }), {
13601 [BUFFER]: buf
13602 });
13603 });
13604 },
13605
13606 /**
13607 * Decode response as json
13608 *
13609 * @return Promise
13610 */
13611 json() {
13612 var _this2 = this;
13613
13614 return consumeBody.call(this).then(function (buffer) {
13615 try {
13616 return JSON.parse(buffer.toString());
13617 } catch (err) {
13618 return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
13619 }
13620 });
13621 },
13622
13623 /**
13624 * Decode response as text
13625 *
13626 * @return Promise
13627 */
13628 text() {
13629 return consumeBody.call(this).then(function (buffer) {
13630 return buffer.toString();
13631 });
13632 },
13633
13634 /**
13635 * Decode response as buffer (non-spec api)
13636 *
13637 * @return Promise
13638 */
13639 buffer() {
13640 return consumeBody.call(this);
13641 },
13642
13643 /**
13644 * Decode response as text, while automatically detecting the encoding and
13645 * trying to decode to UTF-8 (non-spec api)
13646 *
13647 * @return Promise
13648 */
13649 textConverted() {
13650 var _this3 = this;
13651
13652 return consumeBody.call(this).then(function (buffer) {
13653 return convertBody(buffer, _this3.headers);
13654 });
13655 }
13656};
13657
13658// In browsers, all properties are enumerable.
13659Object.defineProperties(Body.prototype, {
13660 body: { enumerable: true },
13661 bodyUsed: { enumerable: true },
13662 arrayBuffer: { enumerable: true },
13663 blob: { enumerable: true },
13664 json: { enumerable: true },
13665 text: { enumerable: true }
13666});
13667
13668Body.mixIn = function (proto) {
13669 for (const name of Object.getOwnPropertyNames(Body.prototype)) {
13670 // istanbul ignore else: future proof
13671 if (!(name in proto)) {
13672 const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
13673 Object.defineProperty(proto, name, desc);
13674 }
13675 }
13676};
13677
13678/**
13679 * Consume and convert an entire Body to a Buffer.
13680 *
13681 * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
13682 *
13683 * @return Promise
13684 */
13685function consumeBody() {
13686 var _this4 = this;
13687
13688 if (this[INTERNALS].disturbed) {
13689 return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
13690 }
13691
13692 this[INTERNALS].disturbed = true;
13693
13694 if (this[INTERNALS].error) {
13695 return Body.Promise.reject(this[INTERNALS].error);
13696 }
13697
13698 let body = this.body;
13699
13700 // body is null
13701 if (body === null) {
13702 return Body.Promise.resolve(Buffer.alloc(0));
13703 }
13704
13705 // body is blob
13706 if (isBlob(body)) {
13707 body = body.stream();
13708 }
13709
13710 // body is buffer
13711 if (Buffer.isBuffer(body)) {
13712 return Body.Promise.resolve(body);
13713 }
13714
13715 // istanbul ignore if: should never happen
13716 if (!(body instanceof Stream)) {
13717 return Body.Promise.resolve(Buffer.alloc(0));
13718 }
13719
13720 // body is stream
13721 // get ready to actually consume the body
13722 let accum = [];
13723 let accumBytes = 0;
13724 let abort = false;
13725
13726 return new Body.Promise(function (resolve, reject) {
13727 let resTimeout;
13728
13729 // allow timeout on slow response body
13730 if (_this4.timeout) {
13731 resTimeout = setTimeout(function () {
13732 abort = true;
13733 reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
13734 }, _this4.timeout);
13735 }
13736
13737 // handle stream errors
13738 body.on('error', function (err) {
13739 if (err.name === 'AbortError') {
13740 // if the request was aborted, reject with this Error
13741 abort = true;
13742 reject(err);
13743 } else {
13744 // other errors, such as incorrect content-encoding
13745 reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
13746 }
13747 });
13748
13749 body.on('data', function (chunk) {
13750 if (abort || chunk === null) {
13751 return;
13752 }
13753
13754 if (_this4.size && accumBytes + chunk.length > _this4.size) {
13755 abort = true;
13756 reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
13757 return;
13758 }
13759
13760 accumBytes += chunk.length;
13761 accum.push(chunk);
13762 });
13763
13764 body.on('end', function () {
13765 if (abort) {
13766 return;
13767 }
13768
13769 clearTimeout(resTimeout);
13770
13771 try {
13772 resolve(Buffer.concat(accum, accumBytes));
13773 } catch (err) {
13774 // handle streams that have accumulated too much data (issue #414)
13775 reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
13776 }
13777 });
13778 });
13779}
13780
13781/**
13782 * Detect buffer encoding and convert to target encoding
13783 * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
13784 *
13785 * @param Buffer buffer Incoming buffer
13786 * @param String encoding Target encoding
13787 * @return String
13788 */
13789function convertBody(buffer, headers) {
13790 if (typeof convert !== 'function') {
13791 throw new Error('The package `encoding` must be installed to use the textConverted() function');
13792 }
13793
13794 const ct = headers.get('content-type');
13795 let charset = 'utf-8';
13796 let res, str;
13797
13798 // header
13799 if (ct) {
13800 res = /charset=([^;]*)/i.exec(ct);
13801 }
13802
13803 // no charset in content type, peek at response body for at most 1024 bytes
13804 str = buffer.slice(0, 1024).toString();
13805
13806 // html5
13807 if (!res && str) {
13808 res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
13809 }
13810
13811 // html4
13812 if (!res && str) {
13813 res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
13814
13815 if (res) {
13816 res = /charset=(.*)/i.exec(res.pop());
13817 }
13818 }
13819
13820 // xml
13821 if (!res && str) {
13822 res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
13823 }
13824
13825 // found charset
13826 if (res) {
13827 charset = res.pop();
13828
13829 // prevent decode issues when sites use incorrect encoding
13830 // ref: https://hsivonen.fi/encoding-menu/
13831 if (charset === 'gb2312' || charset === 'gbk') {
13832 charset = 'gb18030';
13833 }
13834 }
13835
13836 // turn raw buffers into a single utf-8 buffer
13837 return convert(buffer, 'UTF-8', charset).toString();
13838}
13839
13840/**
13841 * Detect a URLSearchParams object
13842 * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
13843 *
13844 * @param Object obj Object to detect by type or brand
13845 * @return String
13846 */
13847function isURLSearchParams(obj) {
13848 // Duck-typing as a necessary condition.
13849 if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {
13850 return false;
13851 }
13852
13853 // Brand-checking and more duck-typing as optional condition.
13854 return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
13855}
13856
13857/**
13858 * Check if `obj` is a W3C `Blob` object (which `File` inherits from)
13859 * @param {*} obj
13860 * @return {boolean}
13861 */
13862function isBlob(obj) {
13863 return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
13864}
13865
13866/**
13867 * Clone body given Res/Req instance
13868 *
13869 * @param Mixed instance Response or Request instance
13870 * @return Mixed
13871 */
13872function clone(instance) {
13873 let p1, p2;
13874 let body = instance.body;
13875
13876 // don't allow cloning a used body
13877 if (instance.bodyUsed) {
13878 throw new Error('cannot clone body after it is used');
13879 }
13880
13881 // check that body is a stream and not form-data object
13882 // note: we can't clone the form-data object without having it as a dependency
13883 if (body instanceof Stream && typeof body.getBoundary !== 'function') {
13884 // tee instance body
13885 p1 = new PassThrough$1();
13886 p2 = new PassThrough$1();
13887 body.pipe(p1);
13888 body.pipe(p2);
13889 // set instance body to teed body and return the other teed body
13890 instance[INTERNALS].body = p1;
13891 body = p2;
13892 }
13893
13894 return body;
13895}
13896
13897/**
13898 * Performs the operation "extract a `Content-Type` value from |object|" as
13899 * specified in the specification:
13900 * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
13901 *
13902 * This function assumes that instance.body is present.
13903 *
13904 * @param Mixed instance Any options.body input
13905 */
13906function extractContentType(body) {
13907 if (body === null) {
13908 // body is null
13909 return null;
13910 } else if (typeof body === 'string') {
13911 // body is string
13912 return 'text/plain;charset=UTF-8';
13913 } else if (isURLSearchParams(body)) {
13914 // body is a URLSearchParams
13915 return 'application/x-www-form-urlencoded;charset=UTF-8';
13916 } else if (isBlob(body)) {
13917 // body is blob
13918 return body.type || null;
13919 } else if (Buffer.isBuffer(body)) {
13920 // body is buffer
13921 return null;
13922 } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
13923 // body is ArrayBuffer
13924 return null;
13925 } else if (ArrayBuffer.isView(body)) {
13926 // body is ArrayBufferView
13927 return null;
13928 } else if (typeof body.getBoundary === 'function') {
13929 // detect form data input from form-data module
13930 return `multipart/form-data;boundary=${body.getBoundary()}`;
13931 } else if (body instanceof Stream) {
13932 // body is stream
13933 // can't really do much about this
13934 return null;
13935 } else {
13936 // Body constructor defaults other things to string
13937 return 'text/plain;charset=UTF-8';
13938 }
13939}
13940
13941/**
13942 * The Fetch Standard treats this as if "total bytes" is a property on the body.
13943 * For us, we have to explicitly get it with a function.
13944 *
13945 * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
13946 *
13947 * @param Body instance Instance of Body
13948 * @return Number? Number of bytes, or null if not possible
13949 */
13950function getTotalBytes(instance) {
13951 const body = instance.body;
13952
13953
13954 if (body === null) {
13955 // body is null
13956 return 0;
13957 } else if (isBlob(body)) {
13958 return body.size;
13959 } else if (Buffer.isBuffer(body)) {
13960 // body is buffer
13961 return body.length;
13962 } else if (body && typeof body.getLengthSync === 'function') {
13963 // detect form data input from form-data module
13964 if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
13965 body.hasKnownLength && body.hasKnownLength()) {
13966 // 2.x
13967 return body.getLengthSync();
13968 }
13969 return null;
13970 } else {
13971 // body is stream
13972 return null;
13973 }
13974}
13975
13976/**
13977 * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
13978 *
13979 * @param Body instance Instance of Body
13980 * @return Void
13981 */
13982function writeToStream(dest, instance) {
13983 const body = instance.body;
13984
13985
13986 if (body === null) {
13987 // body is null
13988 dest.end();
13989 } else if (isBlob(body)) {
13990 body.stream().pipe(dest);
13991 } else if (Buffer.isBuffer(body)) {
13992 // body is buffer
13993 dest.write(body);
13994 dest.end();
13995 } else {
13996 // body is stream
13997 body.pipe(dest);
13998 }
13999}
14000
14001// expose Promise
14002Body.Promise = global.Promise;
14003
14004/**
14005 * headers.js
14006 *
14007 * Headers class offers convenient helpers
14008 */
14009
14010const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
14011const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
14012
14013function validateName(name) {
14014 name = `${name}`;
14015 if (invalidTokenRegex.test(name) || name === '') {
14016 throw new TypeError(`${name} is not a legal HTTP header name`);
14017 }
14018}
14019
14020function validateValue(value) {
14021 value = `${value}`;
14022 if (invalidHeaderCharRegex.test(value)) {
14023 throw new TypeError(`${value} is not a legal HTTP header value`);
14024 }
14025}
14026
14027/**
14028 * Find the key in the map object given a header name.
14029 *
14030 * Returns undefined if not found.
14031 *
14032 * @param String name Header name
14033 * @return String|Undefined
14034 */
14035function find(map, name) {
14036 name = name.toLowerCase();
14037 for (const key in map) {
14038 if (key.toLowerCase() === name) {
14039 return key;
14040 }
14041 }
14042 return undefined;
14043}
14044
14045const MAP = Symbol('map');
14046class Headers {
14047 /**
14048 * Headers class
14049 *
14050 * @param Object headers Response headers
14051 * @return Void
14052 */
14053 constructor() {
14054 let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
14055
14056 this[MAP] = Object.create(null);
14057
14058 if (init instanceof Headers) {
14059 const rawHeaders = init.raw();
14060 const headerNames = Object.keys(rawHeaders);
14061
14062 for (const headerName of headerNames) {
14063 for (const value of rawHeaders[headerName]) {
14064 this.append(headerName, value);
14065 }
14066 }
14067
14068 return;
14069 }
14070
14071 // We don't worry about converting prop to ByteString here as append()
14072 // will handle it.
14073 if (init == null) ; else if (typeof init === 'object') {
14074 const method = init[Symbol.iterator];
14075 if (method != null) {
14076 if (typeof method !== 'function') {
14077 throw new TypeError('Header pairs must be iterable');
14078 }
14079
14080 // sequence<sequence<ByteString>>
14081 // Note: per spec we have to first exhaust the lists then process them
14082 const pairs = [];
14083 for (const pair of init) {
14084 if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
14085 throw new TypeError('Each header pair must be iterable');
14086 }
14087 pairs.push(Array.from(pair));
14088 }
14089
14090 for (const pair of pairs) {
14091 if (pair.length !== 2) {
14092 throw new TypeError('Each header pair must be a name/value tuple');
14093 }
14094 this.append(pair[0], pair[1]);
14095 }
14096 } else {
14097 // record<ByteString, ByteString>
14098 for (const key of Object.keys(init)) {
14099 const value = init[key];
14100 this.append(key, value);
14101 }
14102 }
14103 } else {
14104 throw new TypeError('Provided initializer must be an object');
14105 }
14106 }
14107
14108 /**
14109 * Return combined header value given name
14110 *
14111 * @param String name Header name
14112 * @return Mixed
14113 */
14114 get(name) {
14115 name = `${name}`;
14116 validateName(name);
14117 const key = find(this[MAP], name);
14118 if (key === undefined) {
14119 return null;
14120 }
14121
14122 return this[MAP][key].join(', ');
14123 }
14124
14125 /**
14126 * Iterate over all headers
14127 *
14128 * @param Function callback Executed for each item with parameters (value, name, thisArg)
14129 * @param Boolean thisArg `this` context for callback function
14130 * @return Void
14131 */
14132 forEach(callback) {
14133 let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
14134
14135 let pairs = getHeaders(this);
14136 let i = 0;
14137 while (i < pairs.length) {
14138 var _pairs$i = pairs[i];
14139 const name = _pairs$i[0],
14140 value = _pairs$i[1];
14141
14142 callback.call(thisArg, value, name, this);
14143 pairs = getHeaders(this);
14144 i++;
14145 }
14146 }
14147
14148 /**
14149 * Overwrite header values given name
14150 *
14151 * @param String name Header name
14152 * @param String value Header value
14153 * @return Void
14154 */
14155 set(name, value) {
14156 name = `${name}`;
14157 value = `${value}`;
14158 validateName(name);
14159 validateValue(value);
14160 const key = find(this[MAP], name);
14161 this[MAP][key !== undefined ? key : name] = [value];
14162 }
14163
14164 /**
14165 * Append a value onto existing header
14166 *
14167 * @param String name Header name
14168 * @param String value Header value
14169 * @return Void
14170 */
14171 append(name, value) {
14172 name = `${name}`;
14173 value = `${value}`;
14174 validateName(name);
14175 validateValue(value);
14176 const key = find(this[MAP], name);
14177 if (key !== undefined) {
14178 this[MAP][key].push(value);
14179 } else {
14180 this[MAP][name] = [value];
14181 }
14182 }
14183
14184 /**
14185 * Check for header name existence
14186 *
14187 * @param String name Header name
14188 * @return Boolean
14189 */
14190 has(name) {
14191 name = `${name}`;
14192 validateName(name);
14193 return find(this[MAP], name) !== undefined;
14194 }
14195
14196 /**
14197 * Delete all header values given name
14198 *
14199 * @param String name Header name
14200 * @return Void
14201 */
14202 delete(name) {
14203 name = `${name}`;
14204 validateName(name);
14205 const key = find(this[MAP], name);
14206 if (key !== undefined) {
14207 delete this[MAP][key];
14208 }
14209 }
14210
14211 /**
14212 * Return raw headers (non-spec api)
14213 *
14214 * @return Object
14215 */
14216 raw() {
14217 return this[MAP];
14218 }
14219
14220 /**
14221 * Get an iterator on keys.
14222 *
14223 * @return Iterator
14224 */
14225 keys() {
14226 return createHeadersIterator(this, 'key');
14227 }
14228
14229 /**
14230 * Get an iterator on values.
14231 *
14232 * @return Iterator
14233 */
14234 values() {
14235 return createHeadersIterator(this, 'value');
14236 }
14237
14238 /**
14239 * Get an iterator on entries.
14240 *
14241 * This is the default iterator of the Headers object.
14242 *
14243 * @return Iterator
14244 */
14245 [Symbol.iterator]() {
14246 return createHeadersIterator(this, 'key+value');
14247 }
14248}
14249Headers.prototype.entries = Headers.prototype[Symbol.iterator];
14250
14251Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
14252 value: 'Headers',
14253 writable: false,
14254 enumerable: false,
14255 configurable: true
14256});
14257
14258Object.defineProperties(Headers.prototype, {
14259 get: { enumerable: true },
14260 forEach: { enumerable: true },
14261 set: { enumerable: true },
14262 append: { enumerable: true },
14263 has: { enumerable: true },
14264 delete: { enumerable: true },
14265 keys: { enumerable: true },
14266 values: { enumerable: true },
14267 entries: { enumerable: true }
14268});
14269
14270function getHeaders(headers) {
14271 let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
14272
14273 const keys = Object.keys(headers[MAP]).sort();
14274 return keys.map(kind === 'key' ? function (k) {
14275 return k.toLowerCase();
14276 } : kind === 'value' ? function (k) {
14277 return headers[MAP][k].join(', ');
14278 } : function (k) {
14279 return [k.toLowerCase(), headers[MAP][k].join(', ')];
14280 });
14281}
14282
14283const INTERNAL = Symbol('internal');
14284
14285function createHeadersIterator(target, kind) {
14286 const iterator = Object.create(HeadersIteratorPrototype);
14287 iterator[INTERNAL] = {
14288 target,
14289 kind,
14290 index: 0
14291 };
14292 return iterator;
14293}
14294
14295const HeadersIteratorPrototype = Object.setPrototypeOf({
14296 next() {
14297 // istanbul ignore if
14298 if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
14299 throw new TypeError('Value of `this` is not a HeadersIterator');
14300 }
14301
14302 var _INTERNAL = this[INTERNAL];
14303 const target = _INTERNAL.target,
14304 kind = _INTERNAL.kind,
14305 index = _INTERNAL.index;
14306
14307 const values = getHeaders(target, kind);
14308 const len = values.length;
14309 if (index >= len) {
14310 return {
14311 value: undefined,
14312 done: true
14313 };
14314 }
14315
14316 this[INTERNAL].index = index + 1;
14317
14318 return {
14319 value: values[index],
14320 done: false
14321 };
14322 }
14323}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
14324
14325Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
14326 value: 'HeadersIterator',
14327 writable: false,
14328 enumerable: false,
14329 configurable: true
14330});
14331
14332/**
14333 * Export the Headers object in a form that Node.js can consume.
14334 *
14335 * @param Headers headers
14336 * @return Object
14337 */
14338function exportNodeCompatibleHeaders(headers) {
14339 const obj = Object.assign({ __proto__: null }, headers[MAP]);
14340
14341 // http.request() only supports string as Host header. This hack makes
14342 // specifying custom Host header possible.
14343 const hostHeaderKey = find(headers[MAP], 'Host');
14344 if (hostHeaderKey !== undefined) {
14345 obj[hostHeaderKey] = obj[hostHeaderKey][0];
14346 }
14347
14348 return obj;
14349}
14350
14351/**
14352 * Create a Headers object from an object of headers, ignoring those that do
14353 * not conform to HTTP grammar productions.
14354 *
14355 * @param Object obj Object of headers
14356 * @return Headers
14357 */
14358function createHeadersLenient(obj) {
14359 const headers = new Headers();
14360 for (const name of Object.keys(obj)) {
14361 if (invalidTokenRegex.test(name)) {
14362 continue;
14363 }
14364 if (Array.isArray(obj[name])) {
14365 for (const val of obj[name]) {
14366 if (invalidHeaderCharRegex.test(val)) {
14367 continue;
14368 }
14369 if (headers[MAP][name] === undefined) {
14370 headers[MAP][name] = [val];
14371 } else {
14372 headers[MAP][name].push(val);
14373 }
14374 }
14375 } else if (!invalidHeaderCharRegex.test(obj[name])) {
14376 headers[MAP][name] = [obj[name]];
14377 }
14378 }
14379 return headers;
14380}
14381
14382const INTERNALS$1 = Symbol('Response internals');
14383
14384// fix an issue where "STATUS_CODES" aren't a named export for node <10
14385const STATUS_CODES$1 = http.STATUS_CODES;
14386
14387/**
14388 * Response class
14389 *
14390 * @param Stream body Readable stream
14391 * @param Object opts Response options
14392 * @return Void
14393 */
14394class Response {
14395 constructor() {
14396 let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
14397 let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
14398
14399 Body.call(this, body, opts);
14400
14401 const status = opts.status || 200;
14402 const headers = new Headers(opts.headers);
14403
14404 if (body != null && !headers.has('Content-Type')) {
14405 const contentType = extractContentType(body);
14406 if (contentType) {
14407 headers.append('Content-Type', contentType);
14408 }
14409 }
14410
14411 this[INTERNALS$1] = {
14412 url: opts.url,
14413 status,
14414 statusText: opts.statusText || STATUS_CODES$1[status],
14415 headers,
14416 counter: opts.counter
14417 };
14418 }
14419
14420 get url() {
14421 return this[INTERNALS$1].url || '';
14422 }
14423
14424 get status() {
14425 return this[INTERNALS$1].status;
14426 }
14427
14428 /**
14429 * Convenience property representing if the request ended normally
14430 */
14431 get ok() {
14432 return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
14433 }
14434
14435 get redirected() {
14436 return this[INTERNALS$1].counter > 0;
14437 }
14438
14439 get statusText() {
14440 return this[INTERNALS$1].statusText;
14441 }
14442
14443 get headers() {
14444 return this[INTERNALS$1].headers;
14445 }
14446
14447 /**
14448 * Clone this response
14449 *
14450 * @return Response
14451 */
14452 clone() {
14453 return new Response(clone(this), {
14454 url: this.url,
14455 status: this.status,
14456 statusText: this.statusText,
14457 headers: this.headers,
14458 ok: this.ok,
14459 redirected: this.redirected
14460 });
14461 }
14462}
14463
14464Body.mixIn(Response.prototype);
14465
14466Object.defineProperties(Response.prototype, {
14467 url: { enumerable: true },
14468 status: { enumerable: true },
14469 ok: { enumerable: true },
14470 redirected: { enumerable: true },
14471 statusText: { enumerable: true },
14472 headers: { enumerable: true },
14473 clone: { enumerable: true }
14474});
14475
14476Object.defineProperty(Response.prototype, Symbol.toStringTag, {
14477 value: 'Response',
14478 writable: false,
14479 enumerable: false,
14480 configurable: true
14481});
14482
14483const INTERNALS$2 = Symbol('Request internals');
14484
14485// fix an issue where "format", "parse" aren't a named export for node <10
14486const parse_url = Url.parse;
14487const format_url = Url.format;
14488
14489const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
14490
14491/**
14492 * Check if a value is an instance of Request.
14493 *
14494 * @param Mixed input
14495 * @return Boolean
14496 */
14497function isRequest(input) {
14498 return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
14499}
14500
14501function isAbortSignal(signal) {
14502 const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
14503 return !!(proto && proto.constructor.name === 'AbortSignal');
14504}
14505
14506/**
14507 * Request class
14508 *
14509 * @param Mixed input Url or Request instance
14510 * @param Object init Custom options
14511 * @return Void
14512 */
14513class Request {
14514 constructor(input) {
14515 let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
14516
14517 let parsedURL;
14518
14519 // normalize input
14520 if (!isRequest(input)) {
14521 if (input && input.href) {
14522 // in order to support Node.js' Url objects; though WHATWG's URL objects
14523 // will fall into this branch also (since their `toString()` will return
14524 // `href` property anyway)
14525 parsedURL = parse_url(input.href);
14526 } else {
14527 // coerce input to a string before attempting to parse
14528 parsedURL = parse_url(`${input}`);
14529 }
14530 input = {};
14531 } else {
14532 parsedURL = parse_url(input.url);
14533 }
14534
14535 let method = init.method || input.method || 'GET';
14536 method = method.toUpperCase();
14537
14538 if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
14539 throw new TypeError('Request with GET/HEAD method cannot have body');
14540 }
14541
14542 let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
14543
14544 Body.call(this, inputBody, {
14545 timeout: init.timeout || input.timeout || 0,
14546 size: init.size || input.size || 0
14547 });
14548
14549 const headers = new Headers(init.headers || input.headers || {});
14550
14551 if (inputBody != null && !headers.has('Content-Type')) {
14552 const contentType = extractContentType(inputBody);
14553 if (contentType) {
14554 headers.append('Content-Type', contentType);
14555 }
14556 }
14557
14558 let signal = isRequest(input) ? input.signal : null;
14559 if ('signal' in init) signal = init.signal;
14560
14561 if (signal != null && !isAbortSignal(signal)) {
14562 throw new TypeError('Expected signal to be an instanceof AbortSignal');
14563 }
14564
14565 this[INTERNALS$2] = {
14566 method,
14567 redirect: init.redirect || input.redirect || 'follow',
14568 headers,
14569 parsedURL,
14570 signal
14571 };
14572
14573 // node-fetch-only options
14574 this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
14575 this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
14576 this.counter = init.counter || input.counter || 0;
14577 this.agent = init.agent || input.agent;
14578 }
14579
14580 get method() {
14581 return this[INTERNALS$2].method;
14582 }
14583
14584 get url() {
14585 return format_url(this[INTERNALS$2].parsedURL);
14586 }
14587
14588 get headers() {
14589 return this[INTERNALS$2].headers;
14590 }
14591
14592 get redirect() {
14593 return this[INTERNALS$2].redirect;
14594 }
14595
14596 get signal() {
14597 return this[INTERNALS$2].signal;
14598 }
14599
14600 /**
14601 * Clone this request
14602 *
14603 * @return Request
14604 */
14605 clone() {
14606 return new Request(this);
14607 }
14608}
14609
14610Body.mixIn(Request.prototype);
14611
14612Object.defineProperty(Request.prototype, Symbol.toStringTag, {
14613 value: 'Request',
14614 writable: false,
14615 enumerable: false,
14616 configurable: true
14617});
14618
14619Object.defineProperties(Request.prototype, {
14620 method: { enumerable: true },
14621 url: { enumerable: true },
14622 headers: { enumerable: true },
14623 redirect: { enumerable: true },
14624 clone: { enumerable: true },
14625 signal: { enumerable: true }
14626});
14627
14628/**
14629 * Convert a Request to Node.js http request options.
14630 *
14631 * @param Request A Request instance
14632 * @return Object The options object to be passed to http.request
14633 */
14634function getNodeRequestOptions(request) {
14635 const parsedURL = request[INTERNALS$2].parsedURL;
14636 const headers = new Headers(request[INTERNALS$2].headers);
14637
14638 // fetch step 1.3
14639 if (!headers.has('Accept')) {
14640 headers.set('Accept', '*/*');
14641 }
14642
14643 // Basic fetch
14644 if (!parsedURL.protocol || !parsedURL.hostname) {
14645 throw new TypeError('Only absolute URLs are supported');
14646 }
14647
14648 if (!/^https?:$/.test(parsedURL.protocol)) {
14649 throw new TypeError('Only HTTP(S) protocols are supported');
14650 }
14651
14652 if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
14653 throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
14654 }
14655
14656 // HTTP-network-or-cache fetch steps 2.4-2.7
14657 let contentLengthValue = null;
14658 if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
14659 contentLengthValue = '0';
14660 }
14661 if (request.body != null) {
14662 const totalBytes = getTotalBytes(request);
14663 if (typeof totalBytes === 'number') {
14664 contentLengthValue = String(totalBytes);
14665 }
14666 }
14667 if (contentLengthValue) {
14668 headers.set('Content-Length', contentLengthValue);
14669 }
14670
14671 // HTTP-network-or-cache fetch step 2.11
14672 if (!headers.has('User-Agent')) {
14673 headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
14674 }
14675
14676 // HTTP-network-or-cache fetch step 2.15
14677 if (request.compress && !headers.has('Accept-Encoding')) {
14678 headers.set('Accept-Encoding', 'gzip,deflate');
14679 }
14680
14681 let agent = request.agent;
14682 if (typeof agent === 'function') {
14683 agent = agent(parsedURL);
14684 }
14685
14686 if (!headers.has('Connection') && !agent) {
14687 headers.set('Connection', 'close');
14688 }
14689
14690 // HTTP-network fetch step 4.2
14691 // chunked encoding is handled by Node.js
14692
14693 return Object.assign({}, parsedURL, {
14694 method: request.method,
14695 headers: exportNodeCompatibleHeaders(headers),
14696 agent
14697 });
14698}
14699
14700/**
14701 * abort-error.js
14702 *
14703 * AbortError interface for cancelled requests
14704 */
14705
14706/**
14707 * Create AbortError instance
14708 *
14709 * @param String message Error message for human
14710 * @return AbortError
14711 */
14712function AbortError(message) {
14713 Error.call(this, message);
14714
14715 this.type = 'aborted';
14716 this.message = message;
14717
14718 // hide custom error implementation details from end-users
14719 Error.captureStackTrace(this, this.constructor);
14720}
14721
14722AbortError.prototype = Object.create(Error.prototype);
14723AbortError.prototype.constructor = AbortError;
14724AbortError.prototype.name = 'AbortError';
14725
14726// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
14727const PassThrough$1$1 = Stream.PassThrough;
14728const resolve_url = Url.resolve;
14729
14730/**
14731 * Fetch function
14732 *
14733 * @param Mixed url Absolute url or Request instance
14734 * @param Object opts Fetch options
14735 * @return Promise
14736 */
14737function fetch(url, opts) {
14738
14739 // allow custom promise
14740 if (!fetch.Promise) {
14741 throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
14742 }
14743
14744 Body.Promise = fetch.Promise;
14745
14746 // wrap http.request into fetch
14747 return new fetch.Promise(function (resolve, reject) {
14748 // build request object
14749 const request = new Request(url, opts);
14750 const options = getNodeRequestOptions(request);
14751
14752 const send = (options.protocol === 'https:' ? http : http).request;
14753 const signal = request.signal;
14754
14755 let response = null;
14756
14757 const abort = function abort() {
14758 let error = new AbortError('The user aborted a request.');
14759 reject(error);
14760 if (request.body && request.body instanceof Stream.Readable) {
14761 request.body.destroy(error);
14762 }
14763 if (!response || !response.body) return;
14764 response.body.emit('error', error);
14765 };
14766
14767 if (signal && signal.aborted) {
14768 abort();
14769 return;
14770 }
14771
14772 const abortAndFinalize = function abortAndFinalize() {
14773 abort();
14774 finalize();
14775 };
14776
14777 // send request
14778 const req = send(options);
14779 let reqTimeout;
14780
14781 if (signal) {
14782 signal.addEventListener('abort', abortAndFinalize);
14783 }
14784
14785 function finalize() {
14786 req.abort();
14787 if (signal) signal.removeEventListener('abort', abortAndFinalize);
14788 clearTimeout(reqTimeout);
14789 }
14790
14791 if (request.timeout) {
14792 req.once('socket', function (socket) {
14793 reqTimeout = setTimeout(function () {
14794 reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
14795 finalize();
14796 }, request.timeout);
14797 });
14798 }
14799
14800 req.on('error', function (err) {
14801 reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
14802 finalize();
14803 });
14804
14805 req.on('response', function (res) {
14806 clearTimeout(reqTimeout);
14807
14808 const headers = createHeadersLenient(res.headers);
14809
14810 // HTTP fetch step 5
14811 if (fetch.isRedirect(res.statusCode)) {
14812 // HTTP fetch step 5.2
14813 const location = headers.get('Location');
14814
14815 // HTTP fetch step 5.3
14816 const locationURL = location === null ? null : resolve_url(request.url, location);
14817
14818 // HTTP fetch step 5.5
14819 switch (request.redirect) {
14820 case 'error':
14821 reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));
14822 finalize();
14823 return;
14824 case 'manual':
14825 // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
14826 if (locationURL !== null) {
14827 // handle corrupted header
14828 try {
14829 headers.set('Location', locationURL);
14830 } catch (err) {
14831 // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
14832 reject(err);
14833 }
14834 }
14835 break;
14836 case 'follow':
14837 // HTTP-redirect fetch step 2
14838 if (locationURL === null) {
14839 break;
14840 }
14841
14842 // HTTP-redirect fetch step 5
14843 if (request.counter >= request.follow) {
14844 reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
14845 finalize();
14846 return;
14847 }
14848
14849 // HTTP-redirect fetch step 6 (counter increment)
14850 // Create a new Request object.
14851 const requestOpts = {
14852 headers: new Headers(request.headers),
14853 follow: request.follow,
14854 counter: request.counter + 1,
14855 agent: request.agent,
14856 compress: request.compress,
14857 method: request.method,
14858 body: request.body,
14859 signal: request.signal,
14860 timeout: request.timeout
14861 };
14862
14863 // HTTP-redirect fetch step 9
14864 if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
14865 reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
14866 finalize();
14867 return;
14868 }
14869
14870 // HTTP-redirect fetch step 11
14871 if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
14872 requestOpts.method = 'GET';
14873 requestOpts.body = undefined;
14874 requestOpts.headers.delete('content-length');
14875 }
14876
14877 // HTTP-redirect fetch step 15
14878 resolve(fetch(new Request(locationURL, requestOpts)));
14879 finalize();
14880 return;
14881 }
14882 }
14883
14884 // prepare response
14885 res.once('end', function () {
14886 if (signal) signal.removeEventListener('abort', abortAndFinalize);
14887 });
14888 let body = res.pipe(new PassThrough$1$1());
14889
14890 const response_options = {
14891 url: request.url,
14892 status: res.statusCode,
14893 statusText: res.statusMessage,
14894 headers: headers,
14895 size: request.size,
14896 timeout: request.timeout,
14897 counter: request.counter
14898 };
14899
14900 // HTTP-network fetch step 12.1.1.3
14901 const codings = headers.get('Content-Encoding');
14902
14903 // HTTP-network fetch step 12.1.1.4: handle content codings
14904
14905 // in following scenarios we ignore compression support
14906 // 1. compression support is disabled
14907 // 2. HEAD request
14908 // 3. no Content-Encoding header
14909 // 4. no content response (204)
14910 // 5. content not modified response (304)
14911 if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
14912 response = new Response(body, response_options);
14913 resolve(response);
14914 return;
14915 }
14916
14917 // For Node v6+
14918 // Be less strict when decoding compressed responses, since sometimes
14919 // servers send slightly invalid responses that are still accepted
14920 // by common browsers.
14921 // Always using Z_SYNC_FLUSH is what cURL does.
14922 const zlibOptions = {
14923 flush: zlib.Z_SYNC_FLUSH,
14924 finishFlush: zlib.Z_SYNC_FLUSH
14925 };
14926
14927 // for gzip
14928 if (codings == 'gzip' || codings == 'x-gzip') {
14929 body = body.pipe(zlib.createGunzip(zlibOptions));
14930 response = new Response(body, response_options);
14931 resolve(response);
14932 return;
14933 }
14934
14935 // for deflate
14936 if (codings == 'deflate' || codings == 'x-deflate') {
14937 // handle the infamous raw deflate response from old servers
14938 // a hack for old IIS and Apache servers
14939 const raw = res.pipe(new PassThrough$1$1());
14940 raw.once('data', function (chunk) {
14941 // see http://stackoverflow.com/questions/37519828
14942 if ((chunk[0] & 0x0F) === 0x08) {
14943 body = body.pipe(zlib.createInflate());
14944 } else {
14945 body = body.pipe(zlib.createInflateRaw());
14946 }
14947 response = new Response(body, response_options);
14948 resolve(response);
14949 });
14950 return;
14951 }
14952
14953 // for br
14954 if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
14955 body = body.pipe(zlib.createBrotliDecompress());
14956 response = new Response(body, response_options);
14957 resolve(response);
14958 return;
14959 }
14960
14961 // otherwise, use response as-is
14962 response = new Response(body, response_options);
14963 resolve(response);
14964 });
14965
14966 writeToStream(req, request);
14967 });
14968}
14969/**
14970 * Redirect code matching
14971 *
14972 * @param Number code Status code
14973 * @return Boolean
14974 */
14975fetch.isRedirect = function (code) {
14976 return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
14977};
14978
14979// expose Promise
14980fetch.Promise = global.Promise;
14981
14982var lib = /*#__PURE__*/Object.freeze({
14983 __proto__: null,
14984 'default': fetch,
14985 Headers: Headers,
14986 Request: Request,
14987 Response: Response,
14988 FetchError: FetchError
14989});
14990
14991var browser$1 = true;
14992
14993/**
14994 * Helpers.
14995 */
14996
14997var s = 1000;
14998var m = s * 60;
14999var h = m * 60;
15000var d = h * 24;
15001var w = d * 7;
15002var y = d * 365.25;
15003
15004/**
15005 * Parse or format the given `val`.
15006 *
15007 * Options:
15008 *
15009 * - `long` verbose formatting [false]
15010 *
15011 * @param {String|Number} val
15012 * @param {Object} [options]
15013 * @throws {Error} throw an error if val is not a non-empty string or a number
15014 * @return {String|Number}
15015 * @api public
15016 */
15017
15018var ms = function(val, options) {
15019 options = options || {};
15020 var type = typeof val;
15021 if (type === 'string' && val.length > 0) {
15022 return parse$2(val);
15023 } else if (type === 'number' && isFinite(val)) {
15024 return options.long ? fmtLong(val) : fmtShort(val);
15025 }
15026 throw new Error(
15027 'val is not a non-empty string or a valid number. val=' +
15028 JSON.stringify(val)
15029 );
15030};
15031
15032/**
15033 * Parse the given `str` and return milliseconds.
15034 *
15035 * @param {String} str
15036 * @return {Number}
15037 * @api private
15038 */
15039
15040function parse$2(str) {
15041 str = String(str);
15042 if (str.length > 100) {
15043 return;
15044 }
15045 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
15046 str
15047 );
15048 if (!match) {
15049 return;
15050 }
15051 var n = parseFloat(match[1]);
15052 var type = (match[2] || 'ms').toLowerCase();
15053 switch (type) {
15054 case 'years':
15055 case 'year':
15056 case 'yrs':
15057 case 'yr':
15058 case 'y':
15059 return n * y;
15060 case 'weeks':
15061 case 'week':
15062 case 'w':
15063 return n * w;
15064 case 'days':
15065 case 'day':
15066 case 'd':
15067 return n * d;
15068 case 'hours':
15069 case 'hour':
15070 case 'hrs':
15071 case 'hr':
15072 case 'h':
15073 return n * h;
15074 case 'minutes':
15075 case 'minute':
15076 case 'mins':
15077 case 'min':
15078 case 'm':
15079 return n * m;
15080 case 'seconds':
15081 case 'second':
15082 case 'secs':
15083 case 'sec':
15084 case 's':
15085 return n * s;
15086 case 'milliseconds':
15087 case 'millisecond':
15088 case 'msecs':
15089 case 'msec':
15090 case 'ms':
15091 return n;
15092 default:
15093 return undefined;
15094 }
15095}
15096
15097/**
15098 * Short format for `ms`.
15099 *
15100 * @param {Number} ms
15101 * @return {String}
15102 * @api private
15103 */
15104
15105function fmtShort(ms) {
15106 var msAbs = Math.abs(ms);
15107 if (msAbs >= d) {
15108 return Math.round(ms / d) + 'd';
15109 }
15110 if (msAbs >= h) {
15111 return Math.round(ms / h) + 'h';
15112 }
15113 if (msAbs >= m) {
15114 return Math.round(ms / m) + 'm';
15115 }
15116 if (msAbs >= s) {
15117 return Math.round(ms / s) + 's';
15118 }
15119 return ms + 'ms';
15120}
15121
15122/**
15123 * Long format for `ms`.
15124 *
15125 * @param {Number} ms
15126 * @return {String}
15127 * @api private
15128 */
15129
15130function fmtLong(ms) {
15131 var msAbs = Math.abs(ms);
15132 if (msAbs >= d) {
15133 return plural(ms, msAbs, d, 'day');
15134 }
15135 if (msAbs >= h) {
15136 return plural(ms, msAbs, h, 'hour');
15137 }
15138 if (msAbs >= m) {
15139 return plural(ms, msAbs, m, 'minute');
15140 }
15141 if (msAbs >= s) {
15142 return plural(ms, msAbs, s, 'second');
15143 }
15144 return ms + ' ms';
15145}
15146
15147/**
15148 * Pluralization helper.
15149 */
15150
15151function plural(ms, msAbs, n, name) {
15152 var isPlural = msAbs >= n * 1.5;
15153 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
15154}
15155
15156/**
15157 * This is the common logic for both the Node.js and web browser
15158 * implementations of `debug()`.
15159 */
15160
15161function setup(env) {
15162 createDebug.debug = createDebug;
15163 createDebug.default = createDebug;
15164 createDebug.coerce = coerce;
15165 createDebug.disable = disable;
15166 createDebug.enable = enable;
15167 createDebug.enabled = enabled;
15168 createDebug.humanize = ms;
15169
15170 Object.keys(env).forEach(key => {
15171 createDebug[key] = env[key];
15172 });
15173
15174 /**
15175 * Active `debug` instances.
15176 */
15177 createDebug.instances = [];
15178
15179 /**
15180 * The currently active debug mode names, and names to skip.
15181 */
15182
15183 createDebug.names = [];
15184 createDebug.skips = [];
15185
15186 /**
15187 * Map of special "%n" handling functions, for the debug "format" argument.
15188 *
15189 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
15190 */
15191 createDebug.formatters = {};
15192
15193 /**
15194 * Selects a color for a debug namespace
15195 * @param {String} namespace The namespace string for the for the debug instance to be colored
15196 * @return {Number|String} An ANSI color code for the given namespace
15197 * @api private
15198 */
15199 function selectColor(namespace) {
15200 let hash = 0;
15201
15202 for (let i = 0; i < namespace.length; i++) {
15203 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
15204 hash |= 0; // Convert to 32bit integer
15205 }
15206
15207 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
15208 }
15209 createDebug.selectColor = selectColor;
15210
15211 /**
15212 * Create a debugger with the given `namespace`.
15213 *
15214 * @param {String} namespace
15215 * @return {Function}
15216 * @api public
15217 */
15218 function createDebug(namespace) {
15219 let prevTime;
15220
15221 function debug(...args) {
15222 // Disabled?
15223 if (!debug.enabled) {
15224 return;
15225 }
15226
15227 const self = debug;
15228
15229 // Set `diff` timestamp
15230 const curr = Number(new Date());
15231 const ms = curr - (prevTime || curr);
15232 self.diff = ms;
15233 self.prev = prevTime;
15234 self.curr = curr;
15235 prevTime = curr;
15236
15237 args[0] = createDebug.coerce(args[0]);
15238
15239 if (typeof args[0] !== 'string') {
15240 // Anything else let's inspect with %O
15241 args.unshift('%O');
15242 }
15243
15244 // Apply any `formatters` transformations
15245 let index = 0;
15246 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
15247 // If we encounter an escaped % then don't increase the array index
15248 if (match === '%%') {
15249 return match;
15250 }
15251 index++;
15252 const formatter = createDebug.formatters[format];
15253 if (typeof formatter === 'function') {
15254 const val = args[index];
15255 match = formatter.call(self, val);
15256
15257 // Now we need to remove `args[index]` since it's inlined in the `format`
15258 args.splice(index, 1);
15259 index--;
15260 }
15261 return match;
15262 });
15263
15264 // Apply env-specific formatting (colors, etc.)
15265 createDebug.formatArgs.call(self, args);
15266
15267 const logFn = self.log || createDebug.log;
15268 logFn.apply(self, args);
15269 }
15270
15271 debug.namespace = namespace;
15272 debug.enabled = createDebug.enabled(namespace);
15273 debug.useColors = createDebug.useColors();
15274 debug.color = selectColor(namespace);
15275 debug.destroy = destroy;
15276 debug.extend = extend;
15277 // Debug.formatArgs = formatArgs;
15278 // debug.rawLog = rawLog;
15279
15280 // env-specific initialization logic for debug instances
15281 if (typeof createDebug.init === 'function') {
15282 createDebug.init(debug);
15283 }
15284
15285 createDebug.instances.push(debug);
15286
15287 return debug;
15288 }
15289
15290 function destroy() {
15291 const index = createDebug.instances.indexOf(this);
15292 if (index !== -1) {
15293 createDebug.instances.splice(index, 1);
15294 return true;
15295 }
15296 return false;
15297 }
15298
15299 function extend(namespace, delimiter) {
15300 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
15301 newDebug.log = this.log;
15302 return newDebug;
15303 }
15304
15305 /**
15306 * Enables a debug mode by namespaces. This can include modes
15307 * separated by a colon and wildcards.
15308 *
15309 * @param {String} namespaces
15310 * @api public
15311 */
15312 function enable(namespaces) {
15313 createDebug.save(namespaces);
15314
15315 createDebug.names = [];
15316 createDebug.skips = [];
15317
15318 let i;
15319 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
15320 const len = split.length;
15321
15322 for (i = 0; i < len; i++) {
15323 if (!split[i]) {
15324 // ignore empty strings
15325 continue;
15326 }
15327
15328 namespaces = split[i].replace(/\*/g, '.*?');
15329
15330 if (namespaces[0] === '-') {
15331 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
15332 } else {
15333 createDebug.names.push(new RegExp('^' + namespaces + '$'));
15334 }
15335 }
15336
15337 for (i = 0; i < createDebug.instances.length; i++) {
15338 const instance = createDebug.instances[i];
15339 instance.enabled = createDebug.enabled(instance.namespace);
15340 }
15341 }
15342
15343 /**
15344 * Disable debug output.
15345 *
15346 * @return {String} namespaces
15347 * @api public
15348 */
15349 function disable() {
15350 const namespaces = [
15351 ...createDebug.names.map(toNamespace),
15352 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
15353 ].join(',');
15354 createDebug.enable('');
15355 return namespaces;
15356 }
15357
15358 /**
15359 * Returns true if the given mode name is enabled, false otherwise.
15360 *
15361 * @param {String} name
15362 * @return {Boolean}
15363 * @api public
15364 */
15365 function enabled(name) {
15366 if (name[name.length - 1] === '*') {
15367 return true;
15368 }
15369
15370 let i;
15371 let len;
15372
15373 for (i = 0, len = createDebug.skips.length; i < len; i++) {
15374 if (createDebug.skips[i].test(name)) {
15375 return false;
15376 }
15377 }
15378
15379 for (i = 0, len = createDebug.names.length; i < len; i++) {
15380 if (createDebug.names[i].test(name)) {
15381 return true;
15382 }
15383 }
15384
15385 return false;
15386 }
15387
15388 /**
15389 * Convert regexp to namespace
15390 *
15391 * @param {RegExp} regxep
15392 * @return {String} namespace
15393 * @api private
15394 */
15395 function toNamespace(regexp) {
15396 return regexp.toString()
15397 .substring(2, regexp.toString().length - 2)
15398 .replace(/\.\*\?$/, '*');
15399 }
15400
15401 /**
15402 * Coerce `val`.
15403 *
15404 * @param {Mixed} val
15405 * @return {Mixed}
15406 * @api private
15407 */
15408 function coerce(val) {
15409 if (val instanceof Error) {
15410 return val.stack || val.message;
15411 }
15412 return val;
15413 }
15414
15415 createDebug.enable(createDebug.load());
15416
15417 return createDebug;
15418}
15419
15420var common = setup;
15421
15422var browser$2 = createCommonjsModule(function (module, exports) {
15423/* eslint-env browser */
15424
15425/**
15426 * This is the web browser implementation of `debug()`.
15427 */
15428
15429exports.log = log;
15430exports.formatArgs = formatArgs;
15431exports.save = save;
15432exports.load = load;
15433exports.useColors = useColors;
15434exports.storage = localstorage();
15435
15436/**
15437 * Colors.
15438 */
15439
15440exports.colors = [
15441 '#0000CC',
15442 '#0000FF',
15443 '#0033CC',
15444 '#0033FF',
15445 '#0066CC',
15446 '#0066FF',
15447 '#0099CC',
15448 '#0099FF',
15449 '#00CC00',
15450 '#00CC33',
15451 '#00CC66',
15452 '#00CC99',
15453 '#00CCCC',
15454 '#00CCFF',
15455 '#3300CC',
15456 '#3300FF',
15457 '#3333CC',
15458 '#3333FF',
15459 '#3366CC',
15460 '#3366FF',
15461 '#3399CC',
15462 '#3399FF',
15463 '#33CC00',
15464 '#33CC33',
15465 '#33CC66',
15466 '#33CC99',
15467 '#33CCCC',
15468 '#33CCFF',
15469 '#6600CC',
15470 '#6600FF',
15471 '#6633CC',
15472 '#6633FF',
15473 '#66CC00',
15474 '#66CC33',
15475 '#9900CC',
15476 '#9900FF',
15477 '#9933CC',
15478 '#9933FF',
15479 '#99CC00',
15480 '#99CC33',
15481 '#CC0000',
15482 '#CC0033',
15483 '#CC0066',
15484 '#CC0099',
15485 '#CC00CC',
15486 '#CC00FF',
15487 '#CC3300',
15488 '#CC3333',
15489 '#CC3366',
15490 '#CC3399',
15491 '#CC33CC',
15492 '#CC33FF',
15493 '#CC6600',
15494 '#CC6633',
15495 '#CC9900',
15496 '#CC9933',
15497 '#CCCC00',
15498 '#CCCC33',
15499 '#FF0000',
15500 '#FF0033',
15501 '#FF0066',
15502 '#FF0099',
15503 '#FF00CC',
15504 '#FF00FF',
15505 '#FF3300',
15506 '#FF3333',
15507 '#FF3366',
15508 '#FF3399',
15509 '#FF33CC',
15510 '#FF33FF',
15511 '#FF6600',
15512 '#FF6633',
15513 '#FF9900',
15514 '#FF9933',
15515 '#FFCC00',
15516 '#FFCC33'
15517];
15518
15519/**
15520 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
15521 * and the Firebug extension (any Firefox version) are known
15522 * to support "%c" CSS customizations.
15523 *
15524 * TODO: add a `localStorage` variable to explicitly enable/disable colors
15525 */
15526
15527// eslint-disable-next-line complexity
15528function useColors() {
15529 // NB: In an Electron preload script, document will be defined but not fully
15530 // initialized. Since we know we're in Chrome, we'll just detect this case
15531 // explicitly
15532 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
15533 return true;
15534 }
15535
15536 // Internet Explorer and Edge do not support colors.
15537 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
15538 return false;
15539 }
15540
15541 // Is webkit? http://stackoverflow.com/a/16459606/376773
15542 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
15543 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
15544 // Is firebug? http://stackoverflow.com/a/398120/376773
15545 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
15546 // Is firefox >= v31?
15547 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
15548 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
15549 // Double check webkit in userAgent just in case we are in a worker
15550 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
15551}
15552
15553/**
15554 * Colorize log arguments if enabled.
15555 *
15556 * @api public
15557 */
15558
15559function formatArgs(args) {
15560 args[0] = (this.useColors ? '%c' : '') +
15561 this.namespace +
15562 (this.useColors ? ' %c' : ' ') +
15563 args[0] +
15564 (this.useColors ? '%c ' : ' ') +
15565 '+' + module.exports.humanize(this.diff);
15566
15567 if (!this.useColors) {
15568 return;
15569 }
15570
15571 const c = 'color: ' + this.color;
15572 args.splice(1, 0, c, 'color: inherit');
15573
15574 // The final "%c" is somewhat tricky, because there could be other
15575 // arguments passed either before or after the %c, so we need to
15576 // figure out the correct index to insert the CSS into
15577 let index = 0;
15578 let lastC = 0;
15579 args[0].replace(/%[a-zA-Z%]/g, match => {
15580 if (match === '%%') {
15581 return;
15582 }
15583 index++;
15584 if (match === '%c') {
15585 // We only are interested in the *last* %c
15586 // (the user may have provided their own)
15587 lastC = index;
15588 }
15589 });
15590
15591 args.splice(lastC, 0, c);
15592}
15593
15594/**
15595 * Invokes `console.log()` when available.
15596 * No-op when `console.log` is not a "function".
15597 *
15598 * @api public
15599 */
15600function log(...args) {
15601 // This hackery is required for IE8/9, where
15602 // the `console.log` function doesn't have 'apply'
15603 return typeof console === 'object' &&
15604 console.log &&
15605 console.log(...args);
15606}
15607
15608/**
15609 * Save `namespaces`.
15610 *
15611 * @param {String} namespaces
15612 * @api private
15613 */
15614function save(namespaces) {
15615 try {
15616 if (namespaces) {
15617 exports.storage.setItem('debug', namespaces);
15618 } else {
15619 exports.storage.removeItem('debug');
15620 }
15621 } catch (error) {
15622 // Swallow
15623 // XXX (@Qix-) should we be logging these?
15624 }
15625}
15626
15627/**
15628 * Load `namespaces`.
15629 *
15630 * @return {String} returns the previously persisted debug modes
15631 * @api private
15632 */
15633function load() {
15634 let r;
15635 try {
15636 r = exports.storage.getItem('debug');
15637 } catch (error) {
15638 // Swallow
15639 // XXX (@Qix-) should we be logging these?
15640 }
15641
15642 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
15643 if (!r && typeof process !== 'undefined' && 'env' in process) {
15644 r = process.env.DEBUG;
15645 }
15646
15647 return r;
15648}
15649
15650/**
15651 * Localstorage attempts to return the localstorage.
15652 *
15653 * This is necessary because safari throws
15654 * when a user disables cookies/localstorage
15655 * and you attempt to access it.
15656 *
15657 * @return {LocalStorage}
15658 * @api private
15659 */
15660
15661function localstorage() {
15662 try {
15663 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
15664 // The Browser also has localStorage in the global context.
15665 return localStorage;
15666 } catch (error) {
15667 // Swallow
15668 // XXX (@Qix-) should we be logging these?
15669 }
15670}
15671
15672module.exports = common(exports);
15673
15674const {formatters} = module.exports;
15675
15676/**
15677 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
15678 */
15679
15680formatters.j = function (v) {
15681 try {
15682 return JSON.stringify(v);
15683 } catch (error) {
15684 return '[UnexpectedJSONParseError]: ' + error.message;
15685 }
15686};
15687});
15688var browser_1 = browser$2.log;
15689var browser_2 = browser$2.formatArgs;
15690var browser_3 = browser$2.save;
15691var browser_4 = browser$2.load;
15692var browser_5 = browser$2.useColors;
15693var browser_6 = browser$2.storage;
15694var browser_7 = browser$2.colors;
15695
15696// MIT lisence
15697// from https://github.com/substack/tty-browserify/blob/1ba769a6429d242f36226538835b4034bf6b7886/index.js
15698
15699function isatty() {
15700 return false;
15701}
15702
15703function ReadStream() {
15704 throw new Error('tty.ReadStream is not implemented');
15705}
15706
15707function WriteStream() {
15708 throw new Error('tty.ReadStream is not implemented');
15709}
15710
15711var tty = {
15712 isatty: isatty,
15713 ReadStream: ReadStream,
15714 WriteStream: WriteStream
15715};
15716
15717var argv$1 = process.argv;
15718
15719var terminator = argv$1.indexOf('--');
15720var hasFlag = function (flag) {
15721 flag = '--' + flag;
15722 var pos = argv$1.indexOf(flag);
15723 return pos !== -1 && (terminator !== -1 ? pos < terminator : true);
15724};
15725
15726var supportsColor = (function () {
15727 if ('FORCE_COLOR' in process.env) {
15728 return true;
15729 }
15730
15731 if (hasFlag('no-color') ||
15732 hasFlag('no-colors') ||
15733 hasFlag('color=false')) {
15734 return false;
15735 }
15736
15737 if (hasFlag('color') ||
15738 hasFlag('colors') ||
15739 hasFlag('color=true') ||
15740 hasFlag('color=always')) {
15741 return true;
15742 }
15743
15744 if ('COLORTERM' in process.env) {
15745 return true;
15746 }
15747
15748 if (process.env.TERM === 'dumb') {
15749 return false;
15750 }
15751
15752 if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) {
15753 return true;
15754 }
15755
15756 return false;
15757})();
15758
15759var node = createCommonjsModule(function (module, exports) {
15760/**
15761 * Module dependencies.
15762 */
15763
15764
15765
15766
15767/**
15768 * This is the Node.js implementation of `debug()`.
15769 */
15770
15771exports.init = init;
15772exports.log = log;
15773exports.formatArgs = formatArgs;
15774exports.save = save;
15775exports.load = load;
15776exports.useColors = useColors;
15777
15778/**
15779 * Colors.
15780 */
15781
15782exports.colors = [6, 2, 3, 4, 5, 1];
15783
15784try {
15785 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
15786 // eslint-disable-next-line import/no-extraneous-dependencies
15787 const supportsColor$1 = supportsColor;
15788
15789 if (supportsColor$1 && (supportsColor$1.stderr || supportsColor$1).level >= 2) {
15790 exports.colors = [
15791 20,
15792 21,
15793 26,
15794 27,
15795 32,
15796 33,
15797 38,
15798 39,
15799 40,
15800 41,
15801 42,
15802 43,
15803 44,
15804 45,
15805 56,
15806 57,
15807 62,
15808 63,
15809 68,
15810 69,
15811 74,
15812 75,
15813 76,
15814 77,
15815 78,
15816 79,
15817 80,
15818 81,
15819 92,
15820 93,
15821 98,
15822 99,
15823 112,
15824 113,
15825 128,
15826 129,
15827 134,
15828 135,
15829 148,
15830 149,
15831 160,
15832 161,
15833 162,
15834 163,
15835 164,
15836 165,
15837 166,
15838 167,
15839 168,
15840 169,
15841 170,
15842 171,
15843 172,
15844 173,
15845 178,
15846 179,
15847 184,
15848 185,
15849 196,
15850 197,
15851 198,
15852 199,
15853 200,
15854 201,
15855 202,
15856 203,
15857 204,
15858 205,
15859 206,
15860 207,
15861 208,
15862 209,
15863 214,
15864 215,
15865 220,
15866 221
15867 ];
15868 }
15869} catch (error) {
15870 // Swallow - we only care if `supports-color` is available; it doesn't have to be.
15871}
15872
15873/**
15874 * Build up the default `inspectOpts` object from the environment variables.
15875 *
15876 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
15877 */
15878
15879exports.inspectOpts = Object.keys(process.env).filter(key => {
15880 return /^debug_/i.test(key);
15881}).reduce((obj, key) => {
15882 // Camel-case
15883 const prop = key
15884 .substring(6)
15885 .toLowerCase()
15886 .replace(/_([a-z])/g, (_, k) => {
15887 return k.toUpperCase();
15888 });
15889
15890 // Coerce string value into JS value
15891 let val = process.env[key];
15892 if (/^(yes|on|true|enabled)$/i.test(val)) {
15893 val = true;
15894 } else if (/^(no|off|false|disabled)$/i.test(val)) {
15895 val = false;
15896 } else if (val === 'null') {
15897 val = null;
15898 } else {
15899 val = Number(val);
15900 }
15901
15902 obj[prop] = val;
15903 return obj;
15904}, {});
15905
15906/**
15907 * Is stdout a TTY? Colored output is enabled when `true`.
15908 */
15909
15910function useColors() {
15911 return 'colors' in exports.inspectOpts ?
15912 Boolean(exports.inspectOpts.colors) :
15913 tty.isatty(process.stderr.fd);
15914}
15915
15916/**
15917 * Adds ANSI color escape codes if enabled.
15918 *
15919 * @api public
15920 */
15921
15922function formatArgs(args) {
15923 const {namespace: name, useColors} = this;
15924
15925 if (useColors) {
15926 const c = this.color;
15927 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
15928 const prefix = ` ${colorCode};1m${name} \u001B[0m`;
15929
15930 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
15931 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
15932 } else {
15933 args[0] = getDate() + name + ' ' + args[0];
15934 }
15935}
15936
15937function getDate() {
15938 if (exports.inspectOpts.hideDate) {
15939 return '';
15940 }
15941 return new Date().toISOString() + ' ';
15942}
15943
15944/**
15945 * Invokes `util.format()` with the specified arguments and writes to stderr.
15946 */
15947
15948function log(...args) {
15949 return process.stderr.write(util.format(...args) + '\n');
15950}
15951
15952/**
15953 * Save `namespaces`.
15954 *
15955 * @param {String} namespaces
15956 * @api private
15957 */
15958function save(namespaces) {
15959 if (namespaces) {
15960 process.env.DEBUG = namespaces;
15961 } else {
15962 // If you set a process.env field to null or undefined, it gets cast to the
15963 // string 'null' or 'undefined'. Just delete instead.
15964 delete process.env.DEBUG;
15965 }
15966}
15967
15968/**
15969 * Load `namespaces`.
15970 *
15971 * @return {String} returns the previously persisted debug modes
15972 * @api private
15973 */
15974
15975function load() {
15976 return process.env.DEBUG;
15977}
15978
15979/**
15980 * Init logic for `debug` instances.
15981 *
15982 * Create a new `inspectOpts` object in case `useColors` is set
15983 * differently for a particular `debug` instance.
15984 */
15985
15986function init(debug) {
15987 debug.inspectOpts = {};
15988
15989 const keys = Object.keys(exports.inspectOpts);
15990 for (let i = 0; i < keys.length; i++) {
15991 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
15992 }
15993}
15994
15995module.exports = common(exports);
15996
15997const {formatters} = module.exports;
15998
15999/**
16000 * Map %o to `util.inspect()`, all on a single line.
16001 */
16002
16003formatters.o = function (v) {
16004 this.inspectOpts.colors = this.useColors;
16005 return util.inspect(v, this.inspectOpts)
16006 .replace(/\s*\n\s*/g, ' ');
16007};
16008
16009/**
16010 * Map %O to `util.inspect()`, allowing multiple lines if needed.
16011 */
16012
16013formatters.O = function (v) {
16014 this.inspectOpts.colors = this.useColors;
16015 return util.inspect(v, this.inspectOpts);
16016};
16017});
16018var node_1 = node.init;
16019var node_2 = node.log;
16020var node_3 = node.formatArgs;
16021var node_4 = node.save;
16022var node_5 = node.load;
16023var node_6 = node.useColors;
16024var node_7 = node.colors;
16025var node_8 = node.inspectOpts;
16026
16027var src = createCommonjsModule(function (module) {
16028/**
16029 * Detect Electron renderer / nwjs process, which is node, but we should
16030 * treat as a browser.
16031 */
16032
16033if (typeof process === 'undefined' || process.type === 'renderer' || browser$1 === true || process.__nwjs) {
16034 module.exports = browser$2;
16035} else {
16036 module.exports = node;
16037}
16038});
16039
16040let debugFunc;
16041let phase = 'default';
16042let namespace = '';
16043const newDebug = () => {
16044 debugFunc = namespace
16045 ? src(`fetch-mock:${phase}:${namespace}`)
16046 : src(`fetch-mock:${phase}`);
16047};
16048
16049const newDebugSandbox = ns => src(`fetch-mock:${phase}:${ns}`);
16050
16051newDebug();
16052
16053var debug_1 = {
16054 debug: (...args) => {
16055 debugFunc(...args);
16056 },
16057 setDebugNamespace: str => {
16058 namespace = str;
16059 newDebug();
16060 },
16061 setDebugPhase: str => {
16062 phase = str || 'default';
16063 newDebug();
16064 },
16065 getDebug: namespace => newDebugSandbox(namespace)
16066};
16067
16068var globToRegexp = function (glob, opts) {
16069 if (typeof glob !== 'string') {
16070 throw new TypeError('Expected a string');
16071 }
16072
16073 var str = String(glob);
16074
16075 // The regexp we are building, as a string.
16076 var reStr = "";
16077
16078 // Whether we are matching so called "extended" globs (like bash) and should
16079 // support single character matching, matching ranges of characters, group
16080 // matching, etc.
16081 var extended = opts ? !!opts.extended : false;
16082
16083 // When globstar is _false_ (default), '/foo/*' is translated a regexp like
16084 // '^\/foo\/.*$' which will match any string beginning with '/foo/'
16085 // When globstar is _true_, '/foo/*' is translated to regexp like
16086 // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT
16087 // which does not have a '/' to the right of it.
16088 // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but
16089 // these will not '/foo/bar/baz', '/foo/bar/baz.txt'
16090 // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when
16091 // globstar is _false_
16092 var globstar = opts ? !!opts.globstar : false;
16093
16094 // If we are doing extended matching, this boolean is true when we are inside
16095 // a group (eg {*.html,*.js}), and false otherwise.
16096 var inGroup = false;
16097
16098 // RegExp flags (eg "i" ) to pass in to RegExp constructor.
16099 var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : "";
16100
16101 var c;
16102 for (var i = 0, len = str.length; i < len; i++) {
16103 c = str[i];
16104
16105 switch (c) {
16106 case "/":
16107 case "$":
16108 case "^":
16109 case "+":
16110 case ".":
16111 case "(":
16112 case ")":
16113 case "=":
16114 case "!":
16115 case "|":
16116 reStr += "\\" + c;
16117 break;
16118
16119 case "?":
16120 if (extended) {
16121 reStr += ".";
16122 break;
16123 }
16124
16125 case "[":
16126 case "]":
16127 if (extended) {
16128 reStr += c;
16129 break;
16130 }
16131
16132 case "{":
16133 if (extended) {
16134 inGroup = true;
16135 reStr += "(";
16136 break;
16137 }
16138
16139 case "}":
16140 if (extended) {
16141 inGroup = false;
16142 reStr += ")";
16143 break;
16144 }
16145
16146 case ",":
16147 if (inGroup) {
16148 reStr += "|";
16149 break;
16150 }
16151 reStr += "\\" + c;
16152 break;
16153
16154 case "*":
16155 // Move over all consecutive "*"'s.
16156 // Also store the previous and next characters
16157 var prevChar = str[i - 1];
16158 var starCount = 1;
16159 while(str[i + 1] === "*") {
16160 starCount++;
16161 i++;
16162 }
16163 var nextChar = str[i + 1];
16164
16165 if (!globstar) {
16166 // globstar is disabled, so treat any number of "*" as one
16167 reStr += ".*";
16168 } else {
16169 // globstar is enabled, so determine if this is a globstar segment
16170 var isGlobstar = starCount > 1 // multiple "*"'s
16171 && (prevChar === "/" || prevChar === undefined) // from the start of the segment
16172 && (nextChar === "/" || nextChar === undefined); // to the end of the segment
16173
16174 if (isGlobstar) {
16175 // it's a globstar, so match zero or more path segments
16176 reStr += "((?:[^/]*(?:\/|$))*)";
16177 i++; // move over the "/"
16178 } else {
16179 // it's not a globstar, so only match one path segment
16180 reStr += "([^/]*)";
16181 }
16182 }
16183 break;
16184
16185 default:
16186 reStr += c;
16187 }
16188 }
16189
16190 // When regexp 'g' flag is specified don't
16191 // constrain the regular expression with ^ & $
16192 if (!flags || !~flags.indexOf('g')) {
16193 reStr = "^" + reStr + "$";
16194 }
16195
16196 return new RegExp(reStr, flags);
16197};
16198
16199/**
16200 * Expose `pathToRegexp`.
16201 */
16202var pathToRegexp_1 = pathToRegexp;
16203var parse_1 = parse$3;
16204var compile_1 = compile;
16205var tokensToFunction_1 = tokensToFunction;
16206var tokensToRegExp_1 = tokensToRegExp;
16207
16208/**
16209 * Default configs.
16210 */
16211var DEFAULT_DELIMITER = '/';
16212var DEFAULT_DELIMITERS = './';
16213
16214/**
16215 * The main path matching regexp utility.
16216 *
16217 * @type {RegExp}
16218 */
16219var PATH_REGEXP = new RegExp([
16220 // Match escaped characters that would otherwise appear in future matches.
16221 // This allows the user to escape special characters that won't transform.
16222 '(\\\\.)',
16223 // Match Express-style parameters and un-named parameters with a prefix
16224 // and optional suffixes. Matches appear as:
16225 //
16226 // ":test(\\d+)?" => ["test", "\d+", undefined, "?"]
16227 // "(\\d+)" => [undefined, undefined, "\d+", undefined]
16228 '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?'
16229].join('|'), 'g');
16230
16231/**
16232 * Parse a string for the raw tokens.
16233 *
16234 * @param {string} str
16235 * @param {Object=} options
16236 * @return {!Array}
16237 */
16238function parse$3 (str, options) {
16239 var tokens = [];
16240 var key = 0;
16241 var index = 0;
16242 var path = '';
16243 var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER;
16244 var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS;
16245 var pathEscaped = false;
16246 var res;
16247
16248 while ((res = PATH_REGEXP.exec(str)) !== null) {
16249 var m = res[0];
16250 var escaped = res[1];
16251 var offset = res.index;
16252 path += str.slice(index, offset);
16253 index = offset + m.length;
16254
16255 // Ignore already escaped sequences.
16256 if (escaped) {
16257 path += escaped[1];
16258 pathEscaped = true;
16259 continue
16260 }
16261
16262 var prev = '';
16263 var next = str[index];
16264 var name = res[2];
16265 var capture = res[3];
16266 var group = res[4];
16267 var modifier = res[5];
16268
16269 if (!pathEscaped && path.length) {
16270 var k = path.length - 1;
16271
16272 if (delimiters.indexOf(path[k]) > -1) {
16273 prev = path[k];
16274 path = path.slice(0, k);
16275 }
16276 }
16277
16278 // Push the current path onto the tokens.
16279 if (path) {
16280 tokens.push(path);
16281 path = '';
16282 pathEscaped = false;
16283 }
16284
16285 var partial = prev !== '' && next !== undefined && next !== prev;
16286 var repeat = modifier === '+' || modifier === '*';
16287 var optional = modifier === '?' || modifier === '*';
16288 var delimiter = prev || defaultDelimiter;
16289 var pattern = capture || group;
16290
16291 tokens.push({
16292 name: name || key++,
16293 prefix: prev,
16294 delimiter: delimiter,
16295 optional: optional,
16296 repeat: repeat,
16297 partial: partial,
16298 pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?'
16299 });
16300 }
16301
16302 // Push any remaining characters.
16303 if (path || index < str.length) {
16304 tokens.push(path + str.substr(index));
16305 }
16306
16307 return tokens
16308}
16309
16310/**
16311 * Compile a string to a template function for the path.
16312 *
16313 * @param {string} str
16314 * @param {Object=} options
16315 * @return {!function(Object=, Object=)}
16316 */
16317function compile (str, options) {
16318 return tokensToFunction(parse$3(str, options))
16319}
16320
16321/**
16322 * Expose a method for transforming tokens into the path function.
16323 */
16324function tokensToFunction (tokens) {
16325 // Compile all the tokens into regexps.
16326 var matches = new Array(tokens.length);
16327
16328 // Compile all the patterns before compilation.
16329 for (var i = 0; i < tokens.length; i++) {
16330 if (typeof tokens[i] === 'object') {
16331 matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
16332 }
16333 }
16334
16335 return function (data, options) {
16336 var path = '';
16337 var encode = (options && options.encode) || encodeURIComponent;
16338
16339 for (var i = 0; i < tokens.length; i++) {
16340 var token = tokens[i];
16341
16342 if (typeof token === 'string') {
16343 path += token;
16344 continue
16345 }
16346
16347 var value = data ? data[token.name] : undefined;
16348 var segment;
16349
16350 if (Array.isArray(value)) {
16351 if (!token.repeat) {
16352 throw new TypeError('Expected "' + token.name + '" to not repeat, but got array')
16353 }
16354
16355 if (value.length === 0) {
16356 if (token.optional) continue
16357
16358 throw new TypeError('Expected "' + token.name + '" to not be empty')
16359 }
16360
16361 for (var j = 0; j < value.length; j++) {
16362 segment = encode(value[j], token);
16363
16364 if (!matches[i].test(segment)) {
16365 throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"')
16366 }
16367
16368 path += (j === 0 ? token.prefix : token.delimiter) + segment;
16369 }
16370
16371 continue
16372 }
16373
16374 if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
16375 segment = encode(String(value), token);
16376
16377 if (!matches[i].test(segment)) {
16378 throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"')
16379 }
16380
16381 path += token.prefix + segment;
16382 continue
16383 }
16384
16385 if (token.optional) {
16386 // Prepend partial segment prefixes.
16387 if (token.partial) path += token.prefix;
16388
16389 continue
16390 }
16391
16392 throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string'))
16393 }
16394
16395 return path
16396 }
16397}
16398
16399/**
16400 * Escape a regular expression string.
16401 *
16402 * @param {string} str
16403 * @return {string}
16404 */
16405function escapeString (str) {
16406 return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1')
16407}
16408
16409/**
16410 * Escape the capturing group by escaping special characters and meaning.
16411 *
16412 * @param {string} group
16413 * @return {string}
16414 */
16415function escapeGroup (group) {
16416 return group.replace(/([=!:$/()])/g, '\\$1')
16417}
16418
16419/**
16420 * Get the flags for a regexp from the options.
16421 *
16422 * @param {Object} options
16423 * @return {string}
16424 */
16425function flags (options) {
16426 return options && options.sensitive ? '' : 'i'
16427}
16428
16429/**
16430 * Pull out keys from a regexp.
16431 *
16432 * @param {!RegExp} path
16433 * @param {Array=} keys
16434 * @return {!RegExp}
16435 */
16436function regexpToRegexp (path, keys) {
16437 if (!keys) return path
16438
16439 // Use a negative lookahead to match only capturing groups.
16440 var groups = path.source.match(/\((?!\?)/g);
16441
16442 if (groups) {
16443 for (var i = 0; i < groups.length; i++) {
16444 keys.push({
16445 name: i,
16446 prefix: null,
16447 delimiter: null,
16448 optional: false,
16449 repeat: false,
16450 partial: false,
16451 pattern: null
16452 });
16453 }
16454 }
16455
16456 return path
16457}
16458
16459/**
16460 * Transform an array into a regexp.
16461 *
16462 * @param {!Array} path
16463 * @param {Array=} keys
16464 * @param {Object=} options
16465 * @return {!RegExp}
16466 */
16467function arrayToRegexp (path, keys, options) {
16468 var parts = [];
16469
16470 for (var i = 0; i < path.length; i++) {
16471 parts.push(pathToRegexp(path[i], keys, options).source);
16472 }
16473
16474 return new RegExp('(?:' + parts.join('|') + ')', flags(options))
16475}
16476
16477/**
16478 * Create a path regexp from string input.
16479 *
16480 * @param {string} path
16481 * @param {Array=} keys
16482 * @param {Object=} options
16483 * @return {!RegExp}
16484 */
16485function stringToRegexp (path, keys, options) {
16486 return tokensToRegExp(parse$3(path, options), keys, options)
16487}
16488
16489/**
16490 * Expose a function for taking tokens and returning a RegExp.
16491 *
16492 * @param {!Array} tokens
16493 * @param {Array=} keys
16494 * @param {Object=} options
16495 * @return {!RegExp}
16496 */
16497function tokensToRegExp (tokens, keys, options) {
16498 options = options || {};
16499
16500 var strict = options.strict;
16501 var start = options.start !== false;
16502 var end = options.end !== false;
16503 var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER);
16504 var delimiters = options.delimiters || DEFAULT_DELIMITERS;
16505 var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|');
16506 var route = start ? '^' : '';
16507 var isEndDelimited = tokens.length === 0;
16508
16509 // Iterate over the tokens and create our regexp string.
16510 for (var i = 0; i < tokens.length; i++) {
16511 var token = tokens[i];
16512
16513 if (typeof token === 'string') {
16514 route += escapeString(token);
16515 isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1;
16516 } else {
16517 var capture = token.repeat
16518 ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*'
16519 : token.pattern;
16520
16521 if (keys) keys.push(token);
16522
16523 if (token.optional) {
16524 if (token.partial) {
16525 route += escapeString(token.prefix) + '(' + capture + ')?';
16526 } else {
16527 route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?';
16528 }
16529 } else {
16530 route += escapeString(token.prefix) + '(' + capture + ')';
16531 }
16532 }
16533 }
16534
16535 if (end) {
16536 if (!strict) route += '(?:' + delimiter + ')?';
16537
16538 route += endsWith === '$' ? '$' : '(?=' + endsWith + ')';
16539 } else {
16540 if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?';
16541 if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')';
16542 }
16543
16544 return new RegExp(route, flags(options))
16545}
16546
16547/**
16548 * Normalize the given path string, returning a regular expression.
16549 *
16550 * An empty array can be passed in for the keys, which will hold the
16551 * placeholder key descriptions. For example, using `/user/:id`, `keys` will
16552 * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
16553 *
16554 * @param {(string|RegExp|Array)} path
16555 * @param {Array=} keys
16556 * @param {Object=} options
16557 * @return {!RegExp}
16558 */
16559function pathToRegexp (path, keys, options) {
16560 if (path instanceof RegExp) {
16561 return regexpToRegexp(path, keys)
16562 }
16563
16564 if (Array.isArray(path)) {
16565 return arrayToRegexp(/** @type {!Array} */ (path), keys, options)
16566 }
16567
16568 return stringToRegexp(/** @type {string} */ (path), keys, options)
16569}
16570pathToRegexp_1.parse = parse_1;
16571pathToRegexp_1.compile = compile_1;
16572pathToRegexp_1.tokensToFunction = tokensToFunction_1;
16573pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
16574
16575var isSubset_1 = createCommonjsModule(function (module, exports) {
16576
16577Object.defineProperty(exports, '__esModule', {
16578 value: true
16579});
16580/**
16581 * Check if an object is contained within another object.
16582 *
16583 * Returns `true` if:
16584 * - all enumerable keys of *subset* are also enumerable in *superset*, and
16585 * - every value assigned to an enumerable key of *subset* strictly equals
16586 * the value assigned to the same key of *superset* – or is a subset of it.
16587 *
16588 * @param {Object} superset
16589 * @param {Object} subset
16590 *
16591 * @returns {Boolean}
16592 *
16593 * @module is-subset
16594 * @function default
16595 * @alias isSubset
16596 */
16597var isSubset = (function (_isSubset) {
16598 function isSubset(_x, _x2) {
16599 return _isSubset.apply(this, arguments);
16600 }
16601
16602 isSubset.toString = function () {
16603 return _isSubset.toString();
16604 };
16605
16606 return isSubset;
16607})(function (superset, subset) {
16608 if (typeof superset !== 'object' || superset === null || (typeof subset !== 'object' || subset === null)) return false;
16609
16610 return Object.keys(subset).every(function (key) {
16611 if (!superset.propertyIsEnumerable(key)) return false;
16612
16613 var subsetItem = subset[key];
16614 var supersetItem = superset[key];
16615 if (typeof subsetItem === 'object' && subsetItem !== null ? !isSubset(supersetItem, subsetItem) : supersetItem !== subsetItem) return false;
16616
16617 return true;
16618 });
16619});
16620
16621exports['default'] = isSubset;
16622module.exports = exports['default'];
16623});
16624
16625unwrapExports(isSubset_1);
16626
16627let URL;
16628// https://stackoverflow.com/a/19709846/308237
16629const absoluteUrlRX = new RegExp('^(?:[a-z]+:)?//', 'i');
16630
16631const headersToArray = headers => {
16632 // node-fetch 1 Headers
16633 if (typeof headers.raw === 'function') {
16634 return Object.entries(headers.raw());
16635 } else if (headers[Symbol.iterator]) {
16636 return [...headers];
16637 } else {
16638 return Object.entries(headers);
16639 }
16640};
16641
16642const zipObject = entries =>
16643 entries.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {});
16644
16645const normalizeUrl = url => {
16646 if (
16647 typeof url === 'function' ||
16648 url instanceof RegExp ||
16649 /^(begin|end|glob|express|path)\:/.test(url)
16650 ) {
16651 return url;
16652 }
16653 if (absoluteUrlRX.test(url)) {
16654 const u = new URL(url);
16655 return u.href;
16656 } else {
16657 const u = new URL(url, 'http://dummy');
16658 return u.pathname + u.search;
16659 }
16660};
16661
16662const extractBody = async request => {
16663 try {
16664 // node-fetch
16665 if ('body' in request) {
16666 return request.body.toString();
16667 }
16668 // fetch
16669 return request.clone().text();
16670 } catch (err) {
16671 return;
16672 }
16673};
16674
16675var requestUtils = {
16676 setUrlImplementation: it => {
16677 URL = it;
16678 },
16679 normalizeRequest: (url, options, Request) => {
16680 if (Request.prototype.isPrototypeOf(url)) {
16681 const derivedOptions = {
16682 method: url.method
16683 };
16684
16685 const body = extractBody(url);
16686
16687 if (typeof body !== 'undefined') {
16688 derivedOptions.body = body;
16689 }
16690
16691 const normalizedRequestObject = {
16692 url: normalizeUrl(url.url),
16693 options: Object.assign(derivedOptions, options),
16694 request: url,
16695 signal: (options && options.signal) || url.signal
16696 };
16697
16698 const headers = headersToArray(url.headers);
16699
16700 if (headers.length) {
16701 normalizedRequestObject.options.headers = zipObject(headers);
16702 }
16703 return normalizedRequestObject;
16704 } else if (
16705 typeof url === 'string' ||
16706 // horrible URL object duck-typing
16707 (typeof url === 'object' && 'href' in url)
16708 ) {
16709 return {
16710 url: normalizeUrl(url),
16711 options: options,
16712 signal: options && options.signal
16713 };
16714 } else if (typeof url === 'object') {
16715 throw new TypeError(
16716 'fetch-mock: Unrecognised Request object. Read the Config and Installation sections of the docs'
16717 );
16718 } else {
16719 throw new TypeError('fetch-mock: Invalid arguments passed to fetch');
16720 }
16721 },
16722 normalizeUrl,
16723 getPath: url => {
16724 const u = absoluteUrlRX.test(url)
16725 ? new URL(url)
16726 : new URL(url, 'http://dummy');
16727 return u.pathname;
16728 },
16729
16730 getQuery: url => {
16731 const u = absoluteUrlRX.test(url)
16732 ? new URL(url)
16733 : new URL(url, 'http://dummy');
16734 return u.search ? u.search.substr(1) : '';
16735 },
16736 headers: {
16737 normalize: headers => zipObject(headersToArray(headers)),
16738 toLowerCase: headers =>
16739 Object.keys(headers).reduce((obj, k) => {
16740 obj[k.toLowerCase()] = headers[k];
16741 return obj;
16742 }, {}),
16743 equal: (actualHeader, expectedHeader) => {
16744 actualHeader = Array.isArray(actualHeader)
16745 ? actualHeader
16746 : [actualHeader];
16747 expectedHeader = Array.isArray(expectedHeader)
16748 ? expectedHeader
16749 : [expectedHeader];
16750
16751 if (actualHeader.length !== expectedHeader.length) {
16752 return false;
16753 }
16754
16755 return actualHeader.every((val, i) => val === expectedHeader[i]);
16756 }
16757 }
16758};
16759
16760var lodash_isequal = createCommonjsModule(function (module, exports) {
16761/**
16762 * Lodash (Custom Build) <https://lodash.com/>
16763 * Build: `lodash modularize exports="npm" -o ./`
16764 * Copyright JS Foundation and other contributors <https://js.foundation/>
16765 * Released under MIT license <https://lodash.com/license>
16766 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
16767 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
16768 */
16769
16770/** Used as the size to enable large array optimizations. */
16771var LARGE_ARRAY_SIZE = 200;
16772
16773/** Used to stand-in for `undefined` hash values. */
16774var HASH_UNDEFINED = '__lodash_hash_undefined__';
16775
16776/** Used to compose bitmasks for value comparisons. */
16777var COMPARE_PARTIAL_FLAG = 1,
16778 COMPARE_UNORDERED_FLAG = 2;
16779
16780/** Used as references for various `Number` constants. */
16781var MAX_SAFE_INTEGER = 9007199254740991;
16782
16783/** `Object#toString` result references. */
16784var argsTag = '[object Arguments]',
16785 arrayTag = '[object Array]',
16786 asyncTag = '[object AsyncFunction]',
16787 boolTag = '[object Boolean]',
16788 dateTag = '[object Date]',
16789 errorTag = '[object Error]',
16790 funcTag = '[object Function]',
16791 genTag = '[object GeneratorFunction]',
16792 mapTag = '[object Map]',
16793 numberTag = '[object Number]',
16794 nullTag = '[object Null]',
16795 objectTag = '[object Object]',
16796 promiseTag = '[object Promise]',
16797 proxyTag = '[object Proxy]',
16798 regexpTag = '[object RegExp]',
16799 setTag = '[object Set]',
16800 stringTag = '[object String]',
16801 symbolTag = '[object Symbol]',
16802 undefinedTag = '[object Undefined]',
16803 weakMapTag = '[object WeakMap]';
16804
16805var arrayBufferTag = '[object ArrayBuffer]',
16806 dataViewTag = '[object DataView]',
16807 float32Tag = '[object Float32Array]',
16808 float64Tag = '[object Float64Array]',
16809 int8Tag = '[object Int8Array]',
16810 int16Tag = '[object Int16Array]',
16811 int32Tag = '[object Int32Array]',
16812 uint8Tag = '[object Uint8Array]',
16813 uint8ClampedTag = '[object Uint8ClampedArray]',
16814 uint16Tag = '[object Uint16Array]',
16815 uint32Tag = '[object Uint32Array]';
16816
16817/**
16818 * Used to match `RegExp`
16819 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
16820 */
16821var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
16822
16823/** Used to detect host constructors (Safari). */
16824var reIsHostCtor = /^\[object .+?Constructor\]$/;
16825
16826/** Used to detect unsigned integer values. */
16827var reIsUint = /^(?:0|[1-9]\d*)$/;
16828
16829/** Used to identify `toStringTag` values of typed arrays. */
16830var typedArrayTags = {};
16831typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
16832typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
16833typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
16834typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
16835typedArrayTags[uint32Tag] = true;
16836typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
16837typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
16838typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
16839typedArrayTags[errorTag] = typedArrayTags[funcTag] =
16840typedArrayTags[mapTag] = typedArrayTags[numberTag] =
16841typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
16842typedArrayTags[setTag] = typedArrayTags[stringTag] =
16843typedArrayTags[weakMapTag] = false;
16844
16845/** Detect free variable `global` from Node.js. */
16846var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
16847
16848/** Detect free variable `self`. */
16849var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
16850
16851/** Used as a reference to the global object. */
16852var root = freeGlobal || freeSelf || Function('return this')();
16853
16854/** Detect free variable `exports`. */
16855var freeExports = exports && !exports.nodeType && exports;
16856
16857/** Detect free variable `module`. */
16858var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
16859
16860/** Detect the popular CommonJS extension `module.exports`. */
16861var moduleExports = freeModule && freeModule.exports === freeExports;
16862
16863/** Detect free variable `process` from Node.js. */
16864var freeProcess = moduleExports && freeGlobal.process;
16865
16866/** Used to access faster Node.js helpers. */
16867var nodeUtil = (function() {
16868 try {
16869 return freeProcess && freeProcess.binding && freeProcess.binding('util');
16870 } catch (e) {}
16871}());
16872
16873/* Node.js helper references. */
16874var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
16875
16876/**
16877 * A specialized version of `_.filter` for arrays without support for
16878 * iteratee shorthands.
16879 *
16880 * @private
16881 * @param {Array} [array] The array to iterate over.
16882 * @param {Function} predicate The function invoked per iteration.
16883 * @returns {Array} Returns the new filtered array.
16884 */
16885function arrayFilter(array, predicate) {
16886 var index = -1,
16887 length = array == null ? 0 : array.length,
16888 resIndex = 0,
16889 result = [];
16890
16891 while (++index < length) {
16892 var value = array[index];
16893 if (predicate(value, index, array)) {
16894 result[resIndex++] = value;
16895 }
16896 }
16897 return result;
16898}
16899
16900/**
16901 * Appends the elements of `values` to `array`.
16902 *
16903 * @private
16904 * @param {Array} array The array to modify.
16905 * @param {Array} values The values to append.
16906 * @returns {Array} Returns `array`.
16907 */
16908function arrayPush(array, values) {
16909 var index = -1,
16910 length = values.length,
16911 offset = array.length;
16912
16913 while (++index < length) {
16914 array[offset + index] = values[index];
16915 }
16916 return array;
16917}
16918
16919/**
16920 * A specialized version of `_.some` for arrays without support for iteratee
16921 * shorthands.
16922 *
16923 * @private
16924 * @param {Array} [array] The array to iterate over.
16925 * @param {Function} predicate The function invoked per iteration.
16926 * @returns {boolean} Returns `true` if any element passes the predicate check,
16927 * else `false`.
16928 */
16929function arraySome(array, predicate) {
16930 var index = -1,
16931 length = array == null ? 0 : array.length;
16932
16933 while (++index < length) {
16934 if (predicate(array[index], index, array)) {
16935 return true;
16936 }
16937 }
16938 return false;
16939}
16940
16941/**
16942 * The base implementation of `_.times` without support for iteratee shorthands
16943 * or max array length checks.
16944 *
16945 * @private
16946 * @param {number} n The number of times to invoke `iteratee`.
16947 * @param {Function} iteratee The function invoked per iteration.
16948 * @returns {Array} Returns the array of results.
16949 */
16950function baseTimes(n, iteratee) {
16951 var index = -1,
16952 result = Array(n);
16953
16954 while (++index < n) {
16955 result[index] = iteratee(index);
16956 }
16957 return result;
16958}
16959
16960/**
16961 * The base implementation of `_.unary` without support for storing metadata.
16962 *
16963 * @private
16964 * @param {Function} func The function to cap arguments for.
16965 * @returns {Function} Returns the new capped function.
16966 */
16967function baseUnary(func) {
16968 return function(value) {
16969 return func(value);
16970 };
16971}
16972
16973/**
16974 * Checks if a `cache` value for `key` exists.
16975 *
16976 * @private
16977 * @param {Object} cache The cache to query.
16978 * @param {string} key The key of the entry to check.
16979 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
16980 */
16981function cacheHas(cache, key) {
16982 return cache.has(key);
16983}
16984
16985/**
16986 * Gets the value at `key` of `object`.
16987 *
16988 * @private
16989 * @param {Object} [object] The object to query.
16990 * @param {string} key The key of the property to get.
16991 * @returns {*} Returns the property value.
16992 */
16993function getValue(object, key) {
16994 return object == null ? undefined : object[key];
16995}
16996
16997/**
16998 * Converts `map` to its key-value pairs.
16999 *
17000 * @private
17001 * @param {Object} map The map to convert.
17002 * @returns {Array} Returns the key-value pairs.
17003 */
17004function mapToArray(map) {
17005 var index = -1,
17006 result = Array(map.size);
17007
17008 map.forEach(function(value, key) {
17009 result[++index] = [key, value];
17010 });
17011 return result;
17012}
17013
17014/**
17015 * Creates a unary function that invokes `func` with its argument transformed.
17016 *
17017 * @private
17018 * @param {Function} func The function to wrap.
17019 * @param {Function} transform The argument transform.
17020 * @returns {Function} Returns the new function.
17021 */
17022function overArg(func, transform) {
17023 return function(arg) {
17024 return func(transform(arg));
17025 };
17026}
17027
17028/**
17029 * Converts `set` to an array of its values.
17030 *
17031 * @private
17032 * @param {Object} set The set to convert.
17033 * @returns {Array} Returns the values.
17034 */
17035function setToArray(set) {
17036 var index = -1,
17037 result = Array(set.size);
17038
17039 set.forEach(function(value) {
17040 result[++index] = value;
17041 });
17042 return result;
17043}
17044
17045/** Used for built-in method references. */
17046var arrayProto = Array.prototype,
17047 funcProto = Function.prototype,
17048 objectProto = Object.prototype;
17049
17050/** Used to detect overreaching core-js shims. */
17051var coreJsData = root['__core-js_shared__'];
17052
17053/** Used to resolve the decompiled source of functions. */
17054var funcToString = funcProto.toString;
17055
17056/** Used to check objects for own properties. */
17057var hasOwnProperty = objectProto.hasOwnProperty;
17058
17059/** Used to detect methods masquerading as native. */
17060var maskSrcKey = (function() {
17061 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
17062 return uid ? ('Symbol(src)_1.' + uid) : '';
17063}());
17064
17065/**
17066 * Used to resolve the
17067 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
17068 * of values.
17069 */
17070var nativeObjectToString = objectProto.toString;
17071
17072/** Used to detect if a method is native. */
17073var reIsNative = RegExp('^' +
17074 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
17075 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
17076);
17077
17078/** Built-in value references. */
17079var Buffer = moduleExports ? root.Buffer : undefined,
17080 Symbol = root.Symbol,
17081 Uint8Array = root.Uint8Array,
17082 propertyIsEnumerable = objectProto.propertyIsEnumerable,
17083 splice = arrayProto.splice,
17084 symToStringTag = Symbol ? Symbol.toStringTag : undefined;
17085
17086/* Built-in method references for those with the same name as other `lodash` methods. */
17087var nativeGetSymbols = Object.getOwnPropertySymbols,
17088 nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
17089 nativeKeys = overArg(Object.keys, Object);
17090
17091/* Built-in method references that are verified to be native. */
17092var DataView = getNative(root, 'DataView'),
17093 Map = getNative(root, 'Map'),
17094 Promise = getNative(root, 'Promise'),
17095 Set = getNative(root, 'Set'),
17096 WeakMap = getNative(root, 'WeakMap'),
17097 nativeCreate = getNative(Object, 'create');
17098
17099/** Used to detect maps, sets, and weakmaps. */
17100var dataViewCtorString = toSource(DataView),
17101 mapCtorString = toSource(Map),
17102 promiseCtorString = toSource(Promise),
17103 setCtorString = toSource(Set),
17104 weakMapCtorString = toSource(WeakMap);
17105
17106/** Used to convert symbols to primitives and strings. */
17107var symbolProto = Symbol ? Symbol.prototype : undefined,
17108 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
17109
17110/**
17111 * Creates a hash object.
17112 *
17113 * @private
17114 * @constructor
17115 * @param {Array} [entries] The key-value pairs to cache.
17116 */
17117function Hash(entries) {
17118 var index = -1,
17119 length = entries == null ? 0 : entries.length;
17120
17121 this.clear();
17122 while (++index < length) {
17123 var entry = entries[index];
17124 this.set(entry[0], entry[1]);
17125 }
17126}
17127
17128/**
17129 * Removes all key-value entries from the hash.
17130 *
17131 * @private
17132 * @name clear
17133 * @memberOf Hash
17134 */
17135function hashClear() {
17136 this.__data__ = nativeCreate ? nativeCreate(null) : {};
17137 this.size = 0;
17138}
17139
17140/**
17141 * Removes `key` and its value from the hash.
17142 *
17143 * @private
17144 * @name delete
17145 * @memberOf Hash
17146 * @param {Object} hash The hash to modify.
17147 * @param {string} key The key of the value to remove.
17148 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
17149 */
17150function hashDelete(key) {
17151 var result = this.has(key) && delete this.__data__[key];
17152 this.size -= result ? 1 : 0;
17153 return result;
17154}
17155
17156/**
17157 * Gets the hash value for `key`.
17158 *
17159 * @private
17160 * @name get
17161 * @memberOf Hash
17162 * @param {string} key The key of the value to get.
17163 * @returns {*} Returns the entry value.
17164 */
17165function hashGet(key) {
17166 var data = this.__data__;
17167 if (nativeCreate) {
17168 var result = data[key];
17169 return result === HASH_UNDEFINED ? undefined : result;
17170 }
17171 return hasOwnProperty.call(data, key) ? data[key] : undefined;
17172}
17173
17174/**
17175 * Checks if a hash value for `key` exists.
17176 *
17177 * @private
17178 * @name has
17179 * @memberOf Hash
17180 * @param {string} key The key of the entry to check.
17181 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
17182 */
17183function hashHas(key) {
17184 var data = this.__data__;
17185 return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
17186}
17187
17188/**
17189 * Sets the hash `key` to `value`.
17190 *
17191 * @private
17192 * @name set
17193 * @memberOf Hash
17194 * @param {string} key The key of the value to set.
17195 * @param {*} value The value to set.
17196 * @returns {Object} Returns the hash instance.
17197 */
17198function hashSet(key, value) {
17199 var data = this.__data__;
17200 this.size += this.has(key) ? 0 : 1;
17201 data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
17202 return this;
17203}
17204
17205// Add methods to `Hash`.
17206Hash.prototype.clear = hashClear;
17207Hash.prototype['delete'] = hashDelete;
17208Hash.prototype.get = hashGet;
17209Hash.prototype.has = hashHas;
17210Hash.prototype.set = hashSet;
17211
17212/**
17213 * Creates an list cache object.
17214 *
17215 * @private
17216 * @constructor
17217 * @param {Array} [entries] The key-value pairs to cache.
17218 */
17219function ListCache(entries) {
17220 var index = -1,
17221 length = entries == null ? 0 : entries.length;
17222
17223 this.clear();
17224 while (++index < length) {
17225 var entry = entries[index];
17226 this.set(entry[0], entry[1]);
17227 }
17228}
17229
17230/**
17231 * Removes all key-value entries from the list cache.
17232 *
17233 * @private
17234 * @name clear
17235 * @memberOf ListCache
17236 */
17237function listCacheClear() {
17238 this.__data__ = [];
17239 this.size = 0;
17240}
17241
17242/**
17243 * Removes `key` and its value from the list cache.
17244 *
17245 * @private
17246 * @name delete
17247 * @memberOf ListCache
17248 * @param {string} key The key of the value to remove.
17249 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
17250 */
17251function listCacheDelete(key) {
17252 var data = this.__data__,
17253 index = assocIndexOf(data, key);
17254
17255 if (index < 0) {
17256 return false;
17257 }
17258 var lastIndex = data.length - 1;
17259 if (index == lastIndex) {
17260 data.pop();
17261 } else {
17262 splice.call(data, index, 1);
17263 }
17264 --this.size;
17265 return true;
17266}
17267
17268/**
17269 * Gets the list cache value for `key`.
17270 *
17271 * @private
17272 * @name get
17273 * @memberOf ListCache
17274 * @param {string} key The key of the value to get.
17275 * @returns {*} Returns the entry value.
17276 */
17277function listCacheGet(key) {
17278 var data = this.__data__,
17279 index = assocIndexOf(data, key);
17280
17281 return index < 0 ? undefined : data[index][1];
17282}
17283
17284/**
17285 * Checks if a list cache value for `key` exists.
17286 *
17287 * @private
17288 * @name has
17289 * @memberOf ListCache
17290 * @param {string} key The key of the entry to check.
17291 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
17292 */
17293function listCacheHas(key) {
17294 return assocIndexOf(this.__data__, key) > -1;
17295}
17296
17297/**
17298 * Sets the list cache `key` to `value`.
17299 *
17300 * @private
17301 * @name set
17302 * @memberOf ListCache
17303 * @param {string} key The key of the value to set.
17304 * @param {*} value The value to set.
17305 * @returns {Object} Returns the list cache instance.
17306 */
17307function listCacheSet(key, value) {
17308 var data = this.__data__,
17309 index = assocIndexOf(data, key);
17310
17311 if (index < 0) {
17312 ++this.size;
17313 data.push([key, value]);
17314 } else {
17315 data[index][1] = value;
17316 }
17317 return this;
17318}
17319
17320// Add methods to `ListCache`.
17321ListCache.prototype.clear = listCacheClear;
17322ListCache.prototype['delete'] = listCacheDelete;
17323ListCache.prototype.get = listCacheGet;
17324ListCache.prototype.has = listCacheHas;
17325ListCache.prototype.set = listCacheSet;
17326
17327/**
17328 * Creates a map cache object to store key-value pairs.
17329 *
17330 * @private
17331 * @constructor
17332 * @param {Array} [entries] The key-value pairs to cache.
17333 */
17334function MapCache(entries) {
17335 var index = -1,
17336 length = entries == null ? 0 : entries.length;
17337
17338 this.clear();
17339 while (++index < length) {
17340 var entry = entries[index];
17341 this.set(entry[0], entry[1]);
17342 }
17343}
17344
17345/**
17346 * Removes all key-value entries from the map.
17347 *
17348 * @private
17349 * @name clear
17350 * @memberOf MapCache
17351 */
17352function mapCacheClear() {
17353 this.size = 0;
17354 this.__data__ = {
17355 'hash': new Hash,
17356 'map': new (Map || ListCache),
17357 'string': new Hash
17358 };
17359}
17360
17361/**
17362 * Removes `key` and its value from the map.
17363 *
17364 * @private
17365 * @name delete
17366 * @memberOf MapCache
17367 * @param {string} key The key of the value to remove.
17368 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
17369 */
17370function mapCacheDelete(key) {
17371 var result = getMapData(this, key)['delete'](key);
17372 this.size -= result ? 1 : 0;
17373 return result;
17374}
17375
17376/**
17377 * Gets the map value for `key`.
17378 *
17379 * @private
17380 * @name get
17381 * @memberOf MapCache
17382 * @param {string} key The key of the value to get.
17383 * @returns {*} Returns the entry value.
17384 */
17385function mapCacheGet(key) {
17386 return getMapData(this, key).get(key);
17387}
17388
17389/**
17390 * Checks if a map value for `key` exists.
17391 *
17392 * @private
17393 * @name has
17394 * @memberOf MapCache
17395 * @param {string} key The key of the entry to check.
17396 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
17397 */
17398function mapCacheHas(key) {
17399 return getMapData(this, key).has(key);
17400}
17401
17402/**
17403 * Sets the map `key` to `value`.
17404 *
17405 * @private
17406 * @name set
17407 * @memberOf MapCache
17408 * @param {string} key The key of the value to set.
17409 * @param {*} value The value to set.
17410 * @returns {Object} Returns the map cache instance.
17411 */
17412function mapCacheSet(key, value) {
17413 var data = getMapData(this, key),
17414 size = data.size;
17415
17416 data.set(key, value);
17417 this.size += data.size == size ? 0 : 1;
17418 return this;
17419}
17420
17421// Add methods to `MapCache`.
17422MapCache.prototype.clear = mapCacheClear;
17423MapCache.prototype['delete'] = mapCacheDelete;
17424MapCache.prototype.get = mapCacheGet;
17425MapCache.prototype.has = mapCacheHas;
17426MapCache.prototype.set = mapCacheSet;
17427
17428/**
17429 *
17430 * Creates an array cache object to store unique values.
17431 *
17432 * @private
17433 * @constructor
17434 * @param {Array} [values] The values to cache.
17435 */
17436function SetCache(values) {
17437 var index = -1,
17438 length = values == null ? 0 : values.length;
17439
17440 this.__data__ = new MapCache;
17441 while (++index < length) {
17442 this.add(values[index]);
17443 }
17444}
17445
17446/**
17447 * Adds `value` to the array cache.
17448 *
17449 * @private
17450 * @name add
17451 * @memberOf SetCache
17452 * @alias push
17453 * @param {*} value The value to cache.
17454 * @returns {Object} Returns the cache instance.
17455 */
17456function setCacheAdd(value) {
17457 this.__data__.set(value, HASH_UNDEFINED);
17458 return this;
17459}
17460
17461/**
17462 * Checks if `value` is in the array cache.
17463 *
17464 * @private
17465 * @name has
17466 * @memberOf SetCache
17467 * @param {*} value The value to search for.
17468 * @returns {number} Returns `true` if `value` is found, else `false`.
17469 */
17470function setCacheHas(value) {
17471 return this.__data__.has(value);
17472}
17473
17474// Add methods to `SetCache`.
17475SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
17476SetCache.prototype.has = setCacheHas;
17477
17478/**
17479 * Creates a stack cache object to store key-value pairs.
17480 *
17481 * @private
17482 * @constructor
17483 * @param {Array} [entries] The key-value pairs to cache.
17484 */
17485function Stack(entries) {
17486 var data = this.__data__ = new ListCache(entries);
17487 this.size = data.size;
17488}
17489
17490/**
17491 * Removes all key-value entries from the stack.
17492 *
17493 * @private
17494 * @name clear
17495 * @memberOf Stack
17496 */
17497function stackClear() {
17498 this.__data__ = new ListCache;
17499 this.size = 0;
17500}
17501
17502/**
17503 * Removes `key` and its value from the stack.
17504 *
17505 * @private
17506 * @name delete
17507 * @memberOf Stack
17508 * @param {string} key The key of the value to remove.
17509 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
17510 */
17511function stackDelete(key) {
17512 var data = this.__data__,
17513 result = data['delete'](key);
17514
17515 this.size = data.size;
17516 return result;
17517}
17518
17519/**
17520 * Gets the stack value for `key`.
17521 *
17522 * @private
17523 * @name get
17524 * @memberOf Stack
17525 * @param {string} key The key of the value to get.
17526 * @returns {*} Returns the entry value.
17527 */
17528function stackGet(key) {
17529 return this.__data__.get(key);
17530}
17531
17532/**
17533 * Checks if a stack value for `key` exists.
17534 *
17535 * @private
17536 * @name has
17537 * @memberOf Stack
17538 * @param {string} key The key of the entry to check.
17539 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
17540 */
17541function stackHas(key) {
17542 return this.__data__.has(key);
17543}
17544
17545/**
17546 * Sets the stack `key` to `value`.
17547 *
17548 * @private
17549 * @name set
17550 * @memberOf Stack
17551 * @param {string} key The key of the value to set.
17552 * @param {*} value The value to set.
17553 * @returns {Object} Returns the stack cache instance.
17554 */
17555function stackSet(key, value) {
17556 var data = this.__data__;
17557 if (data instanceof ListCache) {
17558 var pairs = data.__data__;
17559 if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
17560 pairs.push([key, value]);
17561 this.size = ++data.size;
17562 return this;
17563 }
17564 data = this.__data__ = new MapCache(pairs);
17565 }
17566 data.set(key, value);
17567 this.size = data.size;
17568 return this;
17569}
17570
17571// Add methods to `Stack`.
17572Stack.prototype.clear = stackClear;
17573Stack.prototype['delete'] = stackDelete;
17574Stack.prototype.get = stackGet;
17575Stack.prototype.has = stackHas;
17576Stack.prototype.set = stackSet;
17577
17578/**
17579 * Creates an array of the enumerable property names of the array-like `value`.
17580 *
17581 * @private
17582 * @param {*} value The value to query.
17583 * @param {boolean} inherited Specify returning inherited property names.
17584 * @returns {Array} Returns the array of property names.
17585 */
17586function arrayLikeKeys(value, inherited) {
17587 var isArr = isArray(value),
17588 isArg = !isArr && isArguments(value),
17589 isBuff = !isArr && !isArg && isBuffer(value),
17590 isType = !isArr && !isArg && !isBuff && isTypedArray(value),
17591 skipIndexes = isArr || isArg || isBuff || isType,
17592 result = skipIndexes ? baseTimes(value.length, String) : [],
17593 length = result.length;
17594
17595 for (var key in value) {
17596 if ((inherited || hasOwnProperty.call(value, key)) &&
17597 !(skipIndexes && (
17598 // Safari 9 has enumerable `arguments.length` in strict mode.
17599 key == 'length' ||
17600 // Node.js 0.10 has enumerable non-index properties on buffers.
17601 (isBuff && (key == 'offset' || key == 'parent')) ||
17602 // PhantomJS 2 has enumerable non-index properties on typed arrays.
17603 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
17604 // Skip index properties.
17605 isIndex(key, length)
17606 ))) {
17607 result.push(key);
17608 }
17609 }
17610 return result;
17611}
17612
17613/**
17614 * Gets the index at which the `key` is found in `array` of key-value pairs.
17615 *
17616 * @private
17617 * @param {Array} array The array to inspect.
17618 * @param {*} key The key to search for.
17619 * @returns {number} Returns the index of the matched value, else `-1`.
17620 */
17621function assocIndexOf(array, key) {
17622 var length = array.length;
17623 while (length--) {
17624 if (eq(array[length][0], key)) {
17625 return length;
17626 }
17627 }
17628 return -1;
17629}
17630
17631/**
17632 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
17633 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
17634 * symbols of `object`.
17635 *
17636 * @private
17637 * @param {Object} object The object to query.
17638 * @param {Function} keysFunc The function to get the keys of `object`.
17639 * @param {Function} symbolsFunc The function to get the symbols of `object`.
17640 * @returns {Array} Returns the array of property names and symbols.
17641 */
17642function baseGetAllKeys(object, keysFunc, symbolsFunc) {
17643 var result = keysFunc(object);
17644 return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
17645}
17646
17647/**
17648 * The base implementation of `getTag` without fallbacks for buggy environments.
17649 *
17650 * @private
17651 * @param {*} value The value to query.
17652 * @returns {string} Returns the `toStringTag`.
17653 */
17654function baseGetTag(value) {
17655 if (value == null) {
17656 return value === undefined ? undefinedTag : nullTag;
17657 }
17658 return (symToStringTag && symToStringTag in Object(value))
17659 ? getRawTag(value)
17660 : objectToString(value);
17661}
17662
17663/**
17664 * The base implementation of `_.isArguments`.
17665 *
17666 * @private
17667 * @param {*} value The value to check.
17668 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
17669 */
17670function baseIsArguments(value) {
17671 return isObjectLike(value) && baseGetTag(value) == argsTag;
17672}
17673
17674/**
17675 * The base implementation of `_.isEqual` which supports partial comparisons
17676 * and tracks traversed objects.
17677 *
17678 * @private
17679 * @param {*} value The value to compare.
17680 * @param {*} other The other value to compare.
17681 * @param {boolean} bitmask The bitmask flags.
17682 * 1 - Unordered comparison
17683 * 2 - Partial comparison
17684 * @param {Function} [customizer] The function to customize comparisons.
17685 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
17686 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
17687 */
17688function baseIsEqual(value, other, bitmask, customizer, stack) {
17689 if (value === other) {
17690 return true;
17691 }
17692 if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
17693 return value !== value && other !== other;
17694 }
17695 return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
17696}
17697
17698/**
17699 * A specialized version of `baseIsEqual` for arrays and objects which performs
17700 * deep comparisons and tracks traversed objects enabling objects with circular
17701 * references to be compared.
17702 *
17703 * @private
17704 * @param {Object} object The object to compare.
17705 * @param {Object} other The other object to compare.
17706 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
17707 * @param {Function} customizer The function to customize comparisons.
17708 * @param {Function} equalFunc The function to determine equivalents of values.
17709 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
17710 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
17711 */
17712function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
17713 var objIsArr = isArray(object),
17714 othIsArr = isArray(other),
17715 objTag = objIsArr ? arrayTag : getTag(object),
17716 othTag = othIsArr ? arrayTag : getTag(other);
17717
17718 objTag = objTag == argsTag ? objectTag : objTag;
17719 othTag = othTag == argsTag ? objectTag : othTag;
17720
17721 var objIsObj = objTag == objectTag,
17722 othIsObj = othTag == objectTag,
17723 isSameTag = objTag == othTag;
17724
17725 if (isSameTag && isBuffer(object)) {
17726 if (!isBuffer(other)) {
17727 return false;
17728 }
17729 objIsArr = true;
17730 objIsObj = false;
17731 }
17732 if (isSameTag && !objIsObj) {
17733 stack || (stack = new Stack);
17734 return (objIsArr || isTypedArray(object))
17735 ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
17736 : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
17737 }
17738 if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
17739 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
17740 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
17741
17742 if (objIsWrapped || othIsWrapped) {
17743 var objUnwrapped = objIsWrapped ? object.value() : object,
17744 othUnwrapped = othIsWrapped ? other.value() : other;
17745
17746 stack || (stack = new Stack);
17747 return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
17748 }
17749 }
17750 if (!isSameTag) {
17751 return false;
17752 }
17753 stack || (stack = new Stack);
17754 return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
17755}
17756
17757/**
17758 * The base implementation of `_.isNative` without bad shim checks.
17759 *
17760 * @private
17761 * @param {*} value The value to check.
17762 * @returns {boolean} Returns `true` if `value` is a native function,
17763 * else `false`.
17764 */
17765function baseIsNative(value) {
17766 if (!isObject(value) || isMasked(value)) {
17767 return false;
17768 }
17769 var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
17770 return pattern.test(toSource(value));
17771}
17772
17773/**
17774 * The base implementation of `_.isTypedArray` without Node.js optimizations.
17775 *
17776 * @private
17777 * @param {*} value The value to check.
17778 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
17779 */
17780function baseIsTypedArray(value) {
17781 return isObjectLike(value) &&
17782 isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
17783}
17784
17785/**
17786 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
17787 *
17788 * @private
17789 * @param {Object} object The object to query.
17790 * @returns {Array} Returns the array of property names.
17791 */
17792function baseKeys(object) {
17793 if (!isPrototype(object)) {
17794 return nativeKeys(object);
17795 }
17796 var result = [];
17797 for (var key in Object(object)) {
17798 if (hasOwnProperty.call(object, key) && key != 'constructor') {
17799 result.push(key);
17800 }
17801 }
17802 return result;
17803}
17804
17805/**
17806 * A specialized version of `baseIsEqualDeep` for arrays with support for
17807 * partial deep comparisons.
17808 *
17809 * @private
17810 * @param {Array} array The array to compare.
17811 * @param {Array} other The other array to compare.
17812 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
17813 * @param {Function} customizer The function to customize comparisons.
17814 * @param {Function} equalFunc The function to determine equivalents of values.
17815 * @param {Object} stack Tracks traversed `array` and `other` objects.
17816 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
17817 */
17818function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
17819 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
17820 arrLength = array.length,
17821 othLength = other.length;
17822
17823 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
17824 return false;
17825 }
17826 // Assume cyclic values are equal.
17827 var stacked = stack.get(array);
17828 if (stacked && stack.get(other)) {
17829 return stacked == other;
17830 }
17831 var index = -1,
17832 result = true,
17833 seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
17834
17835 stack.set(array, other);
17836 stack.set(other, array);
17837
17838 // Ignore non-index properties.
17839 while (++index < arrLength) {
17840 var arrValue = array[index],
17841 othValue = other[index];
17842
17843 if (customizer) {
17844 var compared = isPartial
17845 ? customizer(othValue, arrValue, index, other, array, stack)
17846 : customizer(arrValue, othValue, index, array, other, stack);
17847 }
17848 if (compared !== undefined) {
17849 if (compared) {
17850 continue;
17851 }
17852 result = false;
17853 break;
17854 }
17855 // Recursively compare arrays (susceptible to call stack limits).
17856 if (seen) {
17857 if (!arraySome(other, function(othValue, othIndex) {
17858 if (!cacheHas(seen, othIndex) &&
17859 (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
17860 return seen.push(othIndex);
17861 }
17862 })) {
17863 result = false;
17864 break;
17865 }
17866 } else if (!(
17867 arrValue === othValue ||
17868 equalFunc(arrValue, othValue, bitmask, customizer, stack)
17869 )) {
17870 result = false;
17871 break;
17872 }
17873 }
17874 stack['delete'](array);
17875 stack['delete'](other);
17876 return result;
17877}
17878
17879/**
17880 * A specialized version of `baseIsEqualDeep` for comparing objects of
17881 * the same `toStringTag`.
17882 *
17883 * **Note:** This function only supports comparing values with tags of
17884 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
17885 *
17886 * @private
17887 * @param {Object} object The object to compare.
17888 * @param {Object} other The other object to compare.
17889 * @param {string} tag The `toStringTag` of the objects to compare.
17890 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
17891 * @param {Function} customizer The function to customize comparisons.
17892 * @param {Function} equalFunc The function to determine equivalents of values.
17893 * @param {Object} stack Tracks traversed `object` and `other` objects.
17894 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
17895 */
17896function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
17897 switch (tag) {
17898 case dataViewTag:
17899 if ((object.byteLength != other.byteLength) ||
17900 (object.byteOffset != other.byteOffset)) {
17901 return false;
17902 }
17903 object = object.buffer;
17904 other = other.buffer;
17905
17906 case arrayBufferTag:
17907 if ((object.byteLength != other.byteLength) ||
17908 !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
17909 return false;
17910 }
17911 return true;
17912
17913 case boolTag:
17914 case dateTag:
17915 case numberTag:
17916 // Coerce booleans to `1` or `0` and dates to milliseconds.
17917 // Invalid dates are coerced to `NaN`.
17918 return eq(+object, +other);
17919
17920 case errorTag:
17921 return object.name == other.name && object.message == other.message;
17922
17923 case regexpTag:
17924 case stringTag:
17925 // Coerce regexes to strings and treat strings, primitives and objects,
17926 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
17927 // for more details.
17928 return object == (other + '');
17929
17930 case mapTag:
17931 var convert = mapToArray;
17932
17933 case setTag:
17934 var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
17935 convert || (convert = setToArray);
17936
17937 if (object.size != other.size && !isPartial) {
17938 return false;
17939 }
17940 // Assume cyclic values are equal.
17941 var stacked = stack.get(object);
17942 if (stacked) {
17943 return stacked == other;
17944 }
17945 bitmask |= COMPARE_UNORDERED_FLAG;
17946
17947 // Recursively compare objects (susceptible to call stack limits).
17948 stack.set(object, other);
17949 var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
17950 stack['delete'](object);
17951 return result;
17952
17953 case symbolTag:
17954 if (symbolValueOf) {
17955 return symbolValueOf.call(object) == symbolValueOf.call(other);
17956 }
17957 }
17958 return false;
17959}
17960
17961/**
17962 * A specialized version of `baseIsEqualDeep` for objects with support for
17963 * partial deep comparisons.
17964 *
17965 * @private
17966 * @param {Object} object The object to compare.
17967 * @param {Object} other The other object to compare.
17968 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
17969 * @param {Function} customizer The function to customize comparisons.
17970 * @param {Function} equalFunc The function to determine equivalents of values.
17971 * @param {Object} stack Tracks traversed `object` and `other` objects.
17972 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
17973 */
17974function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
17975 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
17976 objProps = getAllKeys(object),
17977 objLength = objProps.length,
17978 othProps = getAllKeys(other),
17979 othLength = othProps.length;
17980
17981 if (objLength != othLength && !isPartial) {
17982 return false;
17983 }
17984 var index = objLength;
17985 while (index--) {
17986 var key = objProps[index];
17987 if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
17988 return false;
17989 }
17990 }
17991 // Assume cyclic values are equal.
17992 var stacked = stack.get(object);
17993 if (stacked && stack.get(other)) {
17994 return stacked == other;
17995 }
17996 var result = true;
17997 stack.set(object, other);
17998 stack.set(other, object);
17999
18000 var skipCtor = isPartial;
18001 while (++index < objLength) {
18002 key = objProps[index];
18003 var objValue = object[key],
18004 othValue = other[key];
18005
18006 if (customizer) {
18007 var compared = isPartial
18008 ? customizer(othValue, objValue, key, other, object, stack)
18009 : customizer(objValue, othValue, key, object, other, stack);
18010 }
18011 // Recursively compare objects (susceptible to call stack limits).
18012 if (!(compared === undefined
18013 ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
18014 : compared
18015 )) {
18016 result = false;
18017 break;
18018 }
18019 skipCtor || (skipCtor = key == 'constructor');
18020 }
18021 if (result && !skipCtor) {
18022 var objCtor = object.constructor,
18023 othCtor = other.constructor;
18024
18025 // Non `Object` object instances with different constructors are not equal.
18026 if (objCtor != othCtor &&
18027 ('constructor' in object && 'constructor' in other) &&
18028 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
18029 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
18030 result = false;
18031 }
18032 }
18033 stack['delete'](object);
18034 stack['delete'](other);
18035 return result;
18036}
18037
18038/**
18039 * Creates an array of own enumerable property names and symbols of `object`.
18040 *
18041 * @private
18042 * @param {Object} object The object to query.
18043 * @returns {Array} Returns the array of property names and symbols.
18044 */
18045function getAllKeys(object) {
18046 return baseGetAllKeys(object, keys, getSymbols);
18047}
18048
18049/**
18050 * Gets the data for `map`.
18051 *
18052 * @private
18053 * @param {Object} map The map to query.
18054 * @param {string} key The reference key.
18055 * @returns {*} Returns the map data.
18056 */
18057function getMapData(map, key) {
18058 var data = map.__data__;
18059 return isKeyable(key)
18060 ? data[typeof key == 'string' ? 'string' : 'hash']
18061 : data.map;
18062}
18063
18064/**
18065 * Gets the native function at `key` of `object`.
18066 *
18067 * @private
18068 * @param {Object} object The object to query.
18069 * @param {string} key The key of the method to get.
18070 * @returns {*} Returns the function if it's native, else `undefined`.
18071 */
18072function getNative(object, key) {
18073 var value = getValue(object, key);
18074 return baseIsNative(value) ? value : undefined;
18075}
18076
18077/**
18078 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
18079 *
18080 * @private
18081 * @param {*} value The value to query.
18082 * @returns {string} Returns the raw `toStringTag`.
18083 */
18084function getRawTag(value) {
18085 var isOwn = hasOwnProperty.call(value, symToStringTag),
18086 tag = value[symToStringTag];
18087
18088 try {
18089 value[symToStringTag] = undefined;
18090 var unmasked = true;
18091 } catch (e) {}
18092
18093 var result = nativeObjectToString.call(value);
18094 if (unmasked) {
18095 if (isOwn) {
18096 value[symToStringTag] = tag;
18097 } else {
18098 delete value[symToStringTag];
18099 }
18100 }
18101 return result;
18102}
18103
18104/**
18105 * Creates an array of the own enumerable symbols of `object`.
18106 *
18107 * @private
18108 * @param {Object} object The object to query.
18109 * @returns {Array} Returns the array of symbols.
18110 */
18111var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
18112 if (object == null) {
18113 return [];
18114 }
18115 object = Object(object);
18116 return arrayFilter(nativeGetSymbols(object), function(symbol) {
18117 return propertyIsEnumerable.call(object, symbol);
18118 });
18119};
18120
18121/**
18122 * Gets the `toStringTag` of `value`.
18123 *
18124 * @private
18125 * @param {*} value The value to query.
18126 * @returns {string} Returns the `toStringTag`.
18127 */
18128var getTag = baseGetTag;
18129
18130// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
18131if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
18132 (Map && getTag(new Map) != mapTag) ||
18133 (Promise && getTag(Promise.resolve()) != promiseTag) ||
18134 (Set && getTag(new Set) != setTag) ||
18135 (WeakMap && getTag(new WeakMap) != weakMapTag)) {
18136 getTag = function(value) {
18137 var result = baseGetTag(value),
18138 Ctor = result == objectTag ? value.constructor : undefined,
18139 ctorString = Ctor ? toSource(Ctor) : '';
18140
18141 if (ctorString) {
18142 switch (ctorString) {
18143 case dataViewCtorString: return dataViewTag;
18144 case mapCtorString: return mapTag;
18145 case promiseCtorString: return promiseTag;
18146 case setCtorString: return setTag;
18147 case weakMapCtorString: return weakMapTag;
18148 }
18149 }
18150 return result;
18151 };
18152}
18153
18154/**
18155 * Checks if `value` is a valid array-like index.
18156 *
18157 * @private
18158 * @param {*} value The value to check.
18159 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
18160 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
18161 */
18162function isIndex(value, length) {
18163 length = length == null ? MAX_SAFE_INTEGER : length;
18164 return !!length &&
18165 (typeof value == 'number' || reIsUint.test(value)) &&
18166 (value > -1 && value % 1 == 0 && value < length);
18167}
18168
18169/**
18170 * Checks if `value` is suitable for use as unique object key.
18171 *
18172 * @private
18173 * @param {*} value The value to check.
18174 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
18175 */
18176function isKeyable(value) {
18177 var type = typeof value;
18178 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
18179 ? (value !== '__proto__')
18180 : (value === null);
18181}
18182
18183/**
18184 * Checks if `func` has its source masked.
18185 *
18186 * @private
18187 * @param {Function} func The function to check.
18188 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
18189 */
18190function isMasked(func) {
18191 return !!maskSrcKey && (maskSrcKey in func);
18192}
18193
18194/**
18195 * Checks if `value` is likely a prototype object.
18196 *
18197 * @private
18198 * @param {*} value The value to check.
18199 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
18200 */
18201function isPrototype(value) {
18202 var Ctor = value && value.constructor,
18203 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
18204
18205 return value === proto;
18206}
18207
18208/**
18209 * Converts `value` to a string using `Object.prototype.toString`.
18210 *
18211 * @private
18212 * @param {*} value The value to convert.
18213 * @returns {string} Returns the converted string.
18214 */
18215function objectToString(value) {
18216 return nativeObjectToString.call(value);
18217}
18218
18219/**
18220 * Converts `func` to its source code.
18221 *
18222 * @private
18223 * @param {Function} func The function to convert.
18224 * @returns {string} Returns the source code.
18225 */
18226function toSource(func) {
18227 if (func != null) {
18228 try {
18229 return funcToString.call(func);
18230 } catch (e) {}
18231 try {
18232 return (func + '');
18233 } catch (e) {}
18234 }
18235 return '';
18236}
18237
18238/**
18239 * Performs a
18240 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
18241 * comparison between two values to determine if they are equivalent.
18242 *
18243 * @static
18244 * @memberOf _
18245 * @since 4.0.0
18246 * @category Lang
18247 * @param {*} value The value to compare.
18248 * @param {*} other The other value to compare.
18249 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
18250 * @example
18251 *
18252 * var object = { 'a': 1 };
18253 * var other = { 'a': 1 };
18254 *
18255 * _.eq(object, object);
18256 * // => true
18257 *
18258 * _.eq(object, other);
18259 * // => false
18260 *
18261 * _.eq('a', 'a');
18262 * // => true
18263 *
18264 * _.eq('a', Object('a'));
18265 * // => false
18266 *
18267 * _.eq(NaN, NaN);
18268 * // => true
18269 */
18270function eq(value, other) {
18271 return value === other || (value !== value && other !== other);
18272}
18273
18274/**
18275 * Checks if `value` is likely an `arguments` object.
18276 *
18277 * @static
18278 * @memberOf _
18279 * @since 0.1.0
18280 * @category Lang
18281 * @param {*} value The value to check.
18282 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
18283 * else `false`.
18284 * @example
18285 *
18286 * _.isArguments(function() { return arguments; }());
18287 * // => true
18288 *
18289 * _.isArguments([1, 2, 3]);
18290 * // => false
18291 */
18292var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
18293 return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
18294 !propertyIsEnumerable.call(value, 'callee');
18295};
18296
18297/**
18298 * Checks if `value` is classified as an `Array` object.
18299 *
18300 * @static
18301 * @memberOf _
18302 * @since 0.1.0
18303 * @category Lang
18304 * @param {*} value The value to check.
18305 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
18306 * @example
18307 *
18308 * _.isArray([1, 2, 3]);
18309 * // => true
18310 *
18311 * _.isArray(document.body.children);
18312 * // => false
18313 *
18314 * _.isArray('abc');
18315 * // => false
18316 *
18317 * _.isArray(_.noop);
18318 * // => false
18319 */
18320var isArray = Array.isArray;
18321
18322/**
18323 * Checks if `value` is array-like. A value is considered array-like if it's
18324 * not a function and has a `value.length` that's an integer greater than or
18325 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
18326 *
18327 * @static
18328 * @memberOf _
18329 * @since 4.0.0
18330 * @category Lang
18331 * @param {*} value The value to check.
18332 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
18333 * @example
18334 *
18335 * _.isArrayLike([1, 2, 3]);
18336 * // => true
18337 *
18338 * _.isArrayLike(document.body.children);
18339 * // => true
18340 *
18341 * _.isArrayLike('abc');
18342 * // => true
18343 *
18344 * _.isArrayLike(_.noop);
18345 * // => false
18346 */
18347function isArrayLike(value) {
18348 return value != null && isLength(value.length) && !isFunction(value);
18349}
18350
18351/**
18352 * Checks if `value` is a buffer.
18353 *
18354 * @static
18355 * @memberOf _
18356 * @since 4.3.0
18357 * @category Lang
18358 * @param {*} value The value to check.
18359 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
18360 * @example
18361 *
18362 * _.isBuffer(new Buffer(2));
18363 * // => true
18364 *
18365 * _.isBuffer(new Uint8Array(2));
18366 * // => false
18367 */
18368var isBuffer = nativeIsBuffer || stubFalse;
18369
18370/**
18371 * Performs a deep comparison between two values to determine if they are
18372 * equivalent.
18373 *
18374 * **Note:** This method supports comparing arrays, array buffers, booleans,
18375 * date objects, error objects, maps, numbers, `Object` objects, regexes,
18376 * sets, strings, symbols, and typed arrays. `Object` objects are compared
18377 * by their own, not inherited, enumerable properties. Functions and DOM
18378 * nodes are compared by strict equality, i.e. `===`.
18379 *
18380 * @static
18381 * @memberOf _
18382 * @since 0.1.0
18383 * @category Lang
18384 * @param {*} value The value to compare.
18385 * @param {*} other The other value to compare.
18386 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
18387 * @example
18388 *
18389 * var object = { 'a': 1 };
18390 * var other = { 'a': 1 };
18391 *
18392 * _.isEqual(object, other);
18393 * // => true
18394 *
18395 * object === other;
18396 * // => false
18397 */
18398function isEqual(value, other) {
18399 return baseIsEqual(value, other);
18400}
18401
18402/**
18403 * Checks if `value` is classified as a `Function` object.
18404 *
18405 * @static
18406 * @memberOf _
18407 * @since 0.1.0
18408 * @category Lang
18409 * @param {*} value The value to check.
18410 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
18411 * @example
18412 *
18413 * _.isFunction(_);
18414 * // => true
18415 *
18416 * _.isFunction(/abc/);
18417 * // => false
18418 */
18419function isFunction(value) {
18420 if (!isObject(value)) {
18421 return false;
18422 }
18423 // The use of `Object#toString` avoids issues with the `typeof` operator
18424 // in Safari 9 which returns 'object' for typed arrays and other constructors.
18425 var tag = baseGetTag(value);
18426 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
18427}
18428
18429/**
18430 * Checks if `value` is a valid array-like length.
18431 *
18432 * **Note:** This method is loosely based on
18433 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
18434 *
18435 * @static
18436 * @memberOf _
18437 * @since 4.0.0
18438 * @category Lang
18439 * @param {*} value The value to check.
18440 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
18441 * @example
18442 *
18443 * _.isLength(3);
18444 * // => true
18445 *
18446 * _.isLength(Number.MIN_VALUE);
18447 * // => false
18448 *
18449 * _.isLength(Infinity);
18450 * // => false
18451 *
18452 * _.isLength('3');
18453 * // => false
18454 */
18455function isLength(value) {
18456 return typeof value == 'number' &&
18457 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
18458}
18459
18460/**
18461 * Checks if `value` is the
18462 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
18463 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
18464 *
18465 * @static
18466 * @memberOf _
18467 * @since 0.1.0
18468 * @category Lang
18469 * @param {*} value The value to check.
18470 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
18471 * @example
18472 *
18473 * _.isObject({});
18474 * // => true
18475 *
18476 * _.isObject([1, 2, 3]);
18477 * // => true
18478 *
18479 * _.isObject(_.noop);
18480 * // => true
18481 *
18482 * _.isObject(null);
18483 * // => false
18484 */
18485function isObject(value) {
18486 var type = typeof value;
18487 return value != null && (type == 'object' || type == 'function');
18488}
18489
18490/**
18491 * Checks if `value` is object-like. A value is object-like if it's not `null`
18492 * and has a `typeof` result of "object".
18493 *
18494 * @static
18495 * @memberOf _
18496 * @since 4.0.0
18497 * @category Lang
18498 * @param {*} value The value to check.
18499 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
18500 * @example
18501 *
18502 * _.isObjectLike({});
18503 * // => true
18504 *
18505 * _.isObjectLike([1, 2, 3]);
18506 * // => true
18507 *
18508 * _.isObjectLike(_.noop);
18509 * // => false
18510 *
18511 * _.isObjectLike(null);
18512 * // => false
18513 */
18514function isObjectLike(value) {
18515 return value != null && typeof value == 'object';
18516}
18517
18518/**
18519 * Checks if `value` is classified as a typed array.
18520 *
18521 * @static
18522 * @memberOf _
18523 * @since 3.0.0
18524 * @category Lang
18525 * @param {*} value The value to check.
18526 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
18527 * @example
18528 *
18529 * _.isTypedArray(new Uint8Array);
18530 * // => true
18531 *
18532 * _.isTypedArray([]);
18533 * // => false
18534 */
18535var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
18536
18537/**
18538 * Creates an array of the own enumerable property names of `object`.
18539 *
18540 * **Note:** Non-object values are coerced to objects. See the
18541 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
18542 * for more details.
18543 *
18544 * @static
18545 * @since 0.1.0
18546 * @memberOf _
18547 * @category Object
18548 * @param {Object} object The object to query.
18549 * @returns {Array} Returns the array of property names.
18550 * @example
18551 *
18552 * function Foo() {
18553 * this.a = 1;
18554 * this.b = 2;
18555 * }
18556 *
18557 * Foo.prototype.c = 3;
18558 *
18559 * _.keys(new Foo);
18560 * // => ['a', 'b'] (iteration order is not guaranteed)
18561 *
18562 * _.keys('hi');
18563 * // => ['0', '1']
18564 */
18565function keys(object) {
18566 return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
18567}
18568
18569/**
18570 * This method returns a new empty array.
18571 *
18572 * @static
18573 * @memberOf _
18574 * @since 4.13.0
18575 * @category Util
18576 * @returns {Array} Returns the new empty array.
18577 * @example
18578 *
18579 * var arrays = _.times(2, _.stubArray);
18580 *
18581 * console.log(arrays);
18582 * // => [[], []]
18583 *
18584 * console.log(arrays[0] === arrays[1]);
18585 * // => false
18586 */
18587function stubArray() {
18588 return [];
18589}
18590
18591/**
18592 * This method returns `false`.
18593 *
18594 * @static
18595 * @memberOf _
18596 * @since 4.13.0
18597 * @category Util
18598 * @returns {boolean} Returns `false`.
18599 * @example
18600 *
18601 * _.times(2, _.stubFalse);
18602 * // => [false, false]
18603 */
18604function stubFalse() {
18605 return false;
18606}
18607
18608module.exports = isEqual;
18609});
18610
18611const { debug: debug$1, setDebugNamespace } = debug_1;
18612
18613
18614
18615
18616const {
18617 headers: headerUtils,
18618 getPath,
18619 getQuery,
18620 normalizeUrl: normalizeUrl$1
18621} = requestUtils;
18622
18623
18624const debuggableUrlFunc = func => url => {
18625 debug$1('Actual url:', url);
18626 return func(url);
18627};
18628
18629const stringMatchers = {
18630 begin: targetString =>
18631 debuggableUrlFunc(url => url.indexOf(targetString) === 0),
18632 end: targetString =>
18633 debuggableUrlFunc(url => url.substr(-targetString.length) === targetString),
18634 glob: targetString => {
18635 const urlRX = globToRegexp(targetString);
18636 return debuggableUrlFunc(url => urlRX.test(url));
18637 },
18638 express: targetString => {
18639 const urlRX = pathToRegexp_1(targetString);
18640 return debuggableUrlFunc(url => urlRX.test(getPath(url)));
18641 },
18642 path: targetString => debuggableUrlFunc(url => getPath(url) === targetString)
18643};
18644
18645const getHeaderMatcher = ({ headers: expectedHeaders }) => {
18646 debug$1('Generating header matcher');
18647 if (!expectedHeaders) {
18648 debug$1(' No header expectations defined - skipping');
18649 return;
18650 }
18651 const expectation = headerUtils.toLowerCase(expectedHeaders);
18652 debug$1(' Expected headers:', expectation);
18653 return (url, { headers = {} }) => {
18654 debug$1('Attempting to match headers');
18655 const lowerCaseHeaders = headerUtils.toLowerCase(
18656 headerUtils.normalize(headers)
18657 );
18658 debug$1(' Expected headers:', expectation);
18659 debug$1(' Actual headers:', lowerCaseHeaders);
18660 return Object.keys(expectation).every(headerName =>
18661 headerUtils.equal(lowerCaseHeaders[headerName], expectation[headerName])
18662 );
18663 };
18664};
18665
18666const getMethodMatcher = ({ method: expectedMethod }) => {
18667 debug$1('Generating method matcher');
18668 if (!expectedMethod) {
18669 debug$1(' No method expectations defined - skipping');
18670 return;
18671 }
18672 debug$1(' Expected method:', expectedMethod);
18673 return (url, { method }) => {
18674 debug$1('Attempting to match method');
18675 const actualMethod = method ? method.toLowerCase() : 'get';
18676 debug$1(' Expected method:', expectedMethod);
18677 debug$1(' Actual method:', actualMethod);
18678 return expectedMethod === actualMethod;
18679 };
18680};
18681
18682const getQueryStringMatcher = ({ query: expectedQuery }) => {
18683 debug$1('Generating query parameters matcher');
18684 if (!expectedQuery) {
18685 debug$1(' No query parameters expectations defined - skipping');
18686 return;
18687 }
18688 debug$1(' Expected query parameters:', expectedQuery);
18689 const keys = Object.keys(expectedQuery);
18690 return url => {
18691 debug$1('Attempting to match query parameters');
18692 const query = querystring.parse(getQuery(url));
18693 debug$1(' Expected query parameters:', expectedQuery);
18694 debug$1(' Actual query parameters:', query);
18695 return keys.every(key => query[key] === expectedQuery[key]);
18696 };
18697};
18698
18699const getParamsMatcher = ({ params: expectedParams, url: matcherUrl }) => {
18700 debug$1('Generating path parameters matcher');
18701 if (!expectedParams) {
18702 debug$1(' No path parameters expectations defined - skipping');
18703 return;
18704 }
18705 if (!/express:/.test(matcherUrl)) {
18706 throw new Error(
18707 'fetch-mock: matching on params is only possible when using an express: matcher'
18708 );
18709 }
18710 debug$1(' Expected path parameters:', expectedParams);
18711 const expectedKeys = Object.keys(expectedParams);
18712 const keys = [];
18713 const re = pathToRegexp_1(matcherUrl.replace(/^express:/, ''), keys);
18714 return url => {
18715 debug$1('Attempting to match path parameters');
18716 const vals = re.exec(getPath(url)) || [];
18717 vals.shift();
18718 const params = keys.reduce(
18719 (map, { name }, i) =>
18720 vals[i] ? Object.assign(map, { [name]: vals[i] }) : map,
18721 {}
18722 );
18723 debug$1(' Expected path parameters:', expectedParams);
18724 debug$1(' Actual path parameters:', params);
18725 return expectedKeys.every(key => params[key] === expectedParams[key]);
18726 };
18727};
18728
18729const getBodyMatcher = (route, fetchMock) => {
18730 const matchPartialBody = fetchMock.getOption('matchPartialBody', route);
18731 const { body: expectedBody } = route;
18732
18733 debug$1('Generating body matcher');
18734 return (url, { body, method = 'get' }) => {
18735 debug$1('Attempting to match body');
18736 if (method.toLowerCase() === 'get') {
18737 debug$1(' GET request - skip matching body');
18738 // GET requests don’t send a body so the body matcher should be ignored for them
18739 return true;
18740 }
18741
18742 let sentBody;
18743
18744 try {
18745 debug$1(' Parsing request body as JSON');
18746 sentBody = JSON.parse(body);
18747 } catch (err) {
18748 debug$1(' Failed to parse request body as JSON', err);
18749 }
18750 debug$1('Expected body:', expectedBody);
18751 debug$1('Actual body:', sentBody);
18752 if (matchPartialBody) {
18753 debug$1('matchPartialBody is true - checking for partial match only');
18754 }
18755
18756 return (
18757 sentBody &&
18758 (matchPartialBody
18759 ? isSubset_1(sentBody, expectedBody)
18760 : lodash_isequal(sentBody, expectedBody))
18761 );
18762 };
18763};
18764
18765const getFullUrlMatcher = (route, matcherUrl, query) => {
18766 // if none of the special syntaxes apply, it's just a simple string match
18767 // but we have to be careful to normalize the url we check and the name
18768 // of the route to allow for e.g. http://it.at.there being indistinguishable
18769 // from http://it.at.there/ once we start generating Request/Url objects
18770 debug$1(' Matching using full url', matcherUrl);
18771 const expectedUrl = normalizeUrl$1(matcherUrl);
18772 debug$1(' Normalised url to:', matcherUrl);
18773 if (route.identifier === matcherUrl) {
18774 debug$1(' Updating route identifier to match normalized url:', matcherUrl);
18775 route.identifier = expectedUrl;
18776 }
18777
18778 return matcherUrl => {
18779 debug$1('Expected url:', expectedUrl);
18780 debug$1('Actual url:', matcherUrl);
18781 if (query && expectedUrl.indexOf('?')) {
18782 debug$1('Ignoring query string when matching url');
18783 return matcherUrl.indexOf(expectedUrl) === 0;
18784 }
18785 return normalizeUrl$1(matcherUrl) === expectedUrl;
18786 };
18787};
18788
18789const getFunctionMatcher = ({ functionMatcher }) => {
18790 debug$1('Detected user defined function matcher', functionMatcher);
18791 return (...args) => {
18792 debug$1('Calling function matcher with arguments', args);
18793 return functionMatcher(...args);
18794 };
18795};
18796
18797const getUrlMatcher = route => {
18798 debug$1('Generating url matcher');
18799 const { url: matcherUrl, query } = route;
18800
18801 if (matcherUrl === '*') {
18802 debug$1(' Using universal * rule to match any url');
18803 return () => true;
18804 }
18805
18806 if (matcherUrl instanceof RegExp) {
18807 debug$1(' Using regular expression to match url:', matcherUrl);
18808 return url => matcherUrl.test(url);
18809 }
18810
18811 if (matcherUrl.href) {
18812 debug$1(` Using URL object to match url`, matcherUrl);
18813 return getFullUrlMatcher(route, matcherUrl.href, query);
18814 }
18815
18816 for (const shorthand in stringMatchers) {
18817 if (matcherUrl.indexOf(shorthand + ':') === 0) {
18818 debug$1(` Using ${shorthand}: pattern to match url`, matcherUrl);
18819 const urlFragment = matcherUrl.replace(new RegExp(`^${shorthand}:`), '');
18820 return stringMatchers[shorthand](urlFragment);
18821 }
18822 }
18823
18824 return getFullUrlMatcher(route, matcherUrl, query);
18825};
18826
18827var generateMatcher = (route, fetchMock) => {
18828 setDebugNamespace('generateMatcher()');
18829 debug$1('Compiling matcher for route');
18830 const matchers = [
18831 route.query && getQueryStringMatcher(route),
18832 route.method && getMethodMatcher(route),
18833 route.headers && getHeaderMatcher(route),
18834 route.params && getParamsMatcher(route),
18835 route.body && getBodyMatcher(route, fetchMock),
18836 route.functionMatcher && getFunctionMatcher(route),
18837 route.url && getUrlMatcher(route)
18838 ].filter(matcher => !!matcher);
18839
18840 debug$1('Compiled matcher for route');
18841 setDebugNamespace();
18842 return (url, options = {}, request) =>
18843 matchers.every(matcher => matcher(url, options, request));
18844};
18845
18846const { getDebug } = debug_1;
18847
18848
18849const matcherProperties = [
18850 'query',
18851 'method',
18852 'headers',
18853 'params',
18854 'body',
18855 'functionMatcher',
18856 'url'
18857];
18858
18859const isUrlMatcher = matcher =>
18860 matcher instanceof RegExp ||
18861 typeof matcher === 'string' ||
18862 (typeof matcher === 'object' && 'href' in matcher);
18863
18864const isFunctionMatcher = matcher => typeof matcher === 'function';
18865
18866const argsToRoute = args => {
18867 const [matcher, response, options = {}] = args;
18868
18869 const routeConfig = {};
18870
18871 if (isUrlMatcher(matcher) || isFunctionMatcher(matcher)) {
18872 routeConfig.matcher = matcher;
18873 } else {
18874 Object.assign(routeConfig, matcher);
18875 }
18876
18877 if (response) {
18878 routeConfig.response = response;
18879 }
18880
18881 Object.assign(routeConfig, options);
18882 return routeConfig;
18883};
18884
18885const sanitizeRoute = route => {
18886 const debug = getDebug('sanitizeRoute()');
18887 debug('Sanitizing route properties');
18888 route = Object.assign({}, route);
18889
18890 if (route.method) {
18891 debug(`Converting method ${route.method} to lower case`);
18892 route.method = route.method.toLowerCase();
18893 }
18894 if (isUrlMatcher(route.matcher)) {
18895 debug('Mock uses a url matcher', route.matcher);
18896 route.url = route.matcher;
18897 delete route.matcher;
18898 }
18899
18900 route.functionMatcher = route.matcher || route.functionMatcher;
18901
18902 debug('Setting route.identifier...');
18903 debug(` route.name is ${route.name}`);
18904 debug(` route.url is ${route.url}`);
18905 debug(` route.functionMatcher is ${route.functionMatcher}`);
18906 route.identifier = route.name || route.url || route.functionMatcher;
18907 debug(` -> route.identifier set to ${route.identifier}`);
18908 return route;
18909};
18910
18911const validateRoute = route => {
18912 if (!('response' in route)) {
18913 throw new Error('fetch-mock: Each route must define a response');
18914 }
18915
18916 if (!matcherProperties.some(matcherType => matcherType in route)) {
18917 throw new Error(
18918 "fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'"
18919 );
18920 }
18921};
18922
18923const limit = route => {
18924 const debug = getDebug('limit()');
18925 debug('Limiting number of requests to handle by route');
18926 if (!route.repeat) {
18927 debug(
18928 ' No `repeat` value set on route. Will match any number of requests'
18929 );
18930 return;
18931 }
18932
18933 debug(` Route set to repeat ${route.repeat} times`);
18934 const matcher = route.matcher;
18935 let timesLeft = route.repeat;
18936 route.matcher = (url, options) => {
18937 const match = timesLeft && matcher(url, options);
18938 if (match) {
18939 timesLeft--;
18940 return true;
18941 }
18942 };
18943 route.reset = () => (timesLeft = route.repeat);
18944};
18945
18946const delayResponse = route => {
18947 const debug = getDebug('delayResponse()');
18948 debug(`Applying response delay settings`);
18949 const { delay } = route;
18950 if (delay) {
18951 debug(` Wrapping response in delay of ${delay} miliseconds`);
18952 const response = route.response;
18953 route.response = () => {
18954 debug(`Delaying response by ${delay} miliseconds`);
18955 return new Promise(res => setTimeout(() => res(response), delay));
18956 };
18957 } else {
18958 debug(
18959 ` No delay set on route. Will respond 'immediately' (but asynchronously)`
18960 );
18961 }
18962};
18963
18964const compileRoute = function(args) {
18965 const debug = getDebug('compileRoute()');
18966 debug('Compiling route');
18967 const route = sanitizeRoute(argsToRoute(args));
18968 validateRoute(route);
18969 route.matcher = generateMatcher(route, this);
18970 limit(route);
18971 delayResponse(route);
18972 return route;
18973};
18974
18975var compileRoute_1 = {
18976 compileRoute,
18977 sanitizeRoute
18978};
18979
18980const { debug: debug$2, setDebugPhase } = debug_1;
18981const { compileRoute: compileRoute$1 } = compileRoute_1;
18982const FetchMock = {};
18983
18984FetchMock.mock = function(...args) {
18985 setDebugPhase('setup');
18986 if (args.length) {
18987 this.addRoute(args);
18988 }
18989
18990 return this._mock();
18991};
18992
18993FetchMock.addRoute = function(uncompiledRoute) {
18994 debug$2('Adding route', uncompiledRoute);
18995 const route = this.compileRoute(uncompiledRoute);
18996 const clashes = this.routes.filter(
18997 ({ identifier, method }) =>
18998 identifier === route.identifier &&
18999 (!method || !route.method || method === route.method)
19000 );
19001
19002 if (this.getOption('overwriteRoutes', route) === false || !clashes.length) {
19003 this._uncompiledRoutes.push(uncompiledRoute);
19004 return this.routes.push(route);
19005 }
19006
19007 if (this.getOption('overwriteRoutes', route) === true) {
19008 clashes.forEach(clash => {
19009 const index = this.routes.indexOf(clash);
19010 this._uncompiledRoutes.splice(index, 1, uncompiledRoute);
19011 this.routes.splice(index, 1, route);
19012 });
19013 return this.routes;
19014 }
19015
19016 if (clashes.length) {
19017 throw new Error(
19018 'fetch-mock: Adding route with same name or matcher as existing route. See `overwriteRoutes` option.'
19019 );
19020 }
19021
19022 this._uncompiledRoutes.push(uncompiledRoute);
19023 this.routes.push(route);
19024};
19025
19026FetchMock._mock = function() {
19027 if (!this.isSandbox) {
19028 // Do this here rather than in the constructor to ensure it's scoped to the test
19029 this.realFetch = this.realFetch || this.global.fetch;
19030 this.global.fetch = this.fetchHandler;
19031 }
19032 setDebugPhase();
19033 return this;
19034};
19035
19036FetchMock.catch = function(response) {
19037 if (this.fallbackResponse) {
19038 console.warn(
19039 'calling fetchMock.catch() twice - are you sure you want to overwrite the previous fallback response'
19040 ); // eslint-disable-line
19041 }
19042 this.fallbackResponse = response || 'ok';
19043 return this._mock();
19044};
19045
19046FetchMock.spy = function() {
19047 this._mock();
19048 return this.catch(this.getNativeFetch());
19049};
19050
19051FetchMock.compileRoute = compileRoute$1;
19052
19053const defineShorthand = (methodName, underlyingMethod, shorthandOptions) => {
19054 FetchMock[methodName] = function(matcher, response, options) {
19055 return this[underlyingMethod](
19056 matcher,
19057 response,
19058 Object.assign(options || {}, shorthandOptions)
19059 );
19060 };
19061};
19062defineShorthand('once', 'mock', { repeat: 1 });
19063
19064['get', 'post', 'put', 'delete', 'head', 'patch'].forEach(method => {
19065 defineShorthand(method, 'mock', { method });
19066 defineShorthand(`${method}Once`, 'once', { method });
19067});
19068
19069FetchMock.resetBehavior = function() {
19070 if (this.realFetch) {
19071 this.global.fetch = this.realFetch;
19072 this.realFetch = undefined;
19073 }
19074 this.fallbackResponse = undefined;
19075 this.routes = [];
19076 this._uncompiledRoutes = [];
19077 return this;
19078};
19079
19080FetchMock.resetHistory = function() {
19081 this._calls = [];
19082 this._holdingPromises = [];
19083 this.routes.forEach(route => route.reset && route.reset());
19084 return this;
19085};
19086
19087FetchMock.restore = FetchMock.reset = function() {
19088 this.resetBehavior();
19089 this.resetHistory();
19090 return this;
19091};
19092
19093var setUpAndTearDown = FetchMock;
19094
19095const { getDebug: getDebug$1 } = debug_1;
19096const responseConfigProps = [
19097 'body',
19098 'headers',
19099 'throws',
19100 'status',
19101 'redirectUrl'
19102];
19103
19104class ResponseBuilder {
19105 constructor(options) {
19106 this.debug = getDebug$1('ResponseBuilder()');
19107 this.debug('Response builder created with options', options);
19108 Object.assign(this, options);
19109 }
19110
19111 exec() {
19112 this.debug('building response');
19113 this.normalizeResponseConfig();
19114 this.constructFetchOpts();
19115 this.constructResponseBody();
19116 return this.buildObservableResponse(
19117 new this.fetchMock.config.Response(this.body, this.options)
19118 );
19119 }
19120
19121 sendAsObject() {
19122 if (responseConfigProps.some(prop => this.responseConfig[prop])) {
19123 if (
19124 Object.keys(this.responseConfig).every(key =>
19125 responseConfigProps.includes(key)
19126 )
19127 ) {
19128 return false;
19129 } else {
19130 return true;
19131 }
19132 } else {
19133 return true;
19134 }
19135 }
19136
19137 normalizeResponseConfig() {
19138 // If the response config looks like a status, start to generate a simple response
19139 if (typeof this.responseConfig === 'number') {
19140 this.debug('building response using status', this.responseConfig);
19141 this.responseConfig = {
19142 status: this.responseConfig
19143 };
19144 // If the response config is not an object, or is an object that doesn't use
19145 // any reserved properties, assume it is meant to be the body of the response
19146 } else if (typeof this.responseConfig === 'string' || this.sendAsObject()) {
19147 this.debug('building text response from', this.responseConfig);
19148 this.responseConfig = {
19149 body: this.responseConfig
19150 };
19151 }
19152 }
19153
19154 validateStatus(status) {
19155 if (!status) {
19156 this.debug('No status provided. Defaulting to 200');
19157 return 200;
19158 }
19159
19160 if (
19161 (typeof status === 'number' &&
19162 parseInt(status, 10) !== status &&
19163 status >= 200) ||
19164 status < 600
19165 ) {
19166 this.debug('Valid status provided', status);
19167 return status;
19168 }
19169
19170 throw new TypeError(`fetch-mock: Invalid status ${status} passed on response object.
19171To respond with a JSON object that has status as a property assign the object to body
19172e.g. {"body": {"status: "registered"}}`);
19173 }
19174
19175 constructFetchOpts() {
19176 this.options = this.responseConfig.options || {};
19177 this.options.url = this.responseConfig.redirectUrl || this.url;
19178 this.options.status = this.validateStatus(this.responseConfig.status);
19179 this.options.statusText = this.fetchMock.statusTextMap[
19180 '' + this.options.status
19181 ];
19182 // Set up response headers. The empty object is to cope with
19183 // new Headers(undefined) throwing in Chrome
19184 // https://code.google.com/p/chromium/issues/detail?id=335871
19185 this.options.headers = new this.fetchMock.config.Headers(
19186 this.responseConfig.headers || {}
19187 );
19188 }
19189
19190 getOption(name) {
19191 return this.fetchMock.getOption(name, this.route);
19192 }
19193
19194 convertToJson() {
19195 // convert to json if we need to
19196 if (
19197 this.getOption('sendAsJson') &&
19198 this.responseConfig.body != null && //eslint-disable-line
19199 typeof this.body === 'object'
19200 ) {
19201 this.debug('Stringifying JSON response body');
19202 this.body = JSON.stringify(this.body);
19203 if (!this.options.headers.has('Content-Type')) {
19204 this.options.headers.set('Content-Type', 'application/json');
19205 }
19206 }
19207 }
19208
19209 setContentLength() {
19210 // add a Content-Length header if we need to
19211 if (
19212 this.getOption('includeContentLength') &&
19213 typeof this.body === 'string' &&
19214 !this.options.headers.has('Content-Length')
19215 ) {
19216 this.debug('Setting content-length header:', this.body.length.toString());
19217 this.options.headers.set('Content-Length', this.body.length.toString());
19218 }
19219 }
19220
19221 constructResponseBody() {
19222 // start to construct the body
19223 this.body = this.responseConfig.body;
19224 this.convertToJson();
19225 this.setContentLength();
19226
19227 // On the server we need to manually construct the readable stream for the
19228 // Response object (on the client this done automatically)
19229 if (this.Stream) {
19230 this.debug('Creating response stream');
19231 const stream = new this.Stream.Readable();
19232 if (this.body != null) { //eslint-disable-line
19233 stream.push(this.body, 'utf-8');
19234 }
19235 stream.push(null);
19236 this.body = stream;
19237 }
19238 this.body = this.body;
19239 }
19240
19241 buildObservableResponse(response) {
19242 const fetchMock = this.fetchMock;
19243
19244 // Using a proxy means we can set properties that may not be writable on
19245 // the original Response. It also means we can track the resolution of
19246 // promises returned by res.json(), res.text() etc
19247 this.debug('Wrappipng Response in ES proxy for observability');
19248 return new Proxy(response, {
19249 get: (originalResponse, name) => {
19250 if (this.responseConfig.redirectUrl) {
19251 if (name === 'url') {
19252 this.debug(
19253 'Retrieving redirect url',
19254 this.responseConfig.redirectUrl
19255 );
19256 return this.responseConfig.redirectUrl;
19257 }
19258
19259 if (name === 'redirected') {
19260 this.debug('Retrieving redirected status', true);
19261 return true;
19262 }
19263 }
19264
19265 if (typeof originalResponse[name] === 'function') {
19266 this.debug('Wrapping body promises in ES proxies for observability');
19267 return new Proxy(originalResponse[name], {
19268 apply: (func, thisArg, args) => {
19269 this.debug(`Calling res.${name}`);
19270 const result = func.apply(response, args);
19271 if (result.then) {
19272 fetchMock._holdingPromises.push(result.catch(() => null));
19273 }
19274 return result;
19275 }
19276 });
19277 }
19278
19279 return originalResponse[name];
19280 }
19281 });
19282 }
19283}
19284
19285var responseBuilder = options => new ResponseBuilder(options).exec();
19286
19287const { debug: debug$3, setDebugPhase: setDebugPhase$1, getDebug: getDebug$2 } = debug_1;
19288
19289
19290const FetchMock$1 = {};
19291
19292// see https://heycam.github.io/webidl/#aborterror for the standardised interface
19293// Note that this differs slightly from node-fetch
19294class AbortError$1 extends Error {
19295 constructor() {
19296 super(...arguments);
19297 this.name = 'AbortError';
19298 this.message = 'The operation was aborted.';
19299
19300 // Do not include this class in the stacktrace
19301 if (Error.captureStackTrace) {
19302 Error.captureStackTrace(this, this.constructor);
19303 }
19304 }
19305}
19306
19307const resolve = async (
19308 { response, responseIsFetch = false },
19309 url,
19310 options,
19311 request
19312) => {
19313 const debug = getDebug$2('resolve()');
19314 debug('Recursively resolving function and promise responses');
19315 // We want to allow things like
19316 // - function returning a Promise for a response
19317 // - delaying (using a timeout Promise) a function's execution to generate
19318 // a response
19319 // Because of this we can't safely check for function before Promisey-ness,
19320 // or vice versa. So to keep it DRY, and flexible, we keep trying until we
19321 // have something that looks like neither Promise nor function
19322 while (true) {
19323 if (typeof response === 'function') {
19324 debug(' Response is a function');
19325 // in the case of falling back to the network we need to make sure we're using
19326 // the original Request instance, not our normalised url + options
19327 if (responseIsFetch) {
19328 if (request) {
19329 debug(' -> Calling fetch with Request instance');
19330 return response(request);
19331 }
19332 debug(' -> Calling fetch with url and options');
19333 return response(url, options);
19334 } else {
19335 debug(' -> Calling response function');
19336 response = response(url, options, request);
19337 }
19338 } else if (typeof response.then === 'function') {
19339 debug(' Response is a promise');
19340 debug(' -> Resolving promise');
19341 response = await response;
19342 } else {
19343 debug(' Response is not a function or a promise');
19344 debug(' -> Exiting response resolution recursion');
19345 return response;
19346 }
19347 }
19348};
19349
19350FetchMock$1.fetchHandler = function(url, options, request) {
19351 setDebugPhase$1('handle');
19352 const debug = getDebug$2('fetchHandler()');
19353 debug('fetch called with:', url, options);
19354 const normalizedRequest = requestUtils.normalizeRequest(
19355 url,
19356 options,
19357 this.config.Request
19358 );
19359
19360 ({ url, options, request } = normalizedRequest);
19361
19362 const { signal } = normalizedRequest;
19363
19364 debug('Request normalised');
19365 debug(' url', url);
19366 debug(' options', options);
19367 debug(' request', request);
19368 debug(' signal', signal);
19369
19370 if (request && this.routes.some(({ body }) => !!body)) {
19371 debug(
19372 'Need to wait for Body to be streamed before calling router: switching to async mode'
19373 );
19374 return this._asyncFetchHandler(url, options, request, signal);
19375 }
19376 return this._fetchHandler(url, options, request, signal);
19377};
19378
19379FetchMock$1._asyncFetchHandler = async function(url, options, request, signal) {
19380 options.body = await options.body;
19381 return this._fetchHandler(url, options, request, signal);
19382};
19383
19384FetchMock$1._fetchHandler = function(url, options, request, signal) {
19385 const route = this.executeRouter(url, options, request);
19386
19387 // this is used to power the .flush() method
19388 let done;
19389 this._holdingPromises.push(new this.config.Promise(res => (done = res)));
19390
19391 // wrapped in this promise to make sure we respect custom Promise
19392 // constructors defined by the user
19393 return new this.config.Promise((res, rej) => {
19394 if (signal) {
19395 debug$3('signal exists - enabling fetch abort');
19396 const abort = () => {
19397 debug$3('aborting fetch');
19398 // note that DOMException is not available in node.js; even node-fetch uses a custom error class: https://github.com/bitinn/node-fetch/blob/master/src/abort-error.js
19399 rej(
19400 typeof DOMException !== 'undefined'
19401 ? new DOMException('The operation was aborted.', 'AbortError')
19402 : new AbortError$1()
19403 );
19404 done();
19405 };
19406 if (signal.aborted) {
19407 debug$3('signal is already aborted - aborting the fetch');
19408 abort();
19409 }
19410 signal.addEventListener('abort', abort);
19411 }
19412
19413 this.generateResponse(route, url, options, request)
19414 .then(res, rej)
19415 .then(done, done)
19416 .then(() => {
19417 setDebugPhase$1();
19418 });
19419 });
19420};
19421
19422FetchMock$1.fetchHandler.isMock = true;
19423
19424FetchMock$1.executeRouter = function(url, options, request) {
19425 const debug = getDebug$2('executeRouter()');
19426 debug(`Attempting to match request to a route`);
19427 if (this.getOption('fallbackToNetwork') === 'always') {
19428 debug(
19429 ' Configured with fallbackToNetwork=always - passing through to fetch'
19430 );
19431 return { response: this.getNativeFetch(), responseIsFetch: true };
19432 }
19433
19434 const match = this.router(url, options, request);
19435
19436 if (match) {
19437 debug(' Matching route found');
19438 return match;
19439 }
19440
19441 if (this.getOption('warnOnFallback')) {
19442 console.warn(`Unmatched ${(options && options.method) || 'GET'} to ${url}`); // eslint-disable-line
19443 }
19444
19445 this.push({ url, options, request, isUnmatched: true });
19446
19447 if (this.fallbackResponse) {
19448 debug(' No matching route found - using fallbackResponse');
19449 return { response: this.fallbackResponse };
19450 }
19451
19452 if (!this.getOption('fallbackToNetwork')) {
19453 throw new Error(
19454 `fetch-mock: No fallback response defined for ${(options &&
19455 options.method) ||
19456 'GET'} to ${url}`
19457 );
19458 }
19459
19460 debug(' Configured to fallbackToNetwork - passing through to fetch');
19461 return { response: this.getNativeFetch(), responseIsFetch: true };
19462};
19463
19464FetchMock$1.generateResponse = async function(route, url, options, request) {
19465 const debug = getDebug$2('generateResponse()');
19466 const response = await resolve(route, url, options, request);
19467
19468 // If the response says to throw an error, throw it
19469 // Type checking is to deal with sinon spies having a throws property :-0
19470 if (response.throws && typeof response !== 'function') {
19471 debug('response.throws is defined - throwing an error');
19472 throw response.throws;
19473 }
19474
19475 // If the response is a pre-made Response, respond with it
19476 if (this.config.Response.prototype.isPrototypeOf(response)) {
19477 debug('response is already a Response instance - returning it');
19478 return response;
19479 }
19480
19481 // finally, if we need to convert config into a response, we do it
19482 return responseBuilder({
19483 url,
19484 responseConfig: response,
19485 fetchMock: this,
19486 route
19487 });
19488};
19489
19490FetchMock$1.router = function(url, options, request) {
19491 const route = this.routes.find((route, i) => {
19492 debug$3(`Trying to match route ${i}`);
19493 return route.matcher(url, options, request);
19494 });
19495
19496 if (route) {
19497 this.push({
19498 url,
19499 options,
19500 request,
19501 identifier: route.identifier
19502 });
19503 return route;
19504 }
19505};
19506
19507FetchMock$1.getNativeFetch = function() {
19508 const func = this.realFetch || (this.isSandbox && this.config.fetch);
19509 if (!func) {
19510 throw new Error(
19511 'fetch-mock: Falling back to network only available on global fetch-mock, or by setting config.fetch on sandboxed fetch-mock'
19512 );
19513 }
19514 return func;
19515};
19516
19517FetchMock$1.push = function({ url, options, request, isUnmatched, identifier }) {
19518 debug$3('Recording fetch call', {
19519 url,
19520 options,
19521 request,
19522 isUnmatched,
19523 identifier
19524 });
19525 const args = [url, options];
19526 args.request = request;
19527 args.identifier = identifier;
19528 args.isUnmatched = isUnmatched;
19529 this._calls.push(args);
19530};
19531
19532var fetchHandler = FetchMock$1;
19533
19534const { setDebugPhase: setDebugPhase$2, setDebugNamespace: setDebugNamespace$1, debug: debug$4 } = debug_1;
19535const { normalizeUrl: normalizeUrl$2 } = requestUtils;
19536const FetchMock$2 = {};
19537const { sanitizeRoute: sanitizeRoute$1 } = compileRoute_1;
19538
19539const isName = nameOrMatcher =>
19540 typeof nameOrMatcher === 'string' && /^[\da-zA-Z\-]+$/.test(nameOrMatcher);
19541
19542const filterCallsWithMatcher = function(matcher, options = {}, calls) {
19543 matcher = generateMatcher(
19544 sanitizeRoute$1(Object.assign({ matcher }, options)),
19545 this
19546 );
19547 return calls.filter(([url, options]) => matcher(normalizeUrl$2(url), options));
19548};
19549
19550const formatDebug = func => {
19551 return function(...args) {
19552 setDebugPhase$2('inspect');
19553 const result = func.call(this, ...args);
19554 setDebugPhase$2();
19555 return result;
19556 };
19557};
19558
19559FetchMock$2.filterCalls = function(nameOrMatcher, options) {
19560 debug$4('Filtering fetch calls');
19561 let calls = this._calls;
19562 let matcher = '*';
19563
19564 if ([true, 'matched'].includes(nameOrMatcher)) {
19565 debug$4(`Filter provided is ${nameOrMatcher}. Returning matched calls only`);
19566 calls = calls.filter(({ isUnmatched }) => !isUnmatched);
19567 } else if ([false, 'unmatched'].includes(nameOrMatcher)) {
19568 debug$4(
19569 `Filter provided is ${nameOrMatcher}. Returning unmatched calls only`
19570 );
19571 calls = calls.filter(({ isUnmatched }) => isUnmatched);
19572 } else if (typeof nameOrMatcher === 'undefined') {
19573 debug$4(`Filter provided is undefined. Returning all calls`);
19574 calls = calls;
19575 } else if (isName(nameOrMatcher)) {
19576 debug$4(
19577 `Filter provided, looks like the name of a named route. Returning only calls handled by that route`
19578 );
19579 calls = calls.filter(({ identifier }) => identifier === nameOrMatcher);
19580 } else {
19581 matcher = normalizeUrl$2(nameOrMatcher);
19582 if (this.routes.some(({ identifier }) => identifier === matcher)) {
19583 debug$4(
19584 `Filter provided, ${nameOrMatcher}, identifies a route. Returning only calls handled by that route`
19585 );
19586 calls = calls.filter(call => call.identifier === matcher);
19587 }
19588 }
19589
19590 if ((options || matcher !== '*') && calls.length) {
19591 if (typeof options === 'string') {
19592 options = { method: options };
19593 }
19594 debug$4(
19595 'Compiling filter and options to route in order to filter all calls',
19596 nameOrMatcher
19597 );
19598 calls = filterCallsWithMatcher.call(this, matcher, options, calls);
19599 }
19600 debug$4(`Retrieved ${calls.length} calls`);
19601 return calls;
19602};
19603
19604FetchMock$2.calls = formatDebug(function(nameOrMatcher, options) {
19605 debug$4('retrieving matching calls');
19606 return this.filterCalls(nameOrMatcher, options);
19607});
19608
19609FetchMock$2.lastCall = formatDebug(function(nameOrMatcher, options) {
19610 debug$4('retrieving last matching call');
19611 return [...this.filterCalls(nameOrMatcher, options)].pop();
19612});
19613
19614FetchMock$2.lastUrl = formatDebug(function(nameOrMatcher, options) {
19615 debug$4('retrieving url of last matching call');
19616 return (this.lastCall(nameOrMatcher, options) || [])[0];
19617});
19618
19619FetchMock$2.lastOptions = formatDebug(function(nameOrMatcher, options) {
19620 debug$4('retrieving options of last matching call');
19621 return (this.lastCall(nameOrMatcher, options) || [])[1];
19622});
19623
19624FetchMock$2.called = formatDebug(function(nameOrMatcher, options) {
19625 debug$4('checking if matching call was made');
19626 return !!this.filterCalls(nameOrMatcher, options).length;
19627});
19628
19629FetchMock$2.flush = formatDebug(async function(waitForResponseMethods) {
19630 setDebugNamespace$1('flush');
19631 debug$4(
19632 `flushing all fetch calls. ${
19633 waitForResponseMethods ? '' : 'Not '
19634 }waiting for response bodies to complete download`
19635 );
19636
19637 const queuedPromises = this._holdingPromises;
19638 this._holdingPromises = [];
19639 debug$4(`${queuedPromises.length} fetch calls to be awaited`);
19640
19641 await Promise.all(queuedPromises);
19642 debug$4(`All fetch calls have completed`);
19643 if (waitForResponseMethods && this._holdingPromises.length) {
19644 debug$4(`Awaiting all fetch bodies to download`);
19645 await this.flush(waitForResponseMethods);
19646 debug$4(`All fetch bodies have completed downloading`);
19647 }
19648 setDebugNamespace$1();
19649});
19650
19651FetchMock$2.done = formatDebug(function(nameOrMatcher) {
19652 setDebugPhase$2('inspect');
19653 setDebugNamespace$1('done');
19654 debug$4('Checking to see if expected calls have been made');
19655 let routesToCheck;
19656
19657 if (nameOrMatcher && typeof nameOrMatcher !== 'boolean') {
19658 debug$4(
19659 'Checking to see if expected calls have been made for single route:',
19660 nameOrMatcher
19661 );
19662 routesToCheck = [{ identifier: nameOrMatcher }];
19663 } else {
19664 debug$4('Checking to see if expected calls have been made for all routes');
19665 routesToCheck = this.routes;
19666 }
19667
19668 // Can't use array.every because would exit after first failure, which would
19669 // break the logging
19670 const result = routesToCheck
19671 .map(({ identifier }) => {
19672 if (!this.called(identifier)) {
19673 debug$4('No calls made for route:', identifier);
19674 console.warn(`Warning: ${identifier} not called`); // eslint-disable-line
19675 return false;
19676 }
19677
19678 const expectedTimes = (
19679 this.routes.find(r => r.identifier === identifier) || {}
19680 ).repeat;
19681
19682 if (!expectedTimes) {
19683 debug$4(
19684 'Route has been called at least once, and no expectation of more set:',
19685 identifier
19686 );
19687 return true;
19688 }
19689 const actualTimes = this.filterCalls(identifier).length;
19690
19691 debug$4(`Route called ${actualTimes} times:`, identifier);
19692 if (expectedTimes > actualTimes) {
19693 debug$4(
19694 `Route called ${actualTimes} times, but expected ${expectedTimes}:`,
19695 identifier
19696 );
19697 console.warn(
19698 `Warning: ${identifier} only called ${actualTimes} times, but ${expectedTimes} expected`
19699 ); // eslint-disable-line
19700 return false;
19701 } else {
19702 return true;
19703 }
19704 })
19705 .every(isDone => isDone);
19706
19707 setDebugNamespace$1();
19708 setDebugPhase$2();
19709 return result;
19710});
19711
19712var inspecting = FetchMock$2;
19713
19714const { debug: debug$5 } = debug_1;
19715
19716
19717
19718
19719const FetchMock$3 = Object.assign({}, fetchHandler, setUpAndTearDown, inspecting);
19720
19721FetchMock$3.config = {
19722 fallbackToNetwork: false,
19723 includeContentLength: true,
19724 sendAsJson: true,
19725 warnOnFallback: true,
19726 overwriteRoutes: undefined
19727};
19728
19729FetchMock$3.createInstance = function() {
19730 debug$5('Creating fetch-mock instance');
19731 const instance = Object.create(FetchMock$3);
19732 instance._uncompiledRoutes = (this._uncompiledRoutes || []).slice();
19733 instance.routes = instance._uncompiledRoutes.map(config =>
19734 instance.compileRoute(config)
19735 );
19736 instance.fallbackResponse = this.fallbackResponse || undefined;
19737 instance.config = Object.assign({}, this.config || FetchMock$3.config);
19738 instance._calls = [];
19739 instance._holdingPromises = [];
19740 instance.bindMethods();
19741 return instance;
19742};
19743
19744FetchMock$3.bindMethods = function() {
19745 this.fetchHandler = FetchMock$3.fetchHandler.bind(this);
19746 this.reset = this.restore = FetchMock$3.reset.bind(this);
19747 this.resetHistory = FetchMock$3.resetHistory.bind(this);
19748 this.resetBehavior = FetchMock$3.resetBehavior.bind(this);
19749};
19750
19751FetchMock$3.sandbox = function() {
19752 debug$5('Creating sandboxed fetch-mock instance');
19753 // this construct allows us to create a fetch-mock instance which is also
19754 // a callable function, while circumventing circularity when defining the
19755 // object that this function should be bound to
19756 const proxy = (url, options) => sandbox.fetchHandler(url, options);
19757
19758 const sandbox = Object.assign(
19759 proxy, // Ensures that the entire returned object is a callable function
19760 FetchMock$3, // prototype methods
19761 this.createInstance() // instance data
19762 );
19763
19764 sandbox.bindMethods();
19765 sandbox.isSandbox = true;
19766 return sandbox;
19767};
19768
19769FetchMock$3.getOption = function(name, route = {}) {
19770 return name in route ? route[name] : this.config[name];
19771};
19772
19773var lib$1 = FetchMock$3;
19774
19775var lib$2 = createCommonjsModule(function (module, exports) {
19776
19777function _(message, opts) {
19778 return `${opts && opts.context ? opts.context : "Value"} ${message}.`;
19779}
19780
19781function type(V) {
19782 if (V === null) {
19783 return "Null";
19784 }
19785 switch (typeof V) {
19786 case "undefined":
19787 return "Undefined";
19788 case "boolean":
19789 return "Boolean";
19790 case "number":
19791 return "Number";
19792 case "string":
19793 return "String";
19794 case "symbol":
19795 return "Symbol";
19796 case "object":
19797 // Falls through
19798 case "function":
19799 // Falls through
19800 default:
19801 // Per ES spec, typeof returns an implemention-defined value that is not any of the existing ones for
19802 // uncallable non-standard exotic objects. Yet Type() which the Web IDL spec depends on returns Object for
19803 // such cases. So treat the default case as an object.
19804 return "Object";
19805 }
19806}
19807
19808// Round x to the nearest integer, choosing the even integer if it lies halfway between two.
19809function evenRound(x) {
19810 // There are four cases for numbers with fractional part being .5:
19811 //
19812 // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example
19813 // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0
19814 // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2
19815 // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0
19816 // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2
19817 // (where n is a non-negative integer)
19818 //
19819 // Branch here for cases 1 and 4
19820 if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) ||
19821 (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) {
19822 return censorNegativeZero(Math.floor(x));
19823 }
19824
19825 return censorNegativeZero(Math.round(x));
19826}
19827
19828function integerPart(n) {
19829 return censorNegativeZero(Math.trunc(n));
19830}
19831
19832function sign(x) {
19833 return x < 0 ? -1 : 1;
19834}
19835
19836function modulo(x, y) {
19837 // https://tc39.github.io/ecma262/#eqn-modulo
19838 // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos
19839 const signMightNotMatch = x % y;
19840 if (sign(y) !== sign(signMightNotMatch)) {
19841 return signMightNotMatch + y;
19842 }
19843 return signMightNotMatch;
19844}
19845
19846function censorNegativeZero(x) {
19847 return x === 0 ? 0 : x;
19848}
19849
19850function createIntegerConversion(bitLength, typeOpts) {
19851 const isSigned = !typeOpts.unsigned;
19852
19853 let lowerBound;
19854 let upperBound;
19855 if (bitLength === 64) {
19856 upperBound = Math.pow(2, 53) - 1;
19857 lowerBound = !isSigned ? 0 : -Math.pow(2, 53) + 1;
19858 } else if (!isSigned) {
19859 lowerBound = 0;
19860 upperBound = Math.pow(2, bitLength) - 1;
19861 } else {
19862 lowerBound = -Math.pow(2, bitLength - 1);
19863 upperBound = Math.pow(2, bitLength - 1) - 1;
19864 }
19865
19866 const twoToTheBitLength = Math.pow(2, bitLength);
19867 const twoToOneLessThanTheBitLength = Math.pow(2, bitLength - 1);
19868
19869 return (V, opts) => {
19870 if (opts === undefined) {
19871 opts = {};
19872 }
19873
19874 let x = +V;
19875 x = censorNegativeZero(x); // Spec discussion ongoing: https://github.com/heycam/webidl/issues/306
19876
19877 if (opts.enforceRange) {
19878 if (!Number.isFinite(x)) {
19879 throw new TypeError(_("is not a finite number", opts));
19880 }
19881
19882 x = integerPart(x);
19883
19884 if (x < lowerBound || x > upperBound) {
19885 throw new TypeError(_(
19886 `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts));
19887 }
19888
19889 return x;
19890 }
19891
19892 if (!Number.isNaN(x) && opts.clamp) {
19893 x = Math.min(Math.max(x, lowerBound), upperBound);
19894 x = evenRound(x);
19895 return x;
19896 }
19897
19898 if (!Number.isFinite(x) || x === 0) {
19899 return 0;
19900 }
19901 x = integerPart(x);
19902
19903 // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if
19904 // possible. Hopefully it's an optimization for the non-64-bitLength cases too.
19905 if (x >= lowerBound && x <= upperBound) {
19906 return x;
19907 }
19908
19909 // These will not work great for bitLength of 64, but oh well. See the README for more details.
19910 x = modulo(x, twoToTheBitLength);
19911 if (isSigned && x >= twoToOneLessThanTheBitLength) {
19912 return x - twoToTheBitLength;
19913 }
19914 return x;
19915 };
19916}
19917
19918exports.any = V => {
19919 return V;
19920};
19921
19922exports.void = function () {
19923 return undefined;
19924};
19925
19926exports.boolean = function (val) {
19927 return !!val;
19928};
19929
19930exports.byte = createIntegerConversion(8, { unsigned: false });
19931exports.octet = createIntegerConversion(8, { unsigned: true });
19932
19933exports.short = createIntegerConversion(16, { unsigned: false });
19934exports["unsigned short"] = createIntegerConversion(16, { unsigned: true });
19935
19936exports.long = createIntegerConversion(32, { unsigned: false });
19937exports["unsigned long"] = createIntegerConversion(32, { unsigned: true });
19938
19939exports["long long"] = createIntegerConversion(64, { unsigned: false });
19940exports["unsigned long long"] = createIntegerConversion(64, { unsigned: true });
19941
19942exports.double = (V, opts) => {
19943 const x = +V;
19944
19945 if (!Number.isFinite(x)) {
19946 throw new TypeError(_("is not a finite floating-point value", opts));
19947 }
19948
19949 return x;
19950};
19951
19952exports["unrestricted double"] = V => {
19953 const x = +V;
19954
19955 return x;
19956};
19957
19958exports.float = (V, opts) => {
19959 const x = +V;
19960
19961 if (!Number.isFinite(x)) {
19962 throw new TypeError(_("is not a finite floating-point value", opts));
19963 }
19964
19965 if (Object.is(x, -0)) {
19966 return x;
19967 }
19968
19969 const y = Math.fround(x);
19970
19971 if (!Number.isFinite(y)) {
19972 throw new TypeError(_("is outside the range of a single-precision floating-point value", opts));
19973 }
19974
19975 return y;
19976};
19977
19978exports["unrestricted float"] = V => {
19979 const x = +V;
19980
19981 if (isNaN(x)) {
19982 return x;
19983 }
19984
19985 if (Object.is(x, -0)) {
19986 return x;
19987 }
19988
19989 return Math.fround(x);
19990};
19991
19992exports.DOMString = function (V, opts) {
19993 if (opts === undefined) {
19994 opts = {};
19995 }
19996
19997 if (opts.treatNullAsEmptyString && V === null) {
19998 return "";
19999 }
20000
20001 if (typeof V === "symbol") {
20002 throw new TypeError(_("is a symbol, which cannot be converted to a string", opts));
20003 }
20004
20005 return String(V);
20006};
20007
20008exports.ByteString = (V, opts) => {
20009 const x = exports.DOMString(V, opts);
20010 let c;
20011 for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) {
20012 if (c > 255) {
20013 throw new TypeError(_("is not a valid ByteString", opts));
20014 }
20015 }
20016
20017 return x;
20018};
20019
20020exports.USVString = (V, opts) => {
20021 const S = exports.DOMString(V, opts);
20022 const n = S.length;
20023 const U = [];
20024 for (let i = 0; i < n; ++i) {
20025 const c = S.charCodeAt(i);
20026 if (c < 0xD800 || c > 0xDFFF) {
20027 U.push(String.fromCodePoint(c));
20028 } else if (0xDC00 <= c && c <= 0xDFFF) {
20029 U.push(String.fromCodePoint(0xFFFD));
20030 } else if (i === n - 1) {
20031 U.push(String.fromCodePoint(0xFFFD));
20032 } else {
20033 const d = S.charCodeAt(i + 1);
20034 if (0xDC00 <= d && d <= 0xDFFF) {
20035 const a = c & 0x3FF;
20036 const b = d & 0x3FF;
20037 U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b));
20038 ++i;
20039 } else {
20040 U.push(String.fromCodePoint(0xFFFD));
20041 }
20042 }
20043 }
20044
20045 return U.join("");
20046};
20047
20048exports.object = (V, opts) => {
20049 if (type(V) !== "Object") {
20050 throw new TypeError(_("is not an object", opts));
20051 }
20052
20053 return V;
20054};
20055
20056// Not exported, but used in Function and VoidFunction.
20057
20058// Neither Function nor VoidFunction is defined with [TreatNonObjectAsNull], so
20059// handling for that is omitted.
20060function convertCallbackFunction(V, opts) {
20061 if (typeof V !== "function") {
20062 throw new TypeError(_("is not a function", opts));
20063 }
20064 return V;
20065}
20066
20067[
20068 Error,
20069 ArrayBuffer, // The IsDetachedBuffer abstract operation is not exposed in JS
20070 DataView, Int8Array, Int16Array, Int32Array, Uint8Array,
20071 Uint16Array, Uint32Array, Uint8ClampedArray, Float32Array, Float64Array
20072].forEach(func => {
20073 const name = func.name;
20074 const article = /^[AEIOU]/.test(name) ? "an" : "a";
20075 exports[name] = (V, opts) => {
20076 if (!(V instanceof func)) {
20077 throw new TypeError(_(`is not ${article} ${name} object`, opts));
20078 }
20079
20080 return V;
20081 };
20082});
20083
20084// Common definitions
20085
20086exports.ArrayBufferView = (V, opts) => {
20087 if (!ArrayBuffer.isView(V)) {
20088 throw new TypeError(_("is not a view on an ArrayBuffer object", opts));
20089 }
20090
20091 return V;
20092};
20093
20094exports.BufferSource = (V, opts) => {
20095 if (!(ArrayBuffer.isView(V) || V instanceof ArrayBuffer)) {
20096 throw new TypeError(_("is not an ArrayBuffer object or a view on one", opts));
20097 }
20098
20099 return V;
20100};
20101
20102exports.DOMTimeStamp = exports["unsigned long long"];
20103
20104exports.Function = convertCallbackFunction;
20105
20106exports.VoidFunction = convertCallbackFunction;
20107});
20108var lib_1 = lib$2.any;
20109var lib_2 = lib$2.octet;
20110var lib_3 = lib$2.DOMString;
20111var lib_4 = lib$2.ByteString;
20112var lib_5 = lib$2.USVString;
20113var lib_6 = lib$2.object;
20114var lib_7 = lib$2.ArrayBufferView;
20115var lib_8 = lib$2.BufferSource;
20116var lib_9 = lib$2.DOMTimeStamp;
20117var lib_10 = lib$2.Function;
20118var lib_11 = lib$2.VoidFunction;
20119
20120var utils = createCommonjsModule(function (module, exports) {
20121
20122// Returns "Type(value) is Object" in ES terminology.
20123function isObject(value) {
20124 return typeof value === "object" && value !== null || typeof value === "function";
20125}
20126
20127function getReferenceToBytes(bufferSource) {
20128 // Node.js' Buffer does not allow subclassing for now, so we can get away with a prototype object check for perf.
20129 if (Object.getPrototypeOf(bufferSource) === Buffer$1.prototype) {
20130 return bufferSource;
20131 }
20132 if (bufferSource instanceof ArrayBuffer) {
20133 return Buffer$1.from(bufferSource);
20134 }
20135 return Buffer$1.from(bufferSource.buffer, bufferSource.byteOffset, bufferSource.byteLength);
20136}
20137
20138function getCopyToBytes(bufferSource) {
20139 return Buffer$1.from(getReferenceToBytes(bufferSource));
20140}
20141
20142function mixin(target, source) {
20143 const keys = Object.getOwnPropertyNames(source);
20144 for (let i = 0; i < keys.length; ++i) {
20145 if (keys[i] in target) {
20146 continue;
20147 }
20148
20149 Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i]));
20150 }
20151}
20152
20153const wrapperSymbol = Symbol("wrapper");
20154const implSymbol = Symbol("impl");
20155const sameObjectCaches = Symbol("SameObject caches");
20156
20157function getSameObject(wrapper, prop, creator) {
20158 if (!wrapper[sameObjectCaches]) {
20159 wrapper[sameObjectCaches] = Object.create(null);
20160 }
20161
20162 if (prop in wrapper[sameObjectCaches]) {
20163 return wrapper[sameObjectCaches][prop];
20164 }
20165
20166 wrapper[sameObjectCaches][prop] = creator();
20167 return wrapper[sameObjectCaches][prop];
20168}
20169
20170function wrapperForImpl(impl) {
20171 return impl ? impl[wrapperSymbol] : null;
20172}
20173
20174function implForWrapper(wrapper) {
20175 return wrapper ? wrapper[implSymbol] : null;
20176}
20177
20178function tryWrapperForImpl(impl) {
20179 const wrapper = wrapperForImpl(impl);
20180 return wrapper ? wrapper : impl;
20181}
20182
20183function tryImplForWrapper(wrapper) {
20184 const impl = implForWrapper(wrapper);
20185 return impl ? impl : wrapper;
20186}
20187
20188const iterInternalSymbol = Symbol("internal");
20189const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
20190
20191function isArrayIndexPropName(P) {
20192 if (typeof P !== "string") {
20193 return false;
20194 }
20195 const i = P >>> 0;
20196 if (i === Math.pow(2, 32) - 1) {
20197 return false;
20198 }
20199 const s = `${i}`;
20200 if (P !== s) {
20201 return false;
20202 }
20203 return true;
20204}
20205
20206const supportsPropertyIndex = Symbol("supports property index");
20207const supportedPropertyIndices = Symbol("supported property indices");
20208const supportsPropertyName = Symbol("supports property name");
20209const supportedPropertyNames = Symbol("supported property names");
20210const indexedGet = Symbol("indexed property get");
20211const indexedSetNew = Symbol("indexed property set new");
20212const indexedSetExisting = Symbol("indexed property set existing");
20213const namedGet = Symbol("named property get");
20214const namedSetNew = Symbol("named property set new");
20215const namedSetExisting = Symbol("named property set existing");
20216const namedDelete = Symbol("named property delete");
20217
20218module.exports = exports = {
20219 isObject,
20220 getReferenceToBytes,
20221 getCopyToBytes,
20222 mixin,
20223 wrapperSymbol,
20224 implSymbol,
20225 getSameObject,
20226 wrapperForImpl,
20227 implForWrapper,
20228 tryWrapperForImpl,
20229 tryImplForWrapper,
20230 iterInternalSymbol,
20231 IteratorPrototype,
20232 isArrayIndexPropName,
20233 supportsPropertyIndex,
20234 supportedPropertyIndices,
20235 supportsPropertyName,
20236 supportedPropertyNames,
20237 indexedGet,
20238 indexedSetNew,
20239 indexedSetExisting,
20240 namedGet,
20241 namedSetNew,
20242 namedSetExisting,
20243 namedDelete
20244};
20245});
20246
20247const combiningMarks = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{11000}-\u{11002}\u{11038}-\u{11046}\u{1107F}-\u{11082}\u{110B0}-\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{11134}\u{11173}\u{11180}-\u{11182}\u{111B3}-\u{111C0}\u{111CA}-\u{111CC}\u{1122C}-\u{11237}\u{1123E}\u{112DF}-\u{112EA}\u{11300}-\u{11303}\u{1133C}\u{1133E}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11357}\u{11362}\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11435}-\u{11446}\u{114B0}-\u{114C3}\u{115AF}-\u{115B5}\u{115B8}-\u{115C0}\u{115DC}\u{115DD}\u{11630}-\u{11640}\u{116AB}-\u{116B7}\u{1171D}-\u{1172B}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A39}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A5B}\u{11A8A}-\u{11A99}\u{11C2F}-\u{11C36}\u{11C38}-\u{11C3F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F51}-\u{16F7E}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1D165}-\u{1D169}\u{1D16D}-\u{1D172}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]/u;
20248const combiningClassVirama = /[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D3B\u0D3C\u0D4D\u0DCA\u0E3A\u0F84\u1039\u103A\u1714\u1734\u17D2\u1A60\u1B44\u1BAA\u1BAB\u1BF2\u1BF3\u2D7F\uA806\uA8C4\uA953\uA9C0\uAAF6\uABED\u{10A3F}\u{11046}\u{1107F}\u{110B9}\u{11133}\u{11134}\u{111C0}\u{11235}\u{112EA}\u{1134D}\u{11442}\u{114C2}\u{115BF}\u{1163F}\u{116B6}\u{1172B}\u{11A34}\u{11A47}\u{11A99}\u{11C3F}\u{11D44}\u{11D45}]/u;
20249const validZWNJ = /[\u0620\u0626\u0628\u062A-\u062E\u0633-\u063F\u0641-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u08A0-\u08A9\u08AF\u08B0\u08B3\u08B4\u08B6-\u08B8\u08BA-\u08BD\u1807\u1820-\u1877\u1887-\u18A8\u18AA\uA840-\uA872\u{10AC0}-\u{10AC4}\u{10ACD}\u{10AD3}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{1E900}-\u{1E943}][\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110BD}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111CA}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*\u200C[\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110BD}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111CA}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*[\u0620\u0622-\u063F\u0641-\u064A\u066E\u066F\u0671-\u0673\u0675-\u06D3\u06D5\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u077F\u07CA-\u07EA\u0840-\u0855\u0860\u0862-\u0865\u0867-\u086A\u08A0-\u08AC\u08AE-\u08B4\u08B6-\u08BD\u1807\u1820-\u1877\u1887-\u18A8\u18AA\uA840-\uA871\u{10AC0}-\u{10AC5}\u{10AC7}\u{10AC9}\u{10ACA}\u{10ACE}-\u{10AD6}\u{10AD8}-\u{10AE1}\u{10AE4}\u{10AEB}-\u{10AEF}\u{10B80}-\u{10B91}\u{10BA9}-\u{10BAE}\u{1E900}-\u{1E943}]/u;
20250const bidiDomain = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05F0-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08E2\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A33}\u{10A40}-\u{10A47}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10CFF}\u{10E60}-\u{10E7E}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u;
20251const bidiS1LTR = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u055F\u0561-\u0587\u0589\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C7F\u0C80\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1735\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4B\u1B50-\u1B6A\u1B74-\u1B7C\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1CC0-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u3190-\u31BA\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u32FE\u3300-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FD\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BD-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB65\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11143}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C9}\u{111CD}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{11459}\u{1145B}\u{1145D}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116C0}-\u{116C9}\u{11700}-\u{11719}\u{11720}\u{11721}\u{11726}\u{11730}-\u{1173F}\u{118A0}-\u{118F2}\u{118FF}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A83}\u{11A86}-\u{11A89}\u{11A97}\u{11A9A}-\u{11A9C}\u{11A9E}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{12000}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16F00}-\u{16F44}\u{16F50}-\u{16F7E}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{17000}-\u{187EC}\u{18800}-\u{18AF2}\u{1B000}-\u{1B11E}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D360}-\u{1D371}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u;
20252const bidiS1RTL = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05F0-\u05F4\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A33}\u{10A40}-\u{10A47}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10CFF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u;
20253const bidiS2 = /^[\0-\x08\x0E-\x1B!-@\[-`\{-\x84\x86-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02B9\u02BA\u02C2-\u02CF\u02D2-\u02DF\u02E5-\u02ED\u02EF-\u036F\u0374\u0375\u037E\u0384\u0385\u0387\u03F6\u0483-\u0489\u058A\u058D-\u058F\u0591-\u05C7\u05D0-\u05EA\u05F0-\u05F4\u0600-\u061C\u061E-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u0800-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09F2\u09F3\u09FB\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AF1\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0BF3-\u0BFA\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C78-\u0C7E\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E3F\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39-\u0F3D\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1390-\u1399\u1400\u169B\u169C\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DB\u17DD\u17F0-\u17F9\u1800-\u180E\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1940\u1944\u1945\u19DE-\u19FF\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u200B-\u200D\u200F-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2070\u2074-\u207E\u2080-\u208E\u20A0-\u20BF\u20D0-\u20F0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u2150-\u215F\u2189-\u218B\u2190-\u2335\u237B-\u2394\u2396-\u2426\u2440-\u244A\u2460-\u249B\u24EA-\u26AB\u26AD-\u27FF\u2900-\u2B73\u2B76-\u2B95\u2B98-\u2BB9\u2BBD-\u2BC8\u2BCA-\u2BD2\u2BEC-\u2BEF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF9-\u2CFF\u2D7F\u2DE0-\u2E49\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u3004\u3008-\u3020\u302A-\u302D\u3030\u3036\u3037\u303D-\u303F\u3099-\u309C\u30A0\u30FB\u31C0-\u31E3\u321D\u321E\u3250-\u325F\u327C-\u327E\u32B1-\u32BF\u32CC-\u32CF\u3377-\u337A\u33DE\u33DF\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA60D-\uA60F\uA66F-\uA67F\uA69E\uA69F\uA6F0\uA6F1\uA700-\uA721\uA788\uA802\uA806\uA80B\uA825\uA826\uA828-\uA82B\uA838\uA839\uA874-\uA877\uA8C4\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3F\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFD\uFE00-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFEFF\uFF01-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10101}\u{10140}-\u{1018C}\u{10190}-\u{1019B}\u{101A0}\u{101FD}\u{102E0}-\u{102FB}\u{10376}-\u{1037A}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{1091F}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A33}\u{10A38}-\u{10A3A}\u{10A3F}-\u{10A47}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE6}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B39}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10CFF}\u{10E60}-\u{10E7E}\u{11001}\u{11038}-\u{11046}\u{11052}-\u{11065}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111CA}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{11660}-\u{1166C}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D200}-\u{1D245}\u{1D300}-\u{1D356}\u{1D6DB}\u{1D715}\u{1D74F}\u{1D789}\u{1D7C3}\u{1D7CE}-\u{1D7FF}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8D6}\u{1E900}-\u{1E94A}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10C}\u{1F16A}\u{1F16B}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D4}\u{1F6E0}-\u{1F6EC}\u{1F6F0}-\u{1F6F8}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D4}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F900}-\u{1F90B}\u{1F910}-\u{1F93E}\u{1F940}-\u{1F94C}\u{1F950}-\u{1F96B}\u{1F980}-\u{1F997}\u{1F9C0}\u{1F9D0}-\u{1F9E6}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*$/u;
20254const bidiS3 = /[0-9\xB2\xB3\xB9\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05F0-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08E2\u200F\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\u{102E1}-\u{102FB}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A33}\u{10A40}-\u{10A47}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10CFF}\u{10E60}-\u{10E7E}\u{1D7CE}-\u{1D7FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1F100}-\u{1F10A}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111CA}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u;
20255const bidiS4EN = /[0-9\xB2\xB3\xB9\u06F0-\u06F9\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFF10-\uFF19\u{102E1}-\u{102FB}\u{1D7CE}-\u{1D7FF}\u{1F100}-\u{1F10A}]/u;
20256const bidiS4AN = /[\u0600-\u0605\u0660-\u0669\u066B\u066C\u06DD\u08E2\u{10E60}-\u{10E7E}]/u;
20257const bidiS5 = /^[\0-\x08\x0E-\x1B!-\x84\x86-\u0377\u037A-\u037F\u0384-\u038A\u038C\u038E-\u03A1\u03A3-\u052F\u0531-\u0556\u0559-\u055F\u0561-\u0587\u0589\u058A\u058D-\u058F\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0606\u0607\u0609\u060A\u060C\u060E-\u061A\u064B-\u065F\u066A\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07F6-\u07F9\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09FD\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AF1\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B77\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BFA\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C78-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4F\u0D54-\u0D63\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E3A\u0E3F-\u0E5B\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FDA\u1000-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u137C\u1380-\u1399\u13A0-\u13F5\u13F8-\u13FD\u1400-\u167F\u1681-\u169C\u16A0-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1736\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17DD\u17E0-\u17E9\u17F0-\u17F9\u1800-\u180E\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1940\u1944-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u19DE-\u1A1B\u1A1E-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1AB0-\u1ABE\u1B00-\u1B4B\u1B50-\u1B7C\u1B80-\u1BF3\u1BFC-\u1C37\u1C3B-\u1C49\u1C4D-\u1C88\u1CC0-\u1CC7\u1CD0-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEF\u1FF2-\u1FF4\u1FF6-\u1FFE\u200B-\u200E\u2010-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2071\u2074-\u208E\u2090-\u209C\u20A0-\u20BF\u20D0-\u20F0\u2100-\u218B\u2190-\u2426\u2440-\u244A\u2460-\u2B73\u2B76-\u2B95\u2B98-\u2BB9\u2BBD-\u2BC8\u2BCA-\u2BD2\u2BEC-\u2BEF\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CF3\u2CF9-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2E49\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u303F\u3041-\u3096\u3099-\u30FF\u3105-\u312E\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u32FE\u3300-\u4DB5\u4DC0-\u9FEA\uA000-\uA48C\uA490-\uA4C6\uA4D0-\uA62B\uA640-\uA6F7\uA700-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA82B\uA830-\uA839\uA840-\uA877\uA880-\uA8C5\uA8CE-\uA8D9\uA8E0-\uA8FD\uA900-\uA953\uA95F-\uA97C\uA980-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA5C-\uAAC2\uAADB-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB65\uAB70-\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1E\uFB29\uFD3E\uFD3F\uFDFD\uFE00-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFEFF\uFF01-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}-\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1018E}\u{10190}-\u{1019B}\u{101A0}\u{101D0}-\u{101FD}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E0}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{1037A}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{1091F}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10B39}-\u{10B3F}\u{11000}-\u{1104D}\u{11052}-\u{1106F}\u{1107F}-\u{110C1}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11100}-\u{11134}\u{11136}-\u{11143}\u{11150}-\u{11176}\u{11180}-\u{111CD}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1123E}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112EA}\u{112F0}-\u{112F9}\u{11300}-\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133C}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11400}-\u{11459}\u{1145B}\u{1145D}\u{11480}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B5}\u{115B8}-\u{115DD}\u{11600}-\u{11644}\u{11650}-\u{11659}\u{11660}-\u{1166C}\u{11680}-\u{116B7}\u{116C0}-\u{116C9}\u{11700}-\u{11719}\u{1171D}-\u{1172B}\u{11730}-\u{1173F}\u{118A0}-\u{118F2}\u{118FF}\u{11A00}-\u{11A47}\u{11A50}-\u{11A83}\u{11A86}-\u{11A9C}\u{11A9E}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C36}\u{11C38}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D47}\u{11D50}-\u{11D59}\u{12000}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF0}-\u{16AF5}\u{16B00}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16F00}-\u{16F44}\u{16F50}-\u{16F7E}\u{16F8F}-\u{16F9F}\u{16FE0}\u{16FE1}\u{17000}-\u{187EC}\u{18800}-\u{18AF2}\u{1B000}-\u{1B11E}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}-\u{1BCA3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D1E8}\u{1D200}-\u{1D245}\u{1D300}-\u{1D356}\u{1D360}-\u{1D371}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D7CB}\u{1D7CE}-\u{1DA8B}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10C}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F16B}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D4}\u{1F6E0}-\u{1F6EC}\u{1F6F0}-\u{1F6F8}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D4}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F900}-\u{1F90B}\u{1F910}-\u{1F93E}\u{1F940}-\u{1F94C}\u{1F950}-\u{1F96B}\u{1F980}-\u{1F997}\u{1F9C0}\u{1F9D0}-\u{1F9E6}\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]*$/u;
20258const bidiS6 = /[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u055F\u0561-\u0587\u0589\u06F0-\u06F9\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C7F\u0C80\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1735\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4B\u1B50-\u1B6A\u1B74-\u1B7C\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1CC0-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u2488-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u3190-\u31BA\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u32FE\u3300-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FD\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BD-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB65\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E1}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11143}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C9}\u{111CD}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{11459}\u{1145B}\u{1145D}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116C0}-\u{116C9}\u{11700}-\u{11719}\u{11720}\u{11721}\u{11726}\u{11730}-\u{1173F}\u{118A0}-\u{118F2}\u{118FF}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A83}\u{11A86}-\u{11A89}\u{11A97}\u{11A9A}-\u{11A9C}\u{11A9E}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{12000}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16F00}-\u{16F44}\u{16F50}-\u{16F7E}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{17000}-\u{187EC}\u{18800}-\u{18AF2}\u{1B000}-\u{1B11E}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D360}-\u{1D371}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D7CE}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1F100}-\u{1F10A}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111CA}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u;
20259
20260var regexes = {
20261 combiningMarks,
20262 combiningClassVirama,
20263 validZWNJ,
20264 bidiDomain,
20265 bidiS1LTR,
20266 bidiS1RTL,
20267 bidiS2,
20268 bidiS3,
20269 bidiS4EN,
20270 bidiS4AN,
20271 bidiS5,
20272 bidiS6
20273};
20274
20275
20276
20277var mappingTable = /*#__PURE__*/Object.freeze({
20278 __proto__: null
20279});
20280
20281var mappingTable$1 = getCjsExportFromNamespace(mappingTable);
20282
20283function containsNonASCII(str) {
20284 return /[^\x00-\x7F]/.test(str);
20285}
20286
20287function findStatus(val, { useSTD3ASCIIRules }) {
20288 let start = 0;
20289 let end = mappingTable$1.length - 1;
20290
20291 while (start <= end) {
20292 const mid = Math.floor((start + end) / 2);
20293
20294 const target = mappingTable$1[mid];
20295 if (target[0][0] <= val && target[0][1] >= val) {
20296 if (target[1].startsWith("disallowed_STD3_")) {
20297 const newStatus = useSTD3ASCIIRules ? "disallowed" : target[1].slice(16);
20298 return [newStatus, ...target.slice(2)];
20299 }
20300 return target.slice(1);
20301 } else if (target[0][0] > val) {
20302 end = mid - 1;
20303 } else {
20304 start = mid + 1;
20305 }
20306 }
20307
20308 return null;
20309}
20310
20311function mapChars(domainName, { useSTD3ASCIIRules, processingOption }) {
20312 let hasError = false;
20313 let processed = "";
20314
20315 for (const ch of domainName) {
20316 const [status, mapping] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules });
20317
20318 switch (status) {
20319 case "disallowed":
20320 hasError = true;
20321 processed += ch;
20322 break;
20323 case "ignored":
20324 break;
20325 case "mapped":
20326 processed += mapping;
20327 break;
20328 case "deviation":
20329 if (processingOption === "transitional") {
20330 processed += mapping;
20331 } else {
20332 processed += ch;
20333 }
20334 break;
20335 case "valid":
20336 processed += ch;
20337 break;
20338 }
20339 }
20340
20341 return {
20342 string: processed,
20343 error: hasError
20344 };
20345}
20346
20347function validateLabel(label, { checkHyphens, checkBidi, checkJoiners, processingOption, useSTD3ASCIIRules }) {
20348 if (label.normalize("NFC") !== label) {
20349 return false;
20350 }
20351
20352 const codePoints = Array.from(label);
20353
20354 if (checkHyphens) {
20355 if ((codePoints[2] === "-" && codePoints[3] === "-") ||
20356 (label.startsWith("-") || label.endsWith("-"))) {
20357 return false;
20358 }
20359 }
20360
20361 if (label.includes(".") ||
20362 (codePoints.length > 0 && regexes.combiningMarks.test(codePoints[0]))) {
20363 return false;
20364 }
20365
20366 for (const ch of codePoints) {
20367 const [status] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules });
20368 if ((processingOption === "transitional" && status !== "valid") ||
20369 (processingOption === "nontransitional" &&
20370 status !== "valid" && status !== "deviation")) {
20371 return false;
20372 }
20373 }
20374
20375 // https://tools.ietf.org/html/rfc5892#appendix-A
20376 if (checkJoiners) {
20377 let last = 0;
20378 for (const [i, ch] of codePoints.entries()) {
20379 if (ch === "\u200C" || ch === "\u200D") {
20380 if (i > 0) {
20381 if (regexes.combiningClassVirama.test(codePoints[i - 1])) {
20382 continue;
20383 }
20384 if (ch === "\u200C") {
20385 // TODO: make this more efficient
20386 const next = codePoints.indexOf("\u200C", i + 1);
20387 const test = next < 0 ? codePoints.slice(last) : codePoints.slice(last, next);
20388 if (regexes.validZWNJ.test(test.join(""))) {
20389 last = i + 1;
20390 continue;
20391 }
20392 }
20393 }
20394 return false;
20395 }
20396 }
20397 }
20398
20399 // https://tools.ietf.org/html/rfc5893#section-2
20400 if (checkBidi) {
20401 let rtl;
20402
20403 // 1
20404 if (regexes.bidiS1LTR.test(codePoints[0])) {
20405 rtl = false;
20406 } else if (regexes.bidiS1RTL.test(codePoints[0])) {
20407 rtl = true;
20408 } else {
20409 return false;
20410 }
20411
20412 if (rtl) {
20413 // 2-4
20414 if (!regexes.bidiS2.test(label) ||
20415 !regexes.bidiS3.test(label) ||
20416 (regexes.bidiS4EN.test(label) && regexes.bidiS4AN.test(label))) {
20417 return false;
20418 }
20419 } else if (!regexes.bidiS5.test(label) ||
20420 !regexes.bidiS6.test(label)) { // 5-6
20421 return false;
20422 }
20423 }
20424
20425 return true;
20426}
20427
20428function isBidiDomain(labels) {
20429 const domain = labels.map(label => {
20430 if (label.startsWith("xn--")) {
20431 try {
20432 return punycode.decode(label.substring(4));
20433 } catch (err) {
20434 return "";
20435 }
20436 }
20437 return label;
20438 }).join(".");
20439 return regexes.bidiDomain.test(domain);
20440}
20441
20442function processing(domainName, options) {
20443 const { processingOption } = options;
20444
20445 // 1. Map.
20446 let { string, error } = mapChars(domainName, options);
20447
20448 // 2. Normalize.
20449 string = string.normalize("NFC");
20450
20451 // 3. Break.
20452 const labels = string.split(".");
20453 const isBidi = isBidiDomain(labels);
20454
20455 // 4. Convert/Validate.
20456 for (const [i, origLabel] of labels.entries()) {
20457 let label = origLabel;
20458 let curProcessing = processingOption;
20459 if (label.startsWith("xn--")) {
20460 try {
20461 label = punycode.decode(label.substring(4));
20462 labels[i] = label;
20463 } catch (err) {
20464 error = true;
20465 continue;
20466 }
20467 curProcessing = "nontransitional";
20468 }
20469
20470 // No need to validate if we already know there is an error.
20471 if (error) {
20472 continue;
20473 }
20474 const validation = validateLabel(label, Object.assign({}, options, {
20475 processingOption: curProcessing,
20476 checkBidi: options.checkBidi && isBidi
20477 }));
20478 if (!validation) {
20479 error = true;
20480 }
20481 }
20482
20483 return {
20484 string: labels.join("."),
20485 error
20486 };
20487}
20488
20489function toASCII$1(domainName, {
20490 checkHyphens = false,
20491 checkBidi = false,
20492 checkJoiners = false,
20493 useSTD3ASCIIRules = false,
20494 processingOption = "nontransitional",
20495 verifyDNSLength = false
20496} = {}) {
20497 if (processingOption !== "transitional" && processingOption !== "nontransitional") {
20498 throw new RangeError("processingOption must be either transitional or nontransitional");
20499 }
20500
20501 const result = processing(domainName, {
20502 processingOption,
20503 checkHyphens,
20504 checkBidi,
20505 checkJoiners,
20506 useSTD3ASCIIRules
20507 });
20508 let labels = result.string.split(".");
20509 labels = labels.map(l => {
20510 if (containsNonASCII(l)) {
20511 try {
20512 return "xn--" + punycode.encode(l);
20513 } catch (e) {
20514 result.error = true;
20515 }
20516 }
20517 return l;
20518 });
20519
20520 if (verifyDNSLength) {
20521 const total = labels.join(".").length;
20522 if (total > 253 || total === 0) {
20523 result.error = true;
20524 }
20525
20526 for (let i = 0; i < labels.length; ++i) {
20527 if (labels[i].length > 63 || labels[i].length === 0) {
20528 result.error = true;
20529 break;
20530 }
20531 }
20532 }
20533
20534 if (result.error) {
20535 return null;
20536 }
20537 return labels.join(".");
20538}
20539
20540function toUnicode$1(domainName, {
20541 checkHyphens = false,
20542 checkBidi = false,
20543 checkJoiners = false,
20544 useSTD3ASCIIRules = false
20545} = {}) {
20546 const result = processing(domainName, {
20547 processingOption: "nontransitional",
20548 checkHyphens,
20549 checkBidi,
20550 checkJoiners,
20551 useSTD3ASCIIRules
20552 });
20553
20554 return {
20555 domain: result.string,
20556 error: result.error
20557 };
20558}
20559
20560var tr46 = {
20561 toASCII: toASCII$1,
20562 toUnicode: toUnicode$1
20563};
20564
20565function isASCIIDigit(c) {
20566 return c >= 0x30 && c <= 0x39;
20567}
20568
20569function isASCIIAlpha(c) {
20570 return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A);
20571}
20572
20573function isASCIIAlphanumeric(c) {
20574 return isASCIIAlpha(c) || isASCIIDigit(c);
20575}
20576
20577function isASCIIHex(c) {
20578 return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66);
20579}
20580
20581var infra = {
20582 isASCIIDigit,
20583 isASCIIAlpha,
20584 isASCIIAlphanumeric,
20585 isASCIIHex
20586};
20587
20588const { isASCIIHex: isASCIIHex$1 } = infra;
20589
20590function strictlySplitByteSequence(buf, cp) {
20591 const list = [];
20592 let last = 0;
20593 let i = buf.indexOf(cp);
20594 while (i >= 0) {
20595 list.push(buf.slice(last, i));
20596 last = i + 1;
20597 i = buf.indexOf(cp, last);
20598 }
20599 if (last !== buf.length) {
20600 list.push(buf.slice(last));
20601 }
20602 return list;
20603}
20604
20605function replaceByteInByteSequence(buf, from, to) {
20606 let i = buf.indexOf(from);
20607 while (i >= 0) {
20608 buf[i] = to;
20609 i = buf.indexOf(from, i + 1);
20610 }
20611 return buf;
20612}
20613
20614function percentEncode(c) {
20615 let hex = c.toString(16).toUpperCase();
20616 if (hex.length === 1) {
20617 hex = "0" + hex;
20618 }
20619
20620 return "%" + hex;
20621}
20622
20623function percentDecode(input) {
20624 const output = Buffer$1.alloc(input.byteLength);
20625 let ptr = 0;
20626 for (let i = 0; i < input.length; ++i) {
20627 if (input[i] !== 37 || !isASCIIHex$1(input[i + 1]) || !isASCIIHex$1(input[i + 2])) {
20628 output[ptr++] = input[i];
20629 } else {
20630 output[ptr++] = parseInt(input.slice(i + 1, i + 3).toString(), 16);
20631 i += 2;
20632 }
20633 }
20634 return output.slice(0, ptr);
20635}
20636
20637function parseUrlencoded(input) {
20638 const sequences = strictlySplitByteSequence(input, 38);
20639 const output = [];
20640 for (const bytes of sequences) {
20641 if (bytes.length === 0) {
20642 continue;
20643 }
20644
20645 let name;
20646 let value;
20647 const indexOfEqual = bytes.indexOf(61);
20648
20649 if (indexOfEqual >= 0) {
20650 name = bytes.slice(0, indexOfEqual);
20651 value = bytes.slice(indexOfEqual + 1);
20652 } else {
20653 name = bytes;
20654 value = Buffer$1.alloc(0);
20655 }
20656
20657 name = replaceByteInByteSequence(Buffer$1.from(name), 43, 32);
20658 value = replaceByteInByteSequence(Buffer$1.from(value), 43, 32);
20659
20660 output.push([percentDecode(name).toString(), percentDecode(value).toString()]);
20661 }
20662 return output;
20663}
20664
20665function serializeUrlencodedByte(input) {
20666 let output = "";
20667 for (const byte of input) {
20668 if (byte === 32) {
20669 output += "+";
20670 } else if (byte === 42 ||
20671 byte === 45 ||
20672 byte === 46 ||
20673 (byte >= 48 && byte <= 57) ||
20674 (byte >= 65 && byte <= 90) ||
20675 byte === 95 ||
20676 (byte >= 97 && byte <= 122)) {
20677 output += String.fromCodePoint(byte);
20678 } else {
20679 output += percentEncode(byte);
20680 }
20681 }
20682 return output;
20683}
20684
20685function serializeUrlencoded(tuples, encodingOverride = undefined) {
20686 let encoding = "utf-8";
20687 if (encodingOverride !== undefined) {
20688 encoding = encodingOverride;
20689 }
20690
20691 let output = "";
20692 for (const [i, tuple] of tuples.entries()) {
20693 // TODO: handle encoding override
20694 const name = serializeUrlencodedByte(Buffer$1.from(tuple[0]));
20695 let value = tuple[1];
20696 if (tuple.length > 2 && tuple[2] !== undefined) {
20697 if (tuple[2] === "hidden" && name === "_charset_") {
20698 value = encoding;
20699 } else if (tuple[2] === "file") {
20700 // value is a File object
20701 value = value.name;
20702 }
20703 }
20704 value = serializeUrlencodedByte(Buffer$1.from(value));
20705 if (i !== 0) {
20706 output += "&";
20707 }
20708 output += `${name}=${value}`;
20709 }
20710 return output;
20711}
20712
20713var urlencoded = {
20714 percentEncode,
20715 percentDecode,
20716
20717 // application/x-www-form-urlencoded string parser
20718 parseUrlencoded(input) {
20719 return parseUrlencoded(Buffer$1.from(input));
20720 },
20721
20722 // application/x-www-form-urlencoded serializer
20723 serializeUrlencoded
20724};
20725
20726var urlStateMachine = createCommonjsModule(function (module) {
20727
20728
20729
20730
20731const { percentEncode, percentDecode } = urlencoded;
20732
20733const specialSchemes = {
20734 ftp: 21,
20735 file: null,
20736 gopher: 70,
20737 http: 80,
20738 https: 443,
20739 ws: 80,
20740 wss: 443
20741};
20742
20743const failure = Symbol("failure");
20744
20745function countSymbols(str) {
20746 return punycode.ucs2.decode(str).length;
20747}
20748
20749function at(input, idx) {
20750 const c = input[idx];
20751 return isNaN(c) ? undefined : String.fromCodePoint(c);
20752}
20753
20754function isSingleDot(buffer) {
20755 return buffer === "." || buffer.toLowerCase() === "%2e";
20756}
20757
20758function isDoubleDot(buffer) {
20759 buffer = buffer.toLowerCase();
20760 return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e";
20761}
20762
20763function isWindowsDriveLetterCodePoints(cp1, cp2) {
20764 return infra.isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124);
20765}
20766
20767function isWindowsDriveLetterString(string) {
20768 return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|");
20769}
20770
20771function isNormalizedWindowsDriveLetterString(string) {
20772 return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && string[1] === ":";
20773}
20774
20775function containsForbiddenHostCodePoint(string) {
20776 return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1;
20777}
20778
20779function containsForbiddenHostCodePointExcludingPercent(string) {
20780 return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1;
20781}
20782
20783function isSpecialScheme(scheme) {
20784 return specialSchemes[scheme] !== undefined;
20785}
20786
20787function isSpecial(url) {
20788 return isSpecialScheme(url.scheme);
20789}
20790
20791function isNotSpecial(url) {
20792 return !isSpecialScheme(url.scheme);
20793}
20794
20795function defaultPort(scheme) {
20796 return specialSchemes[scheme];
20797}
20798
20799function utf8PercentEncode(c) {
20800 const buf = Buffer$1.from(c);
20801
20802 let str = "";
20803
20804 for (let i = 0; i < buf.length; ++i) {
20805 str += percentEncode(buf[i]);
20806 }
20807
20808 return str;
20809}
20810
20811function isC0ControlPercentEncode(c) {
20812 return c <= 0x1F || c > 0x7E;
20813}
20814
20815const extraUserinfoPercentEncodeSet =
20816 new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]);
20817function isUserinfoPercentEncode(c) {
20818 return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c);
20819}
20820
20821const extraFragmentPercentEncodeSet = new Set([32, 34, 60, 62, 96]);
20822function isFragmentPercentEncode(c) {
20823 return isC0ControlPercentEncode(c) || extraFragmentPercentEncodeSet.has(c);
20824}
20825
20826const extraPathPercentEncodeSet = new Set([35, 63, 123, 125]);
20827function isPathPercentEncode(c) {
20828 return isFragmentPercentEncode(c) || extraPathPercentEncodeSet.has(c);
20829}
20830
20831function percentEncodeChar(c, encodeSetPredicate) {
20832 const cStr = String.fromCodePoint(c);
20833
20834 if (encodeSetPredicate(c)) {
20835 return utf8PercentEncode(cStr);
20836 }
20837
20838 return cStr;
20839}
20840
20841function parseIPv4Number(input) {
20842 let R = 10;
20843
20844 if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {
20845 input = input.substring(2);
20846 R = 16;
20847 } else if (input.length >= 2 && input.charAt(0) === "0") {
20848 input = input.substring(1);
20849 R = 8;
20850 }
20851
20852 if (input === "") {
20853 return 0;
20854 }
20855
20856 let regex = /[^0-7]/;
20857 if (R === 10) {
20858 regex = /[^0-9]/;
20859 }
20860 if (R === 16) {
20861 regex = /[^0-9A-Fa-f]/;
20862 }
20863
20864 if (regex.test(input)) {
20865 return failure;
20866 }
20867
20868 return parseInt(input, R);
20869}
20870
20871function parseIPv4(input) {
20872 const parts = input.split(".");
20873 if (parts[parts.length - 1] === "") {
20874 if (parts.length > 1) {
20875 parts.pop();
20876 }
20877 }
20878
20879 if (parts.length > 4) {
20880 return input;
20881 }
20882
20883 const numbers = [];
20884 for (const part of parts) {
20885 if (part === "") {
20886 return input;
20887 }
20888 const n = parseIPv4Number(part);
20889 if (n === failure) {
20890 return input;
20891 }
20892
20893 numbers.push(n);
20894 }
20895
20896 for (let i = 0; i < numbers.length - 1; ++i) {
20897 if (numbers[i] > 255) {
20898 return failure;
20899 }
20900 }
20901 if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) {
20902 return failure;
20903 }
20904
20905 let ipv4 = numbers.pop();
20906 let counter = 0;
20907
20908 for (const n of numbers) {
20909 ipv4 += n * Math.pow(256, 3 - counter);
20910 ++counter;
20911 }
20912
20913 return ipv4;
20914}
20915
20916function serializeIPv4(address) {
20917 let output = "";
20918 let n = address;
20919
20920 for (let i = 1; i <= 4; ++i) {
20921 output = String(n % 256) + output;
20922 if (i !== 4) {
20923 output = "." + output;
20924 }
20925 n = Math.floor(n / 256);
20926 }
20927
20928 return output;
20929}
20930
20931function parseIPv6(input) {
20932 const address = [0, 0, 0, 0, 0, 0, 0, 0];
20933 let pieceIndex = 0;
20934 let compress = null;
20935 let pointer = 0;
20936
20937 input = punycode.ucs2.decode(input);
20938
20939 if (input[pointer] === 58) {
20940 if (input[pointer + 1] !== 58) {
20941 return failure;
20942 }
20943
20944 pointer += 2;
20945 ++pieceIndex;
20946 compress = pieceIndex;
20947 }
20948
20949 while (pointer < input.length) {
20950 if (pieceIndex === 8) {
20951 return failure;
20952 }
20953
20954 if (input[pointer] === 58) {
20955 if (compress !== null) {
20956 return failure;
20957 }
20958 ++pointer;
20959 ++pieceIndex;
20960 compress = pieceIndex;
20961 continue;
20962 }
20963
20964 let value = 0;
20965 let length = 0;
20966
20967 while (length < 4 && infra.isASCIIHex(input[pointer])) {
20968 value = value * 0x10 + parseInt(at(input, pointer), 16);
20969 ++pointer;
20970 ++length;
20971 }
20972
20973 if (input[pointer] === 46) {
20974 if (length === 0) {
20975 return failure;
20976 }
20977
20978 pointer -= length;
20979
20980 if (pieceIndex > 6) {
20981 return failure;
20982 }
20983
20984 let numbersSeen = 0;
20985
20986 while (input[pointer] !== undefined) {
20987 let ipv4Piece = null;
20988
20989 if (numbersSeen > 0) {
20990 if (input[pointer] === 46 && numbersSeen < 4) {
20991 ++pointer;
20992 } else {
20993 return failure;
20994 }
20995 }
20996
20997 if (!infra.isASCIIDigit(input[pointer])) {
20998 return failure;
20999 }
21000
21001 while (infra.isASCIIDigit(input[pointer])) {
21002 const number = parseInt(at(input, pointer));
21003 if (ipv4Piece === null) {
21004 ipv4Piece = number;
21005 } else if (ipv4Piece === 0) {
21006 return failure;
21007 } else {
21008 ipv4Piece = ipv4Piece * 10 + number;
21009 }
21010 if (ipv4Piece > 255) {
21011 return failure;
21012 }
21013 ++pointer;
21014 }
21015
21016 address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece;
21017
21018 ++numbersSeen;
21019
21020 if (numbersSeen === 2 || numbersSeen === 4) {
21021 ++pieceIndex;
21022 }
21023 }
21024
21025 if (numbersSeen !== 4) {
21026 return failure;
21027 }
21028
21029 break;
21030 } else if (input[pointer] === 58) {
21031 ++pointer;
21032 if (input[pointer] === undefined) {
21033 return failure;
21034 }
21035 } else if (input[pointer] !== undefined) {
21036 return failure;
21037 }
21038
21039 address[pieceIndex] = value;
21040 ++pieceIndex;
21041 }
21042
21043 if (compress !== null) {
21044 let swaps = pieceIndex - compress;
21045 pieceIndex = 7;
21046 while (pieceIndex !== 0 && swaps > 0) {
21047 const temp = address[compress + swaps - 1];
21048 address[compress + swaps - 1] = address[pieceIndex];
21049 address[pieceIndex] = temp;
21050 --pieceIndex;
21051 --swaps;
21052 }
21053 } else if (compress === null && pieceIndex !== 8) {
21054 return failure;
21055 }
21056
21057 return address;
21058}
21059
21060function serializeIPv6(address) {
21061 let output = "";
21062 const seqResult = findLongestZeroSequence(address);
21063 const compress = seqResult.idx;
21064 let ignore0 = false;
21065
21066 for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {
21067 if (ignore0 && address[pieceIndex] === 0) {
21068 continue;
21069 } else if (ignore0) {
21070 ignore0 = false;
21071 }
21072
21073 if (compress === pieceIndex) {
21074 const separator = pieceIndex === 0 ? "::" : ":";
21075 output += separator;
21076 ignore0 = true;
21077 continue;
21078 }
21079
21080 output += address[pieceIndex].toString(16);
21081
21082 if (pieceIndex !== 7) {
21083 output += ":";
21084 }
21085 }
21086
21087 return output;
21088}
21089
21090function parseHost(input, isNotSpecialArg = false) {
21091 if (input[0] === "[") {
21092 if (input[input.length - 1] !== "]") {
21093 return failure;
21094 }
21095
21096 return parseIPv6(input.substring(1, input.length - 1));
21097 }
21098
21099 if (isNotSpecialArg) {
21100 return parseOpaqueHost(input);
21101 }
21102
21103 const domain = percentDecode(Buffer$1.from(input)).toString();
21104 const asciiDomain = domainToASCII(domain);
21105 if (asciiDomain === failure) {
21106 return failure;
21107 }
21108
21109 if (containsForbiddenHostCodePoint(asciiDomain)) {
21110 return failure;
21111 }
21112
21113 const ipv4Host = parseIPv4(asciiDomain);
21114 if (typeof ipv4Host === "number" || ipv4Host === failure) {
21115 return ipv4Host;
21116 }
21117
21118 return asciiDomain;
21119}
21120
21121function parseOpaqueHost(input) {
21122 if (containsForbiddenHostCodePointExcludingPercent(input)) {
21123 return failure;
21124 }
21125
21126 let output = "";
21127 const decoded = punycode.ucs2.decode(input);
21128 for (let i = 0; i < decoded.length; ++i) {
21129 output += percentEncodeChar(decoded[i], isC0ControlPercentEncode);
21130 }
21131 return output;
21132}
21133
21134function findLongestZeroSequence(arr) {
21135 let maxIdx = null;
21136 let maxLen = 1; // only find elements > 1
21137 let currStart = null;
21138 let currLen = 0;
21139
21140 for (let i = 0; i < arr.length; ++i) {
21141 if (arr[i] !== 0) {
21142 if (currLen > maxLen) {
21143 maxIdx = currStart;
21144 maxLen = currLen;
21145 }
21146
21147 currStart = null;
21148 currLen = 0;
21149 } else {
21150 if (currStart === null) {
21151 currStart = i;
21152 }
21153 ++currLen;
21154 }
21155 }
21156
21157 // if trailing zeros
21158 if (currLen > maxLen) {
21159 maxIdx = currStart;
21160 maxLen = currLen;
21161 }
21162
21163 return {
21164 idx: maxIdx,
21165 len: maxLen
21166 };
21167}
21168
21169function serializeHost(host) {
21170 if (typeof host === "number") {
21171 return serializeIPv4(host);
21172 }
21173
21174 // IPv6 serializer
21175 if (host instanceof Array) {
21176 return "[" + serializeIPv6(host) + "]";
21177 }
21178
21179 return host;
21180}
21181
21182function domainToASCII(domain, beStrict = false) {
21183 const result = tr46.toASCII(domain, {
21184 checkBidi: true,
21185 checkHyphens: false,
21186 checkJoiners: true,
21187 useSTD3ASCIIRules: beStrict,
21188 verifyDNSLength: beStrict
21189 });
21190 if (result === null) {
21191 return failure;
21192 }
21193 return result;
21194}
21195
21196function trimControlChars(url) {
21197 return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, "");
21198}
21199
21200function trimTabAndNewline(url) {
21201 return url.replace(/\u0009|\u000A|\u000D/g, "");
21202}
21203
21204function shortenPath(url) {
21205 const { path } = url;
21206 if (path.length === 0) {
21207 return;
21208 }
21209 if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) {
21210 return;
21211 }
21212
21213 path.pop();
21214}
21215
21216function includesCredentials(url) {
21217 return url.username !== "" || url.password !== "";
21218}
21219
21220function cannotHaveAUsernamePasswordPort(url) {
21221 return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file";
21222}
21223
21224function isNormalizedWindowsDriveLetter(string) {
21225 return /^[A-Za-z]:$/.test(string);
21226}
21227
21228function URLStateMachine(input, base, encodingOverride, url, stateOverride) {
21229 this.pointer = 0;
21230 this.input = input;
21231 this.base = base || null;
21232 this.encodingOverride = encodingOverride || "utf-8";
21233 this.stateOverride = stateOverride;
21234 this.url = url;
21235 this.failure = false;
21236 this.parseError = false;
21237
21238 if (!this.url) {
21239 this.url = {
21240 scheme: "",
21241 username: "",
21242 password: "",
21243 host: null,
21244 port: null,
21245 path: [],
21246 query: null,
21247 fragment: null,
21248
21249 cannotBeABaseURL: false
21250 };
21251
21252 const res = trimControlChars(this.input);
21253 if (res !== this.input) {
21254 this.parseError = true;
21255 }
21256 this.input = res;
21257 }
21258
21259 const res = trimTabAndNewline(this.input);
21260 if (res !== this.input) {
21261 this.parseError = true;
21262 }
21263 this.input = res;
21264
21265 this.state = stateOverride || "scheme start";
21266
21267 this.buffer = "";
21268 this.atFlag = false;
21269 this.arrFlag = false;
21270 this.passwordTokenSeenFlag = false;
21271
21272 this.input = punycode.ucs2.decode(this.input);
21273
21274 for (; this.pointer <= this.input.length; ++this.pointer) {
21275 const c = this.input[this.pointer];
21276 const cStr = isNaN(c) ? undefined : String.fromCodePoint(c);
21277
21278 // exec state machine
21279 const ret = this["parse " + this.state](c, cStr);
21280 if (!ret) {
21281 break; // terminate algorithm
21282 } else if (ret === failure) {
21283 this.failure = true;
21284 break;
21285 }
21286 }
21287}
21288
21289URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) {
21290 if (infra.isASCIIAlpha(c)) {
21291 this.buffer += cStr.toLowerCase();
21292 this.state = "scheme";
21293 } else if (!this.stateOverride) {
21294 this.state = "no scheme";
21295 --this.pointer;
21296 } else {
21297 this.parseError = true;
21298 return failure;
21299 }
21300
21301 return true;
21302};
21303
21304URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) {
21305 if (infra.isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) {
21306 this.buffer += cStr.toLowerCase();
21307 } else if (c === 58) {
21308 if (this.stateOverride) {
21309 if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {
21310 return false;
21311 }
21312
21313 if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {
21314 return false;
21315 }
21316
21317 if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") {
21318 return false;
21319 }
21320
21321 if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) {
21322 return false;
21323 }
21324 }
21325 this.url.scheme = this.buffer;
21326 if (this.stateOverride) {
21327 if (this.url.port === defaultPort(this.url.scheme)) {
21328 this.url.port = null;
21329 }
21330 return false;
21331 }
21332 this.buffer = "";
21333 if (this.url.scheme === "file") {
21334 if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) {
21335 this.parseError = true;
21336 }
21337 this.state = "file";
21338 } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {
21339 this.state = "special relative or authority";
21340 } else if (isSpecial(this.url)) {
21341 this.state = "special authority slashes";
21342 } else if (this.input[this.pointer + 1] === 47) {
21343 this.state = "path or authority";
21344 ++this.pointer;
21345 } else {
21346 this.url.cannotBeABaseURL = true;
21347 this.url.path.push("");
21348 this.state = "cannot-be-a-base-URL path";
21349 }
21350 } else if (!this.stateOverride) {
21351 this.buffer = "";
21352 this.state = "no scheme";
21353 this.pointer = -1;
21354 } else {
21355 this.parseError = true;
21356 return failure;
21357 }
21358
21359 return true;
21360};
21361
21362URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) {
21363 if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) {
21364 return failure;
21365 } else if (this.base.cannotBeABaseURL && c === 35) {
21366 this.url.scheme = this.base.scheme;
21367 this.url.path = this.base.path.slice();
21368 this.url.query = this.base.query;
21369 this.url.fragment = "";
21370 this.url.cannotBeABaseURL = true;
21371 this.state = "fragment";
21372 } else if (this.base.scheme === "file") {
21373 this.state = "file";
21374 --this.pointer;
21375 } else {
21376 this.state = "relative";
21377 --this.pointer;
21378 }
21379
21380 return true;
21381};
21382
21383URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) {
21384 if (c === 47 && this.input[this.pointer + 1] === 47) {
21385 this.state = "special authority ignore slashes";
21386 ++this.pointer;
21387 } else {
21388 this.parseError = true;
21389 this.state = "relative";
21390 --this.pointer;
21391 }
21392
21393 return true;
21394};
21395
21396URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) {
21397 if (c === 47) {
21398 this.state = "authority";
21399 } else {
21400 this.state = "path";
21401 --this.pointer;
21402 }
21403
21404 return true;
21405};
21406
21407URLStateMachine.prototype["parse relative"] = function parseRelative(c) {
21408 this.url.scheme = this.base.scheme;
21409 if (isNaN(c)) {
21410 this.url.username = this.base.username;
21411 this.url.password = this.base.password;
21412 this.url.host = this.base.host;
21413 this.url.port = this.base.port;
21414 this.url.path = this.base.path.slice();
21415 this.url.query = this.base.query;
21416 } else if (c === 47) {
21417 this.state = "relative slash";
21418 } else if (c === 63) {
21419 this.url.username = this.base.username;
21420 this.url.password = this.base.password;
21421 this.url.host = this.base.host;
21422 this.url.port = this.base.port;
21423 this.url.path = this.base.path.slice();
21424 this.url.query = "";
21425 this.state = "query";
21426 } else if (c === 35) {
21427 this.url.username = this.base.username;
21428 this.url.password = this.base.password;
21429 this.url.host = this.base.host;
21430 this.url.port = this.base.port;
21431 this.url.path = this.base.path.slice();
21432 this.url.query = this.base.query;
21433 this.url.fragment = "";
21434 this.state = "fragment";
21435 } else if (isSpecial(this.url) && c === 92) {
21436 this.parseError = true;
21437 this.state = "relative slash";
21438 } else {
21439 this.url.username = this.base.username;
21440 this.url.password = this.base.password;
21441 this.url.host = this.base.host;
21442 this.url.port = this.base.port;
21443 this.url.path = this.base.path.slice(0, this.base.path.length - 1);
21444
21445 this.state = "path";
21446 --this.pointer;
21447 }
21448
21449 return true;
21450};
21451
21452URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) {
21453 if (isSpecial(this.url) && (c === 47 || c === 92)) {
21454 if (c === 92) {
21455 this.parseError = true;
21456 }
21457 this.state = "special authority ignore slashes";
21458 } else if (c === 47) {
21459 this.state = "authority";
21460 } else {
21461 this.url.username = this.base.username;
21462 this.url.password = this.base.password;
21463 this.url.host = this.base.host;
21464 this.url.port = this.base.port;
21465 this.state = "path";
21466 --this.pointer;
21467 }
21468
21469 return true;
21470};
21471
21472URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) {
21473 if (c === 47 && this.input[this.pointer + 1] === 47) {
21474 this.state = "special authority ignore slashes";
21475 ++this.pointer;
21476 } else {
21477 this.parseError = true;
21478 this.state = "special authority ignore slashes";
21479 --this.pointer;
21480 }
21481
21482 return true;
21483};
21484
21485URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) {
21486 if (c !== 47 && c !== 92) {
21487 this.state = "authority";
21488 --this.pointer;
21489 } else {
21490 this.parseError = true;
21491 }
21492
21493 return true;
21494};
21495
21496URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) {
21497 if (c === 64) {
21498 this.parseError = true;
21499 if (this.atFlag) {
21500 this.buffer = "%40" + this.buffer;
21501 }
21502 this.atFlag = true;
21503
21504 // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars
21505 const len = countSymbols(this.buffer);
21506 for (let pointer = 0; pointer < len; ++pointer) {
21507 const codePoint = this.buffer.codePointAt(pointer);
21508
21509 if (codePoint === 58 && !this.passwordTokenSeenFlag) {
21510 this.passwordTokenSeenFlag = true;
21511 continue;
21512 }
21513 const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode);
21514 if (this.passwordTokenSeenFlag) {
21515 this.url.password += encodedCodePoints;
21516 } else {
21517 this.url.username += encodedCodePoints;
21518 }
21519 }
21520 this.buffer = "";
21521 } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
21522 (isSpecial(this.url) && c === 92)) {
21523 if (this.atFlag && this.buffer === "") {
21524 this.parseError = true;
21525 return failure;
21526 }
21527 this.pointer -= countSymbols(this.buffer) + 1;
21528 this.buffer = "";
21529 this.state = "host";
21530 } else {
21531 this.buffer += cStr;
21532 }
21533
21534 return true;
21535};
21536
21537URLStateMachine.prototype["parse hostname"] =
21538URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) {
21539 if (this.stateOverride && this.url.scheme === "file") {
21540 --this.pointer;
21541 this.state = "file host";
21542 } else if (c === 58 && !this.arrFlag) {
21543 if (this.buffer === "") {
21544 this.parseError = true;
21545 return failure;
21546 }
21547
21548 const host = parseHost(this.buffer, isNotSpecial(this.url));
21549 if (host === failure) {
21550 return failure;
21551 }
21552
21553 this.url.host = host;
21554 this.buffer = "";
21555 this.state = "port";
21556 if (this.stateOverride === "hostname") {
21557 return false;
21558 }
21559 } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
21560 (isSpecial(this.url) && c === 92)) {
21561 --this.pointer;
21562 if (isSpecial(this.url) && this.buffer === "") {
21563 this.parseError = true;
21564 return failure;
21565 } else if (this.stateOverride && this.buffer === "" &&
21566 (includesCredentials(this.url) || this.url.port !== null)) {
21567 this.parseError = true;
21568 return false;
21569 }
21570
21571 const host = parseHost(this.buffer, isNotSpecial(this.url));
21572 if (host === failure) {
21573 return failure;
21574 }
21575
21576 this.url.host = host;
21577 this.buffer = "";
21578 this.state = "path start";
21579 if (this.stateOverride) {
21580 return false;
21581 }
21582 } else {
21583 if (c === 91) {
21584 this.arrFlag = true;
21585 } else if (c === 93) {
21586 this.arrFlag = false;
21587 }
21588 this.buffer += cStr;
21589 }
21590
21591 return true;
21592};
21593
21594URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) {
21595 if (infra.isASCIIDigit(c)) {
21596 this.buffer += cStr;
21597 } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
21598 (isSpecial(this.url) && c === 92) ||
21599 this.stateOverride) {
21600 if (this.buffer !== "") {
21601 const port = parseInt(this.buffer);
21602 if (port > Math.pow(2, 16) - 1) {
21603 this.parseError = true;
21604 return failure;
21605 }
21606 this.url.port = port === defaultPort(this.url.scheme) ? null : port;
21607 this.buffer = "";
21608 }
21609 if (this.stateOverride) {
21610 return false;
21611 }
21612 this.state = "path start";
21613 --this.pointer;
21614 } else {
21615 this.parseError = true;
21616 return failure;
21617 }
21618
21619 return true;
21620};
21621
21622const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]);
21623
21624function startsWithWindowsDriveLetter(input, pointer) {
21625 const length = input.length - pointer;
21626 return length >= 2 &&
21627 isWindowsDriveLetterCodePoints(input[pointer], input[pointer + 1]) &&
21628 (length === 2 || fileOtherwiseCodePoints.has(input[pointer + 2]));
21629}
21630
21631URLStateMachine.prototype["parse file"] = function parseFile(c) {
21632 this.url.scheme = "file";
21633
21634 if (c === 47 || c === 92) {
21635 if (c === 92) {
21636 this.parseError = true;
21637 }
21638 this.state = "file slash";
21639 } else if (this.base !== null && this.base.scheme === "file") {
21640 if (isNaN(c)) {
21641 this.url.host = this.base.host;
21642 this.url.path = this.base.path.slice();
21643 this.url.query = this.base.query;
21644 } else if (c === 63) {
21645 this.url.host = this.base.host;
21646 this.url.path = this.base.path.slice();
21647 this.url.query = "";
21648 this.state = "query";
21649 } else if (c === 35) {
21650 this.url.host = this.base.host;
21651 this.url.path = this.base.path.slice();
21652 this.url.query = this.base.query;
21653 this.url.fragment = "";
21654 this.state = "fragment";
21655 } else {
21656 if (!startsWithWindowsDriveLetter(this.input, this.pointer)) {
21657 this.url.host = this.base.host;
21658 this.url.path = this.base.path.slice();
21659 shortenPath(this.url);
21660 } else {
21661 this.parseError = true;
21662 }
21663
21664 this.state = "path";
21665 --this.pointer;
21666 }
21667 } else {
21668 this.state = "path";
21669 --this.pointer;
21670 }
21671
21672 return true;
21673};
21674
21675URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) {
21676 if (c === 47 || c === 92) {
21677 if (c === 92) {
21678 this.parseError = true;
21679 }
21680 this.state = "file host";
21681 } else {
21682 if (this.base !== null && this.base.scheme === "file" &&
21683 !startsWithWindowsDriveLetter(this.input, this.pointer)) {
21684 if (isNormalizedWindowsDriveLetterString(this.base.path[0])) {
21685 this.url.path.push(this.base.path[0]);
21686 } else {
21687 this.url.host = this.base.host;
21688 }
21689 }
21690 this.state = "path";
21691 --this.pointer;
21692 }
21693
21694 return true;
21695};
21696
21697URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) {
21698 if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) {
21699 --this.pointer;
21700 if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {
21701 this.parseError = true;
21702 this.state = "path";
21703 } else if (this.buffer === "") {
21704 this.url.host = "";
21705 if (this.stateOverride) {
21706 return false;
21707 }
21708 this.state = "path start";
21709 } else {
21710 let host = parseHost(this.buffer, isNotSpecial(this.url));
21711 if (host === failure) {
21712 return failure;
21713 }
21714 if (host === "localhost") {
21715 host = "";
21716 }
21717 this.url.host = host;
21718
21719 if (this.stateOverride) {
21720 return false;
21721 }
21722
21723 this.buffer = "";
21724 this.state = "path start";
21725 }
21726 } else {
21727 this.buffer += cStr;
21728 }
21729
21730 return true;
21731};
21732
21733URLStateMachine.prototype["parse path start"] = function parsePathStart(c) {
21734 if (isSpecial(this.url)) {
21735 if (c === 92) {
21736 this.parseError = true;
21737 }
21738 this.state = "path";
21739
21740 if (c !== 47 && c !== 92) {
21741 --this.pointer;
21742 }
21743 } else if (!this.stateOverride && c === 63) {
21744 this.url.query = "";
21745 this.state = "query";
21746 } else if (!this.stateOverride && c === 35) {
21747 this.url.fragment = "";
21748 this.state = "fragment";
21749 } else if (c !== undefined) {
21750 this.state = "path";
21751 if (c !== 47) {
21752 --this.pointer;
21753 }
21754 }
21755
21756 return true;
21757};
21758
21759URLStateMachine.prototype["parse path"] = function parsePath(c) {
21760 if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) ||
21761 (!this.stateOverride && (c === 63 || c === 35))) {
21762 if (isSpecial(this.url) && c === 92) {
21763 this.parseError = true;
21764 }
21765
21766 if (isDoubleDot(this.buffer)) {
21767 shortenPath(this.url);
21768 if (c !== 47 && !(isSpecial(this.url) && c === 92)) {
21769 this.url.path.push("");
21770 }
21771 } else if (isSingleDot(this.buffer) && c !== 47 &&
21772 !(isSpecial(this.url) && c === 92)) {
21773 this.url.path.push("");
21774 } else if (!isSingleDot(this.buffer)) {
21775 if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) {
21776 if (this.url.host !== "" && this.url.host !== null) {
21777 this.parseError = true;
21778 this.url.host = "";
21779 }
21780 this.buffer = this.buffer[0] + ":";
21781 }
21782 this.url.path.push(this.buffer);
21783 }
21784 this.buffer = "";
21785 if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) {
21786 while (this.url.path.length > 1 && this.url.path[0] === "") {
21787 this.parseError = true;
21788 this.url.path.shift();
21789 }
21790 }
21791 if (c === 63) {
21792 this.url.query = "";
21793 this.state = "query";
21794 }
21795 if (c === 35) {
21796 this.url.fragment = "";
21797 this.state = "fragment";
21798 }
21799 } else {
21800 // TODO: If c is not a URL code point and not "%", parse error.
21801
21802 if (c === 37 &&
21803 (!infra.isASCIIHex(this.input[this.pointer + 1]) ||
21804 !infra.isASCIIHex(this.input[this.pointer + 2]))) {
21805 this.parseError = true;
21806 }
21807
21808 this.buffer += percentEncodeChar(c, isPathPercentEncode);
21809 }
21810
21811 return true;
21812};
21813
21814URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) {
21815 if (c === 63) {
21816 this.url.query = "";
21817 this.state = "query";
21818 } else if (c === 35) {
21819 this.url.fragment = "";
21820 this.state = "fragment";
21821 } else {
21822 // TODO: Add: not a URL code point
21823 if (!isNaN(c) && c !== 37) {
21824 this.parseError = true;
21825 }
21826
21827 if (c === 37 &&
21828 (!infra.isASCIIHex(this.input[this.pointer + 1]) ||
21829 !infra.isASCIIHex(this.input[this.pointer + 2]))) {
21830 this.parseError = true;
21831 }
21832
21833 if (!isNaN(c)) {
21834 this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode);
21835 }
21836 }
21837
21838 return true;
21839};
21840
21841URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) {
21842 if (isNaN(c) || (!this.stateOverride && c === 35)) {
21843 if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") {
21844 this.encodingOverride = "utf-8";
21845 }
21846
21847 const buffer = Buffer$1.from(this.buffer); // TODO: Use encoding override instead
21848 for (let i = 0; i < buffer.length; ++i) {
21849 if (buffer[i] < 0x21 ||
21850 buffer[i] > 0x7E ||
21851 buffer[i] === 0x22 || buffer[i] === 0x23 || buffer[i] === 0x3C || buffer[i] === 0x3E ||
21852 (buffer[i] === 0x27 && isSpecial(this.url))) {
21853 this.url.query += percentEncode(buffer[i]);
21854 } else {
21855 this.url.query += String.fromCodePoint(buffer[i]);
21856 }
21857 }
21858
21859 this.buffer = "";
21860 if (c === 35) {
21861 this.url.fragment = "";
21862 this.state = "fragment";
21863 }
21864 } else {
21865 // TODO: If c is not a URL code point and not "%", parse error.
21866 if (c === 37 &&
21867 (!infra.isASCIIHex(this.input[this.pointer + 1]) ||
21868 !infra.isASCIIHex(this.input[this.pointer + 2]))) {
21869 this.parseError = true;
21870 }
21871
21872 this.buffer += cStr;
21873 }
21874
21875 return true;
21876};
21877
21878URLStateMachine.prototype["parse fragment"] = function parseFragment(c) {
21879 if (isNaN(c)) ; else if (c === 0x0) {
21880 this.parseError = true;
21881 } else {
21882 // TODO: If c is not a URL code point and not "%", parse error.
21883 if (c === 37 &&
21884 (!infra.isASCIIHex(this.input[this.pointer + 1]) ||
21885 !infra.isASCIIHex(this.input[this.pointer + 2]))) {
21886 this.parseError = true;
21887 }
21888
21889 this.url.fragment += percentEncodeChar(c, isFragmentPercentEncode);
21890 }
21891
21892 return true;
21893};
21894
21895function serializeURL(url, excludeFragment) {
21896 let output = url.scheme + ":";
21897 if (url.host !== null) {
21898 output += "//";
21899
21900 if (url.username !== "" || url.password !== "") {
21901 output += url.username;
21902 if (url.password !== "") {
21903 output += ":" + url.password;
21904 }
21905 output += "@";
21906 }
21907
21908 output += serializeHost(url.host);
21909
21910 if (url.port !== null) {
21911 output += ":" + url.port;
21912 }
21913 } else if (url.host === null && url.scheme === "file") {
21914 output += "//";
21915 }
21916
21917 if (url.cannotBeABaseURL) {
21918 output += url.path[0];
21919 } else {
21920 for (const string of url.path) {
21921 output += "/" + string;
21922 }
21923 }
21924
21925 if (url.query !== null) {
21926 output += "?" + url.query;
21927 }
21928
21929 if (!excludeFragment && url.fragment !== null) {
21930 output += "#" + url.fragment;
21931 }
21932
21933 return output;
21934}
21935
21936function serializeOrigin(tuple) {
21937 let result = tuple.scheme + "://";
21938 result += serializeHost(tuple.host);
21939
21940 if (tuple.port !== null) {
21941 result += ":" + tuple.port;
21942 }
21943
21944 return result;
21945}
21946
21947module.exports.serializeURL = serializeURL;
21948
21949module.exports.serializeURLOrigin = function (url) {
21950 // https://url.spec.whatwg.org/#concept-url-origin
21951 switch (url.scheme) {
21952 case "blob":
21953 try {
21954 return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0]));
21955 } catch (e) {
21956 // serializing an opaque origin returns "null"
21957 return "null";
21958 }
21959 case "ftp":
21960 case "gopher":
21961 case "http":
21962 case "https":
21963 case "ws":
21964 case "wss":
21965 return serializeOrigin({
21966 scheme: url.scheme,
21967 host: url.host,
21968 port: url.port
21969 });
21970 case "file":
21971 // spec says "exercise to the reader", chrome says "file://"
21972 return "file://";
21973 default:
21974 // serializing an opaque origin returns "null"
21975 return "null";
21976 }
21977};
21978
21979module.exports.basicURLParse = function (input, options) {
21980 if (options === undefined) {
21981 options = {};
21982 }
21983
21984 const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride);
21985 if (usm.failure) {
21986 return null;
21987 }
21988
21989 return usm.url;
21990};
21991
21992module.exports.setTheUsername = function (url, username) {
21993 url.username = "";
21994 const decoded = punycode.ucs2.decode(username);
21995 for (let i = 0; i < decoded.length; ++i) {
21996 url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
21997 }
21998};
21999
22000module.exports.setThePassword = function (url, password) {
22001 url.password = "";
22002 const decoded = punycode.ucs2.decode(password);
22003 for (let i = 0; i < decoded.length; ++i) {
22004 url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
22005 }
22006};
22007
22008module.exports.serializeHost = serializeHost;
22009
22010module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort;
22011
22012module.exports.serializeInteger = function (integer) {
22013 return String(integer);
22014};
22015
22016module.exports.parseURL = function (input, options) {
22017 if (options === undefined) {
22018 options = {};
22019 }
22020
22021 // We don't handle blobs, so this just delegates:
22022 return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride });
22023};
22024});
22025var urlStateMachine_1 = urlStateMachine.serializeURL;
22026var urlStateMachine_2 = urlStateMachine.serializeURLOrigin;
22027var urlStateMachine_3 = urlStateMachine.basicURLParse;
22028var urlStateMachine_4 = urlStateMachine.setTheUsername;
22029var urlStateMachine_5 = urlStateMachine.setThePassword;
22030var urlStateMachine_6 = urlStateMachine.serializeHost;
22031var urlStateMachine_7 = urlStateMachine.cannotHaveAUsernamePasswordPort;
22032var urlStateMachine_8 = urlStateMachine.serializeInteger;
22033var urlStateMachine_9 = urlStateMachine.parseURL;
22034
22035var lodash_sortby = createCommonjsModule(function (module, exports) {
22036/**
22037 * lodash (Custom Build) <https://lodash.com/>
22038 * Build: `lodash modularize exports="npm" -o ./`
22039 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
22040 * Released under MIT license <https://lodash.com/license>
22041 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
22042 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
22043 */
22044
22045/** Used as the size to enable large array optimizations. */
22046var LARGE_ARRAY_SIZE = 200;
22047
22048/** Used as the `TypeError` message for "Functions" methods. */
22049var FUNC_ERROR_TEXT = 'Expected a function';
22050
22051/** Used to stand-in for `undefined` hash values. */
22052var HASH_UNDEFINED = '__lodash_hash_undefined__';
22053
22054/** Used to compose bitmasks for comparison styles. */
22055var UNORDERED_COMPARE_FLAG = 1,
22056 PARTIAL_COMPARE_FLAG = 2;
22057
22058/** Used as references for various `Number` constants. */
22059var INFINITY = 1 / 0,
22060 MAX_SAFE_INTEGER = 9007199254740991;
22061
22062/** `Object#toString` result references. */
22063var argsTag = '[object Arguments]',
22064 arrayTag = '[object Array]',
22065 boolTag = '[object Boolean]',
22066 dateTag = '[object Date]',
22067 errorTag = '[object Error]',
22068 funcTag = '[object Function]',
22069 genTag = '[object GeneratorFunction]',
22070 mapTag = '[object Map]',
22071 numberTag = '[object Number]',
22072 objectTag = '[object Object]',
22073 promiseTag = '[object Promise]',
22074 regexpTag = '[object RegExp]',
22075 setTag = '[object Set]',
22076 stringTag = '[object String]',
22077 symbolTag = '[object Symbol]',
22078 weakMapTag = '[object WeakMap]';
22079
22080var arrayBufferTag = '[object ArrayBuffer]',
22081 dataViewTag = '[object DataView]',
22082 float32Tag = '[object Float32Array]',
22083 float64Tag = '[object Float64Array]',
22084 int8Tag = '[object Int8Array]',
22085 int16Tag = '[object Int16Array]',
22086 int32Tag = '[object Int32Array]',
22087 uint8Tag = '[object Uint8Array]',
22088 uint8ClampedTag = '[object Uint8ClampedArray]',
22089 uint16Tag = '[object Uint16Array]',
22090 uint32Tag = '[object Uint32Array]';
22091
22092/** Used to match property names within property paths. */
22093var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
22094 reIsPlainProp = /^\w*$/,
22095 reLeadingDot = /^\./,
22096 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
22097
22098/**
22099 * Used to match `RegExp`
22100 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
22101 */
22102var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
22103
22104/** Used to match backslashes in property paths. */
22105var reEscapeChar = /\\(\\)?/g;
22106
22107/** Used to detect host constructors (Safari). */
22108var reIsHostCtor = /^\[object .+?Constructor\]$/;
22109
22110/** Used to detect unsigned integer values. */
22111var reIsUint = /^(?:0|[1-9]\d*)$/;
22112
22113/** Used to identify `toStringTag` values of typed arrays. */
22114var typedArrayTags = {};
22115typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
22116typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
22117typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
22118typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
22119typedArrayTags[uint32Tag] = true;
22120typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
22121typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
22122typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
22123typedArrayTags[errorTag] = typedArrayTags[funcTag] =
22124typedArrayTags[mapTag] = typedArrayTags[numberTag] =
22125typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
22126typedArrayTags[setTag] = typedArrayTags[stringTag] =
22127typedArrayTags[weakMapTag] = false;
22128
22129/** Detect free variable `global` from Node.js. */
22130var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
22131
22132/** Detect free variable `self`. */
22133var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
22134
22135/** Used as a reference to the global object. */
22136var root = freeGlobal || freeSelf || Function('return this')();
22137
22138/** Detect free variable `exports`. */
22139var freeExports = exports && !exports.nodeType && exports;
22140
22141/** Detect free variable `module`. */
22142var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
22143
22144/** Detect the popular CommonJS extension `module.exports`. */
22145var moduleExports = freeModule && freeModule.exports === freeExports;
22146
22147/** Detect free variable `process` from Node.js. */
22148var freeProcess = moduleExports && freeGlobal.process;
22149
22150/** Used to access faster Node.js helpers. */
22151var nodeUtil = (function() {
22152 try {
22153 return freeProcess && freeProcess.binding('util');
22154 } catch (e) {}
22155}());
22156
22157/* Node.js helper references. */
22158var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
22159
22160/**
22161 * A faster alternative to `Function#apply`, this function invokes `func`
22162 * with the `this` binding of `thisArg` and the arguments of `args`.
22163 *
22164 * @private
22165 * @param {Function} func The function to invoke.
22166 * @param {*} thisArg The `this` binding of `func`.
22167 * @param {Array} args The arguments to invoke `func` with.
22168 * @returns {*} Returns the result of `func`.
22169 */
22170function apply(func, thisArg, args) {
22171 switch (args.length) {
22172 case 0: return func.call(thisArg);
22173 case 1: return func.call(thisArg, args[0]);
22174 case 2: return func.call(thisArg, args[0], args[1]);
22175 case 3: return func.call(thisArg, args[0], args[1], args[2]);
22176 }
22177 return func.apply(thisArg, args);
22178}
22179
22180/**
22181 * A specialized version of `_.map` for arrays without support for iteratee
22182 * shorthands.
22183 *
22184 * @private
22185 * @param {Array} [array] The array to iterate over.
22186 * @param {Function} iteratee The function invoked per iteration.
22187 * @returns {Array} Returns the new mapped array.
22188 */
22189function arrayMap(array, iteratee) {
22190 var index = -1,
22191 length = array ? array.length : 0,
22192 result = Array(length);
22193
22194 while (++index < length) {
22195 result[index] = iteratee(array[index], index, array);
22196 }
22197 return result;
22198}
22199
22200/**
22201 * Appends the elements of `values` to `array`.
22202 *
22203 * @private
22204 * @param {Array} array The array to modify.
22205 * @param {Array} values The values to append.
22206 * @returns {Array} Returns `array`.
22207 */
22208function arrayPush(array, values) {
22209 var index = -1,
22210 length = values.length,
22211 offset = array.length;
22212
22213 while (++index < length) {
22214 array[offset + index] = values[index];
22215 }
22216 return array;
22217}
22218
22219/**
22220 * A specialized version of `_.some` for arrays without support for iteratee
22221 * shorthands.
22222 *
22223 * @private
22224 * @param {Array} [array] The array to iterate over.
22225 * @param {Function} predicate The function invoked per iteration.
22226 * @returns {boolean} Returns `true` if any element passes the predicate check,
22227 * else `false`.
22228 */
22229function arraySome(array, predicate) {
22230 var index = -1,
22231 length = array ? array.length : 0;
22232
22233 while (++index < length) {
22234 if (predicate(array[index], index, array)) {
22235 return true;
22236 }
22237 }
22238 return false;
22239}
22240
22241/**
22242 * The base implementation of `_.property` without support for deep paths.
22243 *
22244 * @private
22245 * @param {string} key The key of the property to get.
22246 * @returns {Function} Returns the new accessor function.
22247 */
22248function baseProperty(key) {
22249 return function(object) {
22250 return object == null ? undefined : object[key];
22251 };
22252}
22253
22254/**
22255 * The base implementation of `_.sortBy` which uses `comparer` to define the
22256 * sort order of `array` and replaces criteria objects with their corresponding
22257 * values.
22258 *
22259 * @private
22260 * @param {Array} array The array to sort.
22261 * @param {Function} comparer The function to define sort order.
22262 * @returns {Array} Returns `array`.
22263 */
22264function baseSortBy(array, comparer) {
22265 var length = array.length;
22266
22267 array.sort(comparer);
22268 while (length--) {
22269 array[length] = array[length].value;
22270 }
22271 return array;
22272}
22273
22274/**
22275 * The base implementation of `_.times` without support for iteratee shorthands
22276 * or max array length checks.
22277 *
22278 * @private
22279 * @param {number} n The number of times to invoke `iteratee`.
22280 * @param {Function} iteratee The function invoked per iteration.
22281 * @returns {Array} Returns the array of results.
22282 */
22283function baseTimes(n, iteratee) {
22284 var index = -1,
22285 result = Array(n);
22286
22287 while (++index < n) {
22288 result[index] = iteratee(index);
22289 }
22290 return result;
22291}
22292
22293/**
22294 * The base implementation of `_.unary` without support for storing metadata.
22295 *
22296 * @private
22297 * @param {Function} func The function to cap arguments for.
22298 * @returns {Function} Returns the new capped function.
22299 */
22300function baseUnary(func) {
22301 return function(value) {
22302 return func(value);
22303 };
22304}
22305
22306/**
22307 * Gets the value at `key` of `object`.
22308 *
22309 * @private
22310 * @param {Object} [object] The object to query.
22311 * @param {string} key The key of the property to get.
22312 * @returns {*} Returns the property value.
22313 */
22314function getValue(object, key) {
22315 return object == null ? undefined : object[key];
22316}
22317
22318/**
22319 * Checks if `value` is a host object in IE < 9.
22320 *
22321 * @private
22322 * @param {*} value The value to check.
22323 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
22324 */
22325function isHostObject(value) {
22326 // Many host objects are `Object` objects that can coerce to strings
22327 // despite having improperly defined `toString` methods.
22328 var result = false;
22329 if (value != null && typeof value.toString != 'function') {
22330 try {
22331 result = !!(value + '');
22332 } catch (e) {}
22333 }
22334 return result;
22335}
22336
22337/**
22338 * Converts `map` to its key-value pairs.
22339 *
22340 * @private
22341 * @param {Object} map The map to convert.
22342 * @returns {Array} Returns the key-value pairs.
22343 */
22344function mapToArray(map) {
22345 var index = -1,
22346 result = Array(map.size);
22347
22348 map.forEach(function(value, key) {
22349 result[++index] = [key, value];
22350 });
22351 return result;
22352}
22353
22354/**
22355 * Creates a unary function that invokes `func` with its argument transformed.
22356 *
22357 * @private
22358 * @param {Function} func The function to wrap.
22359 * @param {Function} transform The argument transform.
22360 * @returns {Function} Returns the new function.
22361 */
22362function overArg(func, transform) {
22363 return function(arg) {
22364 return func(transform(arg));
22365 };
22366}
22367
22368/**
22369 * Converts `set` to an array of its values.
22370 *
22371 * @private
22372 * @param {Object} set The set to convert.
22373 * @returns {Array} Returns the values.
22374 */
22375function setToArray(set) {
22376 var index = -1,
22377 result = Array(set.size);
22378
22379 set.forEach(function(value) {
22380 result[++index] = value;
22381 });
22382 return result;
22383}
22384
22385/** Used for built-in method references. */
22386var arrayProto = Array.prototype,
22387 funcProto = Function.prototype,
22388 objectProto = Object.prototype;
22389
22390/** Used to detect overreaching core-js shims. */
22391var coreJsData = root['__core-js_shared__'];
22392
22393/** Used to detect methods masquerading as native. */
22394var maskSrcKey = (function() {
22395 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
22396 return uid ? ('Symbol(src)_1.' + uid) : '';
22397}());
22398
22399/** Used to resolve the decompiled source of functions. */
22400var funcToString = funcProto.toString;
22401
22402/** Used to check objects for own properties. */
22403var hasOwnProperty = objectProto.hasOwnProperty;
22404
22405/**
22406 * Used to resolve the
22407 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
22408 * of values.
22409 */
22410var objectToString = objectProto.toString;
22411
22412/** Used to detect if a method is native. */
22413var reIsNative = RegExp('^' +
22414 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
22415 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
22416);
22417
22418/** Built-in value references. */
22419var Symbol = root.Symbol,
22420 Uint8Array = root.Uint8Array,
22421 propertyIsEnumerable = objectProto.propertyIsEnumerable,
22422 splice = arrayProto.splice,
22423 spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
22424
22425/* Built-in method references for those with the same name as other `lodash` methods. */
22426var nativeKeys = overArg(Object.keys, Object),
22427 nativeMax = Math.max;
22428
22429/* Built-in method references that are verified to be native. */
22430var DataView = getNative(root, 'DataView'),
22431 Map = getNative(root, 'Map'),
22432 Promise = getNative(root, 'Promise'),
22433 Set = getNative(root, 'Set'),
22434 WeakMap = getNative(root, 'WeakMap'),
22435 nativeCreate = getNative(Object, 'create');
22436
22437/** Used to detect maps, sets, and weakmaps. */
22438var dataViewCtorString = toSource(DataView),
22439 mapCtorString = toSource(Map),
22440 promiseCtorString = toSource(Promise),
22441 setCtorString = toSource(Set),
22442 weakMapCtorString = toSource(WeakMap);
22443
22444/** Used to convert symbols to primitives and strings. */
22445var symbolProto = Symbol ? Symbol.prototype : undefined,
22446 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
22447 symbolToString = symbolProto ? symbolProto.toString : undefined;
22448
22449/**
22450 * Creates a hash object.
22451 *
22452 * @private
22453 * @constructor
22454 * @param {Array} [entries] The key-value pairs to cache.
22455 */
22456function Hash(entries) {
22457 var index = -1,
22458 length = entries ? entries.length : 0;
22459
22460 this.clear();
22461 while (++index < length) {
22462 var entry = entries[index];
22463 this.set(entry[0], entry[1]);
22464 }
22465}
22466
22467/**
22468 * Removes all key-value entries from the hash.
22469 *
22470 * @private
22471 * @name clear
22472 * @memberOf Hash
22473 */
22474function hashClear() {
22475 this.__data__ = nativeCreate ? nativeCreate(null) : {};
22476}
22477
22478/**
22479 * Removes `key` and its value from the hash.
22480 *
22481 * @private
22482 * @name delete
22483 * @memberOf Hash
22484 * @param {Object} hash The hash to modify.
22485 * @param {string} key The key of the value to remove.
22486 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
22487 */
22488function hashDelete(key) {
22489 return this.has(key) && delete this.__data__[key];
22490}
22491
22492/**
22493 * Gets the hash value for `key`.
22494 *
22495 * @private
22496 * @name get
22497 * @memberOf Hash
22498 * @param {string} key The key of the value to get.
22499 * @returns {*} Returns the entry value.
22500 */
22501function hashGet(key) {
22502 var data = this.__data__;
22503 if (nativeCreate) {
22504 var result = data[key];
22505 return result === HASH_UNDEFINED ? undefined : result;
22506 }
22507 return hasOwnProperty.call(data, key) ? data[key] : undefined;
22508}
22509
22510/**
22511 * Checks if a hash value for `key` exists.
22512 *
22513 * @private
22514 * @name has
22515 * @memberOf Hash
22516 * @param {string} key The key of the entry to check.
22517 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
22518 */
22519function hashHas(key) {
22520 var data = this.__data__;
22521 return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
22522}
22523
22524/**
22525 * Sets the hash `key` to `value`.
22526 *
22527 * @private
22528 * @name set
22529 * @memberOf Hash
22530 * @param {string} key The key of the value to set.
22531 * @param {*} value The value to set.
22532 * @returns {Object} Returns the hash instance.
22533 */
22534function hashSet(key, value) {
22535 var data = this.__data__;
22536 data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
22537 return this;
22538}
22539
22540// Add methods to `Hash`.
22541Hash.prototype.clear = hashClear;
22542Hash.prototype['delete'] = hashDelete;
22543Hash.prototype.get = hashGet;
22544Hash.prototype.has = hashHas;
22545Hash.prototype.set = hashSet;
22546
22547/**
22548 * Creates an list cache object.
22549 *
22550 * @private
22551 * @constructor
22552 * @param {Array} [entries] The key-value pairs to cache.
22553 */
22554function ListCache(entries) {
22555 var index = -1,
22556 length = entries ? entries.length : 0;
22557
22558 this.clear();
22559 while (++index < length) {
22560 var entry = entries[index];
22561 this.set(entry[0], entry[1]);
22562 }
22563}
22564
22565/**
22566 * Removes all key-value entries from the list cache.
22567 *
22568 * @private
22569 * @name clear
22570 * @memberOf ListCache
22571 */
22572function listCacheClear() {
22573 this.__data__ = [];
22574}
22575
22576/**
22577 * Removes `key` and its value from the list cache.
22578 *
22579 * @private
22580 * @name delete
22581 * @memberOf ListCache
22582 * @param {string} key The key of the value to remove.
22583 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
22584 */
22585function listCacheDelete(key) {
22586 var data = this.__data__,
22587 index = assocIndexOf(data, key);
22588
22589 if (index < 0) {
22590 return false;
22591 }
22592 var lastIndex = data.length - 1;
22593 if (index == lastIndex) {
22594 data.pop();
22595 } else {
22596 splice.call(data, index, 1);
22597 }
22598 return true;
22599}
22600
22601/**
22602 * Gets the list cache value for `key`.
22603 *
22604 * @private
22605 * @name get
22606 * @memberOf ListCache
22607 * @param {string} key The key of the value to get.
22608 * @returns {*} Returns the entry value.
22609 */
22610function listCacheGet(key) {
22611 var data = this.__data__,
22612 index = assocIndexOf(data, key);
22613
22614 return index < 0 ? undefined : data[index][1];
22615}
22616
22617/**
22618 * Checks if a list cache value for `key` exists.
22619 *
22620 * @private
22621 * @name has
22622 * @memberOf ListCache
22623 * @param {string} key The key of the entry to check.
22624 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
22625 */
22626function listCacheHas(key) {
22627 return assocIndexOf(this.__data__, key) > -1;
22628}
22629
22630/**
22631 * Sets the list cache `key` to `value`.
22632 *
22633 * @private
22634 * @name set
22635 * @memberOf ListCache
22636 * @param {string} key The key of the value to set.
22637 * @param {*} value The value to set.
22638 * @returns {Object} Returns the list cache instance.
22639 */
22640function listCacheSet(key, value) {
22641 var data = this.__data__,
22642 index = assocIndexOf(data, key);
22643
22644 if (index < 0) {
22645 data.push([key, value]);
22646 } else {
22647 data[index][1] = value;
22648 }
22649 return this;
22650}
22651
22652// Add methods to `ListCache`.
22653ListCache.prototype.clear = listCacheClear;
22654ListCache.prototype['delete'] = listCacheDelete;
22655ListCache.prototype.get = listCacheGet;
22656ListCache.prototype.has = listCacheHas;
22657ListCache.prototype.set = listCacheSet;
22658
22659/**
22660 * Creates a map cache object to store key-value pairs.
22661 *
22662 * @private
22663 * @constructor
22664 * @param {Array} [entries] The key-value pairs to cache.
22665 */
22666function MapCache(entries) {
22667 var index = -1,
22668 length = entries ? entries.length : 0;
22669
22670 this.clear();
22671 while (++index < length) {
22672 var entry = entries[index];
22673 this.set(entry[0], entry[1]);
22674 }
22675}
22676
22677/**
22678 * Removes all key-value entries from the map.
22679 *
22680 * @private
22681 * @name clear
22682 * @memberOf MapCache
22683 */
22684function mapCacheClear() {
22685 this.__data__ = {
22686 'hash': new Hash,
22687 'map': new (Map || ListCache),
22688 'string': new Hash
22689 };
22690}
22691
22692/**
22693 * Removes `key` and its value from the map.
22694 *
22695 * @private
22696 * @name delete
22697 * @memberOf MapCache
22698 * @param {string} key The key of the value to remove.
22699 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
22700 */
22701function mapCacheDelete(key) {
22702 return getMapData(this, key)['delete'](key);
22703}
22704
22705/**
22706 * Gets the map value for `key`.
22707 *
22708 * @private
22709 * @name get
22710 * @memberOf MapCache
22711 * @param {string} key The key of the value to get.
22712 * @returns {*} Returns the entry value.
22713 */
22714function mapCacheGet(key) {
22715 return getMapData(this, key).get(key);
22716}
22717
22718/**
22719 * Checks if a map value for `key` exists.
22720 *
22721 * @private
22722 * @name has
22723 * @memberOf MapCache
22724 * @param {string} key The key of the entry to check.
22725 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
22726 */
22727function mapCacheHas(key) {
22728 return getMapData(this, key).has(key);
22729}
22730
22731/**
22732 * Sets the map `key` to `value`.
22733 *
22734 * @private
22735 * @name set
22736 * @memberOf MapCache
22737 * @param {string} key The key of the value to set.
22738 * @param {*} value The value to set.
22739 * @returns {Object} Returns the map cache instance.
22740 */
22741function mapCacheSet(key, value) {
22742 getMapData(this, key).set(key, value);
22743 return this;
22744}
22745
22746// Add methods to `MapCache`.
22747MapCache.prototype.clear = mapCacheClear;
22748MapCache.prototype['delete'] = mapCacheDelete;
22749MapCache.prototype.get = mapCacheGet;
22750MapCache.prototype.has = mapCacheHas;
22751MapCache.prototype.set = mapCacheSet;
22752
22753/**
22754 *
22755 * Creates an array cache object to store unique values.
22756 *
22757 * @private
22758 * @constructor
22759 * @param {Array} [values] The values to cache.
22760 */
22761function SetCache(values) {
22762 var index = -1,
22763 length = values ? values.length : 0;
22764
22765 this.__data__ = new MapCache;
22766 while (++index < length) {
22767 this.add(values[index]);
22768 }
22769}
22770
22771/**
22772 * Adds `value` to the array cache.
22773 *
22774 * @private
22775 * @name add
22776 * @memberOf SetCache
22777 * @alias push
22778 * @param {*} value The value to cache.
22779 * @returns {Object} Returns the cache instance.
22780 */
22781function setCacheAdd(value) {
22782 this.__data__.set(value, HASH_UNDEFINED);
22783 return this;
22784}
22785
22786/**
22787 * Checks if `value` is in the array cache.
22788 *
22789 * @private
22790 * @name has
22791 * @memberOf SetCache
22792 * @param {*} value The value to search for.
22793 * @returns {number} Returns `true` if `value` is found, else `false`.
22794 */
22795function setCacheHas(value) {
22796 return this.__data__.has(value);
22797}
22798
22799// Add methods to `SetCache`.
22800SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
22801SetCache.prototype.has = setCacheHas;
22802
22803/**
22804 * Creates a stack cache object to store key-value pairs.
22805 *
22806 * @private
22807 * @constructor
22808 * @param {Array} [entries] The key-value pairs to cache.
22809 */
22810function Stack(entries) {
22811 this.__data__ = new ListCache(entries);
22812}
22813
22814/**
22815 * Removes all key-value entries from the stack.
22816 *
22817 * @private
22818 * @name clear
22819 * @memberOf Stack
22820 */
22821function stackClear() {
22822 this.__data__ = new ListCache;
22823}
22824
22825/**
22826 * Removes `key` and its value from the stack.
22827 *
22828 * @private
22829 * @name delete
22830 * @memberOf Stack
22831 * @param {string} key The key of the value to remove.
22832 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
22833 */
22834function stackDelete(key) {
22835 return this.__data__['delete'](key);
22836}
22837
22838/**
22839 * Gets the stack value for `key`.
22840 *
22841 * @private
22842 * @name get
22843 * @memberOf Stack
22844 * @param {string} key The key of the value to get.
22845 * @returns {*} Returns the entry value.
22846 */
22847function stackGet(key) {
22848 return this.__data__.get(key);
22849}
22850
22851/**
22852 * Checks if a stack value for `key` exists.
22853 *
22854 * @private
22855 * @name has
22856 * @memberOf Stack
22857 * @param {string} key The key of the entry to check.
22858 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
22859 */
22860function stackHas(key) {
22861 return this.__data__.has(key);
22862}
22863
22864/**
22865 * Sets the stack `key` to `value`.
22866 *
22867 * @private
22868 * @name set
22869 * @memberOf Stack
22870 * @param {string} key The key of the value to set.
22871 * @param {*} value The value to set.
22872 * @returns {Object} Returns the stack cache instance.
22873 */
22874function stackSet(key, value) {
22875 var cache = this.__data__;
22876 if (cache instanceof ListCache) {
22877 var pairs = cache.__data__;
22878 if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
22879 pairs.push([key, value]);
22880 return this;
22881 }
22882 cache = this.__data__ = new MapCache(pairs);
22883 }
22884 cache.set(key, value);
22885 return this;
22886}
22887
22888// Add methods to `Stack`.
22889Stack.prototype.clear = stackClear;
22890Stack.prototype['delete'] = stackDelete;
22891Stack.prototype.get = stackGet;
22892Stack.prototype.has = stackHas;
22893Stack.prototype.set = stackSet;
22894
22895/**
22896 * Creates an array of the enumerable property names of the array-like `value`.
22897 *
22898 * @private
22899 * @param {*} value The value to query.
22900 * @param {boolean} inherited Specify returning inherited property names.
22901 * @returns {Array} Returns the array of property names.
22902 */
22903function arrayLikeKeys(value, inherited) {
22904 // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
22905 // Safari 9 makes `arguments.length` enumerable in strict mode.
22906 var result = (isArray(value) || isArguments(value))
22907 ? baseTimes(value.length, String)
22908 : [];
22909
22910 var length = result.length,
22911 skipIndexes = !!length;
22912
22913 for (var key in value) {
22914 if ((inherited || hasOwnProperty.call(value, key)) &&
22915 !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
22916 result.push(key);
22917 }
22918 }
22919 return result;
22920}
22921
22922/**
22923 * Gets the index at which the `key` is found in `array` of key-value pairs.
22924 *
22925 * @private
22926 * @param {Array} array The array to inspect.
22927 * @param {*} key The key to search for.
22928 * @returns {number} Returns the index of the matched value, else `-1`.
22929 */
22930function assocIndexOf(array, key) {
22931 var length = array.length;
22932 while (length--) {
22933 if (eq(array[length][0], key)) {
22934 return length;
22935 }
22936 }
22937 return -1;
22938}
22939
22940/**
22941 * The base implementation of `_.forEach` without support for iteratee shorthands.
22942 *
22943 * @private
22944 * @param {Array|Object} collection The collection to iterate over.
22945 * @param {Function} iteratee The function invoked per iteration.
22946 * @returns {Array|Object} Returns `collection`.
22947 */
22948var baseEach = createBaseEach(baseForOwn);
22949
22950/**
22951 * The base implementation of `_.flatten` with support for restricting flattening.
22952 *
22953 * @private
22954 * @param {Array} array The array to flatten.
22955 * @param {number} depth The maximum recursion depth.
22956 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
22957 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
22958 * @param {Array} [result=[]] The initial result value.
22959 * @returns {Array} Returns the new flattened array.
22960 */
22961function baseFlatten(array, depth, predicate, isStrict, result) {
22962 var index = -1,
22963 length = array.length;
22964
22965 predicate || (predicate = isFlattenable);
22966 result || (result = []);
22967
22968 while (++index < length) {
22969 var value = array[index];
22970 if (depth > 0 && predicate(value)) {
22971 if (depth > 1) {
22972 // Recursively flatten arrays (susceptible to call stack limits).
22973 baseFlatten(value, depth - 1, predicate, isStrict, result);
22974 } else {
22975 arrayPush(result, value);
22976 }
22977 } else if (!isStrict) {
22978 result[result.length] = value;
22979 }
22980 }
22981 return result;
22982}
22983
22984/**
22985 * The base implementation of `baseForOwn` which iterates over `object`
22986 * properties returned by `keysFunc` and invokes `iteratee` for each property.
22987 * Iteratee functions may exit iteration early by explicitly returning `false`.
22988 *
22989 * @private
22990 * @param {Object} object The object to iterate over.
22991 * @param {Function} iteratee The function invoked per iteration.
22992 * @param {Function} keysFunc The function to get the keys of `object`.
22993 * @returns {Object} Returns `object`.
22994 */
22995var baseFor = createBaseFor();
22996
22997/**
22998 * The base implementation of `_.forOwn` without support for iteratee shorthands.
22999 *
23000 * @private
23001 * @param {Object} object The object to iterate over.
23002 * @param {Function} iteratee The function invoked per iteration.
23003 * @returns {Object} Returns `object`.
23004 */
23005function baseForOwn(object, iteratee) {
23006 return object && baseFor(object, iteratee, keys);
23007}
23008
23009/**
23010 * The base implementation of `_.get` without support for default values.
23011 *
23012 * @private
23013 * @param {Object} object The object to query.
23014 * @param {Array|string} path The path of the property to get.
23015 * @returns {*} Returns the resolved value.
23016 */
23017function baseGet(object, path) {
23018 path = isKey(path, object) ? [path] : castPath(path);
23019
23020 var index = 0,
23021 length = path.length;
23022
23023 while (object != null && index < length) {
23024 object = object[toKey(path[index++])];
23025 }
23026 return (index && index == length) ? object : undefined;
23027}
23028
23029/**
23030 * The base implementation of `getTag`.
23031 *
23032 * @private
23033 * @param {*} value The value to query.
23034 * @returns {string} Returns the `toStringTag`.
23035 */
23036function baseGetTag(value) {
23037 return objectToString.call(value);
23038}
23039
23040/**
23041 * The base implementation of `_.hasIn` without support for deep paths.
23042 *
23043 * @private
23044 * @param {Object} [object] The object to query.
23045 * @param {Array|string} key The key to check.
23046 * @returns {boolean} Returns `true` if `key` exists, else `false`.
23047 */
23048function baseHasIn(object, key) {
23049 return object != null && key in Object(object);
23050}
23051
23052/**
23053 * The base implementation of `_.isEqual` which supports partial comparisons
23054 * and tracks traversed objects.
23055 *
23056 * @private
23057 * @param {*} value The value to compare.
23058 * @param {*} other The other value to compare.
23059 * @param {Function} [customizer] The function to customize comparisons.
23060 * @param {boolean} [bitmask] The bitmask of comparison flags.
23061 * The bitmask may be composed of the following flags:
23062 * 1 - Unordered comparison
23063 * 2 - Partial comparison
23064 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
23065 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
23066 */
23067function baseIsEqual(value, other, customizer, bitmask, stack) {
23068 if (value === other) {
23069 return true;
23070 }
23071 if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
23072 return value !== value && other !== other;
23073 }
23074 return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
23075}
23076
23077/**
23078 * A specialized version of `baseIsEqual` for arrays and objects which performs
23079 * deep comparisons and tracks traversed objects enabling objects with circular
23080 * references to be compared.
23081 *
23082 * @private
23083 * @param {Object} object The object to compare.
23084 * @param {Object} other The other object to compare.
23085 * @param {Function} equalFunc The function to determine equivalents of values.
23086 * @param {Function} [customizer] The function to customize comparisons.
23087 * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
23088 * for more details.
23089 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
23090 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
23091 */
23092function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
23093 var objIsArr = isArray(object),
23094 othIsArr = isArray(other),
23095 objTag = arrayTag,
23096 othTag = arrayTag;
23097
23098 if (!objIsArr) {
23099 objTag = getTag(object);
23100 objTag = objTag == argsTag ? objectTag : objTag;
23101 }
23102 if (!othIsArr) {
23103 othTag = getTag(other);
23104 othTag = othTag == argsTag ? objectTag : othTag;
23105 }
23106 var objIsObj = objTag == objectTag && !isHostObject(object),
23107 othIsObj = othTag == objectTag && !isHostObject(other),
23108 isSameTag = objTag == othTag;
23109
23110 if (isSameTag && !objIsObj) {
23111 stack || (stack = new Stack);
23112 return (objIsArr || isTypedArray(object))
23113 ? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
23114 : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
23115 }
23116 if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
23117 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
23118 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
23119
23120 if (objIsWrapped || othIsWrapped) {
23121 var objUnwrapped = objIsWrapped ? object.value() : object,
23122 othUnwrapped = othIsWrapped ? other.value() : other;
23123
23124 stack || (stack = new Stack);
23125 return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
23126 }
23127 }
23128 if (!isSameTag) {
23129 return false;
23130 }
23131 stack || (stack = new Stack);
23132 return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
23133}
23134
23135/**
23136 * The base implementation of `_.isMatch` without support for iteratee shorthands.
23137 *
23138 * @private
23139 * @param {Object} object The object to inspect.
23140 * @param {Object} source The object of property values to match.
23141 * @param {Array} matchData The property names, values, and compare flags to match.
23142 * @param {Function} [customizer] The function to customize comparisons.
23143 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
23144 */
23145function baseIsMatch(object, source, matchData, customizer) {
23146 var index = matchData.length,
23147 length = index,
23148 noCustomizer = !customizer;
23149
23150 if (object == null) {
23151 return !length;
23152 }
23153 object = Object(object);
23154 while (index--) {
23155 var data = matchData[index];
23156 if ((noCustomizer && data[2])
23157 ? data[1] !== object[data[0]]
23158 : !(data[0] in object)
23159 ) {
23160 return false;
23161 }
23162 }
23163 while (++index < length) {
23164 data = matchData[index];
23165 var key = data[0],
23166 objValue = object[key],
23167 srcValue = data[1];
23168
23169 if (noCustomizer && data[2]) {
23170 if (objValue === undefined && !(key in object)) {
23171 return false;
23172 }
23173 } else {
23174 var stack = new Stack;
23175 if (customizer) {
23176 var result = customizer(objValue, srcValue, key, object, source, stack);
23177 }
23178 if (!(result === undefined
23179 ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
23180 : result
23181 )) {
23182 return false;
23183 }
23184 }
23185 }
23186 return true;
23187}
23188
23189/**
23190 * The base implementation of `_.isNative` without bad shim checks.
23191 *
23192 * @private
23193 * @param {*} value The value to check.
23194 * @returns {boolean} Returns `true` if `value` is a native function,
23195 * else `false`.
23196 */
23197function baseIsNative(value) {
23198 if (!isObject(value) || isMasked(value)) {
23199 return false;
23200 }
23201 var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
23202 return pattern.test(toSource(value));
23203}
23204
23205/**
23206 * The base implementation of `_.isTypedArray` without Node.js optimizations.
23207 *
23208 * @private
23209 * @param {*} value The value to check.
23210 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
23211 */
23212function baseIsTypedArray(value) {
23213 return isObjectLike(value) &&
23214 isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
23215}
23216
23217/**
23218 * The base implementation of `_.iteratee`.
23219 *
23220 * @private
23221 * @param {*} [value=_.identity] The value to convert to an iteratee.
23222 * @returns {Function} Returns the iteratee.
23223 */
23224function baseIteratee(value) {
23225 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
23226 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
23227 if (typeof value == 'function') {
23228 return value;
23229 }
23230 if (value == null) {
23231 return identity;
23232 }
23233 if (typeof value == 'object') {
23234 return isArray(value)
23235 ? baseMatchesProperty(value[0], value[1])
23236 : baseMatches(value);
23237 }
23238 return property(value);
23239}
23240
23241/**
23242 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
23243 *
23244 * @private
23245 * @param {Object} object The object to query.
23246 * @returns {Array} Returns the array of property names.
23247 */
23248function baseKeys(object) {
23249 if (!isPrototype(object)) {
23250 return nativeKeys(object);
23251 }
23252 var result = [];
23253 for (var key in Object(object)) {
23254 if (hasOwnProperty.call(object, key) && key != 'constructor') {
23255 result.push(key);
23256 }
23257 }
23258 return result;
23259}
23260
23261/**
23262 * The base implementation of `_.map` without support for iteratee shorthands.
23263 *
23264 * @private
23265 * @param {Array|Object} collection The collection to iterate over.
23266 * @param {Function} iteratee The function invoked per iteration.
23267 * @returns {Array} Returns the new mapped array.
23268 */
23269function baseMap(collection, iteratee) {
23270 var index = -1,
23271 result = isArrayLike(collection) ? Array(collection.length) : [];
23272
23273 baseEach(collection, function(value, key, collection) {
23274 result[++index] = iteratee(value, key, collection);
23275 });
23276 return result;
23277}
23278
23279/**
23280 * The base implementation of `_.matches` which doesn't clone `source`.
23281 *
23282 * @private
23283 * @param {Object} source The object of property values to match.
23284 * @returns {Function} Returns the new spec function.
23285 */
23286function baseMatches(source) {
23287 var matchData = getMatchData(source);
23288 if (matchData.length == 1 && matchData[0][2]) {
23289 return matchesStrictComparable(matchData[0][0], matchData[0][1]);
23290 }
23291 return function(object) {
23292 return object === source || baseIsMatch(object, source, matchData);
23293 };
23294}
23295
23296/**
23297 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
23298 *
23299 * @private
23300 * @param {string} path The path of the property to get.
23301 * @param {*} srcValue The value to match.
23302 * @returns {Function} Returns the new spec function.
23303 */
23304function baseMatchesProperty(path, srcValue) {
23305 if (isKey(path) && isStrictComparable(srcValue)) {
23306 return matchesStrictComparable(toKey(path), srcValue);
23307 }
23308 return function(object) {
23309 var objValue = get(object, path);
23310 return (objValue === undefined && objValue === srcValue)
23311 ? hasIn(object, path)
23312 : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
23313 };
23314}
23315
23316/**
23317 * The base implementation of `_.orderBy` without param guards.
23318 *
23319 * @private
23320 * @param {Array|Object} collection The collection to iterate over.
23321 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
23322 * @param {string[]} orders The sort orders of `iteratees`.
23323 * @returns {Array} Returns the new sorted array.
23324 */
23325function baseOrderBy(collection, iteratees, orders) {
23326 var index = -1;
23327 iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee));
23328
23329 var result = baseMap(collection, function(value, key, collection) {
23330 var criteria = arrayMap(iteratees, function(iteratee) {
23331 return iteratee(value);
23332 });
23333 return { 'criteria': criteria, 'index': ++index, 'value': value };
23334 });
23335
23336 return baseSortBy(result, function(object, other) {
23337 return compareMultiple(object, other, orders);
23338 });
23339}
23340
23341/**
23342 * A specialized version of `baseProperty` which supports deep paths.
23343 *
23344 * @private
23345 * @param {Array|string} path The path of the property to get.
23346 * @returns {Function} Returns the new accessor function.
23347 */
23348function basePropertyDeep(path) {
23349 return function(object) {
23350 return baseGet(object, path);
23351 };
23352}
23353
23354/**
23355 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
23356 *
23357 * @private
23358 * @param {Function} func The function to apply a rest parameter to.
23359 * @param {number} [start=func.length-1] The start position of the rest parameter.
23360 * @returns {Function} Returns the new function.
23361 */
23362function baseRest(func, start) {
23363 start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
23364 return function() {
23365 var args = arguments,
23366 index = -1,
23367 length = nativeMax(args.length - start, 0),
23368 array = Array(length);
23369
23370 while (++index < length) {
23371 array[index] = args[start + index];
23372 }
23373 index = -1;
23374 var otherArgs = Array(start + 1);
23375 while (++index < start) {
23376 otherArgs[index] = args[index];
23377 }
23378 otherArgs[start] = array;
23379 return apply(func, this, otherArgs);
23380 };
23381}
23382
23383/**
23384 * The base implementation of `_.toString` which doesn't convert nullish
23385 * values to empty strings.
23386 *
23387 * @private
23388 * @param {*} value The value to process.
23389 * @returns {string} Returns the string.
23390 */
23391function baseToString(value) {
23392 // Exit early for strings to avoid a performance hit in some environments.
23393 if (typeof value == 'string') {
23394 return value;
23395 }
23396 if (isSymbol(value)) {
23397 return symbolToString ? symbolToString.call(value) : '';
23398 }
23399 var result = (value + '');
23400 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
23401}
23402
23403/**
23404 * Casts `value` to a path array if it's not one.
23405 *
23406 * @private
23407 * @param {*} value The value to inspect.
23408 * @returns {Array} Returns the cast property path array.
23409 */
23410function castPath(value) {
23411 return isArray(value) ? value : stringToPath(value);
23412}
23413
23414/**
23415 * Compares values to sort them in ascending order.
23416 *
23417 * @private
23418 * @param {*} value The value to compare.
23419 * @param {*} other The other value to compare.
23420 * @returns {number} Returns the sort order indicator for `value`.
23421 */
23422function compareAscending(value, other) {
23423 if (value !== other) {
23424 var valIsDefined = value !== undefined,
23425 valIsNull = value === null,
23426 valIsReflexive = value === value,
23427 valIsSymbol = isSymbol(value);
23428
23429 var othIsDefined = other !== undefined,
23430 othIsNull = other === null,
23431 othIsReflexive = other === other,
23432 othIsSymbol = isSymbol(other);
23433
23434 if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
23435 (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
23436 (valIsNull && othIsDefined && othIsReflexive) ||
23437 (!valIsDefined && othIsReflexive) ||
23438 !valIsReflexive) {
23439 return 1;
23440 }
23441 if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
23442 (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
23443 (othIsNull && valIsDefined && valIsReflexive) ||
23444 (!othIsDefined && valIsReflexive) ||
23445 !othIsReflexive) {
23446 return -1;
23447 }
23448 }
23449 return 0;
23450}
23451
23452/**
23453 * Used by `_.orderBy` to compare multiple properties of a value to another
23454 * and stable sort them.
23455 *
23456 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
23457 * specify an order of "desc" for descending or "asc" for ascending sort order
23458 * of corresponding values.
23459 *
23460 * @private
23461 * @param {Object} object The object to compare.
23462 * @param {Object} other The other object to compare.
23463 * @param {boolean[]|string[]} orders The order to sort by for each property.
23464 * @returns {number} Returns the sort order indicator for `object`.
23465 */
23466function compareMultiple(object, other, orders) {
23467 var index = -1,
23468 objCriteria = object.criteria,
23469 othCriteria = other.criteria,
23470 length = objCriteria.length,
23471 ordersLength = orders.length;
23472
23473 while (++index < length) {
23474 var result = compareAscending(objCriteria[index], othCriteria[index]);
23475 if (result) {
23476 if (index >= ordersLength) {
23477 return result;
23478 }
23479 var order = orders[index];
23480 return result * (order == 'desc' ? -1 : 1);
23481 }
23482 }
23483 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
23484 // that causes it, under certain circumstances, to provide the same value for
23485 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
23486 // for more details.
23487 //
23488 // This also ensures a stable sort in V8 and other engines.
23489 // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
23490 return object.index - other.index;
23491}
23492
23493/**
23494 * Creates a `baseEach` or `baseEachRight` function.
23495 *
23496 * @private
23497 * @param {Function} eachFunc The function to iterate over a collection.
23498 * @param {boolean} [fromRight] Specify iterating from right to left.
23499 * @returns {Function} Returns the new base function.
23500 */
23501function createBaseEach(eachFunc, fromRight) {
23502 return function(collection, iteratee) {
23503 if (collection == null) {
23504 return collection;
23505 }
23506 if (!isArrayLike(collection)) {
23507 return eachFunc(collection, iteratee);
23508 }
23509 var length = collection.length,
23510 index = fromRight ? length : -1,
23511 iterable = Object(collection);
23512
23513 while ((fromRight ? index-- : ++index < length)) {
23514 if (iteratee(iterable[index], index, iterable) === false) {
23515 break;
23516 }
23517 }
23518 return collection;
23519 };
23520}
23521
23522/**
23523 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
23524 *
23525 * @private
23526 * @param {boolean} [fromRight] Specify iterating from right to left.
23527 * @returns {Function} Returns the new base function.
23528 */
23529function createBaseFor(fromRight) {
23530 return function(object, iteratee, keysFunc) {
23531 var index = -1,
23532 iterable = Object(object),
23533 props = keysFunc(object),
23534 length = props.length;
23535
23536 while (length--) {
23537 var key = props[fromRight ? length : ++index];
23538 if (iteratee(iterable[key], key, iterable) === false) {
23539 break;
23540 }
23541 }
23542 return object;
23543 };
23544}
23545
23546/**
23547 * A specialized version of `baseIsEqualDeep` for arrays with support for
23548 * partial deep comparisons.
23549 *
23550 * @private
23551 * @param {Array} array The array to compare.
23552 * @param {Array} other The other array to compare.
23553 * @param {Function} equalFunc The function to determine equivalents of values.
23554 * @param {Function} customizer The function to customize comparisons.
23555 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
23556 * for more details.
23557 * @param {Object} stack Tracks traversed `array` and `other` objects.
23558 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
23559 */
23560function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
23561 var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
23562 arrLength = array.length,
23563 othLength = other.length;
23564
23565 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
23566 return false;
23567 }
23568 // Assume cyclic values are equal.
23569 var stacked = stack.get(array);
23570 if (stacked && stack.get(other)) {
23571 return stacked == other;
23572 }
23573 var index = -1,
23574 result = true,
23575 seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined;
23576
23577 stack.set(array, other);
23578 stack.set(other, array);
23579
23580 // Ignore non-index properties.
23581 while (++index < arrLength) {
23582 var arrValue = array[index],
23583 othValue = other[index];
23584
23585 if (customizer) {
23586 var compared = isPartial
23587 ? customizer(othValue, arrValue, index, other, array, stack)
23588 : customizer(arrValue, othValue, index, array, other, stack);
23589 }
23590 if (compared !== undefined) {
23591 if (compared) {
23592 continue;
23593 }
23594 result = false;
23595 break;
23596 }
23597 // Recursively compare arrays (susceptible to call stack limits).
23598 if (seen) {
23599 if (!arraySome(other, function(othValue, othIndex) {
23600 if (!seen.has(othIndex) &&
23601 (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
23602 return seen.add(othIndex);
23603 }
23604 })) {
23605 result = false;
23606 break;
23607 }
23608 } else if (!(
23609 arrValue === othValue ||
23610 equalFunc(arrValue, othValue, customizer, bitmask, stack)
23611 )) {
23612 result = false;
23613 break;
23614 }
23615 }
23616 stack['delete'](array);
23617 stack['delete'](other);
23618 return result;
23619}
23620
23621/**
23622 * A specialized version of `baseIsEqualDeep` for comparing objects of
23623 * the same `toStringTag`.
23624 *
23625 * **Note:** This function only supports comparing values with tags of
23626 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
23627 *
23628 * @private
23629 * @param {Object} object The object to compare.
23630 * @param {Object} other The other object to compare.
23631 * @param {string} tag The `toStringTag` of the objects to compare.
23632 * @param {Function} equalFunc The function to determine equivalents of values.
23633 * @param {Function} customizer The function to customize comparisons.
23634 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
23635 * for more details.
23636 * @param {Object} stack Tracks traversed `object` and `other` objects.
23637 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
23638 */
23639function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
23640 switch (tag) {
23641 case dataViewTag:
23642 if ((object.byteLength != other.byteLength) ||
23643 (object.byteOffset != other.byteOffset)) {
23644 return false;
23645 }
23646 object = object.buffer;
23647 other = other.buffer;
23648
23649 case arrayBufferTag:
23650 if ((object.byteLength != other.byteLength) ||
23651 !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
23652 return false;
23653 }
23654 return true;
23655
23656 case boolTag:
23657 case dateTag:
23658 case numberTag:
23659 // Coerce booleans to `1` or `0` and dates to milliseconds.
23660 // Invalid dates are coerced to `NaN`.
23661 return eq(+object, +other);
23662
23663 case errorTag:
23664 return object.name == other.name && object.message == other.message;
23665
23666 case regexpTag:
23667 case stringTag:
23668 // Coerce regexes to strings and treat strings, primitives and objects,
23669 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
23670 // for more details.
23671 return object == (other + '');
23672
23673 case mapTag:
23674 var convert = mapToArray;
23675
23676 case setTag:
23677 var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
23678 convert || (convert = setToArray);
23679
23680 if (object.size != other.size && !isPartial) {
23681 return false;
23682 }
23683 // Assume cyclic values are equal.
23684 var stacked = stack.get(object);
23685 if (stacked) {
23686 return stacked == other;
23687 }
23688 bitmask |= UNORDERED_COMPARE_FLAG;
23689
23690 // Recursively compare objects (susceptible to call stack limits).
23691 stack.set(object, other);
23692 var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
23693 stack['delete'](object);
23694 return result;
23695
23696 case symbolTag:
23697 if (symbolValueOf) {
23698 return symbolValueOf.call(object) == symbolValueOf.call(other);
23699 }
23700 }
23701 return false;
23702}
23703
23704/**
23705 * A specialized version of `baseIsEqualDeep` for objects with support for
23706 * partial deep comparisons.
23707 *
23708 * @private
23709 * @param {Object} object The object to compare.
23710 * @param {Object} other The other object to compare.
23711 * @param {Function} equalFunc The function to determine equivalents of values.
23712 * @param {Function} customizer The function to customize comparisons.
23713 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
23714 * for more details.
23715 * @param {Object} stack Tracks traversed `object` and `other` objects.
23716 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
23717 */
23718function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
23719 var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
23720 objProps = keys(object),
23721 objLength = objProps.length,
23722 othProps = keys(other),
23723 othLength = othProps.length;
23724
23725 if (objLength != othLength && !isPartial) {
23726 return false;
23727 }
23728 var index = objLength;
23729 while (index--) {
23730 var key = objProps[index];
23731 if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
23732 return false;
23733 }
23734 }
23735 // Assume cyclic values are equal.
23736 var stacked = stack.get(object);
23737 if (stacked && stack.get(other)) {
23738 return stacked == other;
23739 }
23740 var result = true;
23741 stack.set(object, other);
23742 stack.set(other, object);
23743
23744 var skipCtor = isPartial;
23745 while (++index < objLength) {
23746 key = objProps[index];
23747 var objValue = object[key],
23748 othValue = other[key];
23749
23750 if (customizer) {
23751 var compared = isPartial
23752 ? customizer(othValue, objValue, key, other, object, stack)
23753 : customizer(objValue, othValue, key, object, other, stack);
23754 }
23755 // Recursively compare objects (susceptible to call stack limits).
23756 if (!(compared === undefined
23757 ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
23758 : compared
23759 )) {
23760 result = false;
23761 break;
23762 }
23763 skipCtor || (skipCtor = key == 'constructor');
23764 }
23765 if (result && !skipCtor) {
23766 var objCtor = object.constructor,
23767 othCtor = other.constructor;
23768
23769 // Non `Object` object instances with different constructors are not equal.
23770 if (objCtor != othCtor &&
23771 ('constructor' in object && 'constructor' in other) &&
23772 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
23773 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
23774 result = false;
23775 }
23776 }
23777 stack['delete'](object);
23778 stack['delete'](other);
23779 return result;
23780}
23781
23782/**
23783 * Gets the data for `map`.
23784 *
23785 * @private
23786 * @param {Object} map The map to query.
23787 * @param {string} key The reference key.
23788 * @returns {*} Returns the map data.
23789 */
23790function getMapData(map, key) {
23791 var data = map.__data__;
23792 return isKeyable(key)
23793 ? data[typeof key == 'string' ? 'string' : 'hash']
23794 : data.map;
23795}
23796
23797/**
23798 * Gets the property names, values, and compare flags of `object`.
23799 *
23800 * @private
23801 * @param {Object} object The object to query.
23802 * @returns {Array} Returns the match data of `object`.
23803 */
23804function getMatchData(object) {
23805 var result = keys(object),
23806 length = result.length;
23807
23808 while (length--) {
23809 var key = result[length],
23810 value = object[key];
23811
23812 result[length] = [key, value, isStrictComparable(value)];
23813 }
23814 return result;
23815}
23816
23817/**
23818 * Gets the native function at `key` of `object`.
23819 *
23820 * @private
23821 * @param {Object} object The object to query.
23822 * @param {string} key The key of the method to get.
23823 * @returns {*} Returns the function if it's native, else `undefined`.
23824 */
23825function getNative(object, key) {
23826 var value = getValue(object, key);
23827 return baseIsNative(value) ? value : undefined;
23828}
23829
23830/**
23831 * Gets the `toStringTag` of `value`.
23832 *
23833 * @private
23834 * @param {*} value The value to query.
23835 * @returns {string} Returns the `toStringTag`.
23836 */
23837var getTag = baseGetTag;
23838
23839// Fallback for data views, maps, sets, and weak maps in IE 11,
23840// for data views in Edge < 14, and promises in Node.js.
23841if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
23842 (Map && getTag(new Map) != mapTag) ||
23843 (Promise && getTag(Promise.resolve()) != promiseTag) ||
23844 (Set && getTag(new Set) != setTag) ||
23845 (WeakMap && getTag(new WeakMap) != weakMapTag)) {
23846 getTag = function(value) {
23847 var result = objectToString.call(value),
23848 Ctor = result == objectTag ? value.constructor : undefined,
23849 ctorString = Ctor ? toSource(Ctor) : undefined;
23850
23851 if (ctorString) {
23852 switch (ctorString) {
23853 case dataViewCtorString: return dataViewTag;
23854 case mapCtorString: return mapTag;
23855 case promiseCtorString: return promiseTag;
23856 case setCtorString: return setTag;
23857 case weakMapCtorString: return weakMapTag;
23858 }
23859 }
23860 return result;
23861 };
23862}
23863
23864/**
23865 * Checks if `path` exists on `object`.
23866 *
23867 * @private
23868 * @param {Object} object The object to query.
23869 * @param {Array|string} path The path to check.
23870 * @param {Function} hasFunc The function to check properties.
23871 * @returns {boolean} Returns `true` if `path` exists, else `false`.
23872 */
23873function hasPath(object, path, hasFunc) {
23874 path = isKey(path, object) ? [path] : castPath(path);
23875
23876 var result,
23877 index = -1,
23878 length = path.length;
23879
23880 while (++index < length) {
23881 var key = toKey(path[index]);
23882 if (!(result = object != null && hasFunc(object, key))) {
23883 break;
23884 }
23885 object = object[key];
23886 }
23887 if (result) {
23888 return result;
23889 }
23890 var length = object ? object.length : 0;
23891 return !!length && isLength(length) && isIndex(key, length) &&
23892 (isArray(object) || isArguments(object));
23893}
23894
23895/**
23896 * Checks if `value` is a flattenable `arguments` object or array.
23897 *
23898 * @private
23899 * @param {*} value The value to check.
23900 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
23901 */
23902function isFlattenable(value) {
23903 return isArray(value) || isArguments(value) ||
23904 !!(spreadableSymbol && value && value[spreadableSymbol]);
23905}
23906
23907/**
23908 * Checks if `value` is a valid array-like index.
23909 *
23910 * @private
23911 * @param {*} value The value to check.
23912 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
23913 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
23914 */
23915function isIndex(value, length) {
23916 length = length == null ? MAX_SAFE_INTEGER : length;
23917 return !!length &&
23918 (typeof value == 'number' || reIsUint.test(value)) &&
23919 (value > -1 && value % 1 == 0 && value < length);
23920}
23921
23922/**
23923 * Checks if the given arguments are from an iteratee call.
23924 *
23925 * @private
23926 * @param {*} value The potential iteratee value argument.
23927 * @param {*} index The potential iteratee index or key argument.
23928 * @param {*} object The potential iteratee object argument.
23929 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
23930 * else `false`.
23931 */
23932function isIterateeCall(value, index, object) {
23933 if (!isObject(object)) {
23934 return false;
23935 }
23936 var type = typeof index;
23937 if (type == 'number'
23938 ? (isArrayLike(object) && isIndex(index, object.length))
23939 : (type == 'string' && index in object)
23940 ) {
23941 return eq(object[index], value);
23942 }
23943 return false;
23944}
23945
23946/**
23947 * Checks if `value` is a property name and not a property path.
23948 *
23949 * @private
23950 * @param {*} value The value to check.
23951 * @param {Object} [object] The object to query keys on.
23952 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
23953 */
23954function isKey(value, object) {
23955 if (isArray(value)) {
23956 return false;
23957 }
23958 var type = typeof value;
23959 if (type == 'number' || type == 'symbol' || type == 'boolean' ||
23960 value == null || isSymbol(value)) {
23961 return true;
23962 }
23963 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
23964 (object != null && value in Object(object));
23965}
23966
23967/**
23968 * Checks if `value` is suitable for use as unique object key.
23969 *
23970 * @private
23971 * @param {*} value The value to check.
23972 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
23973 */
23974function isKeyable(value) {
23975 var type = typeof value;
23976 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
23977 ? (value !== '__proto__')
23978 : (value === null);
23979}
23980
23981/**
23982 * Checks if `func` has its source masked.
23983 *
23984 * @private
23985 * @param {Function} func The function to check.
23986 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
23987 */
23988function isMasked(func) {
23989 return !!maskSrcKey && (maskSrcKey in func);
23990}
23991
23992/**
23993 * Checks if `value` is likely a prototype object.
23994 *
23995 * @private
23996 * @param {*} value The value to check.
23997 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
23998 */
23999function isPrototype(value) {
24000 var Ctor = value && value.constructor,
24001 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
24002
24003 return value === proto;
24004}
24005
24006/**
24007 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
24008 *
24009 * @private
24010 * @param {*} value The value to check.
24011 * @returns {boolean} Returns `true` if `value` if suitable for strict
24012 * equality comparisons, else `false`.
24013 */
24014function isStrictComparable(value) {
24015 return value === value && !isObject(value);
24016}
24017
24018/**
24019 * A specialized version of `matchesProperty` for source values suitable
24020 * for strict equality comparisons, i.e. `===`.
24021 *
24022 * @private
24023 * @param {string} key The key of the property to get.
24024 * @param {*} srcValue The value to match.
24025 * @returns {Function} Returns the new spec function.
24026 */
24027function matchesStrictComparable(key, srcValue) {
24028 return function(object) {
24029 if (object == null) {
24030 return false;
24031 }
24032 return object[key] === srcValue &&
24033 (srcValue !== undefined || (key in Object(object)));
24034 };
24035}
24036
24037/**
24038 * Converts `string` to a property path array.
24039 *
24040 * @private
24041 * @param {string} string The string to convert.
24042 * @returns {Array} Returns the property path array.
24043 */
24044var stringToPath = memoize(function(string) {
24045 string = toString(string);
24046
24047 var result = [];
24048 if (reLeadingDot.test(string)) {
24049 result.push('');
24050 }
24051 string.replace(rePropName, function(match, number, quote, string) {
24052 result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
24053 });
24054 return result;
24055});
24056
24057/**
24058 * Converts `value` to a string key if it's not a string or symbol.
24059 *
24060 * @private
24061 * @param {*} value The value to inspect.
24062 * @returns {string|symbol} Returns the key.
24063 */
24064function toKey(value) {
24065 if (typeof value == 'string' || isSymbol(value)) {
24066 return value;
24067 }
24068 var result = (value + '');
24069 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
24070}
24071
24072/**
24073 * Converts `func` to its source code.
24074 *
24075 * @private
24076 * @param {Function} func The function to process.
24077 * @returns {string} Returns the source code.
24078 */
24079function toSource(func) {
24080 if (func != null) {
24081 try {
24082 return funcToString.call(func);
24083 } catch (e) {}
24084 try {
24085 return (func + '');
24086 } catch (e) {}
24087 }
24088 return '';
24089}
24090
24091/**
24092 * Creates an array of elements, sorted in ascending order by the results of
24093 * running each element in a collection thru each iteratee. This method
24094 * performs a stable sort, that is, it preserves the original sort order of
24095 * equal elements. The iteratees are invoked with one argument: (value).
24096 *
24097 * @static
24098 * @memberOf _
24099 * @since 0.1.0
24100 * @category Collection
24101 * @param {Array|Object} collection The collection to iterate over.
24102 * @param {...(Function|Function[])} [iteratees=[_.identity]]
24103 * The iteratees to sort by.
24104 * @returns {Array} Returns the new sorted array.
24105 * @example
24106 *
24107 * var users = [
24108 * { 'user': 'fred', 'age': 48 },
24109 * { 'user': 'barney', 'age': 36 },
24110 * { 'user': 'fred', 'age': 40 },
24111 * { 'user': 'barney', 'age': 34 }
24112 * ];
24113 *
24114 * _.sortBy(users, function(o) { return o.user; });
24115 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
24116 *
24117 * _.sortBy(users, ['user', 'age']);
24118 * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
24119 *
24120 * _.sortBy(users, 'user', function(o) {
24121 * return Math.floor(o.age / 10);
24122 * });
24123 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
24124 */
24125var sortBy = baseRest(function(collection, iteratees) {
24126 if (collection == null) {
24127 return [];
24128 }
24129 var length = iteratees.length;
24130 if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
24131 iteratees = [];
24132 } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
24133 iteratees = [iteratees[0]];
24134 }
24135 return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
24136});
24137
24138/**
24139 * Creates a function that memoizes the result of `func`. If `resolver` is
24140 * provided, it determines the cache key for storing the result based on the
24141 * arguments provided to the memoized function. By default, the first argument
24142 * provided to the memoized function is used as the map cache key. The `func`
24143 * is invoked with the `this` binding of the memoized function.
24144 *
24145 * **Note:** The cache is exposed as the `cache` property on the memoized
24146 * function. Its creation may be customized by replacing the `_.memoize.Cache`
24147 * constructor with one whose instances implement the
24148 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
24149 * method interface of `delete`, `get`, `has`, and `set`.
24150 *
24151 * @static
24152 * @memberOf _
24153 * @since 0.1.0
24154 * @category Function
24155 * @param {Function} func The function to have its output memoized.
24156 * @param {Function} [resolver] The function to resolve the cache key.
24157 * @returns {Function} Returns the new memoized function.
24158 * @example
24159 *
24160 * var object = { 'a': 1, 'b': 2 };
24161 * var other = { 'c': 3, 'd': 4 };
24162 *
24163 * var values = _.memoize(_.values);
24164 * values(object);
24165 * // => [1, 2]
24166 *
24167 * values(other);
24168 * // => [3, 4]
24169 *
24170 * object.a = 2;
24171 * values(object);
24172 * // => [1, 2]
24173 *
24174 * // Modify the result cache.
24175 * values.cache.set(object, ['a', 'b']);
24176 * values(object);
24177 * // => ['a', 'b']
24178 *
24179 * // Replace `_.memoize.Cache`.
24180 * _.memoize.Cache = WeakMap;
24181 */
24182function memoize(func, resolver) {
24183 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
24184 throw new TypeError(FUNC_ERROR_TEXT);
24185 }
24186 var memoized = function() {
24187 var args = arguments,
24188 key = resolver ? resolver.apply(this, args) : args[0],
24189 cache = memoized.cache;
24190
24191 if (cache.has(key)) {
24192 return cache.get(key);
24193 }
24194 var result = func.apply(this, args);
24195 memoized.cache = cache.set(key, result);
24196 return result;
24197 };
24198 memoized.cache = new (memoize.Cache || MapCache);
24199 return memoized;
24200}
24201
24202// Assign cache to `_.memoize`.
24203memoize.Cache = MapCache;
24204
24205/**
24206 * Performs a
24207 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
24208 * comparison between two values to determine if they are equivalent.
24209 *
24210 * @static
24211 * @memberOf _
24212 * @since 4.0.0
24213 * @category Lang
24214 * @param {*} value The value to compare.
24215 * @param {*} other The other value to compare.
24216 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
24217 * @example
24218 *
24219 * var object = { 'a': 1 };
24220 * var other = { 'a': 1 };
24221 *
24222 * _.eq(object, object);
24223 * // => true
24224 *
24225 * _.eq(object, other);
24226 * // => false
24227 *
24228 * _.eq('a', 'a');
24229 * // => true
24230 *
24231 * _.eq('a', Object('a'));
24232 * // => false
24233 *
24234 * _.eq(NaN, NaN);
24235 * // => true
24236 */
24237function eq(value, other) {
24238 return value === other || (value !== value && other !== other);
24239}
24240
24241/**
24242 * Checks if `value` is likely an `arguments` object.
24243 *
24244 * @static
24245 * @memberOf _
24246 * @since 0.1.0
24247 * @category Lang
24248 * @param {*} value The value to check.
24249 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
24250 * else `false`.
24251 * @example
24252 *
24253 * _.isArguments(function() { return arguments; }());
24254 * // => true
24255 *
24256 * _.isArguments([1, 2, 3]);
24257 * // => false
24258 */
24259function isArguments(value) {
24260 // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
24261 return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
24262 (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
24263}
24264
24265/**
24266 * Checks if `value` is classified as an `Array` object.
24267 *
24268 * @static
24269 * @memberOf _
24270 * @since 0.1.0
24271 * @category Lang
24272 * @param {*} value The value to check.
24273 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
24274 * @example
24275 *
24276 * _.isArray([1, 2, 3]);
24277 * // => true
24278 *
24279 * _.isArray(document.body.children);
24280 * // => false
24281 *
24282 * _.isArray('abc');
24283 * // => false
24284 *
24285 * _.isArray(_.noop);
24286 * // => false
24287 */
24288var isArray = Array.isArray;
24289
24290/**
24291 * Checks if `value` is array-like. A value is considered array-like if it's
24292 * not a function and has a `value.length` that's an integer greater than or
24293 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
24294 *
24295 * @static
24296 * @memberOf _
24297 * @since 4.0.0
24298 * @category Lang
24299 * @param {*} value The value to check.
24300 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
24301 * @example
24302 *
24303 * _.isArrayLike([1, 2, 3]);
24304 * // => true
24305 *
24306 * _.isArrayLike(document.body.children);
24307 * // => true
24308 *
24309 * _.isArrayLike('abc');
24310 * // => true
24311 *
24312 * _.isArrayLike(_.noop);
24313 * // => false
24314 */
24315function isArrayLike(value) {
24316 return value != null && isLength(value.length) && !isFunction(value);
24317}
24318
24319/**
24320 * This method is like `_.isArrayLike` except that it also checks if `value`
24321 * is an object.
24322 *
24323 * @static
24324 * @memberOf _
24325 * @since 4.0.0
24326 * @category Lang
24327 * @param {*} value The value to check.
24328 * @returns {boolean} Returns `true` if `value` is an array-like object,
24329 * else `false`.
24330 * @example
24331 *
24332 * _.isArrayLikeObject([1, 2, 3]);
24333 * // => true
24334 *
24335 * _.isArrayLikeObject(document.body.children);
24336 * // => true
24337 *
24338 * _.isArrayLikeObject('abc');
24339 * // => false
24340 *
24341 * _.isArrayLikeObject(_.noop);
24342 * // => false
24343 */
24344function isArrayLikeObject(value) {
24345 return isObjectLike(value) && isArrayLike(value);
24346}
24347
24348/**
24349 * Checks if `value` is classified as a `Function` object.
24350 *
24351 * @static
24352 * @memberOf _
24353 * @since 0.1.0
24354 * @category Lang
24355 * @param {*} value The value to check.
24356 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
24357 * @example
24358 *
24359 * _.isFunction(_);
24360 * // => true
24361 *
24362 * _.isFunction(/abc/);
24363 * // => false
24364 */
24365function isFunction(value) {
24366 // The use of `Object#toString` avoids issues with the `typeof` operator
24367 // in Safari 8-9 which returns 'object' for typed array and other constructors.
24368 var tag = isObject(value) ? objectToString.call(value) : '';
24369 return tag == funcTag || tag == genTag;
24370}
24371
24372/**
24373 * Checks if `value` is a valid array-like length.
24374 *
24375 * **Note:** This method is loosely based on
24376 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
24377 *
24378 * @static
24379 * @memberOf _
24380 * @since 4.0.0
24381 * @category Lang
24382 * @param {*} value The value to check.
24383 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
24384 * @example
24385 *
24386 * _.isLength(3);
24387 * // => true
24388 *
24389 * _.isLength(Number.MIN_VALUE);
24390 * // => false
24391 *
24392 * _.isLength(Infinity);
24393 * // => false
24394 *
24395 * _.isLength('3');
24396 * // => false
24397 */
24398function isLength(value) {
24399 return typeof value == 'number' &&
24400 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
24401}
24402
24403/**
24404 * Checks if `value` is the
24405 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
24406 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
24407 *
24408 * @static
24409 * @memberOf _
24410 * @since 0.1.0
24411 * @category Lang
24412 * @param {*} value The value to check.
24413 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
24414 * @example
24415 *
24416 * _.isObject({});
24417 * // => true
24418 *
24419 * _.isObject([1, 2, 3]);
24420 * // => true
24421 *
24422 * _.isObject(_.noop);
24423 * // => true
24424 *
24425 * _.isObject(null);
24426 * // => false
24427 */
24428function isObject(value) {
24429 var type = typeof value;
24430 return !!value && (type == 'object' || type == 'function');
24431}
24432
24433/**
24434 * Checks if `value` is object-like. A value is object-like if it's not `null`
24435 * and has a `typeof` result of "object".
24436 *
24437 * @static
24438 * @memberOf _
24439 * @since 4.0.0
24440 * @category Lang
24441 * @param {*} value The value to check.
24442 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
24443 * @example
24444 *
24445 * _.isObjectLike({});
24446 * // => true
24447 *
24448 * _.isObjectLike([1, 2, 3]);
24449 * // => true
24450 *
24451 * _.isObjectLike(_.noop);
24452 * // => false
24453 *
24454 * _.isObjectLike(null);
24455 * // => false
24456 */
24457function isObjectLike(value) {
24458 return !!value && typeof value == 'object';
24459}
24460
24461/**
24462 * Checks if `value` is classified as a `Symbol` primitive or object.
24463 *
24464 * @static
24465 * @memberOf _
24466 * @since 4.0.0
24467 * @category Lang
24468 * @param {*} value The value to check.
24469 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
24470 * @example
24471 *
24472 * _.isSymbol(Symbol.iterator);
24473 * // => true
24474 *
24475 * _.isSymbol('abc');
24476 * // => false
24477 */
24478function isSymbol(value) {
24479 return typeof value == 'symbol' ||
24480 (isObjectLike(value) && objectToString.call(value) == symbolTag);
24481}
24482
24483/**
24484 * Checks if `value` is classified as a typed array.
24485 *
24486 * @static
24487 * @memberOf _
24488 * @since 3.0.0
24489 * @category Lang
24490 * @param {*} value The value to check.
24491 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
24492 * @example
24493 *
24494 * _.isTypedArray(new Uint8Array);
24495 * // => true
24496 *
24497 * _.isTypedArray([]);
24498 * // => false
24499 */
24500var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
24501
24502/**
24503 * Converts `value` to a string. An empty string is returned for `null`
24504 * and `undefined` values. The sign of `-0` is preserved.
24505 *
24506 * @static
24507 * @memberOf _
24508 * @since 4.0.0
24509 * @category Lang
24510 * @param {*} value The value to process.
24511 * @returns {string} Returns the string.
24512 * @example
24513 *
24514 * _.toString(null);
24515 * // => ''
24516 *
24517 * _.toString(-0);
24518 * // => '-0'
24519 *
24520 * _.toString([1, 2, 3]);
24521 * // => '1,2,3'
24522 */
24523function toString(value) {
24524 return value == null ? '' : baseToString(value);
24525}
24526
24527/**
24528 * Gets the value at `path` of `object`. If the resolved value is
24529 * `undefined`, the `defaultValue` is returned in its place.
24530 *
24531 * @static
24532 * @memberOf _
24533 * @since 3.7.0
24534 * @category Object
24535 * @param {Object} object The object to query.
24536 * @param {Array|string} path The path of the property to get.
24537 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
24538 * @returns {*} Returns the resolved value.
24539 * @example
24540 *
24541 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
24542 *
24543 * _.get(object, 'a[0].b.c');
24544 * // => 3
24545 *
24546 * _.get(object, ['a', '0', 'b', 'c']);
24547 * // => 3
24548 *
24549 * _.get(object, 'a.b.c', 'default');
24550 * // => 'default'
24551 */
24552function get(object, path, defaultValue) {
24553 var result = object == null ? undefined : baseGet(object, path);
24554 return result === undefined ? defaultValue : result;
24555}
24556
24557/**
24558 * Checks if `path` is a direct or inherited property of `object`.
24559 *
24560 * @static
24561 * @memberOf _
24562 * @since 4.0.0
24563 * @category Object
24564 * @param {Object} object The object to query.
24565 * @param {Array|string} path The path to check.
24566 * @returns {boolean} Returns `true` if `path` exists, else `false`.
24567 * @example
24568 *
24569 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
24570 *
24571 * _.hasIn(object, 'a');
24572 * // => true
24573 *
24574 * _.hasIn(object, 'a.b');
24575 * // => true
24576 *
24577 * _.hasIn(object, ['a', 'b']);
24578 * // => true
24579 *
24580 * _.hasIn(object, 'b');
24581 * // => false
24582 */
24583function hasIn(object, path) {
24584 return object != null && hasPath(object, path, baseHasIn);
24585}
24586
24587/**
24588 * Creates an array of the own enumerable property names of `object`.
24589 *
24590 * **Note:** Non-object values are coerced to objects. See the
24591 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
24592 * for more details.
24593 *
24594 * @static
24595 * @since 0.1.0
24596 * @memberOf _
24597 * @category Object
24598 * @param {Object} object The object to query.
24599 * @returns {Array} Returns the array of property names.
24600 * @example
24601 *
24602 * function Foo() {
24603 * this.a = 1;
24604 * this.b = 2;
24605 * }
24606 *
24607 * Foo.prototype.c = 3;
24608 *
24609 * _.keys(new Foo);
24610 * // => ['a', 'b'] (iteration order is not guaranteed)
24611 *
24612 * _.keys('hi');
24613 * // => ['0', '1']
24614 */
24615function keys(object) {
24616 return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
24617}
24618
24619/**
24620 * This method returns the first argument it receives.
24621 *
24622 * @static
24623 * @since 0.1.0
24624 * @memberOf _
24625 * @category Util
24626 * @param {*} value Any value.
24627 * @returns {*} Returns `value`.
24628 * @example
24629 *
24630 * var object = { 'a': 1 };
24631 *
24632 * console.log(_.identity(object) === object);
24633 * // => true
24634 */
24635function identity(value) {
24636 return value;
24637}
24638
24639/**
24640 * Creates a function that returns the value at `path` of a given object.
24641 *
24642 * @static
24643 * @memberOf _
24644 * @since 2.4.0
24645 * @category Util
24646 * @param {Array|string} path The path of the property to get.
24647 * @returns {Function} Returns the new accessor function.
24648 * @example
24649 *
24650 * var objects = [
24651 * { 'a': { 'b': 2 } },
24652 * { 'a': { 'b': 1 } }
24653 * ];
24654 *
24655 * _.map(objects, _.property('a.b'));
24656 * // => [2, 1]
24657 *
24658 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
24659 * // => [1, 2]
24660 */
24661function property(path) {
24662 return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
24663}
24664
24665module.exports = sortBy;
24666});
24667
24668var implementation = class URLSearchParamsImpl {
24669 constructor(constructorArgs, { doNotStripQMark = false }) {
24670 let init = constructorArgs[0];
24671 this._list = [];
24672 this._url = null;
24673
24674 if (!doNotStripQMark && typeof init === "string" && init[0] === "?") {
24675 init = init.slice(1);
24676 }
24677
24678 if (Array.isArray(init)) {
24679 for (const pair of init) {
24680 if (pair.length !== 2) {
24681 throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not " +
24682 "contain exactly two elements.");
24683 }
24684 this._list.push([pair[0], pair[1]]);
24685 }
24686 } else if (typeof init === "object" && Object.getPrototypeOf(init) === null) {
24687 for (const name of Object.keys(init)) {
24688 const value = init[name];
24689 this._list.push([name, value]);
24690 }
24691 } else {
24692 this._list = urlencoded.parseUrlencoded(init);
24693 }
24694 }
24695
24696 _updateSteps() {
24697 if (this._url !== null) {
24698 let query = urlencoded.serializeUrlencoded(this._list);
24699 if (query === "") {
24700 query = null;
24701 }
24702 this._url._url.query = query;
24703 }
24704 }
24705
24706 append(name, value) {
24707 this._list.push([name, value]);
24708 this._updateSteps();
24709 }
24710
24711 delete(name) {
24712 let i = 0;
24713 while (i < this._list.length) {
24714 if (this._list[i][0] === name) {
24715 this._list.splice(i, 1);
24716 } else {
24717 i++;
24718 }
24719 }
24720 this._updateSteps();
24721 }
24722
24723 get(name) {
24724 for (const tuple of this._list) {
24725 if (tuple[0] === name) {
24726 return tuple[1];
24727 }
24728 }
24729 return null;
24730 }
24731
24732 getAll(name) {
24733 const output = [];
24734 for (const tuple of this._list) {
24735 if (tuple[0] === name) {
24736 output.push(tuple[1]);
24737 }
24738 }
24739 return output;
24740 }
24741
24742 has(name) {
24743 for (const tuple of this._list) {
24744 if (tuple[0] === name) {
24745 return true;
24746 }
24747 }
24748 return false;
24749 }
24750
24751 set(name, value) {
24752 let found = false;
24753 let i = 0;
24754 while (i < this._list.length) {
24755 if (this._list[i][0] === name) {
24756 if (found) {
24757 this._list.splice(i, 1);
24758 } else {
24759 found = true;
24760 this._list[i][1] = value;
24761 i++;
24762 }
24763 } else {
24764 i++;
24765 }
24766 }
24767 if (!found) {
24768 this._list.push([name, value]);
24769 }
24770 this._updateSteps();
24771 }
24772
24773 sort() {
24774 this._list = lodash_sortby(this._list, [0]);
24775 this._updateSteps();
24776 }
24777
24778 [Symbol.iterator]() {
24779 return this._list[Symbol.iterator]();
24780 }
24781
24782 toString() {
24783 return urlencoded.serializeUrlencoded(this._list);
24784 }
24785};
24786
24787var URLSearchParamsImpl_1 = {
24788 implementation: implementation
24789};
24790
24791var URLSearchParams_1 = createCommonjsModule(function (module) {
24792
24793
24794
24795
24796const impl = utils.implSymbol;
24797
24798const IteratorPrototype = Object.create(utils.IteratorPrototype, {
24799 next: {
24800 value: function next() {
24801 const internal = this[utils.iterInternalSymbol];
24802 const { target, kind, index } = internal;
24803 const values = Array.from(target[impl]);
24804 const len = values.length;
24805 if (index >= len) {
24806 return { value: undefined, done: true };
24807 }
24808
24809 const pair = values[index];
24810 internal.index = index + 1;
24811 const [key, value] = pair.map(utils.tryWrapperForImpl);
24812
24813 let result;
24814 switch (kind) {
24815 case "key":
24816 result = key;
24817 break;
24818 case "value":
24819 result = value;
24820 break;
24821 case "key+value":
24822 result = [key, value];
24823 break;
24824 }
24825 return { value: result, done: false };
24826 },
24827 writable: true,
24828 enumerable: true,
24829 configurable: true
24830 },
24831 [Symbol.toStringTag]: {
24832 value: "URLSearchParamsIterator",
24833 writable: false,
24834 enumerable: false,
24835 configurable: true
24836 }
24837});
24838
24839function URLSearchParams() {
24840 const args = [];
24841 for (let i = 0; i < arguments.length && i < 1; ++i) {
24842 args[i] = arguments[i];
24843 }
24844
24845 if (args[0] !== undefined) {
24846 if (utils.isObject(args[0])) {
24847 if (args[0][Symbol.iterator] !== undefined) {
24848 if (!utils.isObject(args[0])) {
24849 throw new TypeError(
24850 "Failed to construct 'URLSearchParams': parameter 1" + " sequence" + " is not an iterable object."
24851 );
24852 } else {
24853 const V = [];
24854 const tmp = args[0];
24855 for (let nextItem of tmp) {
24856 if (!utils.isObject(nextItem)) {
24857 throw new TypeError(
24858 "Failed to construct 'URLSearchParams': parameter 1" +
24859 " sequence" +
24860 "'s element" +
24861 " is not an iterable object."
24862 );
24863 } else {
24864 const V = [];
24865 const tmp = nextItem;
24866 for (let nextItem of tmp) {
24867 nextItem = lib$2["USVString"](nextItem, {
24868 context:
24869 "Failed to construct 'URLSearchParams': parameter 1" + " sequence" + "'s element" + "'s element"
24870 });
24871
24872 V.push(nextItem);
24873 }
24874 nextItem = V;
24875 }
24876
24877 V.push(nextItem);
24878 }
24879 args[0] = V;
24880 }
24881 } else {
24882 if (!utils.isObject(args[0])) {
24883 throw new TypeError("Failed to construct 'URLSearchParams': parameter 1" + " record" + " is not an object.");
24884 } else {
24885 const result = Object.create(null);
24886 for (const key of Reflect.ownKeys(args[0])) {
24887 const desc = Object.getOwnPropertyDescriptor(args[0], key);
24888 if (desc && desc.enumerable) {
24889 let typedKey = key;
24890 let typedValue = args[0][key];
24891
24892 typedKey = lib$2["USVString"](typedKey, {
24893 context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s key"
24894 });
24895
24896 typedValue = lib$2["USVString"](typedValue, {
24897 context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s value"
24898 });
24899
24900 result[typedKey] = typedValue;
24901 }
24902 }
24903 args[0] = result;
24904 }
24905 }
24906 } else {
24907 args[0] = lib$2["USVString"](args[0], { context: "Failed to construct 'URLSearchParams': parameter 1" });
24908 }
24909 } else {
24910 args[0] = "";
24911 }
24912
24913 iface.setup(this, args);
24914}
24915
24916Object.defineProperty(URLSearchParams, "prototype", {
24917 value: URLSearchParams.prototype,
24918 writable: false,
24919 enumerable: false,
24920 configurable: false
24921});
24922
24923Object.defineProperty(URLSearchParams.prototype, Symbol.iterator, {
24924 writable: true,
24925 enumerable: false,
24926 configurable: true,
24927 value: function entries() {
24928 if (!this || !module.exports.is(this)) {
24929 throw new TypeError("Illegal invocation");
24930 }
24931 return module.exports.createDefaultIterator(this, "key+value");
24932 }
24933});
24934URLSearchParams.prototype.forEach = function forEach(callback) {
24935 if (!this || !module.exports.is(this)) {
24936 throw new TypeError("Illegal invocation");
24937 }
24938 if (arguments.length < 1) {
24939 throw new TypeError(
24940 "Failed to execute 'forEach' on 'URLSearchParams': 1 argument required, " + "but only 0 present."
24941 );
24942 }
24943 if (typeof callback !== "function") {
24944 throw new TypeError(
24945 "Failed to execute 'forEach' on 'URLSearchParams': The callback provided " + "as parameter 1 is not a function."
24946 );
24947 }
24948 const thisArg = arguments[1];
24949 let pairs = Array.from(this[impl]);
24950 let i = 0;
24951 while (i < pairs.length) {
24952 const [key, value] = pairs[i].map(utils.tryWrapperForImpl);
24953 callback.call(thisArg, value, key, this);
24954 pairs = Array.from(this[impl]);
24955 i++;
24956 }
24957};
24958URLSearchParams.prototype.append = function append(name, value) {
24959 if (!this || !module.exports.is(this)) {
24960 throw new TypeError("Illegal invocation");
24961 }
24962
24963 if (arguments.length < 2) {
24964 throw new TypeError(
24965 "Failed to execute 'append' on 'URLSearchParams': 2 " +
24966 "arguments required, but only " +
24967 arguments.length +
24968 " present."
24969 );
24970 }
24971
24972 const args = [];
24973 for (let i = 0; i < arguments.length && i < 2; ++i) {
24974 args[i] = arguments[i];
24975 }
24976
24977 args[0] = lib$2["USVString"](args[0], {
24978 context: "Failed to execute 'append' on 'URLSearchParams': parameter 1"
24979 });
24980
24981 args[1] = lib$2["USVString"](args[1], {
24982 context: "Failed to execute 'append' on 'URLSearchParams': parameter 2"
24983 });
24984
24985 return this[impl].append(...args);
24986};
24987
24988URLSearchParams.prototype.delete = function _(name) {
24989 if (!this || !module.exports.is(this)) {
24990 throw new TypeError("Illegal invocation");
24991 }
24992
24993 if (arguments.length < 1) {
24994 throw new TypeError(
24995 "Failed to execute 'delete' on 'URLSearchParams': 1 " +
24996 "argument required, but only " +
24997 arguments.length +
24998 " present."
24999 );
25000 }
25001
25002 const args = [];
25003 for (let i = 0; i < arguments.length && i < 1; ++i) {
25004 args[i] = arguments[i];
25005 }
25006
25007 args[0] = lib$2["USVString"](args[0], {
25008 context: "Failed to execute 'delete' on 'URLSearchParams': parameter 1"
25009 });
25010
25011 return this[impl].delete(...args);
25012};
25013
25014URLSearchParams.prototype.get = function get(name) {
25015 if (!this || !module.exports.is(this)) {
25016 throw new TypeError("Illegal invocation");
25017 }
25018
25019 if (arguments.length < 1) {
25020 throw new TypeError(
25021 "Failed to execute 'get' on 'URLSearchParams': 1 " +
25022 "argument required, but only " +
25023 arguments.length +
25024 " present."
25025 );
25026 }
25027
25028 const args = [];
25029 for (let i = 0; i < arguments.length && i < 1; ++i) {
25030 args[i] = arguments[i];
25031 }
25032
25033 args[0] = lib$2["USVString"](args[0], { context: "Failed to execute 'get' on 'URLSearchParams': parameter 1" });
25034
25035 return this[impl].get(...args);
25036};
25037
25038URLSearchParams.prototype.getAll = function getAll(name) {
25039 if (!this || !module.exports.is(this)) {
25040 throw new TypeError("Illegal invocation");
25041 }
25042
25043 if (arguments.length < 1) {
25044 throw new TypeError(
25045 "Failed to execute 'getAll' on 'URLSearchParams': 1 " +
25046 "argument required, but only " +
25047 arguments.length +
25048 " present."
25049 );
25050 }
25051
25052 const args = [];
25053 for (let i = 0; i < arguments.length && i < 1; ++i) {
25054 args[i] = arguments[i];
25055 }
25056
25057 args[0] = lib$2["USVString"](args[0], {
25058 context: "Failed to execute 'getAll' on 'URLSearchParams': parameter 1"
25059 });
25060
25061 return utils.tryWrapperForImpl(this[impl].getAll(...args));
25062};
25063
25064URLSearchParams.prototype.has = function has(name) {
25065 if (!this || !module.exports.is(this)) {
25066 throw new TypeError("Illegal invocation");
25067 }
25068
25069 if (arguments.length < 1) {
25070 throw new TypeError(
25071 "Failed to execute 'has' on 'URLSearchParams': 1 " +
25072 "argument required, but only " +
25073 arguments.length +
25074 " present."
25075 );
25076 }
25077
25078 const args = [];
25079 for (let i = 0; i < arguments.length && i < 1; ++i) {
25080 args[i] = arguments[i];
25081 }
25082
25083 args[0] = lib$2["USVString"](args[0], { context: "Failed to execute 'has' on 'URLSearchParams': parameter 1" });
25084
25085 return this[impl].has(...args);
25086};
25087
25088URLSearchParams.prototype.set = function set(name, value) {
25089 if (!this || !module.exports.is(this)) {
25090 throw new TypeError("Illegal invocation");
25091 }
25092
25093 if (arguments.length < 2) {
25094 throw new TypeError(
25095 "Failed to execute 'set' on 'URLSearchParams': 2 " +
25096 "arguments required, but only " +
25097 arguments.length +
25098 " present."
25099 );
25100 }
25101
25102 const args = [];
25103 for (let i = 0; i < arguments.length && i < 2; ++i) {
25104 args[i] = arguments[i];
25105 }
25106
25107 args[0] = lib$2["USVString"](args[0], { context: "Failed to execute 'set' on 'URLSearchParams': parameter 1" });
25108
25109 args[1] = lib$2["USVString"](args[1], { context: "Failed to execute 'set' on 'URLSearchParams': parameter 2" });
25110
25111 return this[impl].set(...args);
25112};
25113
25114URLSearchParams.prototype.sort = function sort() {
25115 if (!this || !module.exports.is(this)) {
25116 throw new TypeError("Illegal invocation");
25117 }
25118
25119 return this[impl].sort();
25120};
25121
25122URLSearchParams.prototype.toString = function toString() {
25123 if (!this || !module.exports.is(this)) {
25124 throw new TypeError("Illegal invocation");
25125 }
25126
25127 return this[impl].toString();
25128};
25129
25130URLSearchParams.prototype.entries = URLSearchParams.prototype[Symbol.iterator];
25131
25132URLSearchParams.prototype.keys = function keys() {
25133 if (!this || !module.exports.is(this)) {
25134 throw new TypeError("Illegal invocation");
25135 }
25136 return module.exports.createDefaultIterator(this, "key");
25137};
25138
25139URLSearchParams.prototype.values = function values() {
25140 if (!this || !module.exports.is(this)) {
25141 throw new TypeError("Illegal invocation");
25142 }
25143 return module.exports.createDefaultIterator(this, "value");
25144};
25145
25146Object.defineProperty(URLSearchParams.prototype, Symbol.toStringTag, {
25147 value: "URLSearchParams",
25148 writable: false,
25149 enumerable: false,
25150 configurable: true
25151});
25152
25153const iface = {
25154 mixedInto: [],
25155 is(obj) {
25156 if (obj) {
25157 if (obj[impl] instanceof URLSearchParamsImpl_1.implementation) {
25158 return true;
25159 }
25160 for (let i = 0; i < module.exports.mixedInto.length; ++i) {
25161 if (obj instanceof module.exports.mixedInto[i]) {
25162 return true;
25163 }
25164 }
25165 }
25166 return false;
25167 },
25168 isImpl(obj) {
25169 if (obj) {
25170 if (obj instanceof URLSearchParamsImpl_1.implementation) {
25171 return true;
25172 }
25173
25174 const wrapper = utils.wrapperForImpl(obj);
25175 for (let i = 0; i < module.exports.mixedInto.length; ++i) {
25176 if (wrapper instanceof module.exports.mixedInto[i]) {
25177 return true;
25178 }
25179 }
25180 }
25181 return false;
25182 },
25183 convert(obj, { context = "The provided value" } = {}) {
25184 if (module.exports.is(obj)) {
25185 return utils.implForWrapper(obj);
25186 }
25187 throw new TypeError(`${context} is not of type 'URLSearchParams'.`);
25188 },
25189
25190 createDefaultIterator(target, kind) {
25191 const iterator = Object.create(IteratorPrototype);
25192 Object.defineProperty(iterator, utils.iterInternalSymbol, {
25193 value: { target, kind, index: 0 },
25194 writable: false,
25195 enumerable: false,
25196 configurable: true
25197 });
25198 return iterator;
25199 },
25200
25201 create(constructorArgs, privateData) {
25202 let obj = Object.create(URLSearchParams.prototype);
25203 obj = this.setup(obj, constructorArgs, privateData);
25204 return obj;
25205 },
25206 createImpl(constructorArgs, privateData) {
25207 let obj = Object.create(URLSearchParams.prototype);
25208 obj = this.setup(obj, constructorArgs, privateData);
25209 return utils.implForWrapper(obj);
25210 },
25211 _internalSetup(obj) {},
25212 setup(obj, constructorArgs, privateData) {
25213 if (!privateData) privateData = {};
25214
25215 privateData.wrapper = obj;
25216
25217 this._internalSetup(obj);
25218 Object.defineProperty(obj, impl, {
25219 value: new URLSearchParamsImpl_1.implementation(constructorArgs, privateData),
25220 writable: false,
25221 enumerable: false,
25222 configurable: true
25223 });
25224
25225 obj[impl][utils.wrapperSymbol] = obj;
25226 if (URLSearchParamsImpl_1.init) {
25227 URLSearchParamsImpl_1.init(obj[impl], privateData);
25228 }
25229 return obj;
25230 },
25231 interface: URLSearchParams,
25232 expose: {
25233 Window: { URLSearchParams },
25234 Worker: { URLSearchParams }
25235 }
25236}; // iface
25237module.exports = iface;
25238});
25239
25240var implementation$1 = class URLImpl {
25241 constructor(constructorArgs) {
25242 const url = constructorArgs[0];
25243 const base = constructorArgs[1];
25244
25245 let parsedBase = null;
25246 if (base !== undefined) {
25247 parsedBase = urlStateMachine.basicURLParse(base);
25248 if (parsedBase === null) {
25249 throw new TypeError("Invalid base URL");
25250 }
25251 }
25252
25253 const parsedURL = urlStateMachine.basicURLParse(url, { baseURL: parsedBase });
25254 if (parsedURL === null) {
25255 throw new TypeError("Invalid URL");
25256 }
25257
25258 const query = parsedURL.query !== null ? parsedURL.query : "";
25259
25260 this._url = parsedURL;
25261
25262 // We cannot invoke the "new URLSearchParams object" algorithm without going through the constructor, which strips
25263 // question mark by default. Therefore the doNotStripQMark hack is used.
25264 this._query = URLSearchParams_1.createImpl([query], { doNotStripQMark: true });
25265 this._query._url = this;
25266 }
25267
25268 get href() {
25269 return urlStateMachine.serializeURL(this._url);
25270 }
25271
25272 set href(v) {
25273 const parsedURL = urlStateMachine.basicURLParse(v);
25274 if (parsedURL === null) {
25275 throw new TypeError("Invalid URL");
25276 }
25277
25278 this._url = parsedURL;
25279
25280 this._query._list.splice(0);
25281 const { query } = parsedURL;
25282 if (query !== null) {
25283 this._query._list = urlencoded.parseUrlencoded(query);
25284 }
25285 }
25286
25287 get origin() {
25288 return urlStateMachine.serializeURLOrigin(this._url);
25289 }
25290
25291 get protocol() {
25292 return this._url.scheme + ":";
25293 }
25294
25295 set protocol(v) {
25296 urlStateMachine.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" });
25297 }
25298
25299 get username() {
25300 return this._url.username;
25301 }
25302
25303 set username(v) {
25304 if (urlStateMachine.cannotHaveAUsernamePasswordPort(this._url)) {
25305 return;
25306 }
25307
25308 urlStateMachine.setTheUsername(this._url, v);
25309 }
25310
25311 get password() {
25312 return this._url.password;
25313 }
25314
25315 set password(v) {
25316 if (urlStateMachine.cannotHaveAUsernamePasswordPort(this._url)) {
25317 return;
25318 }
25319
25320 urlStateMachine.setThePassword(this._url, v);
25321 }
25322
25323 get host() {
25324 const url = this._url;
25325
25326 if (url.host === null) {
25327 return "";
25328 }
25329
25330 if (url.port === null) {
25331 return urlStateMachine.serializeHost(url.host);
25332 }
25333
25334 return urlStateMachine.serializeHost(url.host) + ":" + urlStateMachine.serializeInteger(url.port);
25335 }
25336
25337 set host(v) {
25338 if (this._url.cannotBeABaseURL) {
25339 return;
25340 }
25341
25342 urlStateMachine.basicURLParse(v, { url: this._url, stateOverride: "host" });
25343 }
25344
25345 get hostname() {
25346 if (this._url.host === null) {
25347 return "";
25348 }
25349
25350 return urlStateMachine.serializeHost(this._url.host);
25351 }
25352
25353 set hostname(v) {
25354 if (this._url.cannotBeABaseURL) {
25355 return;
25356 }
25357
25358 urlStateMachine.basicURLParse(v, { url: this._url, stateOverride: "hostname" });
25359 }
25360
25361 get port() {
25362 if (this._url.port === null) {
25363 return "";
25364 }
25365
25366 return urlStateMachine.serializeInteger(this._url.port);
25367 }
25368
25369 set port(v) {
25370 if (urlStateMachine.cannotHaveAUsernamePasswordPort(this._url)) {
25371 return;
25372 }
25373
25374 if (v === "") {
25375 this._url.port = null;
25376 } else {
25377 urlStateMachine.basicURLParse(v, { url: this._url, stateOverride: "port" });
25378 }
25379 }
25380
25381 get pathname() {
25382 if (this._url.cannotBeABaseURL) {
25383 return this._url.path[0];
25384 }
25385
25386 if (this._url.path.length === 0) {
25387 return "";
25388 }
25389
25390 return "/" + this._url.path.join("/");
25391 }
25392
25393 set pathname(v) {
25394 if (this._url.cannotBeABaseURL) {
25395 return;
25396 }
25397
25398 this._url.path = [];
25399 urlStateMachine.basicURLParse(v, { url: this._url, stateOverride: "path start" });
25400 }
25401
25402 get search() {
25403 if (this._url.query === null || this._url.query === "") {
25404 return "";
25405 }
25406
25407 return "?" + this._url.query;
25408 }
25409
25410 set search(v) {
25411 const url = this._url;
25412
25413 if (v === "") {
25414 url.query = null;
25415 this._query._list = [];
25416 return;
25417 }
25418
25419 const input = v[0] === "?" ? v.substring(1) : v;
25420 url.query = "";
25421 urlStateMachine.basicURLParse(input, { url, stateOverride: "query" });
25422 this._query._list = urlencoded.parseUrlencoded(input);
25423 }
25424
25425 get searchParams() {
25426 return this._query;
25427 }
25428
25429 get hash() {
25430 if (this._url.fragment === null || this._url.fragment === "") {
25431 return "";
25432 }
25433
25434 return "#" + this._url.fragment;
25435 }
25436
25437 set hash(v) {
25438 if (v === "") {
25439 this._url.fragment = null;
25440 return;
25441 }
25442
25443 const input = v[0] === "#" ? v.substring(1) : v;
25444 this._url.fragment = "";
25445 urlStateMachine.basicURLParse(input, { url: this._url, stateOverride: "fragment" });
25446 }
25447
25448 toJSON() {
25449 return this.href;
25450 }
25451};
25452
25453var URLImpl_1 = {
25454 implementation: implementation$1
25455};
25456
25457var URL_1 = createCommonjsModule(function (module) {
25458
25459
25460
25461
25462const impl = utils.implSymbol;
25463
25464function URL(url) {
25465 if (!new.target) {
25466 throw new TypeError(
25467 "Failed to construct 'URL'. Please use the 'new' operator; this constructor " + "cannot be called as a function."
25468 );
25469 }
25470 if (arguments.length < 1) {
25471 throw new TypeError(
25472 "Failed to construct 'URL': 1 " + "argument required, but only " + arguments.length + " present."
25473 );
25474 }
25475
25476 const args = [];
25477 for (let i = 0; i < arguments.length && i < 2; ++i) {
25478 args[i] = arguments[i];
25479 }
25480
25481 args[0] = lib$2["USVString"](args[0], { context: "Failed to construct 'URL': parameter 1" });
25482
25483 if (args[1] !== undefined) {
25484 args[1] = lib$2["USVString"](args[1], { context: "Failed to construct 'URL': parameter 2" });
25485 }
25486
25487 iface.setup(this, args);
25488}
25489
25490Object.defineProperty(URL, "prototype", {
25491 value: URL.prototype,
25492 writable: false,
25493 enumerable: false,
25494 configurable: false
25495});
25496
25497URL.prototype.toJSON = function toJSON() {
25498 if (!this || !module.exports.is(this)) {
25499 throw new TypeError("Illegal invocation");
25500 }
25501
25502 return this[impl].toJSON();
25503};
25504
25505Object.defineProperty(URL.prototype, "href", {
25506 get() {
25507 if (!this || !module.exports.is(this)) {
25508 throw new TypeError("Illegal invocation");
25509 }
25510
25511 return this[impl]["href"];
25512 },
25513
25514 set(V) {
25515 if (!this || !module.exports.is(this)) {
25516 throw new TypeError("Illegal invocation");
25517 }
25518
25519 V = lib$2["USVString"](V, { context: "Failed to set the 'href' property on 'URL': The provided value" });
25520
25521 this[impl]["href"] = V;
25522 },
25523
25524 enumerable: true,
25525 configurable: true
25526});
25527
25528URL.prototype.toString = function toString() {
25529 if (!this || !module.exports.is(this)) {
25530 throw new TypeError("Illegal invocation");
25531 }
25532 return this[impl]["href"];
25533};
25534
25535Object.defineProperty(URL.prototype, "origin", {
25536 get() {
25537 if (!this || !module.exports.is(this)) {
25538 throw new TypeError("Illegal invocation");
25539 }
25540
25541 return this[impl]["origin"];
25542 },
25543
25544 enumerable: true,
25545 configurable: true
25546});
25547
25548Object.defineProperty(URL.prototype, "protocol", {
25549 get() {
25550 if (!this || !module.exports.is(this)) {
25551 throw new TypeError("Illegal invocation");
25552 }
25553
25554 return this[impl]["protocol"];
25555 },
25556
25557 set(V) {
25558 if (!this || !module.exports.is(this)) {
25559 throw new TypeError("Illegal invocation");
25560 }
25561
25562 V = lib$2["USVString"](V, { context: "Failed to set the 'protocol' property on 'URL': The provided value" });
25563
25564 this[impl]["protocol"] = V;
25565 },
25566
25567 enumerable: true,
25568 configurable: true
25569});
25570
25571Object.defineProperty(URL.prototype, "username", {
25572 get() {
25573 if (!this || !module.exports.is(this)) {
25574 throw new TypeError("Illegal invocation");
25575 }
25576
25577 return this[impl]["username"];
25578 },
25579
25580 set(V) {
25581 if (!this || !module.exports.is(this)) {
25582 throw new TypeError("Illegal invocation");
25583 }
25584
25585 V = lib$2["USVString"](V, { context: "Failed to set the 'username' property on 'URL': The provided value" });
25586
25587 this[impl]["username"] = V;
25588 },
25589
25590 enumerable: true,
25591 configurable: true
25592});
25593
25594Object.defineProperty(URL.prototype, "password", {
25595 get() {
25596 if (!this || !module.exports.is(this)) {
25597 throw new TypeError("Illegal invocation");
25598 }
25599
25600 return this[impl]["password"];
25601 },
25602
25603 set(V) {
25604 if (!this || !module.exports.is(this)) {
25605 throw new TypeError("Illegal invocation");
25606 }
25607
25608 V = lib$2["USVString"](V, { context: "Failed to set the 'password' property on 'URL': The provided value" });
25609
25610 this[impl]["password"] = V;
25611 },
25612
25613 enumerable: true,
25614 configurable: true
25615});
25616
25617Object.defineProperty(URL.prototype, "host", {
25618 get() {
25619 if (!this || !module.exports.is(this)) {
25620 throw new TypeError("Illegal invocation");
25621 }
25622
25623 return this[impl]["host"];
25624 },
25625
25626 set(V) {
25627 if (!this || !module.exports.is(this)) {
25628 throw new TypeError("Illegal invocation");
25629 }
25630
25631 V = lib$2["USVString"](V, { context: "Failed to set the 'host' property on 'URL': The provided value" });
25632
25633 this[impl]["host"] = V;
25634 },
25635
25636 enumerable: true,
25637 configurable: true
25638});
25639
25640Object.defineProperty(URL.prototype, "hostname", {
25641 get() {
25642 if (!this || !module.exports.is(this)) {
25643 throw new TypeError("Illegal invocation");
25644 }
25645
25646 return this[impl]["hostname"];
25647 },
25648
25649 set(V) {
25650 if (!this || !module.exports.is(this)) {
25651 throw new TypeError("Illegal invocation");
25652 }
25653
25654 V = lib$2["USVString"](V, { context: "Failed to set the 'hostname' property on 'URL': The provided value" });
25655
25656 this[impl]["hostname"] = V;
25657 },
25658
25659 enumerable: true,
25660 configurable: true
25661});
25662
25663Object.defineProperty(URL.prototype, "port", {
25664 get() {
25665 if (!this || !module.exports.is(this)) {
25666 throw new TypeError("Illegal invocation");
25667 }
25668
25669 return this[impl]["port"];
25670 },
25671
25672 set(V) {
25673 if (!this || !module.exports.is(this)) {
25674 throw new TypeError("Illegal invocation");
25675 }
25676
25677 V = lib$2["USVString"](V, { context: "Failed to set the 'port' property on 'URL': The provided value" });
25678
25679 this[impl]["port"] = V;
25680 },
25681
25682 enumerable: true,
25683 configurable: true
25684});
25685
25686Object.defineProperty(URL.prototype, "pathname", {
25687 get() {
25688 if (!this || !module.exports.is(this)) {
25689 throw new TypeError("Illegal invocation");
25690 }
25691
25692 return this[impl]["pathname"];
25693 },
25694
25695 set(V) {
25696 if (!this || !module.exports.is(this)) {
25697 throw new TypeError("Illegal invocation");
25698 }
25699
25700 V = lib$2["USVString"](V, { context: "Failed to set the 'pathname' property on 'URL': The provided value" });
25701
25702 this[impl]["pathname"] = V;
25703 },
25704
25705 enumerable: true,
25706 configurable: true
25707});
25708
25709Object.defineProperty(URL.prototype, "search", {
25710 get() {
25711 if (!this || !module.exports.is(this)) {
25712 throw new TypeError("Illegal invocation");
25713 }
25714
25715 return this[impl]["search"];
25716 },
25717
25718 set(V) {
25719 if (!this || !module.exports.is(this)) {
25720 throw new TypeError("Illegal invocation");
25721 }
25722
25723 V = lib$2["USVString"](V, { context: "Failed to set the 'search' property on 'URL': The provided value" });
25724
25725 this[impl]["search"] = V;
25726 },
25727
25728 enumerable: true,
25729 configurable: true
25730});
25731
25732Object.defineProperty(URL.prototype, "searchParams", {
25733 get() {
25734 if (!this || !module.exports.is(this)) {
25735 throw new TypeError("Illegal invocation");
25736 }
25737
25738 return utils.getSameObject(this, "searchParams", () => {
25739 return utils.tryWrapperForImpl(this[impl]["searchParams"]);
25740 });
25741 },
25742
25743 enumerable: true,
25744 configurable: true
25745});
25746
25747Object.defineProperty(URL.prototype, "hash", {
25748 get() {
25749 if (!this || !module.exports.is(this)) {
25750 throw new TypeError("Illegal invocation");
25751 }
25752
25753 return this[impl]["hash"];
25754 },
25755
25756 set(V) {
25757 if (!this || !module.exports.is(this)) {
25758 throw new TypeError("Illegal invocation");
25759 }
25760
25761 V = lib$2["USVString"](V, { context: "Failed to set the 'hash' property on 'URL': The provided value" });
25762
25763 this[impl]["hash"] = V;
25764 },
25765
25766 enumerable: true,
25767 configurable: true
25768});
25769
25770Object.defineProperty(URL.prototype, Symbol.toStringTag, {
25771 value: "URL",
25772 writable: false,
25773 enumerable: false,
25774 configurable: true
25775});
25776
25777const iface = {
25778 mixedInto: [],
25779 is(obj) {
25780 if (obj) {
25781 if (obj[impl] instanceof URLImpl_1.implementation) {
25782 return true;
25783 }
25784 for (let i = 0; i < module.exports.mixedInto.length; ++i) {
25785 if (obj instanceof module.exports.mixedInto[i]) {
25786 return true;
25787 }
25788 }
25789 }
25790 return false;
25791 },
25792 isImpl(obj) {
25793 if (obj) {
25794 if (obj instanceof URLImpl_1.implementation) {
25795 return true;
25796 }
25797
25798 const wrapper = utils.wrapperForImpl(obj);
25799 for (let i = 0; i < module.exports.mixedInto.length; ++i) {
25800 if (wrapper instanceof module.exports.mixedInto[i]) {
25801 return true;
25802 }
25803 }
25804 }
25805 return false;
25806 },
25807 convert(obj, { context = "The provided value" } = {}) {
25808 if (module.exports.is(obj)) {
25809 return utils.implForWrapper(obj);
25810 }
25811 throw new TypeError(`${context} is not of type 'URL'.`);
25812 },
25813
25814 create(constructorArgs, privateData) {
25815 let obj = Object.create(URL.prototype);
25816 obj = this.setup(obj, constructorArgs, privateData);
25817 return obj;
25818 },
25819 createImpl(constructorArgs, privateData) {
25820 let obj = Object.create(URL.prototype);
25821 obj = this.setup(obj, constructorArgs, privateData);
25822 return utils.implForWrapper(obj);
25823 },
25824 _internalSetup(obj) {},
25825 setup(obj, constructorArgs, privateData) {
25826 if (!privateData) privateData = {};
25827
25828 privateData.wrapper = obj;
25829
25830 this._internalSetup(obj);
25831 Object.defineProperty(obj, impl, {
25832 value: new URLImpl_1.implementation(constructorArgs, privateData),
25833 writable: false,
25834 enumerable: false,
25835 configurable: true
25836 });
25837
25838 obj[impl][utils.wrapperSymbol] = obj;
25839 if (URLImpl_1.init) {
25840 URLImpl_1.init(obj[impl], privateData);
25841 }
25842 return obj;
25843 },
25844 interface: URL,
25845 expose: {
25846 Window: { URL },
25847 Worker: { URL }
25848 }
25849}; // iface
25850module.exports = iface;
25851});
25852
25853var URL$1 = URL_1.interface;
25854var URLSearchParams = URLSearchParams_1.interface;
25855
25856var parseURL = urlStateMachine.parseURL;
25857var basicURLParse = urlStateMachine.basicURLParse;
25858var serializeURL = urlStateMachine.serializeURL;
25859var serializeHost = urlStateMachine.serializeHost;
25860var serializeInteger = urlStateMachine.serializeInteger;
25861var serializeURLOrigin = urlStateMachine.serializeURLOrigin;
25862var setTheUsername = urlStateMachine.setTheUsername;
25863var setThePassword = urlStateMachine.setThePassword;
25864var cannotHaveAUsernamePasswordPort = urlStateMachine.cannotHaveAUsernamePasswordPort;
25865
25866var percentDecode$1 = urlencoded.percentDecode;
25867
25868var publicApi = {
25869 URL: URL$1,
25870 URLSearchParams: URLSearchParams,
25871 parseURL: parseURL,
25872 basicURLParse: basicURLParse,
25873 serializeURL: serializeURL,
25874 serializeHost: serializeHost,
25875 serializeInteger: serializeInteger,
25876 serializeURLOrigin: serializeURLOrigin,
25877 setTheUsername: setTheUsername,
25878 setThePassword: setThePassword,
25879 cannotHaveAUsernamePasswordPort: cannotHaveAUsernamePasswordPort,
25880 percentDecode: percentDecode$1
25881};
25882
25883var require$$0 = getCjsExportFromNamespace(lib);
25884
25885// avoid circular dependency when using jest.mock()
25886let fetch$1;
25887try {
25888 // note that jest is not a global, but is injected somehow into
25889 // the environment. So we can't be safe and check for global.jest
25890 // Hence the try/catch
25891 fetch$1 = jest.requireActual('node-fetch'); //eslint-disable-line no-undef
25892} catch (e) {
25893 fetch$1 = require$$0;
25894}
25895const Request$1 = fetch$1.Request;
25896const Response$1 = fetch$1.Response;
25897const Headers$1 = fetch$1.Headers;
25898
25899
25900
25901const { setUrlImplementation } = requestUtils;
25902setUrlImplementation(publicApi.URL);
25903
25904lib$1.global = commonjsGlobal;
25905lib$1.statusTextMap = http.STATUS_CODES;
25906lib$1.Stream = Stream;
25907
25908lib$1.config = Object.assign(lib$1.config, {
25909 Promise: Promise,
25910 Request: Request$1,
25911 Response: Response$1,
25912 Headers: Headers$1
25913});
25914
25915var server = lib$1.createInstance();
25916
25917export default server;