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){
5 var interlaceUtils = require('./interlace');
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');
18 var pixel = data[rawPos];
19 pxData[pxPos] = pixel;
20 pxData[pxPos + 1] = pixel;
21 pxData[pxPos + 2] = pixel;
22 pxData[pxPos + 3] = 0xff;
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');
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];
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');
46 pxData[pxPos] = data[rawPos];
47 pxData[pxPos + 1] = data[rawPos + 1];
48 pxData[pxPos + 2] = data[rawPos + 2];
49 pxData[pxPos + 3] = 0xff;
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');
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];
66 var pixelBppCustomMapper = [
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;
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];
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;
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];
109 function bitRetriever(data, depth) {
115 if (i === data.length) {
116 throw new Error('Ran out of data');
120 var byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
123 throw new Error('unrecognised depth');
127 leftOver.push(((byte << 8) + byte2));
132 leftOver.push(byte1, byte2);
136 byte3 = byte >> 2 & 3;
137 byte2 = byte >> 4 & 3;
138 byte1 = byte >> 6 & 3;
139 leftOver.push(byte1, byte2, byte3, byte4);
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);
156 get: function(count) {
157 while (leftOver.length < count) {
160 var returner = leftOver.slice(0, count);
161 leftOver = leftOver.slice(count);
164 resetAfterLine: function() {
168 if (i !== data.length) {
169 throw new Error('extra data found');
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
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);
199 bits.resetAfterLine();
203 exports.dataToBitMap = function(data, bitmapInfo) {
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;
212 var bits = bitRetriever(data, depth);
216 pxData = new Buffer(width * height * 4);
219 pxData = new Uint16Array(width * height * 4);
221 var maxBit = Math.pow(2, depth) - 1;
227 images = interlaceUtils.getImagePasses(width, height);
228 getPxPos = interlaceUtils.getInterlaceIterator(width, height);
231 var nonInterlacedPxPos = 0;
232 getPxPos = function() {
233 var returner = nonInterlacedPxPos;
234 nonInterlacedPxPos += 4;
237 images = [{ width: width, height: height }];
240 for (var imageIndex = 0; imageIndex < images.length; imageIndex++) {
242 rawPos = mapImage8Bit(images[imageIndex], pxData, getPxPos, bpp, data, rawPos);
245 mapImageCustomBit(images[imageIndex], pxData, getPxPos, bpp, bits, maxBit);
249 if (rawPos !== data.length) {
250 throw new Error('extra data found');
260 }).call(this,require("buffer").Buffer)
261 },{"./interlace":11,"buffer":32}],2:[function(require,module,exports){
265 var constants = require('./constants');
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;
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)) {
282 // map to a UInt16 array if data is 16bit, fix endianness below
283 var data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
286 var inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
287 if (inBpp === 4 && !options.inputHasAlpha) {
290 var outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
291 if (options.bitDepth === 16) {
295 var outData = new Buffer(width * height * outBpp);
300 var bgColor = options.bgColor || {};
301 if (bgColor.red === undefined) {
302 bgColor.red = maxValue;
304 if (bgColor.green === undefined) {
305 bgColor.green = maxValue;
307 if (bgColor.blue === undefined) {
308 bgColor.blue = maxValue;
315 var alpha = maxValue;
316 switch (options.inputColorType) {
317 case constants.COLORTYPE_COLOR_ALPHA:
318 alpha = data[inIndex + 3];
320 green = data[inIndex + 1];
321 blue = data[inIndex + 2];
323 case constants.COLORTYPE_COLOR:
325 green = data[inIndex + 1];
326 blue = data[inIndex + 2];
328 case constants.COLORTYPE_ALPHA:
329 alpha = data[inIndex + 1];
334 case constants.COLORTYPE_GRAYSCALE:
340 throw new Error('input color type:' + options.inputColorType + ' is not supported at present');
343 if (options.inputHasAlpha) {
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);
351 return { red: red, green: green, blue: blue, alpha: alpha };
354 for (var y = 0; y < height; y++) {
355 for (var x = 0; x < width; x++) {
356 var rgba = getRGBA(data, inIndex);
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;
366 outData[outIndex + 3] = rgba.alpha;
370 outData.writeUInt16BE(rgba.red, outIndex);
371 outData.writeUInt16BE(rgba.green, outIndex + 2);
372 outData.writeUInt16BE(rgba.blue, outIndex + 4);
374 outData.writeUInt16BE(rgba.alpha, outIndex + 6);
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;
385 outData[outIndex + 1] = rgba.alpha;
389 outData.writeUInt16BE(grayscale, outIndex);
391 outData.writeUInt16BE(rgba.alpha, outIndex + 2);
396 throw new Error('unrecognised color Type ' + options.colorType);
407 }).call(this,require("buffer").Buffer)
408 },{"./constants":4,"buffer":32}],3:[function(require,module,exports){
409 (function (process,Buffer){
413 var util = require('util');
414 var Stream = require('stream');
417 var ChunkStream = module.exports = function() {
424 this._paused = false;
426 this._encoding = 'utf8';
427 this.writable = true;
429 util.inherits(ChunkStream, Stream);
432 ChunkStream.prototype.read = function(length, callback) {
435 length: Math.abs(length), // if length < 0 then at most this length
436 allowLess: length < 0,
440 process.nextTick(function() {
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;
452 ChunkStream.prototype.write = function(data, encoding) {
454 if (!this.writable) {
455 this.emit('error', new Error('Stream not writable'));
460 if (Buffer.isBuffer(data)) {
464 dataBuffer = new Buffer(data, encoding || this._encoding);
467 this._buffers.push(dataBuffer);
468 this._buffered += dataBuffer.length;
472 // ok if there are no more read requests
473 if (this._reads && this._reads.length === 0) {
477 return this.writable && !this._paused;
480 ChunkStream.prototype.end = function(data, encoding) {
483 this.write(data, encoding);
486 this.writable = false;
489 if (!this._buffers) {
493 // enqueue or handle end
494 if (this._buffers.length === 0) {
498 this._buffers.push(null);
503 ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
505 ChunkStream.prototype._end = function() {
507 if (this._reads.length > 0) {
509 new Error('Unexpected end of input')
516 ChunkStream.prototype.destroy = function() {
518 if (!this._buffers) {
522 this.writable = false;
524 this._buffers = null;
529 ChunkStream.prototype._processReadAllowingLess = function(read) {
530 // ok there is any data so that we can satisfy this request
531 this._reads.shift(); // == read
533 // first we need to peek into first buffer
534 var smallerBuf = this._buffers[0];
536 // ok there is more data than we need
537 if (smallerBuf.length > read.length) {
539 this._buffered -= read.length;
540 this._buffers[0] = smallerBuf.slice(read.length);
542 read.func.call(this, smallerBuf.slice(0, read.length));
546 // ok this is less than maximum length so use it all
547 this._buffered -= smallerBuf.length;
548 this._buffers.shift(); // == smallerBuf
550 read.func.call(this, smallerBuf);
554 ChunkStream.prototype._processRead = function(read) {
555 this._reads.shift(); // == read
559 var data = new Buffer(read.length);
561 // create buffer for all data
562 while (pos < read.length) {
564 var buf = this._buffers[count++];
565 var len = Math.min(buf.length, read.length - pos);
567 buf.copy(data, pos, 0, len);
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);
576 // remove all used buffers
578 this._buffers.splice(0, count);
581 this._buffered -= read.length;
583 read.func.call(this, data);
586 ChunkStream.prototype._process = function() {
589 // as long as there is any data and read requests
590 while (this._buffered > 0 && this._reads && this._reads.length > 0) {
592 var read = this._reads[0];
594 // read any data (but no more than length)
595 if (read.allowLess) {
596 this._processReadAllowingLess(read);
599 else if (this._buffered >= read.length) {
600 // ok we can meet some expectations
602 this._processRead(read);
605 // not enought data to satisfy first request in queue
606 // so we need to wait for more
611 if (this._buffers && !this.writable) {
616 this.emit('error', ex);
620 }).call(this,require('_process'),require("buffer").Buffer)
621 },{"_process":51,"buffer":32,"stream":64,"util":69}],4:[function(require,module,exports){
627 PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
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
637 COLORTYPE_GRAYSCALE: 0,
638 COLORTYPE_PALETTE: 1,
640 COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
642 // color-type combinations
643 COLORTYPE_PALETTE_COLOR: 3,
644 COLORTYPE_COLOR_ALPHA: 6,
646 COLORTYPE_TO_BPP_MAP: {
654 GAMMA_DIVISION: 100000
657 },{}],5:[function(require,module,exports){
663 for (var i = 0; i < 256; i++) {
665 for (var j = 0; j < 8; j++) {
666 if (currentCrc & 1) {
667 currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
670 currentCrc = currentCrc >>> 1;
673 crcTable[i] = currentCrc;
677 var CrcCalculator = module.exports = function() {
681 CrcCalculator.prototype.write = function(data) {
683 for (var i = 0; i < data.length; i++) {
684 this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
689 CrcCalculator.prototype.crc32 = function() {
690 return this._crc ^ -1;
694 CrcCalculator.crc32 = function(buf) {
697 for (var i = 0; i < buf.length; i++) {
698 crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
703 },{}],6:[function(require,module,exports){
707 var paethPredictor = require('./paeth-predictor');
709 function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
711 for (var x = 0; x < byteWidth; x++) {
712 rawData[rawPos + x] = pxData[pxPos + x];
716 function filterSumNone(pxData, pxPos, byteWidth) {
719 var length = pxPos + byteWidth;
721 for (var i = pxPos; i < length; i++) {
722 sum += Math.abs(pxData[i]);
727 function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
729 for (var x = 0; x < byteWidth; x++) {
731 var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
732 var val = pxData[pxPos + x] - left;
734 rawData[rawPos + x] = val;
738 function filterSumSub(pxData, pxPos, byteWidth, bpp) {
741 for (var x = 0; x < byteWidth; x++) {
743 var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
744 var val = pxData[pxPos + x] - left;
746 sum += Math.abs(val);
752 function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
754 for (var x = 0; x < byteWidth; x++) {
756 var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
757 var val = pxData[pxPos + x] - up;
759 rawData[rawPos + x] = val;
763 function filterSumUp(pxData, pxPos, byteWidth) {
766 var length = pxPos + byteWidth;
767 for (var x = pxPos; x < length; x++) {
769 var up = pxPos > 0 ? pxData[x - byteWidth] : 0;
770 var val = pxData[x] - up;
772 sum += Math.abs(val);
778 function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
780 for (var x = 0; x < byteWidth; x++) {
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);
786 rawData[rawPos + x] = val;
790 function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
793 for (var x = 0; x < byteWidth; x++) {
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);
799 sum += Math.abs(val);
805 function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
807 for (var x = 0; x < byteWidth; x++) {
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);
814 rawData[rawPos + x] = val;
818 function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
820 for (var x = 0; x < byteWidth; x++) {
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);
827 sum += Math.abs(val);
849 module.exports = function(pxData, width, height, options, bpp) {
852 if (!('filterType' in options) || options.filterType === -1) {
853 filterTypes = [0, 1, 2, 3, 4];
855 else if (typeof options.filterType === 'number') {
856 filterTypes = [options.filterType];
859 throw new Error('unrecognised filter types');
862 if (options.bitDepth === 16) {
865 var byteWidth = width * bpp;
868 var rawData = new Buffer((byteWidth + 1) * height);
870 var sel = filterTypes[0];
872 for (var y = 0; y < height; y++) {
874 if (filterTypes.length > 1) {
875 // find best filter for this line (with lowest sum of values)
878 for (var i = 0; i < filterTypes.length; i++) {
879 var sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
881 sel = filterTypes[i];
887 rawData[rawPos] = sel;
889 filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
896 }).call(this,require("buffer").Buffer)
897 },{"./paeth-predictor":15,"buffer":32}],7:[function(require,module,exports){
901 var util = require('util');
902 var ChunkStream = require('./chunkstream');
903 var Filter = require('./filter-parse');
906 var FilterAsync = module.exports = function(bitmapInfo) {
907 ChunkStream.call(this);
911 this._filter = new Filter(bitmapInfo, {
912 read: this.read.bind(this),
913 write: function(buffer) {
914 buffers.push(buffer);
916 complete: function() {
917 that.emit('complete', Buffer.concat(buffers));
921 this._filter.start();
923 util.inherits(FilterAsync, ChunkStream);
925 }).call(this,require("buffer").Buffer)
926 },{"./chunkstream":3,"./filter-parse":9,"buffer":32,"util":69}],8:[function(require,module,exports){
930 var SyncReader = require('./sync-reader');
931 var Filter = require('./filter-parse');
934 exports.process = function(inBuffer, bitmapInfo) {
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);
943 complete: function() {
950 return Buffer.concat(outBuffers);
952 }).call(this,require("buffer").Buffer)
953 },{"./filter-parse":9,"./sync-reader":22,"buffer":32}],9:[function(require,module,exports){
957 var interlaceUtils = require('./interlace');
958 var paethPredictor = require('./paeth-predictor');
960 function getByteWidth(width, bpp, depth) {
961 var byteWidth = width * bpp;
963 byteWidth = Math.ceil(byteWidth / (8 / depth));
968 var Filter = module.exports = function(bitmapInfo, dependencies) {
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;
976 this.read = dependencies.read;
977 this.write = dependencies.write;
978 this.complete = dependencies.complete;
980 this._imageIndex = 0;
983 var passes = interlaceUtils.getImagePasses(width, height);
984 for (var i = 0; i < passes.length; i++) {
986 byteWidth: getByteWidth(passes[i].width, bpp, depth),
987 height: passes[i].height,
994 byteWidth: getByteWidth(width, bpp, depth),
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.
1005 this._xComparison = bpp;
1007 else if (depth === 16) {
1008 this._xComparison = bpp * 2;
1011 this._xComparison = 1;
1015 Filter.prototype.start = function() {
1016 this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this));
1019 Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
1021 var xComparison = this._xComparison;
1022 var xBiggerThan = xComparison - 1;
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;
1031 Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
1033 var lastLine = this._lastLine;
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;
1042 Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
1044 var xComparison = this._xComparison;
1045 var xBiggerThan = xComparison - 1;
1046 var lastLine = this._lastLine;
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;
1057 Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
1059 var xComparison = this._xComparison;
1060 var xBiggerThan = xComparison - 1;
1061 var lastLine = this._lastLine;
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;
1073 Filter.prototype._reverseFilterLine = function(rawData) {
1075 var filter = rawData[0];
1077 var currentImage = this._images[this._imageIndex];
1078 var byteWidth = currentImage.byteWidth;
1081 unfilteredLine = rawData.slice(1, byteWidth + 1);
1085 unfilteredLine = new Buffer(byteWidth);
1089 this._unFilterType1(rawData, unfilteredLine, byteWidth);
1092 this._unFilterType2(rawData, unfilteredLine, byteWidth);
1095 this._unFilterType3(rawData, unfilteredLine, byteWidth);
1098 this._unFilterType4(rawData, unfilteredLine, byteWidth);
1101 throw new Error('Unrecognised filter type - ' + filter);
1105 this.write(unfilteredLine);
1107 currentImage.lineIndex++;
1108 if (currentImage.lineIndex >= currentImage.height) {
1109 this._lastLine = null;
1111 currentImage = this._images[this._imageIndex];
1114 this._lastLine = unfilteredLine;
1118 // read, using the byte width that may be from the new current image
1119 this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
1122 this._lastLine = null;
1127 }).call(this,require("buffer").Buffer)
1128 },{"./interlace":11,"./paeth-predictor":15,"buffer":32}],10:[function(require,module,exports){
1132 function dePalette(indata, outdata, width, height, palette) {
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]];
1140 throw new Error('index ' + indata[pxPos] + ' not in palette');
1143 for (var i = 0; i < 4; i++) {
1144 outdata[pxPos + i] = color[i];
1151 function replaceTransparentColor(indata, outdata, width, height, transColor) {
1153 for (var y = 0; y < height; y++) {
1154 for (var x = 0; x < width; x++) {
1155 var makeTrans = false;
1157 if (transColor.length === 1) {
1158 if (transColor[0] === indata[pxPos]) {
1162 else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) {
1166 for (var i = 0; i < 4; i++) {
1167 outdata[pxPos + i] = 0;
1175 function scaleDepth(indata, outdata, width, height, depth) {
1176 var maxOutSample = 255;
1177 var maxInSample = Math.pow(2, depth) - 1;
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);
1190 module.exports = function(indata, imageData) {
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;
1199 var outdata = indata; // only different for 16 bits
1201 if (colorType === 3) { // paletted
1202 dePalette(indata, outdata, width, height, palette);
1206 replaceTransparentColor(indata, outdata, width, height, transColor);
1208 // if it needs scaling
1210 // if we need to change the buffer size
1212 outdata = new Buffer(width * height * 4);
1214 scaleDepth(indata, outdata, width, height, depth);
1220 }).call(this,require("buffer").Buffer)
1221 },{"buffer":32}],11:[function(require,module,exports){
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
1262 x: [0, 1, 2, 3, 4, 5, 6, 7],
1267 exports.getImagePasses = function(width, height) {
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) {
1285 for (j = 0; j < pass.y.length; j++) {
1286 if (pass.y[j] < yLeftOver) {
1293 if (passWidth > 0 && passHeight > 0) {
1294 images.push({ width: passWidth, height: passHeight, index: i });
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);
1309 },{}],12:[function(require,module,exports){
1313 var util = require('util');
1314 var Stream = require('stream');
1315 var constants = require('./constants');
1316 var Packer = require('./packer');
1318 var PackerAsync = module.exports = function(opt) {
1321 var options = opt || {};
1323 this._packer = new Packer(options);
1324 this._deflate = this._packer.createDeflate();
1326 this.readable = true;
1328 util.inherits(PackerAsync, Stream);
1331 PackerAsync.prototype.pack = function(data, width, height, gamma) {
1333 this.emit('data', new Buffer(constants.PNG_SIGNATURE));
1334 this.emit('data', this._packer.packIHDR(width, height));
1337 this.emit('data', this._packer.packGAMA(gamma));
1340 var filteredData = this._packer.filterData(data, width, height);
1343 this._deflate.on('error', this.emit.bind(this, 'error'));
1345 this._deflate.on('data', function(compressedData) {
1346 this.emit('data', this._packer.packIDAT(compressedData));
1349 this._deflate.on('end', function() {
1350 this.emit('data', this._packer.packIEND());
1354 this._deflate.end(filteredData);
1357 }).call(this,require("buffer").Buffer)
1358 },{"./constants":4,"./packer":14,"buffer":32,"stream":64,"util":69}],13:[function(require,module,exports){
1362 var hasSyncZlib = true;
1363 var zlib = require('zlib');
1364 if (!zlib.deflateSync) {
1365 hasSyncZlib = false;
1367 var constants = require('./constants');
1368 var Packer = require('./packer');
1370 module.exports = function(metaData, opt) {
1373 throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
1376 var options = opt || {};
1378 var packer = new Packer(options);
1383 chunks.push(new Buffer(constants.PNG_SIGNATURE));
1386 chunks.push(packer.packIHDR(metaData.width, metaData.height));
1388 if (metaData.gamma) {
1389 chunks.push(packer.packGAMA(metaData.gamma));
1392 var filteredData = packer.filterData(metaData.data, metaData.width, metaData.height);
1395 var compressedData = zlib.deflateSync(filteredData, packer.getDeflateOptions());
1396 filteredData = null;
1398 if (!compressedData || !compressedData.length) {
1399 throw new Error('bad png - invalid compressed data response');
1401 chunks.push(packer.packIDAT(compressedData));
1404 chunks.push(packer.packIEND());
1406 return Buffer.concat(chunks);
1409 }).call(this,require("buffer").Buffer)
1410 },{"./constants":4,"./packer":14,"buffer":32,"zlib":30}],14:[function(require,module,exports){
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');
1420 var Packer = module.exports = function(options) {
1421 this._options = options;
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;
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');
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');
1449 if (options.bitDepth !== 8 && options.bitDepth !== 16) {
1450 throw new Error('option bit depth:' + options.bitDepth + ' is not supported at present');
1454 Packer.prototype.getDeflateOptions = function() {
1456 chunkSize: this._options.deflateChunkSize,
1457 level: this._options.deflateLevel,
1458 strategy: this._options.deflateStrategy
1462 Packer.prototype.createDeflate = function() {
1463 return this._options.deflateFactory(this.getDeflateOptions());
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);
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;
1476 Packer.prototype._packChunk = function(type, data) {
1478 var len = (data ? data.length : 0);
1479 var buf = new Buffer(len + 12);
1481 buf.writeUInt32BE(len, 0);
1482 buf.writeUInt32BE(type, 4);
1488 buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4);
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);
1498 Packer.prototype.packIHDR = function(width, height) {
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
1509 return this._packChunk(constants.TYPE_IHDR, buf);
1512 Packer.prototype.packIDAT = function(data) {
1513 return this._packChunk(constants.TYPE_IDAT, data);
1516 Packer.prototype.packIEND = function() {
1517 return this._packChunk(constants.TYPE_IEND, null);
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){
1524 module.exports = function paethPredictor(left, above, upLeft) {
\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
1531 if (pLeft <= pAbove && pLeft <= pUpLeft) {
\r
1534 if (pAbove <= pUpLeft) {
\r
1539 },{}],16:[function(require,module,exports){
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');
1550 var ParserAsync = module.exports = function(options) {
1551 ChunkStream.call(this);
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)
1565 this._options = options;
1566 this.writable = true;
1568 this._parser.start();
1570 util.inherits(ParserAsync, ChunkStream);
1573 ParserAsync.prototype._handleError = function(err) {
1575 this.emit('error', err);
1577 this.writable = false;
1581 if (this._inflate && this._inflate.destroy) {
1582 this._inflate.destroy();
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() {});
1596 ParserAsync.prototype._inflateData = function(data) {
1597 if (!this._inflate) {
1598 if (this._bitmapInfo.interlace) {
1599 this._inflate = zlib.createInflate();
1601 this._inflate.on('error', this.emit.bind(this, 'error'));
1602 this._filter.on('complete', this._complete.bind(this));
1604 this._inflate.pipe(this._filter);
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);
1611 this._inflate = zlib.createInflate({ chunkSize: chunkSize });
1612 var leftToInflate = imageSize;
1614 var emitError = this.emit.bind(this, 'error');
1615 this._inflate.on('error', function(err) {
1616 if (!leftToInflate) {
1622 this._filter.on('complete', this._complete.bind(this));
1624 var filterWrite = this._filter.write.bind(this._filter);
1625 this._inflate.on('data', function(chunk) {
1626 if (!leftToInflate) {
1630 if (chunk.length > leftToInflate) {
1631 chunk = chunk.slice(0, leftToInflate);
1634 leftToInflate -= chunk.length;
1639 this._inflate.on('end', this._filter.end.bind(this._filter));
1642 this._inflate.write(data);
1645 ParserAsync.prototype._handleMetaData = function(metaData) {
1646 this._metaData = metaData;
1647 this._bitmapInfo = Object.create(metaData);
1649 this._filter = new FilterAsync(this._bitmapInfo);
1652 ParserAsync.prototype._handleTransColor = function(transColor) {
1653 this._bitmapInfo.transColor = transColor;
1656 ParserAsync.prototype._handlePalette = function(palette) {
1657 this._bitmapInfo.palette = palette;
1660 ParserAsync.prototype._simpleTransparency = function() {
1661 this._metaData.alpha = true;
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);
1670 ParserAsync.prototype._finished = function() {
1675 if (!this._inflate) {
1676 this.emit('error', 'No Inflate block');
1679 // no more data to inflate
1680 this._inflate.end();
1685 ParserAsync.prototype._complete = function(filteredData) {
1692 var bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
1694 var normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo);
1698 this._handleError(ex);
1702 this.emit('parsed', normalisedBitmapData);
1705 },{"./bitmapper":1,"./chunkstream":3,"./filter-parse-async":7,"./format-normaliser":10,"./parser":18,"util":69,"zlib":30}],17:[function(require,module,exports){
1709 var hasSyncZlib = true;
1710 var zlib = require('zlib');
1711 var inflateSync = require('./sync-inflate');
1712 if (!zlib.deflateSync) {
1713 hasSyncZlib = false;
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');
1722 module.exports = function(buffer, options) {
1725 throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
1729 function handleError(_err_) {
1734 function handleMetaData(_metaData_) {
1735 metaData = _metaData_;
1738 function handleTransColor(transColor) {
1739 metaData.transColor = transColor;
1742 function handlePalette(palette) {
1743 metaData.palette = palette;
1746 function handleSimpleTransparency() {
1747 metaData.alpha = true;
1751 function handleGamma(_gamma_) {
1755 var inflateDataList = [];
1756 function handleInflateData(inflatedData) {
1757 inflateDataList.push(inflatedData);
1760 var reader = new SyncReader(buffer);
1762 var parser = new Parser(options, {
1763 read: reader.read.bind(reader),
1765 metadata: handleMetaData,
1767 palette: handlePalette,
1768 transColor: handleTransColor,
1769 inflateData: handleInflateData,
1770 simpleTransparency: handleSimpleTransparency
1780 //join together the inflate datas
1781 var inflateData = Buffer.concat(inflateDataList);
1782 inflateDataList.length = 0;
1785 if (metaData.interlace) {
1786 inflatedData = zlib.inflateSync(inflateData);
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 });
1795 if (!inflatedData || !inflatedData.length) {
1796 throw new Error('bad png - invalid inflate data response');
1799 var unfilteredData = FilterSync.process(inflatedData, metaData);
1802 var bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
1803 unfilteredData = null;
1805 var normalisedBitmapData = formatNormaliser(bitmapData, metaData);
1807 metaData.data = normalisedBitmapData;
1808 metaData.gamma = gamma || 0;
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){
1818 var constants = require('./constants');
1819 var CrcCalculator = require('./crc');
1822 var Parser = module.exports = function(options, dependencies) {
1824 this._options = options;
1825 options.checkCRC = options.checkCRC !== false;
1827 this._hasIHDR = false;
1828 this._hasIEND = false;
1829 this._emittedHeadersFinished = false;
1831 // input flags/metadata
1833 this._colorType = 0;
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);
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() {};
1856 Parser.prototype.start = function() {
1857 this.read(constants.PNG_SIGNATURE.length,
1858 this._parseSignature.bind(this)
1862 Parser.prototype._parseSignature = function(data) {
1864 var signature = constants.PNG_SIGNATURE;
1866 for (var i = 0; i < signature.length; i++) {
1867 if (data[i] !== signature[i]) {
1868 this.error(new Error('Invalid file signature'));
1872 this.read(8, this._parseChunkBegin.bind(this));
1875 Parser.prototype._parseChunkBegin = function(data) {
1877 // chunk content length
1878 var length = data.readUInt32BE(0);
1881 var type = data.readUInt32BE(4);
1883 for (var i = 4; i < 8; i++) {
1884 name += String.fromCharCode(data[i]);
1887 //console.log('chunk ', name, length);
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
1894 if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
1895 this.error(new Error('Expected IHDR on beggining'));
1899 this._crc = new CrcCalculator();
1900 this._crc.write(new Buffer(name));
1902 if (this._chunks[type]) {
1903 return this._chunks[type](length);
1907 this.error(new Error('Unsupported critical chunk type ' + name));
1911 this.read(length + 4, this._skipChunk.bind(this));
1914 Parser.prototype._skipChunk = function(/*data*/) {
1915 this.read(8, this._parseChunkBegin.bind(this));
1918 Parser.prototype._handleChunkEnd = function() {
1919 this.read(4, this._parseChunkEnd.bind(this));
1922 Parser.prototype._parseChunkEnd = function(data) {
1924 var fileCrc = data.readInt32BE(0);
1925 var calcCrc = this._crc.crc32();
1928 if (this._options.checkCRC && calcCrc !== fileCrc) {
1929 this.error(new Error('Crc error - ' + fileCrc + ' - ' + calcCrc));
1933 if (!this._hasIEND) {
1934 this.read(8, this._parseChunkBegin.bind(this));
1938 Parser.prototype._handleIHDR = function(length) {
1939 this.read(length, this._parseIHDR.bind(this));
1941 Parser.prototype._parseIHDR = function(data) {
1943 this._crc.write(data);
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];
1953 // console.log(' width', width, 'height', height,
1954 // 'depth', depth, 'colorType', colorType,
1955 // 'compr', compr, 'filter', filter, 'interlace', interlace
1958 if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
1959 this.error(new Error('Unsupported bit depth ' + depth));
1962 if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
1963 this.error(new Error('Unsupported color type'));
1967 this.error(new Error('Unsupported compression method'));
1971 this.error(new Error('Unsupported filter method'));
1974 if (interlace !== 0 && interlace !== 1) {
1975 this.error(new Error('Unsupported interlace method'));
1979 this._colorType = colorType;
1981 var bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
1983 this._hasIHDR = true;
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),
1994 colorType: colorType
1997 this._handleChunkEnd();
2001 Parser.prototype._handlePLTE = function(length) {
2002 this.read(length, this._parsePLTE.bind(this));
2004 Parser.prototype._parsePLTE = function(data) {
2006 this._crc.write(data);
2008 var entries = Math.floor(data.length / 3);
2009 // console.log('Palette:', entries);
2011 for (var i = 0; i < entries; i++) {
2012 this._palette.push([
2020 this.palette(this._palette);
2022 this._handleChunkEnd();
2025 Parser.prototype._handleTRNS = function(length) {
2026 this.simpleTransparency();
2027 this.read(length, this._parseTRNS.bind(this));
2029 Parser.prototype._parseTRNS = function(data) {
2031 this._crc.write(data);
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'));
2039 if (data.length > this._palette.length) {
2040 this.error(new Error('More transparent colors than palette size'));
2043 for (var i = 0; i < data.length; i++) {
2044 this._palette[i][3] = data[i];
2046 this.palette(this._palette);
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) {
2053 this.transColor([data.readUInt16BE(0)]);
2055 if (this._colorType === constants.COLORTYPE_COLOR) {
2056 this.transColor([data.readUInt16BE(0), data.readUInt16BE(2), data.readUInt16BE(4)]);
2059 this._handleChunkEnd();
2062 Parser.prototype._handleGAMA = function(length) {
2063 this.read(length, this._parseGAMA.bind(this));
2065 Parser.prototype._parseGAMA = function(data) {
2067 this._crc.write(data);
2068 this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
2070 this._handleChunkEnd();
2073 Parser.prototype._handleIDAT = function(length) {
2074 if (!this._emittedHeadersFinished) {
2075 this._emittedHeadersFinished = true;
2076 this.headersFinished();
2078 this.read(-length, this._parseIDAT.bind(this, length));
2080 Parser.prototype._parseIDAT = function(length, data) {
2082 this._crc.write(data);
2084 if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
2085 throw new Error('Expected palette not found');
2088 this.inflateData(data);
2089 var leftOverLength = length - data.length;
2091 if (leftOverLength > 0) {
2092 this._handleIDAT(leftOverLength);
2095 this._handleChunkEnd();
2099 Parser.prototype._handleIEND = function(length) {
2100 this.read(length, this._parseIEND.bind(this));
2102 Parser.prototype._parseIEND = function(data) {
2104 this._crc.write(data);
2106 this._hasIEND = true;
2107 this._handleChunkEnd();
2109 if (this.finished) {
2114 }).call(this,require("buffer").Buffer)
2115 },{"./constants":4,"./crc":5,"buffer":32}],19:[function(require,module,exports){
2119 var parse = require('./parser-sync');
2120 var pack = require('./packer-sync');
2123 exports.read = function(buffer, options) {
2125 return parse(buffer, options || {});
2128 exports.write = function(png, options) {
2130 return pack(png, options);
2133 },{"./packer-sync":13,"./parser-sync":17}],20:[function(require,module,exports){
2134 (function (process,Buffer){
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');
2144 var PNG = exports.PNG = function(options) {
2147 options = options || {}; // eslint-disable-line no-param-reassign
2149 // coerce pixel dimensions to integers (also coerces undefined -> 0):
2150 this.width = options.width | 0;
2151 this.height = options.height | 0;
2153 this.data = this.width > 0 && this.height > 0 ?
2154 new Buffer(4 * this.width * this.height) : null;
2156 if (options.fill && this.data) {
2161 this.readable = this.writable = true;
2163 this._parser = new Parser(options);
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) {
2171 this.emit('parsed', data);
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'));
2181 util.inherits(PNG, Stream);
2185 PNG.prototype.pack = function() {
2187 if (!this.data || !this.data.length) {
2188 this.emit('error', 'No data provided');
2192 process.nextTick(function() {
2193 this._packer.pack(this.data, this.width, this.height, this.gamma);
2200 PNG.prototype.parse = function(data, callback) {
2203 var onParsed, onError;
2205 onParsed = function(parsedData) {
2206 this.removeListener('error', onError);
2208 this.data = parsedData;
2209 callback(null, this);
2212 onError = function(err) {
2213 this.removeListener('parsed', onParsed);
2215 callback(err, null);
2218 this.once('parsed', onParsed);
2219 this.once('error', onError);
2226 PNG.prototype.write = function(data) {
2227 this._parser.write(data);
2231 PNG.prototype.end = function(data) {
2232 this._parser.end(data);
2235 PNG.prototype._metadata = function(metadata) {
2236 this.width = metadata.width;
2237 this.height = metadata.height;
2239 this.emit('metadata', metadata);
2242 PNG.prototype._gamma = function(gamma) {
2246 PNG.prototype._handleClose = function() {
2247 if (!this._parser.writable && !this._packer.readable) {
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 */
2262 /* eslint-enable no-param-reassign */
2264 if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
2265 throw new Error('bitblt reading outside image');
2268 if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
2269 throw new Error('bitblt writing outside image');
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
2282 PNG.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
2284 PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
2288 PNG.adjustGamma = function(src) {
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;
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);
2305 PNG.prototype.adjustGamma = function() {
2306 PNG.adjustGamma(this);
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){
2314 var assert = require('assert').ok;
2315 var zlib = require('zlib');
2316 var util = require('util');
2318 var kMaxLength = require('buffer').kMaxLength;
2320 function Inflate(opts) {
2321 if (!(this instanceof Inflate)) {
2322 return new Inflate(opts);
2325 if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
2326 opts.chunkSize = zlib.Z_MIN_CHUNK;
2329 zlib.Inflate.call(this, opts);
2331 // Node 8 --> 9 compatibility check
2332 this._offset = this._offset === undefined ? this._outOffset : this._offset;
2333 this._buffer = this._buffer || this._outBuffer;
2335 if (opts && opts.maxLength != null) {
2336 this._maxLength = opts.maxLength;
2340 function createInflate(opts) {
2341 return new Inflate(opts);
2344 function _close(engine, callback) {
2346 process.nextTick(callback);
2349 // Caller may invoke .close after a zlib error (which will null _handle).
2350 if (!engine._handle) {
2354 engine._handle.close();
2355 engine._handle = null;
2358 Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) {
2359 if (typeof asyncCb === 'function') {
2360 return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
2365 var availInBefore = chunk && chunk.length;
2366 var availOutBefore = this._chunkSize - this._offset;
2367 var leftToInflate = this._maxLength;
2374 this.on('error', function(err) {
2378 function handleChunk(availInAfter, availOutAfter) {
2379 if (self._hadError) {
2383 var have = availOutBefore - availOutAfter;
2384 assert(have >= 0, 'have should not go down');
2387 var out = self._buffer.slice(self._offset, self._offset + have);
2388 self._offset += have;
2390 if (out.length > leftToInflate) {
2391 out = out.slice(0, leftToInflate);
2395 nread += out.length;
2396 leftToInflate -= out.length;
2398 if (leftToInflate === 0) {
2403 if (availOutAfter === 0 || self._offset >= self._chunkSize) {
2404 availOutBefore = self._chunkSize;
2406 self._buffer = Buffer.allocUnsafe(self._chunkSize);
2409 if (availOutAfter === 0) {
2410 inOff += (availInBefore - availInAfter);
2411 availInBefore = availInAfter;
2419 assert(this._handle, 'zlib binding closed');
2421 var res = this._handle.writeSync(flushFlag,
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]));
2432 if (this._hadError) {
2436 if (nread >= kMaxLength) {
2438 throw new RangeError('Cannot create final Buffer. It would be larger than 0x' + kMaxLength.toString(16) + ' bytes');
2441 var buf = Buffer.concat(buffers, nread);
2447 util.inherits(Inflate, zlib.Inflate);
2449 function zlibBufferSync(engine, buffer) {
2450 if (typeof buffer === 'string') {
2451 buffer = Buffer.from(buffer);
2453 if (!(buffer instanceof Buffer)) {
2454 throw new TypeError('Not a string or buffer');
2457 var flushFlag = engine._finishFlushFlag;
2458 if (flushFlag == null) {
2459 flushFlag = zlib.Z_FINISH;
2462 return engine._processChunk(buffer, flushFlag);
2465 function inflateSync(buffer, opts) {
2466 return zlibBufferSync(new Inflate(opts), buffer);
2469 module.exports = exports = inflateSync;
2470 exports.Inflate = Inflate;
2471 exports.createInflate = createInflate;
2472 exports.inflateSync = inflateSync;
2474 }).call(this,require('_process'),require("buffer").Buffer)
2475 },{"_process":51,"assert":23,"buffer":32,"util":69,"zlib":30}],22:[function(require,module,exports){
2478 var SyncReader = module.exports = function(buffer) {
2480 this._buffer = buffer;
2484 SyncReader.prototype.read = function(length, callback) {
2487 length: Math.abs(length), // if length < 0 then at most this length
2488 allowLess: length < 0,
2493 SyncReader.prototype.process = function() {
2495 // as long as there is any data and read requests
2496 while (this._reads.length > 0 && this._buffer.length) {
2498 var read = this._reads[0];
2500 if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
2502 // ok there is any data so that we can satisfy this request
2503 this._reads.shift(); // == read
2505 var buf = this._buffer;
2507 this._buffer = buf.slice(read.length);
2509 read.func.call(this, buf.slice(0, read.length));
2518 if (this._reads.length > 0) {
2519 return new Error('There are some read requests waitng on finished stream');
2522 if (this._buffer.length > 0) {
2523 return new Error('unrecognised content at end of stream');
2528 },{}],23:[function(require,module,exports){
2532 // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
2536 * The buffer module from node.js, for the browser.
2538 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
2541 function compare(a, b) {
2549 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
2550 if (a[i] !== b[i]) {
2565 function isBuffer(b) {
2566 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
2567 return global.Buffer.isBuffer(b);
2569 return !!(b != null && b._isBuffer);
2572 // based on node assert, original notice:
2574 // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
2576 // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
2578 // Originally from narwhal.js (http://narwhaljs.org)
2579 // Copyright (c) 2009 Thomas Robinson <280north.com>
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:
2588 // The above copyright notice and this permission notice shall be included in
2589 // all copies or substantial portions of the Software.
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.
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';
2604 function pToString (obj) {
2605 return Object.prototype.toString.call(obj);
2607 function isView(arrbuf) {
2608 if (isBuffer(arrbuf)) {
2611 if (typeof global.ArrayBuffer !== 'function') {
2614 if (typeof ArrayBuffer.isView === 'function') {
2615 return ArrayBuffer.isView(arrbuf);
2620 if (arrbuf instanceof DataView) {
2623 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
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.
2632 var assert = module.exports = ok;
2634 // 2. The AssertionError is defined in assert.
2635 // new assert.AssertionError({ message: message,
2637 // expected: expected })
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)) {
2645 if (functionsHaveNames) {
2648 var str = func.toString();
2649 var match = str.match(regex);
2650 return match && match[1];
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;
2661 this.message = getMessage(this);
2662 this.generatedMessage = true;
2664 var stackStartFunction = options.stackStartFunction || fail;
2665 if (Error.captureStackTrace) {
2666 Error.captureStackTrace(this, stackStartFunction);
2668 // non v8 browsers so we can have a stacktrace
2669 var err = new Error();
2671 var out = err.stack;
2673 // try to strip useless frames
2674 var fn_name = getName(stackStartFunction);
2675 var idx = out.indexOf('\n' + fn_name);
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);
2688 // assert.AssertionError instanceof Error
2689 util.inherits(assert.AssertionError, Error);
2691 function truncate(s, n) {
2692 if (typeof s === 'string') {
2693 return s.length < n ? s : s.slice(0, n);
2698 function inspect(something) {
2699 if (functionsHaveNames || !util.isFunction(something)) {
2700 return util.inspect(something);
2702 var rawname = getName(something);
2703 var name = rawname ? ': ' + rawname : '';
2704 return '[Function' + name + ']';
2706 function getMessage(self) {
2707 return truncate(inspect(self.actual), 128) + ' ' +
2708 self.operator + ' ' +
2709 truncate(inspect(self.expected), 128);
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
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.
2723 function fail(actual, expected, message, operator, stackStartFunction) {
2724 throw new assert.AssertionError({
2729 stackStartFunction: stackStartFunction
2733 // EXTENSION! allows for well behaved errors defined elsewhere.
2736 // 4. Pure assertion tests whether a value is truthy, as determined
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);.
2743 function ok(value, message) {
2744 if (!value) fail(value, true, message, '==', assert.ok);
2748 // 5. The equality assertion tests shallow, coercive equality with
2750 // assert.equal(actual, expected, message_opt);
2752 assert.equal = function equal(actual, expected, message) {
2753 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
2756 // 6. The non-equality assertion tests for whether two objects are not equal
2757 // with != assert.notEqual(actual, expected, message_opt);
2759 assert.notEqual = function notEqual(actual, expected, message) {
2760 if (actual == expected) {
2761 fail(actual, expected, message, '!=', assert.notEqual);
2765 // 7. The equivalence assertion tests a deep equality relation.
2766 // assert.deepEqual(actual, expected, message_opt);
2768 assert.deepEqual = function deepEqual(actual, expected, message) {
2769 if (!_deepEqual(actual, expected, false)) {
2770 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
2774 assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
2775 if (!_deepEqual(actual, expected, true)) {
2776 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
2780 function _deepEqual(actual, expected, strict, memos) {
2781 // 7.1. All identical values are equivalent, as determined by ===.
2782 if (actual === expected) {
2784 } else if (isBuffer(actual) && isBuffer(expected)) {
2785 return compare(actual, expected) === 0;
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();
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;
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;
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;
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)) {
2830 memos = memos || {actual: [], expected: []};
2832 var actualIndex = memos.actual.indexOf(actual);
2833 if (actualIndex !== -1) {
2834 if (actualIndex === memos.expected.indexOf(expected)) {
2839 memos.actual.push(actual);
2840 memos.expected.push(expected);
2842 return objEquiv(actual, expected, strict, memos);
2846 function isArguments(object) {
2847 return Object.prototype.toString.call(object) == '[object Arguments]';
2850 function objEquiv(a, b, strict, actualVisitedObjects) {
2851 if (a === null || a === undefined || b === null || b === undefined)
2853 // if one is a primitive, the other must be same
2854 if (util.isPrimitive(a) || util.isPrimitive(b))
2856 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
2858 var aIsArgs = isArguments(a);
2859 var bIsArgs = isArguments(b);
2860 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
2865 return _deepEqual(a, b, strict);
2867 var ka = objectKeys(a);
2868 var kb = objectKeys(b);
2870 // having the same number of owned properties (keys incorporates
2872 if (ka.length !== kb.length)
2874 //the same set of keys (although not necessarily the same order),
2878 for (i = ka.length - 1; i >= 0; i--) {
2879 if (ka[i] !== kb[i])
2882 //equivalent values for every corresponding key, and
2883 //~~~possibly expensive deep test
2884 for (i = ka.length - 1; i >= 0; i--) {
2886 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
2892 // 8. The non-equivalence assertion tests for any deep inequality.
2893 // assert.notDeepEqual(actual, expected, message_opt);
2895 assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
2896 if (_deepEqual(actual, expected, false)) {
2897 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
2901 assert.notDeepStrictEqual = notDeepStrictEqual;
2902 function notDeepStrictEqual(actual, expected, message) {
2903 if (_deepEqual(actual, expected, true)) {
2904 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
2909 // 9. The strict equality assertion tests strict equality, as determined by ===.
2910 // assert.strictEqual(actual, expected, message_opt);
2912 assert.strictEqual = function strictEqual(actual, expected, message) {
2913 if (actual !== expected) {
2914 fail(actual, expected, message, '===', assert.strictEqual);
2918 // 10. The strict non-equality assertion tests for strict inequality, as
2919 // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
2921 assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
2922 if (actual === expected) {
2923 fail(actual, expected, message, '!==', assert.notStrictEqual);
2927 function expectedException(actual, expected) {
2928 if (!actual || !expected) {
2932 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
2933 return expected.test(actual);
2937 if (actual instanceof expected) {
2941 // Ignore. The instanceof check doesn't work for arrow functions.
2944 if (Error.isPrototypeOf(expected)) {
2948 return expected.call({}, actual) === true;
2951 function _tryBlock(block) {
2961 function _throws(shouldThrow, block, expected, message) {
2964 if (typeof block !== 'function') {
2965 throw new TypeError('"block" argument must be a function');
2968 if (typeof expected === 'string') {
2973 actual = _tryBlock(block);
2975 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
2976 (message ? ' ' + message : '.');
2978 if (shouldThrow && !actual) {
2979 fail(actual, expected, 'Missing expected exception' + message);
2982 var userProvidedMessage = typeof message === 'string';
2983 var isUnwantedException = !shouldThrow && util.isError(actual);
2984 var isUnexpectedException = !shouldThrow && actual && !expected;
2986 if ((isUnwantedException &&
2987 userProvidedMessage &&
2988 expectedException(actual, expected)) ||
2989 isUnexpectedException) {
2990 fail(actual, expected, 'Got unwanted exception' + message);
2993 if ((shouldThrow && actual && expected &&
2994 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
2999 // 11. Expected to throw an error:
3000 // assert.throws(block, Error_opt, message_opt);
3002 assert.throws = function(block, /*optional*/error, /*optional*/message) {
3003 _throws(true, block, error, message);
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);
3011 assert.ifError = function(err) { if (err) throw err; };
3013 var objectKeys = Object.keys || function (obj) {
3015 for (var key in obj) {
3016 if (hasOwn.call(obj, key)) keys.push(key);
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, {
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
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';
3054 },{}],26:[function(require,module,exports){
3055 (function (process,global){
3056 // Copyright Joyent, Inc. and other Node contributors.
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:
3066 // The above copyright notice and this permission notice shall be included
3067 // in all copies or substantial portions of the Software.
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.
3077 var formatRegExp = /%[sdj%]/g;
3078 exports.format = function(f) {
3081 for (var i = 0; i < arguments.length; i++) {
3082 objects.push(inspect(arguments[i]));
3084 return objects.join(' ');
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;
3094 case '%s': return String(args[i++]);
3095 case '%d': return Number(args[i++]);
3098 return JSON.stringify(args[i++]);
3100 return '[Circular]';
3106 for (var x = args[i]; i < len; x = args[++i]) {
3107 if (isNull(x) || !isObject(x)) {
3110 str += ' ' + inspect(x);
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)) {
3124 return exports.deprecate(fn, msg).apply(this, arguments);
3128 if (process.noDeprecation === true) {
3133 function deprecated() {
3135 if (process.throwDeprecation) {
3136 throw new Error(msg);
3137 } else if (process.traceDeprecation) {
3144 return fn.apply(this, arguments);
3153 exports.debuglog = function(set) {
3154 if (isUndefined(debugEnviron))
3155 debugEnviron = process.env.NODE_DEBUG || '';
3156 set = set.toUpperCase();
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);
3165 debugs[set] = function() {};
3173 * Echos the value of a value. Trys to print the value out
3174 * in the best way possible given the different types.
3176 * @param {Object} obj The object to print out.
3177 * @param {Object} opts Optional options object that alters the output.
3179 /* legacy: obj, showHidden, depth, colors*/
3180 function inspect(obj, opts) {
3184 stylize: stylizeNoColor
3187 if (arguments.length >= 3) ctx.depth = arguments[2];
3188 if (arguments.length >= 4) ctx.colors = arguments[3];
3189 if (isBoolean(opts)) {
3191 ctx.showHidden = opts;
3193 // got an "options" object
3194 exports._extend(ctx, opts);
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);
3204 exports.inspect = inspect;
3207 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
3211 'underline' : [4, 24],
3212 'inverse' : [7, 27],
3219 'magenta' : [35, 39],
3224 // Don't use 'blue' not visible on cmd.exe
3228 'boolean': 'yellow',
3229 'undefined': 'grey',
3233 // "name": intentionally not styling
3238 function stylizeWithColor(str, styleType) {
3239 var style = inspect.styles[styleType];
3242 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
3243 '\u001b[' + inspect.colors[style][1] + 'm';
3250 function stylizeNoColor(str, styleType) {
3255 function arrayToHash(array) {
3258 array.forEach(function(val, idx) {
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 &&
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);
3283 // Primitive types cannot have properties
3284 var primitive = formatPrimitive(ctx, value);
3289 // Look up the keys of the object.
3290 var keys = Object.keys(value);
3291 var visibleKeys = arrayToHash(keys);
3293 if (ctx.showHidden) {
3294 keys = Object.getOwnPropertyNames(value);
3297 // IE doesn't make error fields non-enumerable
3298 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
3300 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
3301 return formatError(value);
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');
3310 if (isRegExp(value)) {
3311 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
3313 if (isDate(value)) {
3314 return ctx.stylize(Date.prototype.toString.call(value), 'date');
3316 if (isError(value)) {
3317 return formatError(value);
3321 var base = '', array = false, braces = ['{', '}'];
3323 // Make Array say that they are Array
3324 if (isArray(value)) {
3326 braces = ['[', ']'];
3329 // Make functions say that they are functions
3330 if (isFunction(value)) {
3331 var n = value.name ? ': ' + value.name : '';
3332 base = ' [Function' + n + ']';
3335 // Make RegExps say that they are RegExps
3336 if (isRegExp(value)) {
3337 base = ' ' + RegExp.prototype.toString.call(value);
3340 // Make dates with properties first say the date
3341 if (isDate(value)) {
3342 base = ' ' + Date.prototype.toUTCString.call(value);
3345 // Make error with message first say the error
3346 if (isError(value)) {
3347 base = ' ' + formatError(value);
3350 if (keys.length === 0 && (!array || value.length == 0)) {
3351 return braces[0] + base + braces[1];
3354 if (recurseTimes < 0) {
3355 if (isRegExp(value)) {
3356 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
3358 return ctx.stylize('[Object]', 'special');
3362 ctx.seen.push(value);
3366 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
3368 output = keys.map(function(key) {
3369 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
3375 return reduceToSingleString(output, base, braces);
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');
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.
3394 return ctx.stylize('null', 'null');
3398 function formatError(value) {
3399 return '[' + Error.prototype.toString.call(value) + ']';
3403 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
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,
3413 keys.forEach(function(key) {
3414 if (!key.match(/^\d+$/)) {
3415 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
3423 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
3424 var name, str, desc;
3425 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
3428 str = ctx.stylize('[Getter/Setter]', 'special');
3430 str = ctx.stylize('[Getter]', 'special');
3434 str = ctx.stylize('[Setter]', 'special');
3437 if (!hasOwnProperty(visibleKeys, key)) {
3438 name = '[' + key + ']';
3441 if (ctx.seen.indexOf(desc.value) < 0) {
3442 if (isNull(recurseTimes)) {
3443 str = formatValue(ctx, desc.value, null);
3445 str = formatValue(ctx, desc.value, recurseTimes - 1);
3447 if (str.indexOf('\n') > -1) {
3449 str = str.split('\n').map(function(line) {
3451 }).join('\n').substr(2);
3453 str = '\n' + str.split('\n').map(function(line) {
3459 str = ctx.stylize('[Circular]', 'special');
3462 if (isUndefined(name)) {
3463 if (array && key.match(/^\d+$/)) {
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');
3471 name = name.replace(/'/g, "\\'")
3472 .replace(/\\"/g, '"')
3473 .replace(/(^"|"$)/g, "'");
3474 name = ctx.stylize(name, 'string');
3478 return name + ': ' + str;
3482 function reduceToSingleString(output, base, braces) {
3483 var numLinesEst = 0;
3484 var length = output.reduce(function(prev, cur) {
3486 if (cur.indexOf('\n') >= 0) numLinesEst++;
3487 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
3492 (base === '' ? '' : base + '\n ') +
3494 output.join(',\n ') +
3499 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
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);
3508 exports.isArray = isArray;
3510 function isBoolean(arg) {
3511 return typeof arg === 'boolean';
3513 exports.isBoolean = isBoolean;
3515 function isNull(arg) {
3516 return arg === null;
3518 exports.isNull = isNull;
3520 function isNullOrUndefined(arg) {
3523 exports.isNullOrUndefined = isNullOrUndefined;
3525 function isNumber(arg) {
3526 return typeof arg === 'number';
3528 exports.isNumber = isNumber;
3530 function isString(arg) {
3531 return typeof arg === 'string';
3533 exports.isString = isString;
3535 function isSymbol(arg) {
3536 return typeof arg === 'symbol';
3538 exports.isSymbol = isSymbol;
3540 function isUndefined(arg) {
3541 return arg === void 0;
3543 exports.isUndefined = isUndefined;
3545 function isRegExp(re) {
3546 return isObject(re) && objectToString(re) === '[object RegExp]';
3548 exports.isRegExp = isRegExp;
3550 function isObject(arg) {
3551 return typeof arg === 'object' && arg !== null;
3553 exports.isObject = isObject;
3555 function isDate(d) {
3556 return isObject(d) && objectToString(d) === '[object Date]';
3558 exports.isDate = isDate;
3560 function isError(e) {
3561 return isObject(e) &&
3562 (objectToString(e) === '[object Error]' || e instanceof Error);
3564 exports.isError = isError;
3566 function isFunction(arg) {
3567 return typeof arg === 'function';
3569 exports.isFunction = isFunction;
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';
3579 exports.isPrimitive = isPrimitive;
3581 exports.isBuffer = require('./support/isBuffer');
3583 function objectToString(o) {
3584 return Object.prototype.toString.call(o);
3589 return n < 10 ? '0' + n.toString(10) : n.toString(10);
3593 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
3594 'Oct', 'Nov', 'Dec'];
3597 function timestamp() {
3599 var time = [pad(d.getHours()),
3600 pad(d.getMinutes()),
3601 pad(d.getSeconds())].join(':');
3602 return [d.getDate(), months[d.getMonth()], time].join(' ');
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));
3613 * Inherit the prototype methods from one constructor into another.
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).
3621 * @param {function} ctor Constructor function which needs to inherit the
3623 * @param {function} superCtor Constructor function to inherit prototype from.
3625 exports.inherits = require('inherits');
3627 exports._extend = function(origin, add) {
3628 // Don't do anything if add isn't an object
3629 if (!add || !isObject(add)) return origin;
3631 var keys = Object.keys(add);
3632 var i = keys.length;
3634 origin[keys[i]] = add[keys[i]];
3639 function hasOwnProperty(obj, prop) {
3640 return Object.prototype.hasOwnProperty.call(obj, prop);
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){
3647 exports.byteLength = byteLength
3648 exports.toByteArray = toByteArray
3649 exports.fromByteArray = fromByteArray
3653 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
3655 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
3656 for (var i = 0, len = code.length; i < len; ++i) {
3658 revLookup[code.charCodeAt(i)] = i
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
3666 function getLens (b64) {
3667 var len = b64.length
3670 throw new Error('Invalid string. Length must be a multiple of 4')
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
3678 var placeHoldersLen = validLen === len
3680 : 4 - (validLen % 4)
3682 return [validLen, placeHoldersLen]
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
3693 function _byteLength (b64, validLen, placeHoldersLen) {
3694 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
3697 function toByteArray (b64) {
3699 var lens = getLens(b64)
3700 var validLen = lens[0]
3701 var placeHoldersLen = lens[1]
3703 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
3707 // if there are placeholders, only get up to the last complete 4 chars
3708 var len = placeHoldersLen > 0
3712 for (var i = 0; i < len; i += 4) {
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
3723 if (placeHoldersLen === 2) {
3725 (revLookup[b64.charCodeAt(i)] << 2) |
3726 (revLookup[b64.charCodeAt(i + 1)] >> 4)
3727 arr[curByte++] = tmp & 0xFF
3730 if (placeHoldersLen === 1) {
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
3742 function tripletToBase64 (num) {
3743 return lookup[num >> 18 & 0x3F] +
3744 lookup[num >> 12 & 0x3F] +
3745 lookup[num >> 6 & 0x3F] +
3749 function encodeChunk (uint8, start, end) {
3752 for (var i = start; i < end; i += 3) {
3754 ((uint8[i] << 16) & 0xFF0000) +
3755 ((uint8[i + 1] << 8) & 0xFF00) +
3756 (uint8[i + 2] & 0xFF)
3757 output.push(tripletToBase64(tmp))
3759 return output.join('')
3762 function fromByteArray (uint8) {
3764 var len = uint8.length
3765 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
3767 var maxChunkLength = 16383 // must be multiple of 3
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)
3776 // pad the end with zeros, but make sure to not forget the extra bytes
3777 if (extraBytes === 1) {
3778 tmp = uint8[len - 1]
3781 lookup[(tmp << 4) & 0x3F] +
3784 } else if (extraBytes === 2) {
3785 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
3788 lookup[(tmp >> 4) & 0x3F] +
3789 lookup[(tmp << 2) & 0x3F] +
3794 return parts.join('')
3797 },{}],28:[function(require,module,exports){
3799 },{}],29:[function(require,module,exports){
3800 (function (process,Buffer){
3802 /* eslint camelcase: "off" */
3804 var assert = require('assert');
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');
3811 for (var key in constants) {
3812 exports[key] = constants[key];
3817 exports.DEFLATE = 1;
3818 exports.INFLATE = 2;
3821 exports.DEFLATERAW = 5;
3822 exports.INFLATERAW = 6;
3825 var GZIP_HEADER_ID1 = 0x1f;
3826 var GZIP_HEADER_ID2 = 0x8b;
3829 * Emulate Node's zlib C++ layer for use by the JS layer in index.js
3831 function Zlib(mode) {
3832 if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
3833 throw new TypeError('Bad argument');
3836 this.dictionary = null;
3839 this.init_done = false;
3844 this.windowBits = 0;
3845 this.write_in_progress = false;
3846 this.pending_close = false;
3847 this.gzip_id_bytes_read = 0;
3850 Zlib.prototype.close = function () {
3851 if (this.write_in_progress) {
3852 this.pending_close = true;
3856 this.pending_close = false;
3858 assert(this.init_done, 'close before init');
3859 assert(this.mode <= exports.UNZIP);
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);
3867 this.mode = exports.NONE;
3869 this.dictionary = null;
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);
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);
3880 Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
3881 assert.equal(arguments.length, 8);
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');
3888 this.write_in_progress = true;
3890 assert.equal(false, flush === undefined, 'must provide flush value');
3892 this.write_in_progress = true;
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');
3898 if (input == null) {
3899 input = Buffer.alloc(0);
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;
3916 if (this._checkError()) {
3917 return this._afterSync();
3924 process.nextTick(function () {
3932 Zlib.prototype._afterSync = function () {
3933 var avail_out = this.strm.avail_out;
3934 var avail_in = this.strm.avail_in;
3936 this.write_in_progress = false;
3938 return [avail_in, avail_out];
3941 Zlib.prototype._process = function () {
3942 var next_expected_header_byte = null;
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:
3950 case exports.DEFLATERAW:
3951 this.err = zlib_deflate.deflate(this.strm, this.flush);
3954 if (this.strm.avail_in > 0) {
3955 next_expected_header_byte = this.strm.next_in;
3958 switch (this.gzip_id_bytes_read) {
3960 if (next_expected_header_byte === null) {
3964 if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
3965 this.gzip_id_bytes_read = 1;
3966 next_expected_header_byte++;
3968 if (this.strm.avail_in === 1) {
3969 // The only available byte was already read.
3973 this.mode = exports.INFLATE;
3979 if (next_expected_header_byte === null) {
3983 if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
3984 this.gzip_id_bytes_read = 2;
3985 this.mode = exports.GUNZIP;
3987 // There is no actual difference between INFLATE and INFLATERAW
3988 // (after initialization).
3989 this.mode = exports.INFLATE;
3994 throw new Error('invalid number of gzip magic number bytes read');
3998 case exports.INFLATE:
3999 case exports.GUNZIP:
4000 case exports.INFLATERAW:
4001 this.err = zlib_inflate.inflate(this.strm, this.flush
4003 // If data was encoded with dictionary
4004 );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
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
4014 this.err = exports.Z_NEED_DICT;
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.
4024 this.err = zlib_inflate.inflate(this.strm, this.flush);
4028 throw new Error('Unknown mode ' + this.mode);
4032 Zlib.prototype._checkError = function () {
4033 // Acceptable error states depend on the type of zlib stream.
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');
4042 case exports.Z_STREAM_END:
4043 // normal statuses, not fatal
4045 case exports.Z_NEED_DICT:
4046 if (this.dictionary == null) {
4047 this._error('Missing dictionary');
4049 this._error('Bad dictionary');
4054 this._error('Zlib error');
4061 Zlib.prototype._after = function () {
4062 if (!this._checkError()) {
4066 var avail_out = this.strm.avail_out;
4067 var avail_in = this.strm.avail_in;
4069 this.write_in_progress = false;
4071 // call the write() cb
4072 this.callback(avail_in, avail_out);
4074 if (this.pending_close) {
4079 Zlib.prototype._error = function (message) {
4080 if (this.strm.msg) {
4081 message = this.strm.msg;
4083 this.onerror(message, this.err
4085 // no hope of rescue.
4086 );this.write_in_progress = false;
4087 if (this.pending_close) {
4092 Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
4093 assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
4095 assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
4096 assert(level >= -1 && level <= 9, 'invalid compression level');
4098 assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
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');
4102 this._init(level, windowBits, memLevel, strategy, dictionary);
4103 this._setDictionary();
4106 Zlib.prototype.params = function () {
4107 throw new Error('deflateParams Not supported');
4110 Zlib.prototype.reset = function () {
4112 this._setDictionary();
4115 Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
4117 this.windowBits = windowBits;
4118 this.memLevel = memLevel;
4119 this.strategy = strategy;
4121 this.flush = exports.Z_NO_FLUSH;
4123 this.err = exports.Z_OK;
4125 if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
4126 this.windowBits += 16;
4129 if (this.mode === exports.UNZIP) {
4130 this.windowBits += 32;
4133 if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
4134 this.windowBits = -1 * this.windowBits;
4137 this.strm = new Zstream();
4139 switch (this.mode) {
4140 case exports.DEFLATE:
4142 case exports.DEFLATERAW:
4143 this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
4145 case exports.INFLATE:
4146 case exports.GUNZIP:
4147 case exports.INFLATERAW:
4149 this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
4152 throw new Error('Unknown mode ' + this.mode);
4155 if (this.err !== exports.Z_OK) {
4156 this._error('Init error');
4159 this.dictionary = dictionary;
4161 this.write_in_progress = false;
4162 this.init_done = true;
4165 Zlib.prototype._setDictionary = function () {
4166 if (this.dictionary == null) {
4170 this.err = exports.Z_OK;
4172 switch (this.mode) {
4173 case exports.DEFLATE:
4174 case exports.DEFLATERAW:
4175 this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
4181 if (this.err !== exports.Z_OK) {
4182 this._error('Failed to set dictionary');
4186 Zlib.prototype._reset = function () {
4187 this.err = exports.Z_OK;
4189 switch (this.mode) {
4190 case exports.DEFLATE:
4191 case exports.DEFLATERAW:
4193 this.err = zlib_deflate.deflateReset(this.strm);
4195 case exports.INFLATE:
4196 case exports.INFLATERAW:
4197 case exports.GUNZIP:
4198 this.err = zlib_inflate.inflateReset(this.strm);
4204 if (this.err !== exports.Z_OK) {
4205 this._error('Failed to reset stream');
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){
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';
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;
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;
4236 binding.Z_MIN_MEMLEVEL = 1;
4237 binding.Z_MAX_MEMLEVEL = 9;
4238 binding.Z_DEFAULT_MEMLEVEL = 8;
4240 binding.Z_MIN_LEVEL = -1;
4241 binding.Z_MAX_LEVEL = 9;
4242 binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
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
4255 // translation table for return codes.
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
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;
4274 Object.defineProperty(exports, 'codes', {
4275 enumerable: true, value: Object.freeze(codes), writable: false
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;
4286 exports.createDeflate = function (o) {
4287 return new Deflate(o);
4290 exports.createInflate = function (o) {
4291 return new Inflate(o);
4294 exports.createDeflateRaw = function (o) {
4295 return new DeflateRaw(o);
4298 exports.createInflateRaw = function (o) {
4299 return new InflateRaw(o);
4302 exports.createGzip = function (o) {
4306 exports.createGunzip = function (o) {
4307 return new Gunzip(o);
4310 exports.createUnzip = function (o) {
4311 return new Unzip(o);
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') {
4321 return zlibBuffer(new Deflate(opts), buffer, callback);
4324 exports.deflateSync = function (buffer, opts) {
4325 return zlibBufferSync(new Deflate(opts), buffer);
4328 exports.gzip = function (buffer, opts, callback) {
4329 if (typeof opts === 'function') {
4333 return zlibBuffer(new Gzip(opts), buffer, callback);
4336 exports.gzipSync = function (buffer, opts) {
4337 return zlibBufferSync(new Gzip(opts), buffer);
4340 exports.deflateRaw = function (buffer, opts, callback) {
4341 if (typeof opts === 'function') {
4345 return zlibBuffer(new DeflateRaw(opts), buffer, callback);
4348 exports.deflateRawSync = function (buffer, opts) {
4349 return zlibBufferSync(new DeflateRaw(opts), buffer);
4352 exports.unzip = function (buffer, opts, callback) {
4353 if (typeof opts === 'function') {
4357 return zlibBuffer(new Unzip(opts), buffer, callback);
4360 exports.unzipSync = function (buffer, opts) {
4361 return zlibBufferSync(new Unzip(opts), buffer);
4364 exports.inflate = function (buffer, opts, callback) {
4365 if (typeof opts === 'function') {
4369 return zlibBuffer(new Inflate(opts), buffer, callback);
4372 exports.inflateSync = function (buffer, opts) {
4373 return zlibBufferSync(new Inflate(opts), buffer);
4376 exports.gunzip = function (buffer, opts, callback) {
4377 if (typeof opts === 'function') {
4381 return zlibBuffer(new Gunzip(opts), buffer, callback);
4384 exports.gunzipSync = function (buffer, opts) {
4385 return zlibBufferSync(new Gunzip(opts), buffer);
4388 exports.inflateRaw = function (buffer, opts, callback) {
4389 if (typeof opts === 'function') {
4393 return zlibBuffer(new InflateRaw(opts), buffer, callback);
4396 exports.inflateRawSync = function (buffer, opts) {
4397 return zlibBufferSync(new InflateRaw(opts), buffer);
4400 function zlibBuffer(engine, buffer, callback) {
4404 engine.on('error', onError);
4405 engine.on('end', onEnd);
4412 while (null !== (chunk = engine.read())) {
4413 buffers.push(chunk);
4414 nread += chunk.length;
4416 engine.once('readable', flow);
4419 function onError(err) {
4420 engine.removeListener('end', onEnd);
4421 engine.removeListener('readable', flow);
4429 if (nread >= kMaxLength) {
4430 err = new RangeError(kRangeErrorMessage);
4432 buf = Buffer.concat(buffers, nread);
4441 function zlibBufferSync(engine, buffer) {
4442 if (typeof buffer === 'string') buffer = Buffer.from(buffer);
4444 if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
4446 var flushFlag = engine._finishFlushFlag;
4448 return engine._processChunk(buffer, flushFlag);
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);
4458 function Inflate(opts) {
4459 if (!(this instanceof Inflate)) return new Inflate(opts);
4460 Zlib.call(this, opts, binding.INFLATE);
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);
4469 function Gunzip(opts) {
4470 if (!(this instanceof Gunzip)) return new Gunzip(opts);
4471 Zlib.call(this, opts, binding.GUNZIP);
4475 function DeflateRaw(opts) {
4476 if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
4477 Zlib.call(this, opts, binding.DEFLATERAW);
4480 function InflateRaw(opts) {
4481 if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
4482 Zlib.call(this, opts, binding.INFLATERAW);
4485 // auto-detect header.
4486 function Unzip(opts) {
4487 if (!(this instanceof Unzip)) return new Unzip(opts);
4488 Zlib.call(this, opts, binding.UNZIP);
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;
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.
4500 function Zlib(opts, mode) {
4503 this._opts = opts = opts || {};
4504 this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
4506 Transform.call(this, opts);
4508 if (opts.flush && !isValidFlushFlag(opts.flush)) {
4509 throw new Error('Invalid flush flag: ' + opts.flush);
4511 if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
4512 throw new Error('Invalid flush flag: ' + opts.finishFlush);
4515 this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
4516 this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
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);
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);
4531 if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
4532 throw new Error('Invalid compression level: ' + opts.level);
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);
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);
4548 if (opts.dictionary) {
4549 if (!Buffer.isBuffer(opts.dictionary)) {
4550 throw new Error('Invalid dictionary: it should be a Buffer instance');
4554 this._handle = new binding.Zlib(mode);
4557 this._hadError = false;
4558 this._handle.onerror = function (message, errno) {
4559 // there is no way to cleanly recover.
4560 // continuing only obscures problems.
4562 self._hadError = true;
4564 var error = new Error(message);
4565 error.errno = errno;
4566 error.code = exports.codes[errno];
4567 self.emit('error', error);
4570 var level = exports.Z_DEFAULT_COMPRESSION;
4571 if (typeof opts.level === 'number') level = opts.level;
4573 var strategy = exports.Z_DEFAULT_STRATEGY;
4574 if (typeof opts.strategy === 'number') strategy = opts.strategy;
4576 this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
4578 this._buffer = Buffer.allocUnsafe(this._chunkSize);
4580 this._level = level;
4581 this._strategy = strategy;
4583 this.once('end', this.close);
4585 Object.defineProperty(this, '_closed', {
4587 return !_this._handle;
4594 util.inherits(Zlib, Transform);
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);
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);
4604 if (this._level !== level || this._strategy !== strategy) {
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();
4616 process.nextTick(callback);
4620 Zlib.prototype.reset = function () {
4621 assert(this._handle, 'zlib binding closed');
4622 return this._handle.reset();
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);
4631 Zlib.prototype.flush = function (kind, callback) {
4634 var ws = this._writableState;
4636 if (typeof kind === 'function' || kind === undefined && !callback) {
4638 kind = binding.Z_FULL_FLUSH;
4642 if (callback) process.nextTick(callback);
4643 } else if (ws.ending) {
4644 if (callback) this.once('end', callback);
4645 } else if (ws.needDrain) {
4647 this.once('drain', function () {
4648 return _this2.flush(kind, callback);
4652 this._flushFlag = kind;
4653 this.write(Buffer.alloc(0), '', callback);
4657 Zlib.prototype.close = function (callback) {
4658 _close(this, callback);
4659 process.nextTick(emitCloseNT, this);
4662 function _close(engine, callback) {
4663 if (callback) process.nextTick(callback);
4665 // Caller may invoke .close after a zlib error (which will null _handle).
4666 if (!engine._handle) return;
4668 engine._handle.close();
4669 engine._handle = null;
4672 function emitCloseNT(self) {
4676 Zlib.prototype._transform = function (chunk, encoding, cb) {
4678 var ws = this._writableState;
4679 var ending = ws.ending || ws.ended;
4680 var last = ending && (!chunk || ws.length === chunk.length);
4682 if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
4684 if (!this._handle) return cb(new Error('zlib binding closed'));
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
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;
4700 this._processChunk(chunk, flushFlag, cb);
4703 Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
4704 var availInBefore = chunk && chunk.length;
4705 var availOutBefore = this._chunkSize - this._offset;
4710 var async = typeof cb === 'function';
4717 this.on('error', function (er) {
4721 assert(this._handle, 'zlib binding closed');
4723 var res = this._handle.writeSync(flushFlag, chunk, // in
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]));
4731 if (this._hadError) {
4735 if (nread >= kMaxLength) {
4737 throw new RangeError(kRangeErrorMessage);
4740 var buf = Buffer.concat(buffers, nread);
4746 assert(this._handle, 'zlib binding closed');
4747 var req = this._handle.write(flushFlag, chunk, // in
4749 availInBefore, // in_len
4750 this._buffer, // out
4751 this._offset, //out_off
4752 availOutBefore); // out_len
4755 req.callback = callback;
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.
4765 this.callback = null;
4768 if (self._hadError) return;
4770 var have = availOutBefore - availOutAfter;
4771 assert(have >= 0, 'have should not go down');
4774 var out = self._buffer.slice(self._offset, self._offset + have);
4775 self._offset += have;
4776 // serve some output to the consumer.
4781 nread += out.length;
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;
4789 self._buffer = Buffer.allocUnsafe(self._chunkSize);
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;
4800 if (!async) return true;
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;
4808 if (!async) return false;
4810 // finished with the chunk.
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){
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);
4835 if (typeof encoding === 'number') {
4836 throw new TypeError('encoding must not be number');
4838 if (typeof size !== 'number') {
4839 throw new TypeError('size must be a number');
4841 if (size > MAX_LEN) {
4842 throw new RangeError('size is too large');
4846 if (_fill === undefined) {
4850 var buf = new Buffer(size);
4851 if (typeof _fill === 'string') {
4852 var fillBuf = new Buffer(_fill, enc);
4853 var flen = fillBuf.length;
4855 while (++i < size) {
4856 buf[i] = fillBuf[i % flen];
4863 exports.allocUnsafe = function allocUnsafe(size) {
4864 if (typeof Buffer.allocUnsafe === 'function') {
4865 return Buffer.allocUnsafe(size);
4867 if (typeof size !== 'number') {
4868 throw new TypeError('size must be a number');
4870 if (size > MAX_LEN) {
4871 throw new RangeError('size is too large');
4873 return new Buffer(size);
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);
4879 if (typeof value === 'number') {
4880 throw new TypeError('"value" argument must not be a number');
4882 if (typeof value === 'string') {
4883 return new Buffer(value, encodingOrOffset);
4885 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
4886 var offset = encodingOrOffset;
4887 if (arguments.length === 1) {
4888 return new Buffer(value);
4890 if (typeof offset === 'undefined') {
4894 if (typeof len === 'undefined') {
4895 len = value.byteLength - offset;
4897 if (offset >= value.byteLength) {
4898 throw new RangeError('\'offset\' is out of bounds');
4900 if (len > value.byteLength - offset) {
4901 throw new RangeError('\'length\' is out of bounds');
4903 return new Buffer(value.slice(offset, offset + len));
4905 if (Buffer.isBuffer(value)) {
4906 var out = new Buffer(value.length);
4907 value.copy(out, 0, 0, value.length);
4911 if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
4912 return new Buffer(value);
4914 if (value.type === 'Buffer' && Array.isArray(value.data)) {
4915 return new Buffer(value.data);
4919 throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
4921 exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
4922 if (typeof Buffer.allocUnsafeSlow === 'function') {
4923 return Buffer.allocUnsafeSlow(size);
4925 if (typeof size !== 'number') {
4926 throw new TypeError('size must be a number');
4928 if (size >= MAX_LEN) {
4929 throw new RangeError('size is too large');
4931 return new SlowBuffer(size);
4934 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4935 },{"buffer":32}],32:[function(require,module,exports){
4938 * The buffer module from node.js, for the browser.
4940 * @author Feross Aboukhadijeh <https://feross.org>
4943 /* eslint-disable no-proto */
4947 var base64 = require('base64-js')
4948 var ieee754 = require('ieee754')
4950 exports.Buffer = Buffer
4951 exports.SlowBuffer = SlowBuffer
4952 exports.INSPECT_MAX_BYTES = 50
4954 var K_MAX_LENGTH = 0x7fffffff
4955 exports.kMaxLength = K_MAX_LENGTH
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)
4963 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
4964 * Opera 11.6+, iOS 4.2+.
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.
4971 Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
4973 if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
4974 typeof console.error === 'function') {
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.'
4981 function typedArraySupport () {
4982 // Can typed array instances can be augmented?
4984 var arr = new Uint8Array(1)
4985 arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
4986 return arr.foo() === 42
4992 Object.defineProperty(Buffer.prototype, 'parent', {
4995 if (!Buffer.isBuffer(this)) return undefined
5000 Object.defineProperty(Buffer.prototype, 'offset', {
5003 if (!Buffer.isBuffer(this)) return undefined
5004 return this.byteOffset
5008 function createBuffer (length) {
5009 if (length > K_MAX_LENGTH) {
5010 throw new RangeError('The value "' + length + '" is invalid for option "size"')
5012 // Return an augmented `Uint8Array` instance
5013 var buf = new Uint8Array(length)
5014 buf.__proto__ = Buffer.prototype
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.
5025 * The `Uint8Array` prototype remains unmodified.
5028 function Buffer (arg, encodingOrOffset, length) {
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'
5036 return allocUnsafe(arg)
5038 return from(arg, encodingOrOffset, length)
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, {
5052 Buffer.poolSize = 8192 // not used by this implementation
5054 function from (value, encodingOrOffset, length) {
5055 if (typeof value === 'string') {
5056 return fromString(value, encodingOrOffset)
5059 if (ArrayBuffer.isView(value)) {
5060 return fromArrayLike(value)
5063 if (value == null) {
5065 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
5066 'or Array-like Object. Received type ' + (typeof value)
5070 if (isInstance(value, ArrayBuffer) ||
5071 (value && isInstance(value.buffer, ArrayBuffer))) {
5072 return fromArrayBuffer(value, encodingOrOffset, length)
5075 if (typeof value === 'number') {
5076 throw new TypeError(
5077 'The "value" argument must not be of type number. Received type number'
5081 var valueOf = value.valueOf && value.valueOf()
5082 if (valueOf != null && valueOf !== value) {
5083 return Buffer.from(valueOf, encodingOrOffset, length)
5086 var b = fromObject(value)
5089 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
5090 typeof value[Symbol.toPrimitive] === 'function') {
5092 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
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)
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]])
5110 Buffer.from = function (value, encodingOrOffset, length) {
5111 return from(value, encodingOrOffset, length)
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
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"')
5127 function alloc (size, fill, encoding) {
5130 return createBuffer(size)
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)
5140 return createBuffer(size)
5144 * Creates a new filled Buffer instance.
5145 * alloc(size[, fill[, encoding]])
5147 Buffer.alloc = function (size, fill, encoding) {
5148 return alloc(size, fill, encoding)
5151 function allocUnsafe (size) {
5153 return createBuffer(size < 0 ? 0 : checked(size) | 0)
5157 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
5159 Buffer.allocUnsafe = function (size) {
5160 return allocUnsafe(size)
5163 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
5165 Buffer.allocUnsafeSlow = function (size) {
5166 return allocUnsafe(size)
5169 function fromString (string, encoding) {
5170 if (typeof encoding !== 'string' || encoding === '') {
5174 if (!Buffer.isEncoding(encoding)) {
5175 throw new TypeError('Unknown encoding: ' + encoding)
5178 var length = byteLength(string, encoding) | 0
5179 var buf = createBuffer(length)
5181 var actual = buf.write(string, encoding)
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)
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
5202 function fromArrayBuffer (array, byteOffset, length) {
5203 if (byteOffset < 0 || array.byteLength < byteOffset) {
5204 throw new RangeError('"offset" is outside of buffer bounds')
5207 if (array.byteLength < byteOffset + (length || 0)) {
5208 throw new RangeError('"length" is outside of buffer bounds')
5212 if (byteOffset === undefined && length === undefined) {
5213 buf = new Uint8Array(array)
5214 } else if (length === undefined) {
5215 buf = new Uint8Array(array, byteOffset)
5217 buf = new Uint8Array(array, byteOffset, length)
5220 // Return an augmented `Uint8Array` instance
5221 buf.__proto__ = Buffer.prototype
5225 function fromObject (obj) {
5226 if (Buffer.isBuffer(obj)) {
5227 var len = checked(obj.length) | 0
5228 var buf = createBuffer(len)
5230 if (buf.length === 0) {
5234 obj.copy(buf, 0, 0, len)
5238 if (obj.length !== undefined) {
5239 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
5240 return createBuffer(0)
5242 return fromArrayLike(obj)
5245 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
5246 return fromArrayLike(obj.data)
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')
5260 function SlowBuffer (length) {
5261 if (+length != length) { // eslint-disable-line eqeqeq
5264 return Buffer.alloc(+length)
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
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'
5281 if (a === b) return 0
5286 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
5287 if (a[i] !== b[i]) {
5294 if (x < y) return -1
5299 Buffer.isEncoding = function isEncoding (encoding) {
5300 switch (String(encoding).toLowerCase()) {
5318 Buffer.concat = function concat (list, length) {
5319 if (!Array.isArray(list)) {
5320 throw new TypeError('"list" argument must be an Array of Buffers')
5323 if (list.length === 0) {
5324 return Buffer.alloc(0)
5328 if (length === undefined) {
5330 for (i = 0; i < list.length; ++i) {
5331 length += list[i].length
5335 var buffer = Buffer.allocUnsafe(length)
5337 for (i = 0; i < list.length; ++i) {
5339 if (isInstance(buf, Uint8Array)) {
5340 buf = Buffer.from(buf)
5342 if (!Buffer.isBuffer(buf)) {
5343 throw new TypeError('"list" argument must be an Array of Buffers')
5345 buf.copy(buffer, pos)
5351 function byteLength (string, encoding) {
5352 if (Buffer.isBuffer(string)) {
5353 return string.length
5355 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
5356 return string.byteLength
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
5365 var len = string.length
5366 var mustMatch = (arguments.length > 2 && arguments[2] === true)
5367 if (!mustMatch && len === 0) return 0
5369 // Use a for loop to avoid recursion
5370 var loweredCase = false
5379 return utf8ToBytes(string).length
5388 return base64ToBytes(string).length
5391 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
5393 encoding = ('' + encoding).toLowerCase()
5398 Buffer.byteLength = byteLength
5400 function slowToString (encoding, start, end) {
5401 var loweredCase = false
5403 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
5404 // property of a typed array.
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) {
5413 // Return early if start > this.length. Done here to prevent potential uint32
5414 // coercion fail below.
5415 if (start > this.length) {
5419 if (end === undefined || end > this.length) {
5427 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
5435 if (!encoding) encoding = 'utf8'
5440 return hexSlice(this, start, end)
5444 return utf8Slice(this, start, end)
5447 return asciiSlice(this, start, end)
5451 return latin1Slice(this, start, end)
5454 return base64Slice(this, start, end)
5460 return utf16leSlice(this, start, end)
5463 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
5464 encoding = (encoding + '').toLowerCase()
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
5478 function swap (b, n, m) {
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')
5489 for (var i = 0; i < len; i += 2) {
5490 swap(this, i, i + 1)
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')
5500 for (var i = 0; i < len; i += 4) {
5501 swap(this, i, i + 3)
5502 swap(this, i + 1, i + 2)
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')
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)
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)
5528 Buffer.prototype.toLocaleString = Buffer.prototype.toString
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
5536 Buffer.prototype.inspect = function inspect () {
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 + '>'
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)
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)
5555 if (start === undefined) {
5558 if (end === undefined) {
5559 end = target ? target.length : 0
5561 if (thisStart === undefined) {
5564 if (thisEnd === undefined) {
5565 thisEnd = this.length
5568 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
5569 throw new RangeError('out of range index')
5572 if (thisStart >= thisEnd && start >= end) {
5575 if (thisStart >= thisEnd) {
5587 if (this === target) return 0
5589 var x = thisEnd - thisStart
5591 var len = Math.min(x, y)
5593 var thisCopy = this.slice(thisStart, thisEnd)
5594 var targetCopy = target.slice(start, end)
5596 for (var i = 0; i < len; ++i) {
5597 if (thisCopy[i] !== targetCopy[i]) {
5604 if (x < y) return -1
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`.
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
5622 // Normalize byteOffset
5623 if (typeof byteOffset === 'string') {
5624 encoding = byteOffset
5626 } else if (byteOffset > 0x7fffffff) {
5627 byteOffset = 0x7fffffff
5628 } else if (byteOffset < -0x80000000) {
5629 byteOffset = -0x80000000
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)
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) {
5641 else byteOffset = buffer.length - 1
5642 } else if (byteOffset < 0) {
5643 if (dir) byteOffset = 0
5648 if (typeof val === 'string') {
5649 val = Buffer.from(val, encoding)
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) {
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') {
5663 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
5665 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
5668 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
5671 throw new TypeError('val must be string, number or Buffer')
5674 function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
5676 var arrLength = arr.length
5677 var valLength = val.length
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) {
5693 function read (buf, i) {
5694 if (indexSize === 1) {
5697 return buf.readUInt16BE(i * indexSize)
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
5709 if (foundIndex !== -1) i -= i - foundIndex
5714 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
5715 for (i = byteOffset; i >= 0; i--) {
5717 for (var j = 0; j < valLength; j++) {
5718 if (read(arr, i + j) !== read(val, j)) {
5730 Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
5731 return this.indexOf(val, byteOffset, encoding) !== -1
5734 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
5735 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
5738 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
5739 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
5742 function hexWrite (buf, string, offset, length) {
5743 offset = Number(offset) || 0
5744 var remaining = buf.length - offset
5748 length = Number(length)
5749 if (length > remaining) {
5754 var strLen = string.length
5756 if (length > strLen / 2) {
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
5767 function utf8Write (buf, string, offset, length) {
5768 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
5771 function asciiWrite (buf, string, offset, length) {
5772 return blitBuffer(asciiToBytes(string), buf, offset, length)
5775 function latin1Write (buf, string, offset, length) {
5776 return asciiWrite(buf, string, offset, length)
5779 function base64Write (buf, string, offset, length) {
5780 return blitBuffer(base64ToBytes(string), buf, offset, length)
5783 function ucs2Write (buf, string, offset, length) {
5784 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
5787 Buffer.prototype.write = function write (string, offset, length, encoding) {
5788 // Buffer#write(string)
5789 if (offset === undefined) {
5791 length = this.length
5793 // Buffer#write(string, encoding)
5794 } else if (length === undefined && typeof offset === 'string') {
5796 length = this.length
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'
5810 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
5814 var remaining = this.length - offset
5815 if (length === undefined || length > remaining) length = remaining
5817 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
5818 throw new RangeError('Attempt to write outside buffer bounds')
5821 if (!encoding) encoding = 'utf8'
5823 var loweredCase = false
5827 return hexWrite(this, string, offset, length)
5831 return utf8Write(this, string, offset, length)
5834 return asciiWrite(this, string, offset, length)
5838 return latin1Write(this, string, offset, length)
5841 // Warning: maxLength not taken into account in base64Write
5842 return base64Write(this, string, offset, length)
5848 return ucs2Write(this, string, offset, length)
5851 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
5852 encoding = ('' + encoding).toLowerCase()
5858 Buffer.prototype.toJSON = function toJSON () {
5861 data: Array.prototype.slice.call(this._arr || this, 0)
5865 function base64Slice (buf, start, end) {
5866 if (start === 0 && end === buf.length) {
5867 return base64.fromByteArray(buf)
5869 return base64.fromByteArray(buf.slice(start, end))
5873 function utf8Slice (buf, start, end) {
5874 end = Math.min(buf.length, end)
5879 var firstByte = buf[i]
5880 var codePoint = null
5881 var bytesPerSequence = (firstByte > 0xEF) ? 4
5882 : (firstByte > 0xDF) ? 3
5883 : (firstByte > 0xBF) ? 2
5886 if (i + bytesPerSequence <= end) {
5887 var secondByte, thirdByte, fourthByte, tempCodePoint
5889 switch (bytesPerSequence) {
5891 if (firstByte < 0x80) {
5892 codePoint = firstByte
5896 secondByte = buf[i + 1]
5897 if ((secondByte & 0xC0) === 0x80) {
5898 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
5899 if (tempCodePoint > 0x7F) {
5900 codePoint = tempCodePoint
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
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
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
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
5940 i += bytesPerSequence
5943 return decodeCodePointsArray(res)
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
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()
5957 // Decode in chunks to avoid "call stack size exceeded".
5961 res += String.fromCharCode.apply(
5963 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
5969 function asciiSlice (buf, start, end) {
5971 end = Math.min(buf.length, end)
5973 for (var i = start; i < end; ++i) {
5974 ret += String.fromCharCode(buf[i] & 0x7F)
5979 function latin1Slice (buf, start, end) {
5981 end = Math.min(buf.length, end)
5983 for (var i = start; i < end; ++i) {
5984 ret += String.fromCharCode(buf[i])
5989 function hexSlice (buf, start, end) {
5990 var len = buf.length
5992 if (!start || start < 0) start = 0
5993 if (!end || end < 0 || end > len) end = len
5996 for (var i = start; i < end; ++i) {
5997 out += toHex(buf[i])
6002 function utf16leSlice (buf, start, end) {
6003 var bytes = buf.slice(start, end)
6005 for (var i = 0; i < bytes.length; i += 2) {
6006 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
6011 Buffer.prototype.slice = function slice (start, end) {
6012 var len = this.length
6014 end = end === undefined ? len : ~~end
6018 if (start < 0) start = 0
6019 } else if (start > len) {
6025 if (end < 0) end = 0
6026 } else if (end > len) {
6030 if (end < start) end = start
6032 var newBuf = this.subarray(start, end)
6033 // Return an augmented `Uint8Array` instance
6034 newBuf.__proto__ = Buffer.prototype
6039 * Need to make sure that buffer isn't trying to write out of bounds.
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')
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)
6051 var val = this[offset]
6054 while (++i < byteLength && (mul *= 0x100)) {
6055 val += this[offset + i] * mul
6061 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
6062 offset = offset >>> 0
6063 byteLength = byteLength >>> 0
6065 checkOffset(offset, byteLength, this.length)
6068 var val = this[offset + --byteLength]
6070 while (byteLength > 0 && (mul *= 0x100)) {
6071 val += this[offset + --byteLength] * mul
6077 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
6078 offset = offset >>> 0
6079 if (!noAssert) checkOffset(offset, 1, this.length)
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)
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]
6095 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
6096 offset = offset >>> 0
6097 if (!noAssert) checkOffset(offset, 4, this.length)
6099 return ((this[offset]) |
6100 (this[offset + 1] << 8) |
6101 (this[offset + 2] << 16)) +
6102 (this[offset + 3] * 0x1000000)
6105 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
6106 offset = offset >>> 0
6107 if (!noAssert) checkOffset(offset, 4, this.length)
6109 return (this[offset] * 0x1000000) +
6110 ((this[offset + 1] << 16) |
6111 (this[offset + 2] << 8) |
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)
6120 var val = this[offset]
6123 while (++i < byteLength && (mul *= 0x100)) {
6124 val += this[offset + i] * mul
6128 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
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)
6140 var val = this[offset + --i]
6141 while (i > 0 && (mul *= 0x100)) {
6142 val += this[offset + --i] * mul
6146 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
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)
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
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
6172 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
6173 offset = offset >>> 0
6174 if (!noAssert) checkOffset(offset, 4, this.length)
6176 return (this[offset]) |
6177 (this[offset + 1] << 8) |
6178 (this[offset + 2] << 16) |
6179 (this[offset + 3] << 24)
6182 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
6183 offset = offset >>> 0
6184 if (!noAssert) checkOffset(offset, 4, this.length)
6186 return (this[offset] << 24) |
6187 (this[offset + 1] << 16) |
6188 (this[offset + 2] << 8) |
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)
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)
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)
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)
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')
6222 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
6224 offset = offset >>> 0
6225 byteLength = byteLength >>> 0
6227 var maxBytes = Math.pow(2, 8 * byteLength) - 1
6228 checkInt(this, value, offset, byteLength, maxBytes, 0)
6233 this[offset] = value & 0xFF
6234 while (++i < byteLength && (mul *= 0x100)) {
6235 this[offset + i] = (value / mul) & 0xFF
6238 return offset + byteLength
6241 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
6243 offset = offset >>> 0
6244 byteLength = byteLength >>> 0
6246 var maxBytes = Math.pow(2, 8 * byteLength) - 1
6247 checkInt(this, value, offset, byteLength, maxBytes, 0)
6250 var i = byteLength - 1
6252 this[offset + i] = value & 0xFF
6253 while (--i >= 0 && (mul *= 0x100)) {
6254 this[offset + i] = (value / mul) & 0xFF
6257 return offset + byteLength
6260 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
6262 offset = offset >>> 0
6263 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
6264 this[offset] = (value & 0xff)
6268 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
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)
6277 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
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)
6286 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
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)
6297 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
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)
6308 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
6310 offset = offset >>> 0
6312 var limit = Math.pow(2, (8 * byteLength) - 1)
6314 checkInt(this, value, offset, byteLength, limit - 1, -limit)
6320 this[offset] = value & 0xFF
6321 while (++i < byteLength && (mul *= 0x100)) {
6322 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
6325 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
6328 return offset + byteLength
6331 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
6333 offset = offset >>> 0
6335 var limit = Math.pow(2, (8 * byteLength) - 1)
6337 checkInt(this, value, offset, byteLength, limit - 1, -limit)
6340 var i = byteLength - 1
6343 this[offset + i] = value & 0xFF
6344 while (--i >= 0 && (mul *= 0x100)) {
6345 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
6348 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
6351 return offset + byteLength
6354 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
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)
6363 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
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)
6372 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
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)
6381 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
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)
6392 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
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)
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')
6409 function writeFloat (buf, value, offset, littleEndian, noAssert) {
6411 offset = offset >>> 0
6413 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
6415 ieee754.write(buf, value, offset, littleEndian, 23, 4)
6419 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
6420 return writeFloat(this, value, offset, true, noAssert)
6423 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
6424 return writeFloat(this, value, offset, false, noAssert)
6427 function writeDouble (buf, value, offset, littleEndian, noAssert) {
6429 offset = offset >>> 0
6431 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
6433 ieee754.write(buf, value, offset, littleEndian, 52, 8)
6437 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
6438 return writeDouble(this, value, offset, true, noAssert)
6441 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
6442 return writeDouble(this, value, offset, false, noAssert)
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
6454 // Copy 0 bytes; we're done
6455 if (end === start) return 0
6456 if (target.length === 0 || this.length === 0) return 0
6458 // Fatal error conditions
6459 if (targetStart < 0) {
6460 throw new RangeError('targetStart out of bounds')
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')
6466 if (end > this.length) end = this.length
6467 if (target.length - targetStart < end - start) {
6468 end = target.length - targetStart + start
6471 var len = end - start
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]
6482 Uint8Array.prototype.set.call(
6484 this.subarray(start, end),
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') {
6503 } else if (typeof end === 'string') {
6507 if (encoding !== undefined && typeof encoding !== 'string') {
6508 throw new TypeError('encoding must be a string')
6510 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
6511 throw new TypeError('Unknown encoding: ' + encoding)
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.
6521 } else if (typeof val === 'number') {
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')
6535 end = end === undefined ? this.length : end >>> 0
6540 if (typeof val === 'number') {
6541 for (i = start; i < end; ++i) {
6545 var bytes = Buffer.isBuffer(val)
6547 : Buffer.from(val, encoding)
6548 var len = bytes.length
6550 throw new TypeError('The value "' + val +
6551 '" is invalid for argument "value"')
6553 for (i = 0; i < end - start; ++i) {
6554 this[i + start] = bytes[i % len]
6564 var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
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) {
6580 function toHex (n) {
6581 if (n < 16) return '0' + n.toString(16)
6582 return n.toString(16)
6585 function utf8ToBytes (string, units) {
6586 units = units || Infinity
6588 var length = string.length
6589 var leadSurrogate = null
6592 for (var i = 0; i < length; ++i) {
6593 codePoint = string.charCodeAt(i)
6595 // is surrogate component
6596 if (codePoint > 0xD7FF && codePoint < 0xE000) {
6597 // last char was a lead
6598 if (!leadSurrogate) {
6600 if (codePoint > 0xDBFF) {
6602 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
6604 } else if (i + 1 === length) {
6606 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
6611 leadSurrogate = codePoint
6617 if (codePoint < 0xDC00) {
6618 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
6619 leadSurrogate = codePoint
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)
6630 leadSurrogate = null
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
6639 codePoint >> 0x6 | 0xC0,
6640 codePoint & 0x3F | 0x80
6642 } else if (codePoint < 0x10000) {
6643 if ((units -= 3) < 0) break
6645 codePoint >> 0xC | 0xE0,
6646 codePoint >> 0x6 & 0x3F | 0x80,
6647 codePoint & 0x3F | 0x80
6649 } else if (codePoint < 0x110000) {
6650 if ((units -= 4) < 0) break
6652 codePoint >> 0x12 | 0xF0,
6653 codePoint >> 0xC & 0x3F | 0x80,
6654 codePoint >> 0x6 & 0x3F | 0x80,
6655 codePoint & 0x3F | 0x80
6658 throw new Error('Invalid code point')
6665 function asciiToBytes (str) {
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)
6674 function utf16leToBytes (str, units) {
6677 for (var i = 0; i < str.length; ++i) {
6678 if ((units -= 2) < 0) break
6680 c = str.charCodeAt(i)
6690 function base64ToBytes (str) {
6691 return base64.toByteArray(base64clean(str))
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]
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)
6710 function numberIsNaN (obj) {
6712 return obj !== obj // eslint-disable-line no-self-compare
6715 }).call(this,require("buffer").Buffer)
6716 },{"base64-js":27,"buffer":32,"ieee754":35}],33:[function(require,module,exports){
6718 // Copyright Joyent, Inc. and other Node contributors.
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:
6728 // The above copyright notice and this permission notice shall be included
6729 // in all copies or substantial portions of the Software.
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.
6739 // NOTE: These type checking functions intentionally don't use `instanceof`
6740 // because it is fragile and can be easily faked with `Object.create()`.
6742 function isArray(arg) {
6743 if (Array.isArray) {
6744 return Array.isArray(arg);
6746 return objectToString(arg) === '[object Array]';
6748 exports.isArray = isArray;
6750 function isBoolean(arg) {
6751 return typeof arg === 'boolean';
6753 exports.isBoolean = isBoolean;
6755 function isNull(arg) {
6756 return arg === null;
6758 exports.isNull = isNull;
6760 function isNullOrUndefined(arg) {
6763 exports.isNullOrUndefined = isNullOrUndefined;
6765 function isNumber(arg) {
6766 return typeof arg === 'number';
6768 exports.isNumber = isNumber;
6770 function isString(arg) {
6771 return typeof arg === 'string';
6773 exports.isString = isString;
6775 function isSymbol(arg) {
6776 return typeof arg === 'symbol';
6778 exports.isSymbol = isSymbol;
6780 function isUndefined(arg) {
6781 return arg === void 0;
6783 exports.isUndefined = isUndefined;
6785 function isRegExp(re) {
6786 return objectToString(re) === '[object RegExp]';
6788 exports.isRegExp = isRegExp;
6790 function isObject(arg) {
6791 return typeof arg === 'object' && arg !== null;
6793 exports.isObject = isObject;
6795 function isDate(d) {
6796 return objectToString(d) === '[object Date]';
6798 exports.isDate = isDate;
6800 function isError(e) {
6801 return (objectToString(e) === '[object Error]' || e instanceof Error);
6803 exports.isError = isError;
6805 function isFunction(arg) {
6806 return typeof arg === 'function';
6808 exports.isFunction = isFunction;
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';
6818 exports.isPrimitive = isPrimitive;
6820 exports.isBuffer = Buffer.isBuffer;
6822 function objectToString(o) {
6823 return Object.prototype.toString.call(o);
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.
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:
6838 // The above copyright notice and this permission notice shall be included
6839 // in all copies or substantial portions of the Software.
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.
6849 function EventEmitter() {
6850 this._events = this._events || {};
6851 this._maxListeners = this._maxListeners || undefined;
6853 module.exports = EventEmitter;
6855 // Backwards-compat with node 0.10.x
6856 EventEmitter.EventEmitter = EventEmitter;
6858 EventEmitter.prototype._events = undefined;
6859 EventEmitter.prototype._maxListeners = undefined;
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;
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;
6874 EventEmitter.prototype.emit = function(type) {
6875 var er, handler, len, args, i, listeners;
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)) {
6885 if (er instanceof Error) {
6886 throw er; // Unhandled 'error' event
6888 // At least give some kind of context to the user
6889 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
6896 handler = this._events[type];
6898 if (isUndefined(handler))
6901 if (isFunction(handler)) {
6902 switch (arguments.length) {
6908 handler.call(this, arguments[1]);
6911 handler.call(this, arguments[1], arguments[2]);
6915 args = Array.prototype.slice.call(arguments, 1);
6916 handler.apply(this, args);
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);
6929 EventEmitter.prototype.addListener = function(type, listener) {
6932 if (!isFunction(listener))
6933 throw TypeError('listener must be a function');
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);
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);
6952 // Adding the second element, need to change to array.
6953 this._events[type] = [this._events[type], listener];
6955 // Check for listener leak
6956 if (isObject(this._events[type]) && !this._events[type].warned) {
6957 if (!isUndefined(this._maxListeners)) {
6958 m = this._maxListeners;
6960 m = EventEmitter.defaultMaxListeners;
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
6979 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
6981 EventEmitter.prototype.once = function(type, listener) {
6982 if (!isFunction(listener))
6983 throw TypeError('listener must be a function');
6988 this.removeListener(type, g);
6992 listener.apply(this, arguments);
6996 g.listener = listener;
7002 // emits a 'removeListener' event iff the listener was removed
7003 EventEmitter.prototype.removeListener = function(type, listener) {
7004 var list, position, length, i;
7006 if (!isFunction(listener))
7007 throw TypeError('listener must be a function');
7009 if (!this._events || !this._events[type])
7012 list = this._events[type];
7013 length = list.length;
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);
7022 } else if (isObject(list)) {
7023 for (i = length; i-- > 0;) {
7024 if (list[i] === listener ||
7025 (list[i].listener && list[i].listener === listener)) {
7034 if (list.length === 1) {
7036 delete this._events[type];
7038 list.splice(position, 1);
7041 if (this._events.removeListener)
7042 this.emit('removeListener', type, listener);
7048 EventEmitter.prototype.removeAllListeners = function(type) {
7054 // not listening for removeListener, no need to emit
7055 if (!this._events.removeListener) {
7056 if (arguments.length === 0)
7058 else if (this._events[type])
7059 delete this._events[type];
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);
7069 this.removeAllListeners('removeListener');
7074 listeners = this._events[type];
7076 if (isFunction(listeners)) {
7077 this.removeListener(type, listeners);
7078 } else if (listeners) {
7080 while (listeners.length)
7081 this.removeListener(type, listeners[listeners.length - 1]);
7083 delete this._events[type];
7088 EventEmitter.prototype.listeners = function(type) {
7090 if (!this._events || !this._events[type])
7092 else if (isFunction(this._events[type]))
7093 ret = [this._events[type]];
7095 ret = this._events[type].slice();
7099 EventEmitter.prototype.listenerCount = function(type) {
7101 var evlistener = this._events[type];
7103 if (isFunction(evlistener))
7105 else if (evlistener)
7106 return evlistener.length;
7111 EventEmitter.listenerCount = function(emitter, type) {
7112 return emitter.listenerCount(type);
7115 function isFunction(arg) {
7116 return typeof arg === 'function';
7119 function isNumber(arg) {
7120 return typeof arg === 'number';
7123 function isObject(arg) {
7124 return typeof arg === 'object' && arg !== null;
7127 function isUndefined(arg) {
7128 return arg === void 0;
7131 },{}],35:[function(require,module,exports){
7132 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
7134 var eLen = (nBytes * 8) - mLen - 1
7135 var eMax = (1 << eLen) - 1
7136 var eBias = eMax >> 1
7138 var i = isLE ? (nBytes - 1) : 0
7139 var d = isLE ? -1 : 1
7140 var s = buffer[offset + i]
7144 e = s & ((1 << (-nBits)) - 1)
7147 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
7149 m = e & ((1 << (-nBits)) - 1)
7152 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
7156 } else if (e === eMax) {
7157 return m ? NaN : ((s ? -1 : 1) * Infinity)
7159 m = m + Math.pow(2, mLen)
7162 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
7165 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
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
7175 value = Math.abs(value)
7177 if (isNaN(value) || value === Infinity) {
7178 m = isNaN(value) ? 1 : 0
7181 e = Math.floor(Math.log(value) / Math.LN2)
7182 if (value * (c = Math.pow(2, -e)) < 1) {
7186 if (e + eBias >= 1) {
7189 value += rt * Math.pow(2, 1 - eBias)
7191 if (value * c >= 2) {
7196 if (e + eBias >= eMax) {
7199 } else if (e + eBias >= 1) {
7200 m = ((value * c) - 1) * Math.pow(2, mLen)
7203 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
7208 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
7212 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
7214 buffer[offset + i - d] |= s * 128
7217 },{}],36:[function(require,module,exports){
7218 arguments[4][24][0].apply(exports,arguments)
7219 },{"dup":24}],37:[function(require,module,exports){
7221 * Determine if an object is a Buffer
7223 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
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)
7233 function isBuffer (obj) {
7234 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
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))
7242 },{}],38:[function(require,module,exports){
7243 var toString = {}.toString;
7245 module.exports = Array.isArray || function (arr) {
7246 return toString.call(arr) == '[object Array]';
7249 },{}],39:[function(require,module,exports){
7253 var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
7254 (typeof Uint16Array !== 'undefined') &&
7255 (typeof Int32Array !== 'undefined');
7257 function _has(obj, key) {
7258 return Object.prototype.hasOwnProperty.call(obj, key);
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; }
7267 if (typeof source !== 'object') {
7268 throw new TypeError(source + 'must be non-object');
7271 for (var p in source) {
7272 if (_has(source, p)) {
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); }
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);
7297 // Fallback to ordinary array
7298 for (var i = 0; i < len; i++) {
7299 dest[dest_offs + i] = src[src_offs + i];
7302 // Join array of chunks to single array.
7303 flattenChunks: function (chunks) {
7304 var i, l, len, pos, chunk, result;
7306 // calculate data length
7308 for (i = 0, l = chunks.length; i < l; i++) {
7309 len += chunks[i].length;
7313 result = new Uint8Array(len);
7315 for (i = 0, l = chunks.length; i < l; i++) {
7317 result.set(chunk, pos);
7318 pos += chunk.length;
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];
7331 // Join array of chunks to single array.
7332 flattenChunks: function (chunks) {
7333 return [].concat.apply([], chunks);
7338 // Enable/Disable typed arrays use, for testing
7340 exports.setTyped = function (on) {
7342 exports.Buf8 = Uint8Array;
7343 exports.Buf16 = Uint16Array;
7344 exports.Buf32 = Int32Array;
7345 exports.assign(exports, fnTyped);
7347 exports.Buf8 = Array;
7348 exports.Buf16 = Array;
7349 exports.Buf32 = Array;
7350 exports.assign(exports, fnUntyped);
7354 exports.setTyped(TYPED_OK);
7356 },{}],40:[function(require,module,exports){
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.
7363 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
7364 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
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.
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:
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.
7382 function adler32(adler, buf, len, pos) {
7383 var s1 = (adler & 0xffff) |0,
7384 s2 = ((adler >>> 16) & 0xffff) |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;
7395 s1 = (s1 + buf[pos++]) |0;
7403 return (s1 | (s2 << 16)) |0;
7407 module.exports = adler32;
7409 },{}],41:[function(require,module,exports){
7412 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
7413 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
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.
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:
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.
7433 /* Allowed flush values; see deflate() and inflate() below for details */
7442 /* Return codes for the compression/decompression functions. Negative values
7443 * are errors, positive values are used for special but normal events.
7453 //Z_VERSION_ERROR: -6,
7455 /* compression levels */
7456 Z_NO_COMPRESSION: 0,
7458 Z_BEST_COMPRESSION: 9,
7459 Z_DEFAULT_COMPRESSION: -1,
7466 Z_DEFAULT_STRATEGY: 0,
7468 /* Possible values of the data_type field (though see inflate()) */
7471 //Z_ASCII: 1, // = Z_TEXT (deprecated)
7474 /* The deflate compression method */
7476 //Z_NULL: null // Use -1 or null inline, depending on var type
7479 },{}],42:[function(require,module,exports){
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.
7486 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
7487 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
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.
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:
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.
7505 // Use ordinary array, since untyped makes no boost here
7506 function makeTable() {
7509 for (var n = 0; n < 256; n++) {
7511 for (var k = 0; k < 8; k++) {
7512 c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
7520 // Create table on load. Just 255 signed longs. Not a problem.
7521 var crcTable = makeTable();
7524 function crc32(crc, buf, len, pos) {
7530 for (var i = pos; i < end; i++) {
7531 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
7534 return (crc ^ (-1)); // >>> 0;
7538 module.exports = crc32;
7540 },{}],43:[function(require,module,exports){
7543 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
7544 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
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.
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:
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.
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');
7568 /* Public constants ==========================================================*/
7569 /* ===========================================================================*/
7572 /* Allowed flush values; see deflate() and inflate() below for details */
7574 var Z_PARTIAL_FLUSH = 1;
7575 //var Z_SYNC_FLUSH = 2;
7576 var Z_FULL_FLUSH = 3;
7582 /* Return codes for the compression/decompression functions. Negative values
7583 * are errors, positive values are used for special but normal events.
7586 var Z_STREAM_END = 1;
7587 //var Z_NEED_DICT = 2;
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;
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;
7604 var Z_HUFFMAN_ONLY = 2;
7607 var Z_DEFAULT_STRATEGY = 0;
7609 /* Possible values of the data_type field (though see inflate()) */
7612 //var Z_ASCII = 1; // = Z_TEXT
7616 /* The deflate compression method */
7619 /*============================================================================*/
7622 var MAX_MEM_LEVEL = 9;
7623 /* Maximum value for memLevel in deflateInit2 */
7625 /* 32K LZ77 window */
7626 var DEF_MEM_LEVEL = 8;
7629 var LENGTH_CODES = 29;
7630 /* number of length codes, not counting the special END_BLOCK code */
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 */
7636 /* number of distance codes */
7638 /* number of codes used to transfer the bit lengths */
7639 var HEAP_SIZE = 2 * L_CODES + 1;
7640 /* maximum heap size */
7642 /* All codes must not exceed MAX_BITS bits */
7645 var MAX_MATCH = 258;
7646 var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
7648 var PRESET_DICT = 0x20;
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;
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 */
7663 var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
7665 function err(strm, errorCode) {
7666 strm.msg = msg[errorCode];
7671 return ((f) << 1) - ((f) > 4 ? 9 : 0);
7674 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
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()).
7683 function flush_pending(strm) {
7686 //_tr_flush_bits(s);
7687 var len = s.pending;
7688 if (len > strm.avail_out) {
7689 len = strm.avail_out;
7691 if (len === 0) { return; }
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;
7699 if (s.pending === 0) {
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);
7712 function put_byte(s, b) {
7713 s.pending_buf[s.pending++] = b;
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
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;
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()).
7737 function read_buf(strm, buf, start, size) {
7738 var len = strm.avail_in;
7740 if (len > size) { len = size; }
7741 if (len === 0) { return 0; }
7743 strm.avail_in -= len;
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);
7751 else if (strm.state.wrap === 2) {
7752 strm.adler = crc32(strm.adler, buf, len, start);
7755 strm.next_in += len;
7756 strm.total_in += len;
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
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.
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*/;
7781 var _win = s.window; // shortcut
7783 var wmask = s.w_mask;
7786 /* Stop when cur_match becomes <= limit. To simplify the code,
7787 * we prevent matches with the string of window index 0.
7790 var strend = s.strstart + MAX_MATCH;
7791 var scan_end1 = _win[scan + best_len - 1];
7792 var scan_end = _win[scan + best_len];
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.
7797 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
7799 /* Do not waste too much time if we already have a good match: */
7800 if (s.prev_length >= s.good_match) {
7803 /* Do not look for matches beyond the end of the input. This is necessary
7804 * to make deflate deterministic.
7806 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
7808 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
7811 // Assert(cur_match < s->strstart, "no future");
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.
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]) {
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.
7838 // Assert(*scan == *match, "match[2]?");
7840 /* We check for insufficient lookahead only every 8th comparison;
7841 * the 256th check will be made at strstart+258.
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] &&
7851 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
7853 len = MAX_MATCH - (strend - scan);
7854 scan = strend - MAX_MATCH;
7856 if (len > best_len) {
7857 s.match_start = cur_match;
7859 if (len >= nice_match) {
7862 scan_end1 = _win[scan + best_len - 1];
7863 scan_end = _win[scan + best_len];
7865 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
7867 if (best_len <= s.lookahead) {
7874 /* ===========================================================================
7875 * Fill the window when the lookahead becomes insufficient.
7876 * Updates strstart and lookahead.
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).
7884 function fill_window(s) {
7885 var _w_size = s.w_size;
7886 var p, n, m, more, str;
7888 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
7891 more = s.window_size - s.lookahead - s.strstart;
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) {
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)
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.
7911 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
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;
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.)
7930 s.head[p] = (m >= _w_size ? m - _w_size : 0);
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.
7945 if (s.strm.avail_in === 0) {
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.
7960 //Assert(more >= 2, "more < 2");
7961 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
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];
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
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;
7978 s.prev[str & s.w_mask] = s.head[s.ins_h];
7979 s.head[s.ins_h] = str;
7982 if (s.lookahead + s.insert < MIN_MATCH) {
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.
7991 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
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.
8000 // if (s.high_water < s.window_size) {
8001 // var curr = s.strstart + s.lookahead;
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.
8008 // init = s.window_size - curr;
8009 // if (init > WIN_INIT)
8011 // zmemzero(s->window + curr, (unsigned)init);
8012 // s->high_water = curr + init;
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.
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;
8027 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
8028 // "not enough room for search");
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.
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:
8044 var max_block_size = 0xffff;
8046 if (max_block_size > s.pending_buf_size - 5) {
8047 max_block_size = s.pending_buf_size - 5;
8050 /* Copy as much as possible from input to output: */
8052 /* Fill the window as much as possible: */
8053 if (s.lookahead <= 1) {
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");
8063 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
8064 return BS_NEED_MORE;
8067 if (s.lookahead === 0) {
8070 /* flush the current block */
8072 //Assert(s->block_start >= 0L, "block gone");
8073 // if (s.block_start < 0) throw new Error("block gone");
8075 s.strstart += s.lookahead;
8078 /* Emit a stored block if pending_buf will be full: */
8079 var max_start = s.block_start + max_block_size;
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;
8094 /* Flush if we may have to slide, otherwise block_start may become
8095 * negative and the data will be gone:
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;
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;
8116 return BS_FINISH_DONE;
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;
8128 return BS_NEED_MORE;
8131 /* ===========================================================================
8132 * Compress as much as possible from the input stream, return the current
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.
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 */
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.
8148 if (s.lookahead < MIN_LOOKAHEAD) {
8150 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
8151 return BS_NEED_MORE;
8153 if (s.lookahead === 0) {
8154 break; /* flush the current block */
8158 /* Insert the string window[strstart .. strstart+2] in the
8159 * dictionary, and set hash_head to the head of the hash chain:
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;
8170 /* Find the longest match, discarding those <= prev_length.
8171 * At this point we have always match_length < MIN_MATCH
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).
8178 s.match_length = longest_match(s, hash_head);
8179 /* longest_match() sets match_start */
8181 if (s.match_length >= MIN_MATCH) {
8182 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
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);
8188 s.lookahead -= s.match_length;
8190 /* Insert new strings in the hash table only if the match length
8191 * is not too large. This saves time but degrades compression.
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 */
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;
8202 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
8203 * always MIN_MATCH bytes ahead.
8205 } while (--s.match_length !== 0);
8209 s.strstart += s.match_length;
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;
8215 //#if MIN_MATCH != 3
8216 // Call UPDATE_HASH() MIN_MATCH-3 more times
8218 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
8219 * matter since it will be recomputed at next deflate call.
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]);
8232 /*** FLUSH_BLOCK(s, 0); ***/
8233 flush_block_only(s, false);
8234 if (s.strm.avail_out === 0) {
8235 return BS_NEED_MORE;
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;
8248 return BS_FINISH_DONE;
8251 /*** FLUSH_BLOCK(s, 0); ***/
8252 flush_block_only(s, false);
8253 if (s.strm.avail_out === 0) {
8254 return BS_NEED_MORE;
8258 return BS_BLOCK_DONE;
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.
8266 function deflate_slow(s, flush) {
8267 var hash_head; /* head of hash chain */
8268 var bflush; /* set if current block must be flushed */
8272 /* Process the input block. */
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.
8279 if (s.lookahead < MIN_LOOKAHEAD) {
8281 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
8282 return BS_NEED_MORE;
8284 if (s.lookahead === 0) { break; } /* flush the current block */
8287 /* Insert the string window[strstart .. strstart+2] in the
8288 * dictionary, and set hash_head to the head of the hash chain:
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;
8299 /* Find the longest match, discarding those <= prev_length.
8301 s.prev_length = s.match_length;
8302 s.prev_match = s.match_start;
8303 s.match_length = MIN_MATCH - 1;
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).
8311 s.match_length = longest_match(s, hash_head);
8312 /* longest_match() sets match_start */
8314 if (s.match_length <= 5 &&
8315 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
8317 /* If prev_match is also MIN_MATCH, match_start is garbage
8318 * but we will ignore the current match anyway.
8320 s.match_length = MIN_MATCH - 1;
8323 /* If there was a match at the previous step and the current
8324 * match is not better, output the previous match:
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. */
8330 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
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
8340 s.lookahead -= s.prev_length - 1;
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;
8350 } while (--s.prev_length !== 0);
8351 s.match_available = 0;
8352 s.match_length = MIN_MATCH - 1;
8356 /*** FLUSH_BLOCK(s, 0); ***/
8357 flush_block_only(s, false);
8358 if (s.strm.avail_out === 0) {
8359 return BS_NEED_MORE;
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.
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]);
8374 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
8375 flush_block_only(s, false);
8380 if (s.strm.avail_out === 0) {
8381 return BS_NEED_MORE;
8384 /* There is no previous match to compare with, wait for
8385 * the next step to decide.
8387 s.match_available = 1;
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]);
8398 s.match_available = 0;
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;
8408 return BS_FINISH_DONE;
8411 /*** FLUSH_BLOCK(s, 0); ***/
8412 flush_block_only(s, false);
8413 if (s.strm.avail_out === 0) {
8414 return BS_NEED_MORE;
8419 return BS_BLOCK_DONE;
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.)
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 */
8433 var _win = s.window;
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.
8440 if (s.lookahead <= MAX_MATCH) {
8442 if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
8443 return BS_NEED_MORE;
8445 if (s.lookahead === 0) { break; } /* flush the current block */
8448 /* See how many times the previous byte repeats */
8450 if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
8451 scan = s.strstart - 1;
8453 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
8454 strend = s.strstart + MAX_MATCH;
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] &&
8462 s.match_length = MAX_MATCH - (strend - scan);
8463 if (s.match_length > s.lookahead) {
8464 s.match_length = s.lookahead;
8467 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
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);
8474 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
8475 bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
8477 s.lookahead -= s.match_length;
8478 s.strstart += s.match_length;
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]);
8490 /*** FLUSH_BLOCK(s, 0); ***/
8491 flush_block_only(s, false);
8492 if (s.strm.avail_out === 0) {
8493 return BS_NEED_MORE;
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;
8506 return BS_FINISH_DONE;
8509 /*** FLUSH_BLOCK(s, 0); ***/
8510 flush_block_only(s, false);
8511 if (s.strm.avail_out === 0) {
8512 return BS_NEED_MORE;
8516 return BS_BLOCK_DONE;
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.)
8523 function deflate_huff(s, flush) {
8524 var bflush; /* set if current block must be flushed */
8527 /* Make sure that we have a literal to write. */
8528 if (s.lookahead === 0) {
8530 if (s.lookahead === 0) {
8531 if (flush === Z_NO_FLUSH) {
8532 return BS_NEED_MORE;
8534 break; /* flush the current block */
8538 /* Output a literal byte */
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]);
8546 /*** FLUSH_BLOCK(s, 0); ***/
8547 flush_block_only(s, false);
8548 if (s.strm.avail_out === 0) {
8549 return BS_NEED_MORE;
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;
8562 return BS_FINISH_DONE;
8565 /*** FLUSH_BLOCK(s, 0); ***/
8566 flush_block_only(s, false);
8567 if (s.strm.avail_out === 0) {
8568 return BS_NEED_MORE;
8572 return BS_BLOCK_DONE;
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.
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;
8588 var configuration_table;
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 */
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 */
8606 /* ===========================================================================
8607 * Initialize the "longest match" routines for a new zlib stream
8609 function lm_init(s) {
8610 s.window_size = 2 * s.w_size;
8612 /*** CLEAR_HASH(s); ***/
8613 zero(s.head); // Fill with NIL (= 0);
8615 /* Set the default configuration parameters:
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;
8626 s.match_length = s.prev_length = MIN_MATCH - 1;
8627 s.match_available = 0;
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 */
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 */
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.
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.
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.
8668 this.head = null; /* Heads of the hash chains or NIL. */
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 */
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
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.
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 */
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.
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
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
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.
8717 this.level = 0; /* compression level (1..9) */
8718 this.strategy = 0; /* favor or force Huffman coding*/
8720 this.good_match = 0;
8721 /* Use a faster search when the previous match is longer than this */
8723 this.nice_match = 0; /* Stop searching when current match exceeds this */
8725 /* used by trees.c: */
8727 /* Didn't use ct_data typedef below to suppress compiler warning */
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 */
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);
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 */
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 */
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 */
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.
8760 this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
8762 /* Depth of each subtree used as tie breaker for trees of equal frequency
8765 this.l_buf = 0; /* buffer index for literals or lengths */
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
8787 this.last_lit = 0; /* running index in l_buf */
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.
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 */
8802 /* Output buffer. bits are inserted starting at the bottom (least
8803 * significant bits).
8806 /* Number of valid bits in bi_buf. All bits above the last valid bit
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.
8821 function deflateResetKeep(strm) {
8824 if (!strm || !strm.state) {
8825 return err(strm, Z_STREAM_ERROR);
8828 strm.total_in = strm.total_out = 0;
8829 strm.data_type = Z_UNKNOWN;
8837 /* was made negative by deflate(..., Z_FINISH); */
8839 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
8840 strm.adler = (s.wrap === 2) ?
8841 0 // crc32(0, Z_NULL, 0)
8843 1; // adler32(0, Z_NULL, 0)
8844 s.last_flush = Z_NO_FLUSH;
8850 function deflateReset(strm) {
8851 var ret = deflateResetKeep(strm);
8853 lm_init(strm.state);
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;
8867 function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
8868 if (!strm) { // === Z_NULL
8869 return Z_STREAM_ERROR;
8873 if (level === Z_DEFAULT_COMPRESSION) {
8877 if (windowBits < 0) { /* suppress zlib wrapper */
8879 windowBits = -windowBits;
8882 else if (windowBits > 15) {
8883 wrap = 2; /* write gzip wrapper instead */
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);
8895 if (windowBits === 8) {
8898 /* until 256-byte window bug fixed */
8900 var s = new DeflateState();
8907 s.w_bits = windowBits;
8908 s.w_size = 1 << s.w_bits;
8909 s.w_mask = s.w_size - 1;
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);
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);
8920 // Don't need mem init magic for JS.
8921 //s.high_water = 0; /* nothing written to s->window yet */
8923 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
8925 s.pending_buf_size = s.lit_bufsize * 4;
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);
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;
8935 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
8936 s.l_buf = (1 + 2) * s.lit_bufsize;
8939 s.strategy = strategy;
8942 return deflateReset(strm);
8945 function deflateInit(strm, level) {
8946 return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
8950 function deflate(strm, flush) {
8952 var beg, val; // for gzip header write only
8954 if (!strm || !strm.state ||
8955 flush > Z_BLOCK || flush < 0) {
8956 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
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);
8967 s.strm = strm; /* just in case */
8968 old_flush = s.last_flush;
8969 s.last_flush = flush;
8971 /* Write the header */
8972 if (s.status === INIT_STATE) {
8974 if (s.wrap === 2) { // GZIP header
8975 strm.adler = 0; //crc32(0L, Z_NULL, 0);
8979 if (!s.gzhead) { // s->gzhead == Z_NULL
8985 put_byte(s, s.level === 9 ? 2 :
8986 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
8988 put_byte(s, OS_CODE);
8989 s.status = BUSY_STATE;
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)
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 ?
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);
9010 if (s.gzhead.hcrc) {
9011 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
9014 s.status = EXTRA_STATE;
9017 else // DEFLATE header
9019 var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
9020 var level_flags = -1;
9022 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
9024 } else if (s.level < 6) {
9026 } else if (s.level === 6) {
9031 header |= (level_flags << 6);
9032 if (s.strstart !== 0) { header |= PRESET_DICT; }
9033 header += 31 - (header % 31);
9035 s.status = BUSY_STATE;
9036 putShortMSB(s, header);
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);
9043 strm.adler = 1; // adler32(0L, Z_NULL, 0);
9048 if (s.status === EXTRA_STATE) {
9049 if (s.gzhead.extra/* != Z_NULL*/) {
9050 beg = s.pending; /* start of bytes to update crc */
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);
9057 flush_pending(strm);
9059 if (s.pending === s.pending_buf_size) {
9063 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
9066 if (s.gzhead.hcrc && s.pending > beg) {
9067 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9069 if (s.gzindex === s.gzhead.extra.length) {
9071 s.status = NAME_STATE;
9075 s.status = NAME_STATE;
9078 if (s.status === NAME_STATE) {
9079 if (s.gzhead.name/* != Z_NULL*/) {
9080 beg = s.pending; /* start of bytes to update crc */
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);
9088 flush_pending(strm);
9090 if (s.pending === s.pending_buf_size) {
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;
9102 } while (val !== 0);
9104 if (s.gzhead.hcrc && s.pending > beg) {
9105 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9109 s.status = COMMENT_STATE;
9113 s.status = COMMENT_STATE;
9116 if (s.status === COMMENT_STATE) {
9117 if (s.gzhead.comment/* != Z_NULL*/) {
9118 beg = s.pending; /* start of bytes to update crc */
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);
9126 flush_pending(strm);
9128 if (s.pending === s.pending_buf_size) {
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;
9140 } while (val !== 0);
9142 if (s.gzhead.hcrc && s.pending > beg) {
9143 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
9146 s.status = HCRC_STATE;
9150 s.status = HCRC_STATE;
9153 if (s.status === HCRC_STATE) {
9154 if (s.gzhead.hcrc) {
9155 if (s.pending + 2 > s.pending_buf_size) {
9156 flush_pending(strm);
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;
9166 s.status = BUSY_STATE;
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:
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.
9189 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
9190 flush !== Z_FINISH) {
9191 return err(strm, Z_BUF_ERROR);
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);
9199 /* Start a new block or continue the current one.
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));
9207 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
9208 s.status = FINISH_STATE;
9210 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
9211 if (strm.avail_out === 0) {
9213 /* avoid BUF_ERROR next call, see above */
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
9224 if (bstate === BS_BLOCK_DONE) {
9225 if (flush === Z_PARTIAL_FLUSH) {
9228 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
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().
9234 if (flush === Z_FULL_FLUSH) {
9235 /*** CLEAR_HASH(s); ***/ /* forget history */
9236 zero(s.head); // Fill with NIL (= 0);
9238 if (s.lookahead === 0) {
9245 flush_pending(strm);
9246 if (strm.avail_out === 0) {
9247 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
9252 //Assert(strm->avail_out > 0, "bug2");
9253 //if (strm.avail_out <= 0) { throw new Error("bug2");}
9255 if (flush !== Z_FINISH) { return Z_OK; }
9256 if (s.wrap <= 0) { return Z_STREAM_END; }
9258 /* Write the trailer */
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);
9271 putShortMSB(s, strm.adler >>> 16);
9272 putShortMSB(s, strm.adler & 0xffff);
9275 flush_pending(strm);
9276 /* If avail_out is zero, the application will call deflate again
9277 * to flush the rest.
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;
9284 function deflateEnd(strm) {
9287 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
9288 return Z_STREAM_ERROR;
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
9300 return err(strm, Z_STREAM_ERROR);
9305 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
9309 /* =========================================================================
9310 * Initializes the compression dictionary from the given byte
9311 * sequence without producing any compressed output.
9313 function deflateSetDictionary(strm, dictionary) {
9314 var dictLength = dictionary.length;
9324 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
9325 return Z_STREAM_ERROR;
9331 if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
9332 return Z_STREAM_ERROR;
9335 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
9337 /* adler32(strm->adler, dictionary, dictLength); */
9338 strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
9341 s.wrap = 0; /* avoid computing Adler-32 in read_buf */
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);
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;
9359 /* insert dictionary into window and hash */
9360 avail = strm.avail_in;
9361 next = strm.next_in;
9363 strm.avail_in = dictLength;
9365 strm.input = dictionary;
9367 while (s.lookahead >= MIN_MATCH) {
9369 n = s.lookahead - (MIN_MATCH - 1);
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;
9374 s.prev[str & s.w_mask] = s.head[s.ins_h];
9376 s.head[s.ins_h] = str;
9380 s.lookahead = MIN_MATCH - 1;
9383 s.strstart += s.lookahead;
9384 s.block_start = s.strstart;
9385 s.insert = s.lookahead;
9387 s.match_length = s.prev_length = MIN_MATCH - 1;
9388 s.match_available = 0;
9389 strm.next_in = next;
9391 strm.avail_in = avail;
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)';
9408 exports.deflateBound = deflateBound;
9409 exports.deflateCopy = deflateCopy;
9410 exports.deflateParams = deflateParams;
9411 exports.deflatePending = deflatePending;
9412 exports.deflatePrime = deflatePrime;
9413 exports.deflateTune = deflateTune;
9416 },{"../utils/common":39,"./adler32":40,"./crc32":42,"./messages":47,"./trees":48}],44:[function(require,module,exports){
9419 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
9420 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
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.
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:
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.
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 */
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.
9454 strm.avail_out >= 258
9455 start >= strm.avail_out
9458 On return, state.mode is one of:
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
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.
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
9477 module.exports = function inflate_fast(strm, start) {
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 */
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 */
9507 var input, output; // JS specific, because we have no pointers
9509 /* copy state to local variables */
9511 //here = state.here;
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
9522 wsize = state.wsize;
9523 whave = state.whave;
9524 wnext = state.wnext;
9525 s_window = state.window;
9528 lcode = state.lencode;
9529 dcode = state.distcode;
9530 lmask = (1 << state.lenbits) - 1;
9531 dmask = (1 << state.distbits) - 1;
9534 /* decode literals and length/distances until end-of-block or not enough
9535 input data or output space */
9540 hold += input[_in++] << bits;
9542 hold += input[_in++] << bits;
9546 here = lcode[hold & lmask];
9549 for (;;) { // Goto emulation
9550 op = here >>> 24/*here.bits*/;
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*/;
9560 else if (op & 16) { /* length base */
9561 len = here & 0xffff/*here.val*/;
9562 op &= 15; /* number of extra bits */
9565 hold += input[_in++] << bits;
9568 len += hold & ((1 << op) - 1);
9572 //Tracevv((stderr, "inflate: length %u\n", len));
9574 hold += input[_in++] << bits;
9576 hold += input[_in++] << bits;
9579 here = dcode[hold & dmask];
9582 for (;;) { // goto emulation
9583 op = here >>> 24/*here.bits*/;
9586 op = (here >>> 16) & 0xff/*here.op*/;
9588 if (op & 16) { /* distance base */
9589 dist = here & 0xffff/*here.val*/;
9590 op &= 15; /* number of extra bits */
9592 hold += input[_in++] << bits;
9595 hold += input[_in++] << bits;
9599 dist += hold & ((1 << op) - 1);
9600 //#ifdef INFLATE_STRICT
9602 strm.msg = 'invalid distance too far back';
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 */
9615 strm.msg = 'invalid distance too far back';
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) {
9625 // output[_out++] = 0;
9629 // len -= op - whave;
9631 // output[_out++] = 0;
9632 // } while (--op > whave);
9634 // from = _out - dist;
9636 // output[_out++] = output[from++];
9642 from = 0; // window index
9643 from_source = s_window;
9644 if (wnext === 0) { /* very common case */
9646 if (op < len) { /* some from window */
9649 output[_out++] = s_window[from++];
9651 from = _out - dist; /* rest from output */
9652 from_source = output;
9655 else if (wnext < op) { /* wrap around window */
9656 from += wsize + wnext - op;
9658 if (op < len) { /* some from end of window */
9661 output[_out++] = s_window[from++];
9664 if (wnext < len) { /* some from start of window */
9668 output[_out++] = s_window[from++];
9670 from = _out - dist; /* rest from output */
9671 from_source = output;
9675 else { /* contiguous in window */
9677 if (op < len) { /* some from window */
9680 output[_out++] = s_window[from++];
9682 from = _out - dist; /* rest from output */
9683 from_source = output;
9687 output[_out++] = from_source[from++];
9688 output[_out++] = from_source[from++];
9689 output[_out++] = from_source[from++];
9693 output[_out++] = from_source[from++];
9695 output[_out++] = from_source[from++];
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++];
9708 output[_out++] = output[from++];
9710 output[_out++] = output[from++];
9715 else if ((op & 64) === 0) { /* 2nd level distance code */
9716 here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
9720 strm.msg = 'invalid distance code';
9725 break; // need to emulate goto via "continue"
9728 else if ((op & 64) === 0) { /* 2nd level length code */
9729 here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
9732 else if (op & 32) { /* end-of-block */
9733 //Tracevv((stderr, "inflate: end of block\n"));
9738 strm.msg = 'invalid literal/length code';
9743 break; // need to emulate goto via "continue"
9745 } while (_in < last && _out < end);
9747 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
9751 hold &= (1 << bits) - 1;
9753 /* update state and return */
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));
9763 },{}],45:[function(require,module,exports){
9766 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
9767 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
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.
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:
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.
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');
9795 /* Public constants ==========================================================*/
9796 /* ===========================================================================*/
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;
9809 /* Return codes for the compression/decompression functions. Negative values
9810 * are errors, positive values are used for special but normal events.
9813 var Z_STREAM_END = 1;
9814 var Z_NEED_DICT = 2;
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;
9822 /* The deflate compression method */
9826 /* STATES ====================================================================*/
9827 /* ===========================================================================*/
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() */
9863 /* ===========================================================================*/
9867 var ENOUGH_LENS = 852;
9868 var ENOUGH_DISTS = 592;
9869 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
9872 /* 32K LZ77 window */
9873 var DEF_WBITS = MAX_WBITS;
9876 function zswap32(q) {
9877 return (((q >>> 24) & 0xff) +
9878 ((q >>> 8) & 0xff00) +
9879 ((q & 0xff00) << 8) +
9880 ((q & 0xff) << 24));
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 */
9894 this.head = null; /* where to save gzip header information */
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 */
9903 /* bit accumulator */
9904 this.hold = 0; /* input bit accumulator */
9905 this.bits = 0; /* number of bits in "in" */
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 */
9911 /* for table and code decoding */
9912 this.extra = 0; /* extra bits needed */
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 */
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[] */
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 */
9931 because we don't have pointers in js, we use lencode and distcode directly
9932 as buffers so we don't need codes
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 */
9942 function inflateResetKeep(strm) {
9945 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
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;
9956 state.head = null/*Z_NULL*/;
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);
9965 //Tracev((stderr, "inflate: reset\n"));
9969 function inflateReset(strm) {
9972 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
9977 return inflateResetKeep(strm);
9981 function inflateReset2(strm, windowBits) {
9986 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
9989 /* extract wrap request from windowBits parameter */
9990 if (windowBits < 0) {
9992 windowBits = -windowBits;
9995 wrap = (windowBits >> 4) + 1;
9996 if (windowBits < 48) {
10001 /* set number of window bits, free window if different */
10002 if (windowBits && (windowBits < 8 || windowBits > 15)) {
10003 return Z_STREAM_ERROR;
10005 if (state.window !== null && state.wbits !== windowBits) {
10006 state.window = null;
10009 /* update state and reset the rest of it */
10011 state.wbits = windowBits;
10012 return inflateReset(strm);
10015 function inflateInit2(strm, windowBits) {
10019 if (!strm) { return Z_STREAM_ERROR; }
10020 //strm.msg = Z_NULL; /* in case we return an error */
10022 state = new InflateState();
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*/;
10035 function inflateInit(strm) {
10036 return inflateInit2(strm, DEF_WBITS);
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.
10052 var lenfix, distfix; // We have no pointers in JS, so keep tables separate
10054 function fixedtables(state) {
10055 /* build fixed huffman tables if first call (may not be thread safe) */
10059 lenfix = new utils.Buf32(512);
10060 distfix = new utils.Buf32(32);
10062 /* literal/length table */
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; }
10069 inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
10071 /* distance table */
10073 while (sym < 32) { state.lens[sym++] = 5; }
10075 inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
10077 /* do this just once */
10081 state.lencode = lenfix;
10083 state.distcode = distfix;
10084 state.distbits = 5;
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
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.
10102 function updatewindow(strm, src, end, copy) {
10104 var state = strm.state;
10106 /* if it hasn't been done already, allocate space for the window */
10107 if (state.window === null) {
10108 state.wsize = 1 << state.wbits;
10112 state.window = new utils.Buf8(state.wsize);
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);
10119 state.whave = state.wsize;
10122 dist = state.wsize - state.wnext;
10126 //zmemcpy(state->window + state->wnext, end - copy, dist);
10127 utils.arraySet(state.window, src, end - copy, dist, state.wnext);
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;
10136 state.wnext += dist;
10137 if (state.wnext === state.wsize) { state.wnext = 0; }
10138 if (state.whave < state.wsize) { state.whave += dist; }
10144 function inflate(strm, flush) {
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 */
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 */
10165 var n; // temporary var for NEED_BITS
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 ];
10171 if (!strm || !strm.state || !strm.output ||
10172 (!strm.input && strm.avail_in !== 0)) {
10173 return Z_STREAM_ERROR;
10176 state = strm.state;
10177 if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
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;
10195 inf_leave: // goto emulation
10197 switch (state.mode) {
10199 if (state.wrap === 0) {
10200 state.mode = TYPEDO;
10203 //=== NEEDBITS(16);
10204 while (bits < 16) {
10205 if (have === 0) { break inf_leave; }
10207 hold += input[next++] << bits;
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);
10223 state.mode = FLAGS;
10226 state.flags = 0; /* expect zlib header */
10228 state.head.done = false;
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';
10236 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
10237 strm.msg = 'unknown compression method';
10241 //--- DROPBITS(4) ---//
10245 len = (hold & 0x0f)/*BITS(4)*/ + 8;
10246 if (state.wbits === 0) {
10249 else if (len > state.wbits) {
10250 strm.msg = 'invalid window size';
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;
10264 //=== NEEDBITS(16); */
10265 while (bits < 16) {
10266 if (have === 0) { break inf_leave; }
10268 hold += input[next++] << bits;
10272 state.flags = hold;
10273 if ((state.flags & 0xff) !== Z_DEFLATED) {
10274 strm.msg = 'unknown compression method';
10278 if (state.flags & 0xe000) {
10279 strm.msg = 'unknown header flags set';
10284 state.head.text = ((hold >> 8) & 1);
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);
10298 /* falls through */
10300 //=== NEEDBITS(32); */
10301 while (bits < 32) {
10302 if (have === 0) { break inf_leave; }
10304 hold += input[next++] << bits;
10309 state.head.time = hold;
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);
10325 /* falls through */
10327 //=== NEEDBITS(16); */
10328 while (bits < 16) {
10329 if (have === 0) { break inf_leave; }
10331 hold += input[next++] << bits;
10336 state.head.xflags = (hold & 0xff);
10337 state.head.os = (hold >> 8);
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);
10350 state.mode = EXLEN;
10351 /* falls through */
10353 if (state.flags & 0x0400) {
10354 //=== NEEDBITS(16); */
10355 while (bits < 16) {
10356 if (have === 0) { break inf_leave; }
10358 hold += input[next++] << bits;
10362 state.length = hold;
10364 state.head.extra_len = hold;
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);
10378 else if (state.head) {
10379 state.head.extra = null/*Z_NULL*/;
10381 state.mode = EXTRA;
10382 /* falls through */
10384 if (state.flags & 0x0400) {
10385 copy = state.length;
10386 if (copy > have) { copy = have; }
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);
10398 // extra field is limited to 65536 bytes
10399 // - no need for additional size check
10401 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
10404 //zmemcpy(state.head.extra + len, next,
10405 // len + copy > state.head.extra_max ?
10406 // state.head.extra_max - len : copy);
10408 if (state.flags & 0x0200) {
10409 state.check = crc32(state.check, input, copy, next);
10413 state.length -= copy;
10415 if (state.length) { break inf_leave; }
10419 /* falls through */
10421 if (state.flags & 0x0800) {
10422 if (have === 0) { break inf_leave; }
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);
10432 } while (len && copy < have);
10434 if (state.flags & 0x0200) {
10435 state.check = crc32(state.check, input, copy, next);
10439 if (len) { break inf_leave; }
10441 else if (state.head) {
10442 state.head.name = null;
10445 state.mode = COMMENT;
10446 /* falls through */
10448 if (state.flags & 0x1000) {
10449 if (have === 0) { break inf_leave; }
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);
10458 } while (len && copy < have);
10459 if (state.flags & 0x0200) {
10460 state.check = crc32(state.check, input, copy, next);
10464 if (len) { break inf_leave; }
10466 else if (state.head) {
10467 state.head.comment = null;
10470 /* falls through */
10472 if (state.flags & 0x0200) {
10473 //=== NEEDBITS(16); */
10474 while (bits < 16) {
10475 if (have === 0) { break inf_leave; }
10477 hold += input[next++] << bits;
10481 if (hold !== (state.check & 0xffff)) {
10482 strm.msg = 'header crc mismatch';
10492 state.head.hcrc = ((state.flags >> 9) & 1);
10493 state.head.done = true;
10495 strm.adler = state.check = 0;
10499 //=== NEEDBITS(32); */
10500 while (bits < 32) {
10501 if (have === 0) { break inf_leave; }
10503 hold += input[next++] << bits;
10507 strm.adler = state.check = zswap32(hold);
10513 /* falls through */
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;
10524 return Z_NEED_DICT;
10526 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
10528 /* falls through */
10530 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
10531 /* falls through */
10534 //--- BYTEBITS() ---//
10535 hold >>>= bits & 7;
10538 state.mode = CHECK;
10541 //=== NEEDBITS(3); */
10543 if (have === 0) { break inf_leave; }
10545 hold += input[next++] << bits;
10549 state.last = (hold & 0x01)/*BITS(1)*/;
10550 //--- DROPBITS(1) ---//
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;
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) ---//
10574 case 2: /* dynamic block */
10575 //Tracev((stderr, "inflate: dynamic codes block%s\n",
10576 // state.last ? " (last)" : ""));
10577 state.mode = TABLE;
10580 strm.msg = 'invalid block type';
10583 //--- DROPBITS(2) ---//
10589 //--- BYTEBITS() ---// /* go to byte boundary */
10590 hold >>>= bits & 7;
10593 //=== NEEDBITS(32); */
10594 while (bits < 32) {
10595 if (have === 0) { break inf_leave; }
10597 hold += input[next++] << bits;
10601 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
10602 strm.msg = 'invalid stored block lengths';
10606 state.length = hold & 0xffff;
10607 //Tracev((stderr, "inflate: stored length %u\n",
10613 state.mode = COPY_;
10614 if (flush === Z_TREES) { break inf_leave; }
10615 /* falls through */
10618 /* falls through */
10620 copy = state.length;
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);
10632 state.length -= copy;
10635 //Tracev((stderr, "inflate: stored end\n"));
10639 //=== NEEDBITS(14); */
10640 while (bits < 14) {
10641 if (have === 0) { break inf_leave; }
10643 hold += input[next++] << bits;
10647 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
10648 //--- DROPBITS(5) ---//
10652 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
10653 //--- DROPBITS(5) ---//
10657 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
10658 //--- DROPBITS(4) ---//
10662 //#ifndef PKZIP_BUG_WORKAROUND
10663 if (state.nlen > 286 || state.ndist > 30) {
10664 strm.msg = 'too many length or distance symbols';
10669 //Tracev((stderr, "inflate: table sizes ok\n"));
10671 state.mode = LENLENS;
10672 /* falls through */
10674 while (state.have < state.ncode) {
10677 if (have === 0) { break inf_leave; }
10679 hold += input[next++] << bits;
10683 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
10684 //--- DROPBITS(3) ---//
10689 while (state.have < 19) {
10690 state.lens[order[state.have++]] = 0;
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;
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;
10704 strm.msg = 'invalid code lengths set';
10708 //Tracev((stderr, "inflate: code lengths ok\n"));
10710 state.mode = CODELENS;
10711 /* falls through */
10713 while (state.have < state.nlen + state.ndist) {
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;
10720 if ((here_bits) <= bits) { break; }
10721 //--- PULLBYTE() ---//
10722 if (have === 0) { break inf_leave; }
10724 hold += input[next++] << bits;
10728 if (here_val < 16) {
10729 //--- DROPBITS(here.bits) ---//
10730 hold >>>= here_bits;
10733 state.lens[state.have++] = here_val;
10736 if (here_val === 16) {
10737 //=== NEEDBITS(here.bits + 2);
10740 if (have === 0) { break inf_leave; }
10742 hold += input[next++] << bits;
10746 //--- DROPBITS(here.bits) ---//
10747 hold >>>= here_bits;
10750 if (state.have === 0) {
10751 strm.msg = 'invalid bit length repeat';
10755 len = state.lens[state.have - 1];
10756 copy = 3 + (hold & 0x03);//BITS(2);
10757 //--- DROPBITS(2) ---//
10762 else if (here_val === 17) {
10763 //=== NEEDBITS(here.bits + 3);
10766 if (have === 0) { break inf_leave; }
10768 hold += input[next++] << bits;
10772 //--- DROPBITS(here.bits) ---//
10773 hold >>>= here_bits;
10777 copy = 3 + (hold & 0x07);//BITS(3);
10778 //--- DROPBITS(3) ---//
10784 //=== NEEDBITS(here.bits + 7);
10787 if (have === 0) { break inf_leave; }
10789 hold += input[next++] << bits;
10793 //--- DROPBITS(here.bits) ---//
10794 hold >>>= here_bits;
10798 copy = 11 + (hold & 0x7f);//BITS(7);
10799 //--- DROPBITS(7) ---//
10804 if (state.have + copy > state.nlen + state.ndist) {
10805 strm.msg = 'invalid bit length repeat';
10810 state.lens[state.have++] = len;
10815 /* handle error breaks in while */
10816 if (state.mode === BAD) { break; }
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';
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 */
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;
10838 strm.msg = 'invalid literal/lengths set';
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;
10855 strm.msg = 'invalid distances set';
10859 //Tracev((stderr, 'inflate: codes ok\n'));
10861 if (flush === Z_TREES) { break inf_leave; }
10862 /* falls through */
10865 /* falls through */
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;
10876 inflate_fast(strm, _out);
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;
10888 if (state.mode === TYPE) {
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;
10900 if (here_bits <= bits) { break; }
10901 //--- PULLBYTE() ---//
10902 if (have === 0) { break inf_leave; }
10904 hold += input[next++] << bits;
10908 if (here_op && (here_op & 0xf0) === 0) {
10909 last_bits = here_bits;
10911 last_val = here_val;
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;
10919 if ((last_bits + here_bits) <= bits) { break; }
10920 //--- PULLBYTE() ---//
10921 if (have === 0) { break inf_leave; }
10923 hold += input[next++] << bits;
10927 //--- DROPBITS(last.bits) ---//
10928 hold >>>= last_bits;
10931 state.back += last_bits;
10933 //--- DROPBITS(here.bits) ---//
10934 hold >>>= here_bits;
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));
10946 if (here_op & 32) {
10947 //Tracevv((stderr, "inflate: end of block\n"));
10952 if (here_op & 64) {
10953 strm.msg = 'invalid literal/length code';
10957 state.extra = here_op & 15;
10958 state.mode = LENEXT;
10959 /* falls through */
10962 //=== NEEDBITS(state.extra);
10965 if (have === 0) { break inf_leave; }
10967 hold += input[next++] << bits;
10971 state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
10972 //--- DROPBITS(state.extra) ---//
10973 hold >>>= state.extra;
10974 bits -= state.extra;
10976 state.back += state.extra;
10978 //Tracevv((stderr, "inflate: length %u\n", state.length));
10979 state.was = state.length;
10981 /* falls through */
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;
10989 if ((here_bits) <= bits) { break; }
10990 //--- PULLBYTE() ---//
10991 if (have === 0) { break inf_leave; }
10993 hold += input[next++] << bits;
10997 if ((here_op & 0xf0) === 0) {
10998 last_bits = here_bits;
11000 last_val = here_val;
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;
11008 if ((last_bits + here_bits) <= bits) { break; }
11009 //--- PULLBYTE() ---//
11010 if (have === 0) { break inf_leave; }
11012 hold += input[next++] << bits;
11016 //--- DROPBITS(last.bits) ---//
11017 hold >>>= last_bits;
11020 state.back += last_bits;
11022 //--- DROPBITS(here.bits) ---//
11023 hold >>>= here_bits;
11026 state.back += here_bits;
11027 if (here_op & 64) {
11028 strm.msg = 'invalid distance code';
11032 state.offset = here_val;
11033 state.extra = (here_op) & 15;
11034 state.mode = DISTEXT;
11035 /* falls through */
11038 //=== NEEDBITS(state.extra);
11041 if (have === 0) { break inf_leave; }
11043 hold += input[next++] << bits;
11047 state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
11048 //--- DROPBITS(state.extra) ---//
11049 hold >>>= state.extra;
11050 bits -= state.extra;
11052 state.back += state.extra;
11054 //#ifdef INFLATE_STRICT
11055 if (state.offset > state.dmax) {
11056 strm.msg = 'invalid distance too far back';
11061 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
11062 state.mode = MATCH;
11063 /* falls through */
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) {
11071 strm.msg = 'invalid distance too far back';
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; }
11083 // state.length -= copy;
11085 // output[put++] = 0;
11086 // } while (--copy);
11087 // if (state.length === 0) { state.mode = LEN; }
11091 if (copy > state.wnext) {
11092 copy -= state.wnext;
11093 from = state.wsize - copy;
11096 from = state.wnext - copy;
11098 if (copy > state.length) { copy = state.length; }
11099 from_source = state.window;
11101 else { /* copy from output */
11102 from_source = output;
11103 from = put - state.offset;
11104 copy = state.length;
11106 if (copy > left) { copy = left; }
11108 state.length -= copy;
11110 output[put++] = from_source[from++];
11112 if (state.length === 0) { state.mode = LEN; }
11115 if (left === 0) { break inf_leave; }
11116 output[put++] = state.length;
11122 //=== NEEDBITS(32);
11123 while (bits < 32) {
11124 if (have === 0) { break inf_leave; }
11126 // Use '|' instead of '+' to make sure that result is signed
11127 hold |= input[next++] << bits;
11132 strm.total_out += _out;
11133 state.total += _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));
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';
11151 //Tracev((stderr, "inflate: check matches trailer\n"));
11153 state.mode = LENGTH;
11154 /* falls through */
11156 if (state.wrap && state.flags) {
11157 //=== NEEDBITS(32);
11158 while (bits < 32) {
11159 if (have === 0) { break inf_leave; }
11161 hold += input[next++] << bits;
11165 if (hold !== (state.total & 0xffffffff)) {
11166 strm.msg = 'incorrect length check';
11174 //Tracev((stderr, "inflate: length matches trailer\n"));
11177 /* falls through */
11179 ret = Z_STREAM_END;
11182 ret = Z_DATA_ERROR;
11185 return Z_MEM_ERROR;
11187 /* falls through */
11189 return Z_STREAM_ERROR;
11193 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
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.
11202 //--- RESTORE() ---
11203 strm.next_out = put;
11204 strm.avail_out = left;
11205 strm.next_in = next;
11206 strm.avail_in = have;
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)) {
11215 return Z_MEM_ERROR;
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));
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) {
11236 function inflateEnd(strm) {
11238 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
11239 return Z_STREAM_ERROR;
11242 var state = strm.state;
11243 if (state.window) {
11244 state.window = null;
11250 function inflateGetHeader(strm, head) {
11254 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
11255 state = strm.state;
11256 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
11258 /* save header structure */
11264 function inflateSetDictionary(strm, dictionary) {
11265 var dictLength = dictionary.length;
11272 if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
11273 state = strm.state;
11275 if (state.wrap !== 0 && state.mode !== DICT) {
11276 return Z_STREAM_ERROR;
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;
11288 /* copy dictionary to window using updatewindow(), which will amend the
11289 existing dictionary if appropriate */
11290 ret = updatewindow(strm, dictionary, dictLength, dictLength);
11293 return Z_MEM_ERROR;
11295 state.havedict = 1;
11296 // Tracev((stderr, "inflate: dictionary set\n"));
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)';
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;
11321 },{"../utils/common":39,"./adler32":40,"./crc32":42,"./inffast":44,"./inftrees":46}],46:[function(require,module,exports){
11324 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
11325 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
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.
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:
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.
11343 var utils = require('../utils/common');
11346 var ENOUGH_LENS = 852;
11347 var ENOUGH_DISTS = 592;
11348 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
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
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
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
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
11376 module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
11378 var bits = opts.bits;
11379 //here = opts.here; /* table entry for duplication */
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 */
11402 var extra_index = 0;
11404 var here_bits, here_op, here_val;
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.
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.
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
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
11437 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
11438 for (len = 0; len <= MAXBITS; len++) {
11441 for (sym = 0; sym < codes; sym++) {
11442 count[lens[lens_index + sym]]++;
11445 /* bound code lengths, force root to be within code lengths */
11447 for (max = MAXBITS; max >= 1; max--) {
11448 if (count[max] !== 0) { break; }
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;
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;
11466 return 0; /* no symbols, but wait for decoding to report error */
11468 for (min = 1; min < max; min++) {
11469 if (count[min] !== 0) { break; }
11475 /* check for an over-subscribed or incomplete set of lengths */
11477 for (len = 1; len <= MAXBITS; len++) {
11479 left -= count[len];
11482 } /* over-subscribed */
11484 if (left > 0 && (type === CODES || max !== 1)) {
11485 return -1; /* incomplete set */
11488 /* generate offsets into symbol table for each length for sorting */
11490 for (len = 1; len < MAXBITS; len++) {
11491 offs[len + 1] = offs[len] + count[len];
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;
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.
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.
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.
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.
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.
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 */
11539 } else if (type === LENS) {
11543 extra_index -= 257;
11546 } else { /* DISTS */
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 */
11563 /* check available table space */
11564 if ((type === LENS && used > ENOUGH_LENS) ||
11565 (type === DISTS && used > ENOUGH_DISTS)) {
11569 /* process all codes and make table entries */
11571 /* create table entry */
11572 here_bits = len - drop;
11573 if (work[sym] < end) {
11575 here_val = work[sym];
11577 else if (work[sym] > end) {
11578 here_op = extra[extra_index + work[sym]];
11579 here_val = base[base_index + work[sym]];
11582 here_op = 32 + 64; /* end of block */
11586 /* replicate for those indices with low len bits equal to huff */
11587 incr = 1 << (len - drop);
11589 min = fill; /* save offset to next table */
11592 table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
11593 } while (fill !== 0);
11595 /* backwards increment the len-bit code huff */
11596 incr = 1 << (len - 1);
11597 while (huff & incr) {
11607 /* go to next symbol, update count, len */
11609 if (--count[len] === 0) {
11610 if (len === max) { break; }
11611 len = lens[lens_index + work[sym]];
11614 /* create new sub-table if needed */
11615 if (len > root && (huff & mask) !== low) {
11616 /* if first time, transition to sub-tables */
11621 /* increment past last table */
11622 next += min; /* here min is 1 << curr */
11624 /* determine length of next table */
11627 while (curr + drop < max) {
11628 left -= count[curr + drop];
11629 if (left <= 0) { break; }
11634 /* check for enough space */
11636 if ((type === LENS && used > ENOUGH_LENS) ||
11637 (type === DISTS && used > ENOUGH_DISTS)) {
11641 /* point entry in root table to sub-table */
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;
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) */
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;
11660 /* set return parameters */
11661 //opts.table_index += used;
11666 },{"../utils/common":39}],47:[function(require,module,exports){
11669 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
11670 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
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.
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:
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.
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) */
11700 },{}],48:[function(require,module,exports){
11703 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
11704 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
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.
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:
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.
11722 /* eslint-disable space-unary-ops */
11724 var utils = require('../utils/common');
11726 /* Public constants ==========================================================*/
11727 /* ===========================================================================*/
11730 //var Z_FILTERED = 1;
11731 //var Z_HUFFMAN_ONLY = 2;
11734 //var Z_DEFAULT_STRATEGY = 0;
11736 /* Possible values of the data_type field (though see inflate()) */
11739 //var Z_ASCII = 1; // = Z_TEXT
11742 /*============================================================================*/
11745 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
11749 var STORED_BLOCK = 0;
11750 var STATIC_TREES = 1;
11752 /* The three kinds of block type */
11755 var MAX_MATCH = 258;
11756 /* The minimum and maximum match lengths */
11759 /* ===========================================================================
11760 * Internal compression state.
11763 var LENGTH_CODES = 29;
11764 /* number of length codes, not counting the special END_BLOCK code */
11766 var LITERALS = 256;
11767 /* number of literal bytes 0..255 */
11769 var L_CODES = LITERALS + 1 + LENGTH_CODES;
11770 /* number of Literal or Length codes, including the END_BLOCK code */
11773 /* number of distance codes */
11776 /* number of codes used to transfer the bit lengths */
11778 var HEAP_SIZE = 2 * L_CODES + 1;
11779 /* maximum heap size */
11782 /* All codes must not exceed MAX_BITS bits */
11785 /* size of bit buffer in bi_buf */
11788 /* ===========================================================================
11792 var MAX_BL_BITS = 7;
11793 /* Bit length codes must not exceed MAX_BL_BITS bits */
11795 var END_BLOCK = 256;
11796 /* end of block literal code */
11799 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
11801 var REPZ_3_10 = 17;
11802 /* repeat a zero length 3-10 times (3 bits of repeat count) */
11804 var REPZ_11_138 = 18;
11805 /* repeat a zero length 11-138 times (7 bits of repeat count) */
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];
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];
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];
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 */
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.
11825 /* ===========================================================================
11826 * Local data. These are initialized only once.
11829 // We pre-fill arrays with 0 to avoid uninitialized gaps
11831 var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
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
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
11848 var _dist_code = new Array(DIST_CODE_LEN);
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.
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) */
11859 var base_length = new Array(LENGTH_CODES);
11861 /* First normalized length for each code (0 = MIN_MATCH) */
11863 var base_dist = new Array(D_CODES);
11865 /* First normalized distance for each code (0 = distance of 1) */
11868 function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
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 */
11876 // show if `static_tree` has data or dummy - needed for monomorphic objects
11877 this.has_stree = static_tree && static_tree.length;
11883 var static_bl_desc;
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 */
11894 function d_code(dist) {
11895 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
11899 /* ===========================================================================
11900 * Output a short LSB first on the stream.
11901 * IN assertion: there is enough room in pendingBuf.
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;
11911 /* ===========================================================================
11912 * Send a value on a given number of bits.
11913 * IN assertion: length <= 16 and value fits in length bits.
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;
11922 s.bi_buf |= (value << s.bi_valid) & 0xffff;
11923 s.bi_valid += length;
11928 function send_code(s, c, tree) {
11929 send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
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
11938 function bi_reverse(code, len) {
11944 } while (--len > 0);
11949 /* ===========================================================================
11950 * Flush the bit buffer, keeping at most 7 bits in it.
11952 function bi_flush(s) {
11953 if (s.bi_valid === 16) {
11954 put_short(s, s.bi_buf);
11958 } else if (s.bi_valid >= 8) {
11959 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
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
11976 function gen_bitlen(s, desc)
11977 // deflate_state *s;
11978 // tree_desc *desc; /* the tree descriptor */
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 */
11994 for (bits = 0; bits <= MAX_BITS; bits++) {
11995 s.bl_count[bits] = 0;
11998 /* In a first pass, compute the optimal bit lengths (which may
11999 * overflow in the case of the bit length tree).
12001 tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
12003 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
12005 bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
12006 if (bits > max_length) {
12010 tree[n * 2 + 1]/*.Len*/ = bits;
12011 /* We overwrite tree[n].Dad which is no longer needed */
12013 if (n > max_code) { continue; } /* not a leaf node */
12015 s.bl_count[bits]++;
12018 xbits = extra[n - base];
12020 f = tree[n * 2]/*.Freq*/;
12021 s.opt_len += f * (bits + xbits);
12023 s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
12026 if (overflow === 0) { return; }
12028 // Trace((stderr,"\nbit length overflow\n"));
12029 /* This happens for example on obj2 and pic of the Calgary corpus */
12031 /* Find the first bit length which could increase: */
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]
12042 } while (overflow > 0);
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.)
12049 for (bits = max_length; bits !== 0; bits--) {
12050 n = s.bl_count[bits];
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;
12065 /* ===========================================================================
12066 * Generate the codes for a given tree and bit counts (which need not be
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.
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 */
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 */
12083 /* The distribution counts are first used to generate the code values
12084 * without bit reversal.
12086 for (bits = 1; bits <= MAX_BITS; bits++) {
12087 next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
12089 /* Check that the bit counts in bl_count are consistent. The last code
12090 * must be all ones.
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));
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);
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));
12108 /* ===========================================================================
12109 * Initialize the various 'constant' tables.
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 */
12120 // do check in _tr_init()
12121 //if (static_init_done) return;
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;
12132 /* Initialize the mapping length (0..255) -> length code (0..28) */
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;
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:
12145 _length_code[length - 1] = code;
12147 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
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;
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;
12163 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
12165 /* Construct the codes of the static literal tree */
12166 for (bits = 0; bits <= MAX_BITS; bits++) {
12167 bl_count[bits] = 0;
12172 static_ltree[n * 2 + 1]/*.Len*/ = 8;
12177 static_ltree[n * 2 + 1]/*.Len*/ = 9;
12182 static_ltree[n * 2 + 1]/*.Len*/ = 7;
12187 static_ltree[n * 2 + 1]/*.Len*/ = 8;
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
12195 gen_codes(static_ltree, L_CODES + 1, bl_count);
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);
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);
12208 //static_init_done = true;
12212 /* ===========================================================================
12213 * Initialize a new block.
12215 function init_block(s) {
12216 var n; /* iterates over tree elements */
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; }
12223 s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
12224 s.opt_len = s.static_len = 0;
12225 s.last_lit = s.matches = 0;
12229 /* ===========================================================================
12230 * Flush the bit buffer and align the output on a byte boundary
12232 function bi_windup(s)
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;
12244 /* ===========================================================================
12245 * Copy a stored block, storing first the length and its
12246 * one's complement if requested.
12248 function copy_block(s, buf, len, header)
12250 //charf *buf; /* the input data */
12251 //unsigned len; /* its length */
12252 //int header; /* true if block header must be written */
12254 bi_windup(s); /* align on byte boundary */
12258 put_short(s, ~len);
12261 // put_byte(s, *buf++);
12263 utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
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.
12271 function smaller(tree, n, m, depth) {
12274 return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
12275 (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
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
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 */
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)) {
12297 /* Exit if v is smaller than both sons */
12298 if (smaller(tree, v, s.heap[j], s.depth)) { break; }
12300 /* Exchange v with the smallest son */
12301 s.heap[k] = s.heap[j];
12304 /* And continue down the tree, setting j to the left son of k */
12311 // inlined manually
12312 // var SMALLEST = 1;
12314 /* ===========================================================================
12315 * Send the block data compressed using the given Huffman trees
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 */
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 */
12328 if (s.last_lit !== 0) {
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];
12335 send_code(s, lc, ltree); /* send a literal byte */
12336 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
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];
12343 lc -= base_length[code];
12344 send_bits(s, lc, extra); /* send the extra length bits */
12346 dist--; /* dist is now the match distance - 1 */
12347 code = d_code(dist);
12348 //Assert (code < D_CODES, "bad d_code");
12350 send_code(s, code, dtree); /* send the distance code */
12351 extra = extra_dbits[code];
12353 dist -= base_dist[code];
12354 send_bits(s, dist, extra); /* send the extra distance bits */
12356 } /* literal or match pair ? */
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");
12362 } while (lx < s.last_lit);
12365 send_code(s, END_BLOCK, ltree);
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.
12377 function build_tree(s, desc)
12378 // deflate_state *s;
12379 // tree_desc *desc; /* the tree descriptor */
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 */
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.
12394 s.heap_max = HEAP_SIZE;
12396 for (n = 0; n < elems; n++) {
12397 if (tree[n * 2]/*.Freq*/ !== 0) {
12398 s.heap[++s.heap_len] = max_code = n;
12402 tree[n * 2 + 1]/*.Len*/ = 0;
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.
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;
12418 s.static_len -= stree[node * 2 + 1]/*.Len*/;
12420 /* node is 0 or 1 so it does not have extra bits */
12422 desc.max_code = max_code;
12424 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
12425 * establish sub-heaps of increasing lengths:
12427 for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
12429 /* Construct the Huffman tree by repeatedly combining the least two
12432 node = elems; /* next internal node of the tree */
12434 //pqremove(s, tree, n); /* n = node of least frequency */
12436 n = s.heap[1/*SMALLEST*/];
12437 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
12438 pqdownheap(s, tree, 1/*SMALLEST*/);
12441 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
12443 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
12444 s.heap[--s.heap_max] = m;
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;
12451 /* and insert the new node in the heap */
12452 s.heap[1/*SMALLEST*/] = node++;
12453 pqdownheap(s, tree, 1/*SMALLEST*/);
12455 } while (s.heap_len >= 2);
12457 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
12459 /* At this point, the fields freq and dad are set. We can now
12460 * generate the bit lengths.
12462 gen_bitlen(s, desc);
12464 /* The field len is now set, we can generate the bit codes */
12465 gen_codes(tree, max_code, s.bl_count);
12469 /* ===========================================================================
12470 * Scan a literal or distance tree to determine the frequencies of the codes
12471 * in the bit length tree.
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 */
12478 var n; /* iterates over all tree elements */
12479 var prevlen = -1; /* last emitted length */
12480 var curlen; /* length of current code */
12482 var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
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 */
12488 if (nextlen === 0) {
12492 tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
12494 for (n = 0; n <= max_code; n++) {
12496 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
12498 if (++count < max_count && curlen === nextlen) {
12501 } else if (count < min_count) {
12502 s.bl_tree[curlen * 2]/*.Freq*/ += count;
12504 } else if (curlen !== 0) {
12506 if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
12507 s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
12509 } else if (count <= 10) {
12510 s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
12513 s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
12519 if (nextlen === 0) {
12523 } else if (curlen === nextlen) {
12535 /* ===========================================================================
12536 * Send a literal or distance tree in compressed form, using the codes in
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 */
12544 var n; /* iterates over all tree elements */
12545 var prevlen = -1; /* last emitted length */
12546 var curlen; /* length of current code */
12548 var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
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 */
12554 /* tree[max_code+1].Len = -1; */ /* guard already set */
12555 if (nextlen === 0) {
12560 for (n = 0; n <= max_code; n++) {
12562 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
12564 if (++count < max_count && curlen === nextlen) {
12567 } else if (count < min_count) {
12568 do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
12570 } else if (curlen !== 0) {
12571 if (curlen !== prevlen) {
12572 send_code(s, curlen, s.bl_tree);
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);
12579 } else if (count <= 10) {
12580 send_code(s, REPZ_3_10, s.bl_tree);
12581 send_bits(s, count - 3, 3);
12584 send_code(s, REPZ_11_138, s.bl_tree);
12585 send_bits(s, count - 11, 7);
12590 if (nextlen === 0) {
12594 } else if (curlen === nextlen) {
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.
12610 function build_bl_tree(s) {
12611 var max_blindex; /* index of last bit length code of non zero freq */
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);
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.
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.)
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) {
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));
12637 return max_blindex;
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.
12646 function send_all_trees(s, lcodes, dcodes, blcodes)
12647 // deflate_state *s;
12648 // int lcodes, dcodes, blcodes; /* number of codes for each tree */
12650 var rank; /* index in bl_order */
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);
12663 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
12665 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
12666 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
12668 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
12669 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
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.
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
12691 var black_mask = 0xf3ffc07f;
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)) {
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) {
12706 for (n = 32; n < LITERALS; n++) {
12707 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
12712 /* There are no "black-listed" or "white-listed" bytes:
12713 * this stream either is empty or has tolerated ("gray-listed") bytes only.
12719 var static_init_done = false;
12721 /* ===========================================================================
12722 * Initialize the tree data structures for a new zlib stream.
12724 function _tr_init(s)
12727 if (!static_init_done) {
12729 static_init_done = true;
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);
12739 /* Initialize the first block of the first file: */
12744 /* ===========================================================================
12745 * Send a stored block
12747 function _tr_stored_block(s, buf, stored_len, last)
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 */
12753 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
12754 copy_block(s, buf, stored_len, true); /* with header */
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.
12762 function _tr_align(s) {
12763 send_bits(s, STATIC_TREES << 1, 3);
12764 send_code(s, END_BLOCK, static_ltree);
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.
12773 function _tr_flush_block(s, buf, stored_len, last)
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 */
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 */
12782 /* Build the Huffman trees unless a stored block is forced */
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);
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));
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.
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.
12805 max_blindex = build_bl_tree(s);
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;
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,
12815 if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
12818 // Assert(buf != (char*)0, "lost buf");
12819 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
12822 if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
12823 /* 4: two words for the lengths */
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.
12831 _tr_stored_block(s, buf, stored_len, last);
12833 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
12835 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
12836 compress_block(s, static_ltree, static_dtree);
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);
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.
12852 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
12853 // s->compressed_len-7*last));
12856 /* ===========================================================================
12857 * Save the match info and tally the frequency counts. Return true if
12858 * the current block must be flushed.
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) */
12865 //var out_length, in_length, dcode;
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;
12870 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
12874 /* lc is the unmatched char */
12875 s.dyn_ltree[lc * 2]/*.Freq*/++;
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");
12884 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
12885 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
12888 // (!) This block is disabled in zlib defaults,
12889 // don't enable it for binary compatibility
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;
12898 // for (dcode = 0; dcode < D_CODES; dcode++) {
12899 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
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*/) {
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
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;
12924 },{"../utils/common":39}],49:[function(require,module,exports){
12927 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
12928 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
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.
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:
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.
12946 function ZStream() {
12947 /* next input byte */
12948 this.input = null; // JS specific, because we have no pointers
12950 /* number of bytes available at input */
12952 /* total number of input bytes read so far */
12954 /* next output byte should be put there */
12955 this.output = null; // JS specific, because we have no pointers
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 */
12965 /* best guess about the data type: binary or text */
12966 this.data_type = 2/*Z_UNKNOWN*/;
12967 /* adler32 value of the uncompressed data */
12971 module.exports = ZStream;
12973 },{}],50:[function(require,module,exports){
12974 (function (process){
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;
12982 module.exports = process.nextTick;
12985 function nextTick(fn, arg1, arg2, arg3) {
12986 if (typeof fn !== 'function') {
12987 throw new TypeError('"callback" argument must be a function');
12989 var len = arguments.length;
12994 return process.nextTick(fn);
12996 return process.nextTick(function afterTickOne() {
12997 fn.call(null, arg1);
13000 return process.nextTick(function afterTickTwo() {
13001 fn.call(null, arg1, arg2);
13004 return process.nextTick(function afterTickThree() {
13005 fn.call(null, arg1, arg2, arg3);
13008 args = new Array(len - 1);
13010 while (i < args.length) {
13011 args[i++] = arguments[i];
13013 return process.nextTick(function afterTick() {
13014 fn.apply(null, args);
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 = {};
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.
13029 var cachedSetTimeout;
13030 var cachedClearTimeout;
13032 function defaultSetTimout() {
13033 throw new Error('setTimeout has not been defined');
13035 function defaultClearTimeout () {
13036 throw new Error('clearTimeout has not been defined');
13040 if (typeof setTimeout === 'function') {
13041 cachedSetTimeout = setTimeout;
13043 cachedSetTimeout = defaultSetTimout;
13046 cachedSetTimeout = defaultSetTimout;
13049 if (typeof clearTimeout === 'function') {
13050 cachedClearTimeout = clearTimeout;
13052 cachedClearTimeout = defaultClearTimeout;
13055 cachedClearTimeout = defaultClearTimeout;
13058 function runTimeout(fun) {
13059 if (cachedSetTimeout === setTimeout) {
13060 //normal enviroments in sane situations
13061 return setTimeout(fun, 0);
13063 // if setTimeout wasn't available but was latter defined
13064 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
13065 cachedSetTimeout = setTimeout;
13066 return setTimeout(fun, 0);
13069 // when when somebody has screwed with setTimeout but no I.E. maddness
13070 return cachedSetTimeout(fun, 0);
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);
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);
13083 function runClearTimeout(marker) {
13084 if (cachedClearTimeout === clearTimeout) {
13085 //normal enviroments in sane situations
13086 return clearTimeout(marker);
13088 // if clearTimeout wasn't available but was latter defined
13089 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
13090 cachedClearTimeout = clearTimeout;
13091 return clearTimeout(marker);
13094 // when when somebody has screwed with setTimeout but no I.E. maddness
13095 return cachedClearTimeout(marker);
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);
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);
13111 var draining = false;
13113 var queueIndex = -1;
13115 function cleanUpNextTick() {
13116 if (!draining || !currentQueue) {
13120 if (currentQueue.length) {
13121 queue = currentQueue.concat(queue);
13125 if (queue.length) {
13130 function drainQueue() {
13134 var timeout = runTimeout(cleanUpNextTick);
13137 var len = queue.length;
13139 currentQueue = queue;
13141 while (++queueIndex < len) {
13142 if (currentQueue) {
13143 currentQueue[queueIndex].run();
13147 len = queue.length;
13149 currentQueue = null;
13151 runClearTimeout(timeout);
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];
13161 queue.push(new Item(fun, args));
13162 if (queue.length === 1 && !draining) {
13163 runTimeout(drainQueue);
13167 // v8 likes predictible objects
13168 function Item(fun, array) {
13170 this.array = array;
13172 Item.prototype.run = function () {
13173 this.fun.apply(null, this.array);
13175 process.title = 'browser';
13176 process.browser = true;
13179 process.version = ''; // empty string to avoid regexp issues
13180 process.versions = {};
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;
13194 process.listeners = function (name) { return [] }
13196 process.binding = function (name) {
13197 throw new Error('process.binding is not supported');
13200 process.cwd = function () { return '/' };
13201 process.chdir = function (dir) {
13202 throw new Error('process.chdir is not supported');
13204 process.umask = function() { return 0; };
13206 },{}],52:[function(require,module,exports){
13207 module.exports = require('./lib/_stream_duplex.js');
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
13219 var objectKeys = Object.keys || function (obj) {
13221 for (var key in obj) {
13227 module.exports = Duplex;
13230 var processNextTick = require('process-nextick-args');
13234 var util = require('core-util-is');
13235 util.inherits = require('inherits');
13238 var Readable = require('./_stream_readable');
13239 var Writable = require('./_stream_writable');
13241 util.inherits(Duplex, Readable);
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];
13249 function Duplex(options) {
13250 if (!(this instanceof Duplex)) return new Duplex(options);
13252 Readable.call(this, options);
13253 Writable.call(this, options);
13255 if (options && options.readable === false) this.readable = false;
13257 if (options && options.writable === false) this.writable = false;
13259 this.allowHalfOpen = true;
13260 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
13262 this.once('end', onend);
13265 // the no-half-open enforcer
13267 // if we allow half-open state, or if the writable side ended,
13269 if (this.allowHalfOpen || this._writableState.ended) return;
13271 // no more data can be written.
13272 // But allow more writes to happen in this tick.
13273 processNextTick(onEndNT, this);
13276 function onEndNT(self) {
13280 function forEach(xs, f) {
13281 for (var i = 0, l = xs.length; i < l; i++) {
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.
13292 module.exports = PassThrough;
13294 var Transform = require('./_stream_transform');
13297 var util = require('core-util-is');
13298 util.inherits = require('inherits');
13301 util.inherits(PassThrough, Transform);
13303 function PassThrough(options) {
13304 if (!(this instanceof PassThrough)) return new PassThrough(options);
13306 Transform.call(this, options);
13309 PassThrough.prototype._transform = function (chunk, encoding, cb) {
13312 },{"./_stream_transform":56,"core-util-is":33,"inherits":36}],55:[function(require,module,exports){
13313 (function (process){
13316 module.exports = Readable;
13319 var processNextTick = require('process-nextick-args');
13323 var isArray = require('isarray');
13330 Readable.ReadableState = ReadableState;
13333 var EE = require('events').EventEmitter;
13335 var EElistenerCount = function (emitter, type) {
13336 return emitter.listeners(type).length;
13341 var Stream = require('./internal/streams/stream');
13344 var Buffer = require('buffer').Buffer;
13346 var bufferShim = require('buffer-shims');
13350 var util = require('core-util-is');
13351 util.inherits = require('inherits');
13355 var debugUtil = require('util');
13356 var debug = void 0;
13357 if (debugUtil && debugUtil.debuglog) {
13358 debug = debugUtil.debuglog('stream');
13360 debug = function () {};
13364 var BufferList = require('./internal/streams/BufferList');
13367 util.inherits(Readable, Stream);
13369 var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
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);
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]];
13385 function ReadableState(options, stream) {
13386 Duplex = Duplex || require('./_stream_duplex');
13388 options = options || {};
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;
13394 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
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;
13403 this.highWaterMark = ~~this.highWaterMark;
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
13408 this.buffer = new BufferList();
13411 this.pipesCount = 0;
13412 this.flowing = null;
13413 this.ended = false;
13414 this.endEmitted = false;
13415 this.reading = false;
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.
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;
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';
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;
13439 // the number of writers that are awaiting a drain event in .pipe()s
13440 this.awaitDrain = 0;
13442 // if true, a maybeReadMore has been scheduled
13443 this.readingMore = false;
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;
13454 function Readable(options) {
13455 Duplex = Duplex || require('./_stream_duplex');
13457 if (!(this instanceof Readable)) return new Readable(options);
13459 this._readableState = new ReadableState(options, this);
13462 this.readable = true;
13464 if (options && typeof options.read === 'function') this._read = options.read;
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;
13476 if (!state.objectMode && typeof chunk === 'string') {
13477 encoding = encoding || state.defaultEncoding;
13478 if (encoding !== state.encoding) {
13479 chunk = bufferShim.from(chunk, encoding);
13484 return readableAddChunk(this, state, chunk, encoding, false);
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);
13493 Readable.prototype.isPaused = function () {
13494 return this._readableState.flowing === false;
13497 function readableAddChunk(stream, state, chunk, encoding, addToFront) {
13498 var er = chunkInvalid(state, chunk);
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);
13513 if (state.decoder && !addToFront && !encoding) {
13514 chunk = state.decoder.write(chunk);
13515 skipAdd = !state.objectMode && chunk.length === 0;
13518 if (!addToFront) state.reading = false;
13520 // Don't add to the buffer if we've decoded to an empty string chunk and
13521 // we're not in object mode
13523 // if we want the data now, just emit it.
13524 if (state.flowing && state.length === 0 && !state.sync) {
13525 stream.emit('data', chunk);
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);
13532 if (state.needReadable) emitReadable(stream);
13536 maybeReadMore(stream, state);
13538 } else if (!addToFront) {
13539 state.reading = false;
13542 return needMoreData(state);
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);
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;
13564 // Don't raise the hwm > 8MB
13565 var MAX_HWM = 0x800000;
13566 function computeNewHighWaterMark(n) {
13567 if (n >= MAX_HWM) {
13570 // Get the next highest power of 2 to prevent increasing hwm excessively in
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;
13589 // Only flow one buffer at a time
13590 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
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;
13600 return state.length;
13603 // you can override either this method, or the async _read(n) below.
13604 Readable.prototype.read = function (n) {
13606 n = parseInt(n, 10);
13607 var state = this._readableState;
13610 if (n !== 0) state.emittedReadable = false;
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);
13621 n = howMuchToRead(n, state);
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);
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.
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.
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
13649 // 3. Actually pull the requested chunks out of the buffer and return.
13651 // if we need a readable event, then we need to do some reading.
13652 var doRead = state.needReadable;
13653 debug('need readable', doRead);
13655 // if we currently have less than the highWaterMark, then also read some
13656 if (state.length === 0 || state.length - n < state.highWaterMark) {
13658 debug('length less than watermark', doRead);
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) {
13665 debug('reading or ended', doRead);
13666 } else if (doRead) {
13668 state.reading = 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);
13681 if (n > 0) ret = fromList(n, state);else ret = null;
13683 if (ret === null) {
13684 state.needReadable = true;
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;
13695 // If we tried to read() past the EOF, then emit end on the next tick.
13696 if (nOrig !== n && state.ended) endReadable(this);
13699 if (ret !== null) this.emit('data', ret);
13704 function chunkInvalid(state, chunk) {
13706 if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
13707 er = new TypeError('Invalid non-string/buffer chunk');
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;
13721 state.ended = true;
13723 // emit 'readable' now to make sure it gets picked up.
13724 emitReadable(stream);
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);
13740 function emitReadable_(stream) {
13741 debug('emit readable');
13742 stream.emit('readable');
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);
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');
13764 if (len === state.length)
13765 // didn't get any data, stop spinning.
13766 break;else len = state.length;
13768 state.readingMore = false;
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'));
13779 Readable.prototype.pipe = function (dest, pipeOpts) {
13781 var state = this._readableState;
13783 switch (state.pipesCount) {
13785 state.pipes = dest;
13788 state.pipes = [state.pipes, dest];
13791 state.pipes.push(dest);
13794 state.pipesCount += 1;
13795 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
13797 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
13799 var endFn = doEnd ? onend : cleanup;
13800 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
13802 dest.on('unpipe', onunpipe);
13803 function onunpipe(readable) {
13805 if (readable === src) {
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
13819 var ondrain = pipeOnDrain(src);
13820 dest.on('drain', ondrain);
13822 var cleanedUp = false;
13823 function 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);
13837 // if the reader is waiting for a drain event from this
13838 // specific writer, then it would cause it to never start
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();
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) {
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;
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);
13874 dest.removeListener('error', onerror);
13875 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
13878 // Make sure our error handler is attached before userland ones.
13879 prependListener(dest, 'error', onerror);
13881 // Both close and finish should trigger unpipe, but only once.
13882 function onclose() {
13883 dest.removeListener('finish', onfinish);
13886 dest.once('close', onclose);
13887 function onfinish() {
13889 dest.removeListener('close', onclose);
13892 dest.once('finish', onfinish);
13894 function unpipe() {
13899 // tell the dest that it's being piped to
13900 dest.emit('pipe', src);
13902 // start the flow if it hasn't been started already.
13903 if (!state.flowing) {
13904 debug('pipe resume');
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;
13923 Readable.prototype.unpipe = function (dest) {
13924 var state = this._readableState;
13926 // if we're not piping anywhere, then do nothing.
13927 if (state.pipesCount === 0) return this;
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;
13934 if (!dest) dest = state.pipes;
13937 state.pipes = null;
13938 state.pipesCount = 0;
13939 state.flowing = false;
13940 if (dest) dest.emit('unpipe', this);
13944 // slow case. multiple pipe destinations.
13948 var dests = state.pipes;
13949 var len = state.pipesCount;
13950 state.pipes = null;
13951 state.pipesCount = 0;
13952 state.flowing = false;
13954 for (var i = 0; i < len; i++) {
13955 dests[i].emit('unpipe', this);
13959 // try to find the right one.
13960 var index = indexOf(state.pipes, dest);
13961 if (index === -1) return this;
13963 state.pipes.splice(index, 1);
13964 state.pipesCount -= 1;
13965 if (state.pipesCount === 1) state.pipes = state.pipes[0];
13967 dest.emit('unpipe', this);
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);
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);
13995 Readable.prototype.addListener = Readable.prototype.on;
13997 function nReadingNextTick(self) {
13998 debug('readable nexttick read 0');
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) {
14008 state.flowing = true;
14009 resume(this, state);
14014 function resume(stream, state) {
14015 if (!state.resumeScheduled) {
14016 state.resumeScheduled = true;
14017 processNextTick(resume_, stream, state);
14021 function resume_(stream, state) {
14022 if (!state.reading) {
14023 debug('resume read 0');
14027 state.resumeScheduled = false;
14028 state.awaitDrain = 0;
14029 stream.emit('resume');
14031 if (state.flowing && !state.reading) stream.read(0);
14034 Readable.prototype.pause = function () {
14035 debug('call pause flowing=%j', this._readableState.flowing);
14036 if (false !== this._readableState.flowing) {
14038 this._readableState.flowing = false;
14039 this.emit('pause');
14044 function flow(stream) {
14045 var state = stream._readableState;
14046 debug('flow', state.flowing);
14047 while (state.flowing && stream.read() !== null) {}
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;
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);
14068 stream.on('data', function (chunk) {
14069 debug('wrapped data');
14070 if (state.decoder) chunk = state.decoder.write(chunk);
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;
14075 var ret = self.push(chunk);
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);
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]));
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);
14112 // exposed for testing purposes only.
14113 Readable._fromList = fromList;
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;
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();
14129 // read part of list
14130 ret = fromListPartial(n, state.buffer, state.decoder);
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) {
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();
14149 // result spans more than one buffer
14150 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
14155 // Copies a specified amount of characters from the list of buffered data
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) {
14164 while (p = p.next) {
14166 var nb = n > str.length ? str.length : n;
14167 if (nb === str.length) ret += str;else ret += str.slice(0, n);
14170 if (nb === str.length) {
14172 if (p.next) list.head = p.next;else list.head = list.tail = null;
14175 p.data = str.slice(nb);
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);
14193 n -= p.data.length;
14194 while (p = p.next) {
14196 var nb = n > buf.length ? buf.length : n;
14197 buf.copy(ret, ret.length - n, 0, nb);
14200 if (nb === buf.length) {
14202 if (p.next) list.head = p.next;else list.head = list.tail = null;
14205 p.data = buf.slice(nb);
14215 function endReadable(stream) {
14216 var state = stream._readableState;
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');
14222 if (!state.endEmitted) {
14223 state.ended = true;
14224 processNextTick(endReadableNT, state, stream);
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');
14237 function forEach(xs, f) {
14238 for (var i = 0, l = xs.length; i < l; i++) {
14243 function indexOf(xs, x) {
14244 for (var i = 0, l = xs.length; i < l; i++) {
14245 if (xs[i] === x) return i;
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.)
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.
14262 // Here's how this works:
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.
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.
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.
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.
14295 module.exports = Transform;
14297 var Duplex = require('./_stream_duplex');
14300 var util = require('core-util-is');
14301 util.inherits = require('inherits');
14304 util.inherits(Transform, Duplex);
14306 function TransformState(stream) {
14307 this.afterTransform = function (er, data) {
14308 return afterTransform(stream, er, data);
14311 this.needTransform = false;
14312 this.transforming = false;
14313 this.writecb = null;
14314 this.writechunk = null;
14315 this.writeencoding = null;
14318 function afterTransform(stream, er, data) {
14319 var ts = stream._transformState;
14320 ts.transforming = false;
14322 var cb = ts.writecb;
14324 if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
14326 ts.writechunk = null;
14329 if (data !== null && data !== undefined) stream.push(data);
14333 var rs = stream._readableState;
14334 rs.reading = false;
14335 if (rs.needReadable || rs.length < rs.highWaterMark) {
14336 stream._read(rs.highWaterMark);
14340 function Transform(options) {
14341 if (!(this instanceof Transform)) return new Transform(options);
14343 Duplex.call(this, options);
14345 this._transformState = new TransformState(this);
14349 // start out asking for a readable event once data is transformed.
14350 this._readableState.needReadable = true;
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;
14358 if (typeof options.transform === 'function') this._transform = options.transform;
14360 if (typeof options.flush === 'function') this._flush = options.flush;
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);
14371 Transform.prototype.push = function (chunk, encoding) {
14372 this._transformState.needTransform = false;
14373 return Duplex.prototype.push.call(this, chunk, encoding);
14376 // This is the part where you do stuff!
14377 // override this function in implementation classes.
14378 // 'chunk' is an input chunk.
14380 // Call `push(newChunk)` to pass along transformed output
14381 // to the readable side. You may call 'push' zero or more times.
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');
14390 Transform.prototype._write = function (chunk, encoding, cb) {
14391 var ts = this._transformState;
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);
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;
14407 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
14408 ts.transforming = true;
14409 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
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;
14417 function done(stream, er, data) {
14418 if (er) return stream.emit('error', er);
14420 if (data !== null && data !== undefined) stream.push(data);
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;
14427 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
14429 if (ts.transforming) throw new Error('Calling transform done when still transforming');
14431 return stream.push(null);
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.
14441 module.exports = Writable;
14444 var processNextTick = require('process-nextick-args');
14448 var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
14455 Writable.WritableState = WritableState;
14458 var util = require('core-util-is');
14459 util.inherits = require('inherits');
14463 var internalUtil = {
14464 deprecate: require('util-deprecate')
14469 var Stream = require('./internal/streams/stream');
14472 var Buffer = require('buffer').Buffer;
14474 var bufferShim = require('buffer-shims');
14477 util.inherits(Writable, Stream);
14481 function WriteReq(chunk, encoding, cb) {
14482 this.chunk = chunk;
14483 this.encoding = encoding;
14484 this.callback = cb;
14488 function WritableState(options, stream) {
14489 Duplex = Duplex || require('./_stream_duplex');
14491 options = options || {};
14493 // object stream flag to indicate whether or not this stream
14494 // contains buffers or objects.
14495 this.objectMode = !!options.objectMode;
14497 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
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;
14507 this.highWaterMark = ~~this.highWaterMark;
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;
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;
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';
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
14534 // a flag to see when we're in the middle of a write.
14535 this.writing = false;
14537 // when true all writes will be buffered until .uncork() call
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.
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;
14551 // the callback that's passed to _write(chunk,cb)
14552 this.onwrite = function (er) {
14553 onwrite(stream, er);
14556 // the callback that the user supplies to write(chunk,encoding,cb)
14557 this.writecb = null;
14559 // the amount that is being written when _write is called.
14562 this.bufferedRequest = null;
14563 this.lastBufferedRequest = null;
14565 // number of pending user-supplied write callbacks
14566 // this must be 0 before 'finish' can be emitted
14567 this.pendingcb = 0;
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;
14573 // True if the error was already emitted and should not be thrown again
14574 this.errorEmitted = false;
14576 // count buffered requests
14577 this.bufferedRequestCount = 0;
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);
14584 WritableState.prototype.getBuffer = function getBuffer() {
14585 var current = this.bufferedRequest;
14589 current = current.next;
14596 Object.defineProperty(WritableState.prototype, 'buffer', {
14597 get: internalUtil.deprecate(function () {
14598 return this.getBuffer();
14599 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
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;
14613 return object && object._writableState instanceof WritableState;
14617 realHasInstance = function (object) {
14618 return object instanceof this;
14622 function Writable(options) {
14623 Duplex = Duplex || require('./_stream_duplex');
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.
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);
14636 this._writableState = new WritableState(options, this);
14639 this.writable = true;
14642 if (typeof options.write === 'function') this._write = options.write;
14644 if (typeof options.writev === 'function') this._writev = options.writev;
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'));
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);
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) {
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');
14675 stream.emit('error', er);
14676 processNextTick(cb, er);
14682 Writable.prototype.write = function (chunk, encoding, cb) {
14683 var state = this._writableState;
14685 var isBuf = Buffer.isBuffer(chunk);
14687 if (typeof encoding === 'function') {
14692 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
14694 if (typeof cb !== 'function') cb = nop;
14696 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
14698 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
14704 Writable.prototype.cork = function () {
14705 var state = this._writableState;
14710 Writable.prototype.uncork = function () {
14711 var state = this._writableState;
14713 if (state.corked) {
14716 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
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;
14728 function decodeChunk(state, chunk, encoding) {
14729 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
14730 chunk = bufferShim.from(chunk, encoding);
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) {
14740 chunk = decodeChunk(state, chunk, encoding);
14741 if (Buffer.isBuffer(chunk)) encoding = 'buffer';
14743 var len = state.objectMode ? 1 : chunk.length;
14745 state.length += len;
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;
14751 if (state.writing || state.corked) {
14752 var last = state.lastBufferedRequest;
14753 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
14755 last.next = state.lastBufferedRequest;
14757 state.bufferedRequest = state.lastBufferedRequest;
14759 state.bufferedRequestCount += 1;
14761 doWrite(stream, state, false, len, chunk, encoding, cb);
14767 function doWrite(stream, state, writev, len, chunk, encoding, cb) {
14768 state.writelen = len;
14769 state.writecb = cb;
14770 state.writing = true;
14772 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
14773 state.sync = false;
14776 function onwriteError(stream, state, sync, er, cb) {
14778 if (sync) processNextTick(cb, er);else cb(er);
14780 stream._writableState.errorEmitted = true;
14781 stream.emit('error', er);
14784 function onwriteStateUpdate(state) {
14785 state.writing = false;
14786 state.writecb = null;
14787 state.length -= state.writelen;
14788 state.writelen = 0;
14791 function onwrite(stream, er) {
14792 var state = stream._writableState;
14793 var sync = state.sync;
14794 var cb = state.writecb;
14796 onwriteStateUpdate(state);
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);
14802 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
14803 clearBuffer(stream, state);
14808 asyncWrite(afterWrite, stream, state, finished, cb);
14811 afterWrite(stream, state, finished, cb);
14816 function afterWrite(stream, state, finished, cb) {
14817 if (!finished) onwriteDrain(stream, state);
14820 finishMaybe(stream, state);
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');
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;
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;
14847 buffer[count] = entry;
14848 entry = entry.next;
14852 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
14854 // doWrite is almost always async, defer these to save a bit of time
14855 // as the hot path ends with doWrite
14857 state.lastBufferedRequest = null;
14859 state.corkedRequestsFree = holder.next;
14860 holder.next = null;
14862 state.corkedRequestsFree = new CorkedRequest(state);
14865 // Slow case, write chunks one-by-one
14867 var chunk = entry.chunk;
14868 var encoding = entry.encoding;
14869 var cb = entry.callback;
14870 var len = state.objectMode ? 1 : chunk.length;
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) {
14883 if (entry === null) state.lastBufferedRequest = null;
14886 state.bufferedRequestCount = 0;
14887 state.bufferedRequest = entry;
14888 state.bufferProcessing = false;
14891 Writable.prototype._write = function (chunk, encoding, cb) {
14892 cb(new Error('_write() is not implemented'));
14895 Writable.prototype._writev = null;
14897 Writable.prototype.end = function (chunk, encoding, cb) {
14898 var state = this._writableState;
14900 if (typeof chunk === 'function') {
14904 } else if (typeof encoding === 'function') {
14909 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
14911 // .end() fully uncorks
14912 if (state.corked) {
14917 // ignore unnecessary end() calls.
14918 if (!state.ending && !state.finished) endWritable(this, state, cb);
14921 function needFinish(state) {
14922 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
14925 function prefinish(stream, state) {
14926 if (!state.prefinished) {
14927 state.prefinished = true;
14928 stream.emit('prefinish');
14932 function finishMaybe(stream, state) {
14933 var need = needFinish(state);
14935 if (state.pendingcb === 0) {
14936 prefinish(stream, state);
14937 state.finished = true;
14938 stream.emit('finish');
14940 prefinish(stream, state);
14946 function endWritable(stream, state, cb) {
14947 state.ending = true;
14948 finishMaybe(stream, state);
14950 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
14952 state.ended = true;
14953 stream.writable = false;
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) {
14963 this.finish = function (err) {
14964 var entry = _this.entry;
14965 _this.entry = null;
14967 var cb = entry.callback;
14970 entry = entry.next;
14972 if (state.corkedRequestsFree) {
14973 state.corkedRequestsFree.next = _this;
14975 state.corkedRequestsFree = _this;
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){
14983 var Buffer = require('buffer').Buffer;
14985 var bufferShim = require('buffer-shims');
14988 module.exports = BufferList;
14990 function BufferList() {
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;
15003 BufferList.prototype.unshift = function (v) {
15004 var entry = { data: v, next: this.head };
15005 if (this.length === 0) this.tail = entry;
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;
15018 BufferList.prototype.clear = function () {
15019 this.head = this.tail = null;
15023 BufferList.prototype.join = function (s) {
15024 if (this.length === 0) return '';
15026 var ret = '' + p.data;
15027 while (p = p.next) {
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);
15039 p.data.copy(ret, i);
15040 i += p.data.length;
15045 },{"buffer":32,"buffer-shims":31}],59:[function(require,module,exports){
15046 module.exports = require('events').EventEmitter;
15048 },{"events":34}],60:[function(require,module,exports){
15049 module.exports = require('./readable').PassThrough
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');
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
15063 },{"./readable":61}],63:[function(require,module,exports){
15064 module.exports = require('./lib/_stream_writable.js');
15066 },{"./lib/_stream_writable.js":57}],64:[function(require,module,exports){
15067 // Copyright Joyent, Inc. and other Node contributors.
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:
15077 // The above copyright notice and this permission notice shall be included
15078 // in all copies or substantial portions of the Software.
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.
15088 module.exports = Stream;
15090 var EE = require('events').EventEmitter;
15091 var inherits = require('inherits');
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');
15100 // Backwards-compat with node 0.4.x
15101 Stream.Stream = Stream;
15105 // old-style streams. Note that the pipe method (the only relevant
15106 // part of this class) is overridden in the Readable class.
15108 function Stream() {
15112 Stream.prototype.pipe = function(dest, options) {
15115 function ondata(chunk) {
15116 if (dest.writable) {
15117 if (false === dest.write(chunk) && source.pause) {
15123 source.on('data', ondata);
15125 function ondrain() {
15126 if (source.readable && source.resume) {
15131 dest.on('drain', ondrain);
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);
15140 var didOnEnd = false;
15142 if (didOnEnd) return;
15149 function onclose() {
15150 if (didOnEnd) return;
15153 if (typeof dest.destroy === 'function') dest.destroy();
15156 // don't leave dangling pipes when there are errors.
15157 function onerror(er) {
15159 if (EE.listenerCount(this, 'error') === 0) {
15160 throw er; // Unhandled stream error in pipe.
15164 source.on('error', onerror);
15165 dest.on('error', onerror);
15167 // remove all the event listeners that were added.
15168 function cleanup() {
15169 source.removeListener('data', ondata);
15170 dest.removeListener('drain', ondrain);
15172 source.removeListener('end', onend);
15173 source.removeListener('close', onclose);
15175 source.removeListener('error', onerror);
15176 dest.removeListener('error', onerror);
15178 source.removeListener('end', cleanup);
15179 source.removeListener('close', cleanup);
15181 dest.removeListener('close', cleanup);
15184 source.on('end', cleanup);
15185 source.on('close', cleanup);
15187 dest.on('close', cleanup);
15189 dest.emit('pipe', source);
15191 // Allow for unix-like usage: A.pipe(B).pipe(C)
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){
15198 var Buffer = require('buffer').Buffer;
15199 var bufferShim = require('buffer-shims');
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':
15211 function _normalizeEncoding(enc) {
15212 if (!enc) return 'utf8';
15232 if (retried) return; // undefined
15233 enc = ('' + enc).toLowerCase();
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;
15247 // StringDecoder provides an interface for efficiently splitting a series of
15248 // buffers into a series of JS strings without breaking apart multi-byte
15250 exports.StringDecoder = StringDecoder;
15251 function StringDecoder(encoding) {
15252 this.encoding = normalizeEncoding(encoding);
15254 switch (this.encoding) {
15256 this.text = utf16Text;
15257 this.end = utf16End;
15261 this.fillLast = utf8FillLast;
15265 this.text = base64Text;
15266 this.end = base64End;
15270 this.write = simpleWrite;
15271 this.end = simpleEnd;
15275 this.lastTotal = 0;
15276 this.lastChar = bufferShim.allocUnsafe(nb);
15279 StringDecoder.prototype.write = function (buf) {
15280 if (buf.length === 0) return '';
15283 if (this.lastNeed) {
15284 r = this.fillLast(buf);
15285 if (r === undefined) return '';
15291 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
15295 StringDecoder.prototype.end = utf8End;
15297 // Returns only complete characters in a Buffer
15298 StringDecoder.prototype.text = utf8Text;
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);
15306 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
15307 this.lastNeed -= buf.length;
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;
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]);
15325 if (nb > 0) self.lastNeed = nb - 1;
15328 if (--j < i) return 0;
15329 nb = utf8CheckByte(buf[j]);
15331 if (nb > 0) self.lastNeed = nb - 2;
15334 if (--j < i) return 0;
15335 nb = utf8CheckByte(buf[j]);
15338 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
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
15353 function utf8CheckExtraBytes(self, buf, p) {
15354 if ((buf[0] & 0xC0) !== 0x80) {
15356 return '\ufffd'.repeat(p);
15358 if (self.lastNeed > 1 && buf.length > 1) {
15359 if ((buf[1] & 0xC0) !== 0x80) {
15361 return '\ufffd'.repeat(p + 1);
15363 if (self.lastNeed > 2 && buf.length > 2) {
15364 if ((buf[2] & 0xC0) !== 0x80) {
15366 return '\ufffd'.repeat(p + 2);
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);
15381 buf.copy(this.lastChar, p, 0, buf.length);
15382 this.lastNeed -= buf.length;
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);
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);
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);
15413 var c = r.charCodeAt(r.length - 1);
15414 if (c >= 0xD800 && c <= 0xDBFF) {
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);
15425 this.lastTotal = 2;
15426 this.lastChar[0] = buf[buf.length - 1];
15427 return buf.toString('utf16le', i, buf.length - 1);
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);
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;
15447 this.lastChar[0] = buf[buf.length - 1];
15449 this.lastChar[0] = buf[buf.length - 2];
15450 this.lastChar[1] = buf[buf.length - 1];
15452 return buf.toString('base64', i, buf.length - n);
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);
15461 // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
15462 function simpleWrite(buf) {
15463 return buf.toString(this.encoding);
15466 function simpleEnd(buf) {
15467 return buf && buf.length ? this.write(buf) : '';
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;
15477 // DOM APIs, for completeness
15479 exports.setTimeout = function() {
15480 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
15482 exports.setInterval = function() {
15483 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
15485 exports.clearTimeout =
15486 exports.clearInterval = function(timeout) { timeout.close(); };
15488 function Timeout(id, clearFn) {
15490 this._clearFn = clearFn;
15492 Timeout.prototype.unref = Timeout.prototype.ref = function() {};
15493 Timeout.prototype.close = function() {
15494 this._clearFn.call(window, this._id);
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;
15503 exports.unenroll = function(item) {
15504 clearTimeout(item._idleTimeoutId);
15505 item._idleTimeout = -1;
15508 exports._unrefActive = exports.active = function(item) {
15509 clearTimeout(item._idleTimeoutId);
15511 var msecs = item._idleTimeout;
15513 item._idleTimeoutId = setTimeout(function onTimeout() {
15514 if (item._onTimeout)
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);
15525 immediateIds[id] = true;
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
15532 fn.apply(null, args);
15536 // Prevent ids from leaking
15537 exports.clearImmediate(id);
15544 exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
15545 delete immediateIds[id];
15547 }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
15548 },{"process/browser.js":51,"timers":66}],67:[function(require,module,exports){
15549 (function (global){
15555 module.exports = deprecate;
15558 * Mark that a method should not be used.
15559 * Returns a modified function which warns once by default.
15561 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
15563 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
15564 * will throw an Error when invoked.
15566 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
15567 * will invoke `console.trace()` instead of `console.error()`.
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`
15575 function deprecate (fn, msg) {
15576 if (config('noDeprecation')) {
15580 var warned = false;
15581 function deprecated() {
15583 if (config('throwDeprecation')) {
15584 throw new Error(msg);
15585 } else if (config('traceDeprecation')) {
15586 console.trace(msg);
15592 return fn.apply(this, arguments);
15599 * Checks `localStorage` for boolean values for the given `name`.
15601 * @param {String} name
15602 * @returns {Boolean}
15606 function config (name) {
15607 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
15609 if (!global.localStorage) return false;
15613 var val = global.localStorage[name];
15614 if (null == val) return false;
15615 return String(val).toLowerCase() === 'true';
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)