[SignalingServer] Optimize dependent modules
[platform/framework/web/wrtjs.git] / device_home / node_modules / pngjs / browser.js
1 (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.png = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2 (function (Buffer){
3 'use strict';
4
5 var interlaceUtils = require('./interlace');
6
7 var pixelBppMapper = [
8   // 0 - dummy entry
9   function() {},
10
11   // 1 - L
12   // 0: 0, 1: 0, 2: 0, 3: 0xff
13   function(pxData, data, pxPos, rawPos) {
14     if (rawPos === data.length) {
15       throw new Error('Ran out of data');
16     }
17
18     var pixel = data[rawPos];
19     pxData[pxPos] = pixel;
20     pxData[pxPos + 1] = pixel;
21     pxData[pxPos + 2] = pixel;
22     pxData[pxPos + 3] = 0xff;
23   },
24
25   // 2 - LA
26   // 0: 0, 1: 0, 2: 0, 3: 1
27   function(pxData, data, pxPos, rawPos) {
28     if (rawPos + 1 >= data.length) {
29       throw new Error('Ran out of data');
30     }
31
32     var pixel = data[rawPos];
33     pxData[pxPos] = pixel;
34     pxData[pxPos + 1] = pixel;
35     pxData[pxPos + 2] = pixel;
36     pxData[pxPos + 3] = data[rawPos + 1];
37   },
38
39   // 3 - RGB
40   // 0: 0, 1: 1, 2: 2, 3: 0xff
41   function(pxData, data, pxPos, rawPos) {
42     if (rawPos + 2 >= data.length) {
43       throw new Error('Ran out of data');
44     }
45
46     pxData[pxPos] = data[rawPos];
47     pxData[pxPos + 1] = data[rawPos + 1];
48     pxData[pxPos + 2] = data[rawPos + 2];
49     pxData[pxPos + 3] = 0xff;
50   },
51
52   // 4 - RGBA
53   // 0: 0, 1: 1, 2: 2, 3: 3
54   function(pxData, data, pxPos, rawPos) {
55     if (rawPos + 3 >= data.length) {
56       throw new Error('Ran out of data');
57     }
58
59     pxData[pxPos] = data[rawPos];
60     pxData[pxPos + 1] = data[rawPos + 1];
61     pxData[pxPos + 2] = data[rawPos + 2];
62     pxData[pxPos + 3] = data[rawPos + 3];
63   }
64 ];
65
66 var pixelBppCustomMapper = [
67   // 0 - dummy entry
68   function() {},
69
70   // 1 - L
71   // 0: 0, 1: 0, 2: 0, 3: 0xff
72   function(pxData, pixelData, pxPos, maxBit) {
73     var pixel = pixelData[0];
74     pxData[pxPos] = pixel;
75     pxData[pxPos + 1] = pixel;
76     pxData[pxPos + 2] = pixel;
77     pxData[pxPos + 3] = maxBit;
78   },
79
80   // 2 - LA
81   // 0: 0, 1: 0, 2: 0, 3: 1
82   function(pxData, pixelData, pxPos) {
83     var pixel = pixelData[0];
84     pxData[pxPos] = pixel;
85     pxData[pxPos + 1] = pixel;
86     pxData[pxPos + 2] = pixel;
87     pxData[pxPos + 3] = pixelData[1];
88   },
89
90   // 3 - RGB
91   // 0: 0, 1: 1, 2: 2, 3: 0xff
92   function(pxData, pixelData, pxPos, maxBit) {
93     pxData[pxPos] = pixelData[0];
94     pxData[pxPos + 1] = pixelData[1];
95     pxData[pxPos + 2] = pixelData[2];
96     pxData[pxPos + 3] = maxBit;
97   },
98
99   // 4 - RGBA
100   // 0: 0, 1: 1, 2: 2, 3: 3
101   function(pxData, pixelData, pxPos) {
102     pxData[pxPos] = pixelData[0];
103     pxData[pxPos + 1] = pixelData[1];
104     pxData[pxPos + 2] = pixelData[2];
105     pxData[pxPos + 3] = pixelData[3];
106   }
107 ];
108
109 function bitRetriever(data, depth) {
110
111   var leftOver = [];
112   var i = 0;
113
114   function split() {
115     if (i === data.length) {
116       throw new Error('Ran out of data');
117     }
118     var byte = data[i];
119     i++;
120     var byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
121     switch (depth) {
122       default:
123         throw new Error('unrecognised depth');
124       case 16:
125         byte2 = data[i];
126         i++;
127         leftOver.push(((byte << 8) + byte2));
128         break;
129       case 4:
130         byte2 = byte & 0x0f;
131         byte1 = byte >> 4;
132         leftOver.push(byte1, byte2);
133         break;
134       case 2:
135         byte4 = byte & 3;
136         byte3 = byte >> 2 & 3;
137         byte2 = byte >> 4 & 3;
138         byte1 = byte >> 6 & 3;
139         leftOver.push(byte1, byte2, byte3, byte4);
140         break;
141       case 1:
142         byte8 = byte & 1;
143         byte7 = byte >> 1 & 1;
144         byte6 = byte >> 2 & 1;
145         byte5 = byte >> 3 & 1;
146         byte4 = byte >> 4 & 1;
147         byte3 = byte >> 5 & 1;
148         byte2 = byte >> 6 & 1;
149         byte1 = byte >> 7 & 1;
150         leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
151         break;
152     }
153   }
154
155   return {
156     get: function(count) {
157       while (leftOver.length < count) {
158         split();
159       }
160       var returner = leftOver.slice(0, count);
161       leftOver = leftOver.slice(count);
162       return returner;
163     },
164     resetAfterLine: function() {
165       leftOver.length = 0;
166     },
167     end: function() {
168       if (i !== data.length) {
169         throw new Error('extra data found');
170       }
171     }
172   };
173 }
174
175 function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { // eslint-disable-line max-params
176   var imageWidth = image.width;
177   var imageHeight = image.height;
178   var imagePass = image.index;
179   for (var y = 0; y < imageHeight; y++) {
180     for (var x = 0; x < imageWidth; x++) {
181       var pxPos = getPxPos(x, y, imagePass);
182       pixelBppMapper[bpp](pxData, data, pxPos, rawPos);
183       rawPos += bpp; //eslint-disable-line no-param-reassign
184     }
185   }
186   return rawPos;
187 }
188
189 function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { // eslint-disable-line max-params
190   var imageWidth = image.width;
191   var imageHeight = image.height;
192   var imagePass = image.index;
193   for (var y = 0; y < imageHeight; y++) {
194     for (var x = 0; x < imageWidth; x++) {
195       var pixelData = bits.get(bpp);
196       var pxPos = getPxPos(x, y, imagePass);
197       pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);
198     }
199     bits.resetAfterLine();
200   }
201 }
202
203 exports.dataToBitMap = function(data, bitmapInfo) {
204
205   var width = bitmapInfo.width;
206   var height = bitmapInfo.height;
207   var depth = bitmapInfo.depth;
208   var bpp = bitmapInfo.bpp;
209   var interlace = bitmapInfo.interlace;
210
211   if (depth !== 8) {
212     var bits = bitRetriever(data, depth);
213   }
214   var pxData;
215   if (depth <= 8) {
216     pxData = new Buffer(width * height * 4);
217   }
218   else {
219     pxData = new Uint16Array(width * height * 4);
220   }
221   var maxBit = Math.pow(2, depth) - 1;
222   var rawPos = 0;
223   var images;
224   var getPxPos;
225
226   if (interlace) {
227     images = interlaceUtils.getImagePasses(width, height);
228     getPxPos = interlaceUtils.getInterlaceIterator(width, height);
229   }
230   else {
231     var nonInterlacedPxPos = 0;
232     getPxPos = function() {
233       var returner = nonInterlacedPxPos;
234       nonInterlacedPxPos += 4;
235       return returner;
236     };
237     images = [{ width: width, height: height }];
238   }
239
240   for (var imageIndex = 0; imageIndex < images.length; imageIndex++) {
241     if (depth === 8) {
242       rawPos = mapImage8Bit(images[imageIndex], pxData, getPxPos, bpp, data, rawPos);
243     }
244     else {
245       mapImageCustomBit(images[imageIndex], pxData, getPxPos, bpp, bits, maxBit);
246     }
247   }
248   if (depth === 8) {
249     if (rawPos !== data.length) {
250       throw new Error('extra data found');
251     }
252   }
253   else {
254     bits.end();
255   }
256
257   return pxData;
258 };
259
260 }).call(this,require("buffer").Buffer)
261 },{"./interlace":11,"buffer":32}],2:[function(require,module,exports){
262 (function (Buffer){
263 'use strict';
264
265 var constants = require('./constants');
266
267 module.exports = function(dataIn, width, height, options) {
268   var outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(options.colorType) !== -1;
269   if (options.colorType === options.inputColorType) {
270     var bigEndian = (function() {
271       var buffer = new ArrayBuffer(2);
272       new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
273       // Int16Array uses the platform's endianness.
274       return new Int16Array(buffer)[0] !== 256;
275     })();
276     // If no need to convert to grayscale and alpha is present/absent in both, take a fast route
277     if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) {
278       return dataIn;
279     }
280   }
281
282   // map to a UInt16 array if data is 16bit, fix endianness below
283   var data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
284
285   var maxValue = 255;
286   var inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
287   if (inBpp === 4 && !options.inputHasAlpha) {
288     inBpp = 3;
289   }
290   var outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
291   if (options.bitDepth === 16) {
292     maxValue = 65535;
293     outBpp *= 2;
294   }
295   var outData = new Buffer(width * height * outBpp);
296
297   var inIndex = 0;
298   var outIndex = 0;
299
300   var bgColor = options.bgColor || {};
301   if (bgColor.red === undefined) {
302     bgColor.red = maxValue;
303   }
304   if (bgColor.green === undefined) {
305     bgColor.green = maxValue;
306   }
307   if (bgColor.blue === undefined) {
308     bgColor.blue = maxValue;
309   }
310
311   function getRGBA() {
312     var red;
313     var green;
314     var blue;
315     var alpha = maxValue;
316     switch (options.inputColorType) {
317       case constants.COLORTYPE_COLOR_ALPHA:
318         alpha = data[inIndex + 3];
319         red = data[inIndex];
320         green = data[inIndex + 1];
321         blue = data[inIndex + 2];
322         break;
323       case constants.COLORTYPE_COLOR:
324         red = data[inIndex];
325         green = data[inIndex + 1];
326         blue = data[inIndex + 2];
327         break;
328       case constants.COLORTYPE_ALPHA:
329         alpha = data[inIndex + 1];
330         red = data[inIndex];
331         green = red;
332         blue = red;
333         break;
334       case constants.COLORTYPE_GRAYSCALE:
335         red = data[inIndex];
336         green = red;
337         blue = red;
338         break;
339       default:
340         throw new Error('input color type:' + options.inputColorType + ' is not supported at present');
341     }
342
343     if (options.inputHasAlpha) {
344       if (!outHasAlpha) {
345         alpha /= maxValue;
346         red = Math.min(Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), maxValue);
347         green = Math.min(Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), maxValue);
348         blue = Math.min(Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), maxValue);
349       }
350     }
351     return { red: red, green: green, blue: blue, alpha: alpha };
352   }
353
354   for (var y = 0; y < height; y++) {
355     for (var x = 0; x < width; x++) {
356       var rgba = getRGBA(data, inIndex);
357
358       switch (options.colorType) {
359         case constants.COLORTYPE_COLOR_ALPHA:
360         case constants.COLORTYPE_COLOR:
361           if (options.bitDepth === 8) {
362             outData[outIndex] = rgba.red;
363             outData[outIndex + 1] = rgba.green;
364             outData[outIndex + 2] = rgba.blue;
365             if (outHasAlpha) {
366               outData[outIndex + 3] = rgba.alpha;
367             }
368           }
369           else {
370             outData.writeUInt16BE(rgba.red, outIndex);
371             outData.writeUInt16BE(rgba.green, outIndex + 2);
372             outData.writeUInt16BE(rgba.blue, outIndex + 4);
373             if (outHasAlpha) {
374               outData.writeUInt16BE(rgba.alpha, outIndex + 6);
375             }
376           }
377           break;
378         case constants.COLORTYPE_ALPHA:
379         case constants.COLORTYPE_GRAYSCALE:
380           // Convert to grayscale and alpha
381           var grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
382           if (options.bitDepth === 8) {
383             outData[outIndex] = grayscale;
384             if (outHasAlpha) {
385               outData[outIndex + 1] = rgba.alpha;
386             }
387           }
388           else {
389             outData.writeUInt16BE(grayscale, outIndex);
390             if (outHasAlpha) {
391               outData.writeUInt16BE(rgba.alpha, outIndex + 2);
392             }
393           }
394           break;
395         default:
396           throw new Error('unrecognised color Type ' + options.colorType);
397       }
398
399       inIndex += inBpp;
400       outIndex += outBpp;
401     }
402   }
403
404   return outData;
405 };
406
407 }).call(this,require("buffer").Buffer)
408 },{"./constants":4,"buffer":32}],3:[function(require,module,exports){
409 (function (process,Buffer){
410 'use strict';
411
412
413 var util = require('util');
414 var Stream = require('stream');
415
416
417 var ChunkStream = module.exports = function() {
418   Stream.call(this);
419
420   this._buffers = [];
421   this._buffered = 0;
422
423   this._reads = [];
424   this._paused = false;
425
426   this._encoding = 'utf8';
427   this.writable = true;
428 };
429 util.inherits(ChunkStream, Stream);
430
431
432 ChunkStream.prototype.read = function(length, callback) {
433
434   this._reads.push({
435     length: Math.abs(length), // if length < 0 then at most this length
436     allowLess: length < 0,
437     func: callback
438   });
439
440   process.nextTick(function() {
441     this._process();
442
443     // its paused and there is not enought data then ask for more
444     if (this._paused && this._reads.length > 0) {
445       this._paused = false;
446
447       this.emit('drain');
448     }
449   }.bind(this));
450 };
451
452 ChunkStream.prototype.write = function(data, encoding) {
453
454   if (!this.writable) {
455     this.emit('error', new Error('Stream not writable'));
456     return false;
457   }
458
459   var dataBuffer;
460   if (Buffer.isBuffer(data)) {
461     dataBuffer = data;
462   }
463   else {
464     dataBuffer = new Buffer(data, encoding || this._encoding);
465   }
466
467   this._buffers.push(dataBuffer);
468   this._buffered += dataBuffer.length;
469
470   this._process();
471
472   // ok if there are no more read requests
473   if (this._reads && this._reads.length === 0) {
474     this._paused = true;
475   }
476
477   return this.writable && !this._paused;
478 };
479
480 ChunkStream.prototype.end = function(data, encoding) {
481
482   if (data) {
483     this.write(data, encoding);
484   }
485
486   this.writable = false;
487
488   // already destroyed
489   if (!this._buffers) {
490     return;
491   }
492
493   // enqueue or handle end
494   if (this._buffers.length === 0) {
495     this._end();
496   }
497   else {
498     this._buffers.push(null);
499     this._process();
500   }
501 };
502
503 ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
504
505 ChunkStream.prototype._end = function() {
506
507   if (this._reads.length > 0) {
508     this.emit('error',
509       new Error('Unexpected end of input')
510     );
511   }
512
513   this.destroy();
514 };
515
516 ChunkStream.prototype.destroy = function() {
517
518   if (!this._buffers) {
519     return;
520   }
521
522   this.writable = false;
523   this._reads = null;
524   this._buffers = null;
525
526   this.emit('close');
527 };
528
529 ChunkStream.prototype._processReadAllowingLess = function(read) {
530   // ok there is any data so that we can satisfy this request
531   this._reads.shift(); // == read
532
533   // first we need to peek into first buffer
534   var smallerBuf = this._buffers[0];
535
536   // ok there is more data than we need
537   if (smallerBuf.length > read.length) {
538
539     this._buffered -= read.length;
540     this._buffers[0] = smallerBuf.slice(read.length);
541
542     read.func.call(this, smallerBuf.slice(0, read.length));
543
544   }
545   else {
546     // ok this is less than maximum length so use it all
547     this._buffered -= smallerBuf.length;
548     this._buffers.shift(); // == smallerBuf
549
550     read.func.call(this, smallerBuf);
551   }
552 };
553
554 ChunkStream.prototype._processRead = function(read) {
555   this._reads.shift(); // == read
556
557   var pos = 0;
558   var count = 0;
559   var data = new Buffer(read.length);
560
561   // create buffer for all data
562   while (pos < read.length) {
563
564     var buf = this._buffers[count++];
565     var len = Math.min(buf.length, read.length - pos);
566
567     buf.copy(data, pos, 0, len);
568     pos += len;
569
570     // last buffer wasn't used all so just slice it and leave
571     if (len !== buf.length) {
572       this._buffers[--count] = buf.slice(len);
573     }
574   }
575
576   // remove all used buffers
577   if (count > 0) {
578     this._buffers.splice(0, count);
579   }
580
581   this._buffered -= read.length;
582
583   read.func.call(this, data);
584 };
585
586 ChunkStream.prototype._process = function() {
587
588   try {
589     // as long as there is any data and read requests
590     while (this._buffered > 0 && this._reads && this._reads.length > 0) {
591
592       var read = this._reads[0];
593
594       // read any data (but no more than length)
595       if (read.allowLess) {
596         this._processReadAllowingLess(read);
597
598       }
599       else if (this._buffered >= read.length) {
600         // ok we can meet some expectations
601
602         this._processRead(read);
603       }
604       else {
605         // not enought data to satisfy first request in queue
606         // so we need to wait for more
607         break;
608       }
609     }
610
611     if (this._buffers && !this.writable) {
612       this._end();
613     }
614   }
615   catch (ex) {
616     this.emit('error', ex);
617   }
618 };
619
620 }).call(this,require('_process'),require("buffer").Buffer)
621 },{"_process":51,"buffer":32,"stream":64,"util":69}],4:[function(require,module,exports){
622 'use strict';
623
624
625 module.exports = {
626
627   PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
628
629   TYPE_IHDR: 0x49484452,
630   TYPE_IEND: 0x49454e44,
631   TYPE_IDAT: 0x49444154,
632   TYPE_PLTE: 0x504c5445,
633   TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase
634   TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase
635
636   // color-type bits
637   COLORTYPE_GRAYSCALE: 0,
638   COLORTYPE_PALETTE: 1,
639   COLORTYPE_COLOR: 2,
640   COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
641
642   // color-type combinations
643   COLORTYPE_PALETTE_COLOR: 3,
644   COLORTYPE_COLOR_ALPHA: 6,
645
646   COLORTYPE_TO_BPP_MAP: {
647     0: 1,
648     2: 3,
649     3: 1,
650     4: 2,
651     6: 4
652   },
653
654   GAMMA_DIVISION: 100000
655 };
656
657 },{}],5:[function(require,module,exports){
658 'use strict';
659
660 var crcTable = [];
661
662 (function() {
663   for (var i = 0; i < 256; i++) {
664     var currentCrc = i;
665     for (var j = 0; j < 8; j++) {
666       if (currentCrc & 1) {
667         currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
668       }
669       else {
670         currentCrc = currentCrc >>> 1;
671       }
672     }
673     crcTable[i] = currentCrc;
674   }
675 }());
676
677 var CrcCalculator = module.exports = function() {
678   this._crc = -1;
679 };
680
681 CrcCalculator.prototype.write = function(data) {
682
683   for (var i = 0; i < data.length; i++) {
684     this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
685   }
686   return true;
687 };
688
689 CrcCalculator.prototype.crc32 = function() {
690   return this._crc ^ -1;
691 };
692
693
694 CrcCalculator.crc32 = function(buf) {
695
696   var crc = -1;
697   for (var i = 0; i < buf.length; i++) {
698     crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
699   }
700   return crc ^ -1;
701 };
702
703 },{}],6:[function(require,module,exports){
704 (function (Buffer){
705 'use strict';
706
707 var paethPredictor = require('./paeth-predictor');
708
709 function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
710
711   for (var x = 0; x < byteWidth; x++) {
712     rawData[rawPos + x] = pxData[pxPos + x];
713   }
714 }
715
716 function filterSumNone(pxData, pxPos, byteWidth) {
717
718   var sum = 0;
719   var length = pxPos + byteWidth;
720
721   for (var i = pxPos; i < length; i++) {
722     sum += Math.abs(pxData[i]);
723   }
724   return sum;
725 }
726
727 function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
728
729   for (var x = 0; x < byteWidth; x++) {
730
731     var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
732     var val = pxData[pxPos + x] - left;
733
734     rawData[rawPos + x] = val;
735   }
736 }
737
738 function filterSumSub(pxData, pxPos, byteWidth, bpp) {
739
740   var sum = 0;
741   for (var x = 0; x < byteWidth; x++) {
742
743     var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
744     var val = pxData[pxPos + x] - left;
745
746     sum += Math.abs(val);
747   }
748
749   return sum;
750 }
751
752 function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
753
754   for (var x = 0; x < byteWidth; x++) {
755
756     var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
757     var val = pxData[pxPos + x] - up;
758
759     rawData[rawPos + x] = val;
760   }
761 }
762
763 function filterSumUp(pxData, pxPos, byteWidth) {
764
765   var sum = 0;
766   var length = pxPos + byteWidth;
767   for (var x = pxPos; x < length; x++) {
768
769     var up = pxPos > 0 ? pxData[x - byteWidth] : 0;
770     var val = pxData[x] - up;
771
772     sum += Math.abs(val);
773   }
774
775   return sum;
776 }
777
778 function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
779
780   for (var x = 0; x < byteWidth; x++) {
781
782     var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
783     var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
784     var val = pxData[pxPos + x] - ((left + up) >> 1);
785
786     rawData[rawPos + x] = val;
787   }
788 }
789
790 function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
791
792   var sum = 0;
793   for (var x = 0; x < byteWidth; x++) {
794
795     var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
796     var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
797     var val = pxData[pxPos + x] - ((left + up) >> 1);
798
799     sum += Math.abs(val);
800   }
801
802   return sum;
803 }
804
805 function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
806
807   for (var x = 0; x < byteWidth; x++) {
808
809     var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
810     var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
811     var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
812     var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
813
814     rawData[rawPos + x] = val;
815   }
816 }
817
818 function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
819   var sum = 0;
820   for (var x = 0; x < byteWidth; x++) {
821
822     var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
823     var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
824     var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
825     var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
826
827     sum += Math.abs(val);
828   }
829
830   return sum;
831 }
832
833 var filters = {
834   0: filterNone,
835   1: filterSub,
836   2: filterUp,
837   3: filterAvg,
838   4: filterPaeth
839 };
840
841 var filterSums = {
842   0: filterSumNone,
843   1: filterSumSub,
844   2: filterSumUp,
845   3: filterSumAvg,
846   4: filterSumPaeth
847 };
848
849 module.exports = function(pxData, width, height, options, bpp) {
850
851   var filterTypes;
852   if (!('filterType' in options) || options.filterType === -1) {
853     filterTypes = [0, 1, 2, 3, 4];
854   }
855   else if (typeof options.filterType === 'number') {
856     filterTypes = [options.filterType];
857   }
858   else {
859     throw new Error('unrecognised filter types');
860   }
861
862   if (options.bitDepth === 16) {
863     bpp *= 2;
864   }
865   var byteWidth = width * bpp;
866   var rawPos = 0;
867   var pxPos = 0;
868   var rawData = new Buffer((byteWidth + 1) * height);
869
870   var sel = filterTypes[0];
871
872   for (var y = 0; y < height; y++) {
873
874     if (filterTypes.length > 1) {
875       // find best filter for this line (with lowest sum of values)
876       var min = Infinity;
877
878       for (var i = 0; i < filterTypes.length; i++) {
879         var sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
880         if (sum < min) {
881           sel = filterTypes[i];
882           min = sum;
883         }
884       }
885     }
886
887     rawData[rawPos] = sel;
888     rawPos++;
889     filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
890     rawPos += byteWidth;
891     pxPos += byteWidth;
892   }
893   return rawData;
894 };
895
896 }).call(this,require("buffer").Buffer)
897 },{"./paeth-predictor":15,"buffer":32}],7:[function(require,module,exports){
898 (function (Buffer){
899 'use strict';
900
901 var util = require('util');
902 var ChunkStream = require('./chunkstream');
903 var Filter = require('./filter-parse');
904
905
906 var FilterAsync = module.exports = function(bitmapInfo) {
907   ChunkStream.call(this);
908
909   var buffers = [];
910   var that = this;
911   this._filter = new Filter(bitmapInfo, {
912     read: this.read.bind(this),
913     write: function(buffer) {
914       buffers.push(buffer);
915     },
916     complete: function() {
917       that.emit('complete', Buffer.concat(buffers));
918     }
919   });
920
921   this._filter.start();
922 };
923 util.inherits(FilterAsync, ChunkStream);
924
925 }).call(this,require("buffer").Buffer)
926 },{"./chunkstream":3,"./filter-parse":9,"buffer":32,"util":69}],8:[function(require,module,exports){
927 (function (Buffer){
928 'use strict';
929
930 var SyncReader = require('./sync-reader');
931 var Filter = require('./filter-parse');
932
933
934 exports.process = function(inBuffer, bitmapInfo) {
935
936   var outBuffers = [];
937   var reader = new SyncReader(inBuffer);
938   var filter = new Filter(bitmapInfo, {
939     read: reader.read.bind(reader),
940     write: function(bufferPart) {
941       outBuffers.push(bufferPart);
942     },
943     complete: function() {
944     }
945   });
946
947   filter.start();
948   reader.process();
949
950   return Buffer.concat(outBuffers);
951 };
952 }).call(this,require("buffer").Buffer)
953 },{"./filter-parse":9,"./sync-reader":22,"buffer":32}],9:[function(require,module,exports){
954 (function (Buffer){
955 'use strict';
956
957 var interlaceUtils = require('./interlace');
958 var paethPredictor = require('./paeth-predictor');
959
960 function getByteWidth(width, bpp, depth) {
961   var byteWidth = width * bpp;
962   if (depth !== 8) {
963     byteWidth = Math.ceil(byteWidth / (8 / depth));
964   }
965   return byteWidth;
966 }
967
968 var Filter = module.exports = function(bitmapInfo, dependencies) {
969
970   var width = bitmapInfo.width;
971   var height = bitmapInfo.height;
972   var interlace = bitmapInfo.interlace;
973   var bpp = bitmapInfo.bpp;
974   var depth = bitmapInfo.depth;
975
976   this.read = dependencies.read;
977   this.write = dependencies.write;
978   this.complete = dependencies.complete;
979
980   this._imageIndex = 0;
981   this._images = [];
982   if (interlace) {
983     var passes = interlaceUtils.getImagePasses(width, height);
984     for (var i = 0; i < passes.length; i++) {
985       this._images.push({
986         byteWidth: getByteWidth(passes[i].width, bpp, depth),
987         height: passes[i].height,
988         lineIndex: 0
989       });
990     }
991   }
992   else {
993     this._images.push({
994       byteWidth: getByteWidth(width, bpp, depth),
995       height: height,
996       lineIndex: 0
997     });
998   }
999
1000   // when filtering the line we look at the pixel to the left
1001   // the spec also says it is done on a byte level regardless of the number of pixels
1002   // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back
1003   // a pixel rather than just a different byte part. However if we are sub byte, we ignore.
1004   if (depth === 8) {
1005     this._xComparison = bpp;
1006   }
1007   else if (depth === 16) {
1008     this._xComparison = bpp * 2;
1009   }
1010   else {
1011     this._xComparison = 1;
1012   }
1013 };
1014
1015 Filter.prototype.start = function() {
1016   this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this));
1017 };
1018
1019 Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
1020
1021   var xComparison = this._xComparison;
1022   var xBiggerThan = xComparison - 1;
1023
1024   for (var x = 0; x < byteWidth; x++) {
1025     var rawByte = rawData[1 + x];
1026     var f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
1027     unfilteredLine[x] = rawByte + f1Left;
1028   }
1029 };
1030
1031 Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
1032
1033   var lastLine = this._lastLine;
1034
1035   for (var x = 0; x < byteWidth; x++) {
1036     var rawByte = rawData[1 + x];
1037     var f2Up = lastLine ? lastLine[x] : 0;
1038     unfilteredLine[x] = rawByte + f2Up;
1039   }
1040 };
1041
1042 Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
1043
1044   var xComparison = this._xComparison;
1045   var xBiggerThan = xComparison - 1;
1046   var lastLine = this._lastLine;
1047
1048   for (var x = 0; x < byteWidth; x++) {
1049     var rawByte = rawData[1 + x];
1050     var f3Up = lastLine ? lastLine[x] : 0;
1051     var f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
1052     var f3Add = Math.floor((f3Left + f3Up) / 2);
1053     unfilteredLine[x] = rawByte + f3Add;
1054   }
1055 };
1056
1057 Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
1058
1059   var xComparison = this._xComparison;
1060   var xBiggerThan = xComparison - 1;
1061   var lastLine = this._lastLine;
1062
1063   for (var x = 0; x < byteWidth; x++) {
1064     var rawByte = rawData[1 + x];
1065     var f4Up = lastLine ? lastLine[x] : 0;
1066     var f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
1067     var f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
1068     var f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
1069     unfilteredLine[x] = rawByte + f4Add;
1070   }
1071 };
1072
1073 Filter.prototype._reverseFilterLine = function(rawData) {
1074
1075   var filter = rawData[0];
1076   var unfilteredLine;
1077   var currentImage = this._images[this._imageIndex];
1078   var byteWidth = currentImage.byteWidth;
1079
1080   if (filter === 0) {
1081     unfilteredLine = rawData.slice(1, byteWidth + 1);
1082   }
1083   else {
1084
1085     unfilteredLine = new Buffer(byteWidth);
1086
1087     switch (filter) {
1088       case 1:
1089         this._unFilterType1(rawData, unfilteredLine, byteWidth);
1090         break;
1091       case 2:
1092         this._unFilterType2(rawData, unfilteredLine, byteWidth);
1093         break;
1094       case 3:
1095         this._unFilterType3(rawData, unfilteredLine, byteWidth);
1096         break;
1097       case 4:
1098         this._unFilterType4(rawData, unfilteredLine, byteWidth);
1099         break;
1100       default:
1101         throw new Error('Unrecognised filter type - ' + filter);
1102     }
1103   }
1104
1105   this.write(unfilteredLine);
1106
1107   currentImage.lineIndex++;
1108   if (currentImage.lineIndex >= currentImage.height) {
1109     this._lastLine = null;
1110     this._imageIndex++;
1111     currentImage = this._images[this._imageIndex];
1112   }
1113   else {
1114     this._lastLine = unfilteredLine;
1115   }
1116
1117   if (currentImage) {
1118     // read, using the byte width that may be from the new current image
1119     this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
1120   }
1121   else {
1122     this._lastLine = null;
1123     this.complete();
1124   }
1125 };
1126
1127 }).call(this,require("buffer").Buffer)
1128 },{"./interlace":11,"./paeth-predictor":15,"buffer":32}],10:[function(require,module,exports){
1129 (function (Buffer){
1130 'use strict';
1131
1132 function dePalette(indata, outdata, width, height, palette) {
1133   var pxPos = 0;
1134   // use values from palette
1135   for (var y = 0; y < height; y++) {
1136     for (var x = 0; x < width; x++) {
1137       var color = palette[indata[pxPos]];
1138
1139       if (!color) {
1140         throw new Error('index ' + indata[pxPos] + ' not in palette');
1141       }
1142
1143       for (var i = 0; i < 4; i++) {
1144         outdata[pxPos + i] = color[i];
1145       }
1146       pxPos += 4;
1147     }
1148   }
1149 }
1150
1151 function replaceTransparentColor(indata, outdata, width, height, transColor) {
1152   var pxPos = 0;
1153   for (var y = 0; y < height; y++) {
1154     for (var x = 0; x < width; x++) {
1155       var makeTrans = false;
1156
1157       if (transColor.length === 1) {
1158         if (transColor[0] === indata[pxPos]) {
1159           makeTrans = true;
1160         }
1161       }
1162       else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) {
1163         makeTrans = true;
1164       }
1165       if (makeTrans) {
1166         for (var i = 0; i < 4; i++) {
1167           outdata[pxPos + i] = 0;
1168         }
1169       }
1170       pxPos += 4;
1171     }
1172   }
1173 }
1174
1175 function scaleDepth(indata, outdata, width, height, depth) {
1176   var maxOutSample = 255;
1177   var maxInSample = Math.pow(2, depth) - 1;
1178   var pxPos = 0;
1179
1180   for (var y = 0; y < height; y++) {
1181     for (var x = 0; x < width; x++) {
1182       for (var i = 0; i < 4; i++) {
1183         outdata[pxPos + i] = Math.floor((indata[pxPos + i] * maxOutSample) / maxInSample + 0.5);
1184       }
1185       pxPos += 4;
1186     }
1187   }
1188 }
1189
1190 module.exports = function(indata, imageData) {
1191
1192   var depth = imageData.depth;
1193   var width = imageData.width;
1194   var height = imageData.height;
1195   var colorType = imageData.colorType;
1196   var transColor = imageData.transColor;
1197   var palette = imageData.palette;
1198
1199   var outdata = indata; // only different for 16 bits
1200
1201   if (colorType === 3) { // paletted
1202     dePalette(indata, outdata, width, height, palette);
1203   }
1204   else {
1205     if (transColor) {
1206       replaceTransparentColor(indata, outdata, width, height, transColor);
1207     }
1208     // if it needs scaling
1209     if (depth !== 8) {
1210       // if we need to change the buffer size
1211       if (depth === 16) {
1212         outdata = new Buffer(width * height * 4);
1213       }
1214       scaleDepth(indata, outdata, width, height, depth);
1215     }
1216   }
1217   return outdata;
1218 };
1219
1220 }).call(this,require("buffer").Buffer)
1221 },{"buffer":32}],11:[function(require,module,exports){
1222 'use strict';
1223
1224 // Adam 7
1225 //   0 1 2 3 4 5 6 7
1226 // 0 x 6 4 6 x 6 4 6
1227 // 1 7 7 7 7 7 7 7 7
1228 // 2 5 6 5 6 5 6 5 6
1229 // 3 7 7 7 7 7 7 7 7
1230 // 4 3 6 4 6 3 6 4 6
1231 // 5 7 7 7 7 7 7 7 7
1232 // 6 5 6 5 6 5 6 5 6
1233 // 7 7 7 7 7 7 7 7 7
1234
1235
1236 var imagePasses = [
1237   { // pass 1 - 1px
1238     x: [0],
1239     y: [0]
1240   },
1241   { // pass 2 - 1px
1242     x: [4],
1243     y: [0]
1244   },
1245   { // pass 3 - 2px
1246     x: [0, 4],
1247     y: [4]
1248   },
1249   { // pass 4 - 4px
1250     x: [2, 6],
1251     y: [0, 4]
1252   },
1253   { // pass 5 - 8px
1254     x: [0, 2, 4, 6],
1255     y: [2, 6]
1256   },
1257   { // pass 6 - 16px
1258     x: [1, 3, 5, 7],
1259     y: [0, 2, 4, 6]
1260   },
1261   { // pass 7 - 32px
1262     x: [0, 1, 2, 3, 4, 5, 6, 7],
1263     y: [1, 3, 5, 7]
1264   }
1265 ];
1266
1267 exports.getImagePasses = function(width, height) {
1268   var images = [];
1269   var xLeftOver = width % 8;
1270   var yLeftOver = height % 8;
1271   var xRepeats = (width - xLeftOver) / 8;
1272   var yRepeats = (height - yLeftOver) / 8;
1273   for (var i = 0; i < imagePasses.length; i++) {
1274     var pass = imagePasses[i];
1275     var passWidth = xRepeats * pass.x.length;
1276     var passHeight = yRepeats * pass.y.length;
1277     for (var j = 0; j < pass.x.length; j++) {
1278       if (pass.x[j] < xLeftOver) {
1279         passWidth++;
1280       }
1281       else {
1282         break;
1283       }
1284     }
1285     for (j = 0; j < pass.y.length; j++) {
1286       if (pass.y[j] < yLeftOver) {
1287         passHeight++;
1288       }
1289       else {
1290         break;
1291       }
1292     }
1293     if (passWidth > 0 && passHeight > 0) {
1294       images.push({ width: passWidth, height: passHeight, index: i });
1295     }
1296   }
1297   return images;
1298 };
1299
1300 exports.getInterlaceIterator = function(width) {
1301   return function(x, y, pass) {
1302     var outerXLeftOver = x % imagePasses[pass].x.length;
1303     var outerX = (((x - outerXLeftOver) / imagePasses[pass].x.length) * 8) + imagePasses[pass].x[outerXLeftOver];
1304     var outerYLeftOver = y % imagePasses[pass].y.length;
1305     var outerY = (((y - outerYLeftOver) / imagePasses[pass].y.length) * 8) + imagePasses[pass].y[outerYLeftOver];
1306     return (outerX * 4) + (outerY * width * 4);
1307   };
1308 };
1309 },{}],12:[function(require,module,exports){
1310 (function (Buffer){
1311 'use strict';
1312
1313 var util = require('util');
1314 var Stream = require('stream');
1315 var constants = require('./constants');
1316 var Packer = require('./packer');
1317
1318 var PackerAsync = module.exports = function(opt) {
1319   Stream.call(this);
1320
1321   var options = opt || {};
1322
1323   this._packer = new Packer(options);
1324   this._deflate = this._packer.createDeflate();
1325
1326   this.readable = true;
1327 };
1328 util.inherits(PackerAsync, Stream);
1329
1330
1331 PackerAsync.prototype.pack = function(data, width, height, gamma) {
1332   // Signature
1333   this.emit('data', new Buffer(constants.PNG_SIGNATURE));
1334   this.emit('data', this._packer.packIHDR(width, height));
1335
1336   if (gamma) {
1337     this.emit('data', this._packer.packGAMA(gamma));
1338   }
1339
1340   var filteredData = this._packer.filterData(data, width, height);
1341
1342   // compress it
1343   this._deflate.on('error', this.emit.bind(this, 'error'));
1344
1345   this._deflate.on('data', function(compressedData) {
1346     this.emit('data', this._packer.packIDAT(compressedData));
1347   }.bind(this));
1348
1349   this._deflate.on('end', function() {
1350     this.emit('data', this._packer.packIEND());
1351     this.emit('end');
1352   }.bind(this));
1353
1354   this._deflate.end(filteredData);
1355 };
1356
1357 }).call(this,require("buffer").Buffer)
1358 },{"./constants":4,"./packer":14,"buffer":32,"stream":64,"util":69}],13:[function(require,module,exports){
1359 (function (Buffer){
1360 'use strict';
1361
1362 var hasSyncZlib = true;
1363 var zlib = require('zlib');
1364 if (!zlib.deflateSync) {
1365   hasSyncZlib = false;
1366 }
1367 var constants = require('./constants');
1368 var Packer = require('./packer');
1369
1370 module.exports = function(metaData, opt) {
1371
1372   if (!hasSyncZlib) {
1373     throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
1374   }
1375
1376   var options = opt || {};
1377
1378   var packer = new Packer(options);
1379
1380   var chunks = [];
1381
1382   // Signature
1383   chunks.push(new Buffer(constants.PNG_SIGNATURE));
1384
1385   // Header
1386   chunks.push(packer.packIHDR(metaData.width, metaData.height));
1387
1388   if (metaData.gamma) {
1389     chunks.push(packer.packGAMA(metaData.gamma));
1390   }
1391
1392   var filteredData = packer.filterData(metaData.data, metaData.width, metaData.height);
1393
1394   // compress it
1395   var compressedData = zlib.deflateSync(filteredData, packer.getDeflateOptions());
1396   filteredData = null;
1397
1398   if (!compressedData || !compressedData.length) {
1399     throw new Error('bad png - invalid compressed data response');
1400   }
1401   chunks.push(packer.packIDAT(compressedData));
1402
1403   // End
1404   chunks.push(packer.packIEND());
1405
1406   return Buffer.concat(chunks);
1407 };
1408
1409 }).call(this,require("buffer").Buffer)
1410 },{"./constants":4,"./packer":14,"buffer":32,"zlib":30}],14:[function(require,module,exports){
1411 (function (Buffer){
1412 'use strict';
1413
1414 var constants = require('./constants');
1415 var CrcStream = require('./crc');
1416 var bitPacker = require('./bitpacker');
1417 var filter = require('./filter-pack');
1418 var zlib = require('zlib');
1419
1420 var Packer = module.exports = function(options) {
1421   this._options = options;
1422
1423   options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
1424   options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9;
1425   options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3;
1426   options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true;
1427   options.deflateFactory = options.deflateFactory || zlib.createDeflate;
1428   options.bitDepth = options.bitDepth || 8;
1429   // This is outputColorType
1430   options.colorType = (typeof options.colorType === 'number') ? options.colorType : constants.COLORTYPE_COLOR_ALPHA;
1431   options.inputColorType = (typeof options.inputColorType === 'number') ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA;
1432
1433   if ([
1434     constants.COLORTYPE_GRAYSCALE,
1435     constants.COLORTYPE_COLOR,
1436     constants.COLORTYPE_COLOR_ALPHA,
1437     constants.COLORTYPE_ALPHA
1438   ].indexOf(options.colorType) === -1) {
1439     throw new Error('option color type:' + options.colorType + ' is not supported at present');
1440   }
1441   if ([
1442     constants.COLORTYPE_GRAYSCALE,
1443     constants.COLORTYPE_COLOR,
1444     constants.COLORTYPE_COLOR_ALPHA,
1445     constants.COLORTYPE_ALPHA
1446   ].indexOf(options.inputColorType) === -1) {
1447     throw new Error('option input color type:' + options.inputColorType + ' is not supported at present');
1448   }
1449   if (options.bitDepth !== 8 && options.bitDepth !== 16) {
1450     throw new Error('option bit depth:' + options.bitDepth + ' is not supported at present');
1451   }
1452 };
1453
1454 Packer.prototype.getDeflateOptions = function() {
1455   return {
1456     chunkSize: this._options.deflateChunkSize,
1457     level: this._options.deflateLevel,
1458     strategy: this._options.deflateStrategy
1459   };
1460 };
1461
1462 Packer.prototype.createDeflate = function() {
1463   return this._options.deflateFactory(this.getDeflateOptions());
1464 };
1465
1466 Packer.prototype.filterData = function(data, width, height) {
1467   // convert to correct format for filtering (e.g. right bpp and bit depth)
1468   var packedData = bitPacker(data, width, height, this._options);
1469
1470   // filter pixel data
1471   var bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
1472   var filteredData = filter(packedData, width, height, this._options, bpp);
1473   return filteredData;
1474 };
1475
1476 Packer.prototype._packChunk = function(type, data) {
1477
1478   var len = (data ? data.length : 0);
1479   var buf = new Buffer(len + 12);
1480
1481   buf.writeUInt32BE(len, 0);
1482   buf.writeUInt32BE(type, 4);
1483
1484   if (data) {
1485     data.copy(buf, 8);
1486   }
1487
1488   buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4);
1489   return buf;
1490 };
1491
1492 Packer.prototype.packGAMA = function(gamma) {
1493   var buf = new Buffer(4);
1494   buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
1495   return this._packChunk(constants.TYPE_gAMA, buf);
1496 };
1497
1498 Packer.prototype.packIHDR = function(width, height) {
1499
1500   var buf = new Buffer(13);
1501   buf.writeUInt32BE(width, 0);
1502   buf.writeUInt32BE(height, 4);
1503   buf[8] = this._options.bitDepth; // Bit depth
1504   buf[9] = this._options.colorType; // colorType
1505   buf[10] = 0; // compression
1506   buf[11] = 0; // filter
1507   buf[12] = 0; // interlace
1508
1509   return this._packChunk(constants.TYPE_IHDR, buf);
1510 };
1511
1512 Packer.prototype.packIDAT = function(data) {
1513   return this._packChunk(constants.TYPE_IDAT, data);
1514 };
1515
1516 Packer.prototype.packIEND = function() {
1517   return this._packChunk(constants.TYPE_IEND, null);
1518 };
1519
1520 }).call(this,require("buffer").Buffer)
1521 },{"./bitpacker":2,"./constants":4,"./crc":5,"./filter-pack":6,"buffer":32,"zlib":30}],15:[function(require,module,exports){
1522 'use strict';\r
1523 \r
1524 module.exports = function paethPredictor(left, above, upLeft) {\r
1525 \r
1526   var paeth = left + above - upLeft;\r
1527   var pLeft = Math.abs(paeth - left);\r
1528   var pAbove = Math.abs(paeth - above);\r
1529   var pUpLeft = Math.abs(paeth - upLeft);\r
1530 \r
1531   if (pLeft <= pAbove && pLeft <= pUpLeft) {\r
1532     return left;\r
1533   }\r
1534   if (pAbove <= pUpLeft) {\r
1535     return above;\r
1536   }\r
1537   return upLeft;\r
1538 };
1539 },{}],16:[function(require,module,exports){
1540 'use strict';
1541
1542 var util = require('util');
1543 var zlib = require('zlib');
1544 var ChunkStream = require('./chunkstream');
1545 var FilterAsync = require('./filter-parse-async');
1546 var Parser = require('./parser');
1547 var bitmapper = require('./bitmapper');
1548 var formatNormaliser = require('./format-normaliser');
1549
1550 var ParserAsync = module.exports = function(options) {
1551   ChunkStream.call(this);
1552
1553   this._parser = new Parser(options, {
1554     read: this.read.bind(this),
1555     error: this._handleError.bind(this),
1556     metadata: this._handleMetaData.bind(this),
1557     gamma: this.emit.bind(this, 'gamma'),
1558     palette: this._handlePalette.bind(this),
1559     transColor: this._handleTransColor.bind(this),
1560     finished: this._finished.bind(this),
1561     inflateData: this._inflateData.bind(this),
1562     simpleTransparency: this._simpleTransparency.bind(this),
1563     headersFinished: this._headersFinished.bind(this)
1564   });
1565   this._options = options;
1566   this.writable = true;
1567
1568   this._parser.start();
1569 };
1570 util.inherits(ParserAsync, ChunkStream);
1571
1572
1573 ParserAsync.prototype._handleError = function(err) {
1574
1575   this.emit('error', err);
1576
1577   this.writable = false;
1578
1579   this.destroy();
1580
1581   if (this._inflate && this._inflate.destroy) {
1582     this._inflate.destroy();
1583   }
1584
1585   if (this._filter) {
1586     this._filter.destroy();
1587     // For backward compatibility with Node 7 and below.
1588     // Suppress errors due to _inflate calling write() even after
1589     // it's destroy()'ed.
1590     this._filter.on('error', function() {});
1591   }
1592
1593   this.errord = true;
1594 };
1595
1596 ParserAsync.prototype._inflateData = function(data) {
1597   if (!this._inflate) {
1598     if (this._bitmapInfo.interlace) {
1599       this._inflate = zlib.createInflate();
1600
1601       this._inflate.on('error', this.emit.bind(this, 'error'));
1602       this._filter.on('complete', this._complete.bind(this));
1603
1604       this._inflate.pipe(this._filter);
1605     }
1606     else {
1607       var rowSize = ((this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7) >> 3) + 1;
1608       var imageSize = rowSize * this._bitmapInfo.height;
1609       var chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
1610
1611       this._inflate = zlib.createInflate({ chunkSize: chunkSize });
1612       var leftToInflate = imageSize;
1613
1614       var emitError = this.emit.bind(this, 'error');
1615       this._inflate.on('error', function(err) {
1616         if (!leftToInflate) {
1617           return;
1618         }
1619
1620         emitError(err);
1621       });
1622       this._filter.on('complete', this._complete.bind(this));
1623
1624       var filterWrite = this._filter.write.bind(this._filter);
1625       this._inflate.on('data', function(chunk) {
1626         if (!leftToInflate) {
1627           return;
1628         }
1629
1630         if (chunk.length > leftToInflate) {
1631           chunk = chunk.slice(0, leftToInflate);
1632         }
1633
1634         leftToInflate -= chunk.length;
1635
1636         filterWrite(chunk);
1637       });
1638
1639       this._inflate.on('end', this._filter.end.bind(this._filter));
1640     }
1641   }
1642   this._inflate.write(data);
1643 };
1644
1645 ParserAsync.prototype._handleMetaData = function(metaData) {
1646   this._metaData = metaData;
1647   this._bitmapInfo = Object.create(metaData);
1648
1649   this._filter = new FilterAsync(this._bitmapInfo);
1650 };
1651
1652 ParserAsync.prototype._handleTransColor = function(transColor) {
1653   this._bitmapInfo.transColor = transColor;
1654 };
1655
1656 ParserAsync.prototype._handlePalette = function(palette) {
1657   this._bitmapInfo.palette = palette;
1658 };
1659
1660 ParserAsync.prototype._simpleTransparency = function() {
1661   this._metaData.alpha = true;
1662 };
1663
1664 ParserAsync.prototype._headersFinished = function() {
1665   // Up until this point, we don't know if we have a tRNS chunk (alpha)
1666   // so we can't emit metadata any earlier
1667   this.emit('metadata', this._metaData);
1668 };
1669
1670 ParserAsync.prototype._finished = function() {
1671   if (this.errord) {
1672     return;
1673   }
1674
1675   if (!this._inflate) {
1676     this.emit('error', 'No Inflate block');
1677   }
1678   else {
1679     // no more data to inflate
1680     this._inflate.end();
1681   }
1682   this.destroySoon();
1683 };
1684
1685 ParserAsync.prototype._complete = function(filteredData) {
1686
1687   if (this.errord) {
1688     return;
1689   }
1690
1691   try {
1692     var bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
1693
1694     var normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo);
1695     bitmapData = null;
1696   }
1697   catch (ex) {
1698     this._handleError(ex);
1699     return;
1700   }
1701
1702   this.emit('parsed', normalisedBitmapData);
1703 };
1704
1705 },{"./bitmapper":1,"./chunkstream":3,"./filter-parse-async":7,"./format-normaliser":10,"./parser":18,"util":69,"zlib":30}],17:[function(require,module,exports){
1706 (function (Buffer){
1707 'use strict';
1708
1709 var hasSyncZlib = true;
1710 var zlib = require('zlib');
1711 var inflateSync = require('./sync-inflate');
1712 if (!zlib.deflateSync) {
1713   hasSyncZlib = false;
1714 }
1715 var SyncReader = require('./sync-reader');
1716 var FilterSync = require('./filter-parse-sync');
1717 var Parser = require('./parser');
1718 var bitmapper = require('./bitmapper');
1719 var formatNormaliser = require('./format-normaliser');
1720
1721
1722 module.exports = function(buffer, options) {
1723
1724   if (!hasSyncZlib) {
1725     throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
1726   }
1727
1728   var err;
1729   function handleError(_err_) {
1730     err = _err_;
1731   }
1732
1733   var metaData;
1734   function handleMetaData(_metaData_) {
1735     metaData = _metaData_;
1736   }
1737
1738   function handleTransColor(transColor) {
1739     metaData.transColor = transColor;
1740   }
1741
1742   function handlePalette(palette) {
1743     metaData.palette = palette;
1744   }
1745
1746   function handleSimpleTransparency() {
1747     metaData.alpha = true;
1748   }
1749
1750   var gamma;
1751   function handleGamma(_gamma_) {
1752     gamma = _gamma_;
1753   }
1754
1755   var inflateDataList = [];
1756   function handleInflateData(inflatedData) {
1757     inflateDataList.push(inflatedData);
1758   }
1759
1760   var reader = new SyncReader(buffer);
1761
1762   var parser = new Parser(options, {
1763     read: reader.read.bind(reader),
1764     error: handleError,
1765     metadata: handleMetaData,
1766     gamma: handleGamma,
1767     palette: handlePalette,
1768     transColor: handleTransColor,
1769     inflateData: handleInflateData,
1770     simpleTransparency: handleSimpleTransparency
1771   });
1772
1773   parser.start();
1774   reader.process();
1775
1776   if (err) {
1777     throw err;
1778   }
1779
1780   //join together the inflate datas
1781   var inflateData = Buffer.concat(inflateDataList);
1782   inflateDataList.length = 0;
1783
1784   var inflatedData;
1785   if (metaData.interlace) {
1786     inflatedData = zlib.inflateSync(inflateData);
1787   }
1788   else {
1789     var rowSize = ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;
1790     var imageSize = rowSize * metaData.height;
1791     inflatedData = inflateSync(inflateData, { chunkSize: imageSize, maxLength: imageSize });
1792   }
1793   inflateData = null;
1794
1795   if (!inflatedData || !inflatedData.length) {
1796     throw new Error('bad png - invalid inflate data response');
1797   }
1798
1799   var unfilteredData = FilterSync.process(inflatedData, metaData);
1800   inflateData = null;
1801
1802   var bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
1803   unfilteredData = null;
1804
1805   var normalisedBitmapData = formatNormaliser(bitmapData, metaData);
1806
1807   metaData.data = normalisedBitmapData;
1808   metaData.gamma = gamma || 0;
1809
1810   return metaData;
1811 };
1812
1813 }).call(this,require("buffer").Buffer)
1814 },{"./bitmapper":1,"./filter-parse-sync":8,"./format-normaliser":10,"./parser":18,"./sync-inflate":21,"./sync-reader":22,"buffer":32,"zlib":30}],18:[function(require,module,exports){
1815 (function (Buffer){
1816 'use strict';
1817
1818 var constants = require('./constants');
1819 var CrcCalculator = require('./crc');
1820
1821
1822 var Parser = module.exports = function(options, dependencies) {
1823
1824   this._options = options;
1825   options.checkCRC = options.checkCRC !== false;
1826
1827   this._hasIHDR = false;
1828   this._hasIEND = false;
1829   this._emittedHeadersFinished = false;
1830
1831   // input flags/metadata
1832   this._palette = [];
1833   this._colorType = 0;
1834
1835   this._chunks = {};
1836   this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
1837   this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
1838   this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
1839   this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
1840   this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
1841   this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
1842
1843   this.read = dependencies.read;
1844   this.error = dependencies.error;
1845   this.metadata = dependencies.metadata;
1846   this.gamma = dependencies.gamma;
1847   this.transColor = dependencies.transColor;
1848   this.palette = dependencies.palette;
1849   this.parsed = dependencies.parsed;
1850   this.inflateData = dependencies.inflateData;
1851   this.finished = dependencies.finished;
1852   this.simpleTransparency = dependencies.simpleTransparency;
1853   this.headersFinished = dependencies.headersFinished || function() {};
1854 };
1855
1856 Parser.prototype.start = function() {
1857   this.read(constants.PNG_SIGNATURE.length,
1858     this._parseSignature.bind(this)
1859   );
1860 };
1861
1862 Parser.prototype._parseSignature = function(data) {
1863
1864   var signature = constants.PNG_SIGNATURE;
1865
1866   for (var i = 0; i < signature.length; i++) {
1867     if (data[i] !== signature[i]) {
1868       this.error(new Error('Invalid file signature'));
1869       return;
1870     }
1871   }
1872   this.read(8, this._parseChunkBegin.bind(this));
1873 };
1874
1875 Parser.prototype._parseChunkBegin = function(data) {
1876
1877   // chunk content length
1878   var length = data.readUInt32BE(0);
1879
1880   // chunk type
1881   var type = data.readUInt32BE(4);
1882   var name = '';
1883   for (var i = 4; i < 8; i++) {
1884     name += String.fromCharCode(data[i]);
1885   }
1886
1887   //console.log('chunk ', name, length);
1888
1889   // chunk flags
1890   var ancillary = Boolean(data[4] & 0x20); // or critical
1891   //    priv = Boolean(data[5] & 0x20), // or public
1892   //    safeToCopy = Boolean(data[7] & 0x20); // or unsafe
1893
1894   if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
1895     this.error(new Error('Expected IHDR on beggining'));
1896     return;
1897   }
1898
1899   this._crc = new CrcCalculator();
1900   this._crc.write(new Buffer(name));
1901
1902   if (this._chunks[type]) {
1903     return this._chunks[type](length);
1904   }
1905
1906   if (!ancillary) {
1907     this.error(new Error('Unsupported critical chunk type ' + name));
1908     return;
1909   }
1910
1911   this.read(length + 4, this._skipChunk.bind(this));
1912 };
1913
1914 Parser.prototype._skipChunk = function(/*data*/) {
1915   this.read(8, this._parseChunkBegin.bind(this));
1916 };
1917
1918 Parser.prototype._handleChunkEnd = function() {
1919   this.read(4, this._parseChunkEnd.bind(this));
1920 };
1921
1922 Parser.prototype._parseChunkEnd = function(data) {
1923
1924   var fileCrc = data.readInt32BE(0);
1925   var calcCrc = this._crc.crc32();
1926
1927   // check CRC
1928   if (this._options.checkCRC && calcCrc !== fileCrc) {
1929     this.error(new Error('Crc error - ' + fileCrc + ' - ' + calcCrc));
1930     return;
1931   }
1932
1933   if (!this._hasIEND) {
1934     this.read(8, this._parseChunkBegin.bind(this));
1935   }
1936 };
1937
1938 Parser.prototype._handleIHDR = function(length) {
1939   this.read(length, this._parseIHDR.bind(this));
1940 };
1941 Parser.prototype._parseIHDR = function(data) {
1942
1943   this._crc.write(data);
1944
1945   var width = data.readUInt32BE(0);
1946   var height = data.readUInt32BE(4);
1947   var depth = data[8];
1948   var colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha
1949   var compr = data[10];
1950   var filter = data[11];
1951   var interlace = data[12];
1952
1953   // console.log('    width', width, 'height', height,
1954   //     'depth', depth, 'colorType', colorType,
1955   //     'compr', compr, 'filter', filter, 'interlace', interlace
1956   // );
1957
1958   if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
1959     this.error(new Error('Unsupported bit depth ' + depth));
1960     return;
1961   }
1962   if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
1963     this.error(new Error('Unsupported color type'));
1964     return;
1965   }
1966   if (compr !== 0) {
1967     this.error(new Error('Unsupported compression method'));
1968     return;
1969   }
1970   if (filter !== 0) {
1971     this.error(new Error('Unsupported filter method'));
1972     return;
1973   }
1974   if (interlace !== 0 && interlace !== 1) {
1975     this.error(new Error('Unsupported interlace method'));
1976     return;
1977   }
1978
1979   this._colorType = colorType;
1980
1981   var bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
1982
1983   this._hasIHDR = true;
1984
1985   this.metadata({
1986     width: width,
1987     height: height,
1988     depth: depth,
1989     interlace: Boolean(interlace),
1990     palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
1991     color: Boolean(colorType & constants.COLORTYPE_COLOR),
1992     alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
1993     bpp: bpp,
1994     colorType: colorType
1995   });
1996
1997   this._handleChunkEnd();
1998 };
1999
2000
2001 Parser.prototype._handlePLTE = function(length) {
2002   this.read(length, this._parsePLTE.bind(this));
2003 };
2004 Parser.prototype._parsePLTE = function(data) {
2005
2006   this._crc.write(data);
2007
2008   var entries = Math.floor(data.length / 3);
2009   // console.log('Palette:', entries);
2010
2011   for (var i = 0; i < entries; i++) {
2012     this._palette.push([
2013       data[i * 3],
2014       data[i * 3 + 1],
2015       data[i * 3 + 2],
2016       0xff
2017     ]);
2018   }
2019
2020   this.palette(this._palette);
2021
2022   this._handleChunkEnd();
2023 };
2024
2025 Parser.prototype._handleTRNS = function(length) {
2026   this.simpleTransparency();
2027   this.read(length, this._parseTRNS.bind(this));
2028 };
2029 Parser.prototype._parseTRNS = function(data) {
2030
2031   this._crc.write(data);
2032
2033   // palette
2034   if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
2035     if (this._palette.length === 0) {
2036       this.error(new Error('Transparency chunk must be after palette'));
2037       return;
2038     }
2039     if (data.length > this._palette.length) {
2040       this.error(new Error('More transparent colors than palette size'));
2041       return;
2042     }
2043     for (var i = 0; i < data.length; i++) {
2044       this._palette[i][3] = data[i];
2045     }
2046     this.palette(this._palette);
2047   }
2048
2049   // for colorType 0 (grayscale) and 2 (rgb)
2050   // there might be one gray/color defined as transparent
2051   if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
2052     // grey, 2 bytes
2053     this.transColor([data.readUInt16BE(0)]);
2054   }
2055   if (this._colorType === constants.COLORTYPE_COLOR) {
2056     this.transColor([data.readUInt16BE(0), data.readUInt16BE(2), data.readUInt16BE(4)]);
2057   }
2058
2059   this._handleChunkEnd();
2060 };
2061
2062 Parser.prototype._handleGAMA = function(length) {
2063   this.read(length, this._parseGAMA.bind(this));
2064 };
2065 Parser.prototype._parseGAMA = function(data) {
2066
2067   this._crc.write(data);
2068   this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
2069
2070   this._handleChunkEnd();
2071 };
2072
2073 Parser.prototype._handleIDAT = function(length) {
2074   if (!this._emittedHeadersFinished) {
2075     this._emittedHeadersFinished = true;
2076     this.headersFinished();
2077   }
2078   this.read(-length, this._parseIDAT.bind(this, length));
2079 };
2080 Parser.prototype._parseIDAT = function(length, data) {
2081
2082   this._crc.write(data);
2083
2084   if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
2085     throw new Error('Expected palette not found');
2086   }
2087
2088   this.inflateData(data);
2089   var leftOverLength = length - data.length;
2090
2091   if (leftOverLength > 0) {
2092     this._handleIDAT(leftOverLength);
2093   }
2094   else {
2095     this._handleChunkEnd();
2096   }
2097 };
2098
2099 Parser.prototype._handleIEND = function(length) {
2100   this.read(length, this._parseIEND.bind(this));
2101 };
2102 Parser.prototype._parseIEND = function(data) {
2103
2104   this._crc.write(data);
2105
2106   this._hasIEND = true;
2107   this._handleChunkEnd();
2108
2109   if (this.finished) {
2110     this.finished();
2111   }
2112 };
2113
2114 }).call(this,require("buffer").Buffer)
2115 },{"./constants":4,"./crc":5,"buffer":32}],19:[function(require,module,exports){
2116 'use strict';
2117
2118
2119 var parse = require('./parser-sync');
2120 var pack = require('./packer-sync');
2121
2122
2123 exports.read = function(buffer, options) {
2124
2125   return parse(buffer, options || {});
2126 };
2127
2128 exports.write = function(png, options) {
2129
2130   return pack(png, options);
2131 };
2132
2133 },{"./packer-sync":13,"./parser-sync":17}],20:[function(require,module,exports){
2134 (function (process,Buffer){
2135 'use strict';
2136
2137 var util = require('util');
2138 var Stream = require('stream');
2139 var Parser = require('./parser-async');
2140 var Packer = require('./packer-async');
2141 var PNGSync = require('./png-sync');
2142
2143
2144 var PNG = exports.PNG = function(options) {
2145   Stream.call(this);
2146
2147   options = options || {}; // eslint-disable-line no-param-reassign
2148
2149   // coerce pixel dimensions to integers (also coerces undefined -> 0):
2150   this.width = options.width | 0;
2151   this.height = options.height | 0;
2152
2153   this.data = this.width > 0 && this.height > 0 ?
2154     new Buffer(4 * this.width * this.height) : null;
2155
2156   if (options.fill && this.data) {
2157     this.data.fill(0);
2158   }
2159
2160   this.gamma = 0;
2161   this.readable = this.writable = true;
2162
2163   this._parser = new Parser(options);
2164
2165   this._parser.on('error', this.emit.bind(this, 'error'));
2166   this._parser.on('close', this._handleClose.bind(this));
2167   this._parser.on('metadata', this._metadata.bind(this));
2168   this._parser.on('gamma', this._gamma.bind(this));
2169   this._parser.on('parsed', function(data) {
2170     this.data = data;
2171     this.emit('parsed', data);
2172   }.bind(this));
2173
2174   this._packer = new Packer(options);
2175   this._packer.on('data', this.emit.bind(this, 'data'));
2176   this._packer.on('end', this.emit.bind(this, 'end'));
2177   this._parser.on('close', this._handleClose.bind(this));
2178   this._packer.on('error', this.emit.bind(this, 'error'));
2179
2180 };
2181 util.inherits(PNG, Stream);
2182
2183 PNG.sync = PNGSync;
2184
2185 PNG.prototype.pack = function() {
2186
2187   if (!this.data || !this.data.length) {
2188     this.emit('error', 'No data provided');
2189     return this;
2190   }
2191
2192   process.nextTick(function() {
2193     this._packer.pack(this.data, this.width, this.height, this.gamma);
2194   }.bind(this));
2195
2196   return this;
2197 };
2198
2199
2200 PNG.prototype.parse = function(data, callback) {
2201
2202   if (callback) {
2203     var onParsed, onError;
2204
2205     onParsed = function(parsedData) {
2206       this.removeListener('error', onError);
2207
2208       this.data = parsedData;
2209       callback(null, this);
2210     }.bind(this);
2211
2212     onError = function(err) {
2213       this.removeListener('parsed', onParsed);
2214
2215       callback(err, null);
2216     }.bind(this);
2217
2218     this.once('parsed', onParsed);
2219     this.once('error', onError);
2220   }
2221
2222   this.end(data);
2223   return this;
2224 };
2225
2226 PNG.prototype.write = function(data) {
2227   this._parser.write(data);
2228   return true;
2229 };
2230
2231 PNG.prototype.end = function(data) {
2232   this._parser.end(data);
2233 };
2234
2235 PNG.prototype._metadata = function(metadata) {
2236   this.width = metadata.width;
2237   this.height = metadata.height;
2238
2239   this.emit('metadata', metadata);
2240 };
2241
2242 PNG.prototype._gamma = function(gamma) {
2243   this.gamma = gamma;
2244 };
2245
2246 PNG.prototype._handleClose = function() {
2247   if (!this._parser.writable && !this._packer.readable) {
2248     this.emit('close');
2249   }
2250 };
2251
2252
2253 PNG.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
2254   // coerce pixel dimensions to integers (also coerces undefined -> 0):
2255   /* eslint-disable no-param-reassign */
2256   srcX |= 0;
2257   srcY |= 0;
2258   width |= 0;
2259   height |= 0;
2260   deltaX |= 0;
2261   deltaY |= 0;
2262   /* eslint-enable no-param-reassign */
2263
2264   if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
2265     throw new Error('bitblt reading outside image');
2266   }
2267
2268   if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
2269     throw new Error('bitblt writing outside image');
2270   }
2271
2272   for (var y = 0; y < height; y++) {
2273     src.data.copy(dst.data,
2274       ((deltaY + y) * dst.width + deltaX) << 2,
2275       ((srcY + y) * src.width + srcX) << 2,
2276       ((srcY + y) * src.width + srcX + width) << 2
2277     );
2278   }
2279 };
2280
2281
2282 PNG.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
2283
2284   PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
2285   return this;
2286 };
2287
2288 PNG.adjustGamma = function(src) {
2289   if (src.gamma) {
2290     for (var y = 0; y < src.height; y++) {
2291       for (var x = 0; x < src.width; x++) {
2292         var idx = (src.width * y + x) << 2;
2293
2294         for (var i = 0; i < 3; i++) {
2295           var sample = src.data[idx + i] / 255;
2296           sample = Math.pow(sample, 1 / 2.2 / src.gamma);
2297           src.data[idx + i] = Math.round(sample * 255);
2298         }
2299       }
2300     }
2301     src.gamma = 0;
2302   }
2303 };
2304
2305 PNG.prototype.adjustGamma = function() {
2306   PNG.adjustGamma(this);
2307 };
2308
2309 }).call(this,require('_process'),require("buffer").Buffer)
2310 },{"./packer-async":12,"./parser-async":16,"./png-sync":19,"_process":51,"buffer":32,"stream":64,"util":69}],21:[function(require,module,exports){
2311 (function (process,Buffer){
2312 'use strict';
2313
2314 var assert = require('assert').ok;
2315 var zlib = require('zlib');
2316 var util = require('util');
2317
2318 var kMaxLength = require('buffer').kMaxLength;
2319
2320 function Inflate(opts) {
2321   if (!(this instanceof Inflate)) {
2322     return new Inflate(opts);
2323   }
2324
2325   if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
2326     opts.chunkSize = zlib.Z_MIN_CHUNK;
2327   }
2328
2329   zlib.Inflate.call(this, opts);
2330
2331   // Node 8 --> 9 compatibility check
2332   this._offset = this._offset === undefined ? this._outOffset : this._offset;
2333   this._buffer = this._buffer || this._outBuffer;
2334
2335   if (opts && opts.maxLength != null) {
2336     this._maxLength = opts.maxLength;
2337   }
2338 }
2339
2340 function createInflate(opts) {
2341   return new Inflate(opts);
2342 }
2343
2344 function _close(engine, callback) {
2345   if (callback) {
2346     process.nextTick(callback);
2347   }
2348
2349   // Caller may invoke .close after a zlib error (which will null _handle).
2350   if (!engine._handle) {
2351     return;
2352   }
2353
2354   engine._handle.close();
2355   engine._handle = null;
2356 }
2357
2358 Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) {
2359   if (typeof asyncCb === 'function') {
2360     return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
2361   }
2362
2363   var self = this;
2364
2365   var availInBefore = chunk && chunk.length;
2366   var availOutBefore = this._chunkSize - this._offset;
2367   var leftToInflate = this._maxLength;
2368   var inOff = 0;
2369
2370   var buffers = [];
2371   var nread = 0;
2372
2373   var error;
2374   this.on('error', function(err) {
2375     error = err;
2376   });
2377
2378   function handleChunk(availInAfter, availOutAfter) {
2379     if (self._hadError) {
2380       return;
2381     }
2382
2383     var have = availOutBefore - availOutAfter;
2384     assert(have >= 0, 'have should not go down');
2385
2386     if (have > 0) {
2387       var out = self._buffer.slice(self._offset, self._offset + have);
2388       self._offset += have;
2389
2390       if (out.length > leftToInflate) {
2391         out = out.slice(0, leftToInflate);
2392       }
2393
2394       buffers.push(out);
2395       nread += out.length;
2396       leftToInflate -= out.length;
2397
2398       if (leftToInflate === 0) {
2399         return false;
2400       }
2401     }
2402
2403     if (availOutAfter === 0 || self._offset >= self._chunkSize) {
2404       availOutBefore = self._chunkSize;
2405       self._offset = 0;
2406       self._buffer = Buffer.allocUnsafe(self._chunkSize);
2407     }
2408
2409     if (availOutAfter === 0) {
2410       inOff += (availInBefore - availInAfter);
2411       availInBefore = availInAfter;
2412
2413       return true;
2414     }
2415
2416     return false;
2417   }
2418
2419   assert(this._handle, 'zlib binding closed');
2420   do {
2421     var res = this._handle.writeSync(flushFlag,
2422       chunk, // in
2423       inOff, // in_off
2424       availInBefore, // in_len
2425       this._buffer, // out
2426       this._offset, //out_off
2427       availOutBefore); // out_len
2428     // Node 8 --> 9 compatibility check
2429     res = res || this._writeState;
2430   } while (!this._hadError && handleChunk(res[0], res[1]));
2431
2432   if (this._hadError) {
2433     throw error;
2434   }
2435
2436   if (nread >= kMaxLength) {
2437     _close(this);
2438     throw new RangeError('Cannot create final Buffer. It would be larger than 0x' + kMaxLength.toString(16) + ' bytes');
2439   }
2440
2441   var buf = Buffer.concat(buffers, nread);
2442   _close(this);
2443
2444   return buf;
2445 };
2446
2447 util.inherits(Inflate, zlib.Inflate);
2448
2449 function zlibBufferSync(engine, buffer) {
2450   if (typeof buffer === 'string') {
2451     buffer = Buffer.from(buffer);
2452   }
2453   if (!(buffer instanceof Buffer)) {
2454     throw new TypeError('Not a string or buffer');
2455   }
2456
2457   var flushFlag = engine._finishFlushFlag;
2458   if (flushFlag == null) {
2459     flushFlag = zlib.Z_FINISH;
2460   }
2461
2462   return engine._processChunk(buffer, flushFlag);
2463 }
2464
2465 function inflateSync(buffer, opts) {
2466   return zlibBufferSync(new Inflate(opts), buffer);
2467 }
2468
2469 module.exports = exports = inflateSync;
2470 exports.Inflate = Inflate;
2471 exports.createInflate = createInflate;
2472 exports.inflateSync = inflateSync;
2473
2474 }).call(this,require('_process'),require("buffer").Buffer)
2475 },{"_process":51,"assert":23,"buffer":32,"util":69,"zlib":30}],22:[function(require,module,exports){
2476 'use strict';
2477
2478 var SyncReader = module.exports = function(buffer) {
2479
2480   this._buffer = buffer;
2481   this._reads = [];
2482 };
2483
2484 SyncReader.prototype.read = function(length, callback) {
2485
2486   this._reads.push({
2487     length: Math.abs(length), // if length < 0 then at most this length
2488     allowLess: length < 0,
2489     func: callback
2490   });
2491 };
2492
2493 SyncReader.prototype.process = function() {
2494
2495   // as long as there is any data and read requests
2496   while (this._reads.length > 0 && this._buffer.length) {
2497
2498     var read = this._reads[0];
2499
2500     if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
2501
2502       // ok there is any data so that we can satisfy this request
2503       this._reads.shift(); // == read
2504
2505       var buf = this._buffer;
2506
2507       this._buffer = buf.slice(read.length);
2508
2509       read.func.call(this, buf.slice(0, read.length));
2510
2511     }
2512     else {
2513       break;
2514     }
2515
2516   }
2517
2518   if (this._reads.length > 0) {
2519     return new Error('There are some read requests waitng on finished stream');
2520   }
2521
2522   if (this._buffer.length > 0) {
2523     return new Error('unrecognised content at end of stream');
2524   }
2525
2526 };
2527
2528 },{}],23:[function(require,module,exports){
2529 (function (global){
2530 'use strict';
2531
2532 // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
2533 // original notice:
2534
2535 /*!
2536  * The buffer module from node.js, for the browser.
2537  *
2538  * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
2539  * @license  MIT
2540  */
2541 function compare(a, b) {
2542   if (a === b) {
2543     return 0;
2544   }
2545
2546   var x = a.length;
2547   var y = b.length;
2548
2549   for (var i = 0, len = Math.min(x, y); i < len; ++i) {
2550     if (a[i] !== b[i]) {
2551       x = a[i];
2552       y = b[i];
2553       break;
2554     }
2555   }
2556
2557   if (x < y) {
2558     return -1;
2559   }
2560   if (y < x) {
2561     return 1;
2562   }
2563   return 0;
2564 }
2565 function isBuffer(b) {
2566   if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
2567     return global.Buffer.isBuffer(b);
2568   }
2569   return !!(b != null && b._isBuffer);
2570 }
2571
2572 // based on node assert, original notice:
2573
2574 // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
2575 //
2576 // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
2577 //
2578 // Originally from narwhal.js (http://narwhaljs.org)
2579 // Copyright (c) 2009 Thomas Robinson <280north.com>
2580 //
2581 // Permission is hereby granted, free of charge, to any person obtaining a copy
2582 // of this software and associated documentation files (the 'Software'), to
2583 // deal in the Software without restriction, including without limitation the
2584 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
2585 // sell copies of the Software, and to permit persons to whom the Software is
2586 // furnished to do so, subject to the following conditions:
2587 //
2588 // The above copyright notice and this permission notice shall be included in
2589 // all copies or substantial portions of the Software.
2590 //
2591 // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2592 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2593 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2594 // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2595 // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
2596 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2597
2598 var util = require('util/');
2599 var hasOwn = Object.prototype.hasOwnProperty;
2600 var pSlice = Array.prototype.slice;
2601 var functionsHaveNames = (function () {
2602   return function foo() {}.name === 'foo';
2603 }());
2604 function pToString (obj) {
2605   return Object.prototype.toString.call(obj);
2606 }
2607 function isView(arrbuf) {
2608   if (isBuffer(arrbuf)) {
2609     return false;
2610   }
2611   if (typeof global.ArrayBuffer !== 'function') {
2612     return false;
2613   }
2614   if (typeof ArrayBuffer.isView === 'function') {
2615     return ArrayBuffer.isView(arrbuf);
2616   }
2617   if (!arrbuf) {
2618     return false;
2619   }
2620   if (arrbuf instanceof DataView) {
2621     return true;
2622   }
2623   if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
2624     return true;
2625   }
2626   return false;
2627 }
2628 // 1. The assert module provides functions that throw
2629 // AssertionError's when particular conditions are not met. The
2630 // assert module must conform to the following interface.
2631
2632 var assert = module.exports = ok;
2633
2634 // 2. The AssertionError is defined in assert.
2635 // new assert.AssertionError({ message: message,
2636 //                             actual: actual,
2637 //                             expected: expected })
2638
2639 var regex = /\s*function\s+([^\(\s]*)\s*/;
2640 // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
2641 function getName(func) {
2642   if (!util.isFunction(func)) {
2643     return;
2644   }
2645   if (functionsHaveNames) {
2646     return func.name;
2647   }
2648   var str = func.toString();
2649   var match = str.match(regex);
2650   return match && match[1];
2651 }
2652 assert.AssertionError = function AssertionError(options) {
2653   this.name = 'AssertionError';
2654   this.actual = options.actual;
2655   this.expected = options.expected;
2656   this.operator = options.operator;
2657   if (options.message) {
2658     this.message = options.message;
2659     this.generatedMessage = false;
2660   } else {
2661     this.message = getMessage(this);
2662     this.generatedMessage = true;
2663   }
2664   var stackStartFunction = options.stackStartFunction || fail;
2665   if (Error.captureStackTrace) {
2666     Error.captureStackTrace(this, stackStartFunction);
2667   } else {
2668     // non v8 browsers so we can have a stacktrace
2669     var err = new Error();
2670     if (err.stack) {
2671       var out = err.stack;
2672
2673       // try to strip useless frames
2674       var fn_name = getName(stackStartFunction);
2675       var idx = out.indexOf('\n' + fn_name);
2676       if (idx >= 0) {
2677         // once we have located the function frame
2678         // we need to strip out everything before it (and its line)
2679         var next_line = out.indexOf('\n', idx + 1);
2680         out = out.substring(next_line + 1);
2681       }
2682
2683       this.stack = out;
2684     }
2685   }
2686 };
2687
2688 // assert.AssertionError instanceof Error
2689 util.inherits(assert.AssertionError, Error);
2690
2691 function truncate(s, n) {
2692   if (typeof s === 'string') {
2693     return s.length < n ? s : s.slice(0, n);
2694   } else {
2695     return s;
2696   }
2697 }
2698 function inspect(something) {
2699   if (functionsHaveNames || !util.isFunction(something)) {
2700     return util.inspect(something);
2701   }
2702   var rawname = getName(something);
2703   var name = rawname ? ': ' + rawname : '';
2704   return '[Function' +  name + ']';
2705 }
2706 function getMessage(self) {
2707   return truncate(inspect(self.actual), 128) + ' ' +
2708          self.operator + ' ' +
2709          truncate(inspect(self.expected), 128);
2710 }
2711
2712 // At present only the three keys mentioned above are used and
2713 // understood by the spec. Implementations or sub modules can pass
2714 // other keys to the AssertionError's constructor - they will be
2715 // ignored.
2716
2717 // 3. All of the following functions must throw an AssertionError
2718 // when a corresponding condition is not met, with a message that
2719 // may be undefined if not provided.  All assertion methods provide
2720 // both the actual and expected values to the assertion error for
2721 // display purposes.
2722
2723 function fail(actual, expected, message, operator, stackStartFunction) {
2724   throw new assert.AssertionError({
2725     message: message,
2726     actual: actual,
2727     expected: expected,
2728     operator: operator,
2729     stackStartFunction: stackStartFunction
2730   });
2731 }
2732
2733 // EXTENSION! allows for well behaved errors defined elsewhere.
2734 assert.fail = fail;
2735
2736 // 4. Pure assertion tests whether a value is truthy, as determined
2737 // by !!guard.
2738 // assert.ok(guard, message_opt);
2739 // This statement is equivalent to assert.equal(true, !!guard,
2740 // message_opt);. To test strictly for the value true, use
2741 // assert.strictEqual(true, guard, message_opt);.
2742
2743 function ok(value, message) {
2744   if (!value) fail(value, true, message, '==', assert.ok);
2745 }
2746 assert.ok = ok;
2747
2748 // 5. The equality assertion tests shallow, coercive equality with
2749 // ==.
2750 // assert.equal(actual, expected, message_opt);
2751
2752 assert.equal = function equal(actual, expected, message) {
2753   if (actual != expected) fail(actual, expected, message, '==', assert.equal);
2754 };
2755
2756 // 6. The non-equality assertion tests for whether two objects are not equal
2757 // with != assert.notEqual(actual, expected, message_opt);
2758
2759 assert.notEqual = function notEqual(actual, expected, message) {
2760   if (actual == expected) {
2761     fail(actual, expected, message, '!=', assert.notEqual);
2762   }
2763 };
2764
2765 // 7. The equivalence assertion tests a deep equality relation.
2766 // assert.deepEqual(actual, expected, message_opt);
2767
2768 assert.deepEqual = function deepEqual(actual, expected, message) {
2769   if (!_deepEqual(actual, expected, false)) {
2770     fail(actual, expected, message, 'deepEqual', assert.deepEqual);
2771   }
2772 };
2773
2774 assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
2775   if (!_deepEqual(actual, expected, true)) {
2776     fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
2777   }
2778 };
2779
2780 function _deepEqual(actual, expected, strict, memos) {
2781   // 7.1. All identical values are equivalent, as determined by ===.
2782   if (actual === expected) {
2783     return true;
2784   } else if (isBuffer(actual) && isBuffer(expected)) {
2785     return compare(actual, expected) === 0;
2786
2787   // 7.2. If the expected value is a Date object, the actual value is
2788   // equivalent if it is also a Date object that refers to the same time.
2789   } else if (util.isDate(actual) && util.isDate(expected)) {
2790     return actual.getTime() === expected.getTime();
2791
2792   // 7.3 If the expected value is a RegExp object, the actual value is
2793   // equivalent if it is also a RegExp object with the same source and
2794   // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
2795   } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
2796     return actual.source === expected.source &&
2797            actual.global === expected.global &&
2798            actual.multiline === expected.multiline &&
2799            actual.lastIndex === expected.lastIndex &&
2800            actual.ignoreCase === expected.ignoreCase;
2801
2802   // 7.4. Other pairs that do not both pass typeof value == 'object',
2803   // equivalence is determined by ==.
2804   } else if ((actual === null || typeof actual !== 'object') &&
2805              (expected === null || typeof expected !== 'object')) {
2806     return strict ? actual === expected : actual == expected;
2807
2808   // If both values are instances of typed arrays, wrap their underlying
2809   // ArrayBuffers in a Buffer each to increase performance
2810   // This optimization requires the arrays to have the same type as checked by
2811   // Object.prototype.toString (aka pToString). Never perform binary
2812   // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
2813   // bit patterns are not identical.
2814   } else if (isView(actual) && isView(expected) &&
2815              pToString(actual) === pToString(expected) &&
2816              !(actual instanceof Float32Array ||
2817                actual instanceof Float64Array)) {
2818     return compare(new Uint8Array(actual.buffer),
2819                    new Uint8Array(expected.buffer)) === 0;
2820
2821   // 7.5 For all other Object pairs, including Array objects, equivalence is
2822   // determined by having the same number of owned properties (as verified
2823   // with Object.prototype.hasOwnProperty.call), the same set of keys
2824   // (although not necessarily the same order), equivalent values for every
2825   // corresponding key, and an identical 'prototype' property. Note: this
2826   // accounts for both named and indexed properties on Arrays.
2827   } else if (isBuffer(actual) !== isBuffer(expected)) {
2828     return false;
2829   } else {
2830     memos = memos || {actual: [], expected: []};
2831
2832     var actualIndex = memos.actual.indexOf(actual);
2833     if (actualIndex !== -1) {
2834       if (actualIndex === memos.expected.indexOf(expected)) {
2835         return true;
2836       }
2837     }
2838
2839     memos.actual.push(actual);
2840     memos.expected.push(expected);
2841
2842     return objEquiv(actual, expected, strict, memos);
2843   }
2844 }
2845
2846 function isArguments(object) {
2847   return Object.prototype.toString.call(object) == '[object Arguments]';
2848 }
2849
2850 function objEquiv(a, b, strict, actualVisitedObjects) {
2851   if (a === null || a === undefined || b === null || b === undefined)
2852     return false;
2853   // if one is a primitive, the other must be same
2854   if (util.isPrimitive(a) || util.isPrimitive(b))
2855     return a === b;
2856   if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
2857     return false;
2858   var aIsArgs = isArguments(a);
2859   var bIsArgs = isArguments(b);
2860   if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
2861     return false;
2862   if (aIsArgs) {
2863     a = pSlice.call(a);
2864     b = pSlice.call(b);
2865     return _deepEqual(a, b, strict);
2866   }
2867   var ka = objectKeys(a);
2868   var kb = objectKeys(b);
2869   var key, i;
2870   // having the same number of owned properties (keys incorporates
2871   // hasOwnProperty)
2872   if (ka.length !== kb.length)
2873     return false;
2874   //the same set of keys (although not necessarily the same order),
2875   ka.sort();
2876   kb.sort();
2877   //~~~cheap key test
2878   for (i = ka.length - 1; i >= 0; i--) {
2879     if (ka[i] !== kb[i])
2880       return false;
2881   }
2882   //equivalent values for every corresponding key, and
2883   //~~~possibly expensive deep test
2884   for (i = ka.length - 1; i >= 0; i--) {
2885     key = ka[i];
2886     if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
2887       return false;
2888   }
2889   return true;
2890 }
2891
2892 // 8. The non-equivalence assertion tests for any deep inequality.
2893 // assert.notDeepEqual(actual, expected, message_opt);
2894
2895 assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
2896   if (_deepEqual(actual, expected, false)) {
2897     fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
2898   }
2899 };
2900
2901 assert.notDeepStrictEqual = notDeepStrictEqual;
2902 function notDeepStrictEqual(actual, expected, message) {
2903   if (_deepEqual(actual, expected, true)) {
2904     fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
2905   }
2906 }
2907
2908
2909 // 9. The strict equality assertion tests strict equality, as determined by ===.
2910 // assert.strictEqual(actual, expected, message_opt);
2911
2912 assert.strictEqual = function strictEqual(actual, expected, message) {
2913   if (actual !== expected) {
2914     fail(actual, expected, message, '===', assert.strictEqual);
2915   }
2916 };
2917
2918 // 10. The strict non-equality assertion tests for strict inequality, as
2919 // determined by !==.  assert.notStrictEqual(actual, expected, message_opt);
2920
2921 assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
2922   if (actual === expected) {
2923     fail(actual, expected, message, '!==', assert.notStrictEqual);
2924   }
2925 };
2926
2927 function expectedException(actual, expected) {
2928   if (!actual || !expected) {
2929     return false;
2930   }
2931
2932   if (Object.prototype.toString.call(expected) == '[object RegExp]') {
2933     return expected.test(actual);
2934   }
2935
2936   try {
2937     if (actual instanceof expected) {
2938       return true;
2939     }
2940   } catch (e) {
2941     // Ignore.  The instanceof check doesn't work for arrow functions.
2942   }
2943
2944   if (Error.isPrototypeOf(expected)) {
2945     return false;
2946   }
2947
2948   return expected.call({}, actual) === true;
2949 }
2950
2951 function _tryBlock(block) {
2952   var error;
2953   try {
2954     block();
2955   } catch (e) {
2956     error = e;
2957   }
2958   return error;
2959 }
2960
2961 function _throws(shouldThrow, block, expected, message) {
2962   var actual;
2963
2964   if (typeof block !== 'function') {
2965     throw new TypeError('"block" argument must be a function');
2966   }
2967
2968   if (typeof expected === 'string') {
2969     message = expected;
2970     expected = null;
2971   }
2972
2973   actual = _tryBlock(block);
2974
2975   message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
2976             (message ? ' ' + message : '.');
2977
2978   if (shouldThrow && !actual) {
2979     fail(actual, expected, 'Missing expected exception' + message);
2980   }
2981
2982   var userProvidedMessage = typeof message === 'string';
2983   var isUnwantedException = !shouldThrow && util.isError(actual);
2984   var isUnexpectedException = !shouldThrow && actual && !expected;
2985
2986   if ((isUnwantedException &&
2987       userProvidedMessage &&
2988       expectedException(actual, expected)) ||
2989       isUnexpectedException) {
2990     fail(actual, expected, 'Got unwanted exception' + message);
2991   }
2992
2993   if ((shouldThrow && actual && expected &&
2994       !expectedException(actual, expected)) || (!shouldThrow && actual)) {
2995     throw actual;
2996   }
2997 }
2998
2999 // 11. Expected to throw an error:
3000 // assert.throws(block, Error_opt, message_opt);
3001
3002 assert.throws = function(block, /*optional*/error, /*optional*/message) {
3003   _throws(true, block, error, message);
3004 };
3005
3006 // EXTENSION! This is annoying to write outside this module.
3007 assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
3008   _throws(false, block, error, message);
3009 };
3010
3011 assert.ifError = function(err) { if (err) throw err; };
3012
3013 var objectKeys = Object.keys || function (obj) {
3014   var keys = [];
3015   for (var key in obj) {
3016     if (hasOwn.call(obj, key)) keys.push(key);
3017   }
3018   return keys;
3019 };
3020
3021 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3022 },{"util/":26}],24:[function(require,module,exports){
3023 if (typeof Object.create === 'function') {
3024   // implementation from standard node.js 'util' module
3025   module.exports = function inherits(ctor, superCtor) {
3026     ctor.super_ = superCtor
3027     ctor.prototype = Object.create(superCtor.prototype, {
3028       constructor: {
3029         value: ctor,
3030         enumerable: false,
3031         writable: true,
3032         configurable: true
3033       }
3034     });
3035   };
3036 } else {
3037   // old school shim for old browsers
3038   module.exports = function inherits(ctor, superCtor) {
3039     ctor.super_ = superCtor
3040     var TempCtor = function () {}
3041     TempCtor.prototype = superCtor.prototype
3042     ctor.prototype = new TempCtor()
3043     ctor.prototype.constructor = ctor
3044   }
3045 }
3046
3047 },{}],25:[function(require,module,exports){
3048 module.exports = function isBuffer(arg) {
3049   return arg && typeof arg === 'object'
3050     && typeof arg.copy === 'function'
3051     && typeof arg.fill === 'function'
3052     && typeof arg.readUInt8 === 'function';
3053 }
3054 },{}],26:[function(require,module,exports){
3055 (function (process,global){
3056 // Copyright Joyent, Inc. and other Node contributors.
3057 //
3058 // Permission is hereby granted, free of charge, to any person obtaining a
3059 // copy of this software and associated documentation files (the
3060 // "Software"), to deal in the Software without restriction, including
3061 // without limitation the rights to use, copy, modify, merge, publish,
3062 // distribute, sublicense, and/or sell copies of the Software, and to permit
3063 // persons to whom the Software is furnished to do so, subject to the
3064 // following conditions:
3065 //
3066 // The above copyright notice and this permission notice shall be included
3067 // in all copies or substantial portions of the Software.
3068 //
3069 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3070 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3071 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3072 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3073 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3074 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3075 // USE OR OTHER DEALINGS IN THE SOFTWARE.
3076
3077 var formatRegExp = /%[sdj%]/g;
3078 exports.format = function(f) {
3079   if (!isString(f)) {
3080     var objects = [];
3081     for (var i = 0; i < arguments.length; i++) {
3082       objects.push(inspect(arguments[i]));
3083     }
3084     return objects.join(' ');
3085   }
3086
3087   var i = 1;
3088   var args = arguments;
3089   var len = args.length;
3090   var str = String(f).replace(formatRegExp, function(x) {
3091     if (x === '%%') return '%';
3092     if (i >= len) return x;
3093     switch (x) {
3094       case '%s': return String(args[i++]);
3095       case '%d': return Number(args[i++]);
3096       case '%j':
3097         try {
3098           return JSON.stringify(args[i++]);
3099         } catch (_) {
3100           return '[Circular]';
3101         }
3102       default:
3103         return x;
3104     }
3105   });
3106   for (var x = args[i]; i < len; x = args[++i]) {
3107     if (isNull(x) || !isObject(x)) {
3108       str += ' ' + x;
3109     } else {
3110       str += ' ' + inspect(x);
3111     }
3112   }
3113   return str;
3114 };
3115
3116
3117 // Mark that a method should not be used.
3118 // Returns a modified function which warns once by default.
3119 // If --no-deprecation is set, then it is a no-op.
3120 exports.deprecate = function(fn, msg) {
3121   // Allow for deprecating things in the process of starting up.
3122   if (isUndefined(global.process)) {
3123     return function() {
3124       return exports.deprecate(fn, msg).apply(this, arguments);
3125     };
3126   }
3127
3128   if (process.noDeprecation === true) {
3129     return fn;
3130   }
3131
3132   var warned = false;
3133   function deprecated() {
3134     if (!warned) {
3135       if (process.throwDeprecation) {
3136         throw new Error(msg);
3137       } else if (process.traceDeprecation) {
3138         console.trace(msg);
3139       } else {
3140         console.error(msg);
3141       }
3142       warned = true;
3143     }
3144     return fn.apply(this, arguments);
3145   }
3146
3147   return deprecated;
3148 };
3149
3150
3151 var debugs = {};
3152 var debugEnviron;
3153 exports.debuglog = function(set) {
3154   if (isUndefined(debugEnviron))
3155     debugEnviron = process.env.NODE_DEBUG || '';
3156   set = set.toUpperCase();
3157   if (!debugs[set]) {
3158     if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
3159       var pid = process.pid;
3160       debugs[set] = function() {
3161         var msg = exports.format.apply(exports, arguments);
3162         console.error('%s %d: %s', set, pid, msg);
3163       };
3164     } else {
3165       debugs[set] = function() {};
3166     }
3167   }
3168   return debugs[set];
3169 };
3170
3171
3172 /**
3173  * Echos the value of a value. Trys to print the value out
3174  * in the best way possible given the different types.
3175  *
3176  * @param {Object} obj The object to print out.
3177  * @param {Object} opts Optional options object that alters the output.
3178  */
3179 /* legacy: obj, showHidden, depth, colors*/
3180 function inspect(obj, opts) {
3181   // default options
3182   var ctx = {
3183     seen: [],
3184     stylize: stylizeNoColor
3185   };
3186   // legacy...
3187   if (arguments.length >= 3) ctx.depth = arguments[2];
3188   if (arguments.length >= 4) ctx.colors = arguments[3];
3189   if (isBoolean(opts)) {
3190     // legacy...
3191     ctx.showHidden = opts;
3192   } else if (opts) {
3193     // got an "options" object
3194     exports._extend(ctx, opts);
3195   }
3196   // set default options
3197   if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
3198   if (isUndefined(ctx.depth)) ctx.depth = 2;
3199   if (isUndefined(ctx.colors)) ctx.colors = false;
3200   if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
3201   if (ctx.colors) ctx.stylize = stylizeWithColor;
3202   return formatValue(ctx, obj, ctx.depth);
3203 }
3204 exports.inspect = inspect;
3205
3206
3207 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
3208 inspect.colors = {
3209   'bold' : [1, 22],
3210   'italic' : [3, 23],
3211   'underline' : [4, 24],
3212   'inverse' : [7, 27],
3213   'white' : [37, 39],
3214   'grey' : [90, 39],
3215   'black' : [30, 39],
3216   'blue' : [34, 39],
3217   'cyan' : [36, 39],
3218   'green' : [32, 39],
3219   'magenta' : [35, 39],
3220   'red' : [31, 39],
3221   'yellow' : [33, 39]
3222 };
3223
3224 // Don't use 'blue' not visible on cmd.exe
3225 inspect.styles = {
3226   'special': 'cyan',
3227   'number': 'yellow',
3228   'boolean': 'yellow',
3229   'undefined': 'grey',
3230   'null': 'bold',
3231   'string': 'green',
3232   'date': 'magenta',
3233   // "name": intentionally not styling
3234   'regexp': 'red'
3235 };
3236
3237
3238 function stylizeWithColor(str, styleType) {
3239   var style = inspect.styles[styleType];
3240
3241   if (style) {
3242     return '\u001b[' + inspect.colors[style][0] + 'm' + str +
3243            '\u001b[' + inspect.colors[style][1] + 'm';
3244   } else {
3245     return str;
3246   }
3247 }
3248
3249
3250 function stylizeNoColor(str, styleType) {
3251   return str;
3252 }
3253
3254
3255 function arrayToHash(array) {
3256   var hash = {};
3257
3258   array.forEach(function(val, idx) {
3259     hash[val] = true;
3260   });
3261
3262   return hash;
3263 }
3264
3265
3266 function formatValue(ctx, value, recurseTimes) {
3267   // Provide a hook for user-specified inspect functions.
3268   // Check that value is an object with an inspect function on it
3269   if (ctx.customInspect &&
3270       value &&
3271       isFunction(value.inspect) &&
3272       // Filter out the util module, it's inspect function is special
3273       value.inspect !== exports.inspect &&
3274       // Also filter out any prototype objects using the circular check.
3275       !(value.constructor && value.constructor.prototype === value)) {
3276     var ret = value.inspect(recurseTimes, ctx);
3277     if (!isString(ret)) {
3278       ret = formatValue(ctx, ret, recurseTimes);
3279     }
3280     return ret;
3281   }
3282
3283   // Primitive types cannot have properties
3284   var primitive = formatPrimitive(ctx, value);
3285   if (primitive) {
3286     return primitive;
3287   }
3288
3289   // Look up the keys of the object.
3290   var keys = Object.keys(value);
3291   var visibleKeys = arrayToHash(keys);
3292
3293   if (ctx.showHidden) {
3294     keys = Object.getOwnPropertyNames(value);
3295   }
3296
3297   // IE doesn't make error fields non-enumerable
3298   // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
3299   if (isError(value)
3300       && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
3301     return formatError(value);
3302   }
3303
3304   // Some type of object without properties can be shortcutted.
3305   if (keys.length === 0) {
3306     if (isFunction(value)) {
3307       var name = value.name ? ': ' + value.name : '';
3308       return ctx.stylize('[Function' + name + ']', 'special');
3309     }
3310     if (isRegExp(value)) {
3311       return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
3312     }
3313     if (isDate(value)) {
3314       return ctx.stylize(Date.prototype.toString.call(value), 'date');
3315     }
3316     if (isError(value)) {
3317       return formatError(value);
3318     }
3319   }
3320
3321   var base = '', array = false, braces = ['{', '}'];
3322
3323   // Make Array say that they are Array
3324   if (isArray(value)) {
3325     array = true;
3326     braces = ['[', ']'];
3327   }
3328
3329   // Make functions say that they are functions
3330   if (isFunction(value)) {
3331     var n = value.name ? ': ' + value.name : '';
3332     base = ' [Function' + n + ']';
3333   }
3334
3335   // Make RegExps say that they are RegExps
3336   if (isRegExp(value)) {
3337     base = ' ' + RegExp.prototype.toString.call(value);
3338   }
3339
3340   // Make dates with properties first say the date
3341   if (isDate(value)) {
3342     base = ' ' + Date.prototype.toUTCString.call(value);
3343   }
3344
3345   // Make error with message first say the error
3346   if (isError(value)) {
3347     base = ' ' + formatError(value);
3348   }
3349
3350   if (keys.length === 0 && (!array || value.length == 0)) {
3351     return braces[0] + base + braces[1];
3352   }
3353
3354   if (recurseTimes < 0) {
3355     if (isRegExp(value)) {
3356       return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
3357     } else {
3358       return ctx.stylize('[Object]', 'special');
3359     }
3360   }
3361
3362   ctx.seen.push(value);
3363
3364   var output;
3365   if (array) {
3366     output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
3367   } else {
3368     output = keys.map(function(key) {
3369       return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
3370     });
3371   }
3372
3373   ctx.seen.pop();
3374
3375   return reduceToSingleString(output, base, braces);
3376 }
3377
3378
3379 function formatPrimitive(ctx, value) {
3380   if (isUndefined(value))
3381     return ctx.stylize('undefined', 'undefined');
3382   if (isString(value)) {
3383     var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
3384                                              .replace(/'/g, "\\'")
3385                                              .replace(/\\"/g, '"') + '\'';
3386     return ctx.stylize(simple, 'string');
3387   }
3388   if (isNumber(value))
3389     return ctx.stylize('' + value, 'number');
3390   if (isBoolean(value))
3391     return ctx.stylize('' + value, 'boolean');
3392   // For some reason typeof null is "object", so special case here.
3393   if (isNull(value))
3394     return ctx.stylize('null', 'null');
3395 }
3396
3397
3398 function formatError(value) {
3399   return '[' + Error.prototype.toString.call(value) + ']';
3400 }
3401
3402
3403 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
3404   var output = [];
3405   for (var i = 0, l = value.length; i < l; ++i) {
3406     if (hasOwnProperty(value, String(i))) {
3407       output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
3408           String(i), true));
3409     } else {
3410       output.push('');
3411     }
3412   }
3413   keys.forEach(function(key) {
3414     if (!key.match(/^\d+$/)) {
3415       output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
3416           key, true));
3417     }
3418   });
3419   return output;
3420 }
3421
3422
3423 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
3424   var name, str, desc;
3425   desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
3426   if (desc.get) {
3427     if (desc.set) {
3428       str = ctx.stylize('[Getter/Setter]', 'special');
3429     } else {
3430       str = ctx.stylize('[Getter]', 'special');
3431     }
3432   } else {
3433     if (desc.set) {
3434       str = ctx.stylize('[Setter]', 'special');
3435     }
3436   }
3437   if (!hasOwnProperty(visibleKeys, key)) {
3438     name = '[' + key + ']';
3439   }
3440   if (!str) {
3441     if (ctx.seen.indexOf(desc.value) < 0) {
3442       if (isNull(recurseTimes)) {
3443         str = formatValue(ctx, desc.value, null);
3444       } else {
3445         str = formatValue(ctx, desc.value, recurseTimes - 1);
3446       }
3447       if (str.indexOf('\n') > -1) {
3448         if (array) {
3449           str = str.split('\n').map(function(line) {
3450             return '  ' + line;
3451           }).join('\n').substr(2);
3452         } else {
3453           str = '\n' + str.split('\n').map(function(line) {
3454             return '   ' + line;
3455           }).join('\n');
3456         }
3457       }
3458     } else {
3459       str = ctx.stylize('[Circular]', 'special');
3460     }
3461   }
3462   if (isUndefined(name)) {
3463     if (array && key.match(/^\d+$/)) {
3464       return str;
3465     }
3466     name = JSON.stringify('' + key);
3467     if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
3468       name = name.substr(1, name.length - 2);
3469       name = ctx.stylize(name, 'name');
3470     } else {
3471       name = name.replace(/'/g, "\\'")
3472                  .replace(/\\"/g, '"')
3473                  .replace(/(^"|"$)/g, "'");
3474       name = ctx.stylize(name, 'string');
3475     }
3476   }
3477
3478   return name + ': ' + str;
3479 }
3480
3481
3482 function reduceToSingleString(output, base, braces) {
3483   var numLinesEst = 0;
3484   var length = output.reduce(function(prev, cur) {
3485     numLinesEst++;
3486     if (cur.indexOf('\n') >= 0) numLinesEst++;
3487     return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
3488   }, 0);
3489
3490   if (length > 60) {
3491     return braces[0] +
3492            (base === '' ? '' : base + '\n ') +
3493            ' ' +
3494            output.join(',\n  ') +
3495            ' ' +
3496            braces[1];
3497   }
3498
3499   return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
3500 }
3501
3502
3503 // NOTE: These type checking functions intentionally don't use `instanceof`
3504 // because it is fragile and can be easily faked with `Object.create()`.
3505 function isArray(ar) {
3506   return Array.isArray(ar);
3507 }
3508 exports.isArray = isArray;
3509
3510 function isBoolean(arg) {
3511   return typeof arg === 'boolean';
3512 }
3513 exports.isBoolean = isBoolean;
3514
3515 function isNull(arg) {
3516   return arg === null;
3517 }
3518 exports.isNull = isNull;
3519
3520 function isNullOrUndefined(arg) {
3521   return arg == null;
3522 }
3523 exports.isNullOrUndefined = isNullOrUndefined;
3524
3525 function isNumber(arg) {
3526   return typeof arg === 'number';
3527 }
3528 exports.isNumber = isNumber;
3529
3530 function isString(arg) {
3531   return typeof arg === 'string';
3532 }
3533 exports.isString = isString;
3534
3535 function isSymbol(arg) {
3536   return typeof arg === 'symbol';
3537 }
3538 exports.isSymbol = isSymbol;
3539
3540 function isUndefined(arg) {
3541   return arg === void 0;
3542 }
3543 exports.isUndefined = isUndefined;
3544
3545 function isRegExp(re) {
3546   return isObject(re) && objectToString(re) === '[object RegExp]';
3547 }
3548 exports.isRegExp = isRegExp;
3549
3550 function isObject(arg) {
3551   return typeof arg === 'object' && arg !== null;
3552 }
3553 exports.isObject = isObject;
3554
3555 function isDate(d) {
3556   return isObject(d) && objectToString(d) === '[object Date]';
3557 }
3558 exports.isDate = isDate;
3559
3560 function isError(e) {
3561   return isObject(e) &&
3562       (objectToString(e) === '[object Error]' || e instanceof Error);
3563 }
3564 exports.isError = isError;
3565
3566 function isFunction(arg) {
3567   return typeof arg === 'function';
3568 }
3569 exports.isFunction = isFunction;
3570
3571 function isPrimitive(arg) {
3572   return arg === null ||
3573          typeof arg === 'boolean' ||
3574          typeof arg === 'number' ||
3575          typeof arg === 'string' ||
3576          typeof arg === 'symbol' ||  // ES6 symbol
3577          typeof arg === 'undefined';
3578 }
3579 exports.isPrimitive = isPrimitive;
3580
3581 exports.isBuffer = require('./support/isBuffer');
3582
3583 function objectToString(o) {
3584   return Object.prototype.toString.call(o);
3585 }
3586
3587
3588 function pad(n) {
3589   return n < 10 ? '0' + n.toString(10) : n.toString(10);
3590 }
3591
3592
3593 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
3594               'Oct', 'Nov', 'Dec'];
3595
3596 // 26 Feb 16:19:34
3597 function timestamp() {
3598   var d = new Date();
3599   var time = [pad(d.getHours()),
3600               pad(d.getMinutes()),
3601               pad(d.getSeconds())].join(':');
3602   return [d.getDate(), months[d.getMonth()], time].join(' ');
3603 }
3604
3605
3606 // log is just a thin wrapper to console.log that prepends a timestamp
3607 exports.log = function() {
3608   console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
3609 };
3610
3611
3612 /**
3613  * Inherit the prototype methods from one constructor into another.
3614  *
3615  * The Function.prototype.inherits from lang.js rewritten as a standalone
3616  * function (not on Function.prototype). NOTE: If this file is to be loaded
3617  * during bootstrapping this function needs to be rewritten using some native
3618  * functions as prototype setup using normal JavaScript does not work as
3619  * expected during bootstrapping (see mirror.js in r114903).
3620  *
3621  * @param {function} ctor Constructor function which needs to inherit the
3622  *     prototype.
3623  * @param {function} superCtor Constructor function to inherit prototype from.
3624  */
3625 exports.inherits = require('inherits');
3626
3627 exports._extend = function(origin, add) {
3628   // Don't do anything if add isn't an object
3629   if (!add || !isObject(add)) return origin;
3630
3631   var keys = Object.keys(add);
3632   var i = keys.length;
3633   while (i--) {
3634     origin[keys[i]] = add[keys[i]];
3635   }
3636   return origin;
3637 };
3638
3639 function hasOwnProperty(obj, prop) {
3640   return Object.prototype.hasOwnProperty.call(obj, prop);
3641 }
3642
3643 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3644 },{"./support/isBuffer":25,"_process":51,"inherits":24}],27:[function(require,module,exports){
3645 'use strict'
3646
3647 exports.byteLength = byteLength
3648 exports.toByteArray = toByteArray
3649 exports.fromByteArray = fromByteArray
3650
3651 var lookup = []
3652 var revLookup = []
3653 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
3654
3655 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
3656 for (var i = 0, len = code.length; i < len; ++i) {
3657   lookup[i] = code[i]
3658   revLookup[code.charCodeAt(i)] = i
3659 }
3660
3661 // Support decoding URL-safe base64 strings, as Node.js does.
3662 // See: https://en.wikipedia.org/wiki/Base64#URL_applications
3663 revLookup['-'.charCodeAt(0)] = 62
3664 revLookup['_'.charCodeAt(0)] = 63
3665
3666 function getLens (b64) {
3667   var len = b64.length
3668
3669   if (len % 4 > 0) {
3670     throw new Error('Invalid string. Length must be a multiple of 4')
3671   }
3672
3673   // Trim off extra bytes after placeholder bytes are found
3674   // See: https://github.com/beatgammit/base64-js/issues/42
3675   var validLen = b64.indexOf('=')
3676   if (validLen === -1) validLen = len
3677
3678   var placeHoldersLen = validLen === len
3679     ? 0
3680     : 4 - (validLen % 4)
3681
3682   return [validLen, placeHoldersLen]
3683 }
3684
3685 // base64 is 4/3 + up to two characters of the original data
3686 function byteLength (b64) {
3687   var lens = getLens(b64)
3688   var validLen = lens[0]
3689   var placeHoldersLen = lens[1]
3690   return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
3691 }
3692
3693 function _byteLength (b64, validLen, placeHoldersLen) {
3694   return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
3695 }
3696
3697 function toByteArray (b64) {
3698   var tmp
3699   var lens = getLens(b64)
3700   var validLen = lens[0]
3701   var placeHoldersLen = lens[1]
3702
3703   var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
3704
3705   var curByte = 0
3706
3707   // if there are placeholders, only get up to the last complete 4 chars
3708   var len = placeHoldersLen > 0
3709     ? validLen - 4
3710     : validLen
3711
3712   for (var i = 0; i < len; i += 4) {
3713     tmp =
3714       (revLookup[b64.charCodeAt(i)] << 18) |
3715       (revLookup[b64.charCodeAt(i + 1)] << 12) |
3716       (revLookup[b64.charCodeAt(i + 2)] << 6) |
3717       revLookup[b64.charCodeAt(i + 3)]
3718     arr[curByte++] = (tmp >> 16) & 0xFF
3719     arr[curByte++] = (tmp >> 8) & 0xFF
3720     arr[curByte++] = tmp & 0xFF
3721   }
3722
3723   if (placeHoldersLen === 2) {
3724     tmp =
3725       (revLookup[b64.charCodeAt(i)] << 2) |
3726       (revLookup[b64.charCodeAt(i + 1)] >> 4)
3727     arr[curByte++] = tmp & 0xFF
3728   }
3729
3730   if (placeHoldersLen === 1) {
3731     tmp =
3732       (revLookup[b64.charCodeAt(i)] << 10) |
3733       (revLookup[b64.charCodeAt(i + 1)] << 4) |
3734       (revLookup[b64.charCodeAt(i + 2)] >> 2)
3735     arr[curByte++] = (tmp >> 8) & 0xFF
3736     arr[curByte++] = tmp & 0xFF
3737   }
3738
3739   return arr
3740 }
3741
3742 function tripletToBase64 (num) {
3743   return lookup[num >> 18 & 0x3F] +
3744     lookup[num >> 12 & 0x3F] +
3745     lookup[num >> 6 & 0x3F] +
3746     lookup[num & 0x3F]
3747 }
3748
3749 function encodeChunk (uint8, start, end) {
3750   var tmp
3751   var output = []
3752   for (var i = start; i < end; i += 3) {
3753     tmp =
3754       ((uint8[i] << 16) & 0xFF0000) +
3755       ((uint8[i + 1] << 8) & 0xFF00) +
3756       (uint8[i + 2] & 0xFF)
3757     output.push(tripletToBase64(tmp))
3758   }
3759   return output.join('')
3760 }
3761
3762 function fromByteArray (uint8) {
3763   var tmp
3764   var len = uint8.length
3765   var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
3766   var parts = []
3767   var maxChunkLength = 16383 // must be multiple of 3
3768
3769   // go through the array every three bytes, we'll deal with trailing stuff later
3770   for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
3771     parts.push(encodeChunk(
3772       uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
3773     ))
3774   }
3775
3776   // pad the end with zeros, but make sure to not forget the extra bytes
3777   if (extraBytes === 1) {
3778     tmp = uint8[len - 1]
3779     parts.push(
3780       lookup[tmp >> 2] +
3781       lookup[(tmp << 4) & 0x3F] +
3782       '=='
3783     )
3784   } else if (extraBytes === 2) {
3785     tmp = (uint8[len - 2] << 8) + uint8[len - 1]
3786     parts.push(
3787       lookup[tmp >> 10] +
3788       lookup[(tmp >> 4) & 0x3F] +
3789       lookup[(tmp << 2) & 0x3F] +
3790       '='
3791     )
3792   }
3793
3794   return parts.join('')
3795 }
3796
3797 },{}],28:[function(require,module,exports){
3798
3799 },{}],29:[function(require,module,exports){
3800 (function (process,Buffer){
3801 'use strict';
3802 /* eslint camelcase: "off" */
3803
3804 var assert = require('assert');
3805
3806 var Zstream = require('pako/lib/zlib/zstream');
3807 var zlib_deflate = require('pako/lib/zlib/deflate.js');
3808 var zlib_inflate = require('pako/lib/zlib/inflate.js');
3809 var constants = require('pako/lib/zlib/constants');
3810
3811 for (var key in constants) {
3812   exports[key] = constants[key];
3813 }
3814
3815 // zlib modes
3816 exports.NONE = 0;
3817 exports.DEFLATE = 1;
3818 exports.INFLATE = 2;
3819 exports.GZIP = 3;
3820 exports.GUNZIP = 4;
3821 exports.DEFLATERAW = 5;
3822 exports.INFLATERAW = 6;
3823 exports.UNZIP = 7;
3824
3825 var GZIP_HEADER_ID1 = 0x1f;
3826 var GZIP_HEADER_ID2 = 0x8b;
3827
3828 /**
3829  * Emulate Node's zlib C++ layer for use by the JS layer in index.js
3830  */
3831 function Zlib(mode) {
3832   if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
3833     throw new TypeError('Bad argument');
3834   }
3835
3836   this.dictionary = null;
3837   this.err = 0;
3838   this.flush = 0;
3839   this.init_done = false;
3840   this.level = 0;
3841   this.memLevel = 0;
3842   this.mode = mode;
3843   this.strategy = 0;
3844   this.windowBits = 0;
3845   this.write_in_progress = false;
3846   this.pending_close = false;
3847   this.gzip_id_bytes_read = 0;
3848 }
3849
3850 Zlib.prototype.close = function () {
3851   if (this.write_in_progress) {
3852     this.pending_close = true;
3853     return;
3854   }
3855
3856   this.pending_close = false;
3857
3858   assert(this.init_done, 'close before init');
3859   assert(this.mode <= exports.UNZIP);
3860
3861   if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
3862     zlib_deflate.deflateEnd(this.strm);
3863   } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
3864     zlib_inflate.inflateEnd(this.strm);
3865   }
3866
3867   this.mode = exports.NONE;
3868
3869   this.dictionary = null;
3870 };
3871
3872 Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
3873   return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
3874 };
3875
3876 Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
3877   return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
3878 };
3879
3880 Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
3881   assert.equal(arguments.length, 8);
3882
3883   assert(this.init_done, 'write before init');
3884   assert(this.mode !== exports.NONE, 'already finalized');
3885   assert.equal(false, this.write_in_progress, 'write already in progress');
3886   assert.equal(false, this.pending_close, 'close is pending');
3887
3888   this.write_in_progress = true;
3889
3890   assert.equal(false, flush === undefined, 'must provide flush value');
3891
3892   this.write_in_progress = true;
3893
3894   if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) {
3895     throw new Error('Invalid flush value');
3896   }
3897
3898   if (input == null) {
3899     input = Buffer.alloc(0);
3900     in_len = 0;
3901     in_off = 0;
3902   }
3903
3904   this.strm.avail_in = in_len;
3905   this.strm.input = input;
3906   this.strm.next_in = in_off;
3907   this.strm.avail_out = out_len;
3908   this.strm.output = out;
3909   this.strm.next_out = out_off;
3910   this.flush = flush;
3911
3912   if (!async) {
3913     // sync version
3914     this._process();
3915
3916     if (this._checkError()) {
3917       return this._afterSync();
3918     }
3919     return;
3920   }
3921
3922   // async version
3923   var self = this;
3924   process.nextTick(function () {
3925     self._process();
3926     self._after();
3927   });
3928
3929   return this;
3930 };
3931
3932 Zlib.prototype._afterSync = function () {
3933   var avail_out = this.strm.avail_out;
3934   var avail_in = this.strm.avail_in;
3935
3936   this.write_in_progress = false;
3937
3938   return [avail_in, avail_out];
3939 };
3940
3941 Zlib.prototype._process = function () {
3942   var next_expected_header_byte = null;
3943
3944   // If the avail_out is left at 0, then it means that it ran out
3945   // of room.  If there was avail_out left over, then it means
3946   // that all of the input was consumed.
3947   switch (this.mode) {
3948     case exports.DEFLATE:
3949     case exports.GZIP:
3950     case exports.DEFLATERAW:
3951       this.err = zlib_deflate.deflate(this.strm, this.flush);
3952       break;
3953     case exports.UNZIP:
3954       if (this.strm.avail_in > 0) {
3955         next_expected_header_byte = this.strm.next_in;
3956       }
3957
3958       switch (this.gzip_id_bytes_read) {
3959         case 0:
3960           if (next_expected_header_byte === null) {
3961             break;
3962           }
3963
3964           if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
3965             this.gzip_id_bytes_read = 1;
3966             next_expected_header_byte++;
3967
3968             if (this.strm.avail_in === 1) {
3969               // The only available byte was already read.
3970               break;
3971             }
3972           } else {
3973             this.mode = exports.INFLATE;
3974             break;
3975           }
3976
3977         // fallthrough
3978         case 1:
3979           if (next_expected_header_byte === null) {
3980             break;
3981           }
3982
3983           if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
3984             this.gzip_id_bytes_read = 2;
3985             this.mode = exports.GUNZIP;
3986           } else {
3987             // There is no actual difference between INFLATE and INFLATERAW
3988             // (after initialization).
3989             this.mode = exports.INFLATE;
3990           }
3991
3992           break;
3993         default:
3994           throw new Error('invalid number of gzip magic number bytes read');
3995       }
3996
3997     // fallthrough
3998     case exports.INFLATE:
3999     case exports.GUNZIP:
4000     case exports.INFLATERAW:
4001       this.err = zlib_inflate.inflate(this.strm, this.flush
4002
4003       // If data was encoded with dictionary
4004       );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
4005         // Load it
4006         this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
4007         if (this.err === exports.Z_OK) {
4008           // And try to decode again
4009           this.err = zlib_inflate.inflate(this.strm, this.flush);
4010         } else if (this.err === exports.Z_DATA_ERROR) {
4011           // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
4012           // Make it possible for After() to tell a bad dictionary from bad
4013           // input.
4014           this.err = exports.Z_NEED_DICT;
4015         }
4016       }
4017       while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
4018         // Bytes remain in input buffer. Perhaps this is another compressed
4019         // member in the same archive, or just trailing garbage.
4020         // Trailing zero bytes are okay, though, since they are frequently
4021         // used for padding.
4022
4023         this.reset();
4024         this.err = zlib_inflate.inflate(this.strm, this.flush);
4025       }
4026       break;
4027     default:
4028       throw new Error('Unknown mode ' + this.mode);
4029   }
4030 };
4031
4032 Zlib.prototype._checkError = function () {
4033   // Acceptable error states depend on the type of zlib stream.
4034   switch (this.err) {
4035     case exports.Z_OK:
4036     case exports.Z_BUF_ERROR:
4037       if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
4038         this._error('unexpected end of file');
4039         return false;
4040       }
4041       break;
4042     case exports.Z_STREAM_END:
4043       // normal statuses, not fatal
4044       break;
4045     case exports.Z_NEED_DICT:
4046       if (this.dictionary == null) {
4047         this._error('Missing dictionary');
4048       } else {
4049         this._error('Bad dictionary');
4050       }
4051       return false;
4052     default:
4053       // something else.
4054       this._error('Zlib error');
4055       return false;
4056   }
4057
4058   return true;
4059 };
4060
4061 Zlib.prototype._after = function () {
4062   if (!this._checkError()) {
4063     return;
4064   }
4065
4066   var avail_out = this.strm.avail_out;
4067   var avail_in = this.strm.avail_in;
4068
4069   this.write_in_progress = false;
4070
4071   // call the write() cb
4072   this.callback(avail_in, avail_out);
4073
4074   if (this.pending_close) {
4075     this.close();
4076   }
4077 };
4078
4079 Zlib.prototype._error = function (message) {
4080   if (this.strm.msg) {
4081     message = this.strm.msg;
4082   }
4083   this.onerror(message, this.err
4084
4085   // no hope of rescue.
4086   );this.write_in_progress = false;
4087   if (this.pending_close) {
4088     this.close();
4089   }
4090 };
4091
4092 Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
4093   assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
4094
4095   assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
4096   assert(level >= -1 && level <= 9, 'invalid compression level');
4097
4098   assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
4099
4100   assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy');
4101
4102   this._init(level, windowBits, memLevel, strategy, dictionary);
4103   this._setDictionary();
4104 };
4105
4106 Zlib.prototype.params = function () {
4107   throw new Error('deflateParams Not supported');
4108 };
4109
4110 Zlib.prototype.reset = function () {
4111   this._reset();
4112   this._setDictionary();
4113 };
4114
4115 Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
4116   this.level = level;
4117   this.windowBits = windowBits;
4118   this.memLevel = memLevel;
4119   this.strategy = strategy;
4120
4121   this.flush = exports.Z_NO_FLUSH;
4122
4123   this.err = exports.Z_OK;
4124
4125   if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
4126     this.windowBits += 16;
4127   }
4128
4129   if (this.mode === exports.UNZIP) {
4130     this.windowBits += 32;
4131   }
4132
4133   if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
4134     this.windowBits = -1 * this.windowBits;
4135   }
4136
4137   this.strm = new Zstream();
4138
4139   switch (this.mode) {
4140     case exports.DEFLATE:
4141     case exports.GZIP:
4142     case exports.DEFLATERAW:
4143       this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
4144       break;
4145     case exports.INFLATE:
4146     case exports.GUNZIP:
4147     case exports.INFLATERAW:
4148     case exports.UNZIP:
4149       this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
4150       break;
4151     default:
4152       throw new Error('Unknown mode ' + this.mode);
4153   }
4154
4155   if (this.err !== exports.Z_OK) {
4156     this._error('Init error');
4157   }
4158
4159   this.dictionary = dictionary;
4160
4161   this.write_in_progress = false;
4162   this.init_done = true;
4163 };
4164
4165 Zlib.prototype._setDictionary = function () {
4166   if (this.dictionary == null) {
4167     return;
4168   }
4169
4170   this.err = exports.Z_OK;
4171
4172   switch (this.mode) {
4173     case exports.DEFLATE:
4174     case exports.DEFLATERAW:
4175       this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
4176       break;
4177     default:
4178       break;
4179   }
4180
4181   if (this.err !== exports.Z_OK) {
4182     this._error('Failed to set dictionary');
4183   }
4184 };
4185
4186 Zlib.prototype._reset = function () {
4187   this.err = exports.Z_OK;
4188
4189   switch (this.mode) {
4190     case exports.DEFLATE:
4191     case exports.DEFLATERAW:
4192     case exports.GZIP:
4193       this.err = zlib_deflate.deflateReset(this.strm);
4194       break;
4195     case exports.INFLATE:
4196     case exports.INFLATERAW:
4197     case exports.GUNZIP:
4198       this.err = zlib_inflate.inflateReset(this.strm);
4199       break;
4200     default:
4201       break;
4202   }
4203
4204   if (this.err !== exports.Z_OK) {
4205     this._error('Failed to reset stream');
4206   }
4207 };
4208
4209 exports.Zlib = Zlib;
4210 }).call(this,require('_process'),require("buffer").Buffer)
4211 },{"_process":51,"assert":23,"buffer":32,"pako/lib/zlib/constants":41,"pako/lib/zlib/deflate.js":43,"pako/lib/zlib/inflate.js":45,"pako/lib/zlib/zstream":49}],30:[function(require,module,exports){
4212 (function (process){
4213 'use strict';
4214
4215 var Buffer = require('buffer').Buffer;
4216 var Transform = require('stream').Transform;
4217 var binding = require('./binding');
4218 var util = require('util');
4219 var assert = require('assert').ok;
4220 var kMaxLength = require('buffer').kMaxLength;
4221 var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
4222
4223 // zlib doesn't provide these, so kludge them in following the same
4224 // const naming scheme zlib uses.
4225 binding.Z_MIN_WINDOWBITS = 8;
4226 binding.Z_MAX_WINDOWBITS = 15;
4227 binding.Z_DEFAULT_WINDOWBITS = 15;
4228
4229 // fewer than 64 bytes per chunk is stupid.
4230 // technically it could work with as few as 8, but even 64 bytes
4231 // is absurdly low.  Usually a MB or more is best.
4232 binding.Z_MIN_CHUNK = 64;
4233 binding.Z_MAX_CHUNK = Infinity;
4234 binding.Z_DEFAULT_CHUNK = 16 * 1024;
4235
4236 binding.Z_MIN_MEMLEVEL = 1;
4237 binding.Z_MAX_MEMLEVEL = 9;
4238 binding.Z_DEFAULT_MEMLEVEL = 8;
4239
4240 binding.Z_MIN_LEVEL = -1;
4241 binding.Z_MAX_LEVEL = 9;
4242 binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
4243
4244 // expose all the zlib constants
4245 var bkeys = Object.keys(binding);
4246 for (var bk = 0; bk < bkeys.length; bk++) {
4247   var bkey = bkeys[bk];
4248   if (bkey.match(/^Z/)) {
4249     Object.defineProperty(exports, bkey, {
4250       enumerable: true, value: binding[bkey], writable: false
4251     });
4252   }
4253 }
4254
4255 // translation table for return codes.
4256 var codes = {
4257   Z_OK: binding.Z_OK,
4258   Z_STREAM_END: binding.Z_STREAM_END,
4259   Z_NEED_DICT: binding.Z_NEED_DICT,
4260   Z_ERRNO: binding.Z_ERRNO,
4261   Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
4262   Z_DATA_ERROR: binding.Z_DATA_ERROR,
4263   Z_MEM_ERROR: binding.Z_MEM_ERROR,
4264   Z_BUF_ERROR: binding.Z_BUF_ERROR,
4265   Z_VERSION_ERROR: binding.Z_VERSION_ERROR
4266 };
4267
4268 var ckeys = Object.keys(codes);
4269 for (var ck = 0; ck < ckeys.length; ck++) {
4270   var ckey = ckeys[ck];
4271   codes[codes[ckey]] = ckey;
4272 }
4273
4274 Object.defineProperty(exports, 'codes', {
4275   enumerable: true, value: Object.freeze(codes), writable: false
4276 });
4277
4278 exports.Deflate = Deflate;
4279 exports.Inflate = Inflate;
4280 exports.Gzip = Gzip;
4281 exports.Gunzip = Gunzip;
4282 exports.DeflateRaw = DeflateRaw;
4283 exports.InflateRaw = InflateRaw;
4284 exports.Unzip = Unzip;
4285
4286 exports.createDeflate = function (o) {
4287   return new Deflate(o);
4288 };
4289
4290 exports.createInflate = function (o) {
4291   return new Inflate(o);
4292 };
4293
4294 exports.createDeflateRaw = function (o) {
4295   return new DeflateRaw(o);
4296 };
4297
4298 exports.createInflateRaw = function (o) {
4299   return new InflateRaw(o);
4300 };
4301
4302 exports.createGzip = function (o) {
4303   return new Gzip(o);
4304 };
4305
4306 exports.createGunzip = function (o) {
4307   return new Gunzip(o);
4308 };
4309
4310 exports.createUnzip = function (o) {
4311   return new Unzip(o);
4312 };
4313
4314 // Convenience methods.
4315 // compress/decompress a string or buffer in one step.
4316 exports.deflate = function (buffer, opts, callback) {
4317   if (typeof opts === 'function') {
4318     callback = opts;
4319     opts = {};
4320   }
4321   return zlibBuffer(new Deflate(opts), buffer, callback);
4322 };
4323
4324 exports.deflateSync = function (buffer, opts) {
4325   return zlibBufferSync(new Deflate(opts), buffer);
4326 };
4327
4328 exports.gzip = function (buffer, opts, callback) {
4329   if (typeof opts === 'function') {
4330     callback = opts;
4331     opts = {};
4332   }
4333   return zlibBuffer(new Gzip(opts), buffer, callback);
4334 };
4335
4336 exports.gzipSync = function (buffer, opts) {
4337   return zlibBufferSync(new Gzip(opts), buffer);
4338 };
4339
4340 exports.deflateRaw = function (buffer, opts, callback) {
4341   if (typeof opts === 'function') {
4342     callback = opts;
4343     opts = {};
4344   }
4345   return zlibBuffer(new DeflateRaw(opts), buffer, callback);
4346 };
4347
4348 exports.deflateRawSync = function (buffer, opts) {
4349   return zlibBufferSync(new DeflateRaw(opts), buffer);
4350 };
4351
4352 exports.unzip = function (buffer, opts, callback) {
4353   if (typeof opts === 'function') {
4354     callback = opts;
4355     opts = {};
4356   }
4357   return zlibBuffer(new Unzip(opts), buffer, callback);
4358 };
4359
4360 exports.unzipSync = function (buffer, opts) {
4361   return zlibBufferSync(new Unzip(opts), buffer);
4362 };
4363
4364 exports.inflate = function (buffer, opts, callback) {
4365   if (typeof opts === 'function') {
4366     callback = opts;
4367     opts = {};
4368   }
4369   return zlibBuffer(new Inflate(opts), buffer, callback);
4370 };
4371
4372 exports.inflateSync = function (buffer, opts) {
4373   return zlibBufferSync(new Inflate(opts), buffer);
4374 };
4375
4376 exports.gunzip = function (buffer, opts, callback) {
4377   if (typeof opts === 'function') {
4378     callback = opts;
4379     opts = {};
4380   }
4381   return zlibBuffer(new Gunzip(opts), buffer, callback);
4382 };
4383
4384 exports.gunzipSync = function (buffer, opts) {
4385   return zlibBufferSync(new Gunzip(opts), buffer);
4386 };
4387
4388 exports.inflateRaw = function (buffer, opts, callback) {
4389   if (typeof opts === 'function') {
4390     callback = opts;
4391     opts = {};
4392   }
4393   return zlibBuffer(new InflateRaw(opts), buffer, callback);
4394 };
4395
4396 exports.inflateRawSync = function (buffer, opts) {
4397   return zlibBufferSync(new InflateRaw(opts), buffer);
4398 };
4399
4400 function zlibBuffer(engine, buffer, callback) {
4401   var buffers = [];
4402   var nread = 0;
4403
4404   engine.on('error', onError);
4405   engine.on('end', onEnd);
4406
4407   engine.end(buffer);
4408   flow();
4409
4410   function flow() {
4411     var chunk;
4412     while (null !== (chunk = engine.read())) {
4413       buffers.push(chunk);
4414       nread += chunk.length;
4415     }
4416     engine.once('readable', flow);
4417   }
4418
4419   function onError(err) {
4420     engine.removeListener('end', onEnd);
4421     engine.removeListener('readable', flow);
4422     callback(err);
4423   }
4424
4425   function onEnd() {
4426     var buf;
4427     var err = null;
4428
4429     if (nread >= kMaxLength) {
4430       err = new RangeError(kRangeErrorMessage);
4431     } else {
4432       buf = Buffer.concat(buffers, nread);
4433     }
4434
4435     buffers = [];
4436     engine.close();
4437     callback(err, buf);
4438   }
4439 }
4440
4441 function zlibBufferSync(engine, buffer) {
4442   if (typeof buffer === 'string') buffer = Buffer.from(buffer);
4443
4444   if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
4445
4446   var flushFlag = engine._finishFlushFlag;
4447
4448   return engine._processChunk(buffer, flushFlag);
4449 }
4450
4451 // generic zlib
4452 // minimal 2-byte header
4453 function Deflate(opts) {
4454   if (!(this instanceof Deflate)) return new Deflate(opts);
4455   Zlib.call(this, opts, binding.DEFLATE);
4456 }
4457
4458 function Inflate(opts) {
4459   if (!(this instanceof Inflate)) return new Inflate(opts);
4460   Zlib.call(this, opts, binding.INFLATE);
4461 }
4462
4463 // gzip - bigger header, same deflate compression
4464 function Gzip(opts) {
4465   if (!(this instanceof Gzip)) return new Gzip(opts);
4466   Zlib.call(this, opts, binding.GZIP);
4467 }
4468
4469 function Gunzip(opts) {
4470   if (!(this instanceof Gunzip)) return new Gunzip(opts);
4471   Zlib.call(this, opts, binding.GUNZIP);
4472 }
4473
4474 // raw - no header
4475 function DeflateRaw(opts) {
4476   if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
4477   Zlib.call(this, opts, binding.DEFLATERAW);
4478 }
4479
4480 function InflateRaw(opts) {
4481   if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
4482   Zlib.call(this, opts, binding.INFLATERAW);
4483 }
4484
4485 // auto-detect header.
4486 function Unzip(opts) {
4487   if (!(this instanceof Unzip)) return new Unzip(opts);
4488   Zlib.call(this, opts, binding.UNZIP);
4489 }
4490
4491 function isValidFlushFlag(flag) {
4492   return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK;
4493 }
4494
4495 // the Zlib class they all inherit from
4496 // This thing manages the queue of requests, and returns
4497 // true or false if there is anything in the queue when
4498 // you call the .write() method.
4499
4500 function Zlib(opts, mode) {
4501   var _this = this;
4502
4503   this._opts = opts = opts || {};
4504   this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
4505
4506   Transform.call(this, opts);
4507
4508   if (opts.flush && !isValidFlushFlag(opts.flush)) {
4509     throw new Error('Invalid flush flag: ' + opts.flush);
4510   }
4511   if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
4512     throw new Error('Invalid flush flag: ' + opts.finishFlush);
4513   }
4514
4515   this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
4516   this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
4517
4518   if (opts.chunkSize) {
4519     if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
4520       throw new Error('Invalid chunk size: ' + opts.chunkSize);
4521     }
4522   }
4523
4524   if (opts.windowBits) {
4525     if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
4526       throw new Error('Invalid windowBits: ' + opts.windowBits);
4527     }
4528   }
4529
4530   if (opts.level) {
4531     if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
4532       throw new Error('Invalid compression level: ' + opts.level);
4533     }
4534   }
4535
4536   if (opts.memLevel) {
4537     if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
4538       throw new Error('Invalid memLevel: ' + opts.memLevel);
4539     }
4540   }
4541
4542   if (opts.strategy) {
4543     if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) {
4544       throw new Error('Invalid strategy: ' + opts.strategy);
4545     }
4546   }
4547
4548   if (opts.dictionary) {
4549     if (!Buffer.isBuffer(opts.dictionary)) {
4550       throw new Error('Invalid dictionary: it should be a Buffer instance');
4551     }
4552   }
4553
4554   this._handle = new binding.Zlib(mode);
4555
4556   var self = this;
4557   this._hadError = false;
4558   this._handle.onerror = function (message, errno) {
4559     // there is no way to cleanly recover.
4560     // continuing only obscures problems.
4561     _close(self);
4562     self._hadError = true;
4563
4564     var error = new Error(message);
4565     error.errno = errno;
4566     error.code = exports.codes[errno];
4567     self.emit('error', error);
4568   };
4569
4570   var level = exports.Z_DEFAULT_COMPRESSION;
4571   if (typeof opts.level === 'number') level = opts.level;
4572
4573   var strategy = exports.Z_DEFAULT_STRATEGY;
4574   if (typeof opts.strategy === 'number') strategy = opts.strategy;
4575
4576   this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
4577
4578   this._buffer = Buffer.allocUnsafe(this._chunkSize);
4579   this._offset = 0;
4580   this._level = level;
4581   this._strategy = strategy;
4582
4583   this.once('end', this.close);
4584
4585   Object.defineProperty(this, '_closed', {
4586     get: function () {
4587       return !_this._handle;
4588     },
4589     configurable: true,
4590     enumerable: true
4591   });
4592 }
4593
4594 util.inherits(Zlib, Transform);
4595
4596 Zlib.prototype.params = function (level, strategy, callback) {
4597   if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
4598     throw new RangeError('Invalid compression level: ' + level);
4599   }
4600   if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
4601     throw new TypeError('Invalid strategy: ' + strategy);
4602   }
4603
4604   if (this._level !== level || this._strategy !== strategy) {
4605     var self = this;
4606     this.flush(binding.Z_SYNC_FLUSH, function () {
4607       assert(self._handle, 'zlib binding closed');
4608       self._handle.params(level, strategy);
4609       if (!self._hadError) {
4610         self._level = level;
4611         self._strategy = strategy;
4612         if (callback) callback();
4613       }
4614     });
4615   } else {
4616     process.nextTick(callback);
4617   }
4618 };
4619
4620 Zlib.prototype.reset = function () {
4621   assert(this._handle, 'zlib binding closed');
4622   return this._handle.reset();
4623 };
4624
4625 // This is the _flush function called by the transform class,
4626 // internally, when the last chunk has been written.
4627 Zlib.prototype._flush = function (callback) {
4628   this._transform(Buffer.alloc(0), '', callback);
4629 };
4630
4631 Zlib.prototype.flush = function (kind, callback) {
4632   var _this2 = this;
4633
4634   var ws = this._writableState;
4635
4636   if (typeof kind === 'function' || kind === undefined && !callback) {
4637     callback = kind;
4638     kind = binding.Z_FULL_FLUSH;
4639   }
4640
4641   if (ws.ended) {
4642     if (callback) process.nextTick(callback);
4643   } else if (ws.ending) {
4644     if (callback) this.once('end', callback);
4645   } else if (ws.needDrain) {
4646     if (callback) {
4647       this.once('drain', function () {
4648         return _this2.flush(kind, callback);
4649       });
4650     }
4651   } else {
4652     this._flushFlag = kind;
4653     this.write(Buffer.alloc(0), '', callback);
4654   }
4655 };
4656
4657 Zlib.prototype.close = function (callback) {
4658   _close(this, callback);
4659   process.nextTick(emitCloseNT, this);
4660 };
4661
4662 function _close(engine, callback) {
4663   if (callback) process.nextTick(callback);
4664
4665   // Caller may invoke .close after a zlib error (which will null _handle).
4666   if (!engine._handle) return;
4667
4668   engine._handle.close();
4669   engine._handle = null;
4670 }
4671
4672 function emitCloseNT(self) {
4673   self.emit('close');
4674 }
4675
4676 Zlib.prototype._transform = function (chunk, encoding, cb) {
4677   var flushFlag;
4678   var ws = this._writableState;
4679   var ending = ws.ending || ws.ended;
4680   var last = ending && (!chunk || ws.length === chunk.length);
4681
4682   if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
4683
4684   if (!this._handle) return cb(new Error('zlib binding closed'));
4685
4686   // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
4687   // (or whatever flag was provided using opts.finishFlush).
4688   // If it's explicitly flushing at some other time, then we use
4689   // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
4690   // goodness.
4691   if (last) flushFlag = this._finishFlushFlag;else {
4692     flushFlag = this._flushFlag;
4693     // once we've flushed the last of the queue, stop flushing and
4694     // go back to the normal behavior.
4695     if (chunk.length >= ws.length) {
4696       this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
4697     }
4698   }
4699
4700   this._processChunk(chunk, flushFlag, cb);
4701 };
4702
4703 Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
4704   var availInBefore = chunk && chunk.length;
4705   var availOutBefore = this._chunkSize - this._offset;
4706   var inOff = 0;
4707
4708   var self = this;
4709
4710   var async = typeof cb === 'function';
4711
4712   if (!async) {
4713     var buffers = [];
4714     var nread = 0;
4715
4716     var error;
4717     this.on('error', function (er) {
4718       error = er;
4719     });
4720
4721     assert(this._handle, 'zlib binding closed');
4722     do {
4723       var res = this._handle.writeSync(flushFlag, chunk, // in
4724       inOff, // in_off
4725       availInBefore, // in_len
4726       this._buffer, // out
4727       this._offset, //out_off
4728       availOutBefore); // out_len
4729     } while (!this._hadError && callback(res[0], res[1]));
4730
4731     if (this._hadError) {
4732       throw error;
4733     }
4734
4735     if (nread >= kMaxLength) {
4736       _close(this);
4737       throw new RangeError(kRangeErrorMessage);
4738     }
4739
4740     var buf = Buffer.concat(buffers, nread);
4741     _close(this);
4742
4743     return buf;
4744   }
4745
4746   assert(this._handle, 'zlib binding closed');
4747   var req = this._handle.write(flushFlag, chunk, // in
4748   inOff, // in_off
4749   availInBefore, // in_len
4750   this._buffer, // out
4751   this._offset, //out_off
4752   availOutBefore); // out_len
4753
4754   req.buffer = chunk;
4755   req.callback = callback;
4756
4757   function callback(availInAfter, availOutAfter) {
4758     // When the callback is used in an async write, the callback's
4759     // context is the `req` object that was created. The req object
4760     // is === this._handle, and that's why it's important to null
4761     // out the values after they are done being used. `this._handle`
4762     // can stay in memory longer than the callback and buffer are needed.
4763     if (this) {
4764       this.buffer = null;
4765       this.callback = null;
4766     }
4767
4768     if (self._hadError) return;
4769
4770     var have = availOutBefore - availOutAfter;
4771     assert(have >= 0, 'have should not go down');
4772
4773     if (have > 0) {
4774       var out = self._buffer.slice(self._offset, self._offset + have);
4775       self._offset += have;
4776       // serve some output to the consumer.
4777       if (async) {
4778         self.push(out);
4779       } else {
4780         buffers.push(out);
4781         nread += out.length;
4782       }
4783     }
4784
4785     // exhausted the output buffer, or used all the input create a new one.
4786     if (availOutAfter === 0 || self._offset >= self._chunkSize) {
4787       availOutBefore = self._chunkSize;
4788       self._offset = 0;
4789       self._buffer = Buffer.allocUnsafe(self._chunkSize);
4790     }
4791
4792     if (availOutAfter === 0) {
4793       // Not actually done.  Need to reprocess.
4794       // Also, update the availInBefore to the availInAfter value,
4795       // so that if we have to hit it a third (fourth, etc.) time,
4796       // it'll have the correct byte counts.
4797       inOff += availInBefore - availInAfter;
4798       availInBefore = availInAfter;
4799
4800       if (!async) return true;
4801
4802       var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
4803       newReq.callback = callback; // this same function
4804       newReq.buffer = chunk;
4805       return;
4806     }
4807
4808     if (!async) return false;
4809
4810     // finished with the chunk.
4811     cb();
4812   }
4813 };
4814
4815 util.inherits(Deflate, Zlib);
4816 util.inherits(Inflate, Zlib);
4817 util.inherits(Gzip, Zlib);
4818 util.inherits(Gunzip, Zlib);
4819 util.inherits(DeflateRaw, Zlib);
4820 util.inherits(InflateRaw, Zlib);
4821 util.inherits(Unzip, Zlib);
4822 }).call(this,require('_process'))
4823 },{"./binding":29,"_process":51,"assert":23,"buffer":32,"stream":64,"util":69}],31:[function(require,module,exports){
4824 (function (global){
4825 'use strict';
4826
4827 var buffer = require('buffer');
4828 var Buffer = buffer.Buffer;
4829 var SlowBuffer = buffer.SlowBuffer;
4830 var MAX_LEN = buffer.kMaxLength || 2147483647;
4831 exports.alloc = function alloc(size, fill, encoding) {
4832   if (typeof Buffer.alloc === 'function') {
4833     return Buffer.alloc(size, fill, encoding);
4834   }
4835   if (typeof encoding === 'number') {
4836     throw new TypeError('encoding must not be number');
4837   }
4838   if (typeof size !== 'number') {
4839     throw new TypeError('size must be a number');
4840   }
4841   if (size > MAX_LEN) {
4842     throw new RangeError('size is too large');
4843   }
4844   var enc = encoding;
4845   var _fill = fill;
4846   if (_fill === undefined) {
4847     enc = undefined;
4848     _fill = 0;
4849   }
4850   var buf = new Buffer(size);
4851   if (typeof _fill === 'string') {
4852     var fillBuf = new Buffer(_fill, enc);
4853     var flen = fillBuf.length;
4854     var i = -1;
4855     while (++i < size) {
4856       buf[i] = fillBuf[i % flen];
4857     }
4858   } else {
4859     buf.fill(_fill);
4860   }
4861   return buf;
4862 }
4863 exports.allocUnsafe = function allocUnsafe(size) {
4864   if (typeof Buffer.allocUnsafe === 'function') {
4865     return Buffer.allocUnsafe(size);
4866   }
4867   if (typeof size !== 'number') {
4868     throw new TypeError('size must be a number');
4869   }
4870   if (size > MAX_LEN) {
4871     throw new RangeError('size is too large');
4872   }
4873   return new Buffer(size);
4874 }
4875 exports.from = function from(value, encodingOrOffset, length) {
4876   if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
4877     return Buffer.from(value, encodingOrOffset, length);
4878   }
4879   if (typeof value === 'number') {
4880     throw new TypeError('"value" argument must not be a number');
4881   }
4882   if (typeof value === 'string') {
4883     return new Buffer(value, encodingOrOffset);
4884   }
4885   if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
4886     var offset = encodingOrOffset;
4887     if (arguments.length === 1) {
4888       return new Buffer(value);
4889     }
4890     if (typeof offset === 'undefined') {
4891       offset = 0;
4892     }
4893     var len = length;
4894     if (typeof len === 'undefined') {
4895       len = value.byteLength - offset;
4896     }
4897     if (offset >= value.byteLength) {
4898       throw new RangeError('\'offset\' is out of bounds');
4899     }
4900     if (len > value.byteLength - offset) {
4901       throw new RangeError('\'length\' is out of bounds');
4902     }
4903     return new Buffer(value.slice(offset, offset + len));
4904   }
4905   if (Buffer.isBuffer(value)) {
4906     var out = new Buffer(value.length);
4907     value.copy(out, 0, 0, value.length);
4908     return out;
4909   }
4910   if (value) {
4911     if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
4912       return new Buffer(value);
4913     }
4914     if (value.type === 'Buffer' && Array.isArray(value.data)) {
4915       return new Buffer(value.data);
4916     }
4917   }
4918
4919   throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
4920 }
4921 exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
4922   if (typeof Buffer.allocUnsafeSlow === 'function') {
4923     return Buffer.allocUnsafeSlow(size);
4924   }
4925   if (typeof size !== 'number') {
4926     throw new TypeError('size must be a number');
4927   }
4928   if (size >= MAX_LEN) {
4929     throw new RangeError('size is too large');
4930   }
4931   return new SlowBuffer(size);
4932 }
4933
4934 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4935 },{"buffer":32}],32:[function(require,module,exports){
4936 (function (Buffer){
4937 /*!
4938  * The buffer module from node.js, for the browser.
4939  *
4940  * @author   Feross Aboukhadijeh <https://feross.org>
4941  * @license  MIT
4942  */
4943 /* eslint-disable no-proto */
4944
4945 'use strict'
4946
4947 var base64 = require('base64-js')
4948 var ieee754 = require('ieee754')
4949
4950 exports.Buffer = Buffer
4951 exports.SlowBuffer = SlowBuffer
4952 exports.INSPECT_MAX_BYTES = 50
4953
4954 var K_MAX_LENGTH = 0x7fffffff
4955 exports.kMaxLength = K_MAX_LENGTH
4956
4957 /**
4958  * If `Buffer.TYPED_ARRAY_SUPPORT`:
4959  *   === true    Use Uint8Array implementation (fastest)
4960  *   === false   Print warning and recommend using `buffer` v4.x which has an Object
4961  *               implementation (most compatible, even IE6)
4962  *
4963  * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
4964  * Opera 11.6+, iOS 4.2+.
4965  *
4966  * We report that the browser does not support typed arrays if the are not subclassable
4967  * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
4968  * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
4969  * for __proto__ and has a buggy typed array implementation.
4970  */
4971 Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
4972
4973 if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
4974     typeof console.error === 'function') {
4975   console.error(
4976     'This browser lacks typed array (Uint8Array) support which is required by ' +
4977     '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
4978   )
4979 }
4980
4981 function typedArraySupport () {
4982   // Can typed array instances can be augmented?
4983   try {
4984     var arr = new Uint8Array(1)
4985     arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
4986     return arr.foo() === 42
4987   } catch (e) {
4988     return false
4989   }
4990 }
4991
4992 Object.defineProperty(Buffer.prototype, 'parent', {
4993   enumerable: true,
4994   get: function () {
4995     if (!Buffer.isBuffer(this)) return undefined
4996     return this.buffer
4997   }
4998 })
4999
5000 Object.defineProperty(Buffer.prototype, 'offset', {
5001   enumerable: true,
5002   get: function () {
5003     if (!Buffer.isBuffer(this)) return undefined
5004     return this.byteOffset
5005   }
5006 })
5007
5008 function createBuffer (length) {
5009   if (length > K_MAX_LENGTH) {
5010     throw new RangeError('The value "' + length + '" is invalid for option "size"')
5011   }
5012   // Return an augmented `Uint8Array` instance
5013   var buf = new Uint8Array(length)
5014   buf.__proto__ = Buffer.prototype
5015   return buf
5016 }
5017
5018 /**
5019  * The Buffer constructor returns instances of `Uint8Array` that have their
5020  * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
5021  * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
5022  * and the `Uint8Array` methods. Square bracket notation works as expected -- it
5023  * returns a single octet.
5024  *
5025  * The `Uint8Array` prototype remains unmodified.
5026  */
5027
5028 function Buffer (arg, encodingOrOffset, length) {
5029   // Common case.
5030   if (typeof arg === 'number') {
5031     if (typeof encodingOrOffset === 'string') {
5032       throw new TypeError(
5033         'The "string" argument must be of type string. Received type number'
5034       )
5035     }
5036     return allocUnsafe(arg)
5037   }
5038   return from(arg, encodingOrOffset, length)
5039 }
5040
5041 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
5042 if (typeof Symbol !== 'undefined' && Symbol.species != null &&
5043     Buffer[Symbol.species] === Buffer) {
5044   Object.defineProperty(Buffer, Symbol.species, {
5045     value: null,
5046     configurable: true,
5047     enumerable: false,
5048     writable: false
5049   })
5050 }
5051
5052 Buffer.poolSize = 8192 // not used by this implementation
5053
5054 function from (value, encodingOrOffset, length) {
5055   if (typeof value === 'string') {
5056     return fromString(value, encodingOrOffset)
5057   }
5058
5059   if (ArrayBuffer.isView(value)) {
5060     return fromArrayLike(value)
5061   }
5062
5063   if (value == null) {
5064     throw TypeError(
5065       'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
5066       'or Array-like Object. Received type ' + (typeof value)
5067     )
5068   }
5069
5070   if (isInstance(value, ArrayBuffer) ||
5071       (value && isInstance(value.buffer, ArrayBuffer))) {
5072     return fromArrayBuffer(value, encodingOrOffset, length)
5073   }
5074
5075   if (typeof value === 'number') {
5076     throw new TypeError(
5077       'The "value" argument must not be of type number. Received type number'
5078     )
5079   }
5080
5081   var valueOf = value.valueOf && value.valueOf()
5082   if (valueOf != null && valueOf !== value) {
5083     return Buffer.from(valueOf, encodingOrOffset, length)
5084   }
5085
5086   var b = fromObject(value)
5087   if (b) return b
5088
5089   if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
5090       typeof value[Symbol.toPrimitive] === 'function') {
5091     return Buffer.from(
5092       value[Symbol.toPrimitive]('string'), encodingOrOffset, length
5093     )
5094   }
5095
5096   throw new TypeError(
5097     'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
5098     'or Array-like Object. Received type ' + (typeof value)
5099   )
5100 }
5101
5102 /**
5103  * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
5104  * if value is a number.
5105  * Buffer.from(str[, encoding])
5106  * Buffer.from(array)
5107  * Buffer.from(buffer)
5108  * Buffer.from(arrayBuffer[, byteOffset[, length]])
5109  **/
5110 Buffer.from = function (value, encodingOrOffset, length) {
5111   return from(value, encodingOrOffset, length)
5112 }
5113
5114 // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
5115 // https://github.com/feross/buffer/pull/148
5116 Buffer.prototype.__proto__ = Uint8Array.prototype
5117 Buffer.__proto__ = Uint8Array
5118
5119 function assertSize (size) {
5120   if (typeof size !== 'number') {
5121     throw new TypeError('"size" argument must be of type number')
5122   } else if (size < 0) {
5123     throw new RangeError('The value "' + size + '" is invalid for option "size"')
5124   }
5125 }
5126
5127 function alloc (size, fill, encoding) {
5128   assertSize(size)
5129   if (size <= 0) {
5130     return createBuffer(size)
5131   }
5132   if (fill !== undefined) {
5133     // Only pay attention to encoding if it's a string. This
5134     // prevents accidentally sending in a number that would
5135     // be interpretted as a start offset.
5136     return typeof encoding === 'string'
5137       ? createBuffer(size).fill(fill, encoding)
5138       : createBuffer(size).fill(fill)
5139   }
5140   return createBuffer(size)
5141 }
5142
5143 /**
5144  * Creates a new filled Buffer instance.
5145  * alloc(size[, fill[, encoding]])
5146  **/
5147 Buffer.alloc = function (size, fill, encoding) {
5148   return alloc(size, fill, encoding)
5149 }
5150
5151 function allocUnsafe (size) {
5152   assertSize(size)
5153   return createBuffer(size < 0 ? 0 : checked(size) | 0)
5154 }
5155
5156 /**
5157  * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
5158  * */
5159 Buffer.allocUnsafe = function (size) {
5160   return allocUnsafe(size)
5161 }
5162 /**
5163  * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
5164  */
5165 Buffer.allocUnsafeSlow = function (size) {
5166   return allocUnsafe(size)
5167 }
5168
5169 function fromString (string, encoding) {
5170   if (typeof encoding !== 'string' || encoding === '') {
5171     encoding = 'utf8'
5172   }
5173
5174   if (!Buffer.isEncoding(encoding)) {
5175     throw new TypeError('Unknown encoding: ' + encoding)
5176   }
5177
5178   var length = byteLength(string, encoding) | 0
5179   var buf = createBuffer(length)
5180
5181   var actual = buf.write(string, encoding)
5182
5183   if (actual !== length) {
5184     // Writing a hex string, for example, that contains invalid characters will
5185     // cause everything after the first invalid character to be ignored. (e.g.
5186     // 'abxxcd' will be treated as 'ab')
5187     buf = buf.slice(0, actual)
5188   }
5189
5190   return buf
5191 }
5192
5193 function fromArrayLike (array) {
5194   var length = array.length < 0 ? 0 : checked(array.length) | 0
5195   var buf = createBuffer(length)
5196   for (var i = 0; i < length; i += 1) {
5197     buf[i] = array[i] & 255
5198   }
5199   return buf
5200 }
5201
5202 function fromArrayBuffer (array, byteOffset, length) {
5203   if (byteOffset < 0 || array.byteLength < byteOffset) {
5204     throw new RangeError('"offset" is outside of buffer bounds')
5205   }
5206
5207   if (array.byteLength < byteOffset + (length || 0)) {
5208     throw new RangeError('"length" is outside of buffer bounds')
5209   }
5210
5211   var buf
5212   if (byteOffset === undefined && length === undefined) {
5213     buf = new Uint8Array(array)
5214   } else if (length === undefined) {
5215     buf = new Uint8Array(array, byteOffset)
5216   } else {
5217     buf = new Uint8Array(array, byteOffset, length)
5218   }
5219
5220   // Return an augmented `Uint8Array` instance
5221   buf.__proto__ = Buffer.prototype
5222   return buf
5223 }
5224
5225 function fromObject (obj) {
5226   if (Buffer.isBuffer(obj)) {
5227     var len = checked(obj.length) | 0
5228     var buf = createBuffer(len)
5229
5230     if (buf.length === 0) {
5231       return buf
5232     }
5233
5234     obj.copy(buf, 0, 0, len)
5235     return buf
5236   }
5237
5238   if (obj.length !== undefined) {
5239     if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
5240       return createBuffer(0)
5241     }
5242     return fromArrayLike(obj)
5243   }
5244
5245   if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
5246     return fromArrayLike(obj.data)
5247   }
5248 }
5249
5250 function checked (length) {
5251   // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
5252   // length is NaN (which is otherwise coerced to zero.)
5253   if (length >= K_MAX_LENGTH) {
5254     throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
5255                          'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
5256   }
5257   return length | 0
5258 }
5259
5260 function SlowBuffer (length) {
5261   if (+length != length) { // eslint-disable-line eqeqeq
5262     length = 0
5263   }
5264   return Buffer.alloc(+length)
5265 }
5266
5267 Buffer.isBuffer = function isBuffer (b) {
5268   return b != null && b._isBuffer === true &&
5269     b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
5270 }
5271
5272 Buffer.compare = function compare (a, b) {
5273   if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
5274   if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
5275   if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
5276     throw new TypeError(
5277       'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
5278     )
5279   }
5280
5281   if (a === b) return 0
5282
5283   var x = a.length
5284   var y = b.length
5285
5286   for (var i = 0, len = Math.min(x, y); i < len; ++i) {
5287     if (a[i] !== b[i]) {
5288       x = a[i]
5289       y = b[i]
5290       break
5291     }
5292   }
5293
5294   if (x < y) return -1
5295   if (y < x) return 1
5296   return 0
5297 }
5298
5299 Buffer.isEncoding = function isEncoding (encoding) {
5300   switch (String(encoding).toLowerCase()) {
5301     case 'hex':
5302     case 'utf8':
5303     case 'utf-8':
5304     case 'ascii':
5305     case 'latin1':
5306     case 'binary':
5307     case 'base64':
5308     case 'ucs2':
5309     case 'ucs-2':
5310     case 'utf16le':
5311     case 'utf-16le':
5312       return true
5313     default:
5314       return false
5315   }
5316 }
5317
5318 Buffer.concat = function concat (list, length) {
5319   if (!Array.isArray(list)) {
5320     throw new TypeError('"list" argument must be an Array of Buffers')
5321   }
5322
5323   if (list.length === 0) {
5324     return Buffer.alloc(0)
5325   }
5326
5327   var i
5328   if (length === undefined) {
5329     length = 0
5330     for (i = 0; i < list.length; ++i) {
5331       length += list[i].length
5332     }
5333   }
5334
5335   var buffer = Buffer.allocUnsafe(length)
5336   var pos = 0
5337   for (i = 0; i < list.length; ++i) {
5338     var buf = list[i]
5339     if (isInstance(buf, Uint8Array)) {
5340       buf = Buffer.from(buf)
5341     }
5342     if (!Buffer.isBuffer(buf)) {
5343       throw new TypeError('"list" argument must be an Array of Buffers')
5344     }
5345     buf.copy(buffer, pos)
5346     pos += buf.length
5347   }
5348   return buffer
5349 }
5350
5351 function byteLength (string, encoding) {
5352   if (Buffer.isBuffer(string)) {
5353     return string.length
5354   }
5355   if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
5356     return string.byteLength
5357   }
5358   if (typeof string !== 'string') {
5359     throw new TypeError(
5360       'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
5361       'Received type ' + typeof string
5362     )
5363   }
5364
5365   var len = string.length
5366   var mustMatch = (arguments.length > 2 && arguments[2] === true)
5367   if (!mustMatch && len === 0) return 0
5368
5369   // Use a for loop to avoid recursion
5370   var loweredCase = false
5371   for (;;) {
5372     switch (encoding) {
5373       case 'ascii':
5374       case 'latin1':
5375       case 'binary':
5376         return len
5377       case 'utf8':
5378       case 'utf-8':
5379         return utf8ToBytes(string).length
5380       case 'ucs2':
5381       case 'ucs-2':
5382       case 'utf16le':
5383       case 'utf-16le':
5384         return len * 2
5385       case 'hex':
5386         return len >>> 1
5387       case 'base64':
5388         return base64ToBytes(string).length
5389       default:
5390         if (loweredCase) {
5391           return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
5392         }
5393         encoding = ('' + encoding).toLowerCase()
5394         loweredCase = true
5395     }
5396   }
5397 }
5398 Buffer.byteLength = byteLength
5399
5400 function slowToString (encoding, start, end) {
5401   var loweredCase = false
5402
5403   // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
5404   // property of a typed array.
5405
5406   // This behaves neither like String nor Uint8Array in that we set start/end
5407   // to their upper/lower bounds if the value passed is out of range.
5408   // undefined is handled specially as per ECMA-262 6th Edition,
5409   // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
5410   if (start === undefined || start < 0) {
5411     start = 0
5412   }
5413   // Return early if start > this.length. Done here to prevent potential uint32
5414   // coercion fail below.
5415   if (start > this.length) {
5416     return ''
5417   }
5418
5419   if (end === undefined || end > this.length) {
5420     end = this.length
5421   }
5422
5423   if (end <= 0) {
5424     return ''
5425   }
5426
5427   // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
5428   end >>>= 0
5429   start >>>= 0
5430
5431   if (end <= start) {
5432     return ''
5433   }
5434
5435   if (!encoding) encoding = 'utf8'
5436
5437   while (true) {
5438     switch (encoding) {
5439       case 'hex':
5440         return hexSlice(this, start, end)
5441
5442       case 'utf8':
5443       case 'utf-8':
5444         return utf8Slice(this, start, end)
5445
5446       case 'ascii':
5447         return asciiSlice(this, start, end)
5448
5449       case 'latin1':
5450       case 'binary':
5451         return latin1Slice(this, start, end)
5452
5453       case 'base64':
5454         return base64Slice(this, start, end)
5455
5456       case 'ucs2':
5457       case 'ucs-2':
5458       case 'utf16le':
5459       case 'utf-16le':
5460         return utf16leSlice(this, start, end)
5461
5462       default:
5463         if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
5464         encoding = (encoding + '').toLowerCase()
5465         loweredCase = true
5466     }
5467   }
5468 }
5469
5470 // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
5471 // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
5472 // reliably in a browserify context because there could be multiple different
5473 // copies of the 'buffer' package in use. This method works even for Buffer
5474 // instances that were created from another copy of the `buffer` package.
5475 // See: https://github.com/feross/buffer/issues/154
5476 Buffer.prototype._isBuffer = true
5477
5478 function swap (b, n, m) {
5479   var i = b[n]
5480   b[n] = b[m]
5481   b[m] = i
5482 }
5483
5484 Buffer.prototype.swap16 = function swap16 () {
5485   var len = this.length
5486   if (len % 2 !== 0) {
5487     throw new RangeError('Buffer size must be a multiple of 16-bits')
5488   }
5489   for (var i = 0; i < len; i += 2) {
5490     swap(this, i, i + 1)
5491   }
5492   return this
5493 }
5494
5495 Buffer.prototype.swap32 = function swap32 () {
5496   var len = this.length
5497   if (len % 4 !== 0) {
5498     throw new RangeError('Buffer size must be a multiple of 32-bits')
5499   }
5500   for (var i = 0; i < len; i += 4) {
5501     swap(this, i, i + 3)
5502     swap(this, i + 1, i + 2)
5503   }
5504   return this
5505 }
5506
5507 Buffer.prototype.swap64 = function swap64 () {
5508   var len = this.length
5509   if (len % 8 !== 0) {
5510     throw new RangeError('Buffer size must be a multiple of 64-bits')
5511   }
5512   for (var i = 0; i < len; i += 8) {
5513     swap(this, i, i + 7)
5514     swap(this, i + 1, i + 6)
5515     swap(this, i + 2, i + 5)
5516     swap(this, i + 3, i + 4)
5517   }
5518   return this
5519 }
5520
5521 Buffer.prototype.toString = function toString () {
5522   var length = this.length
5523   if (length === 0) return ''
5524   if (arguments.length === 0) return utf8Slice(this, 0, length)
5525   return slowToString.apply(this, arguments)
5526 }
5527
5528 Buffer.prototype.toLocaleString = Buffer.prototype.toString
5529
5530 Buffer.prototype.equals = function equals (b) {
5531   if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
5532   if (this === b) return true
5533   return Buffer.compare(this, b) === 0
5534 }
5535
5536 Buffer.prototype.inspect = function inspect () {
5537   var str = ''
5538   var max = exports.INSPECT_MAX_BYTES
5539   str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
5540   if (this.length > max) str += ' ... '
5541   return '<Buffer ' + str + '>'
5542 }
5543
5544 Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
5545   if (isInstance(target, Uint8Array)) {
5546     target = Buffer.from(target, target.offset, target.byteLength)
5547   }
5548   if (!Buffer.isBuffer(target)) {
5549     throw new TypeError(
5550       'The "target" argument must be one of type Buffer or Uint8Array. ' +
5551       'Received type ' + (typeof target)
5552     )
5553   }
5554
5555   if (start === undefined) {
5556     start = 0
5557   }
5558   if (end === undefined) {
5559     end = target ? target.length : 0
5560   }
5561   if (thisStart === undefined) {
5562     thisStart = 0
5563   }
5564   if (thisEnd === undefined) {
5565     thisEnd = this.length
5566   }
5567
5568   if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
5569     throw new RangeError('out of range index')
5570   }
5571
5572   if (thisStart >= thisEnd && start >= end) {
5573     return 0
5574   }
5575   if (thisStart >= thisEnd) {
5576     return -1
5577   }
5578   if (start >= end) {
5579     return 1
5580   }
5581
5582   start >>>= 0
5583   end >>>= 0
5584   thisStart >>>= 0
5585   thisEnd >>>= 0
5586
5587   if (this === target) return 0
5588
5589   var x = thisEnd - thisStart
5590   var y = end - start
5591   var len = Math.min(x, y)
5592
5593   var thisCopy = this.slice(thisStart, thisEnd)
5594   var targetCopy = target.slice(start, end)
5595
5596   for (var i = 0; i < len; ++i) {
5597     if (thisCopy[i] !== targetCopy[i]) {
5598       x = thisCopy[i]
5599       y = targetCopy[i]
5600       break
5601     }
5602   }
5603
5604   if (x < y) return -1
5605   if (y < x) return 1
5606   return 0
5607 }
5608
5609 // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
5610 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
5611 //
5612 // Arguments:
5613 // - buffer - a Buffer to search
5614 // - val - a string, Buffer, or number
5615 // - byteOffset - an index into `buffer`; will be clamped to an int32
5616 // - encoding - an optional encoding, relevant is val is a string
5617 // - dir - true for indexOf, false for lastIndexOf
5618 function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
5619   // Empty buffer means no match
5620   if (buffer.length === 0) return -1
5621
5622   // Normalize byteOffset
5623   if (typeof byteOffset === 'string') {
5624     encoding = byteOffset
5625     byteOffset = 0
5626   } else if (byteOffset > 0x7fffffff) {
5627     byteOffset = 0x7fffffff
5628   } else if (byteOffset < -0x80000000) {
5629     byteOffset = -0x80000000
5630   }
5631   byteOffset = +byteOffset // Coerce to Number.
5632   if (numberIsNaN(byteOffset)) {
5633     // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
5634     byteOffset = dir ? 0 : (buffer.length - 1)
5635   }
5636
5637   // Normalize byteOffset: negative offsets start from the end of the buffer
5638   if (byteOffset < 0) byteOffset = buffer.length + byteOffset
5639   if (byteOffset >= buffer.length) {
5640     if (dir) return -1
5641     else byteOffset = buffer.length - 1
5642   } else if (byteOffset < 0) {
5643     if (dir) byteOffset = 0
5644     else return -1
5645   }
5646
5647   // Normalize val
5648   if (typeof val === 'string') {
5649     val = Buffer.from(val, encoding)
5650   }
5651
5652   // Finally, search either indexOf (if dir is true) or lastIndexOf
5653   if (Buffer.isBuffer(val)) {
5654     // Special case: looking for empty string/buffer always fails
5655     if (val.length === 0) {
5656       return -1
5657     }
5658     return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
5659   } else if (typeof val === 'number') {
5660     val = val & 0xFF // Search for a byte value [0-255]
5661     if (typeof Uint8Array.prototype.indexOf === 'function') {
5662       if (dir) {
5663         return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
5664       } else {
5665         return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
5666       }
5667     }
5668     return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
5669   }
5670
5671   throw new TypeError('val must be string, number or Buffer')
5672 }
5673
5674 function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
5675   var indexSize = 1
5676   var arrLength = arr.length
5677   var valLength = val.length
5678
5679   if (encoding !== undefined) {
5680     encoding = String(encoding).toLowerCase()
5681     if (encoding === 'ucs2' || encoding === 'ucs-2' ||
5682         encoding === 'utf16le' || encoding === 'utf-16le') {
5683       if (arr.length < 2 || val.length < 2) {
5684         return -1
5685       }
5686       indexSize = 2
5687       arrLength /= 2
5688       valLength /= 2
5689       byteOffset /= 2
5690     }
5691   }
5692
5693   function read (buf, i) {
5694     if (indexSize === 1) {
5695       return buf[i]
5696     } else {
5697       return buf.readUInt16BE(i * indexSize)
5698     }
5699   }
5700
5701   var i
5702   if (dir) {
5703     var foundIndex = -1
5704     for (i = byteOffset; i < arrLength; i++) {
5705       if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
5706         if (foundIndex === -1) foundIndex = i
5707         if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
5708       } else {
5709         if (foundIndex !== -1) i -= i - foundIndex
5710         foundIndex = -1
5711       }
5712     }
5713   } else {
5714     if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
5715     for (i = byteOffset; i >= 0; i--) {
5716       var found = true
5717       for (var j = 0; j < valLength; j++) {
5718         if (read(arr, i + j) !== read(val, j)) {
5719           found = false
5720           break
5721         }
5722       }
5723       if (found) return i
5724     }
5725   }
5726
5727   return -1
5728 }
5729
5730 Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
5731   return this.indexOf(val, byteOffset, encoding) !== -1
5732 }
5733
5734 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
5735   return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
5736 }
5737
5738 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
5739   return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
5740 }
5741
5742 function hexWrite (buf, string, offset, length) {
5743   offset = Number(offset) || 0
5744   var remaining = buf.length - offset
5745   if (!length) {
5746     length = remaining
5747   } else {
5748     length = Number(length)
5749     if (length > remaining) {
5750       length = remaining
5751     }
5752   }
5753
5754   var strLen = string.length
5755
5756   if (length > strLen / 2) {
5757     length = strLen / 2
5758   }
5759   for (var i = 0; i < length; ++i) {
5760     var parsed = parseInt(string.substr(i * 2, 2), 16)
5761     if (numberIsNaN(parsed)) return i
5762     buf[offset + i] = parsed
5763   }
5764   return i
5765 }
5766
5767 function utf8Write (buf, string, offset, length) {
5768   return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
5769 }
5770
5771 function asciiWrite (buf, string, offset, length) {
5772   return blitBuffer(asciiToBytes(string), buf, offset, length)
5773 }
5774
5775 function latin1Write (buf, string, offset, length) {
5776   return asciiWrite(buf, string, offset, length)
5777 }
5778
5779 function base64Write (buf, string, offset, length) {
5780   return blitBuffer(base64ToBytes(string), buf, offset, length)
5781 }
5782
5783 function ucs2Write (buf, string, offset, length) {
5784   return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
5785 }
5786
5787 Buffer.prototype.write = function write (string, offset, length, encoding) {
5788   // Buffer#write(string)
5789   if (offset === undefined) {
5790     encoding = 'utf8'
5791     length = this.length
5792     offset = 0
5793   // Buffer#write(string, encoding)
5794   } else if (length === undefined && typeof offset === 'string') {
5795     encoding = offset
5796     length = this.length
5797     offset = 0
5798   // Buffer#write(string, offset[, length][, encoding])
5799   } else if (isFinite(offset)) {
5800     offset = offset >>> 0
5801     if (isFinite(length)) {
5802       length = length >>> 0
5803       if (encoding === undefined) encoding = 'utf8'
5804     } else {
5805       encoding = length
5806       length = undefined
5807     }
5808   } else {
5809     throw new Error(
5810       'Buffer.write(string, encoding, offset[, length]) is no longer supported'
5811     )
5812   }
5813
5814   var remaining = this.length - offset
5815   if (length === undefined || length > remaining) length = remaining
5816
5817   if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
5818     throw new RangeError('Attempt to write outside buffer bounds')
5819   }
5820
5821   if (!encoding) encoding = 'utf8'
5822
5823   var loweredCase = false
5824   for (;;) {
5825     switch (encoding) {
5826       case 'hex':
5827         return hexWrite(this, string, offset, length)
5828
5829       case 'utf8':
5830       case 'utf-8':
5831         return utf8Write(this, string, offset, length)
5832
5833       case 'ascii':
5834         return asciiWrite(this, string, offset, length)
5835
5836       case 'latin1':
5837       case 'binary':
5838         return latin1Write(this, string, offset, length)
5839
5840       case 'base64':
5841         // Warning: maxLength not taken into account in base64Write
5842         return base64Write(this, string, offset, length)
5843
5844       case 'ucs2':
5845       case 'ucs-2':
5846       case 'utf16le':
5847       case 'utf-16le':
5848         return ucs2Write(this, string, offset, length)
5849
5850       default:
5851         if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
5852         encoding = ('' + encoding).toLowerCase()
5853         loweredCase = true
5854     }
5855   }
5856 }
5857
5858 Buffer.prototype.toJSON = function toJSON () {
5859   return {
5860     type: 'Buffer',
5861     data: Array.prototype.slice.call(this._arr || this, 0)
5862   }
5863 }
5864
5865 function base64Slice (buf, start, end) {
5866   if (start === 0 && end === buf.length) {
5867     return base64.fromByteArray(buf)
5868   } else {
5869     return base64.fromByteArray(buf.slice(start, end))
5870   }
5871 }
5872
5873 function utf8Slice (buf, start, end) {
5874   end = Math.min(buf.length, end)
5875   var res = []
5876
5877   var i = start
5878   while (i < end) {
5879     var firstByte = buf[i]
5880     var codePoint = null
5881     var bytesPerSequence = (firstByte > 0xEF) ? 4
5882       : (firstByte > 0xDF) ? 3
5883         : (firstByte > 0xBF) ? 2
5884           : 1
5885
5886     if (i + bytesPerSequence <= end) {
5887       var secondByte, thirdByte, fourthByte, tempCodePoint
5888
5889       switch (bytesPerSequence) {
5890         case 1:
5891           if (firstByte < 0x80) {
5892             codePoint = firstByte
5893           }
5894           break
5895         case 2:
5896           secondByte = buf[i + 1]
5897           if ((secondByte & 0xC0) === 0x80) {
5898             tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
5899             if (tempCodePoint > 0x7F) {
5900               codePoint = tempCodePoint
5901             }
5902           }
5903           break
5904         case 3:
5905           secondByte = buf[i + 1]
5906           thirdByte = buf[i + 2]
5907           if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
5908             tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
5909             if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
5910               codePoint = tempCodePoint
5911             }
5912           }
5913           break
5914         case 4:
5915           secondByte = buf[i + 1]
5916           thirdByte = buf[i + 2]
5917           fourthByte = buf[i + 3]
5918           if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
5919             tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
5920             if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
5921               codePoint = tempCodePoint
5922             }
5923           }
5924       }
5925     }
5926
5927     if (codePoint === null) {
5928       // we did not generate a valid codePoint so insert a
5929       // replacement char (U+FFFD) and advance only 1 byte
5930       codePoint = 0xFFFD
5931       bytesPerSequence = 1
5932     } else if (codePoint > 0xFFFF) {
5933       // encode to utf16 (surrogate pair dance)
5934       codePoint -= 0x10000
5935       res.push(codePoint >>> 10 & 0x3FF | 0xD800)
5936       codePoint = 0xDC00 | codePoint & 0x3FF
5937     }
5938
5939     res.push(codePoint)
5940     i += bytesPerSequence
5941   }
5942
5943   return decodeCodePointsArray(res)
5944 }
5945
5946 // Based on http://stackoverflow.com/a/22747272/680742, the browser with
5947 // the lowest limit is Chrome, with 0x10000 args.
5948 // We go 1 magnitude less, for safety
5949 var MAX_ARGUMENTS_LENGTH = 0x1000
5950
5951 function decodeCodePointsArray (codePoints) {
5952   var len = codePoints.length
5953   if (len <= MAX_ARGUMENTS_LENGTH) {
5954     return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
5955   }
5956
5957   // Decode in chunks to avoid "call stack size exceeded".
5958   var res = ''
5959   var i = 0
5960   while (i < len) {
5961     res += String.fromCharCode.apply(
5962       String,
5963       codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
5964     )
5965   }
5966   return res
5967 }
5968
5969 function asciiSlice (buf, start, end) {
5970   var ret = ''
5971   end = Math.min(buf.length, end)
5972
5973   for (var i = start; i < end; ++i) {
5974     ret += String.fromCharCode(buf[i] & 0x7F)
5975   }
5976   return ret
5977 }
5978
5979 function latin1Slice (buf, start, end) {
5980   var ret = ''
5981   end = Math.min(buf.length, end)
5982
5983   for (var i = start; i < end; ++i) {
5984     ret += String.fromCharCode(buf[i])
5985   }
5986   return ret
5987 }
5988
5989 function hexSlice (buf, start, end) {
5990   var len = buf.length
5991
5992   if (!start || start < 0) start = 0
5993   if (!end || end < 0 || end > len) end = len
5994
5995   var out = ''
5996   for (var i = start; i < end; ++i) {
5997     out += toHex(buf[i])
5998   }
5999   return out
6000 }
6001
6002 function utf16leSlice (buf, start, end) {
6003   var bytes = buf.slice(start, end)
6004   var res = ''
6005   for (var i = 0; i < bytes.length; i += 2) {
6006     res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
6007   }
6008   return res
6009 }
6010
6011 Buffer.prototype.slice = function slice (start, end) {
6012   var len = this.length
6013   start = ~~start
6014   end = end === undefined ? len : ~~end
6015
6016   if (start < 0) {
6017     start += len
6018     if (start < 0) start = 0
6019   } else if (start > len) {
6020     start = len
6021   }
6022
6023   if (end < 0) {
6024     end += len
6025     if (end < 0) end = 0
6026   } else if (end > len) {
6027     end = len
6028   }
6029
6030   if (end < start) end = start
6031
6032   var newBuf = this.subarray(start, end)
6033   // Return an augmented `Uint8Array` instance
6034   newBuf.__proto__ = Buffer.prototype
6035   return newBuf
6036 }
6037
6038 /*
6039  * Need to make sure that buffer isn't trying to write out of bounds.
6040  */
6041 function checkOffset (offset, ext, length) {
6042   if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
6043   if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
6044 }
6045
6046 Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
6047   offset = offset >>> 0
6048   byteLength = byteLength >>> 0
6049   if (!noAssert) checkOffset(offset, byteLength, this.length)
6050
6051   var val = this[offset]
6052   var mul = 1
6053   var i = 0
6054   while (++i < byteLength && (mul *= 0x100)) {
6055     val += this[offset + i] * mul
6056   }
6057
6058   return val
6059 }
6060
6061 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
6062   offset = offset >>> 0
6063   byteLength = byteLength >>> 0
6064   if (!noAssert) {
6065     checkOffset(offset, byteLength, this.length)
6066   }
6067
6068   var val = this[offset + --byteLength]
6069   var mul = 1
6070   while (byteLength > 0 && (mul *= 0x100)) {
6071     val += this[offset + --byteLength] * mul
6072   }
6073
6074   return val
6075 }
6076
6077 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
6078   offset = offset >>> 0
6079   if (!noAssert) checkOffset(offset, 1, this.length)
6080   return this[offset]
6081 }
6082
6083 Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
6084   offset = offset >>> 0
6085   if (!noAssert) checkOffset(offset, 2, this.length)
6086   return this[offset] | (this[offset + 1] << 8)
6087 }
6088
6089 Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
6090   offset = offset >>> 0
6091   if (!noAssert) checkOffset(offset, 2, this.length)
6092   return (this[offset] << 8) | this[offset + 1]
6093 }
6094
6095 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
6096   offset = offset >>> 0
6097   if (!noAssert) checkOffset(offset, 4, this.length)
6098
6099   return ((this[offset]) |
6100       (this[offset + 1] << 8) |
6101       (this[offset + 2] << 16)) +
6102       (this[offset + 3] * 0x1000000)
6103 }
6104
6105 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
6106   offset = offset >>> 0
6107   if (!noAssert) checkOffset(offset, 4, this.length)
6108
6109   return (this[offset] * 0x1000000) +
6110     ((this[offset + 1] << 16) |
6111     (this[offset + 2] << 8) |
6112     this[offset + 3])
6113 }
6114
6115 Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
6116   offset = offset >>> 0
6117   byteLength = byteLength >>> 0
6118   if (!noAssert) checkOffset(offset, byteLength, this.length)
6119
6120   var val = this[offset]
6121   var mul = 1
6122   var i = 0
6123   while (++i < byteLength && (mul *= 0x100)) {
6124     val += this[offset + i] * mul
6125   }
6126   mul *= 0x80
6127
6128   if (val >= mul) val -= Math.pow(2, 8 * byteLength)
6129
6130   return val
6131 }
6132
6133 Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
6134   offset = offset >>> 0
6135   byteLength = byteLength >>> 0
6136   if (!noAssert) checkOffset(offset, byteLength, this.length)
6137
6138   var i = byteLength
6139   var mul = 1
6140   var val = this[offset + --i]
6141   while (i > 0 && (mul *= 0x100)) {
6142     val += this[offset + --i] * mul
6143   }
6144   mul *= 0x80
6145
6146   if (val >= mul) val -= Math.pow(2, 8 * byteLength)
6147
6148   return val
6149 }
6150
6151 Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
6152   offset = offset >>> 0
6153   if (!noAssert) checkOffset(offset, 1, this.length)
6154   if (!(this[offset] & 0x80)) return (this[offset])
6155   return ((0xff - this[offset] + 1) * -1)
6156 }
6157
6158 Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
6159   offset = offset >>> 0
6160   if (!noAssert) checkOffset(offset, 2, this.length)
6161   var val = this[offset] | (this[offset + 1] << 8)
6162   return (val & 0x8000) ? val | 0xFFFF0000 : val
6163 }
6164
6165 Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
6166   offset = offset >>> 0
6167   if (!noAssert) checkOffset(offset, 2, this.length)
6168   var val = this[offset + 1] | (this[offset] << 8)
6169   return (val & 0x8000) ? val | 0xFFFF0000 : val
6170 }
6171
6172 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
6173   offset = offset >>> 0
6174   if (!noAssert) checkOffset(offset, 4, this.length)
6175
6176   return (this[offset]) |
6177     (this[offset + 1] << 8) |
6178     (this[offset + 2] << 16) |
6179     (this[offset + 3] << 24)
6180 }
6181
6182 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
6183   offset = offset >>> 0
6184   if (!noAssert) checkOffset(offset, 4, this.length)
6185
6186   return (this[offset] << 24) |
6187     (this[offset + 1] << 16) |
6188     (this[offset + 2] << 8) |
6189     (this[offset + 3])
6190 }
6191
6192 Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
6193   offset = offset >>> 0
6194   if (!noAssert) checkOffset(offset, 4, this.length)
6195   return ieee754.read(this, offset, true, 23, 4)
6196 }
6197
6198 Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
6199   offset = offset >>> 0
6200   if (!noAssert) checkOffset(offset, 4, this.length)
6201   return ieee754.read(this, offset, false, 23, 4)
6202 }
6203
6204 Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
6205   offset = offset >>> 0
6206   if (!noAssert) checkOffset(offset, 8, this.length)
6207   return ieee754.read(this, offset, true, 52, 8)
6208 }
6209
6210 Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
6211   offset = offset >>> 0
6212   if (!noAssert) checkOffset(offset, 8, this.length)
6213   return ieee754.read(this, offset, false, 52, 8)
6214 }
6215
6216 function checkInt (buf, value, offset, ext, max, min) {
6217   if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
6218   if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
6219   if (offset + ext > buf.length) throw new RangeError('Index out of range')
6220 }
6221
6222 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
6223   value = +value
6224   offset = offset >>> 0
6225   byteLength = byteLength >>> 0
6226   if (!noAssert) {
6227     var maxBytes = Math.pow(2, 8 * byteLength) - 1
6228     checkInt(this, value, offset, byteLength, maxBytes, 0)
6229   }
6230
6231   var mul = 1
6232   var i = 0
6233   this[offset] = value & 0xFF
6234   while (++i < byteLength && (mul *= 0x100)) {
6235     this[offset + i] = (value / mul) & 0xFF
6236   }
6237
6238   return offset + byteLength
6239 }
6240
6241 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
6242   value = +value
6243   offset = offset >>> 0
6244   byteLength = byteLength >>> 0
6245   if (!noAssert) {
6246     var maxBytes = Math.pow(2, 8 * byteLength) - 1
6247     checkInt(this, value, offset, byteLength, maxBytes, 0)
6248   }
6249
6250   var i = byteLength - 1
6251   var mul = 1
6252   this[offset + i] = value & 0xFF
6253   while (--i >= 0 && (mul *= 0x100)) {
6254     this[offset + i] = (value / mul) & 0xFF
6255   }
6256
6257   return offset + byteLength
6258 }
6259
6260 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
6261   value = +value
6262   offset = offset >>> 0
6263   if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
6264   this[offset] = (value & 0xff)
6265   return offset + 1
6266 }
6267
6268 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
6269   value = +value
6270   offset = offset >>> 0
6271   if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
6272   this[offset] = (value & 0xff)
6273   this[offset + 1] = (value >>> 8)
6274   return offset + 2
6275 }
6276
6277 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
6278   value = +value
6279   offset = offset >>> 0
6280   if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
6281   this[offset] = (value >>> 8)
6282   this[offset + 1] = (value & 0xff)
6283   return offset + 2
6284 }
6285
6286 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
6287   value = +value
6288   offset = offset >>> 0
6289   if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
6290   this[offset + 3] = (value >>> 24)
6291   this[offset + 2] = (value >>> 16)
6292   this[offset + 1] = (value >>> 8)
6293   this[offset] = (value & 0xff)
6294   return offset + 4
6295 }
6296
6297 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
6298   value = +value
6299   offset = offset >>> 0
6300   if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
6301   this[offset] = (value >>> 24)
6302   this[offset + 1] = (value >>> 16)
6303   this[offset + 2] = (value >>> 8)
6304   this[offset + 3] = (value & 0xff)
6305   return offset + 4
6306 }
6307
6308 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
6309   value = +value
6310   offset = offset >>> 0
6311   if (!noAssert) {
6312     var limit = Math.pow(2, (8 * byteLength) - 1)
6313
6314     checkInt(this, value, offset, byteLength, limit - 1, -limit)
6315   }
6316
6317   var i = 0
6318   var mul = 1
6319   var sub = 0
6320   this[offset] = value & 0xFF
6321   while (++i < byteLength && (mul *= 0x100)) {
6322     if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
6323       sub = 1
6324     }
6325     this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
6326   }
6327
6328   return offset + byteLength
6329 }
6330
6331 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
6332   value = +value
6333   offset = offset >>> 0
6334   if (!noAssert) {
6335     var limit = Math.pow(2, (8 * byteLength) - 1)
6336
6337     checkInt(this, value, offset, byteLength, limit - 1, -limit)
6338   }
6339
6340   var i = byteLength - 1
6341   var mul = 1
6342   var sub = 0
6343   this[offset + i] = value & 0xFF
6344   while (--i >= 0 && (mul *= 0x100)) {
6345     if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
6346       sub = 1
6347     }
6348     this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
6349   }
6350
6351   return offset + byteLength
6352 }
6353
6354 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
6355   value = +value
6356   offset = offset >>> 0
6357   if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
6358   if (value < 0) value = 0xff + value + 1
6359   this[offset] = (value & 0xff)
6360   return offset + 1
6361 }
6362
6363 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
6364   value = +value
6365   offset = offset >>> 0
6366   if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
6367   this[offset] = (value & 0xff)
6368   this[offset + 1] = (value >>> 8)
6369   return offset + 2
6370 }
6371
6372 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
6373   value = +value
6374   offset = offset >>> 0
6375   if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
6376   this[offset] = (value >>> 8)
6377   this[offset + 1] = (value & 0xff)
6378   return offset + 2
6379 }
6380
6381 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
6382   value = +value
6383   offset = offset >>> 0
6384   if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
6385   this[offset] = (value & 0xff)
6386   this[offset + 1] = (value >>> 8)
6387   this[offset + 2] = (value >>> 16)
6388   this[offset + 3] = (value >>> 24)
6389   return offset + 4
6390 }
6391
6392 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
6393   value = +value
6394   offset = offset >>> 0
6395   if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
6396   if (value < 0) value = 0xffffffff + value + 1
6397   this[offset] = (value >>> 24)
6398   this[offset + 1] = (value >>> 16)
6399   this[offset + 2] = (value >>> 8)
6400   this[offset + 3] = (value & 0xff)
6401   return offset + 4
6402 }
6403
6404 function checkIEEE754 (buf, value, offset, ext, max, min) {
6405   if (offset + ext > buf.length) throw new RangeError('Index out of range')
6406   if (offset < 0) throw new RangeError('Index out of range')
6407 }
6408
6409 function writeFloat (buf, value, offset, littleEndian, noAssert) {
6410   value = +value
6411   offset = offset >>> 0
6412   if (!noAssert) {
6413     checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
6414   }
6415   ieee754.write(buf, value, offset, littleEndian, 23, 4)
6416   return offset + 4
6417 }
6418
6419 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
6420   return writeFloat(this, value, offset, true, noAssert)
6421 }
6422
6423 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
6424   return writeFloat(this, value, offset, false, noAssert)
6425 }
6426
6427 function writeDouble (buf, value, offset, littleEndian, noAssert) {
6428   value = +value
6429   offset = offset >>> 0
6430   if (!noAssert) {
6431     checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
6432   }
6433   ieee754.write(buf, value, offset, littleEndian, 52, 8)
6434   return offset + 8
6435 }
6436
6437 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
6438   return writeDouble(this, value, offset, true, noAssert)
6439 }
6440
6441 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
6442   return writeDouble(this, value, offset, false, noAssert)
6443 }
6444
6445 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
6446 Buffer.prototype.copy = function copy (target, targetStart, start, end) {
6447   if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
6448   if (!start) start = 0
6449   if (!end && end !== 0) end = this.length
6450   if (targetStart >= target.length) targetStart = target.length
6451   if (!targetStart) targetStart = 0
6452   if (end > 0 && end < start) end = start
6453
6454   // Copy 0 bytes; we're done
6455   if (end === start) return 0
6456   if (target.length === 0 || this.length === 0) return 0
6457
6458   // Fatal error conditions
6459   if (targetStart < 0) {
6460     throw new RangeError('targetStart out of bounds')
6461   }
6462   if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
6463   if (end < 0) throw new RangeError('sourceEnd out of bounds')
6464
6465   // Are we oob?
6466   if (end > this.length) end = this.length
6467   if (target.length - targetStart < end - start) {
6468     end = target.length - targetStart + start
6469   }
6470
6471   var len = end - start
6472
6473   if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
6474     // Use built-in when available, missing from IE11
6475     this.copyWithin(targetStart, start, end)
6476   } else if (this === target && start < targetStart && targetStart < end) {
6477     // descending copy from end
6478     for (var i = len - 1; i >= 0; --i) {
6479       target[i + targetStart] = this[i + start]
6480     }
6481   } else {
6482     Uint8Array.prototype.set.call(
6483       target,
6484       this.subarray(start, end),
6485       targetStart
6486     )
6487   }
6488
6489   return len
6490 }
6491
6492 // Usage:
6493 //    buffer.fill(number[, offset[, end]])
6494 //    buffer.fill(buffer[, offset[, end]])
6495 //    buffer.fill(string[, offset[, end]][, encoding])
6496 Buffer.prototype.fill = function fill (val, start, end, encoding) {
6497   // Handle string cases:
6498   if (typeof val === 'string') {
6499     if (typeof start === 'string') {
6500       encoding = start
6501       start = 0
6502       end = this.length
6503     } else if (typeof end === 'string') {
6504       encoding = end
6505       end = this.length
6506     }
6507     if (encoding !== undefined && typeof encoding !== 'string') {
6508       throw new TypeError('encoding must be a string')
6509     }
6510     if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
6511       throw new TypeError('Unknown encoding: ' + encoding)
6512     }
6513     if (val.length === 1) {
6514       var code = val.charCodeAt(0)
6515       if ((encoding === 'utf8' && code < 128) ||
6516           encoding === 'latin1') {
6517         // Fast path: If `val` fits into a single byte, use that numeric value.
6518         val = code
6519       }
6520     }
6521   } else if (typeof val === 'number') {
6522     val = val & 255
6523   }
6524
6525   // Invalid ranges are not set to a default, so can range check early.
6526   if (start < 0 || this.length < start || this.length < end) {
6527     throw new RangeError('Out of range index')
6528   }
6529
6530   if (end <= start) {
6531     return this
6532   }
6533
6534   start = start >>> 0
6535   end = end === undefined ? this.length : end >>> 0
6536
6537   if (!val) val = 0
6538
6539   var i
6540   if (typeof val === 'number') {
6541     for (i = start; i < end; ++i) {
6542       this[i] = val
6543     }
6544   } else {
6545     var bytes = Buffer.isBuffer(val)
6546       ? val
6547       : Buffer.from(val, encoding)
6548     var len = bytes.length
6549     if (len === 0) {
6550       throw new TypeError('The value "' + val +
6551         '" is invalid for argument "value"')
6552     }
6553     for (i = 0; i < end - start; ++i) {
6554       this[i + start] = bytes[i % len]
6555     }
6556   }
6557
6558   return this
6559 }
6560
6561 // HELPER FUNCTIONS
6562 // ================
6563
6564 var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
6565
6566 function base64clean (str) {
6567   // Node takes equal signs as end of the Base64 encoding
6568   str = str.split('=')[0]
6569   // Node strips out invalid characters like \n and \t from the string, base64-js does not
6570   str = str.trim().replace(INVALID_BASE64_RE, '')
6571   // Node converts strings with length < 2 to ''
6572   if (str.length < 2) return ''
6573   // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
6574   while (str.length % 4 !== 0) {
6575     str = str + '='
6576   }
6577   return str
6578 }
6579
6580 function toHex (n) {
6581   if (n < 16) return '0' + n.toString(16)
6582   return n.toString(16)
6583 }
6584
6585 function utf8ToBytes (string, units) {
6586   units = units || Infinity
6587   var codePoint
6588   var length = string.length
6589   var leadSurrogate = null
6590   var bytes = []
6591
6592   for (var i = 0; i < length; ++i) {
6593     codePoint = string.charCodeAt(i)
6594
6595     // is surrogate component
6596     if (codePoint > 0xD7FF && codePoint < 0xE000) {
6597       // last char was a lead
6598       if (!leadSurrogate) {
6599         // no lead yet
6600         if (codePoint > 0xDBFF) {
6601           // unexpected trail
6602           if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
6603           continue
6604         } else if (i + 1 === length) {
6605           // unpaired lead
6606           if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
6607           continue
6608         }
6609
6610         // valid lead
6611         leadSurrogate = codePoint
6612
6613         continue
6614       }
6615
6616       // 2 leads in a row
6617       if (codePoint < 0xDC00) {
6618         if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
6619         leadSurrogate = codePoint
6620         continue
6621       }
6622
6623       // valid surrogate pair
6624       codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
6625     } else if (leadSurrogate) {
6626       // valid bmp char, but last char was a lead
6627       if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
6628     }
6629
6630     leadSurrogate = null
6631
6632     // encode utf8
6633     if (codePoint < 0x80) {
6634       if ((units -= 1) < 0) break
6635       bytes.push(codePoint)
6636     } else if (codePoint < 0x800) {
6637       if ((units -= 2) < 0) break
6638       bytes.push(
6639         codePoint >> 0x6 | 0xC0,
6640         codePoint & 0x3F | 0x80
6641       )
6642     } else if (codePoint < 0x10000) {
6643       if ((units -= 3) < 0) break
6644       bytes.push(
6645         codePoint >> 0xC | 0xE0,
6646         codePoint >> 0x6 & 0x3F | 0x80,
6647         codePoint & 0x3F | 0x80
6648       )
6649     } else if (codePoint < 0x110000) {
6650       if ((units -= 4) < 0) break
6651       bytes.push(
6652         codePoint >> 0x12 | 0xF0,
6653         codePoint >> 0xC & 0x3F | 0x80,
6654         codePoint >> 0x6 & 0x3F | 0x80,
6655         codePoint & 0x3F | 0x80
6656       )
6657     } else {
6658       throw new Error('Invalid code point')
6659     }
6660   }
6661
6662   return bytes
6663 }
6664
6665 function asciiToBytes (str) {
6666   var byteArray = []
6667   for (var i = 0; i < str.length; ++i) {
6668     // Node's code seems to be doing this and not & 0x7F..
6669     byteArray.push(str.charCodeAt(i) & 0xFF)
6670   }
6671   return byteArray
6672 }
6673
6674 function utf16leToBytes (str, units) {
6675   var c, hi, lo
6676   var byteArray = []
6677   for (var i = 0; i < str.length; ++i) {
6678     if ((units -= 2) < 0) break
6679
6680     c = str.charCodeAt(i)
6681     hi = c >> 8
6682     lo = c % 256
6683     byteArray.push(lo)
6684     byteArray.push(hi)
6685   }
6686
6687   return byteArray
6688 }
6689
6690 function base64ToBytes (str) {
6691   return base64.toByteArray(base64clean(str))
6692 }
6693
6694 function blitBuffer (src, dst, offset, length) {
6695   for (var i = 0; i < length; ++i) {
6696     if ((i + offset >= dst.length) || (i >= src.length)) break
6697     dst[i + offset] = src[i]
6698   }
6699   return i
6700 }
6701
6702 // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
6703 // the `instanceof` check but they should be treated as of that type.
6704 // See: https://github.com/feross/buffer/issues/166
6705 function isInstance (obj, type) {
6706   return obj instanceof type ||
6707     (obj != null && obj.constructor != null && obj.constructor.name != null &&
6708       obj.constructor.name === type.name)
6709 }
6710 function numberIsNaN (obj) {
6711   // For IE11 support
6712   return obj !== obj // eslint-disable-line no-self-compare
6713 }
6714
6715 }).call(this,require("buffer").Buffer)
6716 },{"base64-js":27,"buffer":32,"ieee754":35}],33:[function(require,module,exports){
6717 (function (Buffer){
6718 // Copyright Joyent, Inc. and other Node contributors.
6719 //
6720 // Permission is hereby granted, free of charge, to any person obtaining a
6721 // copy of this software and associated documentation files (the
6722 // "Software"), to deal in the Software without restriction, including
6723 // without limitation the rights to use, copy, modify, merge, publish,
6724 // distribute, sublicense, and/or sell copies of the Software, and to permit
6725 // persons to whom the Software is furnished to do so, subject to the
6726 // following conditions:
6727 //
6728 // The above copyright notice and this permission notice shall be included
6729 // in all copies or substantial portions of the Software.
6730 //
6731 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6732 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6733 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6734 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6735 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6736 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6737 // USE OR OTHER DEALINGS IN THE SOFTWARE.
6738
6739 // NOTE: These type checking functions intentionally don't use `instanceof`
6740 // because it is fragile and can be easily faked with `Object.create()`.
6741
6742 function isArray(arg) {
6743   if (Array.isArray) {
6744     return Array.isArray(arg);
6745   }
6746   return objectToString(arg) === '[object Array]';
6747 }
6748 exports.isArray = isArray;
6749
6750 function isBoolean(arg) {
6751   return typeof arg === 'boolean';
6752 }
6753 exports.isBoolean = isBoolean;
6754
6755 function isNull(arg) {
6756   return arg === null;
6757 }
6758 exports.isNull = isNull;
6759
6760 function isNullOrUndefined(arg) {
6761   return arg == null;
6762 }
6763 exports.isNullOrUndefined = isNullOrUndefined;
6764
6765 function isNumber(arg) {
6766   return typeof arg === 'number';
6767 }
6768 exports.isNumber = isNumber;
6769
6770 function isString(arg) {
6771   return typeof arg === 'string';
6772 }
6773 exports.isString = isString;
6774
6775 function isSymbol(arg) {
6776   return typeof arg === 'symbol';
6777 }
6778 exports.isSymbol = isSymbol;
6779
6780 function isUndefined(arg) {
6781   return arg === void 0;
6782 }
6783 exports.isUndefined = isUndefined;
6784
6785 function isRegExp(re) {
6786   return objectToString(re) === '[object RegExp]';
6787 }
6788 exports.isRegExp = isRegExp;
6789
6790 function isObject(arg) {
6791   return typeof arg === 'object' && arg !== null;
6792 }
6793 exports.isObject = isObject;
6794
6795 function isDate(d) {
6796   return objectToString(d) === '[object Date]';
6797 }
6798 exports.isDate = isDate;
6799
6800 function isError(e) {
6801   return (objectToString(e) === '[object Error]' || e instanceof Error);
6802 }
6803 exports.isError = isError;
6804
6805 function isFunction(arg) {
6806   return typeof arg === 'function';
6807 }
6808 exports.isFunction = isFunction;
6809
6810 function isPrimitive(arg) {
6811   return arg === null ||
6812          typeof arg === 'boolean' ||
6813          typeof arg === 'number' ||
6814          typeof arg === 'string' ||
6815          typeof arg === 'symbol' ||  // ES6 symbol
6816          typeof arg === 'undefined';
6817 }
6818 exports.isPrimitive = isPrimitive;
6819
6820 exports.isBuffer = Buffer.isBuffer;
6821
6822 function objectToString(o) {
6823   return Object.prototype.toString.call(o);
6824 }
6825
6826 }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
6827 },{"../../is-buffer/index.js":37}],34:[function(require,module,exports){
6828 // Copyright Joyent, Inc. and other Node contributors.
6829 //
6830 // Permission is hereby granted, free of charge, to any person obtaining a
6831 // copy of this software and associated documentation files (the
6832 // "Software"), to deal in the Software without restriction, including
6833 // without limitation the rights to use, copy, modify, merge, publish,
6834 // distribute, sublicense, and/or sell copies of the Software, and to permit
6835 // persons to whom the Software is furnished to do so, subject to the
6836 // following conditions:
6837 //
6838 // The above copyright notice and this permission notice shall be included
6839 // in all copies or substantial portions of the Software.
6840 //
6841 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6842 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6843 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6844 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6845 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6846 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6847 // USE OR OTHER DEALINGS IN THE SOFTWARE.
6848
6849 function EventEmitter() {
6850   this._events = this._events || {};
6851   this._maxListeners = this._maxListeners || undefined;
6852 }
6853 module.exports = EventEmitter;
6854
6855 // Backwards-compat with node 0.10.x
6856 EventEmitter.EventEmitter = EventEmitter;
6857
6858 EventEmitter.prototype._events = undefined;
6859 EventEmitter.prototype._maxListeners = undefined;
6860
6861 // By default EventEmitters will print a warning if more than 10 listeners are
6862 // added to it. This is a useful default which helps finding memory leaks.
6863 EventEmitter.defaultMaxListeners = 10;
6864
6865 // Obviously not all Emitters should be limited to 10. This function allows
6866 // that to be increased. Set to zero for unlimited.
6867 EventEmitter.prototype.setMaxListeners = function(n) {
6868   if (!isNumber(n) || n < 0 || isNaN(n))
6869     throw TypeError('n must be a positive number');
6870   this._maxListeners = n;
6871   return this;
6872 };
6873
6874 EventEmitter.prototype.emit = function(type) {
6875   var er, handler, len, args, i, listeners;
6876
6877   if (!this._events)
6878     this._events = {};
6879
6880   // If there is no 'error' event listener then throw.
6881   if (type === 'error') {
6882     if (!this._events.error ||
6883         (isObject(this._events.error) && !this._events.error.length)) {
6884       er = arguments[1];
6885       if (er instanceof Error) {
6886         throw er; // Unhandled 'error' event
6887       } else {
6888         // At least give some kind of context to the user
6889         var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
6890         err.context = er;
6891         throw err;
6892       }
6893     }
6894   }
6895
6896   handler = this._events[type];
6897
6898   if (isUndefined(handler))
6899     return false;
6900
6901   if (isFunction(handler)) {
6902     switch (arguments.length) {
6903       // fast cases
6904       case 1:
6905         handler.call(this);
6906         break;
6907       case 2:
6908         handler.call(this, arguments[1]);
6909         break;
6910       case 3:
6911         handler.call(this, arguments[1], arguments[2]);
6912         break;
6913       // slower
6914       default:
6915         args = Array.prototype.slice.call(arguments, 1);
6916         handler.apply(this, args);
6917     }
6918   } else if (isObject(handler)) {
6919     args = Array.prototype.slice.call(arguments, 1);
6920     listeners = handler.slice();
6921     len = listeners.length;
6922     for (i = 0; i < len; i++)
6923       listeners[i].apply(this, args);
6924   }
6925
6926   return true;
6927 };
6928
6929 EventEmitter.prototype.addListener = function(type, listener) {
6930   var m;
6931
6932   if (!isFunction(listener))
6933     throw TypeError('listener must be a function');
6934
6935   if (!this._events)
6936     this._events = {};
6937
6938   // To avoid recursion in the case that type === "newListener"! Before
6939   // adding it to the listeners, first emit "newListener".
6940   if (this._events.newListener)
6941     this.emit('newListener', type,
6942               isFunction(listener.listener) ?
6943               listener.listener : listener);
6944
6945   if (!this._events[type])
6946     // Optimize the case of one listener. Don't need the extra array object.
6947     this._events[type] = listener;
6948   else if (isObject(this._events[type]))
6949     // If we've already got an array, just append.
6950     this._events[type].push(listener);
6951   else
6952     // Adding the second element, need to change to array.
6953     this._events[type] = [this._events[type], listener];
6954
6955   // Check for listener leak
6956   if (isObject(this._events[type]) && !this._events[type].warned) {
6957     if (!isUndefined(this._maxListeners)) {
6958       m = this._maxListeners;
6959     } else {
6960       m = EventEmitter.defaultMaxListeners;
6961     }
6962
6963     if (m && m > 0 && this._events[type].length > m) {
6964       this._events[type].warned = true;
6965       console.error('(node) warning: possible EventEmitter memory ' +
6966                     'leak detected. %d listeners added. ' +
6967                     'Use emitter.setMaxListeners() to increase limit.',
6968                     this._events[type].length);
6969       if (typeof console.trace === 'function') {
6970         // not supported in IE 10
6971         console.trace();
6972       }
6973     }
6974   }
6975
6976   return this;
6977 };
6978
6979 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
6980
6981 EventEmitter.prototype.once = function(type, listener) {
6982   if (!isFunction(listener))
6983     throw TypeError('listener must be a function');
6984
6985   var fired = false;
6986
6987   function g() {
6988     this.removeListener(type, g);
6989
6990     if (!fired) {
6991       fired = true;
6992       listener.apply(this, arguments);
6993     }
6994   }
6995
6996   g.listener = listener;
6997   this.on(type, g);
6998
6999   return this;
7000 };
7001
7002 // emits a 'removeListener' event iff the listener was removed
7003 EventEmitter.prototype.removeListener = function(type, listener) {
7004   var list, position, length, i;
7005
7006   if (!isFunction(listener))
7007     throw TypeError('listener must be a function');
7008
7009   if (!this._events || !this._events[type])
7010     return this;
7011
7012   list = this._events[type];
7013   length = list.length;
7014   position = -1;
7015
7016   if (list === listener ||
7017       (isFunction(list.listener) && list.listener === listener)) {
7018     delete this._events[type];
7019     if (this._events.removeListener)
7020       this.emit('removeListener', type, listener);
7021
7022   } else if (isObject(list)) {
7023     for (i = length; i-- > 0;) {
7024       if (list[i] === listener ||
7025           (list[i].listener && list[i].listener === listener)) {
7026         position = i;
7027         break;
7028       }
7029     }
7030
7031     if (position < 0)
7032       return this;
7033
7034     if (list.length === 1) {
7035       list.length = 0;
7036       delete this._events[type];
7037     } else {
7038       list.splice(position, 1);
7039     }
7040
7041     if (this._events.removeListener)
7042       this.emit('removeListener', type, listener);
7043   }
7044
7045   return this;
7046 };
7047
7048 EventEmitter.prototype.removeAllListeners = function(type) {
7049   var key, listeners;
7050
7051   if (!this._events)
7052     return this;
7053
7054   // not listening for removeListener, no need to emit
7055   if (!this._events.removeListener) {
7056     if (arguments.length === 0)
7057       this._events = {};
7058     else if (this._events[type])
7059       delete this._events[type];
7060     return this;
7061   }
7062
7063   // emit removeListener for all listeners on all events
7064   if (arguments.length === 0) {
7065     for (key in this._events) {
7066       if (key === 'removeListener') continue;
7067       this.removeAllListeners(key);
7068     }
7069     this.removeAllListeners('removeListener');
7070     this._events = {};
7071     return this;
7072   }
7073
7074   listeners = this._events[type];
7075
7076   if (isFunction(listeners)) {
7077     this.removeListener(type, listeners);
7078   } else if (listeners) {
7079     // LIFO order
7080     while (listeners.length)
7081       this.removeListener(type, listeners[listeners.length - 1]);
7082   }
7083   delete this._events[type];
7084
7085   return this;
7086 };
7087
7088 EventEmitter.prototype.listeners = function(type) {
7089   var ret;
7090   if (!this._events || !this._events[type])
7091     ret = [];
7092   else if (isFunction(this._events[type]))
7093     ret = [this._events[type]];
7094   else
7095     ret = this._events[type].slice();
7096   return ret;
7097 };
7098
7099 EventEmitter.prototype.listenerCount = function(type) {
7100   if (this._events) {
7101     var evlistener = this._events[type];
7102
7103     if (isFunction(evlistener))
7104       return 1;
7105     else if (evlistener)
7106       return evlistener.length;
7107   }
7108   return 0;
7109 };
7110
7111 EventEmitter.listenerCount = function(emitter, type) {
7112   return emitter.listenerCount(type);
7113 };
7114
7115 function isFunction(arg) {
7116   return typeof arg === 'function';
7117 }
7118
7119 function isNumber(arg) {
7120   return typeof arg === 'number';
7121 }
7122
7123 function isObject(arg) {
7124   return typeof arg === 'object' && arg !== null;
7125 }
7126
7127 function isUndefined(arg) {
7128   return arg === void 0;
7129 }
7130
7131 },{}],35:[function(require,module,exports){
7132 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
7133   var e, m
7134   var eLen = (nBytes * 8) - mLen - 1
7135   var eMax = (1 << eLen) - 1
7136   var eBias = eMax >> 1
7137   var nBits = -7
7138   var i = isLE ? (nBytes - 1) : 0
7139   var d = isLE ? -1 : 1
7140   var s = buffer[offset + i]
7141
7142   i += d
7143
7144   e = s & ((1 << (-nBits)) - 1)
7145   s >>= (-nBits)
7146   nBits += eLen
7147   for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
7148
7149   m = e & ((1 << (-nBits)) - 1)
7150   e >>= (-nBits)
7151   nBits += mLen
7152   for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
7153
7154   if (e === 0) {
7155     e = 1 - eBias
7156   } else if (e === eMax) {
7157     return m ? NaN : ((s ? -1 : 1) * Infinity)
7158   } else {
7159     m = m + Math.pow(2, mLen)
7160     e = e - eBias
7161   }
7162   return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
7163 }
7164
7165 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
7166   var e, m, c
7167   var eLen = (nBytes * 8) - mLen - 1
7168   var eMax = (1 << eLen) - 1
7169   var eBias = eMax >> 1
7170   var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
7171   var i = isLE ? 0 : (nBytes - 1)
7172   var d = isLE ? 1 : -1
7173   var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
7174
7175   value = Math.abs(value)
7176
7177   if (isNaN(value) || value === Infinity) {
7178     m = isNaN(value) ? 1 : 0
7179     e = eMax
7180   } else {
7181     e = Math.floor(Math.log(value) / Math.LN2)
7182     if (value * (c = Math.pow(2, -e)) < 1) {
7183       e--
7184       c *= 2
7185     }
7186     if (e + eBias >= 1) {
7187       value += rt / c
7188     } else {
7189       value += rt * Math.pow(2, 1 - eBias)
7190     }
7191     if (value * c >= 2) {
7192       e++
7193       c /= 2
7194     }
7195
7196     if (e + eBias >= eMax) {
7197       m = 0
7198       e = eMax
7199     } else if (e + eBias >= 1) {
7200       m = ((value * c) - 1) * Math.pow(2, mLen)
7201       e = e + eBias
7202     } else {
7203       m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
7204       e = 0
7205     }
7206   }
7207
7208   for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
7209
7210   e = (e << mLen) | m
7211   eLen += mLen
7212   for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
7213
7214   buffer[offset + i - d] |= s * 128
7215 }
7216
7217 },{}],36:[function(require,module,exports){
7218 arguments[4][24][0].apply(exports,arguments)
7219 },{"dup":24}],37:[function(require,module,exports){
7220 /*!
7221  * Determine if an object is a Buffer
7222  *
7223  * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
7224  * @license  MIT
7225  */
7226
7227 // The _isBuffer check is for Safari 5-7 support, because it's missing
7228 // Object.prototype.constructor. Remove this eventually
7229 module.exports = function (obj) {
7230   return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
7231 }
7232
7233 function isBuffer (obj) {
7234   return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
7235 }
7236
7237 // For Node v0.10 support. Remove this eventually.
7238 function isSlowBuffer (obj) {
7239   return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
7240 }
7241
7242 },{}],38:[function(require,module,exports){
7243 var toString = {}.toString;
7244
7245 module.exports = Array.isArray || function (arr) {
7246   return toString.call(arr) == '[object Array]';
7247 };
7248
7249 },{}],39:[function(require,module,exports){
7250 'use strict';
7251
7252
7253 var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
7254                 (typeof Uint16Array !== 'undefined') &&
7255                 (typeof Int32Array !== 'undefined');
7256
7257 function _has(obj, key) {
7258   return Object.prototype.hasOwnProperty.call(obj, key);
7259 }
7260
7261 exports.assign = function (obj /*from1, from2, from3, ...*/) {
7262   var sources = Array.prototype.slice.call(arguments, 1);
7263   while (sources.length) {
7264     var source = sources.shift();
7265     if (!source) { continue; }
7266
7267     if (typeof source !== 'object') {
7268       throw new TypeError(source + 'must be non-object');
7269     }
7270
7271     for (var p in source) {
7272       if (_has(source, p)) {
7273         obj[p] = source[p];
7274       }
7275     }
7276   }
7277
7278   return obj;
7279 };
7280
7281
7282 // reduce buffer size, avoiding mem copy
7283 exports.shrinkBuf = function (buf, size) {
7284   if (buf.length === size) { return buf; }
7285   if (buf.subarray) { return buf.subarray(0, size); }
7286   buf.length = size;
7287   return buf;
7288 };
7289
7290
7291 var fnTyped = {
7292   arraySet: function (dest, src, src_offs, len, dest_offs) {
7293     if (src.subarray && dest.subarray) {
7294       dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
7295       return;
7296     }
7297     // Fallback to ordinary array
7298     for (var i = 0; i < len; i++) {
7299       dest[dest_offs + i] = src[src_offs + i];
7300     }
7301   },
7302   // Join array of chunks to single array.
7303   flattenChunks: function (chunks) {
7304     var i, l, len, pos, chunk, result;
7305
7306     // calculate data length
7307     len = 0;
7308     for (i = 0, l = chunks.length; i < l; i++) {
7309       len += chunks[i].length;
7310     }
7311
7312     // join chunks
7313     result = new Uint8Array(len);
7314     pos = 0;
7315     for (i = 0, l = chunks.length; i < l; i++) {
7316       chunk = chunks[i];
7317       result.set(chunk, pos);
7318       pos += chunk.length;
7319     }
7320
7321     return result;
7322   }
7323 };
7324
7325 var fnUntyped = {
7326   arraySet: function (dest, src, src_offs, len, dest_offs) {
7327     for (var i = 0; i < len; i++) {
7328       dest[dest_offs + i] = src[src_offs + i];
7329     }
7330   },
7331   // Join array of chunks to single array.
7332   flattenChunks: function (chunks) {
7333     return [].concat.apply([], chunks);
7334   }
7335 };
7336
7337
7338 // Enable/Disable typed arrays use, for testing
7339 //
7340 exports.setTyped = function (on) {
7341   if (on) {
7342     exports.Buf8  = Uint8Array;
7343     exports.Buf16 = Uint16Array;
7344     exports.Buf32 = Int32Array;
7345     exports.assign(exports, fnTyped);
7346   } else {
7347     exports.Buf8  = Array;
7348     exports.Buf16 = Array;
7349     exports.Buf32 = Array;
7350     exports.assign(exports, fnUntyped);
7351   }
7352 };
7353
7354 exports.setTyped(TYPED_OK);
7355
7356 },{}],40:[function(require,module,exports){
7357 'use strict';
7358
7359 // Note: adler32 takes 12% for level 0 and 2% for level 6.
7360 // It isn't worth it to make additional optimizations as in original.
7361 // Small size is preferable.
7362
7363 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
7364 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
7365 //
7366 // This software is provided 'as-is', without any express or implied
7367 // warranty. In no event will the authors be held liable for any damages
7368 // arising from the use of this software.
7369 //
7370 // Permission is granted to anyone to use this software for any purpose,
7371 // including commercial applications, and to alter it and redistribute it
7372 // freely, subject to the following restrictions:
7373 //
7374 // 1. The origin of this software must not be misrepresented; you must not
7375 //   claim that you wrote the original software. If you use this software
7376 //   in a product, an acknowledgment in the product documentation would be
7377 //   appreciated but is not required.
7378 // 2. Altered source versions must be plainly marked as such, and must not be
7379 //   misrepresented as being the original software.
7380 // 3. This notice may not be removed or altered from any source distribution.
7381
7382 function adler32(adler, buf, len, pos) {
7383   var s1 = (adler & 0xffff) |0,
7384       s2 = ((adler >>> 16) & 0xffff) |0,
7385       n = 0;
7386
7387   while (len !== 0) {
7388     // Set limit ~ twice less than 5552, to keep
7389     // s2 in 31-bits, because we force signed ints.
7390     // in other case %= will fail.
7391     n = len > 2000 ? 2000 : len;
7392     len -= n;
7393
7394     do {
7395       s1 = (s1 + buf[pos++]) |0;
7396       s2 = (s2 + s1) |0;
7397     } while (--n);
7398
7399     s1 %= 65521;
7400     s2 %= 65521;
7401   }
7402
7403   return (s1 | (s2 << 16)) |0;
7404 }
7405
7406
7407 module.exports = adler32;
7408
7409 },{}],41:[function(require,module,exports){
7410 'use strict';
7411
7412 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
7413 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
7414 //
7415 // This software is provided 'as-is', without any express or implied
7416 // warranty. In no event will the authors be held liable for any damages
7417 // arising from the use of this software.
7418 //
7419 // Permission is granted to anyone to use this software for any purpose,
7420 // including commercial applications, and to alter it and redistribute it
7421 // freely, subject to the following restrictions:
7422 //
7423 // 1. The origin of this software must not be misrepresented; you must not
7424 //   claim that you wrote the original software. If you use this software
7425 //   in a product, an acknowledgment in the product documentation would be
7426 //   appreciated but is not required.
7427 // 2. Altered source versions must be plainly marked as such, and must not be
7428 //   misrepresented as being the original software.
7429 // 3. This notice may not be removed or altered from any source distribution.
7430
7431 module.exports = {
7432
7433   /* Allowed flush values; see deflate() and inflate() below for details */
7434   Z_NO_FLUSH:         0,
7435   Z_PARTIAL_FLUSH:    1,
7436   Z_SYNC_FLUSH:       2,
7437   Z_FULL_FLUSH:       3,
7438   Z_FINISH:           4,
7439   Z_BLOCK:            5,
7440   Z_TREES:            6,
7441
7442   /* Return codes for the compression/decompression functions. Negative values
7443   * are errors, positive values are used for special but normal events.
7444   */
7445   Z_OK:               0,
7446   Z_STREAM_END:       1,
7447   Z_NEED_DICT:        2,
7448   Z_ERRNO:           -1,
7449   Z_STREAM_ERROR:    -2,
7450   Z_DATA_ERROR:      -3,
7451   //Z_MEM_ERROR:     -4,
7452   Z_BUF_ERROR:       -5,
7453   //Z_VERSION_ERROR: -6,
7454
7455   /* compression levels */
7456   Z_NO_COMPRESSION:         0,
7457   Z_BEST_SPEED:             1,
7458   Z_BEST_COMPRESSION:       9,
7459   Z_DEFAULT_COMPRESSION:   -1,
7460
7461
7462   Z_FILTERED:               1,
7463   Z_HUFFMAN_ONLY:           2,
7464   Z_RLE:                    3,
7465   Z_FIXED:                  4,
7466   Z_DEFAULT_STRATEGY:       0,
7467
7468   /* Possible values of the data_type field (though see inflate()) */
7469   Z_BINARY:                 0,
7470   Z_TEXT:                   1,
7471   //Z_ASCII:                1, // = Z_TEXT (deprecated)
7472   Z_UNKNOWN:                2,
7473
7474   /* The deflate compression method */
7475   Z_DEFLATED:               8
7476   //Z_NULL:                 null // Use -1 or null inline, depending on var type
7477 };
7478
7479 },{}],42:[function(require,module,exports){
7480 'use strict';
7481
7482 // Note: we can't get significant speed boost here.
7483 // So write code to minimize size - no pregenerated tables
7484 // and array tools dependencies.
7485
7486 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
7487 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
7488 //
7489 // This software is provided 'as-is', without any express or implied
7490 // warranty. In no event will the authors be held liable for any damages
7491 // arising from the use of this software.
7492 //
7493 // Permission is granted to anyone to use this software for any purpose,
7494 // including commercial applications, and to alter it and redistribute it
7495 // freely, subject to the following restrictions:
7496 //
7497 // 1. The origin of this software must not be misrepresented; you must not
7498 //   claim that you wrote the original software. If you use this software
7499 //   in a product, an acknowledgment in the product documentation would be
7500 //   appreciated but is not required.
7501 // 2. Altered source versions must be plainly marked as such, and must not be
7502 //   misrepresented as being the original software.
7503 // 3. This notice may not be removed or altered from any source distribution.
7504
7505 // Use ordinary array, since untyped makes no boost here
7506 function makeTable() {
7507   var c, table = [];
7508
7509   for (var n = 0; n < 256; n++) {
7510     c = n;
7511     for (var k = 0; k < 8; k++) {
7512       c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
7513     }
7514     table[n] = c;
7515   }
7516
7517   return table;
7518 }
7519
7520 // Create table on load. Just 255 signed longs. Not a problem.
7521 var crcTable = makeTable();
7522
7523
7524 function crc32(crc, buf, len, pos) {
7525   var t = crcTable,
7526       end = pos + len;
7527
7528   crc ^= -1;
7529
7530   for (var i = pos; i < end; i++) {
7531     crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
7532   }
7533
7534   return (crc ^ (-1)); // >>> 0;
7535 }
7536
7537
7538 module.exports = crc32;
7539
7540 },{}],43:[function(require,module,exports){
7541 'use strict';
7542
7543 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
7544 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
7545 //
7546 // This software is provided 'as-is', without any express or implied
7547 // warranty. In no event will the authors be held liable for any damages
7548 // arising from the use of this software.
7549 //
7550 // Permission is granted to anyone to use this software for any purpose,
7551 // including commercial applications, and to alter it and redistribute it
7552 // freely, subject to the following restrictions:
7553 //
7554 // 1. The origin of this software must not be misrepresented; you must not
7555 //   claim that you wrote the original software. If you use this software
7556 //   in a product, an acknowledgment in the product documentation would be
7557 //   appreciated but is not required.
7558 // 2. Altered source versions must be plainly marked as such, and must not be
7559 //   misrepresented as being the original software.
7560 // 3. This notice may not be removed or altered from any source distribution.
7561
7562 var utils   = require('../utils/common');
7563 var trees   = require('./trees');
7564 var adler32 = require('./adler32');
7565 var crc32   = require('./crc32');
7566 var msg     = require('./messages');
7567
7568 /* Public constants ==========================================================*/
7569 /* ===========================================================================*/
7570
7571
7572 /* Allowed flush values; see deflate() and inflate() below for details */
7573 var Z_NO_FLUSH      = 0;
7574 var Z_PARTIAL_FLUSH = 1;
7575 //var Z_SYNC_FLUSH    = 2;
7576 var Z_FULL_FLUSH    = 3;
7577 var Z_FINISH        = 4;
7578 var Z_BLOCK         = 5;
7579 //var Z_TREES         = 6;
7580
7581
7582 /* Return codes for the compression/decompression functions. Negative values
7583  * are errors, positive values are used for special but normal events.
7584  */
7585 var Z_OK            = 0;
7586 var Z_STREAM_END    = 1;
7587 //var Z_NEED_DICT     = 2;
7588 //var Z_ERRNO         = -1;
7589 var Z_STREAM_ERROR  = -2;
7590 var Z_DATA_ERROR    = -3;
7591 //var Z_MEM_ERROR     = -4;
7592 var Z_BUF_ERROR     = -5;
7593 //var Z_VERSION_ERROR = -6;
7594
7595
7596 /* compression levels */
7597 //var Z_NO_COMPRESSION      = 0;
7598 //var Z_BEST_SPEED          = 1;
7599 //var Z_BEST_COMPRESSION    = 9;
7600 var Z_DEFAULT_COMPRESSION = -1;
7601
7602
7603 var Z_FILTERED            = 1;
7604 var Z_HUFFMAN_ONLY        = 2;
7605 var Z_RLE                 = 3;
7606 var Z_FIXED               = 4;
7607 var Z_DEFAULT_STRATEGY    = 0;
7608
7609 /* Possible values of the data_type field (though see inflate()) */
7610 //var Z_BINARY              = 0;
7611 //var Z_TEXT                = 1;
7612 //var Z_ASCII               = 1; // = Z_TEXT
7613 var Z_UNKNOWN             = 2;
7614
7615
7616 /* The deflate compression method */
7617 var Z_DEFLATED  = 8;
7618
7619 /*============================================================================*/
7620
7621
7622 var MAX_MEM_LEVEL = 9;
7623 /* Maximum value for memLevel in deflateInit2 */
7624 var MAX_WBITS = 15;
7625 /* 32K LZ77 window */
7626 var DEF_MEM_LEVEL = 8;
7627
7628
7629 var LENGTH_CODES  = 29;
7630 /* number of length codes, not counting the special END_BLOCK code */
7631 var LITERALS      = 256;
7632 /* number of literal bytes 0..255 */
7633 var L_CODES       = LITERALS + 1 + LENGTH_CODES;
7634 /* number of Literal or Length codes, including the END_BLOCK code */
7635 var D_CODES       = 30;
7636 /* number of distance codes */
7637 var BL_CODES      = 19;
7638 /* number of codes used to transfer the bit lengths */
7639 var HEAP_SIZE     = 2 * L_CODES + 1;
7640 /* maximum heap size */
7641 var MAX_BITS  = 15;
7642 /* All codes must not exceed MAX_BITS bits */
7643
7644 var MIN_MATCH = 3;
7645 var MAX_MATCH = 258;
7646 var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
7647
7648 var PRESET_DICT = 0x20;
7649
7650 var INIT_STATE = 42;
7651 var EXTRA_STATE = 69;
7652 var NAME_STATE = 73;
7653 var COMMENT_STATE = 91;
7654 var HCRC_STATE = 103;
7655 var BUSY_STATE = 113;
7656 var FINISH_STATE = 666;
7657
7658 var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
7659 var BS_BLOCK_DONE     = 2; /* block flush performed */
7660 var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
7661 var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */
7662
7663 var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
7664
7665 function err(strm, errorCode) {
7666   strm.msg = msg[errorCode];
7667   return errorCode;
7668 }
7669
7670 function rank(f) {
7671   return ((f) << 1) - ((f) > 4 ? 9 : 0);
7672 }
7673
7674 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
7675
7676
7677 /* =========================================================================
7678  * Flush as much pending output as possible. All deflate() output goes
7679  * through this function so some applications may wish to modify it
7680  * to avoid allocating a large strm->output buffer and copying into it.
7681  * (See also read_buf()).
7682  */
7683 function flush_pending(strm) {
7684   var s = strm.state;
7685
7686   //_tr_flush_bits(s);
7687   var len = s.pending;
7688   if (len > strm.avail_out) {
7689     len = strm.avail_out;
7690   }
7691   if (len === 0) { return; }
7692
7693   utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
7694   strm.next_out += len;
7695   s.pending_out += len;
7696   strm.total_out += len;
7697   strm.avail_out -= len;
7698   s.pending -= len;
7699   if (s.pending === 0) {
7700     s.pending_out = 0;
7701   }
7702 }
7703
7704
7705 function flush_block_only(s, last) {
7706   trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
7707   s.block_start = s.strstart;
7708   flush_pending(s.strm);
7709 }
7710
7711
7712 function put_byte(s, b) {
7713   s.pending_buf[s.pending++] = b;
7714 }
7715
7716
7717 /* =========================================================================
7718  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
7719  * IN assertion: the stream state is correct and there is enough room in
7720  * pending_buf.
7721  */
7722 function putShortMSB(s, b) {
7723 //  put_byte(s, (Byte)(b >> 8));
7724 //  put_byte(s, (Byte)(b & 0xff));
7725   s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
7726   s.pending_buf[s.pending++] = b & 0xff;
7727 }
7728
7729
7730 /* ===========================================================================
7731  * Read a new buffer from the current input stream, update the adler32
7732  * and total number of bytes read.  All deflate() input goes through
7733  * this function so some applications may wish to modify it to avoid
7734  * allocating a large strm->input buffer and copying from it.
7735  * (See also flush_pending()).
7736  */
7737 function read_buf(strm, buf, start, size) {
7738   var len = strm.avail_in;
7739
7740   if (len > size) { len = size; }
7741   if (len === 0) { return 0; }
7742
7743   strm.avail_in -= len;
7744
7745   // zmemcpy(buf, strm->next_in, len);
7746   utils.arraySet(buf, strm.input, strm.next_in, len, start);
7747   if (strm.state.wrap === 1) {
7748     strm.adler = adler32(strm.adler, buf, len, start);
7749   }
7750
7751   else if (strm.state.wrap === 2) {
7752     strm.adler = crc32(strm.adler, buf, len, start);
7753   }
7754
7755   strm.next_in += len;
7756   strm.total_in += len;
7757
7758   return len;
7759 }
7760
7761
7762 /* ===========================================================================
7763  * Set match_start to the longest match starting at the given string and
7764  * return its length. Matches shorter or equal to prev_length are discarded,
7765  * in which case the result is equal to prev_length and match_start is
7766  * garbage.
7767  * IN assertions: cur_match is the head of the hash chain for the current
7768  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
7769  * OUT assertion: the match length is not greater than s->lookahead.
7770  */
7771 function longest_match(s, cur_match) {
7772   var chain_length = s.max_chain_length;      /* max hash chain length */
7773   var scan = s.strstart; /* current string */
7774   var match;                       /* matched string */
7775   var len;                           /* length of current match */
7776   var best_len = s.prev_length;              /* best match length so far */
7777   var nice_match = s.nice_match;             /* stop if match long enough */
7778   var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
7779       s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
7780
7781   var _win = s.window; // shortcut
7782
7783   var wmask = s.w_mask;
7784   var prev  = s.prev;
7785
7786   /* Stop when cur_match becomes <= limit. To simplify the code,
7787    * we prevent matches with the string of window index 0.
7788    */
7789
7790   var strend = s.strstart + MAX_MATCH;
7791   var scan_end1  = _win[scan + best_len - 1];
7792   var scan_end   = _win[scan + best_len];
7793
7794   /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
7795    * It is easy to get rid of this optimization if necessary.
7796    */
7797   // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
7798
7799   /* Do not waste too much time if we already have a good match: */
7800   if (s.prev_length >= s.good_match) {
7801     chain_length >>= 2;
7802   }
7803   /* Do not look for matches beyond the end of the input. This is necessary
7804    * to make deflate deterministic.
7805    */
7806   if (nice_match > s.lookahead) { nice_match = s.lookahead; }
7807
7808   // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
7809
7810   do {
7811     // Assert(cur_match < s->strstart, "no future");
7812     match = cur_match;
7813
7814     /* Skip to next match if the match length cannot increase
7815      * or if the match length is less than 2.  Note that the checks below
7816      * for insufficient lookahead only occur occasionally for performance
7817      * reasons.  Therefore uninitialized memory will be accessed, and
7818      * conditional jumps will be made that depend on those values.
7819      * However the length of the match is limited to the lookahead, so
7820      * the output of deflate is not affected by the uninitialized values.
7821      */
7822
7823     if (_win[match + best_len]     !== scan_end  ||
7824         _win[match + best_len - 1] !== scan_end1 ||
7825         _win[match]                !== _win[scan] ||
7826         _win[++match]              !== _win[scan + 1]) {
7827       continue;
7828     }
7829
7830     /* The check at best_len-1 can be removed because it will be made
7831      * again later. (This heuristic is not always a win.)
7832      * It is not necessary to compare scan[2] and match[2] since they
7833      * are always equal when the other bytes match, given that
7834      * the hash keys are equal and that HASH_BITS >= 8.
7835      */
7836     scan += 2;
7837     match++;
7838     // Assert(*scan == *match, "match[2]?");
7839
7840     /* We check for insufficient lookahead only every 8th comparison;
7841      * the 256th check will be made at strstart+258.
7842      */
7843     do {
7844       /*jshint noempty:false*/
7845     } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
7846              _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
7847              _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
7848              _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
7849              scan < strend);
7850
7851     // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
7852
7853     len = MAX_MATCH - (strend - scan);
7854     scan = strend - MAX_MATCH;
7855
7856     if (len > best_len) {
7857       s.match_start = cur_match;
7858       best_len = len;
7859       if (len >= nice_match) {
7860         break;
7861       }
7862       scan_end1  = _win[scan + best_len - 1];
7863       scan_end   = _win[scan + best_len];
7864     }
7865   } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
7866
7867   if (best_len <= s.lookahead) {
7868     return best_len;
7869   }
7870   return s.lookahead;
7871 }
7872
7873
7874 /* ===========================================================================
7875  * Fill the window when the lookahead becomes insufficient.
7876  * Updates strstart and lookahead.
7877  *
7878  * IN assertion: lookahead < MIN_LOOKAHEAD
7879  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
7880  *    At least one byte has been read, or avail_in == 0; reads are
7881  *    performed for at least two bytes (required for the zip translate_eol
7882  *    option -- not supported here).
7883  */
7884 function fill_window(s) {
7885   var _w_size = s.w_size;
7886   var p, n, m, more, str;
7887
7888   //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
7889
7890   do {
7891     more = s.window_size - s.lookahead - s.strstart;
7892
7893     // JS ints have 32 bit, block below not needed
7894     /* Deal with !@#$% 64K limit: */
7895     //if (sizeof(int) <= 2) {
7896     //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
7897     //        more = wsize;
7898     //
7899     //  } else if (more == (unsigned)(-1)) {
7900     //        /* Very unlikely, but possible on 16 bit machine if
7901     //         * strstart == 0 && lookahead == 1 (input done a byte at time)
7902     //         */
7903     //        more--;
7904     //    }
7905     //}
7906
7907
7908     /* If the window is almost full and there is insufficient lookahead,
7909      * move the upper half to the lower one to make room in the upper half.
7910      */
7911     if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
7912
7913       utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
7914       s.match_start -= _w_size;
7915       s.strstart -= _w_size;
7916       /* we now have strstart >= MAX_DIST */
7917       s.block_start -= _w_size;
7918
7919       /* Slide the hash table (could be avoided with 32 bit values
7920        at the expense of memory usage). We slide even when level == 0
7921        to keep the hash table consistent if we switch back to level > 0
7922        later. (Using level 0 permanently is not an optimal usage of
7923        zlib, so we don't care about this pathological case.)
7924        */
7925
7926       n = s.hash_size;
7927       p = n;
7928       do {
7929         m = s.head[--p];
7930         s.head[p] = (m >= _w_size ? m - _w_size : 0);
7931       } while (--n);
7932
7933       n = _w_size;
7934       p = n;
7935       do {
7936         m = s.prev[--p];
7937         s.prev[p] = (m >= _w_size ? m - _w_size : 0);
7938         /* If n is not on any hash chain, prev[n] is garbage but
7939          * its value will never be used.
7940          */
7941       } while (--n);
7942
7943       more += _w_size;
7944     }
7945     if (s.strm.avail_in === 0) {
7946       break;
7947     }
7948
7949     /* If there was no sliding:
7950      *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
7951      *    more == window_size - lookahead - strstart
7952      * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
7953      * => more >= window_size - 2*WSIZE + 2
7954      * In the BIG_MEM or MMAP case (not yet supported),
7955      *   window_size == input_size + MIN_LOOKAHEAD  &&
7956      *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
7957      * Otherwise, window_size == 2*WSIZE so more >= 2.
7958      * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
7959      */
7960     //Assert(more >= 2, "more < 2");
7961     n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
7962     s.lookahead += n;
7963
7964     /* Initialize the hash value now that we have some input: */
7965     if (s.lookahead + s.insert >= MIN_MATCH) {
7966       str = s.strstart - s.insert;
7967       s.ins_h = s.window[str];
7968
7969       /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
7970       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
7971 //#if MIN_MATCH != 3
7972 //        Call update_hash() MIN_MATCH-3 more times
7973 //#endif
7974       while (s.insert) {
7975         /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
7976         s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
7977
7978         s.prev[str & s.w_mask] = s.head[s.ins_h];
7979         s.head[s.ins_h] = str;
7980         str++;
7981         s.insert--;
7982         if (s.lookahead + s.insert < MIN_MATCH) {
7983           break;
7984         }
7985       }
7986     }
7987     /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
7988      * but this is not important since only literal bytes will be emitted.
7989      */
7990
7991   } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
7992
7993   /* If the WIN_INIT bytes after the end of the current data have never been
7994    * written, then zero those bytes in order to avoid memory check reports of
7995    * the use of uninitialized (or uninitialised as Julian writes) bytes by
7996    * the longest match routines.  Update the high water mark for the next
7997    * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
7998    * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
7999    */
8000 //  if (s.high_water < s.window_size) {
8001 //    var curr = s.strstart + s.lookahead;
8002 //    var init = 0;
8003 //
8004 //    if (s.high_water < curr) {
8005 //      /* Previous high water mark below current data -- zero WIN_INIT
8006 //       * bytes or up to end of window, whichever is less.
8007 //       */
8008 //      init = s.window_size - curr;
8009 //      if (init > WIN_INIT)
8010 //        init = WIN_INIT;
8011 //      zmemzero(s->window + curr, (unsigned)init);
8012 //      s->high_water = curr + init;
8013 //    }
8014 //    else if (s->high_water < (ulg)curr + WIN_INIT) {
8015 //      /* High water mark at or above current data, but below current data
8016 //       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
8017 //       * to end of window, whichever is less.
8018 //       */
8019 //      init = (ulg)curr + WIN_INIT - s->high_water;
8020 //      if (init > s->window_size - s->high_water)
8021 //        init = s->window_size - s->high_water;
8022 //      zmemzero(s->window + s->high_water, (unsigned)init);
8023 //      s->high_water += init;
8024 //    }
8025 //  }
8026 //
8027 //  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
8028 //    "not enough room for search");
8029 }
8030
8031 /* ===========================================================================
8032  * Copy without compression as much as possible from the input stream, return
8033  * the current block state.
8034  * This function does not insert new strings in the dictionary since
8035  * uncompressible data is probably not useful. This function is used
8036  * only for the level=0 compression option.
8037  * NOTE: this function should be optimized to avoid extra copying from
8038  * window to pending_buf.
8039  */
8040 function deflate_stored(s, flush) {
8041   /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
8042    * to pending_buf_size, and each stored block has a 5 byte header:
8043    */
8044   var max_block_size = 0xffff;
8045
8046   if (max_block_size > s.pending_buf_size - 5) {
8047     max_block_size = s.pending_buf_size - 5;
8048   }
8049
8050   /* Copy as much as possible from input to output: */
8051   for (;;) {
8052     /* Fill the window as much as possible: */
8053     if (s.lookahead <= 1) {
8054
8055       //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
8056       //  s->block_start >= (long)s->w_size, "slide too late");
8057 //      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
8058 //        s.block_start >= s.w_size)) {
8059 //        throw  new Error("slide too late");
8060 //      }
8061
8062       fill_window(s);
8063       if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
8064         return BS_NEED_MORE;
8065       }
8066
8067       if (s.lookahead === 0) {
8068         break;
8069       }
8070       /* flush the current block */
8071     }
8072     //Assert(s->block_start >= 0L, "block gone");
8073 //    if (s.block_start < 0) throw new Error("block gone");
8074
8075     s.strstart += s.lookahead;
8076     s.lookahead = 0;
8077
8078     /* Emit a stored block if pending_buf will be full: */
8079     var max_start = s.block_start + max_block_size;
8080
8081     if (s.strstart === 0 || s.strstart >= max_start) {
8082       /* strstart == 0 is possible when wraparound on 16-bit machine */
8083       s.lookahead = s.strstart - max_start;
8084       s.strstart = max_start;
8085       /*** FLUSH_BLOCK(s, 0); ***/
8086       flush_block_only(s, false);
8087       if (s.strm.avail_out === 0) {
8088         return BS_NEED_MORE;
8089       }
8090       /***/
8091
8092
8093     }
8094     /* Flush if we may have to slide, otherwise block_start may become
8095      * negative and the data will be gone:
8096      */
8097     if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
8098       /*** FLUSH_BLOCK(s, 0); ***/
8099       flush_block_only(s, false);
8100       if (s.strm.avail_out === 0) {
8101         return BS_NEED_MORE;
8102       }
8103       /***/
8104     }
8105   }
8106
8107   s.insert = 0;
8108
8109   if (flush === Z_FINISH) {
8110     /*** FLUSH_BLOCK(s, 1); ***/
8111     flush_block_only(s, true);
8112     if (s.strm.avail_out === 0) {
8113       return BS_FINISH_STARTED;
8114     }
8115     /***/
8116     return BS_FINISH_DONE;
8117   }
8118
8119   if (s.strstart > s.block_start) {
8120     /*** FLUSH_BLOCK(s, 0); ***/
8121     flush_block_only(s, false);
8122     if (s.strm.avail_out === 0) {
8123       return BS_NEED_MORE;
8124     }
8125     /***/
8126   }
8127
8128   return BS_NEED_MORE;
8129 }
8130
8131 /* ===========================================================================
8132  * Compress as much as possible from the input stream, return the current
8133  * block state.
8134  * This function does not perform lazy evaluation of matches and inserts
8135  * new strings in the dictionary only for unmatched strings or for short
8136  * matches. It is used only for the fast compression options.
8137  */
8138 function deflate_fast(s, flush) {
8139   var hash_head;        /* head of the hash chain */
8140   var bflush;           /* set if current block must be flushed */
8141
8142   for (;;) {
8143     /* Make sure that we always have enough lookahead, except
8144      * at the end of the input file. We need MAX_MATCH bytes
8145      * for the next match, plus MIN_MATCH bytes to insert the
8146      * string following the next match.
8147      */
8148     if (s.lookahead < MIN_LOOKAHEAD) {
8149       fill_window(s);
8150       if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
8151         return BS_NEED_MORE;
8152       }
8153       if (s.lookahead === 0) {
8154         break; /* flush the current block */
8155       }
8156     }
8157
8158     /* Insert the string window[strstart .. strstart+2] in the
8159      * dictionary, and set hash_head to the head of the hash chain:
8160      */
8161     hash_head = 0/*NIL*/;
8162     if (s.lookahead >= MIN_MATCH) {
8163       /*** INSERT_STRING(s, s.strstart, hash_head); ***/
8164       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
8165       hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
8166       s.head[s.ins_h] = s.strstart;
8167       /***/
8168     }
8169
8170     /* Find the longest match, discarding those <= prev_length.
8171      * At this point we have always match_length < MIN_MATCH
8172      */
8173     if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
8174       /* To simplify the code, we prevent matches with the string
8175        * of window index 0 (in particular we have to avoid a match
8176        * of the string with itself at the start of the input file).
8177        */
8178       s.match_length = longest_match(s, hash_head);
8179       /* longest_match() sets match_start */
8180     }
8181     if (s.match_length >= MIN_MATCH) {
8182       // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
8183
8184       /*** _tr_tally_dist(s, s.strstart - s.match_start,
8185                      s.match_length - MIN_MATCH, bflush); ***/
8186       bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
8187
8188       s.lookahead -= s.match_length;
8189
8190       /* Insert new strings in the hash table only if the match length
8191        * is not too large. This saves time but degrades compression.
8192        */
8193       if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
8194         s.match_length--; /* string at strstart already in table */
8195         do {
8196           s.strstart++;
8197           /*** INSERT_STRING(s, s.strstart, hash_head); ***/
8198           s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
8199           hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
8200           s.head[s.ins_h] = s.strstart;
8201           /***/
8202           /* strstart never exceeds WSIZE-MAX_MATCH, so there are
8203            * always MIN_MATCH bytes ahead.
8204            */
8205         } while (--s.match_length !== 0);
8206         s.strstart++;
8207       } else
8208       {
8209         s.strstart += s.match_length;
8210         s.match_length = 0;
8211         s.ins_h = s.window[s.strstart];
8212         /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
8213         s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
8214
8215 //#if MIN_MATCH != 3
8216 //                Call UPDATE_HASH() MIN_MATCH-3 more times
8217 //#endif
8218         /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
8219          * matter since it will be recomputed at next deflate call.
8220          */
8221       }
8222     } else {
8223       /* No match, output a literal byte */
8224       //Tracevv((stderr,"%c", s.window[s.strstart]));
8225       /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
8226       bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
8227
8228       s.lookahead--;
8229       s.strstart++;
8230     }
8231     if (bflush) {
8232       /*** FLUSH_BLOCK(s, 0); ***/
8233       flush_block_only(s, false);
8234       if (s.strm.avail_out === 0) {
8235         return BS_NEED_MORE;
8236       }
8237       /***/
8238     }
8239   }
8240   s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
8241   if (flush === Z_FINISH) {
8242     /*** FLUSH_BLOCK(s, 1); ***/
8243     flush_block_only(s, true);
8244     if (s.strm.avail_out === 0) {
8245       return BS_FINISH_STARTED;
8246     }
8247     /***/
8248     return BS_FINISH_DONE;
8249   }
8250   if (s.last_lit) {
8251     /*** FLUSH_BLOCK(s, 0); ***/
8252     flush_block_only(s, false);
8253     if (s.strm.avail_out === 0) {
8254       return BS_NEED_MORE;
8255     }
8256     /***/
8257   }
8258   return BS_BLOCK_DONE;
8259 }
8260
8261 /* ===========================================================================
8262  * Same as above, but achieves better compression. We use a lazy
8263  * evaluation for matches: a match is finally adopted only if there is
8264  * no better match at the next window position.
8265  */
8266 function deflate_slow(s, flush) {
8267   var hash_head;          /* head of hash chain */
8268   var bflush;              /* set if current block must be flushed */
8269
8270   var max_insert;
8271
8272   /* Process the input block. */
8273   for (;;) {
8274     /* Make sure that we always have enough lookahead, except
8275      * at the end of the input file. We need MAX_MATCH bytes
8276      * for the next match, plus MIN_MATCH bytes to insert the
8277      * string following the next match.
8278      */
8279     if (s.lookahead < MIN_LOOKAHEAD) {
8280       fill_window(s);
8281       if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
8282         return BS_NEED_MORE;
8283       }
8284       if (s.lookahead === 0) { break; } /* flush the current block */
8285     }
8286
8287     /* Insert the string window[strstart .. strstart+2] in the
8288      * dictionary, and set hash_head to the head of the hash chain:
8289      */
8290     hash_head = 0/*NIL*/;
8291     if (s.lookahead >= MIN_MATCH) {
8292       /*** INSERT_STRING(s, s.strstart, hash_head); ***/
8293       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
8294       hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
8295       s.head[s.ins_h] = s.strstart;
8296       /***/
8297     }
8298
8299     /* Find the longest match, discarding those <= prev_length.
8300      */
8301     s.prev_length = s.match_length;
8302     s.prev_match = s.match_start;
8303     s.match_length = MIN_MATCH - 1;
8304
8305     if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
8306         s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
8307       /* To simplify the code, we prevent matches with the string
8308        * of window index 0 (in particular we have to avoid a match
8309        * of the string with itself at the start of the input file).
8310        */
8311       s.match_length = longest_match(s, hash_head);
8312       /* longest_match() sets match_start */
8313
8314       if (s.match_length <= 5 &&
8315          (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
8316
8317         /* If prev_match is also MIN_MATCH, match_start is garbage
8318          * but we will ignore the current match anyway.
8319          */
8320         s.match_length = MIN_MATCH - 1;
8321       }
8322     }
8323     /* If there was a match at the previous step and the current
8324      * match is not better, output the previous match:
8325      */
8326     if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
8327       max_insert = s.strstart + s.lookahead - MIN_MATCH;
8328       /* Do not insert strings in hash table beyond this. */
8329
8330       //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
8331
8332       /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
8333                      s.prev_length - MIN_MATCH, bflush);***/
8334       bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
8335       /* Insert in hash table all strings up to the end of the match.
8336        * strstart-1 and strstart are already inserted. If there is not
8337        * enough lookahead, the last two strings are not inserted in
8338        * the hash table.
8339        */
8340       s.lookahead -= s.prev_length - 1;
8341       s.prev_length -= 2;
8342       do {
8343         if (++s.strstart <= max_insert) {
8344           /*** INSERT_STRING(s, s.strstart, hash_head); ***/
8345           s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
8346           hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
8347           s.head[s.ins_h] = s.strstart;
8348           /***/
8349         }
8350       } while (--s.prev_length !== 0);
8351       s.match_available = 0;
8352       s.match_length = MIN_MATCH - 1;
8353       s.strstart++;
8354
8355       if (bflush) {
8356         /*** FLUSH_BLOCK(s, 0); ***/
8357         flush_block_only(s, false);
8358         if (s.strm.avail_out === 0) {
8359           return BS_NEED_MORE;
8360         }
8361         /***/
8362       }
8363
8364     } else if (s.match_available) {
8365       /* If there was no match at the previous position, output a
8366        * single literal. If there was a match but the current match
8367        * is longer, truncate the previous match to a single literal.
8368        */
8369       //Tracevv((stderr,"%c", s->window[s->strstart-1]));
8370       /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
8371       bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
8372
8373       if (bflush) {
8374         /*** FLUSH_BLOCK_ONLY(s, 0) ***/
8375         flush_block_only(s, false);
8376         /***/
8377       }
8378       s.strstart++;
8379       s.lookahead--;
8380       if (s.strm.avail_out === 0) {
8381         return BS_NEED_MORE;
8382       }
8383     } else {
8384       /* There is no previous match to compare with, wait for
8385        * the next step to decide.
8386        */
8387       s.match_available = 1;
8388       s.strstart++;
8389       s.lookahead--;
8390     }
8391   }
8392   //Assert (flush != Z_NO_FLUSH, "no flush?");
8393   if (s.match_available) {
8394     //Tracevv((stderr,"%c", s->window[s->strstart-1]));
8395     /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
8396     bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
8397
8398     s.match_available = 0;
8399   }
8400   s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
8401   if (flush === Z_FINISH) {
8402     /*** FLUSH_BLOCK(s, 1); ***/
8403     flush_block_only(s, true);
8404     if (s.strm.avail_out === 0) {
8405       return BS_FINISH_STARTED;
8406     }
8407     /***/
8408     return BS_FINISH_DONE;
8409   }
8410   if (s.last_lit) {
8411     /*** FLUSH_BLOCK(s, 0); ***/
8412     flush_block_only(s, false);
8413     if (s.strm.avail_out === 0) {
8414       return BS_NEED_MORE;
8415     }
8416     /***/
8417   }
8418
8419   return BS_BLOCK_DONE;
8420 }
8421
8422
8423 /* ===========================================================================
8424  * For Z_RLE, simply look for runs of bytes, generate matches only of distance
8425  * one.  Do not maintain a hash table.  (It will be regenerated if this run of
8426  * deflate switches away from Z_RLE.)
8427  */
8428 function deflate_rle(s, flush) {
8429   var bflush;            /* set if current block must be flushed */
8430   var prev;              /* byte at distance one to match */
8431   var scan, strend;      /* scan goes up to strend for length of run */
8432
8433   var _win = s.window;
8434
8435   for (;;) {
8436     /* Make sure that we always have enough lookahead, except
8437      * at the end of the input file. We need MAX_MATCH bytes
8438      * for the longest run, plus one for the unrolled loop.
8439      */
8440     if (s.lookahead <= MAX_MATCH) {
8441       fill_window(s);
8442       if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
8443         return BS_NEED_MORE;
8444       }
8445       if (s.lookahead === 0) { break; } /* flush the current block */
8446     }
8447
8448     /* See how many times the previous byte repeats */
8449     s.match_length = 0;
8450     if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
8451       scan = s.strstart - 1;
8452       prev = _win[scan];
8453       if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
8454         strend = s.strstart + MAX_MATCH;
8455         do {
8456           /*jshint noempty:false*/
8457         } while (prev === _win[++scan] && prev === _win[++scan] &&
8458                  prev === _win[++scan] && prev === _win[++scan] &&
8459                  prev === _win[++scan] && prev === _win[++scan] &&
8460                  prev === _win[++scan] && prev === _win[++scan] &&
8461                  scan < strend);
8462         s.match_length = MAX_MATCH - (strend - scan);
8463         if (s.match_length > s.lookahead) {
8464           s.match_length = s.lookahead;
8465         }
8466       }
8467       //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
8468     }
8469
8470     /* Emit match if have run of MIN_MATCH or longer, else emit literal */
8471     if (s.match_length >= MIN_MATCH) {
8472       //check_match(s, s.strstart, s.strstart - 1, s.match_length);
8473
8474       /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
8475       bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
8476
8477       s.lookahead -= s.match_length;
8478       s.strstart += s.match_length;
8479       s.match_length = 0;
8480     } else {
8481       /* No match, output a literal byte */
8482       //Tracevv((stderr,"%c", s->window[s->strstart]));
8483       /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
8484       bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
8485
8486       s.lookahead--;
8487       s.strstart++;
8488     }
8489     if (bflush) {
8490       /*** FLUSH_BLOCK(s, 0); ***/
8491       flush_block_only(s, false);
8492       if (s.strm.avail_out === 0) {
8493         return BS_NEED_MORE;
8494       }
8495       /***/
8496     }
8497   }
8498   s.insert = 0;
8499   if (flush === Z_FINISH) {
8500     /*** FLUSH_BLOCK(s, 1); ***/
8501     flush_block_only(s, true);
8502     if (s.strm.avail_out === 0) {
8503       return BS_FINISH_STARTED;
8504     }
8505     /***/
8506     return BS_FINISH_DONE;
8507   }
8508   if (s.last_lit) {
8509     /*** FLUSH_BLOCK(s, 0); ***/
8510     flush_block_only(s, false);
8511     if (s.strm.avail_out === 0) {
8512       return BS_NEED_MORE;
8513     }
8514     /***/
8515   }
8516   return BS_BLOCK_DONE;
8517 }
8518
8519 /* ===========================================================================
8520  * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
8521  * (It will be regenerated if this run of deflate switches away from Huffman.)
8522  */
8523 function deflate_huff(s, flush) {
8524   var bflush;             /* set if current block must be flushed */
8525
8526   for (;;) {
8527     /* Make sure that we have a literal to write. */
8528     if (s.lookahead === 0) {
8529       fill_window(s);
8530       if (s.lookahead === 0) {
8531         if (flush === Z_NO_FLUSH) {
8532           return BS_NEED_MORE;
8533         }
8534         break;      /* flush the current block */
8535       }
8536     }
8537
8538     /* Output a literal byte */
8539     s.match_length = 0;
8540     //Tracevv((stderr,"%c", s->window[s->strstart]));
8541     /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
8542     bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
8543     s.lookahead--;
8544     s.strstart++;
8545     if (bflush) {
8546       /*** FLUSH_BLOCK(s, 0); ***/
8547       flush_block_only(s, false);
8548       if (s.strm.avail_out === 0) {
8549         return BS_NEED_MORE;
8550       }
8551       /***/
8552     }
8553   }
8554   s.insert = 0;
8555   if (flush === Z_FINISH) {
8556     /*** FLUSH_BLOCK(s, 1); ***/
8557     flush_block_only(s, true);
8558     if (s.strm.avail_out === 0) {
8559       return BS_FINISH_STARTED;
8560     }
8561     /***/
8562     return BS_FINISH_DONE;
8563   }
8564   if (s.last_lit) {
8565     /*** FLUSH_BLOCK(s, 0); ***/
8566     flush_block_only(s, false);
8567     if (s.strm.avail_out === 0) {
8568       return BS_NEED_MORE;
8569     }
8570     /***/
8571   }
8572   return BS_BLOCK_DONE;
8573 }
8574
8575 /* Values for max_lazy_match, good_match and max_chain_length, depending on
8576  * the desired pack level (0..9). The values given below have been tuned to
8577  * exclude worst case performance for pathological files. Better values may be
8578  * found for specific files.
8579  */
8580 function Config(good_length, max_lazy, nice_length, max_chain, func) {
8581   this.good_length = good_length;
8582   this.max_lazy = max_lazy;
8583   this.nice_length = nice_length;
8584   this.max_chain = max_chain;
8585   this.func = func;
8586 }
8587
8588 var configuration_table;
8589
8590 configuration_table = [
8591   /*      good lazy nice chain */
8592   new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
8593   new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
8594   new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
8595   new Config(4, 6, 32, 32, deflate_fast),          /* 3 */
8596
8597   new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
8598   new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
8599   new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
8600   new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
8601   new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
8602   new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
8603 ];
8604
8605
8606 /* ===========================================================================
8607  * Initialize the "longest match" routines for a new zlib stream
8608  */
8609 function lm_init(s) {
8610   s.window_size = 2 * s.w_size;
8611
8612   /*** CLEAR_HASH(s); ***/
8613   zero(s.head); // Fill with NIL (= 0);
8614
8615   /* Set the default configuration parameters:
8616    */
8617   s.max_lazy_match = configuration_table[s.level].max_lazy;
8618   s.good_match = configuration_table[s.level].good_length;
8619   s.nice_match = configuration_table[s.level].nice_length;
8620   s.max_chain_length = configuration_table[s.level].max_chain;
8621
8622   s.strstart = 0;
8623   s.block_start = 0;
8624   s.lookahead = 0;
8625   s.insert = 0;
8626   s.match_length = s.prev_length = MIN_MATCH - 1;
8627   s.match_available = 0;
8628   s.ins_h = 0;
8629 }
8630
8631
8632 function DeflateState() {
8633   this.strm = null;            /* pointer back to this zlib stream */
8634   this.status = 0;            /* as the name implies */
8635   this.pending_buf = null;      /* output still pending */
8636   this.pending_buf_size = 0;  /* size of pending_buf */
8637   this.pending_out = 0;       /* next pending byte to output to the stream */
8638   this.pending = 0;           /* nb of bytes in the pending buffer */
8639   this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
8640   this.gzhead = null;         /* gzip header information to write */
8641   this.gzindex = 0;           /* where in extra, name, or comment */
8642   this.method = Z_DEFLATED; /* can only be DEFLATED */
8643   this.last_flush = -1;   /* value of flush param for previous deflate call */
8644
8645   this.w_size = 0;  /* LZ77 window size (32K by default) */
8646   this.w_bits = 0;  /* log2(w_size)  (8..16) */
8647   this.w_mask = 0;  /* w_size - 1 */
8648
8649   this.window = null;
8650   /* Sliding window. Input bytes are read into the second half of the window,
8651    * and move to the first half later to keep a dictionary of at least wSize
8652    * bytes. With this organization, matches are limited to a distance of
8653    * wSize-MAX_MATCH bytes, but this ensures that IO is always
8654    * performed with a length multiple of the block size.
8655    */
8656
8657   this.window_size = 0;
8658   /* Actual size of window: 2*wSize, except when the user input buffer
8659    * is directly used as sliding window.
8660    */
8661
8662   this.prev = null;
8663   /* Link to older string with same hash index. To limit the size of this
8664    * array to 64K, this link is maintained only for the last 32K strings.
8665    * An index in this array is thus a window index modulo 32K.
8666    */
8667
8668   this.head = null;   /* Heads of the hash chains or NIL. */
8669
8670   this.ins_h = 0;       /* hash index of string to be inserted */
8671   this.hash_size = 0;   /* number of elements in hash table */
8672   this.hash_bits = 0;   /* log2(hash_size) */
8673   this.hash_mask = 0;   /* hash_size-1 */
8674
8675   this.hash_shift = 0;
8676   /* Number of bits by which ins_h must be shifted at each input
8677    * step. It must be such that after MIN_MATCH steps, the oldest
8678    * byte no longer takes part in the hash key, that is:
8679    *   hash_shift * MIN_MATCH >= hash_bits
8680    */
8681
8682   this.block_start = 0;
8683   /* Window position at the beginning of the current output block. Gets
8684    * negative when the window is moved backwards.
8685    */
8686
8687   this.match_length = 0;      /* length of best match */
8688   this.prev_match = 0;        /* previous match */
8689   this.match_available = 0;   /* set if previous match exists */
8690   this.strstart = 0;          /* start of string to insert */
8691   this.match_start = 0;       /* start of matching string */
8692   this.lookahead = 0;         /* number of valid bytes ahead in window */
8693
8694   this.prev_length = 0;
8695   /* Length of the best match at previous step. Matches not greater than this
8696    * are discarded. This is used in the lazy match evaluation.
8697    */
8698
8699   this.max_chain_length = 0;
8700   /* To speed up deflation, hash chains are never searched beyond this
8701    * length.  A higher limit improves compression ratio but degrades the
8702    * speed.
8703    */
8704
8705   this.max_lazy_match = 0;
8706   /* Attempt to find a better match only when the current match is strictly
8707    * smaller than this value. This mechanism is used only for compression
8708    * levels >= 4.
8709    */
8710   // That's alias to max_lazy_match, don't use directly
8711   //this.max_insert_length = 0;
8712   /* Insert new strings in the hash table only if the match length is not
8713    * greater than this length. This saves time but degrades compression.
8714    * max_insert_length is used only for compression levels <= 3.
8715    */
8716
8717   this.level = 0;     /* compression level (1..9) */
8718   this.strategy = 0;  /* favor or force Huffman coding*/
8719
8720   this.good_match = 0;
8721   /* Use a faster search when the previous match is longer than this */
8722
8723   this.nice_match = 0; /* Stop searching when current match exceeds this */
8724
8725               /* used by trees.c: */
8726
8727   /* Didn't use ct_data typedef below to suppress compiler warning */
8728
8729   // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
8730   // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
8731   // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
8732
8733   // Use flat array of DOUBLE size, with interleaved fata,
8734   // because JS does not support effective
8735   this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
8736   this.dyn_dtree  = new utils.Buf16((2 * D_CODES + 1) * 2);
8737   this.bl_tree    = new utils.Buf16((2 * BL_CODES + 1) * 2);
8738   zero(this.dyn_ltree);
8739   zero(this.dyn_dtree);
8740   zero(this.bl_tree);
8741
8742   this.l_desc   = null;         /* desc. for literal tree */
8743   this.d_desc   = null;         /* desc. for distance tree */
8744   this.bl_desc  = null;         /* desc. for bit length tree */
8745
8746   //ush bl_count[MAX_BITS+1];
8747   this.bl_count = new utils.Buf16(MAX_BITS + 1);
8748   /* number of codes at each bit length for an optimal tree */
8749
8750   //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
8751   this.heap = new utils.Buf16(2 * L_CODES + 1);  /* heap used to build the Huffman trees */
8752   zero(this.heap);
8753
8754   this.heap_len = 0;               /* number of elements in the heap */
8755   this.heap_max = 0;               /* element of largest frequency */
8756   /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
8757    * The same heap array is used to build all trees.
8758    */
8759
8760   this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
8761   zero(this.depth);
8762   /* Depth of each subtree used as tie breaker for trees of equal frequency
8763    */
8764
8765   this.l_buf = 0;          /* buffer index for literals or lengths */
8766
8767   this.lit_bufsize = 0;
8768   /* Size of match buffer for literals/lengths.  There are 4 reasons for
8769    * limiting lit_bufsize to 64K:
8770    *   - frequencies can be kept in 16 bit counters
8771    *   - if compression is not successful for the first block, all input
8772    *     data is still in the window so we can still emit a stored block even
8773    *     when input comes from standard input.  (This can also be done for
8774    *     all blocks if lit_bufsize is not greater than 32K.)
8775    *   - if compression is not successful for a file smaller than 64K, we can
8776    *     even emit a stored file instead of a stored block (saving 5 bytes).
8777    *     This is applicable only for zip (not gzip or zlib).
8778    *   - creating new Huffman trees less frequently may not provide fast
8779    *     adaptation to changes in the input data statistics. (Take for
8780    *     example a binary file with poorly compressible code followed by
8781    *     a highly compressible string table.) Smaller buffer sizes give
8782    *     fast adaptation but have of course the overhead of transmitting
8783    *     trees more frequently.
8784    *   - I can't count above 4
8785    */
8786
8787   this.last_lit = 0;      /* running index in l_buf */
8788
8789   this.d_buf = 0;
8790   /* Buffer index for distances. To simplify the code, d_buf and l_buf have
8791    * the same number of elements. To use different lengths, an extra flag
8792    * array would be necessary.
8793    */
8794
8795   this.opt_len = 0;       /* bit length of current block with optimal trees */
8796   this.static_len = 0;    /* bit length of current block with static trees */
8797   this.matches = 0;       /* number of string matches in current block */
8798   this.insert = 0;        /* bytes at end of window left to insert */
8799
8800
8801   this.bi_buf = 0;
8802   /* Output buffer. bits are inserted starting at the bottom (least
8803    * significant bits).
8804    */
8805   this.bi_valid = 0;
8806   /* Number of valid bits in bi_buf.  All bits above the last valid bit
8807    * are always zero.
8808    */
8809
8810   // Used for window memory init. We safely ignore it for JS. That makes
8811   // sense only for pointers and memory check tools.
8812   //this.high_water = 0;
8813   /* High water mark offset in window for initialized bytes -- bytes above
8814    * this are set to zero in order to avoid memory check warnings when
8815    * longest match routines access bytes past the input.  This is then
8816    * updated to the new high water mark.
8817    */
8818 }
8819
8820
8821 function deflateResetKeep(strm) {
8822   var s;
8823
8824   if (!strm || !strm.state) {
8825     return err(strm, Z_STREAM_ERROR);
8826   }
8827
8828   strm.total_in = strm.total_out = 0;
8829   strm.data_type = Z_UNKNOWN;
8830
8831   s = strm.state;
8832   s.pending = 0;
8833   s.pending_out = 0;
8834
8835   if (s.wrap < 0) {
8836     s.wrap = -s.wrap;
8837     /* was made negative by deflate(..., Z_FINISH); */
8838   }
8839   s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
8840   strm.adler = (s.wrap === 2) ?
8841     0  // crc32(0, Z_NULL, 0)
8842   :
8843     1; // adler32(0, Z_NULL, 0)
8844   s.last_flush = Z_NO_FLUSH;
8845   trees._tr_init(s);
8846   return Z_OK;
8847 }
8848
8849
8850 function deflateReset(strm) {
8851   var ret = deflateResetKeep(strm);
8852   if (ret === Z_OK) {
8853     lm_init(strm.state);
8854   }
8855   return ret;
8856 }
8857
8858
8859 function deflateSetHeader(strm, head) {
8860   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8861   if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
8862   strm.state.gzhead = head;
8863   return Z_OK;
8864 }
8865
8866
8867 function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
8868   if (!strm) { // === Z_NULL
8869     return Z_STREAM_ERROR;
8870   }
8871   var wrap = 1;
8872
8873   if (level === Z_DEFAULT_COMPRESSION) {
8874     level = 6;
8875   }
8876
8877   if (windowBits < 0) { /* suppress zlib wrapper */
8878     wrap = 0;
8879     windowBits = -windowBits;
8880   }
8881
8882   else if (windowBits > 15) {
8883     wrap = 2;           /* write gzip wrapper instead */
8884     windowBits -= 16;
8885   }
8886
8887
8888   if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
8889     windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
8890     strategy < 0 || strategy > Z_FIXED) {
8891     return err(strm, Z_STREAM_ERROR);
8892   }
8893
8894
8895   if (windowBits === 8) {
8896     windowBits = 9;
8897   }
8898   /* until 256-byte window bug fixed */
8899
8900   var s = new DeflateState();
8901
8902   strm.state = s;
8903   s.strm = strm;
8904
8905   s.wrap = wrap;
8906   s.gzhead = null;
8907   s.w_bits = windowBits;
8908   s.w_size = 1 << s.w_bits;
8909   s.w_mask = s.w_size - 1;
8910
8911   s.hash_bits = memLevel + 7;
8912   s.hash_size = 1 << s.hash_bits;
8913   s.hash_mask = s.hash_size - 1;
8914   s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
8915
8916   s.window = new utils.Buf8(s.w_size * 2);
8917   s.head = new utils.Buf16(s.hash_size);
8918   s.prev = new utils.Buf16(s.w_size);
8919
8920   // Don't need mem init magic for JS.
8921   //s.high_water = 0;  /* nothing written to s->window yet */
8922
8923   s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
8924
8925   s.pending_buf_size = s.lit_bufsize * 4;
8926
8927   //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
8928   //s->pending_buf = (uchf *) overlay;
8929   s.pending_buf = new utils.Buf8(s.pending_buf_size);
8930
8931   // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
8932   //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
8933   s.d_buf = 1 * s.lit_bufsize;
8934
8935   //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
8936   s.l_buf = (1 + 2) * s.lit_bufsize;
8937
8938   s.level = level;
8939   s.strategy = strategy;
8940   s.method = method;
8941
8942   return deflateReset(strm);
8943 }
8944
8945 function deflateInit(strm, level) {
8946   return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
8947 }
8948
8949
8950 function deflate(strm, flush) {
8951   var old_flush, s;
8952   var beg, val; // for gzip header write only
8953
8954   if (!strm || !strm.state ||
8955     flush > Z_BLOCK || flush < 0) {
8956     return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
8957   }
8958
8959   s = strm.state;
8960
8961   if (!strm.output ||
8962       (!strm.input && strm.avail_in !== 0) ||
8963       (s.status === FINISH_STATE && flush !== Z_FINISH)) {
8964     return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
8965   }
8966
8967   s.strm = strm; /* just in case */
8968   old_flush = s.last_flush;
8969   s.last_flush = flush;
8970
8971   /* Write the header */
8972   if (s.status === INIT_STATE) {
8973
8974     if (s.wrap === 2) { // GZIP header
8975       strm.adler = 0;  //crc32(0L, Z_NULL, 0);
8976       put_byte(s, 31);
8977       put_byte(s, 139);
8978       put_byte(s, 8);
8979       if (!s.gzhead) { // s->gzhead == Z_NULL
8980         put_byte(s, 0);
8981         put_byte(s, 0);
8982         put_byte(s, 0);
8983         put_byte(s, 0);
8984         put_byte(s, 0);
8985         put_byte(s, s.level === 9 ? 2 :
8986                     (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
8987                      4 : 0));
8988         put_byte(s, OS_CODE);
8989         s.status = BUSY_STATE;
8990       }
8991       else {
8992         put_byte(s, (s.gzhead.text ? 1 : 0) +
8993                     (s.gzhead.hcrc ? 2 : 0) +
8994                     (!s.gzhead.extra ? 0 : 4) +
8995                     (!s.gzhead.name ? 0 : 8) +
8996                     (!s.gzhead.comment ? 0 : 16)
8997         );
8998         put_byte(s, s.gzhead.time & 0xff);
8999         put_byte(s, (s.gzhead.time >> 8) & 0xff);
9000         put_byte(s, (s.gzhead.time >> 16) & 0xff);
9001         put_byte(s, (s.gzhead.time >> 24) & 0xff);
9002         put_byte(s, s.level === 9 ? 2 :
9003                     (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
9004                      4 : 0));
9005         put_byte(s, s.gzhead.os & 0xff);
9006         if (s.gzhead.extra && s.gzhead.extra.length) {
9007           put_byte(s, s.gzhead.extra.length & 0xff);
9008           put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
9009         }
9010         if (s.gzhead.hcrc) {
9011           strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
9012         }
9013         s.gzindex = 0;
9014         s.status = EXTRA_STATE;
9015       }
9016     }
9017     else // DEFLATE header
9018     {
9019       var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
9020       var level_flags = -1;
9021
9022       if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
9023         level_flags = 0;
9024       } else if (s.level < 6) {
9025         level_flags = 1;
9026       } else if (s.level === 6) {
9027         level_flags = 2;
9028       } else {
9029         level_flags = 3;
9030       }
9031       header |= (level_flags << 6);
9032       if (s.strstart !== 0) { header |= PRESET_DICT; }
9033       header += 31 - (header % 31);
9034
9035       s.status = BUSY_STATE;
9036       putShortMSB(s, header);
9037
9038       /* Save the adler32 of the preset dictionary: */
9039       if (s.strstart !== 0) {
9040         putShortMSB(s, strm.adler >>> 16);
9041         putShortMSB(s, strm.adler & 0xffff);
9042       }
9043       strm.adler = 1; // adler32(0L, Z_NULL, 0);
9044     }
9045   }
9046
9047 //#ifdef GZIP
9048   if (s.status === EXTRA_STATE) {
9049     if (s.gzhead.extra/* != Z_NULL*/) {
9050       beg = s.pending;  /* start of bytes to update crc */
9051
9052       while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
9053         if (s.pending === s.pending_buf_size) {
9054           if (s.gzhead.hcrc && s.pending > beg) {
9055             strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9056           }
9057           flush_pending(strm);
9058           beg = s.pending;
9059           if (s.pending === s.pending_buf_size) {
9060             break;
9061           }
9062         }
9063         put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
9064         s.gzindex++;
9065       }
9066       if (s.gzhead.hcrc && s.pending > beg) {
9067         strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9068       }
9069       if (s.gzindex === s.gzhead.extra.length) {
9070         s.gzindex = 0;
9071         s.status = NAME_STATE;
9072       }
9073     }
9074     else {
9075       s.status = NAME_STATE;
9076     }
9077   }
9078   if (s.status === NAME_STATE) {
9079     if (s.gzhead.name/* != Z_NULL*/) {
9080       beg = s.pending;  /* start of bytes to update crc */
9081       //int val;
9082
9083       do {
9084         if (s.pending === s.pending_buf_size) {
9085           if (s.gzhead.hcrc && s.pending > beg) {
9086             strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9087           }
9088           flush_pending(strm);
9089           beg = s.pending;
9090           if (s.pending === s.pending_buf_size) {
9091             val = 1;
9092             break;
9093           }
9094         }
9095         // JS specific: little magic to add zero terminator to end of string
9096         if (s.gzindex < s.gzhead.name.length) {
9097           val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
9098         } else {
9099           val = 0;
9100         }
9101         put_byte(s, val);
9102       } while (val !== 0);
9103
9104       if (s.gzhead.hcrc && s.pending > beg) {
9105         strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9106       }
9107       if (val === 0) {
9108         s.gzindex = 0;
9109         s.status = COMMENT_STATE;
9110       }
9111     }
9112     else {
9113       s.status = COMMENT_STATE;
9114     }
9115   }
9116   if (s.status === COMMENT_STATE) {
9117     if (s.gzhead.comment/* != Z_NULL*/) {
9118       beg = s.pending;  /* start of bytes to update crc */
9119       //int val;
9120
9121       do {
9122         if (s.pending === s.pending_buf_size) {
9123           if (s.gzhead.hcrc && s.pending > beg) {
9124             strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9125           }
9126           flush_pending(strm);
9127           beg = s.pending;
9128           if (s.pending === s.pending_buf_size) {
9129             val = 1;
9130             break;
9131           }
9132         }
9133         // JS specific: little magic to add zero terminator to end of string
9134         if (s.gzindex < s.gzhead.comment.length) {
9135           val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
9136         } else {
9137           val = 0;
9138         }
9139         put_byte(s, val);
9140       } while (val !== 0);
9141
9142       if (s.gzhead.hcrc && s.pending > beg) {
9143         strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9144       }
9145       if (val === 0) {
9146         s.status = HCRC_STATE;
9147       }
9148     }
9149     else {
9150       s.status = HCRC_STATE;
9151     }
9152   }
9153   if (s.status === HCRC_STATE) {
9154     if (s.gzhead.hcrc) {
9155       if (s.pending + 2 > s.pending_buf_size) {
9156         flush_pending(strm);
9157       }
9158       if (s.pending + 2 <= s.pending_buf_size) {
9159         put_byte(s, strm.adler & 0xff);
9160         put_byte(s, (strm.adler >> 8) & 0xff);
9161         strm.adler = 0; //crc32(0L, Z_NULL, 0);
9162         s.status = BUSY_STATE;
9163       }
9164     }
9165     else {
9166       s.status = BUSY_STATE;
9167     }
9168   }
9169 //#endif
9170
9171   /* Flush as much pending output as possible */
9172   if (s.pending !== 0) {
9173     flush_pending(strm);
9174     if (strm.avail_out === 0) {
9175       /* Since avail_out is 0, deflate will be called again with
9176        * more output space, but possibly with both pending and
9177        * avail_in equal to zero. There won't be anything to do,
9178        * but this is not an error situation so make sure we
9179        * return OK instead of BUF_ERROR at next call of deflate:
9180        */
9181       s.last_flush = -1;
9182       return Z_OK;
9183     }
9184
9185     /* Make sure there is something to do and avoid duplicate consecutive
9186      * flushes. For repeated and useless calls with Z_FINISH, we keep
9187      * returning Z_STREAM_END instead of Z_BUF_ERROR.
9188      */
9189   } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
9190     flush !== Z_FINISH) {
9191     return err(strm, Z_BUF_ERROR);
9192   }
9193
9194   /* User must not provide more input after the first FINISH: */
9195   if (s.status === FINISH_STATE && strm.avail_in !== 0) {
9196     return err(strm, Z_BUF_ERROR);
9197   }
9198
9199   /* Start a new block or continue the current one.
9200    */
9201   if (strm.avail_in !== 0 || s.lookahead !== 0 ||
9202     (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
9203     var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
9204       (s.strategy === Z_RLE ? deflate_rle(s, flush) :
9205         configuration_table[s.level].func(s, flush));
9206
9207     if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
9208       s.status = FINISH_STATE;
9209     }
9210     if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
9211       if (strm.avail_out === 0) {
9212         s.last_flush = -1;
9213         /* avoid BUF_ERROR next call, see above */
9214       }
9215       return Z_OK;
9216       /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
9217        * of deflate should use the same flush parameter to make sure
9218        * that the flush is complete. So we don't have to output an
9219        * empty block here, this will be done at next call. This also
9220        * ensures that for a very small output buffer, we emit at most
9221        * one empty block.
9222        */
9223     }
9224     if (bstate === BS_BLOCK_DONE) {
9225       if (flush === Z_PARTIAL_FLUSH) {
9226         trees._tr_align(s);
9227       }
9228       else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
9229
9230         trees._tr_stored_block(s, 0, 0, false);
9231         /* For a full flush, this empty block will be recognized
9232          * as a special marker by inflate_sync().
9233          */
9234         if (flush === Z_FULL_FLUSH) {
9235           /*** CLEAR_HASH(s); ***/             /* forget history */
9236           zero(s.head); // Fill with NIL (= 0);
9237
9238           if (s.lookahead === 0) {
9239             s.strstart = 0;
9240             s.block_start = 0;
9241             s.insert = 0;
9242           }
9243         }
9244       }
9245       flush_pending(strm);
9246       if (strm.avail_out === 0) {
9247         s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
9248         return Z_OK;
9249       }
9250     }
9251   }
9252   //Assert(strm->avail_out > 0, "bug2");
9253   //if (strm.avail_out <= 0) { throw new Error("bug2");}
9254
9255   if (flush !== Z_FINISH) { return Z_OK; }
9256   if (s.wrap <= 0) { return Z_STREAM_END; }
9257
9258   /* Write the trailer */
9259   if (s.wrap === 2) {
9260     put_byte(s, strm.adler & 0xff);
9261     put_byte(s, (strm.adler >> 8) & 0xff);
9262     put_byte(s, (strm.adler >> 16) & 0xff);
9263     put_byte(s, (strm.adler >> 24) & 0xff);
9264     put_byte(s, strm.total_in & 0xff);
9265     put_byte(s, (strm.total_in >> 8) & 0xff);
9266     put_byte(s, (strm.total_in >> 16) & 0xff);
9267     put_byte(s, (strm.total_in >> 24) & 0xff);
9268   }
9269   else
9270   {
9271     putShortMSB(s, strm.adler >>> 16);
9272     putShortMSB(s, strm.adler & 0xffff);
9273   }
9274
9275   flush_pending(strm);
9276   /* If avail_out is zero, the application will call deflate again
9277    * to flush the rest.
9278    */
9279   if (s.wrap > 0) { s.wrap = -s.wrap; }
9280   /* write the trailer only once! */
9281   return s.pending !== 0 ? Z_OK : Z_STREAM_END;
9282 }
9283
9284 function deflateEnd(strm) {
9285   var status;
9286
9287   if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
9288     return Z_STREAM_ERROR;
9289   }
9290
9291   status = strm.state.status;
9292   if (status !== INIT_STATE &&
9293     status !== EXTRA_STATE &&
9294     status !== NAME_STATE &&
9295     status !== COMMENT_STATE &&
9296     status !== HCRC_STATE &&
9297     status !== BUSY_STATE &&
9298     status !== FINISH_STATE
9299   ) {
9300     return err(strm, Z_STREAM_ERROR);
9301   }
9302
9303   strm.state = null;
9304
9305   return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
9306 }
9307
9308
9309 /* =========================================================================
9310  * Initializes the compression dictionary from the given byte
9311  * sequence without producing any compressed output.
9312  */
9313 function deflateSetDictionary(strm, dictionary) {
9314   var dictLength = dictionary.length;
9315
9316   var s;
9317   var str, n;
9318   var wrap;
9319   var avail;
9320   var next;
9321   var input;
9322   var tmpDict;
9323
9324   if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
9325     return Z_STREAM_ERROR;
9326   }
9327
9328   s = strm.state;
9329   wrap = s.wrap;
9330
9331   if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
9332     return Z_STREAM_ERROR;
9333   }
9334
9335   /* when using zlib wrappers, compute Adler-32 for provided dictionary */
9336   if (wrap === 1) {
9337     /* adler32(strm->adler, dictionary, dictLength); */
9338     strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
9339   }
9340
9341   s.wrap = 0;   /* avoid computing Adler-32 in read_buf */
9342
9343   /* if dictionary would fill window, just replace the history */
9344   if (dictLength >= s.w_size) {
9345     if (wrap === 0) {            /* already empty otherwise */
9346       /*** CLEAR_HASH(s); ***/
9347       zero(s.head); // Fill with NIL (= 0);
9348       s.strstart = 0;
9349       s.block_start = 0;
9350       s.insert = 0;
9351     }
9352     /* use the tail */
9353     // dictionary = dictionary.slice(dictLength - s.w_size);
9354     tmpDict = new utils.Buf8(s.w_size);
9355     utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
9356     dictionary = tmpDict;
9357     dictLength = s.w_size;
9358   }
9359   /* insert dictionary into window and hash */
9360   avail = strm.avail_in;
9361   next = strm.next_in;
9362   input = strm.input;
9363   strm.avail_in = dictLength;
9364   strm.next_in = 0;
9365   strm.input = dictionary;
9366   fill_window(s);
9367   while (s.lookahead >= MIN_MATCH) {
9368     str = s.strstart;
9369     n = s.lookahead - (MIN_MATCH - 1);
9370     do {
9371       /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
9372       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
9373
9374       s.prev[str & s.w_mask] = s.head[s.ins_h];
9375
9376       s.head[s.ins_h] = str;
9377       str++;
9378     } while (--n);
9379     s.strstart = str;
9380     s.lookahead = MIN_MATCH - 1;
9381     fill_window(s);
9382   }
9383   s.strstart += s.lookahead;
9384   s.block_start = s.strstart;
9385   s.insert = s.lookahead;
9386   s.lookahead = 0;
9387   s.match_length = s.prev_length = MIN_MATCH - 1;
9388   s.match_available = 0;
9389   strm.next_in = next;
9390   strm.input = input;
9391   strm.avail_in = avail;
9392   s.wrap = wrap;
9393   return Z_OK;
9394 }
9395
9396
9397 exports.deflateInit = deflateInit;
9398 exports.deflateInit2 = deflateInit2;
9399 exports.deflateReset = deflateReset;
9400 exports.deflateResetKeep = deflateResetKeep;
9401 exports.deflateSetHeader = deflateSetHeader;
9402 exports.deflate = deflate;
9403 exports.deflateEnd = deflateEnd;
9404 exports.deflateSetDictionary = deflateSetDictionary;
9405 exports.deflateInfo = 'pako deflate (from Nodeca project)';
9406
9407 /* Not implemented
9408 exports.deflateBound = deflateBound;
9409 exports.deflateCopy = deflateCopy;
9410 exports.deflateParams = deflateParams;
9411 exports.deflatePending = deflatePending;
9412 exports.deflatePrime = deflatePrime;
9413 exports.deflateTune = deflateTune;
9414 */
9415
9416 },{"../utils/common":39,"./adler32":40,"./crc32":42,"./messages":47,"./trees":48}],44:[function(require,module,exports){
9417 'use strict';
9418
9419 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
9420 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
9421 //
9422 // This software is provided 'as-is', without any express or implied
9423 // warranty. In no event will the authors be held liable for any damages
9424 // arising from the use of this software.
9425 //
9426 // Permission is granted to anyone to use this software for any purpose,
9427 // including commercial applications, and to alter it and redistribute it
9428 // freely, subject to the following restrictions:
9429 //
9430 // 1. The origin of this software must not be misrepresented; you must not
9431 //   claim that you wrote the original software. If you use this software
9432 //   in a product, an acknowledgment in the product documentation would be
9433 //   appreciated but is not required.
9434 // 2. Altered source versions must be plainly marked as such, and must not be
9435 //   misrepresented as being the original software.
9436 // 3. This notice may not be removed or altered from any source distribution.
9437
9438 // See state defs from inflate.js
9439 var BAD = 30;       /* got a data error -- remain here until reset */
9440 var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
9441
9442 /*
9443    Decode literal, length, and distance codes and write out the resulting
9444    literal and match bytes until either not enough input or output is
9445    available, an end-of-block is encountered, or a data error is encountered.
9446    When large enough input and output buffers are supplied to inflate(), for
9447    example, a 16K input buffer and a 64K output buffer, more than 95% of the
9448    inflate execution time is spent in this routine.
9449
9450    Entry assumptions:
9451
9452         state.mode === LEN
9453         strm.avail_in >= 6
9454         strm.avail_out >= 258
9455         start >= strm.avail_out
9456         state.bits < 8
9457
9458    On return, state.mode is one of:
9459
9460         LEN -- ran out of enough output space or enough available input
9461         TYPE -- reached end of block code, inflate() to interpret next block
9462         BAD -- error in block data
9463
9464    Notes:
9465
9466     - The maximum input bits used by a length/distance pair is 15 bits for the
9467       length code, 5 bits for the length extra, 15 bits for the distance code,
9468       and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
9469       Therefore if strm.avail_in >= 6, then there is enough input to avoid
9470       checking for available input while decoding.
9471
9472     - The maximum bytes that a single length/distance pair can output is 258
9473       bytes, which is the maximum length that can be coded.  inflate_fast()
9474       requires strm.avail_out >= 258 for each loop to avoid checking for
9475       output space.
9476  */
9477 module.exports = function inflate_fast(strm, start) {
9478   var state;
9479   var _in;                    /* local strm.input */
9480   var last;                   /* have enough input while in < last */
9481   var _out;                   /* local strm.output */
9482   var beg;                    /* inflate()'s initial strm.output */
9483   var end;                    /* while out < end, enough space available */
9484 //#ifdef INFLATE_STRICT
9485   var dmax;                   /* maximum distance from zlib header */
9486 //#endif
9487   var wsize;                  /* window size or zero if not using window */
9488   var whave;                  /* valid bytes in the window */
9489   var wnext;                  /* window write index */
9490   // Use `s_window` instead `window`, avoid conflict with instrumentation tools
9491   var s_window;               /* allocated sliding window, if wsize != 0 */
9492   var hold;                   /* local strm.hold */
9493   var bits;                   /* local strm.bits */
9494   var lcode;                  /* local strm.lencode */
9495   var dcode;                  /* local strm.distcode */
9496   var lmask;                  /* mask for first level of length codes */
9497   var dmask;                  /* mask for first level of distance codes */
9498   var here;                   /* retrieved table entry */
9499   var op;                     /* code bits, operation, extra bits, or */
9500                               /*  window position, window bytes to copy */
9501   var len;                    /* match length, unused bytes */
9502   var dist;                   /* match distance */
9503   var from;                   /* where to copy match from */
9504   var from_source;
9505
9506
9507   var input, output; // JS specific, because we have no pointers
9508
9509   /* copy state to local variables */
9510   state = strm.state;
9511   //here = state.here;
9512   _in = strm.next_in;
9513   input = strm.input;
9514   last = _in + (strm.avail_in - 5);
9515   _out = strm.next_out;
9516   output = strm.output;
9517   beg = _out - (start - strm.avail_out);
9518   end = _out + (strm.avail_out - 257);
9519 //#ifdef INFLATE_STRICT
9520   dmax = state.dmax;
9521 //#endif
9522   wsize = state.wsize;
9523   whave = state.whave;
9524   wnext = state.wnext;
9525   s_window = state.window;
9526   hold = state.hold;
9527   bits = state.bits;
9528   lcode = state.lencode;
9529   dcode = state.distcode;
9530   lmask = (1 << state.lenbits) - 1;
9531   dmask = (1 << state.distbits) - 1;
9532
9533
9534   /* decode literals and length/distances until end-of-block or not enough
9535      input data or output space */
9536
9537   top:
9538   do {
9539     if (bits < 15) {
9540       hold += input[_in++] << bits;
9541       bits += 8;
9542       hold += input[_in++] << bits;
9543       bits += 8;
9544     }
9545
9546     here = lcode[hold & lmask];
9547
9548     dolen:
9549     for (;;) { // Goto emulation
9550       op = here >>> 24/*here.bits*/;
9551       hold >>>= op;
9552       bits -= op;
9553       op = (here >>> 16) & 0xff/*here.op*/;
9554       if (op === 0) {                          /* literal */
9555         //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
9556         //        "inflate:         literal '%c'\n" :
9557         //        "inflate:         literal 0x%02x\n", here.val));
9558         output[_out++] = here & 0xffff/*here.val*/;
9559       }
9560       else if (op & 16) {                     /* length base */
9561         len = here & 0xffff/*here.val*/;
9562         op &= 15;                           /* number of extra bits */
9563         if (op) {
9564           if (bits < op) {
9565             hold += input[_in++] << bits;
9566             bits += 8;
9567           }
9568           len += hold & ((1 << op) - 1);
9569           hold >>>= op;
9570           bits -= op;
9571         }
9572         //Tracevv((stderr, "inflate:         length %u\n", len));
9573         if (bits < 15) {
9574           hold += input[_in++] << bits;
9575           bits += 8;
9576           hold += input[_in++] << bits;
9577           bits += 8;
9578         }
9579         here = dcode[hold & dmask];
9580
9581         dodist:
9582         for (;;) { // goto emulation
9583           op = here >>> 24/*here.bits*/;
9584           hold >>>= op;
9585           bits -= op;
9586           op = (here >>> 16) & 0xff/*here.op*/;
9587
9588           if (op & 16) {                      /* distance base */
9589             dist = here & 0xffff/*here.val*/;
9590             op &= 15;                       /* number of extra bits */
9591             if (bits < op) {
9592               hold += input[_in++] << bits;
9593               bits += 8;
9594               if (bits < op) {
9595                 hold += input[_in++] << bits;
9596                 bits += 8;
9597               }
9598             }
9599             dist += hold & ((1 << op) - 1);
9600 //#ifdef INFLATE_STRICT
9601             if (dist > dmax) {
9602               strm.msg = 'invalid distance too far back';
9603               state.mode = BAD;
9604               break top;
9605             }
9606 //#endif
9607             hold >>>= op;
9608             bits -= op;
9609             //Tracevv((stderr, "inflate:         distance %u\n", dist));
9610             op = _out - beg;                /* max distance in output */
9611             if (dist > op) {                /* see if copy from window */
9612               op = dist - op;               /* distance back in window */
9613               if (op > whave) {
9614                 if (state.sane) {
9615                   strm.msg = 'invalid distance too far back';
9616                   state.mode = BAD;
9617                   break top;
9618                 }
9619
9620 // (!) This block is disabled in zlib defaults,
9621 // don't enable it for binary compatibility
9622 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
9623 //                if (len <= op - whave) {
9624 //                  do {
9625 //                    output[_out++] = 0;
9626 //                  } while (--len);
9627 //                  continue top;
9628 //                }
9629 //                len -= op - whave;
9630 //                do {
9631 //                  output[_out++] = 0;
9632 //                } while (--op > whave);
9633 //                if (op === 0) {
9634 //                  from = _out - dist;
9635 //                  do {
9636 //                    output[_out++] = output[from++];
9637 //                  } while (--len);
9638 //                  continue top;
9639 //                }
9640 //#endif
9641               }
9642               from = 0; // window index
9643               from_source = s_window;
9644               if (wnext === 0) {           /* very common case */
9645                 from += wsize - op;
9646                 if (op < len) {         /* some from window */
9647                   len -= op;
9648                   do {
9649                     output[_out++] = s_window[from++];
9650                   } while (--op);
9651                   from = _out - dist;  /* rest from output */
9652                   from_source = output;
9653                 }
9654               }
9655               else if (wnext < op) {      /* wrap around window */
9656                 from += wsize + wnext - op;
9657                 op -= wnext;
9658                 if (op < len) {         /* some from end of window */
9659                   len -= op;
9660                   do {
9661                     output[_out++] = s_window[from++];
9662                   } while (--op);
9663                   from = 0;
9664                   if (wnext < len) {  /* some from start of window */
9665                     op = wnext;
9666                     len -= op;
9667                     do {
9668                       output[_out++] = s_window[from++];
9669                     } while (--op);
9670                     from = _out - dist;      /* rest from output */
9671                     from_source = output;
9672                   }
9673                 }
9674               }
9675               else {                      /* contiguous in window */
9676                 from += wnext - op;
9677                 if (op < len) {         /* some from window */
9678                   len -= op;
9679                   do {
9680                     output[_out++] = s_window[from++];
9681                   } while (--op);
9682                   from = _out - dist;  /* rest from output */
9683                   from_source = output;
9684                 }
9685               }
9686               while (len > 2) {
9687                 output[_out++] = from_source[from++];
9688                 output[_out++] = from_source[from++];
9689                 output[_out++] = from_source[from++];
9690                 len -= 3;
9691               }
9692               if (len) {
9693                 output[_out++] = from_source[from++];
9694                 if (len > 1) {
9695                   output[_out++] = from_source[from++];
9696                 }
9697               }
9698             }
9699             else {
9700               from = _out - dist;          /* copy direct from output */
9701               do {                        /* minimum length is three */
9702                 output[_out++] = output[from++];
9703                 output[_out++] = output[from++];
9704                 output[_out++] = output[from++];
9705                 len -= 3;
9706               } while (len > 2);
9707               if (len) {
9708                 output[_out++] = output[from++];
9709                 if (len > 1) {
9710                   output[_out++] = output[from++];
9711                 }
9712               }
9713             }
9714           }
9715           else if ((op & 64) === 0) {          /* 2nd level distance code */
9716             here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
9717             continue dodist;
9718           }
9719           else {
9720             strm.msg = 'invalid distance code';
9721             state.mode = BAD;
9722             break top;
9723           }
9724
9725           break; // need to emulate goto via "continue"
9726         }
9727       }
9728       else if ((op & 64) === 0) {              /* 2nd level length code */
9729         here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
9730         continue dolen;
9731       }
9732       else if (op & 32) {                     /* end-of-block */
9733         //Tracevv((stderr, "inflate:         end of block\n"));
9734         state.mode = TYPE;
9735         break top;
9736       }
9737       else {
9738         strm.msg = 'invalid literal/length code';
9739         state.mode = BAD;
9740         break top;
9741       }
9742
9743       break; // need to emulate goto via "continue"
9744     }
9745   } while (_in < last && _out < end);
9746
9747   /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
9748   len = bits >> 3;
9749   _in -= len;
9750   bits -= len << 3;
9751   hold &= (1 << bits) - 1;
9752
9753   /* update state and return */
9754   strm.next_in = _in;
9755   strm.next_out = _out;
9756   strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
9757   strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
9758   state.hold = hold;
9759   state.bits = bits;
9760   return;
9761 };
9762
9763 },{}],45:[function(require,module,exports){
9764 'use strict';
9765
9766 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
9767 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
9768 //
9769 // This software is provided 'as-is', without any express or implied
9770 // warranty. In no event will the authors be held liable for any damages
9771 // arising from the use of this software.
9772 //
9773 // Permission is granted to anyone to use this software for any purpose,
9774 // including commercial applications, and to alter it and redistribute it
9775 // freely, subject to the following restrictions:
9776 //
9777 // 1. The origin of this software must not be misrepresented; you must not
9778 //   claim that you wrote the original software. If you use this software
9779 //   in a product, an acknowledgment in the product documentation would be
9780 //   appreciated but is not required.
9781 // 2. Altered source versions must be plainly marked as such, and must not be
9782 //   misrepresented as being the original software.
9783 // 3. This notice may not be removed or altered from any source distribution.
9784
9785 var utils         = require('../utils/common');
9786 var adler32       = require('./adler32');
9787 var crc32         = require('./crc32');
9788 var inflate_fast  = require('./inffast');
9789 var inflate_table = require('./inftrees');
9790
9791 var CODES = 0;
9792 var LENS = 1;
9793 var DISTS = 2;
9794
9795 /* Public constants ==========================================================*/
9796 /* ===========================================================================*/
9797
9798
9799 /* Allowed flush values; see deflate() and inflate() below for details */
9800 //var Z_NO_FLUSH      = 0;
9801 //var Z_PARTIAL_FLUSH = 1;
9802 //var Z_SYNC_FLUSH    = 2;
9803 //var Z_FULL_FLUSH    = 3;
9804 var Z_FINISH        = 4;
9805 var Z_BLOCK         = 5;
9806 var Z_TREES         = 6;
9807
9808
9809 /* Return codes for the compression/decompression functions. Negative values
9810  * are errors, positive values are used for special but normal events.
9811  */
9812 var Z_OK            = 0;
9813 var Z_STREAM_END    = 1;
9814 var Z_NEED_DICT     = 2;
9815 //var Z_ERRNO         = -1;
9816 var Z_STREAM_ERROR  = -2;
9817 var Z_DATA_ERROR    = -3;
9818 var Z_MEM_ERROR     = -4;
9819 var Z_BUF_ERROR     = -5;
9820 //var Z_VERSION_ERROR = -6;
9821
9822 /* The deflate compression method */
9823 var Z_DEFLATED  = 8;
9824
9825
9826 /* STATES ====================================================================*/
9827 /* ===========================================================================*/
9828
9829
9830 var    HEAD = 1;       /* i: waiting for magic header */
9831 var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
9832 var    TIME = 3;       /* i: waiting for modification time (gzip) */
9833 var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
9834 var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
9835 var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
9836 var    NAME = 7;       /* i: waiting for end of file name (gzip) */
9837 var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
9838 var    HCRC = 9;       /* i: waiting for header crc (gzip) */
9839 var    DICTID = 10;    /* i: waiting for dictionary check value */
9840 var    DICT = 11;      /* waiting for inflateSetDictionary() call */
9841 var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
9842 var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
9843 var        STORED = 14;    /* i: waiting for stored size (length and complement) */
9844 var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
9845 var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
9846 var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
9847 var        LENLENS = 18;   /* i: waiting for code length code lengths */
9848 var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
9849 var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
9850 var            LEN = 21;       /* i: waiting for length/lit/eob code */
9851 var            LENEXT = 22;    /* i: waiting for length extra bits */
9852 var            DIST = 23;      /* i: waiting for distance code */
9853 var            DISTEXT = 24;   /* i: waiting for distance extra bits */
9854 var            MATCH = 25;     /* o: waiting for output space to copy string */
9855 var            LIT = 26;       /* o: waiting for output space to write literal */
9856 var    CHECK = 27;     /* i: waiting for 32-bit check value */
9857 var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
9858 var    DONE = 29;      /* finished check, done -- remain here until reset */
9859 var    BAD = 30;       /* got a data error -- remain here until reset */
9860 var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
9861 var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */
9862
9863 /* ===========================================================================*/
9864
9865
9866
9867 var ENOUGH_LENS = 852;
9868 var ENOUGH_DISTS = 592;
9869 //var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);
9870
9871 var MAX_WBITS = 15;
9872 /* 32K LZ77 window */
9873 var DEF_WBITS = MAX_WBITS;
9874
9875
9876 function zswap32(q) {
9877   return  (((q >>> 24) & 0xff) +
9878           ((q >>> 8) & 0xff00) +
9879           ((q & 0xff00) << 8) +
9880           ((q & 0xff) << 24));
9881 }
9882
9883
9884 function InflateState() {
9885   this.mode = 0;             /* current inflate mode */
9886   this.last = false;          /* true if processing last block */
9887   this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
9888   this.havedict = false;      /* true if dictionary provided */
9889   this.flags = 0;             /* gzip header method and flags (0 if zlib) */
9890   this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
9891   this.check = 0;             /* protected copy of check value */
9892   this.total = 0;             /* protected copy of output count */
9893   // TODO: may be {}
9894   this.head = null;           /* where to save gzip header information */
9895
9896   /* sliding window */
9897   this.wbits = 0;             /* log base 2 of requested window size */
9898   this.wsize = 0;             /* window size or zero if not using window */
9899   this.whave = 0;             /* valid bytes in the window */
9900   this.wnext = 0;             /* window write index */
9901   this.window = null;         /* allocated sliding window, if needed */
9902
9903   /* bit accumulator */
9904   this.hold = 0;              /* input bit accumulator */
9905   this.bits = 0;              /* number of bits in "in" */
9906
9907   /* for string and stored block copying */
9908   this.length = 0;            /* literal or length of data to copy */
9909   this.offset = 0;            /* distance back to copy string from */
9910
9911   /* for table and code decoding */
9912   this.extra = 0;             /* extra bits needed */
9913
9914   /* fixed and dynamic code tables */
9915   this.lencode = null;          /* starting table for length/literal codes */
9916   this.distcode = null;         /* starting table for distance codes */
9917   this.lenbits = 0;           /* index bits for lencode */
9918   this.distbits = 0;          /* index bits for distcode */
9919
9920   /* dynamic table building */
9921   this.ncode = 0;             /* number of code length code lengths */
9922   this.nlen = 0;              /* number of length code lengths */
9923   this.ndist = 0;             /* number of distance code lengths */
9924   this.have = 0;              /* number of code lengths in lens[] */
9925   this.next = null;              /* next available space in codes[] */
9926
9927   this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
9928   this.work = new utils.Buf16(288); /* work area for code table building */
9929
9930   /*
9931    because we don't have pointers in js, we use lencode and distcode directly
9932    as buffers so we don't need codes
9933   */
9934   //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
9935   this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
9936   this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
9937   this.sane = 0;                   /* if false, allow invalid distance too far */
9938   this.back = 0;                   /* bits back of last unprocessed length/lit */
9939   this.was = 0;                    /* initial length of match */
9940 }
9941
9942 function inflateResetKeep(strm) {
9943   var state;
9944
9945   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
9946   state = strm.state;
9947   strm.total_in = strm.total_out = state.total = 0;
9948   strm.msg = ''; /*Z_NULL*/
9949   if (state.wrap) {       /* to support ill-conceived Java test suite */
9950     strm.adler = state.wrap & 1;
9951   }
9952   state.mode = HEAD;
9953   state.last = 0;
9954   state.havedict = 0;
9955   state.dmax = 32768;
9956   state.head = null/*Z_NULL*/;
9957   state.hold = 0;
9958   state.bits = 0;
9959   //state.lencode = state.distcode = state.next = state.codes;
9960   state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
9961   state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
9962
9963   state.sane = 1;
9964   state.back = -1;
9965   //Tracev((stderr, "inflate: reset\n"));
9966   return Z_OK;
9967 }
9968
9969 function inflateReset(strm) {
9970   var state;
9971
9972   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
9973   state = strm.state;
9974   state.wsize = 0;
9975   state.whave = 0;
9976   state.wnext = 0;
9977   return inflateResetKeep(strm);
9978
9979 }
9980
9981 function inflateReset2(strm, windowBits) {
9982   var wrap;
9983   var state;
9984
9985   /* get the state */
9986   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
9987   state = strm.state;
9988
9989   /* extract wrap request from windowBits parameter */
9990   if (windowBits < 0) {
9991     wrap = 0;
9992     windowBits = -windowBits;
9993   }
9994   else {
9995     wrap = (windowBits >> 4) + 1;
9996     if (windowBits < 48) {
9997       windowBits &= 15;
9998     }
9999   }
10000
10001   /* set number of window bits, free window if different */
10002   if (windowBits && (windowBits < 8 || windowBits > 15)) {
10003     return Z_STREAM_ERROR;
10004   }
10005   if (state.window !== null && state.wbits !== windowBits) {
10006     state.window = null;
10007   }
10008
10009   /* update state and reset the rest of it */
10010   state.wrap = wrap;
10011   state.wbits = windowBits;
10012   return inflateReset(strm);
10013 }
10014
10015 function inflateInit2(strm, windowBits) {
10016   var ret;
10017   var state;
10018
10019   if (!strm) { return Z_STREAM_ERROR; }
10020   //strm.msg = Z_NULL;                 /* in case we return an error */
10021
10022   state = new InflateState();
10023
10024   //if (state === Z_NULL) return Z_MEM_ERROR;
10025   //Tracev((stderr, "inflate: allocated\n"));
10026   strm.state = state;
10027   state.window = null/*Z_NULL*/;
10028   ret = inflateReset2(strm, windowBits);
10029   if (ret !== Z_OK) {
10030     strm.state = null/*Z_NULL*/;
10031   }
10032   return ret;
10033 }
10034
10035 function inflateInit(strm) {
10036   return inflateInit2(strm, DEF_WBITS);
10037 }
10038
10039
10040 /*
10041  Return state with length and distance decoding tables and index sizes set to
10042  fixed code decoding.  Normally this returns fixed tables from inffixed.h.
10043  If BUILDFIXED is defined, then instead this routine builds the tables the
10044  first time it's called, and returns those tables the first time and
10045  thereafter.  This reduces the size of the code by about 2K bytes, in
10046  exchange for a little execution time.  However, BUILDFIXED should not be
10047  used for threaded applications, since the rewriting of the tables and virgin
10048  may not be thread-safe.
10049  */
10050 var virgin = true;
10051
10052 var lenfix, distfix; // We have no pointers in JS, so keep tables separate
10053
10054 function fixedtables(state) {
10055   /* build fixed huffman tables if first call (may not be thread safe) */
10056   if (virgin) {
10057     var sym;
10058
10059     lenfix = new utils.Buf32(512);
10060     distfix = new utils.Buf32(32);
10061
10062     /* literal/length table */
10063     sym = 0;
10064     while (sym < 144) { state.lens[sym++] = 8; }
10065     while (sym < 256) { state.lens[sym++] = 9; }
10066     while (sym < 280) { state.lens[sym++] = 7; }
10067     while (sym < 288) { state.lens[sym++] = 8; }
10068
10069     inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });
10070
10071     /* distance table */
10072     sym = 0;
10073     while (sym < 32) { state.lens[sym++] = 5; }
10074
10075     inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });
10076
10077     /* do this just once */
10078     virgin = false;
10079   }
10080
10081   state.lencode = lenfix;
10082   state.lenbits = 9;
10083   state.distcode = distfix;
10084   state.distbits = 5;
10085 }
10086
10087
10088 /*
10089  Update the window with the last wsize (normally 32K) bytes written before
10090  returning.  If window does not exist yet, create it.  This is only called
10091  when a window is already in use, or when output has been written during this
10092  inflate call, but the end of the deflate stream has not been reached yet.
10093  It is also called to create a window for dictionary data when a dictionary
10094  is loaded.
10095
10096  Providing output buffers larger than 32K to inflate() should provide a speed
10097  advantage, since only the last 32K of output is copied to the sliding window
10098  upon return from inflate(), and since all distances after the first 32K of
10099  output will fall in the output data, making match copies simpler and faster.
10100  The advantage may be dependent on the size of the processor's data caches.
10101  */
10102 function updatewindow(strm, src, end, copy) {
10103   var dist;
10104   var state = strm.state;
10105
10106   /* if it hasn't been done already, allocate space for the window */
10107   if (state.window === null) {
10108     state.wsize = 1 << state.wbits;
10109     state.wnext = 0;
10110     state.whave = 0;
10111
10112     state.window = new utils.Buf8(state.wsize);
10113   }
10114
10115   /* copy state->wsize or less output bytes into the circular window */
10116   if (copy >= state.wsize) {
10117     utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
10118     state.wnext = 0;
10119     state.whave = state.wsize;
10120   }
10121   else {
10122     dist = state.wsize - state.wnext;
10123     if (dist > copy) {
10124       dist = copy;
10125     }
10126     //zmemcpy(state->window + state->wnext, end - copy, dist);
10127     utils.arraySet(state.window, src, end - copy, dist, state.wnext);
10128     copy -= dist;
10129     if (copy) {
10130       //zmemcpy(state->window, end - copy, copy);
10131       utils.arraySet(state.window, src, end - copy, copy, 0);
10132       state.wnext = copy;
10133       state.whave = state.wsize;
10134     }
10135     else {
10136       state.wnext += dist;
10137       if (state.wnext === state.wsize) { state.wnext = 0; }
10138       if (state.whave < state.wsize) { state.whave += dist; }
10139     }
10140   }
10141   return 0;
10142 }
10143
10144 function inflate(strm, flush) {
10145   var state;
10146   var input, output;          // input/output buffers
10147   var next;                   /* next input INDEX */
10148   var put;                    /* next output INDEX */
10149   var have, left;             /* available input and output */
10150   var hold;                   /* bit buffer */
10151   var bits;                   /* bits in bit buffer */
10152   var _in, _out;              /* save starting available input and output */
10153   var copy;                   /* number of stored or match bytes to copy */
10154   var from;                   /* where to copy match bytes from */
10155   var from_source;
10156   var here = 0;               /* current decoding table entry */
10157   var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
10158   //var last;                   /* parent table entry */
10159   var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
10160   var len;                    /* length to copy for repeats, bits to drop */
10161   var ret;                    /* return code */
10162   var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
10163   var opts;
10164
10165   var n; // temporary var for NEED_BITS
10166
10167   var order = /* permutation of code lengths */
10168     [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
10169
10170
10171   if (!strm || !strm.state || !strm.output ||
10172       (!strm.input && strm.avail_in !== 0)) {
10173     return Z_STREAM_ERROR;
10174   }
10175
10176   state = strm.state;
10177   if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */
10178
10179
10180   //--- LOAD() ---
10181   put = strm.next_out;
10182   output = strm.output;
10183   left = strm.avail_out;
10184   next = strm.next_in;
10185   input = strm.input;
10186   have = strm.avail_in;
10187   hold = state.hold;
10188   bits = state.bits;
10189   //---
10190
10191   _in = have;
10192   _out = left;
10193   ret = Z_OK;
10194
10195   inf_leave: // goto emulation
10196   for (;;) {
10197     switch (state.mode) {
10198       case HEAD:
10199         if (state.wrap === 0) {
10200           state.mode = TYPEDO;
10201           break;
10202         }
10203         //=== NEEDBITS(16);
10204         while (bits < 16) {
10205           if (have === 0) { break inf_leave; }
10206           have--;
10207           hold += input[next++] << bits;
10208           bits += 8;
10209         }
10210         //===//
10211         if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
10212           state.check = 0/*crc32(0L, Z_NULL, 0)*/;
10213           //=== CRC2(state.check, hold);
10214           hbuf[0] = hold & 0xff;
10215           hbuf[1] = (hold >>> 8) & 0xff;
10216           state.check = crc32(state.check, hbuf, 2, 0);
10217           //===//
10218
10219           //=== INITBITS();
10220           hold = 0;
10221           bits = 0;
10222           //===//
10223           state.mode = FLAGS;
10224           break;
10225         }
10226         state.flags = 0;           /* expect zlib header */
10227         if (state.head) {
10228           state.head.done = false;
10229         }
10230         if (!(state.wrap & 1) ||   /* check if zlib header allowed */
10231           (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
10232           strm.msg = 'incorrect header check';
10233           state.mode = BAD;
10234           break;
10235         }
10236         if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
10237           strm.msg = 'unknown compression method';
10238           state.mode = BAD;
10239           break;
10240         }
10241         //--- DROPBITS(4) ---//
10242         hold >>>= 4;
10243         bits -= 4;
10244         //---//
10245         len = (hold & 0x0f)/*BITS(4)*/ + 8;
10246         if (state.wbits === 0) {
10247           state.wbits = len;
10248         }
10249         else if (len > state.wbits) {
10250           strm.msg = 'invalid window size';
10251           state.mode = BAD;
10252           break;
10253         }
10254         state.dmax = 1 << len;
10255         //Tracev((stderr, "inflate:   zlib header ok\n"));
10256         strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
10257         state.mode = hold & 0x200 ? DICTID : TYPE;
10258         //=== INITBITS();
10259         hold = 0;
10260         bits = 0;
10261         //===//
10262         break;
10263       case FLAGS:
10264         //=== NEEDBITS(16); */
10265         while (bits < 16) {
10266           if (have === 0) { break inf_leave; }
10267           have--;
10268           hold += input[next++] << bits;
10269           bits += 8;
10270         }
10271         //===//
10272         state.flags = hold;
10273         if ((state.flags & 0xff) !== Z_DEFLATED) {
10274           strm.msg = 'unknown compression method';
10275           state.mode = BAD;
10276           break;
10277         }
10278         if (state.flags & 0xe000) {
10279           strm.msg = 'unknown header flags set';
10280           state.mode = BAD;
10281           break;
10282         }
10283         if (state.head) {
10284           state.head.text = ((hold >> 8) & 1);
10285         }
10286         if (state.flags & 0x0200) {
10287           //=== CRC2(state.check, hold);
10288           hbuf[0] = hold & 0xff;
10289           hbuf[1] = (hold >>> 8) & 0xff;
10290           state.check = crc32(state.check, hbuf, 2, 0);
10291           //===//
10292         }
10293         //=== INITBITS();
10294         hold = 0;
10295         bits = 0;
10296         //===//
10297         state.mode = TIME;
10298         /* falls through */
10299       case TIME:
10300         //=== NEEDBITS(32); */
10301         while (bits < 32) {
10302           if (have === 0) { break inf_leave; }
10303           have--;
10304           hold += input[next++] << bits;
10305           bits += 8;
10306         }
10307         //===//
10308         if (state.head) {
10309           state.head.time = hold;
10310         }
10311         if (state.flags & 0x0200) {
10312           //=== CRC4(state.check, hold)
10313           hbuf[0] = hold & 0xff;
10314           hbuf[1] = (hold >>> 8) & 0xff;
10315           hbuf[2] = (hold >>> 16) & 0xff;
10316           hbuf[3] = (hold >>> 24) & 0xff;
10317           state.check = crc32(state.check, hbuf, 4, 0);
10318           //===
10319         }
10320         //=== INITBITS();
10321         hold = 0;
10322         bits = 0;
10323         //===//
10324         state.mode = OS;
10325         /* falls through */
10326       case OS:
10327         //=== NEEDBITS(16); */
10328         while (bits < 16) {
10329           if (have === 0) { break inf_leave; }
10330           have--;
10331           hold += input[next++] << bits;
10332           bits += 8;
10333         }
10334         //===//
10335         if (state.head) {
10336           state.head.xflags = (hold & 0xff);
10337           state.head.os = (hold >> 8);
10338         }
10339         if (state.flags & 0x0200) {
10340           //=== CRC2(state.check, hold);
10341           hbuf[0] = hold & 0xff;
10342           hbuf[1] = (hold >>> 8) & 0xff;
10343           state.check = crc32(state.check, hbuf, 2, 0);
10344           //===//
10345         }
10346         //=== INITBITS();
10347         hold = 0;
10348         bits = 0;
10349         //===//
10350         state.mode = EXLEN;
10351         /* falls through */
10352       case EXLEN:
10353         if (state.flags & 0x0400) {
10354           //=== NEEDBITS(16); */
10355           while (bits < 16) {
10356             if (have === 0) { break inf_leave; }
10357             have--;
10358             hold += input[next++] << bits;
10359             bits += 8;
10360           }
10361           //===//
10362           state.length = hold;
10363           if (state.head) {
10364             state.head.extra_len = hold;
10365           }
10366           if (state.flags & 0x0200) {
10367             //=== CRC2(state.check, hold);
10368             hbuf[0] = hold & 0xff;
10369             hbuf[1] = (hold >>> 8) & 0xff;
10370             state.check = crc32(state.check, hbuf, 2, 0);
10371             //===//
10372           }
10373           //=== INITBITS();
10374           hold = 0;
10375           bits = 0;
10376           //===//
10377         }
10378         else if (state.head) {
10379           state.head.extra = null/*Z_NULL*/;
10380         }
10381         state.mode = EXTRA;
10382         /* falls through */
10383       case EXTRA:
10384         if (state.flags & 0x0400) {
10385           copy = state.length;
10386           if (copy > have) { copy = have; }
10387           if (copy) {
10388             if (state.head) {
10389               len = state.head.extra_len - state.length;
10390               if (!state.head.extra) {
10391                 // Use untyped array for more convenient processing later
10392                 state.head.extra = new Array(state.head.extra_len);
10393               }
10394               utils.arraySet(
10395                 state.head.extra,
10396                 input,
10397                 next,
10398                 // extra field is limited to 65536 bytes
10399                 // - no need for additional size check
10400                 copy,
10401                 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
10402                 len
10403               );
10404               //zmemcpy(state.head.extra + len, next,
10405               //        len + copy > state.head.extra_max ?
10406               //        state.head.extra_max - len : copy);
10407             }
10408             if (state.flags & 0x0200) {
10409               state.check = crc32(state.check, input, copy, next);
10410             }
10411             have -= copy;
10412             next += copy;
10413             state.length -= copy;
10414           }
10415           if (state.length) { break inf_leave; }
10416         }
10417         state.length = 0;
10418         state.mode = NAME;
10419         /* falls through */
10420       case NAME:
10421         if (state.flags & 0x0800) {
10422           if (have === 0) { break inf_leave; }
10423           copy = 0;
10424           do {
10425             // TODO: 2 or 1 bytes?
10426             len = input[next + copy++];
10427             /* use constant limit because in js we should not preallocate memory */
10428             if (state.head && len &&
10429                 (state.length < 65536 /*state.head.name_max*/)) {
10430               state.head.name += String.fromCharCode(len);
10431             }
10432           } while (len && copy < have);
10433
10434           if (state.flags & 0x0200) {
10435             state.check = crc32(state.check, input, copy, next);
10436           }
10437           have -= copy;
10438           next += copy;
10439           if (len) { break inf_leave; }
10440         }
10441         else if (state.head) {
10442           state.head.name = null;
10443         }
10444         state.length = 0;
10445         state.mode = COMMENT;
10446         /* falls through */
10447       case COMMENT:
10448         if (state.flags & 0x1000) {
10449           if (have === 0) { break inf_leave; }
10450           copy = 0;
10451           do {
10452             len = input[next + copy++];
10453             /* use constant limit because in js we should not preallocate memory */
10454             if (state.head && len &&
10455                 (state.length < 65536 /*state.head.comm_max*/)) {
10456               state.head.comment += String.fromCharCode(len);
10457             }
10458           } while (len && copy < have);
10459           if (state.flags & 0x0200) {
10460             state.check = crc32(state.check, input, copy, next);
10461           }
10462           have -= copy;
10463           next += copy;
10464           if (len) { break inf_leave; }
10465         }
10466         else if (state.head) {
10467           state.head.comment = null;
10468         }
10469         state.mode = HCRC;
10470         /* falls through */
10471       case HCRC:
10472         if (state.flags & 0x0200) {
10473           //=== NEEDBITS(16); */
10474           while (bits < 16) {
10475             if (have === 0) { break inf_leave; }
10476             have--;
10477             hold += input[next++] << bits;
10478             bits += 8;
10479           }
10480           //===//
10481           if (hold !== (state.check & 0xffff)) {
10482             strm.msg = 'header crc mismatch';
10483             state.mode = BAD;
10484             break;
10485           }
10486           //=== INITBITS();
10487           hold = 0;
10488           bits = 0;
10489           //===//
10490         }
10491         if (state.head) {
10492           state.head.hcrc = ((state.flags >> 9) & 1);
10493           state.head.done = true;
10494         }
10495         strm.adler = state.check = 0;
10496         state.mode = TYPE;
10497         break;
10498       case DICTID:
10499         //=== NEEDBITS(32); */
10500         while (bits < 32) {
10501           if (have === 0) { break inf_leave; }
10502           have--;
10503           hold += input[next++] << bits;
10504           bits += 8;
10505         }
10506         //===//
10507         strm.adler = state.check = zswap32(hold);
10508         //=== INITBITS();
10509         hold = 0;
10510         bits = 0;
10511         //===//
10512         state.mode = DICT;
10513         /* falls through */
10514       case DICT:
10515         if (state.havedict === 0) {
10516           //--- RESTORE() ---
10517           strm.next_out = put;
10518           strm.avail_out = left;
10519           strm.next_in = next;
10520           strm.avail_in = have;
10521           state.hold = hold;
10522           state.bits = bits;
10523           //---
10524           return Z_NEED_DICT;
10525         }
10526         strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
10527         state.mode = TYPE;
10528         /* falls through */
10529       case TYPE:
10530         if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
10531         /* falls through */
10532       case TYPEDO:
10533         if (state.last) {
10534           //--- BYTEBITS() ---//
10535           hold >>>= bits & 7;
10536           bits -= bits & 7;
10537           //---//
10538           state.mode = CHECK;
10539           break;
10540         }
10541         //=== NEEDBITS(3); */
10542         while (bits < 3) {
10543           if (have === 0) { break inf_leave; }
10544           have--;
10545           hold += input[next++] << bits;
10546           bits += 8;
10547         }
10548         //===//
10549         state.last = (hold & 0x01)/*BITS(1)*/;
10550         //--- DROPBITS(1) ---//
10551         hold >>>= 1;
10552         bits -= 1;
10553         //---//
10554
10555         switch ((hold & 0x03)/*BITS(2)*/) {
10556           case 0:                             /* stored block */
10557             //Tracev((stderr, "inflate:     stored block%s\n",
10558             //        state.last ? " (last)" : ""));
10559             state.mode = STORED;
10560             break;
10561           case 1:                             /* fixed block */
10562             fixedtables(state);
10563             //Tracev((stderr, "inflate:     fixed codes block%s\n",
10564             //        state.last ? " (last)" : ""));
10565             state.mode = LEN_;             /* decode codes */
10566             if (flush === Z_TREES) {
10567               //--- DROPBITS(2) ---//
10568               hold >>>= 2;
10569               bits -= 2;
10570               //---//
10571               break inf_leave;
10572             }
10573             break;
10574           case 2:                             /* dynamic block */
10575             //Tracev((stderr, "inflate:     dynamic codes block%s\n",
10576             //        state.last ? " (last)" : ""));
10577             state.mode = TABLE;
10578             break;
10579           case 3:
10580             strm.msg = 'invalid block type';
10581             state.mode = BAD;
10582         }
10583         //--- DROPBITS(2) ---//
10584         hold >>>= 2;
10585         bits -= 2;
10586         //---//
10587         break;
10588       case STORED:
10589         //--- BYTEBITS() ---// /* go to byte boundary */
10590         hold >>>= bits & 7;
10591         bits -= bits & 7;
10592         //---//
10593         //=== NEEDBITS(32); */
10594         while (bits < 32) {
10595           if (have === 0) { break inf_leave; }
10596           have--;
10597           hold += input[next++] << bits;
10598           bits += 8;
10599         }
10600         //===//
10601         if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
10602           strm.msg = 'invalid stored block lengths';
10603           state.mode = BAD;
10604           break;
10605         }
10606         state.length = hold & 0xffff;
10607         //Tracev((stderr, "inflate:       stored length %u\n",
10608         //        state.length));
10609         //=== INITBITS();
10610         hold = 0;
10611         bits = 0;
10612         //===//
10613         state.mode = COPY_;
10614         if (flush === Z_TREES) { break inf_leave; }
10615         /* falls through */
10616       case COPY_:
10617         state.mode = COPY;
10618         /* falls through */
10619       case COPY:
10620         copy = state.length;
10621         if (copy) {
10622           if (copy > have) { copy = have; }
10623           if (copy > left) { copy = left; }
10624           if (copy === 0) { break inf_leave; }
10625           //--- zmemcpy(put, next, copy); ---
10626           utils.arraySet(output, input, next, copy, put);
10627           //---//
10628           have -= copy;
10629           next += copy;
10630           left -= copy;
10631           put += copy;
10632           state.length -= copy;
10633           break;
10634         }
10635         //Tracev((stderr, "inflate:       stored end\n"));
10636         state.mode = TYPE;
10637         break;
10638       case TABLE:
10639         //=== NEEDBITS(14); */
10640         while (bits < 14) {
10641           if (have === 0) { break inf_leave; }
10642           have--;
10643           hold += input[next++] << bits;
10644           bits += 8;
10645         }
10646         //===//
10647         state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
10648         //--- DROPBITS(5) ---//
10649         hold >>>= 5;
10650         bits -= 5;
10651         //---//
10652         state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
10653         //--- DROPBITS(5) ---//
10654         hold >>>= 5;
10655         bits -= 5;
10656         //---//
10657         state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
10658         //--- DROPBITS(4) ---//
10659         hold >>>= 4;
10660         bits -= 4;
10661         //---//
10662 //#ifndef PKZIP_BUG_WORKAROUND
10663         if (state.nlen > 286 || state.ndist > 30) {
10664           strm.msg = 'too many length or distance symbols';
10665           state.mode = BAD;
10666           break;
10667         }
10668 //#endif
10669         //Tracev((stderr, "inflate:       table sizes ok\n"));
10670         state.have = 0;
10671         state.mode = LENLENS;
10672         /* falls through */
10673       case LENLENS:
10674         while (state.have < state.ncode) {
10675           //=== NEEDBITS(3);
10676           while (bits < 3) {
10677             if (have === 0) { break inf_leave; }
10678             have--;
10679             hold += input[next++] << bits;
10680             bits += 8;
10681           }
10682           //===//
10683           state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
10684           //--- DROPBITS(3) ---//
10685           hold >>>= 3;
10686           bits -= 3;
10687           //---//
10688         }
10689         while (state.have < 19) {
10690           state.lens[order[state.have++]] = 0;
10691         }
10692         // We have separate tables & no pointers. 2 commented lines below not needed.
10693         //state.next = state.codes;
10694         //state.lencode = state.next;
10695         // Switch to use dynamic table
10696         state.lencode = state.lendyn;
10697         state.lenbits = 7;
10698
10699         opts = { bits: state.lenbits };
10700         ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
10701         state.lenbits = opts.bits;
10702
10703         if (ret) {
10704           strm.msg = 'invalid code lengths set';
10705           state.mode = BAD;
10706           break;
10707         }
10708         //Tracev((stderr, "inflate:       code lengths ok\n"));
10709         state.have = 0;
10710         state.mode = CODELENS;
10711         /* falls through */
10712       case CODELENS:
10713         while (state.have < state.nlen + state.ndist) {
10714           for (;;) {
10715             here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
10716             here_bits = here >>> 24;
10717             here_op = (here >>> 16) & 0xff;
10718             here_val = here & 0xffff;
10719
10720             if ((here_bits) <= bits) { break; }
10721             //--- PULLBYTE() ---//
10722             if (have === 0) { break inf_leave; }
10723             have--;
10724             hold += input[next++] << bits;
10725             bits += 8;
10726             //---//
10727           }
10728           if (here_val < 16) {
10729             //--- DROPBITS(here.bits) ---//
10730             hold >>>= here_bits;
10731             bits -= here_bits;
10732             //---//
10733             state.lens[state.have++] = here_val;
10734           }
10735           else {
10736             if (here_val === 16) {
10737               //=== NEEDBITS(here.bits + 2);
10738               n = here_bits + 2;
10739               while (bits < n) {
10740                 if (have === 0) { break inf_leave; }
10741                 have--;
10742                 hold += input[next++] << bits;
10743                 bits += 8;
10744               }
10745               //===//
10746               //--- DROPBITS(here.bits) ---//
10747               hold >>>= here_bits;
10748               bits -= here_bits;
10749               //---//
10750               if (state.have === 0) {
10751                 strm.msg = 'invalid bit length repeat';
10752                 state.mode = BAD;
10753                 break;
10754               }
10755               len = state.lens[state.have - 1];
10756               copy = 3 + (hold & 0x03);//BITS(2);
10757               //--- DROPBITS(2) ---//
10758               hold >>>= 2;
10759               bits -= 2;
10760               //---//
10761             }
10762             else if (here_val === 17) {
10763               //=== NEEDBITS(here.bits + 3);
10764               n = here_bits + 3;
10765               while (bits < n) {
10766                 if (have === 0) { break inf_leave; }
10767                 have--;
10768                 hold += input[next++] << bits;
10769                 bits += 8;
10770               }
10771               //===//
10772               //--- DROPBITS(here.bits) ---//
10773               hold >>>= here_bits;
10774               bits -= here_bits;
10775               //---//
10776               len = 0;
10777               copy = 3 + (hold & 0x07);//BITS(3);
10778               //--- DROPBITS(3) ---//
10779               hold >>>= 3;
10780               bits -= 3;
10781               //---//
10782             }
10783             else {
10784               //=== NEEDBITS(here.bits + 7);
10785               n = here_bits + 7;
10786               while (bits < n) {
10787                 if (have === 0) { break inf_leave; }
10788                 have--;
10789                 hold += input[next++] << bits;
10790                 bits += 8;
10791               }
10792               //===//
10793               //--- DROPBITS(here.bits) ---//
10794               hold >>>= here_bits;
10795               bits -= here_bits;
10796               //---//
10797               len = 0;
10798               copy = 11 + (hold & 0x7f);//BITS(7);
10799               //--- DROPBITS(7) ---//
10800               hold >>>= 7;
10801               bits -= 7;
10802               //---//
10803             }
10804             if (state.have + copy > state.nlen + state.ndist) {
10805               strm.msg = 'invalid bit length repeat';
10806               state.mode = BAD;
10807               break;
10808             }
10809             while (copy--) {
10810               state.lens[state.have++] = len;
10811             }
10812           }
10813         }
10814
10815         /* handle error breaks in while */
10816         if (state.mode === BAD) { break; }
10817
10818         /* check for end-of-block code (better have one) */
10819         if (state.lens[256] === 0) {
10820           strm.msg = 'invalid code -- missing end-of-block';
10821           state.mode = BAD;
10822           break;
10823         }
10824
10825         /* build code tables -- note: do not change the lenbits or distbits
10826            values here (9 and 6) without reading the comments in inftrees.h
10827            concerning the ENOUGH constants, which depend on those values */
10828         state.lenbits = 9;
10829
10830         opts = { bits: state.lenbits };
10831         ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
10832         // We have separate tables & no pointers. 2 commented lines below not needed.
10833         // state.next_index = opts.table_index;
10834         state.lenbits = opts.bits;
10835         // state.lencode = state.next;
10836
10837         if (ret) {
10838           strm.msg = 'invalid literal/lengths set';
10839           state.mode = BAD;
10840           break;
10841         }
10842
10843         state.distbits = 6;
10844         //state.distcode.copy(state.codes);
10845         // Switch to use dynamic table
10846         state.distcode = state.distdyn;
10847         opts = { bits: state.distbits };
10848         ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
10849         // We have separate tables & no pointers. 2 commented lines below not needed.
10850         // state.next_index = opts.table_index;
10851         state.distbits = opts.bits;
10852         // state.distcode = state.next;
10853
10854         if (ret) {
10855           strm.msg = 'invalid distances set';
10856           state.mode = BAD;
10857           break;
10858         }
10859         //Tracev((stderr, 'inflate:       codes ok\n'));
10860         state.mode = LEN_;
10861         if (flush === Z_TREES) { break inf_leave; }
10862         /* falls through */
10863       case LEN_:
10864         state.mode = LEN;
10865         /* falls through */
10866       case LEN:
10867         if (have >= 6 && left >= 258) {
10868           //--- RESTORE() ---
10869           strm.next_out = put;
10870           strm.avail_out = left;
10871           strm.next_in = next;
10872           strm.avail_in = have;
10873           state.hold = hold;
10874           state.bits = bits;
10875           //---
10876           inflate_fast(strm, _out);
10877           //--- LOAD() ---
10878           put = strm.next_out;
10879           output = strm.output;
10880           left = strm.avail_out;
10881           next = strm.next_in;
10882           input = strm.input;
10883           have = strm.avail_in;
10884           hold = state.hold;
10885           bits = state.bits;
10886           //---
10887
10888           if (state.mode === TYPE) {
10889             state.back = -1;
10890           }
10891           break;
10892         }
10893         state.back = 0;
10894         for (;;) {
10895           here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
10896           here_bits = here >>> 24;
10897           here_op = (here >>> 16) & 0xff;
10898           here_val = here & 0xffff;
10899
10900           if (here_bits <= bits) { break; }
10901           //--- PULLBYTE() ---//
10902           if (have === 0) { break inf_leave; }
10903           have--;
10904           hold += input[next++] << bits;
10905           bits += 8;
10906           //---//
10907         }
10908         if (here_op && (here_op & 0xf0) === 0) {
10909           last_bits = here_bits;
10910           last_op = here_op;
10911           last_val = here_val;
10912           for (;;) {
10913             here = state.lencode[last_val +
10914                     ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
10915             here_bits = here >>> 24;
10916             here_op = (here >>> 16) & 0xff;
10917             here_val = here & 0xffff;
10918
10919             if ((last_bits + here_bits) <= bits) { break; }
10920             //--- PULLBYTE() ---//
10921             if (have === 0) { break inf_leave; }
10922             have--;
10923             hold += input[next++] << bits;
10924             bits += 8;
10925             //---//
10926           }
10927           //--- DROPBITS(last.bits) ---//
10928           hold >>>= last_bits;
10929           bits -= last_bits;
10930           //---//
10931           state.back += last_bits;
10932         }
10933         //--- DROPBITS(here.bits) ---//
10934         hold >>>= here_bits;
10935         bits -= here_bits;
10936         //---//
10937         state.back += here_bits;
10938         state.length = here_val;
10939         if (here_op === 0) {
10940           //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
10941           //        "inflate:         literal '%c'\n" :
10942           //        "inflate:         literal 0x%02x\n", here.val));
10943           state.mode = LIT;
10944           break;
10945         }
10946         if (here_op & 32) {
10947           //Tracevv((stderr, "inflate:         end of block\n"));
10948           state.back = -1;
10949           state.mode = TYPE;
10950           break;
10951         }
10952         if (here_op & 64) {
10953           strm.msg = 'invalid literal/length code';
10954           state.mode = BAD;
10955           break;
10956         }
10957         state.extra = here_op & 15;
10958         state.mode = LENEXT;
10959         /* falls through */
10960       case LENEXT:
10961         if (state.extra) {
10962           //=== NEEDBITS(state.extra);
10963           n = state.extra;
10964           while (bits < n) {
10965             if (have === 0) { break inf_leave; }
10966             have--;
10967             hold += input[next++] << bits;
10968             bits += 8;
10969           }
10970           //===//
10971           state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
10972           //--- DROPBITS(state.extra) ---//
10973           hold >>>= state.extra;
10974           bits -= state.extra;
10975           //---//
10976           state.back += state.extra;
10977         }
10978         //Tracevv((stderr, "inflate:         length %u\n", state.length));
10979         state.was = state.length;
10980         state.mode = DIST;
10981         /* falls through */
10982       case DIST:
10983         for (;;) {
10984           here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
10985           here_bits = here >>> 24;
10986           here_op = (here >>> 16) & 0xff;
10987           here_val = here & 0xffff;
10988
10989           if ((here_bits) <= bits) { break; }
10990           //--- PULLBYTE() ---//
10991           if (have === 0) { break inf_leave; }
10992           have--;
10993           hold += input[next++] << bits;
10994           bits += 8;
10995           //---//
10996         }
10997         if ((here_op & 0xf0) === 0) {
10998           last_bits = here_bits;
10999           last_op = here_op;
11000           last_val = here_val;
11001           for (;;) {
11002             here = state.distcode[last_val +
11003                     ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
11004             here_bits = here >>> 24;
11005             here_op = (here >>> 16) & 0xff;
11006             here_val = here & 0xffff;
11007
11008             if ((last_bits + here_bits) <= bits) { break; }
11009             //--- PULLBYTE() ---//
11010             if (have === 0) { break inf_leave; }
11011             have--;
11012             hold += input[next++] << bits;
11013             bits += 8;
11014             //---//
11015           }
11016           //--- DROPBITS(last.bits) ---//
11017           hold >>>= last_bits;
11018           bits -= last_bits;
11019           //---//
11020           state.back += last_bits;
11021         }
11022         //--- DROPBITS(here.bits) ---//
11023         hold >>>= here_bits;
11024         bits -= here_bits;
11025         //---//
11026         state.back += here_bits;
11027         if (here_op & 64) {
11028           strm.msg = 'invalid distance code';
11029           state.mode = BAD;
11030           break;
11031         }
11032         state.offset = here_val;
11033         state.extra = (here_op) & 15;
11034         state.mode = DISTEXT;
11035         /* falls through */
11036       case DISTEXT:
11037         if (state.extra) {
11038           //=== NEEDBITS(state.extra);
11039           n = state.extra;
11040           while (bits < n) {
11041             if (have === 0) { break inf_leave; }
11042             have--;
11043             hold += input[next++] << bits;
11044             bits += 8;
11045           }
11046           //===//
11047           state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
11048           //--- DROPBITS(state.extra) ---//
11049           hold >>>= state.extra;
11050           bits -= state.extra;
11051           //---//
11052           state.back += state.extra;
11053         }
11054 //#ifdef INFLATE_STRICT
11055         if (state.offset > state.dmax) {
11056           strm.msg = 'invalid distance too far back';
11057           state.mode = BAD;
11058           break;
11059         }
11060 //#endif
11061         //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
11062         state.mode = MATCH;
11063         /* falls through */
11064       case MATCH:
11065         if (left === 0) { break inf_leave; }
11066         copy = _out - left;
11067         if (state.offset > copy) {         /* copy from window */
11068           copy = state.offset - copy;
11069           if (copy > state.whave) {
11070             if (state.sane) {
11071               strm.msg = 'invalid distance too far back';
11072               state.mode = BAD;
11073               break;
11074             }
11075 // (!) This block is disabled in zlib defaults,
11076 // don't enable it for binary compatibility
11077 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
11078 //          Trace((stderr, "inflate.c too far\n"));
11079 //          copy -= state.whave;
11080 //          if (copy > state.length) { copy = state.length; }
11081 //          if (copy > left) { copy = left; }
11082 //          left -= copy;
11083 //          state.length -= copy;
11084 //          do {
11085 //            output[put++] = 0;
11086 //          } while (--copy);
11087 //          if (state.length === 0) { state.mode = LEN; }
11088 //          break;
11089 //#endif
11090           }
11091           if (copy > state.wnext) {
11092             copy -= state.wnext;
11093             from = state.wsize - copy;
11094           }
11095           else {
11096             from = state.wnext - copy;
11097           }
11098           if (copy > state.length) { copy = state.length; }
11099           from_source = state.window;
11100         }
11101         else {                              /* copy from output */
11102           from_source = output;
11103           from = put - state.offset;
11104           copy = state.length;
11105         }
11106         if (copy > left) { copy = left; }
11107         left -= copy;
11108         state.length -= copy;
11109         do {
11110           output[put++] = from_source[from++];
11111         } while (--copy);
11112         if (state.length === 0) { state.mode = LEN; }
11113         break;
11114       case LIT:
11115         if (left === 0) { break inf_leave; }
11116         output[put++] = state.length;
11117         left--;
11118         state.mode = LEN;
11119         break;
11120       case CHECK:
11121         if (state.wrap) {
11122           //=== NEEDBITS(32);
11123           while (bits < 32) {
11124             if (have === 0) { break inf_leave; }
11125             have--;
11126             // Use '|' instead of '+' to make sure that result is signed
11127             hold |= input[next++] << bits;
11128             bits += 8;
11129           }
11130           //===//
11131           _out -= left;
11132           strm.total_out += _out;
11133           state.total += _out;
11134           if (_out) {
11135             strm.adler = state.check =
11136                 /*UPDATE(state.check, put - _out, _out);*/
11137                 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
11138
11139           }
11140           _out = left;
11141           // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
11142           if ((state.flags ? hold : zswap32(hold)) !== state.check) {
11143             strm.msg = 'incorrect data check';
11144             state.mode = BAD;
11145             break;
11146           }
11147           //=== INITBITS();
11148           hold = 0;
11149           bits = 0;
11150           //===//
11151           //Tracev((stderr, "inflate:   check matches trailer\n"));
11152         }
11153         state.mode = LENGTH;
11154         /* falls through */
11155       case LENGTH:
11156         if (state.wrap && state.flags) {
11157           //=== NEEDBITS(32);
11158           while (bits < 32) {
11159             if (have === 0) { break inf_leave; }
11160             have--;
11161             hold += input[next++] << bits;
11162             bits += 8;
11163           }
11164           //===//
11165           if (hold !== (state.total & 0xffffffff)) {
11166             strm.msg = 'incorrect length check';
11167             state.mode = BAD;
11168             break;
11169           }
11170           //=== INITBITS();
11171           hold = 0;
11172           bits = 0;
11173           //===//
11174           //Tracev((stderr, "inflate:   length matches trailer\n"));
11175         }
11176         state.mode = DONE;
11177         /* falls through */
11178       case DONE:
11179         ret = Z_STREAM_END;
11180         break inf_leave;
11181       case BAD:
11182         ret = Z_DATA_ERROR;
11183         break inf_leave;
11184       case MEM:
11185         return Z_MEM_ERROR;
11186       case SYNC:
11187         /* falls through */
11188       default:
11189         return Z_STREAM_ERROR;
11190     }
11191   }
11192
11193   // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
11194
11195   /*
11196      Return from inflate(), updating the total counts and the check value.
11197      If there was no progress during the inflate() call, return a buffer
11198      error.  Call updatewindow() to create and/or update the window state.
11199      Note: a memory error from inflate() is non-recoverable.
11200    */
11201
11202   //--- RESTORE() ---
11203   strm.next_out = put;
11204   strm.avail_out = left;
11205   strm.next_in = next;
11206   strm.avail_in = have;
11207   state.hold = hold;
11208   state.bits = bits;
11209   //---
11210
11211   if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
11212                       (state.mode < CHECK || flush !== Z_FINISH))) {
11213     if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
11214       state.mode = MEM;
11215       return Z_MEM_ERROR;
11216     }
11217   }
11218   _in -= strm.avail_in;
11219   _out -= strm.avail_out;
11220   strm.total_in += _in;
11221   strm.total_out += _out;
11222   state.total += _out;
11223   if (state.wrap && _out) {
11224     strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
11225       (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
11226   }
11227   strm.data_type = state.bits + (state.last ? 64 : 0) +
11228                     (state.mode === TYPE ? 128 : 0) +
11229                     (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
11230   if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
11231     ret = Z_BUF_ERROR;
11232   }
11233   return ret;
11234 }
11235
11236 function inflateEnd(strm) {
11237
11238   if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
11239     return Z_STREAM_ERROR;
11240   }
11241
11242   var state = strm.state;
11243   if (state.window) {
11244     state.window = null;
11245   }
11246   strm.state = null;
11247   return Z_OK;
11248 }
11249
11250 function inflateGetHeader(strm, head) {
11251   var state;
11252
11253   /* check state */
11254   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
11255   state = strm.state;
11256   if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
11257
11258   /* save header structure */
11259   state.head = head;
11260   head.done = false;
11261   return Z_OK;
11262 }
11263
11264 function inflateSetDictionary(strm, dictionary) {
11265   var dictLength = dictionary.length;
11266
11267   var state;
11268   var dictid;
11269   var ret;
11270
11271   /* check state */
11272   if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
11273   state = strm.state;
11274
11275   if (state.wrap !== 0 && state.mode !== DICT) {
11276     return Z_STREAM_ERROR;
11277   }
11278
11279   /* check for correct dictionary identifier */
11280   if (state.mode === DICT) {
11281     dictid = 1; /* adler32(0, null, 0)*/
11282     /* dictid = adler32(dictid, dictionary, dictLength); */
11283     dictid = adler32(dictid, dictionary, dictLength, 0);
11284     if (dictid !== state.check) {
11285       return Z_DATA_ERROR;
11286     }
11287   }
11288   /* copy dictionary to window using updatewindow(), which will amend the
11289    existing dictionary if appropriate */
11290   ret = updatewindow(strm, dictionary, dictLength, dictLength);
11291   if (ret) {
11292     state.mode = MEM;
11293     return Z_MEM_ERROR;
11294   }
11295   state.havedict = 1;
11296   // Tracev((stderr, "inflate:   dictionary set\n"));
11297   return Z_OK;
11298 }
11299
11300 exports.inflateReset = inflateReset;
11301 exports.inflateReset2 = inflateReset2;
11302 exports.inflateResetKeep = inflateResetKeep;
11303 exports.inflateInit = inflateInit;
11304 exports.inflateInit2 = inflateInit2;
11305 exports.inflate = inflate;
11306 exports.inflateEnd = inflateEnd;
11307 exports.inflateGetHeader = inflateGetHeader;
11308 exports.inflateSetDictionary = inflateSetDictionary;
11309 exports.inflateInfo = 'pako inflate (from Nodeca project)';
11310
11311 /* Not implemented
11312 exports.inflateCopy = inflateCopy;
11313 exports.inflateGetDictionary = inflateGetDictionary;
11314 exports.inflateMark = inflateMark;
11315 exports.inflatePrime = inflatePrime;
11316 exports.inflateSync = inflateSync;
11317 exports.inflateSyncPoint = inflateSyncPoint;
11318 exports.inflateUndermine = inflateUndermine;
11319 */
11320
11321 },{"../utils/common":39,"./adler32":40,"./crc32":42,"./inffast":44,"./inftrees":46}],46:[function(require,module,exports){
11322 'use strict';
11323
11324 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
11325 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
11326 //
11327 // This software is provided 'as-is', without any express or implied
11328 // warranty. In no event will the authors be held liable for any damages
11329 // arising from the use of this software.
11330 //
11331 // Permission is granted to anyone to use this software for any purpose,
11332 // including commercial applications, and to alter it and redistribute it
11333 // freely, subject to the following restrictions:
11334 //
11335 // 1. The origin of this software must not be misrepresented; you must not
11336 //   claim that you wrote the original software. If you use this software
11337 //   in a product, an acknowledgment in the product documentation would be
11338 //   appreciated but is not required.
11339 // 2. Altered source versions must be plainly marked as such, and must not be
11340 //   misrepresented as being the original software.
11341 // 3. This notice may not be removed or altered from any source distribution.
11342
11343 var utils = require('../utils/common');
11344
11345 var MAXBITS = 15;
11346 var ENOUGH_LENS = 852;
11347 var ENOUGH_DISTS = 592;
11348 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
11349
11350 var CODES = 0;
11351 var LENS = 1;
11352 var DISTS = 2;
11353
11354 var lbase = [ /* Length codes 257..285 base */
11355   3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
11356   35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
11357 ];
11358
11359 var lext = [ /* Length codes 257..285 extra */
11360   16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
11361   19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
11362 ];
11363
11364 var dbase = [ /* Distance codes 0..29 base */
11365   1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
11366   257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
11367   8193, 12289, 16385, 24577, 0, 0
11368 ];
11369
11370 var dext = [ /* Distance codes 0..29 extra */
11371   16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
11372   23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
11373   28, 28, 29, 29, 64, 64
11374 ];
11375
11376 module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
11377 {
11378   var bits = opts.bits;
11379       //here = opts.here; /* table entry for duplication */
11380
11381   var len = 0;               /* a code's length in bits */
11382   var sym = 0;               /* index of code symbols */
11383   var min = 0, max = 0;          /* minimum and maximum code lengths */
11384   var root = 0;              /* number of index bits for root table */
11385   var curr = 0;              /* number of index bits for current table */
11386   var drop = 0;              /* code bits to drop for sub-table */
11387   var left = 0;                   /* number of prefix codes available */
11388   var used = 0;              /* code entries in table used */
11389   var huff = 0;              /* Huffman code */
11390   var incr;              /* for incrementing code, index */
11391   var fill;              /* index for replicating entries */
11392   var low;               /* low bits for current root entry */
11393   var mask;              /* mask for low root bits */
11394   var next;             /* next available space in table */
11395   var base = null;     /* base value table to use */
11396   var base_index = 0;
11397 //  var shoextra;    /* extra bits table to use */
11398   var end;                    /* use base and extra for symbol > end */
11399   var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
11400   var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
11401   var extra = null;
11402   var extra_index = 0;
11403
11404   var here_bits, here_op, here_val;
11405
11406   /*
11407    Process a set of code lengths to create a canonical Huffman code.  The
11408    code lengths are lens[0..codes-1].  Each length corresponds to the
11409    symbols 0..codes-1.  The Huffman code is generated by first sorting the
11410    symbols by length from short to long, and retaining the symbol order
11411    for codes with equal lengths.  Then the code starts with all zero bits
11412    for the first code of the shortest length, and the codes are integer
11413    increments for the same length, and zeros are appended as the length
11414    increases.  For the deflate format, these bits are stored backwards
11415    from their more natural integer increment ordering, and so when the
11416    decoding tables are built in the large loop below, the integer codes
11417    are incremented backwards.
11418
11419    This routine assumes, but does not check, that all of the entries in
11420    lens[] are in the range 0..MAXBITS.  The caller must assure this.
11421    1..MAXBITS is interpreted as that code length.  zero means that that
11422    symbol does not occur in this code.
11423
11424    The codes are sorted by computing a count of codes for each length,
11425    creating from that a table of starting indices for each length in the
11426    sorted table, and then entering the symbols in order in the sorted
11427    table.  The sorted table is work[], with that space being provided by
11428    the caller.
11429
11430    The length counts are used for other purposes as well, i.e. finding
11431    the minimum and maximum length codes, determining if there are any
11432    codes at all, checking for a valid set of lengths, and looking ahead
11433    at length counts to determine sub-table sizes when building the
11434    decoding tables.
11435    */
11436
11437   /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
11438   for (len = 0; len <= MAXBITS; len++) {
11439     count[len] = 0;
11440   }
11441   for (sym = 0; sym < codes; sym++) {
11442     count[lens[lens_index + sym]]++;
11443   }
11444
11445   /* bound code lengths, force root to be within code lengths */
11446   root = bits;
11447   for (max = MAXBITS; max >= 1; max--) {
11448     if (count[max] !== 0) { break; }
11449   }
11450   if (root > max) {
11451     root = max;
11452   }
11453   if (max === 0) {                     /* no symbols to code at all */
11454     //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
11455     //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
11456     //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
11457     table[table_index++] = (1 << 24) | (64 << 16) | 0;
11458
11459
11460     //table.op[opts.table_index] = 64;
11461     //table.bits[opts.table_index] = 1;
11462     //table.val[opts.table_index++] = 0;
11463     table[table_index++] = (1 << 24) | (64 << 16) | 0;
11464
11465     opts.bits = 1;
11466     return 0;     /* no symbols, but wait for decoding to report error */
11467   }
11468   for (min = 1; min < max; min++) {
11469     if (count[min] !== 0) { break; }
11470   }
11471   if (root < min) {
11472     root = min;
11473   }
11474
11475   /* check for an over-subscribed or incomplete set of lengths */
11476   left = 1;
11477   for (len = 1; len <= MAXBITS; len++) {
11478     left <<= 1;
11479     left -= count[len];
11480     if (left < 0) {
11481       return -1;
11482     }        /* over-subscribed */
11483   }
11484   if (left > 0 && (type === CODES || max !== 1)) {
11485     return -1;                      /* incomplete set */
11486   }
11487
11488   /* generate offsets into symbol table for each length for sorting */
11489   offs[1] = 0;
11490   for (len = 1; len < MAXBITS; len++) {
11491     offs[len + 1] = offs[len] + count[len];
11492   }
11493
11494   /* sort symbols by length, by symbol order within each length */
11495   for (sym = 0; sym < codes; sym++) {
11496     if (lens[lens_index + sym] !== 0) {
11497       work[offs[lens[lens_index + sym]]++] = sym;
11498     }
11499   }
11500
11501   /*
11502    Create and fill in decoding tables.  In this loop, the table being
11503    filled is at next and has curr index bits.  The code being used is huff
11504    with length len.  That code is converted to an index by dropping drop
11505    bits off of the bottom.  For codes where len is less than drop + curr,
11506    those top drop + curr - len bits are incremented through all values to
11507    fill the table with replicated entries.
11508
11509    root is the number of index bits for the root table.  When len exceeds
11510    root, sub-tables are created pointed to by the root entry with an index
11511    of the low root bits of huff.  This is saved in low to check for when a
11512    new sub-table should be started.  drop is zero when the root table is
11513    being filled, and drop is root when sub-tables are being filled.
11514
11515    When a new sub-table is needed, it is necessary to look ahead in the
11516    code lengths to determine what size sub-table is needed.  The length
11517    counts are used for this, and so count[] is decremented as codes are
11518    entered in the tables.
11519
11520    used keeps track of how many table entries have been allocated from the
11521    provided *table space.  It is checked for LENS and DIST tables against
11522    the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
11523    the initial root table size constants.  See the comments in inftrees.h
11524    for more information.
11525
11526    sym increments through all symbols, and the loop terminates when
11527    all codes of length max, i.e. all codes, have been processed.  This
11528    routine permits incomplete codes, so another loop after this one fills
11529    in the rest of the decoding tables with invalid code markers.
11530    */
11531
11532   /* set up for code type */
11533   // poor man optimization - use if-else instead of switch,
11534   // to avoid deopts in old v8
11535   if (type === CODES) {
11536     base = extra = work;    /* dummy value--not used */
11537     end = 19;
11538
11539   } else if (type === LENS) {
11540     base = lbase;
11541     base_index -= 257;
11542     extra = lext;
11543     extra_index -= 257;
11544     end = 256;
11545
11546   } else {                    /* DISTS */
11547     base = dbase;
11548     extra = dext;
11549     end = -1;
11550   }
11551
11552   /* initialize opts for loop */
11553   huff = 0;                   /* starting code */
11554   sym = 0;                    /* starting code symbol */
11555   len = min;                  /* starting code length */
11556   next = table_index;              /* current table to fill in */
11557   curr = root;                /* current table index bits */
11558   drop = 0;                   /* current bits to drop from code for index */
11559   low = -1;                   /* trigger new sub-table when len > root */
11560   used = 1 << root;          /* use root table entries */
11561   mask = used - 1;            /* mask for comparing low */
11562
11563   /* check available table space */
11564   if ((type === LENS && used > ENOUGH_LENS) ||
11565     (type === DISTS && used > ENOUGH_DISTS)) {
11566     return 1;
11567   }
11568
11569   /* process all codes and make table entries */
11570   for (;;) {
11571     /* create table entry */
11572     here_bits = len - drop;
11573     if (work[sym] < end) {
11574       here_op = 0;
11575       here_val = work[sym];
11576     }
11577     else if (work[sym] > end) {
11578       here_op = extra[extra_index + work[sym]];
11579       here_val = base[base_index + work[sym]];
11580     }
11581     else {
11582       here_op = 32 + 64;         /* end of block */
11583       here_val = 0;
11584     }
11585
11586     /* replicate for those indices with low len bits equal to huff */
11587     incr = 1 << (len - drop);
11588     fill = 1 << curr;
11589     min = fill;                 /* save offset to next table */
11590     do {
11591       fill -= incr;
11592       table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
11593     } while (fill !== 0);
11594
11595     /* backwards increment the len-bit code huff */
11596     incr = 1 << (len - 1);
11597     while (huff & incr) {
11598       incr >>= 1;
11599     }
11600     if (incr !== 0) {
11601       huff &= incr - 1;
11602       huff += incr;
11603     } else {
11604       huff = 0;
11605     }
11606
11607     /* go to next symbol, update count, len */
11608     sym++;
11609     if (--count[len] === 0) {
11610       if (len === max) { break; }
11611       len = lens[lens_index + work[sym]];
11612     }
11613
11614     /* create new sub-table if needed */
11615     if (len > root && (huff & mask) !== low) {
11616       /* if first time, transition to sub-tables */
11617       if (drop === 0) {
11618         drop = root;
11619       }
11620
11621       /* increment past last table */
11622       next += min;            /* here min is 1 << curr */
11623
11624       /* determine length of next table */
11625       curr = len - drop;
11626       left = 1 << curr;
11627       while (curr + drop < max) {
11628         left -= count[curr + drop];
11629         if (left <= 0) { break; }
11630         curr++;
11631         left <<= 1;
11632       }
11633
11634       /* check for enough space */
11635       used += 1 << curr;
11636       if ((type === LENS && used > ENOUGH_LENS) ||
11637         (type === DISTS && used > ENOUGH_DISTS)) {
11638         return 1;
11639       }
11640
11641       /* point entry in root table to sub-table */
11642       low = huff & mask;
11643       /*table.op[low] = curr;
11644       table.bits[low] = root;
11645       table.val[low] = next - opts.table_index;*/
11646       table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
11647     }
11648   }
11649
11650   /* fill in remaining table entry if code is incomplete (guaranteed to have
11651    at most one remaining entry, since if the code is incomplete, the
11652    maximum code length that was allowed to get this far is one bit) */
11653   if (huff !== 0) {
11654     //table.op[next + huff] = 64;            /* invalid code marker */
11655     //table.bits[next + huff] = len - drop;
11656     //table.val[next + huff] = 0;
11657     table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
11658   }
11659
11660   /* set return parameters */
11661   //opts.table_index += used;
11662   opts.bits = root;
11663   return 0;
11664 };
11665
11666 },{"../utils/common":39}],47:[function(require,module,exports){
11667 'use strict';
11668
11669 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
11670 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
11671 //
11672 // This software is provided 'as-is', without any express or implied
11673 // warranty. In no event will the authors be held liable for any damages
11674 // arising from the use of this software.
11675 //
11676 // Permission is granted to anyone to use this software for any purpose,
11677 // including commercial applications, and to alter it and redistribute it
11678 // freely, subject to the following restrictions:
11679 //
11680 // 1. The origin of this software must not be misrepresented; you must not
11681 //   claim that you wrote the original software. If you use this software
11682 //   in a product, an acknowledgment in the product documentation would be
11683 //   appreciated but is not required.
11684 // 2. Altered source versions must be plainly marked as such, and must not be
11685 //   misrepresented as being the original software.
11686 // 3. This notice may not be removed or altered from any source distribution.
11687
11688 module.exports = {
11689   2:      'need dictionary',     /* Z_NEED_DICT       2  */
11690   1:      'stream end',          /* Z_STREAM_END      1  */
11691   0:      '',                    /* Z_OK              0  */
11692   '-1':   'file error',          /* Z_ERRNO         (-1) */
11693   '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
11694   '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
11695   '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
11696   '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
11697   '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
11698 };
11699
11700 },{}],48:[function(require,module,exports){
11701 'use strict';
11702
11703 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
11704 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
11705 //
11706 // This software is provided 'as-is', without any express or implied
11707 // warranty. In no event will the authors be held liable for any damages
11708 // arising from the use of this software.
11709 //
11710 // Permission is granted to anyone to use this software for any purpose,
11711 // including commercial applications, and to alter it and redistribute it
11712 // freely, subject to the following restrictions:
11713 //
11714 // 1. The origin of this software must not be misrepresented; you must not
11715 //   claim that you wrote the original software. If you use this software
11716 //   in a product, an acknowledgment in the product documentation would be
11717 //   appreciated but is not required.
11718 // 2. Altered source versions must be plainly marked as such, and must not be
11719 //   misrepresented as being the original software.
11720 // 3. This notice may not be removed or altered from any source distribution.
11721
11722 /* eslint-disable space-unary-ops */
11723
11724 var utils = require('../utils/common');
11725
11726 /* Public constants ==========================================================*/
11727 /* ===========================================================================*/
11728
11729
11730 //var Z_FILTERED          = 1;
11731 //var Z_HUFFMAN_ONLY      = 2;
11732 //var Z_RLE               = 3;
11733 var Z_FIXED               = 4;
11734 //var Z_DEFAULT_STRATEGY  = 0;
11735
11736 /* Possible values of the data_type field (though see inflate()) */
11737 var Z_BINARY              = 0;
11738 var Z_TEXT                = 1;
11739 //var Z_ASCII             = 1; // = Z_TEXT
11740 var Z_UNKNOWN             = 2;
11741
11742 /*============================================================================*/
11743
11744
11745 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
11746
11747 // From zutil.h
11748
11749 var STORED_BLOCK = 0;
11750 var STATIC_TREES = 1;
11751 var DYN_TREES    = 2;
11752 /* The three kinds of block type */
11753
11754 var MIN_MATCH    = 3;
11755 var MAX_MATCH    = 258;
11756 /* The minimum and maximum match lengths */
11757
11758 // From deflate.h
11759 /* ===========================================================================
11760  * Internal compression state.
11761  */
11762
11763 var LENGTH_CODES  = 29;
11764 /* number of length codes, not counting the special END_BLOCK code */
11765
11766 var LITERALS      = 256;
11767 /* number of literal bytes 0..255 */
11768
11769 var L_CODES       = LITERALS + 1 + LENGTH_CODES;
11770 /* number of Literal or Length codes, including the END_BLOCK code */
11771
11772 var D_CODES       = 30;
11773 /* number of distance codes */
11774
11775 var BL_CODES      = 19;
11776 /* number of codes used to transfer the bit lengths */
11777
11778 var HEAP_SIZE     = 2 * L_CODES + 1;
11779 /* maximum heap size */
11780
11781 var MAX_BITS      = 15;
11782 /* All codes must not exceed MAX_BITS bits */
11783
11784 var Buf_size      = 16;
11785 /* size of bit buffer in bi_buf */
11786
11787
11788 /* ===========================================================================
11789  * Constants
11790  */
11791
11792 var MAX_BL_BITS = 7;
11793 /* Bit length codes must not exceed MAX_BL_BITS bits */
11794
11795 var END_BLOCK   = 256;
11796 /* end of block literal code */
11797
11798 var REP_3_6     = 16;
11799 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
11800
11801 var REPZ_3_10   = 17;
11802 /* repeat a zero length 3-10 times  (3 bits of repeat count) */
11803
11804 var REPZ_11_138 = 18;
11805 /* repeat a zero length 11-138 times  (7 bits of repeat count) */
11806
11807 /* eslint-disable comma-spacing,array-bracket-spacing */
11808 var extra_lbits =   /* extra bits for each length code */
11809   [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];
11810
11811 var extra_dbits =   /* extra bits for each distance code */
11812   [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];
11813
11814 var extra_blbits =  /* extra bits for each bit length code */
11815   [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
11816
11817 var bl_order =
11818   [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
11819 /* eslint-enable comma-spacing,array-bracket-spacing */
11820
11821 /* The lengths of the bit length codes are sent in order of decreasing
11822  * probability, to avoid transmitting the lengths for unused bit length codes.
11823  */
11824
11825 /* ===========================================================================
11826  * Local data. These are initialized only once.
11827  */
11828
11829 // We pre-fill arrays with 0 to avoid uninitialized gaps
11830
11831 var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
11832
11833 // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
11834 var static_ltree  = new Array((L_CODES + 2) * 2);
11835 zero(static_ltree);
11836 /* The static literal tree. Since the bit lengths are imposed, there is no
11837  * need for the L_CODES extra codes used during heap construction. However
11838  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
11839  * below).
11840  */
11841
11842 var static_dtree  = new Array(D_CODES * 2);
11843 zero(static_dtree);
11844 /* The static distance tree. (Actually a trivial tree since all codes use
11845  * 5 bits.)
11846  */
11847
11848 var _dist_code    = new Array(DIST_CODE_LEN);
11849 zero(_dist_code);
11850 /* Distance codes. The first 256 values correspond to the distances
11851  * 3 .. 258, the last 256 values correspond to the top 8 bits of
11852  * the 15 bit distances.
11853  */
11854
11855 var _length_code  = new Array(MAX_MATCH - MIN_MATCH + 1);
11856 zero(_length_code);
11857 /* length code for each normalized match length (0 == MIN_MATCH) */
11858
11859 var base_length   = new Array(LENGTH_CODES);
11860 zero(base_length);
11861 /* First normalized length for each code (0 = MIN_MATCH) */
11862
11863 var base_dist     = new Array(D_CODES);
11864 zero(base_dist);
11865 /* First normalized distance for each code (0 = distance of 1) */
11866
11867
11868 function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
11869
11870   this.static_tree  = static_tree;  /* static tree or NULL */
11871   this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
11872   this.extra_base   = extra_base;   /* base index for extra_bits */
11873   this.elems        = elems;        /* max number of elements in the tree */
11874   this.max_length   = max_length;   /* max bit length for the codes */
11875
11876   // show if `static_tree` has data or dummy - needed for monomorphic objects
11877   this.has_stree    = static_tree && static_tree.length;
11878 }
11879
11880
11881 var static_l_desc;
11882 var static_d_desc;
11883 var static_bl_desc;
11884
11885
11886 function TreeDesc(dyn_tree, stat_desc) {
11887   this.dyn_tree = dyn_tree;     /* the dynamic tree */
11888   this.max_code = 0;            /* largest code with non zero frequency */
11889   this.stat_desc = stat_desc;   /* the corresponding static tree */
11890 }
11891
11892
11893
11894 function d_code(dist) {
11895   return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
11896 }
11897
11898
11899 /* ===========================================================================
11900  * Output a short LSB first on the stream.
11901  * IN assertion: there is enough room in pendingBuf.
11902  */
11903 function put_short(s, w) {
11904 //    put_byte(s, (uch)((w) & 0xff));
11905 //    put_byte(s, (uch)((ush)(w) >> 8));
11906   s.pending_buf[s.pending++] = (w) & 0xff;
11907   s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
11908 }
11909
11910
11911 /* ===========================================================================
11912  * Send a value on a given number of bits.
11913  * IN assertion: length <= 16 and value fits in length bits.
11914  */
11915 function send_bits(s, value, length) {
11916   if (s.bi_valid > (Buf_size - length)) {
11917     s.bi_buf |= (value << s.bi_valid) & 0xffff;
11918     put_short(s, s.bi_buf);
11919     s.bi_buf = value >> (Buf_size - s.bi_valid);
11920     s.bi_valid += length - Buf_size;
11921   } else {
11922     s.bi_buf |= (value << s.bi_valid) & 0xffff;
11923     s.bi_valid += length;
11924   }
11925 }
11926
11927
11928 function send_code(s, c, tree) {
11929   send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
11930 }
11931
11932
11933 /* ===========================================================================
11934  * Reverse the first len bits of a code, using straightforward code (a faster
11935  * method would use a table)
11936  * IN assertion: 1 <= len <= 15
11937  */
11938 function bi_reverse(code, len) {
11939   var res = 0;
11940   do {
11941     res |= code & 1;
11942     code >>>= 1;
11943     res <<= 1;
11944   } while (--len > 0);
11945   return res >>> 1;
11946 }
11947
11948
11949 /* ===========================================================================
11950  * Flush the bit buffer, keeping at most 7 bits in it.
11951  */
11952 function bi_flush(s) {
11953   if (s.bi_valid === 16) {
11954     put_short(s, s.bi_buf);
11955     s.bi_buf = 0;
11956     s.bi_valid = 0;
11957
11958   } else if (s.bi_valid >= 8) {
11959     s.pending_buf[s.pending++] = s.bi_buf & 0xff;
11960     s.bi_buf >>= 8;
11961     s.bi_valid -= 8;
11962   }
11963 }
11964
11965
11966 /* ===========================================================================
11967  * Compute the optimal bit lengths for a tree and update the total bit length
11968  * for the current block.
11969  * IN assertion: the fields freq and dad are set, heap[heap_max] and
11970  *    above are the tree nodes sorted by increasing frequency.
11971  * OUT assertions: the field len is set to the optimal bit length, the
11972  *     array bl_count contains the frequencies for each bit length.
11973  *     The length opt_len is updated; static_len is also updated if stree is
11974  *     not null.
11975  */
11976 function gen_bitlen(s, desc)
11977 //    deflate_state *s;
11978 //    tree_desc *desc;    /* the tree descriptor */
11979 {
11980   var tree            = desc.dyn_tree;
11981   var max_code        = desc.max_code;
11982   var stree           = desc.stat_desc.static_tree;
11983   var has_stree       = desc.stat_desc.has_stree;
11984   var extra           = desc.stat_desc.extra_bits;
11985   var base            = desc.stat_desc.extra_base;
11986   var max_length      = desc.stat_desc.max_length;
11987   var h;              /* heap index */
11988   var n, m;           /* iterate over the tree elements */
11989   var bits;           /* bit length */
11990   var xbits;          /* extra bits */
11991   var f;              /* frequency */
11992   var overflow = 0;   /* number of elements with bit length too large */
11993
11994   for (bits = 0; bits <= MAX_BITS; bits++) {
11995     s.bl_count[bits] = 0;
11996   }
11997
11998   /* In a first pass, compute the optimal bit lengths (which may
11999    * overflow in the case of the bit length tree).
12000    */
12001   tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
12002
12003   for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
12004     n = s.heap[h];
12005     bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
12006     if (bits > max_length) {
12007       bits = max_length;
12008       overflow++;
12009     }
12010     tree[n * 2 + 1]/*.Len*/ = bits;
12011     /* We overwrite tree[n].Dad which is no longer needed */
12012
12013     if (n > max_code) { continue; } /* not a leaf node */
12014
12015     s.bl_count[bits]++;
12016     xbits = 0;
12017     if (n >= base) {
12018       xbits = extra[n - base];
12019     }
12020     f = tree[n * 2]/*.Freq*/;
12021     s.opt_len += f * (bits + xbits);
12022     if (has_stree) {
12023       s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
12024     }
12025   }
12026   if (overflow === 0) { return; }
12027
12028   // Trace((stderr,"\nbit length overflow\n"));
12029   /* This happens for example on obj2 and pic of the Calgary corpus */
12030
12031   /* Find the first bit length which could increase: */
12032   do {
12033     bits = max_length - 1;
12034     while (s.bl_count[bits] === 0) { bits--; }
12035     s.bl_count[bits]--;      /* move one leaf down the tree */
12036     s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
12037     s.bl_count[max_length]--;
12038     /* The brother of the overflow item also moves one step up,
12039      * but this does not affect bl_count[max_length]
12040      */
12041     overflow -= 2;
12042   } while (overflow > 0);
12043
12044   /* Now recompute all bit lengths, scanning in increasing frequency.
12045    * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
12046    * lengths instead of fixing only the wrong ones. This idea is taken
12047    * from 'ar' written by Haruhiko Okumura.)
12048    */
12049   for (bits = max_length; bits !== 0; bits--) {
12050     n = s.bl_count[bits];
12051     while (n !== 0) {
12052       m = s.heap[--h];
12053       if (m > max_code) { continue; }
12054       if (tree[m * 2 + 1]/*.Len*/ !== bits) {
12055         // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
12056         s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
12057         tree[m * 2 + 1]/*.Len*/ = bits;
12058       }
12059       n--;
12060     }
12061   }
12062 }
12063
12064
12065 /* ===========================================================================
12066  * Generate the codes for a given tree and bit counts (which need not be
12067  * optimal).
12068  * IN assertion: the array bl_count contains the bit length statistics for
12069  * the given tree and the field len is set for all tree elements.
12070  * OUT assertion: the field code is set for all tree elements of non
12071  *     zero code length.
12072  */
12073 function gen_codes(tree, max_code, bl_count)
12074 //    ct_data *tree;             /* the tree to decorate */
12075 //    int max_code;              /* largest code with non zero frequency */
12076 //    ushf *bl_count;            /* number of codes at each bit length */
12077 {
12078   var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
12079   var code = 0;              /* running code value */
12080   var bits;                  /* bit index */
12081   var n;                     /* code index */
12082
12083   /* The distribution counts are first used to generate the code values
12084    * without bit reversal.
12085    */
12086   for (bits = 1; bits <= MAX_BITS; bits++) {
12087     next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
12088   }
12089   /* Check that the bit counts in bl_count are consistent. The last code
12090    * must be all ones.
12091    */
12092   //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
12093   //        "inconsistent bit counts");
12094   //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
12095
12096   for (n = 0;  n <= max_code; n++) {
12097     var len = tree[n * 2 + 1]/*.Len*/;
12098     if (len === 0) { continue; }
12099     /* Now reverse the bits */
12100     tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
12101
12102     //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
12103     //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
12104   }
12105 }
12106
12107
12108 /* ===========================================================================
12109  * Initialize the various 'constant' tables.
12110  */
12111 function tr_static_init() {
12112   var n;        /* iterates over tree elements */
12113   var bits;     /* bit counter */
12114   var length;   /* length value */
12115   var code;     /* code value */
12116   var dist;     /* distance index */
12117   var bl_count = new Array(MAX_BITS + 1);
12118   /* number of codes at each bit length for an optimal tree */
12119
12120   // do check in _tr_init()
12121   //if (static_init_done) return;
12122
12123   /* For some embedded targets, global variables are not initialized: */
12124 /*#ifdef NO_INIT_GLOBAL_POINTERS
12125   static_l_desc.static_tree = static_ltree;
12126   static_l_desc.extra_bits = extra_lbits;
12127   static_d_desc.static_tree = static_dtree;
12128   static_d_desc.extra_bits = extra_dbits;
12129   static_bl_desc.extra_bits = extra_blbits;
12130 #endif*/
12131
12132   /* Initialize the mapping length (0..255) -> length code (0..28) */
12133   length = 0;
12134   for (code = 0; code < LENGTH_CODES - 1; code++) {
12135     base_length[code] = length;
12136     for (n = 0; n < (1 << extra_lbits[code]); n++) {
12137       _length_code[length++] = code;
12138     }
12139   }
12140   //Assert (length == 256, "tr_static_init: length != 256");
12141   /* Note that the length 255 (match length 258) can be represented
12142    * in two different ways: code 284 + 5 bits or code 285, so we
12143    * overwrite length_code[255] to use the best encoding:
12144    */
12145   _length_code[length - 1] = code;
12146
12147   /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
12148   dist = 0;
12149   for (code = 0; code < 16; code++) {
12150     base_dist[code] = dist;
12151     for (n = 0; n < (1 << extra_dbits[code]); n++) {
12152       _dist_code[dist++] = code;
12153     }
12154   }
12155   //Assert (dist == 256, "tr_static_init: dist != 256");
12156   dist >>= 7; /* from now on, all distances are divided by 128 */
12157   for (; code < D_CODES; code++) {
12158     base_dist[code] = dist << 7;
12159     for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
12160       _dist_code[256 + dist++] = code;
12161     }
12162   }
12163   //Assert (dist == 256, "tr_static_init: 256+dist != 512");
12164
12165   /* Construct the codes of the static literal tree */
12166   for (bits = 0; bits <= MAX_BITS; bits++) {
12167     bl_count[bits] = 0;
12168   }
12169
12170   n = 0;
12171   while (n <= 143) {
12172     static_ltree[n * 2 + 1]/*.Len*/ = 8;
12173     n++;
12174     bl_count[8]++;
12175   }
12176   while (n <= 255) {
12177     static_ltree[n * 2 + 1]/*.Len*/ = 9;
12178     n++;
12179     bl_count[9]++;
12180   }
12181   while (n <= 279) {
12182     static_ltree[n * 2 + 1]/*.Len*/ = 7;
12183     n++;
12184     bl_count[7]++;
12185   }
12186   while (n <= 287) {
12187     static_ltree[n * 2 + 1]/*.Len*/ = 8;
12188     n++;
12189     bl_count[8]++;
12190   }
12191   /* Codes 286 and 287 do not exist, but we must include them in the
12192    * tree construction to get a canonical Huffman tree (longest code
12193    * all ones)
12194    */
12195   gen_codes(static_ltree, L_CODES + 1, bl_count);
12196
12197   /* The static distance tree is trivial: */
12198   for (n = 0; n < D_CODES; n++) {
12199     static_dtree[n * 2 + 1]/*.Len*/ = 5;
12200     static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
12201   }
12202
12203   // Now data ready and we can init static trees
12204   static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
12205   static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
12206   static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);
12207
12208   //static_init_done = true;
12209 }
12210
12211
12212 /* ===========================================================================
12213  * Initialize a new block.
12214  */
12215 function init_block(s) {
12216   var n; /* iterates over tree elements */
12217
12218   /* Initialize the trees. */
12219   for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
12220   for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
12221   for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
12222
12223   s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
12224   s.opt_len = s.static_len = 0;
12225   s.last_lit = s.matches = 0;
12226 }
12227
12228
12229 /* ===========================================================================
12230  * Flush the bit buffer and align the output on a byte boundary
12231  */
12232 function bi_windup(s)
12233 {
12234   if (s.bi_valid > 8) {
12235     put_short(s, s.bi_buf);
12236   } else if (s.bi_valid > 0) {
12237     //put_byte(s, (Byte)s->bi_buf);
12238     s.pending_buf[s.pending++] = s.bi_buf;
12239   }
12240   s.bi_buf = 0;
12241   s.bi_valid = 0;
12242 }
12243
12244 /* ===========================================================================
12245  * Copy a stored block, storing first the length and its
12246  * one's complement if requested.
12247  */
12248 function copy_block(s, buf, len, header)
12249 //DeflateState *s;
12250 //charf    *buf;    /* the input data */
12251 //unsigned len;     /* its length */
12252 //int      header;  /* true if block header must be written */
12253 {
12254   bi_windup(s);        /* align on byte boundary */
12255
12256   if (header) {
12257     put_short(s, len);
12258     put_short(s, ~len);
12259   }
12260 //  while (len--) {
12261 //    put_byte(s, *buf++);
12262 //  }
12263   utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
12264   s.pending += len;
12265 }
12266
12267 /* ===========================================================================
12268  * Compares to subtrees, using the tree depth as tie breaker when
12269  * the subtrees have equal frequency. This minimizes the worst case length.
12270  */
12271 function smaller(tree, n, m, depth) {
12272   var _n2 = n * 2;
12273   var _m2 = m * 2;
12274   return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
12275          (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
12276 }
12277
12278 /* ===========================================================================
12279  * Restore the heap property by moving down the tree starting at node k,
12280  * exchanging a node with the smallest of its two sons if necessary, stopping
12281  * when the heap property is re-established (each father smaller than its
12282  * two sons).
12283  */
12284 function pqdownheap(s, tree, k)
12285 //    deflate_state *s;
12286 //    ct_data *tree;  /* the tree to restore */
12287 //    int k;               /* node to move down */
12288 {
12289   var v = s.heap[k];
12290   var j = k << 1;  /* left son of k */
12291   while (j <= s.heap_len) {
12292     /* Set j to the smallest of the two sons: */
12293     if (j < s.heap_len &&
12294       smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
12295       j++;
12296     }
12297     /* Exit if v is smaller than both sons */
12298     if (smaller(tree, v, s.heap[j], s.depth)) { break; }
12299
12300     /* Exchange v with the smallest son */
12301     s.heap[k] = s.heap[j];
12302     k = j;
12303
12304     /* And continue down the tree, setting j to the left son of k */
12305     j <<= 1;
12306   }
12307   s.heap[k] = v;
12308 }
12309
12310
12311 // inlined manually
12312 // var SMALLEST = 1;
12313
12314 /* ===========================================================================
12315  * Send the block data compressed using the given Huffman trees
12316  */
12317 function compress_block(s, ltree, dtree)
12318 //    deflate_state *s;
12319 //    const ct_data *ltree; /* literal tree */
12320 //    const ct_data *dtree; /* distance tree */
12321 {
12322   var dist;           /* distance of matched string */
12323   var lc;             /* match length or unmatched char (if dist == 0) */
12324   var lx = 0;         /* running index in l_buf */
12325   var code;           /* the code to send */
12326   var extra;          /* number of extra bits to send */
12327
12328   if (s.last_lit !== 0) {
12329     do {
12330       dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
12331       lc = s.pending_buf[s.l_buf + lx];
12332       lx++;
12333
12334       if (dist === 0) {
12335         send_code(s, lc, ltree); /* send a literal byte */
12336         //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
12337       } else {
12338         /* Here, lc is the match length - MIN_MATCH */
12339         code = _length_code[lc];
12340         send_code(s, code + LITERALS + 1, ltree); /* send the length code */
12341         extra = extra_lbits[code];
12342         if (extra !== 0) {
12343           lc -= base_length[code];
12344           send_bits(s, lc, extra);       /* send the extra length bits */
12345         }
12346         dist--; /* dist is now the match distance - 1 */
12347         code = d_code(dist);
12348         //Assert (code < D_CODES, "bad d_code");
12349
12350         send_code(s, code, dtree);       /* send the distance code */
12351         extra = extra_dbits[code];
12352         if (extra !== 0) {
12353           dist -= base_dist[code];
12354           send_bits(s, dist, extra);   /* send the extra distance bits */
12355         }
12356       } /* literal or match pair ? */
12357
12358       /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
12359       //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
12360       //       "pendingBuf overflow");
12361
12362     } while (lx < s.last_lit);
12363   }
12364
12365   send_code(s, END_BLOCK, ltree);
12366 }
12367
12368
12369 /* ===========================================================================
12370  * Construct one Huffman tree and assigns the code bit strings and lengths.
12371  * Update the total bit length for the current block.
12372  * IN assertion: the field freq is set for all tree elements.
12373  * OUT assertions: the fields len and code are set to the optimal bit length
12374  *     and corresponding code. The length opt_len is updated; static_len is
12375  *     also updated if stree is not null. The field max_code is set.
12376  */
12377 function build_tree(s, desc)
12378 //    deflate_state *s;
12379 //    tree_desc *desc; /* the tree descriptor */
12380 {
12381   var tree     = desc.dyn_tree;
12382   var stree    = desc.stat_desc.static_tree;
12383   var has_stree = desc.stat_desc.has_stree;
12384   var elems    = desc.stat_desc.elems;
12385   var n, m;          /* iterate over heap elements */
12386   var max_code = -1; /* largest code with non zero frequency */
12387   var node;          /* new node being created */
12388
12389   /* Construct the initial heap, with least frequent element in
12390    * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
12391    * heap[0] is not used.
12392    */
12393   s.heap_len = 0;
12394   s.heap_max = HEAP_SIZE;
12395
12396   for (n = 0; n < elems; n++) {
12397     if (tree[n * 2]/*.Freq*/ !== 0) {
12398       s.heap[++s.heap_len] = max_code = n;
12399       s.depth[n] = 0;
12400
12401     } else {
12402       tree[n * 2 + 1]/*.Len*/ = 0;
12403     }
12404   }
12405
12406   /* The pkzip format requires that at least one distance code exists,
12407    * and that at least one bit should be sent even if there is only one
12408    * possible code. So to avoid special checks later on we force at least
12409    * two codes of non zero frequency.
12410    */
12411   while (s.heap_len < 2) {
12412     node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
12413     tree[node * 2]/*.Freq*/ = 1;
12414     s.depth[node] = 0;
12415     s.opt_len--;
12416
12417     if (has_stree) {
12418       s.static_len -= stree[node * 2 + 1]/*.Len*/;
12419     }
12420     /* node is 0 or 1 so it does not have extra bits */
12421   }
12422   desc.max_code = max_code;
12423
12424   /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
12425    * establish sub-heaps of increasing lengths:
12426    */
12427   for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
12428
12429   /* Construct the Huffman tree by repeatedly combining the least two
12430    * frequent nodes.
12431    */
12432   node = elems;              /* next internal node of the tree */
12433   do {
12434     //pqremove(s, tree, n);  /* n = node of least frequency */
12435     /*** pqremove ***/
12436     n = s.heap[1/*SMALLEST*/];
12437     s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
12438     pqdownheap(s, tree, 1/*SMALLEST*/);
12439     /***/
12440
12441     m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
12442
12443     s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
12444     s.heap[--s.heap_max] = m;
12445
12446     /* Create a new node father of n and m */
12447     tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
12448     s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
12449     tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
12450
12451     /* and insert the new node in the heap */
12452     s.heap[1/*SMALLEST*/] = node++;
12453     pqdownheap(s, tree, 1/*SMALLEST*/);
12454
12455   } while (s.heap_len >= 2);
12456
12457   s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
12458
12459   /* At this point, the fields freq and dad are set. We can now
12460    * generate the bit lengths.
12461    */
12462   gen_bitlen(s, desc);
12463
12464   /* The field len is now set, we can generate the bit codes */
12465   gen_codes(tree, max_code, s.bl_count);
12466 }
12467
12468
12469 /* ===========================================================================
12470  * Scan a literal or distance tree to determine the frequencies of the codes
12471  * in the bit length tree.
12472  */
12473 function scan_tree(s, tree, max_code)
12474 //    deflate_state *s;
12475 //    ct_data *tree;   /* the tree to be scanned */
12476 //    int max_code;    /* and its largest code of non zero frequency */
12477 {
12478   var n;                     /* iterates over all tree elements */
12479   var prevlen = -1;          /* last emitted length */
12480   var curlen;                /* length of current code */
12481
12482   var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
12483
12484   var count = 0;             /* repeat count of the current code */
12485   var max_count = 7;         /* max repeat count */
12486   var min_count = 4;         /* min repeat count */
12487
12488   if (nextlen === 0) {
12489     max_count = 138;
12490     min_count = 3;
12491   }
12492   tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
12493
12494   for (n = 0; n <= max_code; n++) {
12495     curlen = nextlen;
12496     nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
12497
12498     if (++count < max_count && curlen === nextlen) {
12499       continue;
12500
12501     } else if (count < min_count) {
12502       s.bl_tree[curlen * 2]/*.Freq*/ += count;
12503
12504     } else if (curlen !== 0) {
12505
12506       if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
12507       s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
12508
12509     } else if (count <= 10) {
12510       s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
12511
12512     } else {
12513       s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
12514     }
12515
12516     count = 0;
12517     prevlen = curlen;
12518
12519     if (nextlen === 0) {
12520       max_count = 138;
12521       min_count = 3;
12522
12523     } else if (curlen === nextlen) {
12524       max_count = 6;
12525       min_count = 3;
12526
12527     } else {
12528       max_count = 7;
12529       min_count = 4;
12530     }
12531   }
12532 }
12533
12534
12535 /* ===========================================================================
12536  * Send a literal or distance tree in compressed form, using the codes in
12537  * bl_tree.
12538  */
12539 function send_tree(s, tree, max_code)
12540 //    deflate_state *s;
12541 //    ct_data *tree; /* the tree to be scanned */
12542 //    int max_code;       /* and its largest code of non zero frequency */
12543 {
12544   var n;                     /* iterates over all tree elements */
12545   var prevlen = -1;          /* last emitted length */
12546   var curlen;                /* length of current code */
12547
12548   var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
12549
12550   var count = 0;             /* repeat count of the current code */
12551   var max_count = 7;         /* max repeat count */
12552   var min_count = 4;         /* min repeat count */
12553
12554   /* tree[max_code+1].Len = -1; */  /* guard already set */
12555   if (nextlen === 0) {
12556     max_count = 138;
12557     min_count = 3;
12558   }
12559
12560   for (n = 0; n <= max_code; n++) {
12561     curlen = nextlen;
12562     nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
12563
12564     if (++count < max_count && curlen === nextlen) {
12565       continue;
12566
12567     } else if (count < min_count) {
12568       do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
12569
12570     } else if (curlen !== 0) {
12571       if (curlen !== prevlen) {
12572         send_code(s, curlen, s.bl_tree);
12573         count--;
12574       }
12575       //Assert(count >= 3 && count <= 6, " 3_6?");
12576       send_code(s, REP_3_6, s.bl_tree);
12577       send_bits(s, count - 3, 2);
12578
12579     } else if (count <= 10) {
12580       send_code(s, REPZ_3_10, s.bl_tree);
12581       send_bits(s, count - 3, 3);
12582
12583     } else {
12584       send_code(s, REPZ_11_138, s.bl_tree);
12585       send_bits(s, count - 11, 7);
12586     }
12587
12588     count = 0;
12589     prevlen = curlen;
12590     if (nextlen === 0) {
12591       max_count = 138;
12592       min_count = 3;
12593
12594     } else if (curlen === nextlen) {
12595       max_count = 6;
12596       min_count = 3;
12597
12598     } else {
12599       max_count = 7;
12600       min_count = 4;
12601     }
12602   }
12603 }
12604
12605
12606 /* ===========================================================================
12607  * Construct the Huffman tree for the bit lengths and return the index in
12608  * bl_order of the last bit length code to send.
12609  */
12610 function build_bl_tree(s) {
12611   var max_blindex;  /* index of last bit length code of non zero freq */
12612
12613   /* Determine the bit length frequencies for literal and distance trees */
12614   scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
12615   scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
12616
12617   /* Build the bit length tree: */
12618   build_tree(s, s.bl_desc);
12619   /* opt_len now includes the length of the tree representations, except
12620    * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
12621    */
12622
12623   /* Determine the number of bit length codes to send. The pkzip format
12624    * requires that at least 4 bit length codes be sent. (appnote.txt says
12625    * 3 but the actual value used is 4.)
12626    */
12627   for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
12628     if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
12629       break;
12630     }
12631   }
12632   /* Update opt_len to include the bit length tree and counts */
12633   s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
12634   //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
12635   //        s->opt_len, s->static_len));
12636
12637   return max_blindex;
12638 }
12639
12640
12641 /* ===========================================================================
12642  * Send the header for a block using dynamic Huffman trees: the counts, the
12643  * lengths of the bit length codes, the literal tree and the distance tree.
12644  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
12645  */
12646 function send_all_trees(s, lcodes, dcodes, blcodes)
12647 //    deflate_state *s;
12648 //    int lcodes, dcodes, blcodes; /* number of codes for each tree */
12649 {
12650   var rank;                    /* index in bl_order */
12651
12652   //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
12653   //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
12654   //        "too many codes");
12655   //Tracev((stderr, "\nbl counts: "));
12656   send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
12657   send_bits(s, dcodes - 1,   5);
12658   send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
12659   for (rank = 0; rank < blcodes; rank++) {
12660     //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
12661     send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
12662   }
12663   //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
12664
12665   send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
12666   //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
12667
12668   send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
12669   //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
12670 }
12671
12672
12673 /* ===========================================================================
12674  * Check if the data type is TEXT or BINARY, using the following algorithm:
12675  * - TEXT if the two conditions below are satisfied:
12676  *    a) There are no non-portable control characters belonging to the
12677  *       "black list" (0..6, 14..25, 28..31).
12678  *    b) There is at least one printable character belonging to the
12679  *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
12680  * - BINARY otherwise.
12681  * - The following partially-portable control characters form a
12682  *   "gray list" that is ignored in this detection algorithm:
12683  *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
12684  * IN assertion: the fields Freq of dyn_ltree are set.
12685  */
12686 function detect_data_type(s) {
12687   /* black_mask is the bit mask of black-listed bytes
12688    * set bits 0..6, 14..25, and 28..31
12689    * 0xf3ffc07f = binary 11110011111111111100000001111111
12690    */
12691   var black_mask = 0xf3ffc07f;
12692   var n;
12693
12694   /* Check for non-textual ("black-listed") bytes. */
12695   for (n = 0; n <= 31; n++, black_mask >>>= 1) {
12696     if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
12697       return Z_BINARY;
12698     }
12699   }
12700
12701   /* Check for textual ("white-listed") bytes. */
12702   if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
12703       s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
12704     return Z_TEXT;
12705   }
12706   for (n = 32; n < LITERALS; n++) {
12707     if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
12708       return Z_TEXT;
12709     }
12710   }
12711
12712   /* There are no "black-listed" or "white-listed" bytes:
12713    * this stream either is empty or has tolerated ("gray-listed") bytes only.
12714    */
12715   return Z_BINARY;
12716 }
12717
12718
12719 var static_init_done = false;
12720
12721 /* ===========================================================================
12722  * Initialize the tree data structures for a new zlib stream.
12723  */
12724 function _tr_init(s)
12725 {
12726
12727   if (!static_init_done) {
12728     tr_static_init();
12729     static_init_done = true;
12730   }
12731
12732   s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
12733   s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
12734   s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
12735
12736   s.bi_buf = 0;
12737   s.bi_valid = 0;
12738
12739   /* Initialize the first block of the first file: */
12740   init_block(s);
12741 }
12742
12743
12744 /* ===========================================================================
12745  * Send a stored block
12746  */
12747 function _tr_stored_block(s, buf, stored_len, last)
12748 //DeflateState *s;
12749 //charf *buf;       /* input block */
12750 //ulg stored_len;   /* length of input block */
12751 //int last;         /* one if this is the last block for a file */
12752 {
12753   send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
12754   copy_block(s, buf, stored_len, true); /* with header */
12755 }
12756
12757
12758 /* ===========================================================================
12759  * Send one empty static block to give enough lookahead for inflate.
12760  * This takes 10 bits, of which 7 may remain in the bit buffer.
12761  */
12762 function _tr_align(s) {
12763   send_bits(s, STATIC_TREES << 1, 3);
12764   send_code(s, END_BLOCK, static_ltree);
12765   bi_flush(s);
12766 }
12767
12768
12769 /* ===========================================================================
12770  * Determine the best encoding for the current block: dynamic trees, static
12771  * trees or store, and output the encoded block to the zip file.
12772  */
12773 function _tr_flush_block(s, buf, stored_len, last)
12774 //DeflateState *s;
12775 //charf *buf;       /* input block, or NULL if too old */
12776 //ulg stored_len;   /* length of input block */
12777 //int last;         /* one if this is the last block for a file */
12778 {
12779   var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
12780   var max_blindex = 0;        /* index of last bit length code of non zero freq */
12781
12782   /* Build the Huffman trees unless a stored block is forced */
12783   if (s.level > 0) {
12784
12785     /* Check if the file is binary or text */
12786     if (s.strm.data_type === Z_UNKNOWN) {
12787       s.strm.data_type = detect_data_type(s);
12788     }
12789
12790     /* Construct the literal and distance trees */
12791     build_tree(s, s.l_desc);
12792     // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
12793     //        s->static_len));
12794
12795     build_tree(s, s.d_desc);
12796     // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
12797     //        s->static_len));
12798     /* At this point, opt_len and static_len are the total bit lengths of
12799      * the compressed block data, excluding the tree representations.
12800      */
12801
12802     /* Build the bit length tree for the above two trees, and get the index
12803      * in bl_order of the last bit length code to send.
12804      */
12805     max_blindex = build_bl_tree(s);
12806
12807     /* Determine the best encoding. Compute the block lengths in bytes. */
12808     opt_lenb = (s.opt_len + 3 + 7) >>> 3;
12809     static_lenb = (s.static_len + 3 + 7) >>> 3;
12810
12811     // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
12812     //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
12813     //        s->last_lit));
12814
12815     if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
12816
12817   } else {
12818     // Assert(buf != (char*)0, "lost buf");
12819     opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
12820   }
12821
12822   if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
12823     /* 4: two words for the lengths */
12824
12825     /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
12826      * Otherwise we can't have processed more than WSIZE input bytes since
12827      * the last block flush, because compression would have been
12828      * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
12829      * transform a block into a stored block.
12830      */
12831     _tr_stored_block(s, buf, stored_len, last);
12832
12833   } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
12834
12835     send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
12836     compress_block(s, static_ltree, static_dtree);
12837
12838   } else {
12839     send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
12840     send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
12841     compress_block(s, s.dyn_ltree, s.dyn_dtree);
12842   }
12843   // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
12844   /* The above check is made mod 2^32, for files larger than 512 MB
12845    * and uLong implemented on 32 bits.
12846    */
12847   init_block(s);
12848
12849   if (last) {
12850     bi_windup(s);
12851   }
12852   // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
12853   //       s->compressed_len-7*last));
12854 }
12855
12856 /* ===========================================================================
12857  * Save the match info and tally the frequency counts. Return true if
12858  * the current block must be flushed.
12859  */
12860 function _tr_tally(s, dist, lc)
12861 //    deflate_state *s;
12862 //    unsigned dist;  /* distance of matched string */
12863 //    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
12864 {
12865   //var out_length, in_length, dcode;
12866
12867   s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
12868   s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
12869
12870   s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
12871   s.last_lit++;
12872
12873   if (dist === 0) {
12874     /* lc is the unmatched char */
12875     s.dyn_ltree[lc * 2]/*.Freq*/++;
12876   } else {
12877     s.matches++;
12878     /* Here, lc is the match length - MIN_MATCH */
12879     dist--;             /* dist = match distance - 1 */
12880     //Assert((ush)dist < (ush)MAX_DIST(s) &&
12881     //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
12882     //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
12883
12884     s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
12885     s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
12886   }
12887
12888 // (!) This block is disabled in zlib defaults,
12889 // don't enable it for binary compatibility
12890
12891 //#ifdef TRUNCATE_BLOCK
12892 //  /* Try to guess if it is profitable to stop the current block here */
12893 //  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
12894 //    /* Compute an upper bound for the compressed length */
12895 //    out_length = s.last_lit*8;
12896 //    in_length = s.strstart - s.block_start;
12897 //
12898 //    for (dcode = 0; dcode < D_CODES; dcode++) {
12899 //      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
12900 //    }
12901 //    out_length >>>= 3;
12902 //    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
12903 //    //       s->last_lit, in_length, out_length,
12904 //    //       100L - out_length*100L/in_length));
12905 //    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
12906 //      return true;
12907 //    }
12908 //  }
12909 //#endif
12910
12911   return (s.last_lit === s.lit_bufsize - 1);
12912   /* We avoid equality with lit_bufsize because of wraparound at 64K
12913    * on 16 bit machines and because stored blocks are restricted to
12914    * 64K-1 bytes.
12915    */
12916 }
12917
12918 exports._tr_init  = _tr_init;
12919 exports._tr_stored_block = _tr_stored_block;
12920 exports._tr_flush_block  = _tr_flush_block;
12921 exports._tr_tally = _tr_tally;
12922 exports._tr_align = _tr_align;
12923
12924 },{"../utils/common":39}],49:[function(require,module,exports){
12925 'use strict';
12926
12927 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
12928 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
12929 //
12930 // This software is provided 'as-is', without any express or implied
12931 // warranty. In no event will the authors be held liable for any damages
12932 // arising from the use of this software.
12933 //
12934 // Permission is granted to anyone to use this software for any purpose,
12935 // including commercial applications, and to alter it and redistribute it
12936 // freely, subject to the following restrictions:
12937 //
12938 // 1. The origin of this software must not be misrepresented; you must not
12939 //   claim that you wrote the original software. If you use this software
12940 //   in a product, an acknowledgment in the product documentation would be
12941 //   appreciated but is not required.
12942 // 2. Altered source versions must be plainly marked as such, and must not be
12943 //   misrepresented as being the original software.
12944 // 3. This notice may not be removed or altered from any source distribution.
12945
12946 function ZStream() {
12947   /* next input byte */
12948   this.input = null; // JS specific, because we have no pointers
12949   this.next_in = 0;
12950   /* number of bytes available at input */
12951   this.avail_in = 0;
12952   /* total number of input bytes read so far */
12953   this.total_in = 0;
12954   /* next output byte should be put there */
12955   this.output = null; // JS specific, because we have no pointers
12956   this.next_out = 0;
12957   /* remaining free space at output */
12958   this.avail_out = 0;
12959   /* total number of bytes output so far */
12960   this.total_out = 0;
12961   /* last error message, NULL if no error */
12962   this.msg = ''/*Z_NULL*/;
12963   /* not visible by applications */
12964   this.state = null;
12965   /* best guess about the data type: binary or text */
12966   this.data_type = 2/*Z_UNKNOWN*/;
12967   /* adler32 value of the uncompressed data */
12968   this.adler = 0;
12969 }
12970
12971 module.exports = ZStream;
12972
12973 },{}],50:[function(require,module,exports){
12974 (function (process){
12975 'use strict';
12976
12977 if (!process.version ||
12978     process.version.indexOf('v0.') === 0 ||
12979     process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
12980   module.exports = nextTick;
12981 } else {
12982   module.exports = process.nextTick;
12983 }
12984
12985 function nextTick(fn, arg1, arg2, arg3) {
12986   if (typeof fn !== 'function') {
12987     throw new TypeError('"callback" argument must be a function');
12988   }
12989   var len = arguments.length;
12990   var args, i;
12991   switch (len) {
12992   case 0:
12993   case 1:
12994     return process.nextTick(fn);
12995   case 2:
12996     return process.nextTick(function afterTickOne() {
12997       fn.call(null, arg1);
12998     });
12999   case 3:
13000     return process.nextTick(function afterTickTwo() {
13001       fn.call(null, arg1, arg2);
13002     });
13003   case 4:
13004     return process.nextTick(function afterTickThree() {
13005       fn.call(null, arg1, arg2, arg3);
13006     });
13007   default:
13008     args = new Array(len - 1);
13009     i = 0;
13010     while (i < args.length) {
13011       args[i++] = arguments[i];
13012     }
13013     return process.nextTick(function afterTick() {
13014       fn.apply(null, args);
13015     });
13016   }
13017 }
13018
13019 }).call(this,require('_process'))
13020 },{"_process":51}],51:[function(require,module,exports){
13021 // shim for using process in browser
13022 var process = module.exports = {};
13023
13024 // cached from whatever global is present so that test runners that stub it
13025 // don't break things.  But we need to wrap it in a try catch in case it is
13026 // wrapped in strict mode code which doesn't define any globals.  It's inside a
13027 // function because try/catches deoptimize in certain engines.
13028
13029 var cachedSetTimeout;
13030 var cachedClearTimeout;
13031
13032 function defaultSetTimout() {
13033     throw new Error('setTimeout has not been defined');
13034 }
13035 function defaultClearTimeout () {
13036     throw new Error('clearTimeout has not been defined');
13037 }
13038 (function () {
13039     try {
13040         if (typeof setTimeout === 'function') {
13041             cachedSetTimeout = setTimeout;
13042         } else {
13043             cachedSetTimeout = defaultSetTimout;
13044         }
13045     } catch (e) {
13046         cachedSetTimeout = defaultSetTimout;
13047     }
13048     try {
13049         if (typeof clearTimeout === 'function') {
13050             cachedClearTimeout = clearTimeout;
13051         } else {
13052             cachedClearTimeout = defaultClearTimeout;
13053         }
13054     } catch (e) {
13055         cachedClearTimeout = defaultClearTimeout;
13056     }
13057 } ())
13058 function runTimeout(fun) {
13059     if (cachedSetTimeout === setTimeout) {
13060         //normal enviroments in sane situations
13061         return setTimeout(fun, 0);
13062     }
13063     // if setTimeout wasn't available but was latter defined
13064     if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
13065         cachedSetTimeout = setTimeout;
13066         return setTimeout(fun, 0);
13067     }
13068     try {
13069         // when when somebody has screwed with setTimeout but no I.E. maddness
13070         return cachedSetTimeout(fun, 0);
13071     } catch(e){
13072         try {
13073             // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
13074             return cachedSetTimeout.call(null, fun, 0);
13075         } catch(e){
13076             // 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
13077             return cachedSetTimeout.call(this, fun, 0);
13078         }
13079     }
13080
13081
13082 }
13083 function runClearTimeout(marker) {
13084     if (cachedClearTimeout === clearTimeout) {
13085         //normal enviroments in sane situations
13086         return clearTimeout(marker);
13087     }
13088     // if clearTimeout wasn't available but was latter defined
13089     if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
13090         cachedClearTimeout = clearTimeout;
13091         return clearTimeout(marker);
13092     }
13093     try {
13094         // when when somebody has screwed with setTimeout but no I.E. maddness
13095         return cachedClearTimeout(marker);
13096     } catch (e){
13097         try {
13098             // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
13099             return cachedClearTimeout.call(null, marker);
13100         } catch (e){
13101             // 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.
13102             // Some versions of I.E. have different rules for clearTimeout vs setTimeout
13103             return cachedClearTimeout.call(this, marker);
13104         }
13105     }
13106
13107
13108
13109 }
13110 var queue = [];
13111 var draining = false;
13112 var currentQueue;
13113 var queueIndex = -1;
13114
13115 function cleanUpNextTick() {
13116     if (!draining || !currentQueue) {
13117         return;
13118     }
13119     draining = false;
13120     if (currentQueue.length) {
13121         queue = currentQueue.concat(queue);
13122     } else {
13123         queueIndex = -1;
13124     }
13125     if (queue.length) {
13126         drainQueue();
13127     }
13128 }
13129
13130 function drainQueue() {
13131     if (draining) {
13132         return;
13133     }
13134     var timeout = runTimeout(cleanUpNextTick);
13135     draining = true;
13136
13137     var len = queue.length;
13138     while(len) {
13139         currentQueue = queue;
13140         queue = [];
13141         while (++queueIndex < len) {
13142             if (currentQueue) {
13143                 currentQueue[queueIndex].run();
13144             }
13145         }
13146         queueIndex = -1;
13147         len = queue.length;
13148     }
13149     currentQueue = null;
13150     draining = false;
13151     runClearTimeout(timeout);
13152 }
13153
13154 process.nextTick = function (fun) {
13155     var args = new Array(arguments.length - 1);
13156     if (arguments.length > 1) {
13157         for (var i = 1; i < arguments.length; i++) {
13158             args[i - 1] = arguments[i];
13159         }
13160     }
13161     queue.push(new Item(fun, args));
13162     if (queue.length === 1 && !draining) {
13163         runTimeout(drainQueue);
13164     }
13165 };
13166
13167 // v8 likes predictible objects
13168 function Item(fun, array) {
13169     this.fun = fun;
13170     this.array = array;
13171 }
13172 Item.prototype.run = function () {
13173     this.fun.apply(null, this.array);
13174 };
13175 process.title = 'browser';
13176 process.browser = true;
13177 process.env = {};
13178 process.argv = [];
13179 process.version = ''; // empty string to avoid regexp issues
13180 process.versions = {};
13181
13182 function noop() {}
13183
13184 process.on = noop;
13185 process.addListener = noop;
13186 process.once = noop;
13187 process.off = noop;
13188 process.removeListener = noop;
13189 process.removeAllListeners = noop;
13190 process.emit = noop;
13191 process.prependListener = noop;
13192 process.prependOnceListener = noop;
13193
13194 process.listeners = function (name) { return [] }
13195
13196 process.binding = function (name) {
13197     throw new Error('process.binding is not supported');
13198 };
13199
13200 process.cwd = function () { return '/' };
13201 process.chdir = function (dir) {
13202     throw new Error('process.chdir is not supported');
13203 };
13204 process.umask = function() { return 0; };
13205
13206 },{}],52:[function(require,module,exports){
13207 module.exports = require('./lib/_stream_duplex.js');
13208
13209 },{"./lib/_stream_duplex.js":53}],53:[function(require,module,exports){
13210 // a duplex stream is just a stream that is both readable and writable.
13211 // Since JS doesn't have multiple prototypal inheritance, this class
13212 // prototypally inherits from Readable, and then parasitically from
13213 // Writable.
13214
13215 'use strict';
13216
13217 /*<replacement>*/
13218
13219 var objectKeys = Object.keys || function (obj) {
13220   var keys = [];
13221   for (var key in obj) {
13222     keys.push(key);
13223   }return keys;
13224 };
13225 /*</replacement>*/
13226
13227 module.exports = Duplex;
13228
13229 /*<replacement>*/
13230 var processNextTick = require('process-nextick-args');
13231 /*</replacement>*/
13232
13233 /*<replacement>*/
13234 var util = require('core-util-is');
13235 util.inherits = require('inherits');
13236 /*</replacement>*/
13237
13238 var Readable = require('./_stream_readable');
13239 var Writable = require('./_stream_writable');
13240
13241 util.inherits(Duplex, Readable);
13242
13243 var keys = objectKeys(Writable.prototype);
13244 for (var v = 0; v < keys.length; v++) {
13245   var method = keys[v];
13246   if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
13247 }
13248
13249 function Duplex(options) {
13250   if (!(this instanceof Duplex)) return new Duplex(options);
13251
13252   Readable.call(this, options);
13253   Writable.call(this, options);
13254
13255   if (options && options.readable === false) this.readable = false;
13256
13257   if (options && options.writable === false) this.writable = false;
13258
13259   this.allowHalfOpen = true;
13260   if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
13261
13262   this.once('end', onend);
13263 }
13264
13265 // the no-half-open enforcer
13266 function onend() {
13267   // if we allow half-open state, or if the writable side ended,
13268   // then we're ok.
13269   if (this.allowHalfOpen || this._writableState.ended) return;
13270
13271   // no more data can be written.
13272   // But allow more writes to happen in this tick.
13273   processNextTick(onEndNT, this);
13274 }
13275
13276 function onEndNT(self) {
13277   self.end();
13278 }
13279
13280 function forEach(xs, f) {
13281   for (var i = 0, l = xs.length; i < l; i++) {
13282     f(xs[i], i);
13283   }
13284 }
13285 },{"./_stream_readable":55,"./_stream_writable":57,"core-util-is":33,"inherits":36,"process-nextick-args":50}],54:[function(require,module,exports){
13286 // a passthrough stream.
13287 // basically just the most minimal sort of Transform stream.
13288 // Every written chunk gets output as-is.
13289
13290 'use strict';
13291
13292 module.exports = PassThrough;
13293
13294 var Transform = require('./_stream_transform');
13295
13296 /*<replacement>*/
13297 var util = require('core-util-is');
13298 util.inherits = require('inherits');
13299 /*</replacement>*/
13300
13301 util.inherits(PassThrough, Transform);
13302
13303 function PassThrough(options) {
13304   if (!(this instanceof PassThrough)) return new PassThrough(options);
13305
13306   Transform.call(this, options);
13307 }
13308
13309 PassThrough.prototype._transform = function (chunk, encoding, cb) {
13310   cb(null, chunk);
13311 };
13312 },{"./_stream_transform":56,"core-util-is":33,"inherits":36}],55:[function(require,module,exports){
13313 (function (process){
13314 'use strict';
13315
13316 module.exports = Readable;
13317
13318 /*<replacement>*/
13319 var processNextTick = require('process-nextick-args');
13320 /*</replacement>*/
13321
13322 /*<replacement>*/
13323 var isArray = require('isarray');
13324 /*</replacement>*/
13325
13326 /*<replacement>*/
13327 var Duplex;
13328 /*</replacement>*/
13329
13330 Readable.ReadableState = ReadableState;
13331
13332 /*<replacement>*/
13333 var EE = require('events').EventEmitter;
13334
13335 var EElistenerCount = function (emitter, type) {
13336   return emitter.listeners(type).length;
13337 };
13338 /*</replacement>*/
13339
13340 /*<replacement>*/
13341 var Stream = require('./internal/streams/stream');
13342 /*</replacement>*/
13343
13344 var Buffer = require('buffer').Buffer;
13345 /*<replacement>*/
13346 var bufferShim = require('buffer-shims');
13347 /*</replacement>*/
13348
13349 /*<replacement>*/
13350 var util = require('core-util-is');
13351 util.inherits = require('inherits');
13352 /*</replacement>*/
13353
13354 /*<replacement>*/
13355 var debugUtil = require('util');
13356 var debug = void 0;
13357 if (debugUtil && debugUtil.debuglog) {
13358   debug = debugUtil.debuglog('stream');
13359 } else {
13360   debug = function () {};
13361 }
13362 /*</replacement>*/
13363
13364 var BufferList = require('./internal/streams/BufferList');
13365 var StringDecoder;
13366
13367 util.inherits(Readable, Stream);
13368
13369 var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
13370
13371 function prependListener(emitter, event, fn) {
13372   // Sadly this is not cacheable as some libraries bundle their own
13373   // event emitter implementation with them.
13374   if (typeof emitter.prependListener === 'function') {
13375     return emitter.prependListener(event, fn);
13376   } else {
13377     // This is a hack to make sure that our error handler is attached before any
13378     // userland ones.  NEVER DO THIS. This is here only because this code needs
13379     // to continue to work with older versions of Node.js that do not include
13380     // the prependListener() method. The goal is to eventually remove this hack.
13381     if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
13382   }
13383 }
13384
13385 function ReadableState(options, stream) {
13386   Duplex = Duplex || require('./_stream_duplex');
13387
13388   options = options || {};
13389
13390   // object stream flag. Used to make read(n) ignore n and to
13391   // make all the buffer merging and length checks go away
13392   this.objectMode = !!options.objectMode;
13393
13394   if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
13395
13396   // the point at which it stops calling _read() to fill the buffer
13397   // Note: 0 is a valid value, means "don't call _read preemptively ever"
13398   var hwm = options.highWaterMark;
13399   var defaultHwm = this.objectMode ? 16 : 16 * 1024;
13400   this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
13401
13402   // cast to ints.
13403   this.highWaterMark = ~~this.highWaterMark;
13404
13405   // A linked list is used to store data chunks instead of an array because the
13406   // linked list can remove elements from the beginning faster than
13407   // array.shift()
13408   this.buffer = new BufferList();
13409   this.length = 0;
13410   this.pipes = null;
13411   this.pipesCount = 0;
13412   this.flowing = null;
13413   this.ended = false;
13414   this.endEmitted = false;
13415   this.reading = false;
13416
13417   // a flag to be able to tell if the onwrite cb is called immediately,
13418   // or on a later tick.  We set this to true at first, because any
13419   // actions that shouldn't happen until "later" should generally also
13420   // not happen before the first write call.
13421   this.sync = true;
13422
13423   // whenever we return null, then we set a flag to say
13424   // that we're awaiting a 'readable' event emission.
13425   this.needReadable = false;
13426   this.emittedReadable = false;
13427   this.readableListening = false;
13428   this.resumeScheduled = false;
13429
13430   // Crypto is kind of old and crusty.  Historically, its default string
13431   // encoding is 'binary' so we have to make this configurable.
13432   // Everything else in the universe uses 'utf8', though.
13433   this.defaultEncoding = options.defaultEncoding || 'utf8';
13434
13435   // when piping, we only care about 'readable' events that happen
13436   // after read()ing all the bytes and not getting any pushback.
13437   this.ranOut = false;
13438
13439   // the number of writers that are awaiting a drain event in .pipe()s
13440   this.awaitDrain = 0;
13441
13442   // if true, a maybeReadMore has been scheduled
13443   this.readingMore = false;
13444
13445   this.decoder = null;
13446   this.encoding = null;
13447   if (options.encoding) {
13448     if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
13449     this.decoder = new StringDecoder(options.encoding);
13450     this.encoding = options.encoding;
13451   }
13452 }
13453
13454 function Readable(options) {
13455   Duplex = Duplex || require('./_stream_duplex');
13456
13457   if (!(this instanceof Readable)) return new Readable(options);
13458
13459   this._readableState = new ReadableState(options, this);
13460
13461   // legacy
13462   this.readable = true;
13463
13464   if (options && typeof options.read === 'function') this._read = options.read;
13465
13466   Stream.call(this);
13467 }
13468
13469 // Manually shove something into the read() buffer.
13470 // This returns true if the highWaterMark has not been hit yet,
13471 // similar to how Writable.write() returns true if you should
13472 // write() some more.
13473 Readable.prototype.push = function (chunk, encoding) {
13474   var state = this._readableState;
13475
13476   if (!state.objectMode && typeof chunk === 'string') {
13477     encoding = encoding || state.defaultEncoding;
13478     if (encoding !== state.encoding) {
13479       chunk = bufferShim.from(chunk, encoding);
13480       encoding = '';
13481     }
13482   }
13483
13484   return readableAddChunk(this, state, chunk, encoding, false);
13485 };
13486
13487 // Unshift should *always* be something directly out of read()
13488 Readable.prototype.unshift = function (chunk) {
13489   var state = this._readableState;
13490   return readableAddChunk(this, state, chunk, '', true);
13491 };
13492
13493 Readable.prototype.isPaused = function () {
13494   return this._readableState.flowing === false;
13495 };
13496
13497 function readableAddChunk(stream, state, chunk, encoding, addToFront) {
13498   var er = chunkInvalid(state, chunk);
13499   if (er) {
13500     stream.emit('error', er);
13501   } else if (chunk === null) {
13502     state.reading = false;
13503     onEofChunk(stream, state);
13504   } else if (state.objectMode || chunk && chunk.length > 0) {
13505     if (state.ended && !addToFront) {
13506       var e = new Error('stream.push() after EOF');
13507       stream.emit('error', e);
13508     } else if (state.endEmitted && addToFront) {
13509       var _e = new Error('stream.unshift() after end event');
13510       stream.emit('error', _e);
13511     } else {
13512       var skipAdd;
13513       if (state.decoder && !addToFront && !encoding) {
13514         chunk = state.decoder.write(chunk);
13515         skipAdd = !state.objectMode && chunk.length === 0;
13516       }
13517
13518       if (!addToFront) state.reading = false;
13519
13520       // Don't add to the buffer if we've decoded to an empty string chunk and
13521       // we're not in object mode
13522       if (!skipAdd) {
13523         // if we want the data now, just emit it.
13524         if (state.flowing && state.length === 0 && !state.sync) {
13525           stream.emit('data', chunk);
13526           stream.read(0);
13527         } else {
13528           // update the buffer info.
13529           state.length += state.objectMode ? 1 : chunk.length;
13530           if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
13531
13532           if (state.needReadable) emitReadable(stream);
13533         }
13534       }
13535
13536       maybeReadMore(stream, state);
13537     }
13538   } else if (!addToFront) {
13539     state.reading = false;
13540   }
13541
13542   return needMoreData(state);
13543 }
13544
13545 // if it's past the high water mark, we can push in some more.
13546 // Also, if we have no data yet, we can stand some
13547 // more bytes.  This is to work around cases where hwm=0,
13548 // such as the repl.  Also, if the push() triggered a
13549 // readable event, and the user called read(largeNumber) such that
13550 // needReadable was set, then we ought to push more, so that another
13551 // 'readable' event will be triggered.
13552 function needMoreData(state) {
13553   return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
13554 }
13555
13556 // backwards compatibility.
13557 Readable.prototype.setEncoding = function (enc) {
13558   if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
13559   this._readableState.decoder = new StringDecoder(enc);
13560   this._readableState.encoding = enc;
13561   return this;
13562 };
13563
13564 // Don't raise the hwm > 8MB
13565 var MAX_HWM = 0x800000;
13566 function computeNewHighWaterMark(n) {
13567   if (n >= MAX_HWM) {
13568     n = MAX_HWM;
13569   } else {
13570     // Get the next highest power of 2 to prevent increasing hwm excessively in
13571     // tiny amounts
13572     n--;
13573     n |= n >>> 1;
13574     n |= n >>> 2;
13575     n |= n >>> 4;
13576     n |= n >>> 8;
13577     n |= n >>> 16;
13578     n++;
13579   }
13580   return n;
13581 }
13582
13583 // This function is designed to be inlinable, so please take care when making
13584 // changes to the function body.
13585 function howMuchToRead(n, state) {
13586   if (n <= 0 || state.length === 0 && state.ended) return 0;
13587   if (state.objectMode) return 1;
13588   if (n !== n) {
13589     // Only flow one buffer at a time
13590     if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
13591   }
13592   // If we're asking for more than the current hwm, then raise the hwm.
13593   if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
13594   if (n <= state.length) return n;
13595   // Don't have enough
13596   if (!state.ended) {
13597     state.needReadable = true;
13598     return 0;
13599   }
13600   return state.length;
13601 }
13602
13603 // you can override either this method, or the async _read(n) below.
13604 Readable.prototype.read = function (n) {
13605   debug('read', n);
13606   n = parseInt(n, 10);
13607   var state = this._readableState;
13608   var nOrig = n;
13609
13610   if (n !== 0) state.emittedReadable = false;
13611
13612   // if we're doing read(0) to trigger a readable event, but we
13613   // already have a bunch of data in the buffer, then just trigger
13614   // the 'readable' event and move on.
13615   if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
13616     debug('read: emitReadable', state.length, state.ended);
13617     if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
13618     return null;
13619   }
13620
13621   n = howMuchToRead(n, state);
13622
13623   // if we've ended, and we're now clear, then finish it up.
13624   if (n === 0 && state.ended) {
13625     if (state.length === 0) endReadable(this);
13626     return null;
13627   }
13628
13629   // All the actual chunk generation logic needs to be
13630   // *below* the call to _read.  The reason is that in certain
13631   // synthetic stream cases, such as passthrough streams, _read
13632   // may be a completely synchronous operation which may change
13633   // the state of the read buffer, providing enough data when
13634   // before there was *not* enough.
13635   //
13636   // So, the steps are:
13637   // 1. Figure out what the state of things will be after we do
13638   // a read from the buffer.
13639   //
13640   // 2. If that resulting state will trigger a _read, then call _read.
13641   // Note that this may be asynchronous, or synchronous.  Yes, it is
13642   // deeply ugly to write APIs this way, but that still doesn't mean
13643   // that the Readable class should behave improperly, as streams are
13644   // designed to be sync/async agnostic.
13645   // Take note if the _read call is sync or async (ie, if the read call
13646   // has returned yet), so that we know whether or not it's safe to emit
13647   // 'readable' etc.
13648   //
13649   // 3. Actually pull the requested chunks out of the buffer and return.
13650
13651   // if we need a readable event, then we need to do some reading.
13652   var doRead = state.needReadable;
13653   debug('need readable', doRead);
13654
13655   // if we currently have less than the highWaterMark, then also read some
13656   if (state.length === 0 || state.length - n < state.highWaterMark) {
13657     doRead = true;
13658     debug('length less than watermark', doRead);
13659   }
13660
13661   // however, if we've ended, then there's no point, and if we're already
13662   // reading, then it's unnecessary.
13663   if (state.ended || state.reading) {
13664     doRead = false;
13665     debug('reading or ended', doRead);
13666   } else if (doRead) {
13667     debug('do read');
13668     state.reading = true;
13669     state.sync = true;
13670     // if the length is currently zero, then we *need* a readable event.
13671     if (state.length === 0) state.needReadable = true;
13672     // call internal read method
13673     this._read(state.highWaterMark);
13674     state.sync = false;
13675     // If _read pushed data synchronously, then `reading` will be false,
13676     // and we need to re-evaluate how much data we can return to the user.
13677     if (!state.reading) n = howMuchToRead(nOrig, state);
13678   }
13679
13680   var ret;
13681   if (n > 0) ret = fromList(n, state);else ret = null;
13682
13683   if (ret === null) {
13684     state.needReadable = true;
13685     n = 0;
13686   } else {
13687     state.length -= n;
13688   }
13689
13690   if (state.length === 0) {
13691     // If we have nothing in the buffer, then we want to know
13692     // as soon as we *do* get something into the buffer.
13693     if (!state.ended) state.needReadable = true;
13694
13695     // If we tried to read() past the EOF, then emit end on the next tick.
13696     if (nOrig !== n && state.ended) endReadable(this);
13697   }
13698
13699   if (ret !== null) this.emit('data', ret);
13700
13701   return ret;
13702 };
13703
13704 function chunkInvalid(state, chunk) {
13705   var er = null;
13706   if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
13707     er = new TypeError('Invalid non-string/buffer chunk');
13708   }
13709   return er;
13710 }
13711
13712 function onEofChunk(stream, state) {
13713   if (state.ended) return;
13714   if (state.decoder) {
13715     var chunk = state.decoder.end();
13716     if (chunk && chunk.length) {
13717       state.buffer.push(chunk);
13718       state.length += state.objectMode ? 1 : chunk.length;
13719     }
13720   }
13721   state.ended = true;
13722
13723   // emit 'readable' now to make sure it gets picked up.
13724   emitReadable(stream);
13725 }
13726
13727 // Don't emit readable right away in sync mode, because this can trigger
13728 // another read() call => stack overflow.  This way, it might trigger
13729 // a nextTick recursion warning, but that's not so bad.
13730 function emitReadable(stream) {
13731   var state = stream._readableState;
13732   state.needReadable = false;
13733   if (!state.emittedReadable) {
13734     debug('emitReadable', state.flowing);
13735     state.emittedReadable = true;
13736     if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
13737   }
13738 }
13739
13740 function emitReadable_(stream) {
13741   debug('emit readable');
13742   stream.emit('readable');
13743   flow(stream);
13744 }
13745
13746 // at this point, the user has presumably seen the 'readable' event,
13747 // and called read() to consume some data.  that may have triggered
13748 // in turn another _read(n) call, in which case reading = true if
13749 // it's in progress.
13750 // However, if we're not ended, or reading, and the length < hwm,
13751 // then go ahead and try to read some more preemptively.
13752 function maybeReadMore(stream, state) {
13753   if (!state.readingMore) {
13754     state.readingMore = true;
13755     processNextTick(maybeReadMore_, stream, state);
13756   }
13757 }
13758
13759 function maybeReadMore_(stream, state) {
13760   var len = state.length;
13761   while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
13762     debug('maybeReadMore read 0');
13763     stream.read(0);
13764     if (len === state.length)
13765       // didn't get any data, stop spinning.
13766       break;else len = state.length;
13767   }
13768   state.readingMore = false;
13769 }
13770
13771 // abstract method.  to be overridden in specific implementation classes.
13772 // call cb(er, data) where data is <= n in length.
13773 // for virtual (non-string, non-buffer) streams, "length" is somewhat
13774 // arbitrary, and perhaps not very meaningful.
13775 Readable.prototype._read = function (n) {
13776   this.emit('error', new Error('_read() is not implemented'));
13777 };
13778
13779 Readable.prototype.pipe = function (dest, pipeOpts) {
13780   var src = this;
13781   var state = this._readableState;
13782
13783   switch (state.pipesCount) {
13784     case 0:
13785       state.pipes = dest;
13786       break;
13787     case 1:
13788       state.pipes = [state.pipes, dest];
13789       break;
13790     default:
13791       state.pipes.push(dest);
13792       break;
13793   }
13794   state.pipesCount += 1;
13795   debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
13796
13797   var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
13798
13799   var endFn = doEnd ? onend : cleanup;
13800   if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
13801
13802   dest.on('unpipe', onunpipe);
13803   function onunpipe(readable) {
13804     debug('onunpipe');
13805     if (readable === src) {
13806       cleanup();
13807     }
13808   }
13809
13810   function onend() {
13811     debug('onend');
13812     dest.end();
13813   }
13814
13815   // when the dest drains, it reduces the awaitDrain counter
13816   // on the source.  This would be more elegant with a .once()
13817   // handler in flow(), but adding and removing repeatedly is
13818   // too slow.
13819   var ondrain = pipeOnDrain(src);
13820   dest.on('drain', ondrain);
13821
13822   var cleanedUp = false;
13823   function cleanup() {
13824     debug('cleanup');
13825     // cleanup event handlers once the pipe is broken
13826     dest.removeListener('close', onclose);
13827     dest.removeListener('finish', onfinish);
13828     dest.removeListener('drain', ondrain);
13829     dest.removeListener('error', onerror);
13830     dest.removeListener('unpipe', onunpipe);
13831     src.removeListener('end', onend);
13832     src.removeListener('end', cleanup);
13833     src.removeListener('data', ondata);
13834
13835     cleanedUp = true;
13836
13837     // if the reader is waiting for a drain event from this
13838     // specific writer, then it would cause it to never start
13839     // flowing again.
13840     // So, if this is awaiting a drain, then we just call it now.
13841     // If we don't know, then assume that we are waiting for one.
13842     if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
13843   }
13844
13845   // If the user pushes more data while we're writing to dest then we'll end up
13846   // in ondata again. However, we only want to increase awaitDrain once because
13847   // dest will only emit one 'drain' event for the multiple writes.
13848   // => Introduce a guard on increasing awaitDrain.
13849   var increasedAwaitDrain = false;
13850   src.on('data', ondata);
13851   function ondata(chunk) {
13852     debug('ondata');
13853     increasedAwaitDrain = false;
13854     var ret = dest.write(chunk);
13855     if (false === ret && !increasedAwaitDrain) {
13856       // If the user unpiped during `dest.write()`, it is possible
13857       // to get stuck in a permanently paused state if that write
13858       // also returned false.
13859       // => Check whether `dest` is still a piping destination.
13860       if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
13861         debug('false write response, pause', src._readableState.awaitDrain);
13862         src._readableState.awaitDrain++;
13863         increasedAwaitDrain = true;
13864       }
13865       src.pause();
13866     }
13867   }
13868
13869   // if the dest has an error, then stop piping into it.
13870   // however, don't suppress the throwing behavior for this.
13871   function onerror(er) {
13872     debug('onerror', er);
13873     unpipe();
13874     dest.removeListener('error', onerror);
13875     if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
13876   }
13877
13878   // Make sure our error handler is attached before userland ones.
13879   prependListener(dest, 'error', onerror);
13880
13881   // Both close and finish should trigger unpipe, but only once.
13882   function onclose() {
13883     dest.removeListener('finish', onfinish);
13884     unpipe();
13885   }
13886   dest.once('close', onclose);
13887   function onfinish() {
13888     debug('onfinish');
13889     dest.removeListener('close', onclose);
13890     unpipe();
13891   }
13892   dest.once('finish', onfinish);
13893
13894   function unpipe() {
13895     debug('unpipe');
13896     src.unpipe(dest);
13897   }
13898
13899   // tell the dest that it's being piped to
13900   dest.emit('pipe', src);
13901
13902   // start the flow if it hasn't been started already.
13903   if (!state.flowing) {
13904     debug('pipe resume');
13905     src.resume();
13906   }
13907
13908   return dest;
13909 };
13910
13911 function pipeOnDrain(src) {
13912   return function () {
13913     var state = src._readableState;
13914     debug('pipeOnDrain', state.awaitDrain);
13915     if (state.awaitDrain) state.awaitDrain--;
13916     if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
13917       state.flowing = true;
13918       flow(src);
13919     }
13920   };
13921 }
13922
13923 Readable.prototype.unpipe = function (dest) {
13924   var state = this._readableState;
13925
13926   // if we're not piping anywhere, then do nothing.
13927   if (state.pipesCount === 0) return this;
13928
13929   // just one destination.  most common case.
13930   if (state.pipesCount === 1) {
13931     // passed in one, but it's not the right one.
13932     if (dest && dest !== state.pipes) return this;
13933
13934     if (!dest) dest = state.pipes;
13935
13936     // got a match.
13937     state.pipes = null;
13938     state.pipesCount = 0;
13939     state.flowing = false;
13940     if (dest) dest.emit('unpipe', this);
13941     return this;
13942   }
13943
13944   // slow case. multiple pipe destinations.
13945
13946   if (!dest) {
13947     // remove all.
13948     var dests = state.pipes;
13949     var len = state.pipesCount;
13950     state.pipes = null;
13951     state.pipesCount = 0;
13952     state.flowing = false;
13953
13954     for (var i = 0; i < len; i++) {
13955       dests[i].emit('unpipe', this);
13956     }return this;
13957   }
13958
13959   // try to find the right one.
13960   var index = indexOf(state.pipes, dest);
13961   if (index === -1) return this;
13962
13963   state.pipes.splice(index, 1);
13964   state.pipesCount -= 1;
13965   if (state.pipesCount === 1) state.pipes = state.pipes[0];
13966
13967   dest.emit('unpipe', this);
13968
13969   return this;
13970 };
13971
13972 // set up data events if they are asked for
13973 // Ensure readable listeners eventually get something
13974 Readable.prototype.on = function (ev, fn) {
13975   var res = Stream.prototype.on.call(this, ev, fn);
13976
13977   if (ev === 'data') {
13978     // Start flowing on next tick if stream isn't explicitly paused
13979     if (this._readableState.flowing !== false) this.resume();
13980   } else if (ev === 'readable') {
13981     var state = this._readableState;
13982     if (!state.endEmitted && !state.readableListening) {
13983       state.readableListening = state.needReadable = true;
13984       state.emittedReadable = false;
13985       if (!state.reading) {
13986         processNextTick(nReadingNextTick, this);
13987       } else if (state.length) {
13988         emitReadable(this, state);
13989       }
13990     }
13991   }
13992
13993   return res;
13994 };
13995 Readable.prototype.addListener = Readable.prototype.on;
13996
13997 function nReadingNextTick(self) {
13998   debug('readable nexttick read 0');
13999   self.read(0);
14000 }
14001
14002 // pause() and resume() are remnants of the legacy readable stream API
14003 // If the user uses them, then switch into old mode.
14004 Readable.prototype.resume = function () {
14005   var state = this._readableState;
14006   if (!state.flowing) {
14007     debug('resume');
14008     state.flowing = true;
14009     resume(this, state);
14010   }
14011   return this;
14012 };
14013
14014 function resume(stream, state) {
14015   if (!state.resumeScheduled) {
14016     state.resumeScheduled = true;
14017     processNextTick(resume_, stream, state);
14018   }
14019 }
14020
14021 function resume_(stream, state) {
14022   if (!state.reading) {
14023     debug('resume read 0');
14024     stream.read(0);
14025   }
14026
14027   state.resumeScheduled = false;
14028   state.awaitDrain = 0;
14029   stream.emit('resume');
14030   flow(stream);
14031   if (state.flowing && !state.reading) stream.read(0);
14032 }
14033
14034 Readable.prototype.pause = function () {
14035   debug('call pause flowing=%j', this._readableState.flowing);
14036   if (false !== this._readableState.flowing) {
14037     debug('pause');
14038     this._readableState.flowing = false;
14039     this.emit('pause');
14040   }
14041   return this;
14042 };
14043
14044 function flow(stream) {
14045   var state = stream._readableState;
14046   debug('flow', state.flowing);
14047   while (state.flowing && stream.read() !== null) {}
14048 }
14049
14050 // wrap an old-style stream as the async data source.
14051 // This is *not* part of the readable stream interface.
14052 // It is an ugly unfortunate mess of history.
14053 Readable.prototype.wrap = function (stream) {
14054   var state = this._readableState;
14055   var paused = false;
14056
14057   var self = this;
14058   stream.on('end', function () {
14059     debug('wrapped end');
14060     if (state.decoder && !state.ended) {
14061       var chunk = state.decoder.end();
14062       if (chunk && chunk.length) self.push(chunk);
14063     }
14064
14065     self.push(null);
14066   });
14067
14068   stream.on('data', function (chunk) {
14069     debug('wrapped data');
14070     if (state.decoder) chunk = state.decoder.write(chunk);
14071
14072     // don't skip over falsy values in objectMode
14073     if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
14074
14075     var ret = self.push(chunk);
14076     if (!ret) {
14077       paused = true;
14078       stream.pause();
14079     }
14080   });
14081
14082   // proxy all the other methods.
14083   // important when wrapping filters and duplexes.
14084   for (var i in stream) {
14085     if (this[i] === undefined && typeof stream[i] === 'function') {
14086       this[i] = function (method) {
14087         return function () {
14088           return stream[method].apply(stream, arguments);
14089         };
14090       }(i);
14091     }
14092   }
14093
14094   // proxy certain important events.
14095   for (var n = 0; n < kProxyEvents.length; n++) {
14096     stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
14097   }
14098
14099   // when we try to consume some more bytes, simply unpause the
14100   // underlying stream.
14101   self._read = function (n) {
14102     debug('wrapped _read', n);
14103     if (paused) {
14104       paused = false;
14105       stream.resume();
14106     }
14107   };
14108
14109   return self;
14110 };
14111
14112 // exposed for testing purposes only.
14113 Readable._fromList = fromList;
14114
14115 // Pluck off n bytes from an array of buffers.
14116 // Length is the combined lengths of all the buffers in the list.
14117 // This function is designed to be inlinable, so please take care when making
14118 // changes to the function body.
14119 function fromList(n, state) {
14120   // nothing buffered
14121   if (state.length === 0) return null;
14122
14123   var ret;
14124   if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
14125     // read it all, truncate the list
14126     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);
14127     state.buffer.clear();
14128   } else {
14129     // read part of list
14130     ret = fromListPartial(n, state.buffer, state.decoder);
14131   }
14132
14133   return ret;
14134 }
14135
14136 // Extracts only enough buffered data to satisfy the amount requested.
14137 // This function is designed to be inlinable, so please take care when making
14138 // changes to the function body.
14139 function fromListPartial(n, list, hasStrings) {
14140   var ret;
14141   if (n < list.head.data.length) {
14142     // slice is the same for buffers and strings
14143     ret = list.head.data.slice(0, n);
14144     list.head.data = list.head.data.slice(n);
14145   } else if (n === list.head.data.length) {
14146     // first chunk is a perfect match
14147     ret = list.shift();
14148   } else {
14149     // result spans more than one buffer
14150     ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
14151   }
14152   return ret;
14153 }
14154
14155 // Copies a specified amount of characters from the list of buffered data
14156 // chunks.
14157 // This function is designed to be inlinable, so please take care when making
14158 // changes to the function body.
14159 function copyFromBufferString(n, list) {
14160   var p = list.head;
14161   var c = 1;
14162   var ret = p.data;
14163   n -= ret.length;
14164   while (p = p.next) {
14165     var str = p.data;
14166     var nb = n > str.length ? str.length : n;
14167     if (nb === str.length) ret += str;else ret += str.slice(0, n);
14168     n -= nb;
14169     if (n === 0) {
14170       if (nb === str.length) {
14171         ++c;
14172         if (p.next) list.head = p.next;else list.head = list.tail = null;
14173       } else {
14174         list.head = p;
14175         p.data = str.slice(nb);
14176       }
14177       break;
14178     }
14179     ++c;
14180   }
14181   list.length -= c;
14182   return ret;
14183 }
14184
14185 // Copies a specified amount of bytes from the list of buffered data chunks.
14186 // This function is designed to be inlinable, so please take care when making
14187 // changes to the function body.
14188 function copyFromBuffer(n, list) {
14189   var ret = bufferShim.allocUnsafe(n);
14190   var p = list.head;
14191   var c = 1;
14192   p.data.copy(ret);
14193   n -= p.data.length;
14194   while (p = p.next) {
14195     var buf = p.data;
14196     var nb = n > buf.length ? buf.length : n;
14197     buf.copy(ret, ret.length - n, 0, nb);
14198     n -= nb;
14199     if (n === 0) {
14200       if (nb === buf.length) {
14201         ++c;
14202         if (p.next) list.head = p.next;else list.head = list.tail = null;
14203       } else {
14204         list.head = p;
14205         p.data = buf.slice(nb);
14206       }
14207       break;
14208     }
14209     ++c;
14210   }
14211   list.length -= c;
14212   return ret;
14213 }
14214
14215 function endReadable(stream) {
14216   var state = stream._readableState;
14217
14218   // If we get here before consuming all the bytes, then that is a
14219   // bug in node.  Should never happen.
14220   if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
14221
14222   if (!state.endEmitted) {
14223     state.ended = true;
14224     processNextTick(endReadableNT, state, stream);
14225   }
14226 }
14227
14228 function endReadableNT(state, stream) {
14229   // Check that we didn't get one last unshift.
14230   if (!state.endEmitted && state.length === 0) {
14231     state.endEmitted = true;
14232     stream.readable = false;
14233     stream.emit('end');
14234   }
14235 }
14236
14237 function forEach(xs, f) {
14238   for (var i = 0, l = xs.length; i < l; i++) {
14239     f(xs[i], i);
14240   }
14241 }
14242
14243 function indexOf(xs, x) {
14244   for (var i = 0, l = xs.length; i < l; i++) {
14245     if (xs[i] === x) return i;
14246   }
14247   return -1;
14248 }
14249 }).call(this,require('_process'))
14250 },{"./_stream_duplex":53,"./internal/streams/BufferList":58,"./internal/streams/stream":59,"_process":51,"buffer":32,"buffer-shims":31,"core-util-is":33,"events":34,"inherits":36,"isarray":38,"process-nextick-args":50,"string_decoder/":65,"util":28}],56:[function(require,module,exports){
14251 // a transform stream is a readable/writable stream where you do
14252 // something with the data.  Sometimes it's called a "filter",
14253 // but that's not a great name for it, since that implies a thing where
14254 // some bits pass through, and others are simply ignored.  (That would
14255 // be a valid example of a transform, of course.)
14256 //
14257 // While the output is causally related to the input, it's not a
14258 // necessarily symmetric or synchronous transformation.  For example,
14259 // a zlib stream might take multiple plain-text writes(), and then
14260 // emit a single compressed chunk some time in the future.
14261 //
14262 // Here's how this works:
14263 //
14264 // The Transform stream has all the aspects of the readable and writable
14265 // stream classes.  When you write(chunk), that calls _write(chunk,cb)
14266 // internally, and returns false if there's a lot of pending writes
14267 // buffered up.  When you call read(), that calls _read(n) until
14268 // there's enough pending readable data buffered up.
14269 //
14270 // In a transform stream, the written data is placed in a buffer.  When
14271 // _read(n) is called, it transforms the queued up data, calling the
14272 // buffered _write cb's as it consumes chunks.  If consuming a single
14273 // written chunk would result in multiple output chunks, then the first
14274 // outputted bit calls the readcb, and subsequent chunks just go into
14275 // the read buffer, and will cause it to emit 'readable' if necessary.
14276 //
14277 // This way, back-pressure is actually determined by the reading side,
14278 // since _read has to be called to start processing a new chunk.  However,
14279 // a pathological inflate type of transform can cause excessive buffering
14280 // here.  For example, imagine a stream where every byte of input is
14281 // interpreted as an integer from 0-255, and then results in that many
14282 // bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
14283 // 1kb of data being output.  In this case, you could write a very small
14284 // amount of input, and end up with a very large amount of output.  In
14285 // such a pathological inflating mechanism, there'd be no way to tell
14286 // the system to stop doing the transform.  A single 4MB write could
14287 // cause the system to run out of memory.
14288 //
14289 // However, even in such a pathological case, only a single written chunk
14290 // would be consumed, and then the rest would wait (un-transformed) until
14291 // the results of the previous transformed chunk were consumed.
14292
14293 'use strict';
14294
14295 module.exports = Transform;
14296
14297 var Duplex = require('./_stream_duplex');
14298
14299 /*<replacement>*/
14300 var util = require('core-util-is');
14301 util.inherits = require('inherits');
14302 /*</replacement>*/
14303
14304 util.inherits(Transform, Duplex);
14305
14306 function TransformState(stream) {
14307   this.afterTransform = function (er, data) {
14308     return afterTransform(stream, er, data);
14309   };
14310
14311   this.needTransform = false;
14312   this.transforming = false;
14313   this.writecb = null;
14314   this.writechunk = null;
14315   this.writeencoding = null;
14316 }
14317
14318 function afterTransform(stream, er, data) {
14319   var ts = stream._transformState;
14320   ts.transforming = false;
14321
14322   var cb = ts.writecb;
14323
14324   if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
14325
14326   ts.writechunk = null;
14327   ts.writecb = null;
14328
14329   if (data !== null && data !== undefined) stream.push(data);
14330
14331   cb(er);
14332
14333   var rs = stream._readableState;
14334   rs.reading = false;
14335   if (rs.needReadable || rs.length < rs.highWaterMark) {
14336     stream._read(rs.highWaterMark);
14337   }
14338 }
14339
14340 function Transform(options) {
14341   if (!(this instanceof Transform)) return new Transform(options);
14342
14343   Duplex.call(this, options);
14344
14345   this._transformState = new TransformState(this);
14346
14347   var stream = this;
14348
14349   // start out asking for a readable event once data is transformed.
14350   this._readableState.needReadable = true;
14351
14352   // we have implemented the _read method, and done the other things
14353   // that Readable wants before the first _read call, so unset the
14354   // sync guard flag.
14355   this._readableState.sync = false;
14356
14357   if (options) {
14358     if (typeof options.transform === 'function') this._transform = options.transform;
14359
14360     if (typeof options.flush === 'function') this._flush = options.flush;
14361   }
14362
14363   // When the writable side finishes, then flush out anything remaining.
14364   this.once('prefinish', function () {
14365     if (typeof this._flush === 'function') this._flush(function (er, data) {
14366       done(stream, er, data);
14367     });else done(stream);
14368   });
14369 }
14370
14371 Transform.prototype.push = function (chunk, encoding) {
14372   this._transformState.needTransform = false;
14373   return Duplex.prototype.push.call(this, chunk, encoding);
14374 };
14375
14376 // This is the part where you do stuff!
14377 // override this function in implementation classes.
14378 // 'chunk' is an input chunk.
14379 //
14380 // Call `push(newChunk)` to pass along transformed output
14381 // to the readable side.  You may call 'push' zero or more times.
14382 //
14383 // Call `cb(err)` when you are done with this chunk.  If you pass
14384 // an error, then that'll put the hurt on the whole operation.  If you
14385 // never call cb(), then you'll never get another chunk.
14386 Transform.prototype._transform = function (chunk, encoding, cb) {
14387   throw new Error('_transform() is not implemented');
14388 };
14389
14390 Transform.prototype._write = function (chunk, encoding, cb) {
14391   var ts = this._transformState;
14392   ts.writecb = cb;
14393   ts.writechunk = chunk;
14394   ts.writeencoding = encoding;
14395   if (!ts.transforming) {
14396     var rs = this._readableState;
14397     if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
14398   }
14399 };
14400
14401 // Doesn't matter what the args are here.
14402 // _transform does all the work.
14403 // That we got here means that the readable side wants more data.
14404 Transform.prototype._read = function (n) {
14405   var ts = this._transformState;
14406
14407   if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
14408     ts.transforming = true;
14409     this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
14410   } else {
14411     // mark that we need a transform, so that any data that comes in
14412     // will get processed, now that we've asked for it.
14413     ts.needTransform = true;
14414   }
14415 };
14416
14417 function done(stream, er, data) {
14418   if (er) return stream.emit('error', er);
14419
14420   if (data !== null && data !== undefined) stream.push(data);
14421
14422   // if there's nothing in the write buffer, then that means
14423   // that nothing more will ever be provided
14424   var ws = stream._writableState;
14425   var ts = stream._transformState;
14426
14427   if (ws.length) throw new Error('Calling transform done when ws.length != 0');
14428
14429   if (ts.transforming) throw new Error('Calling transform done when still transforming');
14430
14431   return stream.push(null);
14432 }
14433 },{"./_stream_duplex":53,"core-util-is":33,"inherits":36}],57:[function(require,module,exports){
14434 (function (process,setImmediate){
14435 // A bit simpler than readable streams.
14436 // Implement an async ._write(chunk, encoding, cb), and it'll handle all
14437 // the drain event emission and buffering.
14438
14439 'use strict';
14440
14441 module.exports = Writable;
14442
14443 /*<replacement>*/
14444 var processNextTick = require('process-nextick-args');
14445 /*</replacement>*/
14446
14447 /*<replacement>*/
14448 var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
14449 /*</replacement>*/
14450
14451 /*<replacement>*/
14452 var Duplex;
14453 /*</replacement>*/
14454
14455 Writable.WritableState = WritableState;
14456
14457 /*<replacement>*/
14458 var util = require('core-util-is');
14459 util.inherits = require('inherits');
14460 /*</replacement>*/
14461
14462 /*<replacement>*/
14463 var internalUtil = {
14464   deprecate: require('util-deprecate')
14465 };
14466 /*</replacement>*/
14467
14468 /*<replacement>*/
14469 var Stream = require('./internal/streams/stream');
14470 /*</replacement>*/
14471
14472 var Buffer = require('buffer').Buffer;
14473 /*<replacement>*/
14474 var bufferShim = require('buffer-shims');
14475 /*</replacement>*/
14476
14477 util.inherits(Writable, Stream);
14478
14479 function nop() {}
14480
14481 function WriteReq(chunk, encoding, cb) {
14482   this.chunk = chunk;
14483   this.encoding = encoding;
14484   this.callback = cb;
14485   this.next = null;
14486 }
14487
14488 function WritableState(options, stream) {
14489   Duplex = Duplex || require('./_stream_duplex');
14490
14491   options = options || {};
14492
14493   // object stream flag to indicate whether or not this stream
14494   // contains buffers or objects.
14495   this.objectMode = !!options.objectMode;
14496
14497   if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
14498
14499   // the point at which write() starts returning false
14500   // Note: 0 is a valid value, means that we always return false if
14501   // the entire buffer is not flushed immediately on write()
14502   var hwm = options.highWaterMark;
14503   var defaultHwm = this.objectMode ? 16 : 16 * 1024;
14504   this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
14505
14506   // cast to ints.
14507   this.highWaterMark = ~~this.highWaterMark;
14508
14509   // drain event flag.
14510   this.needDrain = false;
14511   // at the start of calling end()
14512   this.ending = false;
14513   // when end() has been called, and returned
14514   this.ended = false;
14515   // when 'finish' is emitted
14516   this.finished = false;
14517
14518   // should we decode strings into buffers before passing to _write?
14519   // this is here so that some node-core streams can optimize string
14520   // handling at a lower level.
14521   var noDecode = options.decodeStrings === false;
14522   this.decodeStrings = !noDecode;
14523
14524   // Crypto is kind of old and crusty.  Historically, its default string
14525   // encoding is 'binary' so we have to make this configurable.
14526   // Everything else in the universe uses 'utf8', though.
14527   this.defaultEncoding = options.defaultEncoding || 'utf8';
14528
14529   // not an actual buffer we keep track of, but a measurement
14530   // of how much we're waiting to get pushed to some underlying
14531   // socket or file.
14532   this.length = 0;
14533
14534   // a flag to see when we're in the middle of a write.
14535   this.writing = false;
14536
14537   // when true all writes will be buffered until .uncork() call
14538   this.corked = 0;
14539
14540   // a flag to be able to tell if the onwrite cb is called immediately,
14541   // or on a later tick.  We set this to true at first, because any
14542   // actions that shouldn't happen until "later" should generally also
14543   // not happen before the first write call.
14544   this.sync = true;
14545
14546   // a flag to know if we're processing previously buffered items, which
14547   // may call the _write() callback in the same tick, so that we don't
14548   // end up in an overlapped onwrite situation.
14549   this.bufferProcessing = false;
14550
14551   // the callback that's passed to _write(chunk,cb)
14552   this.onwrite = function (er) {
14553     onwrite(stream, er);
14554   };
14555
14556   // the callback that the user supplies to write(chunk,encoding,cb)
14557   this.writecb = null;
14558
14559   // the amount that is being written when _write is called.
14560   this.writelen = 0;
14561
14562   this.bufferedRequest = null;
14563   this.lastBufferedRequest = null;
14564
14565   // number of pending user-supplied write callbacks
14566   // this must be 0 before 'finish' can be emitted
14567   this.pendingcb = 0;
14568
14569   // emit prefinish if the only thing we're waiting for is _write cbs
14570   // This is relevant for synchronous Transform streams
14571   this.prefinished = false;
14572
14573   // True if the error was already emitted and should not be thrown again
14574   this.errorEmitted = false;
14575
14576   // count buffered requests
14577   this.bufferedRequestCount = 0;
14578
14579   // allocate the first CorkedRequest, there is always
14580   // one allocated and free to use, and we maintain at most two
14581   this.corkedRequestsFree = new CorkedRequest(this);
14582 }
14583
14584 WritableState.prototype.getBuffer = function getBuffer() {
14585   var current = this.bufferedRequest;
14586   var out = [];
14587   while (current) {
14588     out.push(current);
14589     current = current.next;
14590   }
14591   return out;
14592 };
14593
14594 (function () {
14595   try {
14596     Object.defineProperty(WritableState.prototype, 'buffer', {
14597       get: internalUtil.deprecate(function () {
14598         return this.getBuffer();
14599       }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
14600     });
14601   } catch (_) {}
14602 })();
14603
14604 // Test _writableState for inheritance to account for Duplex streams,
14605 // whose prototype chain only points to Readable.
14606 var realHasInstance;
14607 if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
14608   realHasInstance = Function.prototype[Symbol.hasInstance];
14609   Object.defineProperty(Writable, Symbol.hasInstance, {
14610     value: function (object) {
14611       if (realHasInstance.call(this, object)) return true;
14612
14613       return object && object._writableState instanceof WritableState;
14614     }
14615   });
14616 } else {
14617   realHasInstance = function (object) {
14618     return object instanceof this;
14619   };
14620 }
14621
14622 function Writable(options) {
14623   Duplex = Duplex || require('./_stream_duplex');
14624
14625   // Writable ctor is applied to Duplexes, too.
14626   // `realHasInstance` is necessary because using plain `instanceof`
14627   // would return false, as no `_writableState` property is attached.
14628
14629   // Trying to use the custom `instanceof` for Writable here will also break the
14630   // Node.js LazyTransform implementation, which has a non-trivial getter for
14631   // `_writableState` that would lead to infinite recursion.
14632   if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
14633     return new Writable(options);
14634   }
14635
14636   this._writableState = new WritableState(options, this);
14637
14638   // legacy.
14639   this.writable = true;
14640
14641   if (options) {
14642     if (typeof options.write === 'function') this._write = options.write;
14643
14644     if (typeof options.writev === 'function') this._writev = options.writev;
14645   }
14646
14647   Stream.call(this);
14648 }
14649
14650 // Otherwise people can pipe Writable streams, which is just wrong.
14651 Writable.prototype.pipe = function () {
14652   this.emit('error', new Error('Cannot pipe, not readable'));
14653 };
14654
14655 function writeAfterEnd(stream, cb) {
14656   var er = new Error('write after end');
14657   // TODO: defer error events consistently everywhere, not just the cb
14658   stream.emit('error', er);
14659   processNextTick(cb, er);
14660 }
14661
14662 // Checks that a user-supplied chunk is valid, especially for the particular
14663 // mode the stream is in. Currently this means that `null` is never accepted
14664 // and undefined/non-string values are only allowed in object mode.
14665 function validChunk(stream, state, chunk, cb) {
14666   var valid = true;
14667   var er = false;
14668
14669   if (chunk === null) {
14670     er = new TypeError('May not write null values to stream');
14671   } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
14672     er = new TypeError('Invalid non-string/buffer chunk');
14673   }
14674   if (er) {
14675     stream.emit('error', er);
14676     processNextTick(cb, er);
14677     valid = false;
14678   }
14679   return valid;
14680 }
14681
14682 Writable.prototype.write = function (chunk, encoding, cb) {
14683   var state = this._writableState;
14684   var ret = false;
14685   var isBuf = Buffer.isBuffer(chunk);
14686
14687   if (typeof encoding === 'function') {
14688     cb = encoding;
14689     encoding = null;
14690   }
14691
14692   if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
14693
14694   if (typeof cb !== 'function') cb = nop;
14695
14696   if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
14697     state.pendingcb++;
14698     ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
14699   }
14700
14701   return ret;
14702 };
14703
14704 Writable.prototype.cork = function () {
14705   var state = this._writableState;
14706
14707   state.corked++;
14708 };
14709
14710 Writable.prototype.uncork = function () {
14711   var state = this._writableState;
14712
14713   if (state.corked) {
14714     state.corked--;
14715
14716     if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
14717   }
14718 };
14719
14720 Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
14721   // node::ParseEncoding() requires lower case.
14722   if (typeof encoding === 'string') encoding = encoding.toLowerCase();
14723   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);
14724   this._writableState.defaultEncoding = encoding;
14725   return this;
14726 };
14727
14728 function decodeChunk(state, chunk, encoding) {
14729   if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
14730     chunk = bufferShim.from(chunk, encoding);
14731   }
14732   return chunk;
14733 }
14734
14735 // if we're already writing something, then just put this
14736 // in the queue, and wait our turn.  Otherwise, call _write
14737 // If we return false, then we need a drain event, so set that flag.
14738 function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
14739   if (!isBuf) {
14740     chunk = decodeChunk(state, chunk, encoding);
14741     if (Buffer.isBuffer(chunk)) encoding = 'buffer';
14742   }
14743   var len = state.objectMode ? 1 : chunk.length;
14744
14745   state.length += len;
14746
14747   var ret = state.length < state.highWaterMark;
14748   // we must ensure that previous needDrain will not be reset to false.
14749   if (!ret) state.needDrain = true;
14750
14751   if (state.writing || state.corked) {
14752     var last = state.lastBufferedRequest;
14753     state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
14754     if (last) {
14755       last.next = state.lastBufferedRequest;
14756     } else {
14757       state.bufferedRequest = state.lastBufferedRequest;
14758     }
14759     state.bufferedRequestCount += 1;
14760   } else {
14761     doWrite(stream, state, false, len, chunk, encoding, cb);
14762   }
14763
14764   return ret;
14765 }
14766
14767 function doWrite(stream, state, writev, len, chunk, encoding, cb) {
14768   state.writelen = len;
14769   state.writecb = cb;
14770   state.writing = true;
14771   state.sync = true;
14772   if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
14773   state.sync = false;
14774 }
14775
14776 function onwriteError(stream, state, sync, er, cb) {
14777   --state.pendingcb;
14778   if (sync) processNextTick(cb, er);else cb(er);
14779
14780   stream._writableState.errorEmitted = true;
14781   stream.emit('error', er);
14782 }
14783
14784 function onwriteStateUpdate(state) {
14785   state.writing = false;
14786   state.writecb = null;
14787   state.length -= state.writelen;
14788   state.writelen = 0;
14789 }
14790
14791 function onwrite(stream, er) {
14792   var state = stream._writableState;
14793   var sync = state.sync;
14794   var cb = state.writecb;
14795
14796   onwriteStateUpdate(state);
14797
14798   if (er) onwriteError(stream, state, sync, er, cb);else {
14799     // Check if we're actually ready to finish, but don't emit yet
14800     var finished = needFinish(state);
14801
14802     if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
14803       clearBuffer(stream, state);
14804     }
14805
14806     if (sync) {
14807       /*<replacement>*/
14808       asyncWrite(afterWrite, stream, state, finished, cb);
14809       /*</replacement>*/
14810     } else {
14811       afterWrite(stream, state, finished, cb);
14812     }
14813   }
14814 }
14815
14816 function afterWrite(stream, state, finished, cb) {
14817   if (!finished) onwriteDrain(stream, state);
14818   state.pendingcb--;
14819   cb();
14820   finishMaybe(stream, state);
14821 }
14822
14823 // Must force callback to be called on nextTick, so that we don't
14824 // emit 'drain' before the write() consumer gets the 'false' return
14825 // value, and has a chance to attach a 'drain' listener.
14826 function onwriteDrain(stream, state) {
14827   if (state.length === 0 && state.needDrain) {
14828     state.needDrain = false;
14829     stream.emit('drain');
14830   }
14831 }
14832
14833 // if there's something in the buffer waiting, then process it
14834 function clearBuffer(stream, state) {
14835   state.bufferProcessing = true;
14836   var entry = state.bufferedRequest;
14837
14838   if (stream._writev && entry && entry.next) {
14839     // Fast case, write everything using _writev()
14840     var l = state.bufferedRequestCount;
14841     var buffer = new Array(l);
14842     var holder = state.corkedRequestsFree;
14843     holder.entry = entry;
14844
14845     var count = 0;
14846     while (entry) {
14847       buffer[count] = entry;
14848       entry = entry.next;
14849       count += 1;
14850     }
14851
14852     doWrite(stream, state, true, state.length, buffer, '', holder.finish);
14853
14854     // doWrite is almost always async, defer these to save a bit of time
14855     // as the hot path ends with doWrite
14856     state.pendingcb++;
14857     state.lastBufferedRequest = null;
14858     if (holder.next) {
14859       state.corkedRequestsFree = holder.next;
14860       holder.next = null;
14861     } else {
14862       state.corkedRequestsFree = new CorkedRequest(state);
14863     }
14864   } else {
14865     // Slow case, write chunks one-by-one
14866     while (entry) {
14867       var chunk = entry.chunk;
14868       var encoding = entry.encoding;
14869       var cb = entry.callback;
14870       var len = state.objectMode ? 1 : chunk.length;
14871
14872       doWrite(stream, state, false, len, chunk, encoding, cb);
14873       entry = entry.next;
14874       // if we didn't call the onwrite immediately, then
14875       // it means that we need to wait until it does.
14876       // also, that means that the chunk and cb are currently
14877       // being processed, so move the buffer counter past them.
14878       if (state.writing) {
14879         break;
14880       }
14881     }
14882
14883     if (entry === null) state.lastBufferedRequest = null;
14884   }
14885
14886   state.bufferedRequestCount = 0;
14887   state.bufferedRequest = entry;
14888   state.bufferProcessing = false;
14889 }
14890
14891 Writable.prototype._write = function (chunk, encoding, cb) {
14892   cb(new Error('_write() is not implemented'));
14893 };
14894
14895 Writable.prototype._writev = null;
14896
14897 Writable.prototype.end = function (chunk, encoding, cb) {
14898   var state = this._writableState;
14899
14900   if (typeof chunk === 'function') {
14901     cb = chunk;
14902     chunk = null;
14903     encoding = null;
14904   } else if (typeof encoding === 'function') {
14905     cb = encoding;
14906     encoding = null;
14907   }
14908
14909   if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
14910
14911   // .end() fully uncorks
14912   if (state.corked) {
14913     state.corked = 1;
14914     this.uncork();
14915   }
14916
14917   // ignore unnecessary end() calls.
14918   if (!state.ending && !state.finished) endWritable(this, state, cb);
14919 };
14920
14921 function needFinish(state) {
14922   return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
14923 }
14924
14925 function prefinish(stream, state) {
14926   if (!state.prefinished) {
14927     state.prefinished = true;
14928     stream.emit('prefinish');
14929   }
14930 }
14931
14932 function finishMaybe(stream, state) {
14933   var need = needFinish(state);
14934   if (need) {
14935     if (state.pendingcb === 0) {
14936       prefinish(stream, state);
14937       state.finished = true;
14938       stream.emit('finish');
14939     } else {
14940       prefinish(stream, state);
14941     }
14942   }
14943   return need;
14944 }
14945
14946 function endWritable(stream, state, cb) {
14947   state.ending = true;
14948   finishMaybe(stream, state);
14949   if (cb) {
14950     if (state.finished) processNextTick(cb);else stream.once('finish', cb);
14951   }
14952   state.ended = true;
14953   stream.writable = false;
14954 }
14955
14956 // It seems a linked list but it is not
14957 // there will be only 2 of these for each stream
14958 function CorkedRequest(state) {
14959   var _this = this;
14960
14961   this.next = null;
14962   this.entry = null;
14963   this.finish = function (err) {
14964     var entry = _this.entry;
14965     _this.entry = null;
14966     while (entry) {
14967       var cb = entry.callback;
14968       state.pendingcb--;
14969       cb(err);
14970       entry = entry.next;
14971     }
14972     if (state.corkedRequestsFree) {
14973       state.corkedRequestsFree.next = _this;
14974     } else {
14975       state.corkedRequestsFree = _this;
14976     }
14977   };
14978 }
14979 }).call(this,require('_process'),require("timers").setImmediate)
14980 },{"./_stream_duplex":53,"./internal/streams/stream":59,"_process":51,"buffer":32,"buffer-shims":31,"core-util-is":33,"inherits":36,"process-nextick-args":50,"timers":66,"util-deprecate":67}],58:[function(require,module,exports){
14981 'use strict';
14982
14983 var Buffer = require('buffer').Buffer;
14984 /*<replacement>*/
14985 var bufferShim = require('buffer-shims');
14986 /*</replacement>*/
14987
14988 module.exports = BufferList;
14989
14990 function BufferList() {
14991   this.head = null;
14992   this.tail = null;
14993   this.length = 0;
14994 }
14995
14996 BufferList.prototype.push = function (v) {
14997   var entry = { data: v, next: null };
14998   if (this.length > 0) this.tail.next = entry;else this.head = entry;
14999   this.tail = entry;
15000   ++this.length;
15001 };
15002
15003 BufferList.prototype.unshift = function (v) {
15004   var entry = { data: v, next: this.head };
15005   if (this.length === 0) this.tail = entry;
15006   this.head = entry;
15007   ++this.length;
15008 };
15009
15010 BufferList.prototype.shift = function () {
15011   if (this.length === 0) return;
15012   var ret = this.head.data;
15013   if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
15014   --this.length;
15015   return ret;
15016 };
15017
15018 BufferList.prototype.clear = function () {
15019   this.head = this.tail = null;
15020   this.length = 0;
15021 };
15022
15023 BufferList.prototype.join = function (s) {
15024   if (this.length === 0) return '';
15025   var p = this.head;
15026   var ret = '' + p.data;
15027   while (p = p.next) {
15028     ret += s + p.data;
15029   }return ret;
15030 };
15031
15032 BufferList.prototype.concat = function (n) {
15033   if (this.length === 0) return bufferShim.alloc(0);
15034   if (this.length === 1) return this.head.data;
15035   var ret = bufferShim.allocUnsafe(n >>> 0);
15036   var p = this.head;
15037   var i = 0;
15038   while (p) {
15039     p.data.copy(ret, i);
15040     i += p.data.length;
15041     p = p.next;
15042   }
15043   return ret;
15044 };
15045 },{"buffer":32,"buffer-shims":31}],59:[function(require,module,exports){
15046 module.exports = require('events').EventEmitter;
15047
15048 },{"events":34}],60:[function(require,module,exports){
15049 module.exports = require('./readable').PassThrough
15050
15051 },{"./readable":61}],61:[function(require,module,exports){
15052 exports = module.exports = require('./lib/_stream_readable.js');
15053 exports.Stream = exports;
15054 exports.Readable = exports;
15055 exports.Writable = require('./lib/_stream_writable.js');
15056 exports.Duplex = require('./lib/_stream_duplex.js');
15057 exports.Transform = require('./lib/_stream_transform.js');
15058 exports.PassThrough = require('./lib/_stream_passthrough.js');
15059
15060 },{"./lib/_stream_duplex.js":53,"./lib/_stream_passthrough.js":54,"./lib/_stream_readable.js":55,"./lib/_stream_transform.js":56,"./lib/_stream_writable.js":57}],62:[function(require,module,exports){
15061 module.exports = require('./readable').Transform
15062
15063 },{"./readable":61}],63:[function(require,module,exports){
15064 module.exports = require('./lib/_stream_writable.js');
15065
15066 },{"./lib/_stream_writable.js":57}],64:[function(require,module,exports){
15067 // Copyright Joyent, Inc. and other Node contributors.
15068 //
15069 // Permission is hereby granted, free of charge, to any person obtaining a
15070 // copy of this software and associated documentation files (the
15071 // "Software"), to deal in the Software without restriction, including
15072 // without limitation the rights to use, copy, modify, merge, publish,
15073 // distribute, sublicense, and/or sell copies of the Software, and to permit
15074 // persons to whom the Software is furnished to do so, subject to the
15075 // following conditions:
15076 //
15077 // The above copyright notice and this permission notice shall be included
15078 // in all copies or substantial portions of the Software.
15079 //
15080 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15081 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15082 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15083 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15084 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15085 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15086 // USE OR OTHER DEALINGS IN THE SOFTWARE.
15087
15088 module.exports = Stream;
15089
15090 var EE = require('events').EventEmitter;
15091 var inherits = require('inherits');
15092
15093 inherits(Stream, EE);
15094 Stream.Readable = require('readable-stream/readable.js');
15095 Stream.Writable = require('readable-stream/writable.js');
15096 Stream.Duplex = require('readable-stream/duplex.js');
15097 Stream.Transform = require('readable-stream/transform.js');
15098 Stream.PassThrough = require('readable-stream/passthrough.js');
15099
15100 // Backwards-compat with node 0.4.x
15101 Stream.Stream = Stream;
15102
15103
15104
15105 // old-style streams.  Note that the pipe method (the only relevant
15106 // part of this class) is overridden in the Readable class.
15107
15108 function Stream() {
15109   EE.call(this);
15110 }
15111
15112 Stream.prototype.pipe = function(dest, options) {
15113   var source = this;
15114
15115   function ondata(chunk) {
15116     if (dest.writable) {
15117       if (false === dest.write(chunk) && source.pause) {
15118         source.pause();
15119       }
15120     }
15121   }
15122
15123   source.on('data', ondata);
15124
15125   function ondrain() {
15126     if (source.readable && source.resume) {
15127       source.resume();
15128     }
15129   }
15130
15131   dest.on('drain', ondrain);
15132
15133   // If the 'end' option is not supplied, dest.end() will be called when
15134   // source gets the 'end' or 'close' events.  Only dest.end() once.
15135   if (!dest._isStdio && (!options || options.end !== false)) {
15136     source.on('end', onend);
15137     source.on('close', onclose);
15138   }
15139
15140   var didOnEnd = false;
15141   function onend() {
15142     if (didOnEnd) return;
15143     didOnEnd = true;
15144
15145     dest.end();
15146   }
15147
15148
15149   function onclose() {
15150     if (didOnEnd) return;
15151     didOnEnd = true;
15152
15153     if (typeof dest.destroy === 'function') dest.destroy();
15154   }
15155
15156   // don't leave dangling pipes when there are errors.
15157   function onerror(er) {
15158     cleanup();
15159     if (EE.listenerCount(this, 'error') === 0) {
15160       throw er; // Unhandled stream error in pipe.
15161     }
15162   }
15163
15164   source.on('error', onerror);
15165   dest.on('error', onerror);
15166
15167   // remove all the event listeners that were added.
15168   function cleanup() {
15169     source.removeListener('data', ondata);
15170     dest.removeListener('drain', ondrain);
15171
15172     source.removeListener('end', onend);
15173     source.removeListener('close', onclose);
15174
15175     source.removeListener('error', onerror);
15176     dest.removeListener('error', onerror);
15177
15178     source.removeListener('end', cleanup);
15179     source.removeListener('close', cleanup);
15180
15181     dest.removeListener('close', cleanup);
15182   }
15183
15184   source.on('end', cleanup);
15185   source.on('close', cleanup);
15186
15187   dest.on('close', cleanup);
15188
15189   dest.emit('pipe', source);
15190
15191   // Allow for unix-like usage: A.pipe(B).pipe(C)
15192   return dest;
15193 };
15194
15195 },{"events":34,"inherits":36,"readable-stream/duplex.js":52,"readable-stream/passthrough.js":60,"readable-stream/readable.js":61,"readable-stream/transform.js":62,"readable-stream/writable.js":63}],65:[function(require,module,exports){
15196 'use strict';
15197
15198 var Buffer = require('buffer').Buffer;
15199 var bufferShim = require('buffer-shims');
15200
15201 var isEncoding = Buffer.isEncoding || function (encoding) {
15202   encoding = '' + encoding;
15203   switch (encoding && encoding.toLowerCase()) {
15204     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':
15205       return true;
15206     default:
15207       return false;
15208   }
15209 };
15210
15211 function _normalizeEncoding(enc) {
15212   if (!enc) return 'utf8';
15213   var retried;
15214   while (true) {
15215     switch (enc) {
15216       case 'utf8':
15217       case 'utf-8':
15218         return 'utf8';
15219       case 'ucs2':
15220       case 'ucs-2':
15221       case 'utf16le':
15222       case 'utf-16le':
15223         return 'utf16le';
15224       case 'latin1':
15225       case 'binary':
15226         return 'latin1';
15227       case 'base64':
15228       case 'ascii':
15229       case 'hex':
15230         return enc;
15231       default:
15232         if (retried) return; // undefined
15233         enc = ('' + enc).toLowerCase();
15234         retried = true;
15235     }
15236   }
15237 };
15238
15239 // Do not cache `Buffer.isEncoding` when checking encoding names as some
15240 // modules monkey-patch it to support additional encodings
15241 function normalizeEncoding(enc) {
15242   var nenc = _normalizeEncoding(enc);
15243   if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
15244   return nenc || enc;
15245 }
15246
15247 // StringDecoder provides an interface for efficiently splitting a series of
15248 // buffers into a series of JS strings without breaking apart multi-byte
15249 // characters.
15250 exports.StringDecoder = StringDecoder;
15251 function StringDecoder(encoding) {
15252   this.encoding = normalizeEncoding(encoding);
15253   var nb;
15254   switch (this.encoding) {
15255     case 'utf16le':
15256       this.text = utf16Text;
15257       this.end = utf16End;
15258       nb = 4;
15259       break;
15260     case 'utf8':
15261       this.fillLast = utf8FillLast;
15262       nb = 4;
15263       break;
15264     case 'base64':
15265       this.text = base64Text;
15266       this.end = base64End;
15267       nb = 3;
15268       break;
15269     default:
15270       this.write = simpleWrite;
15271       this.end = simpleEnd;
15272       return;
15273   }
15274   this.lastNeed = 0;
15275   this.lastTotal = 0;
15276   this.lastChar = bufferShim.allocUnsafe(nb);
15277 }
15278
15279 StringDecoder.prototype.write = function (buf) {
15280   if (buf.length === 0) return '';
15281   var r;
15282   var i;
15283   if (this.lastNeed) {
15284     r = this.fillLast(buf);
15285     if (r === undefined) return '';
15286     i = this.lastNeed;
15287     this.lastNeed = 0;
15288   } else {
15289     i = 0;
15290   }
15291   if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
15292   return r || '';
15293 };
15294
15295 StringDecoder.prototype.end = utf8End;
15296
15297 // Returns only complete characters in a Buffer
15298 StringDecoder.prototype.text = utf8Text;
15299
15300 // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
15301 StringDecoder.prototype.fillLast = function (buf) {
15302   if (this.lastNeed <= buf.length) {
15303     buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
15304     return this.lastChar.toString(this.encoding, 0, this.lastTotal);
15305   }
15306   buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
15307   this.lastNeed -= buf.length;
15308 };
15309
15310 // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
15311 // continuation byte.
15312 function utf8CheckByte(byte) {
15313   if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
15314   return -1;
15315 }
15316
15317 // Checks at most 3 bytes at the end of a Buffer in order to detect an
15318 // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
15319 // needed to complete the UTF-8 character (if applicable) are returned.
15320 function utf8CheckIncomplete(self, buf, i) {
15321   var j = buf.length - 1;
15322   if (j < i) return 0;
15323   var nb = utf8CheckByte(buf[j]);
15324   if (nb >= 0) {
15325     if (nb > 0) self.lastNeed = nb - 1;
15326     return nb;
15327   }
15328   if (--j < i) return 0;
15329   nb = utf8CheckByte(buf[j]);
15330   if (nb >= 0) {
15331     if (nb > 0) self.lastNeed = nb - 2;
15332     return nb;
15333   }
15334   if (--j < i) return 0;
15335   nb = utf8CheckByte(buf[j]);
15336   if (nb >= 0) {
15337     if (nb > 0) {
15338       if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
15339     }
15340     return nb;
15341   }
15342   return 0;
15343 }
15344
15345 // Validates as many continuation bytes for a multi-byte UTF-8 character as
15346 // needed or are available. If we see a non-continuation byte where we expect
15347 // one, we "replace" the validated continuation bytes we've seen so far with
15348 // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
15349 // behavior. The continuation byte check is included three times in the case
15350 // where all of the continuation bytes for a character exist in the same buffer.
15351 // It is also done this way as a slight performance increase instead of using a
15352 // loop.
15353 function utf8CheckExtraBytes(self, buf, p) {
15354   if ((buf[0] & 0xC0) !== 0x80) {
15355     self.lastNeed = 0;
15356     return '\ufffd'.repeat(p);
15357   }
15358   if (self.lastNeed > 1 && buf.length > 1) {
15359     if ((buf[1] & 0xC0) !== 0x80) {
15360       self.lastNeed = 1;
15361       return '\ufffd'.repeat(p + 1);
15362     }
15363     if (self.lastNeed > 2 && buf.length > 2) {
15364       if ((buf[2] & 0xC0) !== 0x80) {
15365         self.lastNeed = 2;
15366         return '\ufffd'.repeat(p + 2);
15367       }
15368     }
15369   }
15370 }
15371
15372 // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
15373 function utf8FillLast(buf) {
15374   var p = this.lastTotal - this.lastNeed;
15375   var r = utf8CheckExtraBytes(this, buf, p);
15376   if (r !== undefined) return r;
15377   if (this.lastNeed <= buf.length) {
15378     buf.copy(this.lastChar, p, 0, this.lastNeed);
15379     return this.lastChar.toString(this.encoding, 0, this.lastTotal);
15380   }
15381   buf.copy(this.lastChar, p, 0, buf.length);
15382   this.lastNeed -= buf.length;
15383 }
15384
15385 // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
15386 // partial character, the character's bytes are buffered until the required
15387 // number of bytes are available.
15388 function utf8Text(buf, i) {
15389   var total = utf8CheckIncomplete(this, buf, i);
15390   if (!this.lastNeed) return buf.toString('utf8', i);
15391   this.lastTotal = total;
15392   var end = buf.length - (total - this.lastNeed);
15393   buf.copy(this.lastChar, 0, end);
15394   return buf.toString('utf8', i, end);
15395 }
15396
15397 // For UTF-8, a replacement character for each buffered byte of a (partial)
15398 // character needs to be added to the output.
15399 function utf8End(buf) {
15400   var r = buf && buf.length ? this.write(buf) : '';
15401   if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
15402   return r;
15403 }
15404
15405 // UTF-16LE typically needs two bytes per character, but even if we have an even
15406 // number of bytes available, we need to check if we end on a leading/high
15407 // surrogate. In that case, we need to wait for the next two bytes in order to
15408 // decode the last character properly.
15409 function utf16Text(buf, i) {
15410   if ((buf.length - i) % 2 === 0) {
15411     var r = buf.toString('utf16le', i);
15412     if (r) {
15413       var c = r.charCodeAt(r.length - 1);
15414       if (c >= 0xD800 && c <= 0xDBFF) {
15415         this.lastNeed = 2;
15416         this.lastTotal = 4;
15417         this.lastChar[0] = buf[buf.length - 2];
15418         this.lastChar[1] = buf[buf.length - 1];
15419         return r.slice(0, -1);
15420       }
15421     }
15422     return r;
15423   }
15424   this.lastNeed = 1;
15425   this.lastTotal = 2;
15426   this.lastChar[0] = buf[buf.length - 1];
15427   return buf.toString('utf16le', i, buf.length - 1);
15428 }
15429
15430 // For UTF-16LE we do not explicitly append special replacement characters if we
15431 // end on a partial character, we simply let v8 handle that.
15432 function utf16End(buf) {
15433   var r = buf && buf.length ? this.write(buf) : '';
15434   if (this.lastNeed) {
15435     var end = this.lastTotal - this.lastNeed;
15436     return r + this.lastChar.toString('utf16le', 0, end);
15437   }
15438   return r;
15439 }
15440
15441 function base64Text(buf, i) {
15442   var n = (buf.length - i) % 3;
15443   if (n === 0) return buf.toString('base64', i);
15444   this.lastNeed = 3 - n;
15445   this.lastTotal = 3;
15446   if (n === 1) {
15447     this.lastChar[0] = buf[buf.length - 1];
15448   } else {
15449     this.lastChar[0] = buf[buf.length - 2];
15450     this.lastChar[1] = buf[buf.length - 1];
15451   }
15452   return buf.toString('base64', i, buf.length - n);
15453 }
15454
15455 function base64End(buf) {
15456   var r = buf && buf.length ? this.write(buf) : '';
15457   if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
15458   return r;
15459 }
15460
15461 // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
15462 function simpleWrite(buf) {
15463   return buf.toString(this.encoding);
15464 }
15465
15466 function simpleEnd(buf) {
15467   return buf && buf.length ? this.write(buf) : '';
15468 }
15469 },{"buffer":32,"buffer-shims":31}],66:[function(require,module,exports){
15470 (function (setImmediate,clearImmediate){
15471 var nextTick = require('process/browser.js').nextTick;
15472 var apply = Function.prototype.apply;
15473 var slice = Array.prototype.slice;
15474 var immediateIds = {};
15475 var nextImmediateId = 0;
15476
15477 // DOM APIs, for completeness
15478
15479 exports.setTimeout = function() {
15480   return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
15481 };
15482 exports.setInterval = function() {
15483   return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
15484 };
15485 exports.clearTimeout =
15486 exports.clearInterval = function(timeout) { timeout.close(); };
15487
15488 function Timeout(id, clearFn) {
15489   this._id = id;
15490   this._clearFn = clearFn;
15491 }
15492 Timeout.prototype.unref = Timeout.prototype.ref = function() {};
15493 Timeout.prototype.close = function() {
15494   this._clearFn.call(window, this._id);
15495 };
15496
15497 // Does not start the time, just sets up the members needed.
15498 exports.enroll = function(item, msecs) {
15499   clearTimeout(item._idleTimeoutId);
15500   item._idleTimeout = msecs;
15501 };
15502
15503 exports.unenroll = function(item) {
15504   clearTimeout(item._idleTimeoutId);
15505   item._idleTimeout = -1;
15506 };
15507
15508 exports._unrefActive = exports.active = function(item) {
15509   clearTimeout(item._idleTimeoutId);
15510
15511   var msecs = item._idleTimeout;
15512   if (msecs >= 0) {
15513     item._idleTimeoutId = setTimeout(function onTimeout() {
15514       if (item._onTimeout)
15515         item._onTimeout();
15516     }, msecs);
15517   }
15518 };
15519
15520 // That's not how node.js implements it but the exposed api is the same.
15521 exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
15522   var id = nextImmediateId++;
15523   var args = arguments.length < 2 ? false : slice.call(arguments, 1);
15524
15525   immediateIds[id] = true;
15526
15527   nextTick(function onNextTick() {
15528     if (immediateIds[id]) {
15529       // fn.call() is faster so we optimize for the common use-case
15530       // @see http://jsperf.com/call-apply-segu
15531       if (args) {
15532         fn.apply(null, args);
15533       } else {
15534         fn.call(null);
15535       }
15536       // Prevent ids from leaking
15537       exports.clearImmediate(id);
15538     }
15539   });
15540
15541   return id;
15542 };
15543
15544 exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
15545   delete immediateIds[id];
15546 };
15547 }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
15548 },{"process/browser.js":51,"timers":66}],67:[function(require,module,exports){
15549 (function (global){
15550
15551 /**
15552  * Module exports.
15553  */
15554
15555 module.exports = deprecate;
15556
15557 /**
15558  * Mark that a method should not be used.
15559  * Returns a modified function which warns once by default.
15560  *
15561  * If `localStorage.noDeprecation = true` is set, then it is a no-op.
15562  *
15563  * If `localStorage.throwDeprecation = true` is set, then deprecated functions
15564  * will throw an Error when invoked.
15565  *
15566  * If `localStorage.traceDeprecation = true` is set, then deprecated functions
15567  * will invoke `console.trace()` instead of `console.error()`.
15568  *
15569  * @param {Function} fn - the function to deprecate
15570  * @param {String} msg - the string to print to the console when `fn` is invoked
15571  * @returns {Function} a new "deprecated" version of `fn`
15572  * @api public
15573  */
15574
15575 function deprecate (fn, msg) {
15576   if (config('noDeprecation')) {
15577     return fn;
15578   }
15579
15580   var warned = false;
15581   function deprecated() {
15582     if (!warned) {
15583       if (config('throwDeprecation')) {
15584         throw new Error(msg);
15585       } else if (config('traceDeprecation')) {
15586         console.trace(msg);
15587       } else {
15588         console.warn(msg);
15589       }
15590       warned = true;
15591     }
15592     return fn.apply(this, arguments);
15593   }
15594
15595   return deprecated;
15596 }
15597
15598 /**
15599  * Checks `localStorage` for boolean values for the given `name`.
15600  *
15601  * @param {String} name
15602  * @returns {Boolean}
15603  * @api private
15604  */
15605
15606 function config (name) {
15607   // accessing global.localStorage can trigger a DOMException in sandboxed iframes
15608   try {
15609     if (!global.localStorage) return false;
15610   } catch (_) {
15611     return false;
15612   }
15613   var val = global.localStorage[name];
15614   if (null == val) return false;
15615   return String(val).toLowerCase() === 'true';
15616 }
15617
15618 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15619 },{}],68:[function(require,module,exports){
15620 arguments[4][25][0].apply(exports,arguments)
15621 },{"dup":25}],69:[function(require,module,exports){
15622 arguments[4][26][0].apply(exports,arguments)
15623 },{"./support/isBuffer":68,"_process":51,"dup":26,"inherits":36}]},{},[20])(20)
15624 });