3 JSZip - A Javascript class for generating and reading zip files
4 <http://stuartk.com/jszip>
6 (c) 2009-2014 Stuart Knightley <stuart [at] stuartk.com>
7 Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
9 JSZip uses the library pako released under the MIT license :
10 https://github.com/nodeca/pako/blob/master/LICENSE
12 !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JSZip=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
15 var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
18 // public method for encoding
19 exports.encode = function(input, utf8) {
21 var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
24 while (i < input.length) {
26 chr1 = input.charCodeAt(i++);
27 chr2 = input.charCodeAt(i++);
28 chr3 = input.charCodeAt(i++);
31 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
32 enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
38 else if (isNaN(chr3)) {
42 output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
49 // public method for decoding
50 exports.decode = function(input, utf8) {
53 var enc1, enc2, enc3, enc4;
56 input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
58 while (i < input.length) {
60 enc1 = _keyStr.indexOf(input.charAt(i++));
61 enc2 = _keyStr.indexOf(input.charAt(i++));
62 enc3 = _keyStr.indexOf(input.charAt(i++));
63 enc4 = _keyStr.indexOf(input.charAt(i++));
65 chr1 = (enc1 << 2) | (enc2 >> 4);
66 chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
67 chr3 = ((enc3 & 3) << 6) | enc4;
69 output = output + String.fromCharCode(chr1);
72 output = output + String.fromCharCode(chr2);
75 output = output + String.fromCharCode(chr3);
84 },{}],2:[function(_dereq_,module,exports){
86 function CompressedObject() {
87 this.compressedSize = 0;
88 this.uncompressedSize = 0;
90 this.compressionMethod = null;
91 this.compressedContent = null;
94 CompressedObject.prototype = {
96 * Return the decompressed content in an unspecified format.
97 * The format will depend on the decompressor.
98 * @return {Object} the decompressed content.
100 getContent: function() {
101 return null; // see implementation
104 * Return the compressed content in an unspecified format.
105 * The format will depend on the compressed conten source.
106 * @return {Object} the compressed content.
108 getCompressedContent: function() {
109 return null; // see implementation
112 module.exports = CompressedObject;
114 },{}],3:[function(_dereq_,module,exports){
118 compress: function(content, compressionOptions) {
119 return content; // no compression
121 uncompress: function(content) {
122 return content; // no compression
124 compressInputType: null,
125 uncompressInputType: null
127 exports.DEFLATE = _dereq_('./flate');
129 },{"./flate":8}],4:[function(_dereq_,module,exports){
132 var utils = _dereq_('./utils');
135 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
136 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
137 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
138 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
139 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
140 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
141 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
142 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
143 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
144 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
145 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
146 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
147 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
148 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
149 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
150 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
151 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
152 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
153 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
154 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
155 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
156 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
157 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
158 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
159 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
160 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
161 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
162 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
163 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
164 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
165 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
166 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
167 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
168 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
169 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
170 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
171 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
172 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
173 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
174 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
175 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
176 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
177 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
178 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
179 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
180 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
181 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
182 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
183 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
184 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
185 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
186 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
187 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
188 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
189 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
190 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
191 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
192 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
193 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
194 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
195 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
196 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
197 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
198 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
204 * http://www.webtoolkit.info/
207 module.exports = function crc32(input, crc) {
208 if (typeof input === "undefined" || !input.length) {
212 var isArray = utils.getTypeOf(input) !== "string";
214 if (typeof(crc) == "undefined") {
222 for (var i = 0, iTop = input.length; i < iTop; i++) {
223 b = isArray ? input[i] : input.charCodeAt(i);
224 y = (crc ^ b) & 0xFF;
226 crc = (crc >>> 8) ^ x;
231 // vim: set shiftwidth=4 softtabstop=4:
233 },{"./utils":21}],5:[function(_dereq_,module,exports){
235 var utils = _dereq_('./utils');
237 function DataReader(data) {
238 this.data = null; // type : see implementation
242 DataReader.prototype = {
244 * Check that the offset will not go too far.
245 * @param {string} offset the additional offset to check.
246 * @throws {Error} an Error if the offset is out of bounds.
248 checkOffset: function(offset) {
249 this.checkIndex(this.index + offset);
252 * Check that the specifed index will not be too far.
253 * @param {string} newIndex the index to check.
254 * @throws {Error} an Error if the index is out of bounds.
256 checkIndex: function(newIndex) {
257 if (this.length < newIndex || newIndex < 0) {
258 throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
263 * @param {number} newIndex The new index.
264 * @throws {Error} if the new index is out of the data.
266 setIndex: function(newIndex) {
267 this.checkIndex(newIndex);
268 this.index = newIndex;
271 * Skip the next n bytes.
272 * @param {number} n the number of bytes to skip.
273 * @throws {Error} if the new index is out of the data.
276 this.setIndex(this.index + n);
279 * Get the byte at the specified index.
280 * @param {number} i the index to use.
281 * @return {number} a byte.
283 byteAt: function(i) {
284 // see implementations
287 * Get the next number with a given byte size.
288 * @param {number} size the number of bytes to read.
289 * @return {number} the corresponding number.
291 readInt: function(size) {
294 this.checkOffset(size);
295 for (i = this.index + size - 1; i >= this.index; i--) {
296 result = (result << 8) + this.byteAt(i);
302 * Get the next string with a given byte size.
303 * @param {number} size the number of bytes to read.
304 * @return {string} the corresponding string.
306 readString: function(size) {
307 return utils.transformTo("string", this.readData(size));
310 * Get raw data without conversion, <size> bytes.
311 * @param {number} size the number of bytes to read.
312 * @return {Object} the raw data, implementation specific.
314 readData: function(size) {
315 // see implementations
318 * Find the last occurence of a zip signature (4 bytes).
319 * @param {string} sig the signature to find.
320 * @return {number} the index of the last occurence, -1 if not found.
322 lastIndexOfSignature: function(sig) {
323 // see implementations
327 * @return {Date} the date.
329 readDate: function() {
330 var dostime = this.readInt(4);
332 ((dostime >> 25) & 0x7f) + 1980, // year
333 ((dostime >> 21) & 0x0f) - 1, // month
334 (dostime >> 16) & 0x1f, // day
335 (dostime >> 11) & 0x1f, // hour
336 (dostime >> 5) & 0x3f, // minute
337 (dostime & 0x1f) << 1); // second
340 module.exports = DataReader;
342 },{"./utils":21}],6:[function(_dereq_,module,exports){
344 exports.base64 = false;
345 exports.binary = false;
347 exports.createFolders = false;
349 exports.compression = null;
350 exports.compressionOptions = null;
351 exports.comment = null;
352 exports.unixPermissions = null;
353 exports.dosPermissions = null;
355 },{}],7:[function(_dereq_,module,exports){
357 var utils = _dereq_('./utils');
361 * This function will be removed in a future version without replacement.
363 exports.string2binary = function(str) {
364 return utils.string2binary(str);
369 * This function will be removed in a future version without replacement.
371 exports.string2Uint8Array = function(str) {
372 return utils.transformTo("uint8array", str);
377 * This function will be removed in a future version without replacement.
379 exports.uint8Array2String = function(array) {
380 return utils.transformTo("string", array);
385 * This function will be removed in a future version without replacement.
387 exports.string2Blob = function(str) {
388 var buffer = utils.transformTo("arraybuffer", str);
389 return utils.arrayBuffer2Blob(buffer);
394 * This function will be removed in a future version without replacement.
396 exports.arrayBuffer2Blob = function(buffer) {
397 return utils.arrayBuffer2Blob(buffer);
402 * This function will be removed in a future version without replacement.
404 exports.transformTo = function(outputType, input) {
405 return utils.transformTo(outputType, input);
410 * This function will be removed in a future version without replacement.
412 exports.getTypeOf = function(input) {
413 return utils.getTypeOf(input);
418 * This function will be removed in a future version without replacement.
420 exports.checkSupport = function(type) {
421 return utils.checkSupport(type);
426 * This value will be removed in a future version without replacement.
428 exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
432 * This value will be removed in a future version without replacement.
434 exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
439 * This function will be removed in a future version without replacement.
441 exports.pretty = function(str) {
442 return utils.pretty(str);
447 * This function will be removed in a future version without replacement.
449 exports.findCompression = function(compressionMethod) {
450 return utils.findCompression(compressionMethod);
455 * This function will be removed in a future version without replacement.
457 exports.isRegExp = function (object) {
458 return utils.isRegExp(object);
462 },{"./utils":21}],8:[function(_dereq_,module,exports){
464 var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
466 var pako = _dereq_("pako");
467 exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
468 exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
470 exports.magic = "\x08\x00";
471 exports.compress = function(input, compressionOptions) {
472 return pako.deflateRaw(input, {
473 level : compressionOptions.level || -1 // default compression
476 exports.uncompress = function(input) {
477 return pako.inflateRaw(input);
480 },{"pako":24}],9:[function(_dereq_,module,exports){
483 var base64 = _dereq_('./base64');
488 zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
489 zip.folder("images").file("smile.gif", base64Data, {base64: true});
490 zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
491 zip.remove("tempfile");
493 base64zip = zip.generate();
498 * Representation a of zip file in js
500 * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
501 * @param {Object=} options the options for creating this objects (optional).
503 function JSZip(data, options) {
504 // if this constructor is used without `new`, it adds `new` before itself:
505 if(!(this instanceof JSZip)) return new JSZip(data, options);
507 // object containing the files :
509 // "folder/" : {...},
510 // "folder/data.txt" : {...}
516 // Where we are in the hierarchy
519 this.load(data, options);
521 this.clone = function() {
522 var newObj = new JSZip();
523 for (var i in this) {
524 if (typeof this[i] !== "function") {
531 JSZip.prototype = _dereq_('./object');
532 JSZip.prototype.load = _dereq_('./load');
533 JSZip.support = _dereq_('./support');
534 JSZip.defaults = _dereq_('./defaults');
538 * This namespace will be removed in a future version without replacement.
540 JSZip.utils = _dereq_('./deprecatedPublicUtils');
545 * This method will be removed in a future version without replacement.
547 encode : function(input) {
548 return base64.encode(input);
552 * This method will be removed in a future version without replacement.
554 decode : function(input) {
555 return base64.decode(input);
558 JSZip.compressions = _dereq_('./compressions');
559 module.exports = JSZip;
561 },{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(_dereq_,module,exports){
563 var base64 = _dereq_('./base64');
564 var ZipEntries = _dereq_('./zipEntries');
565 module.exports = function(data, options) {
566 var files, zipEntries, i, input;
567 options = options || {};
568 if (options.base64) {
569 data = base64.decode(data);
572 zipEntries = new ZipEntries(data, options);
573 files = zipEntries.files;
574 for (i = 0; i < files.length; i++) {
576 this.file(input.fileName, input.decompressed, {
578 optimizedBinaryString: true,
581 comment : input.fileComment.length ? input.fileComment : null,
582 unixPermissions : input.unixPermissions,
583 dosPermissions : input.dosPermissions,
584 createFolders: options.createFolders
587 if (zipEntries.zipComment.length) {
588 this.comment = zipEntries.zipComment;
594 },{"./base64":1,"./zipEntries":22}],11:[function(_dereq_,module,exports){
597 module.exports = function(data, encoding){
598 return new Buffer(data, encoding);
600 module.exports.test = function(b){
601 return Buffer.isBuffer(b);
604 }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
605 },{}],12:[function(_dereq_,module,exports){
607 var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
609 function NodeBufferReader(data) {
611 this.length = this.data.length;
614 NodeBufferReader.prototype = new Uint8ArrayReader();
617 * @see DataReader.readData
619 NodeBufferReader.prototype.readData = function(size) {
620 this.checkOffset(size);
621 var result = this.data.slice(this.index, this.index + size);
625 module.exports = NodeBufferReader;
627 },{"./uint8ArrayReader":18}],13:[function(_dereq_,module,exports){
629 var support = _dereq_('./support');
630 var utils = _dereq_('./utils');
631 var crc32 = _dereq_('./crc32');
632 var signature = _dereq_('./signature');
633 var defaults = _dereq_('./defaults');
634 var base64 = _dereq_('./base64');
635 var compressions = _dereq_('./compressions');
636 var CompressedObject = _dereq_('./compressedObject');
637 var nodeBuffer = _dereq_('./nodeBuffer');
638 var utf8 = _dereq_('./utf8');
639 var StringWriter = _dereq_('./stringWriter');
640 var Uint8ArrayWriter = _dereq_('./uint8ArrayWriter');
643 * Returns the raw data of a ZipObject, decompress the content if necessary.
644 * @param {ZipObject} file the file to use.
645 * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
647 var getRawData = function(file) {
648 if (file._data instanceof CompressedObject) {
649 file._data = file._data.getContent();
650 file.options.binary = true;
651 file.options.base64 = false;
653 if (utils.getTypeOf(file._data) === "uint8array") {
654 var copy = file._data;
655 // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
656 // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
657 file._data = new Uint8Array(copy.length);
658 // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
659 if (copy.length !== 0) {
660 file._data.set(copy, 0);
668 * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
669 * @param {ZipObject} file the file to use.
670 * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
672 var getBinaryData = function(file) {
673 var result = getRawData(file),
674 type = utils.getTypeOf(result);
675 if (type === "string") {
676 if (!file.options.binary) {
678 // unicode string => binary string is a painful process, check if we can avoid it.
679 if (support.nodebuffer) {
680 return nodeBuffer(result, "utf-8");
683 return file.asBinary();
689 * Transform this._data into a string.
690 * @param {function} filter a function String -> String, applied if not null on the result.
691 * @return {String} the string representing this._data.
693 var dataToString = function(asUTF8) {
694 var result = getRawData(this);
695 if (result === null || typeof result === "undefined") {
698 // if the data is a base64 string, we decode it before checking the encoding !
699 if (this.options.base64) {
700 result = base64.decode(result);
702 if (asUTF8 && this.options.binary) {
703 // JSZip.prototype.utf8decode supports arrays as input
704 // skip to array => string step, utf8decode will do it.
705 result = out.utf8decode(result);
708 // no utf8 transformation, do the array => string step.
709 result = utils.transformTo("string", result);
712 if (!asUTF8 && !this.options.binary) {
713 result = utils.transformTo("string", out.utf8encode(result));
718 * A simple object representing a file in the zip file.
720 * @param {string} name the name of the file
721 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
722 * @param {Object} options the options of the file
724 var ZipObject = function(name, data, options) {
726 this.dir = options.dir;
727 this.date = options.date;
728 this.comment = options.comment;
729 this.unixPermissions = options.unixPermissions;
730 this.dosPermissions = options.dosPermissions;
733 this.options = options;
736 * This object contains initial values for dir and date.
737 * With them, we can check if the user changed the deprecated metadata in
738 * `ZipObject#options` or not.
740 this._initialMetadata = {
746 ZipObject.prototype = {
748 * Return the content as UTF8 string.
749 * @return {string} the UTF8 string.
752 return dataToString.call(this, true);
755 * Returns the binary content.
756 * @return {string} the content as binary.
758 asBinary: function() {
759 return dataToString.call(this, false);
762 * Returns the content as a nodejs Buffer.
763 * @return {Buffer} the content as a Buffer.
765 asNodeBuffer: function() {
766 var result = getBinaryData(this);
767 return utils.transformTo("nodebuffer", result);
770 * Returns the content as an Uint8Array.
771 * @return {Uint8Array} the content as an Uint8Array.
773 asUint8Array: function() {
774 var result = getBinaryData(this);
775 return utils.transformTo("uint8array", result);
778 * Returns the content as an ArrayBuffer.
779 * @return {ArrayBuffer} the content as an ArrayBufer.
781 asArrayBuffer: function() {
782 return this.asUint8Array().buffer;
787 * Transform an integer into a string in hexadecimal.
789 * @param {number} dec the number to convert.
790 * @param {number} bytes the number of bytes to generate.
791 * @returns {string} the result.
793 var decToHex = function(dec, bytes) {
796 for (i = 0; i < bytes; i++) {
797 hex += String.fromCharCode(dec & 0xff);
804 * Merge the objects passed as parameters into a new one.
806 * @param {...Object} var_args All objects to merge.
807 * @return {Object} a new object with the data of the others.
809 var extend = function() {
810 var result = {}, i, attr;
811 for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
812 for (attr in arguments[i]) {
813 if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
814 result[attr] = arguments[i][attr];
822 * Transforms the (incomplete) options from the user into the complete
823 * set of options to create a file.
825 * @param {Object} o the options from the user.
826 * @return {Object} the complete set of options.
828 var prepareFileAttrs = function(o) {
830 if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
833 o = extend(o, defaults);
834 o.date = o.date || new Date();
835 if (o.compression !== null) o.compression = o.compression.toUpperCase();
841 * Add a file in the current folder.
843 * @param {string} name the name of the file
844 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
845 * @param {Object} o the options of the file
846 * @return {Object} the new file.
848 var fileAdd = function(name, data, o) {
849 // be sure sub folders exist
850 var dataType = utils.getTypeOf(data),
853 o = prepareFileAttrs(o);
855 if (typeof o.unixPermissions === "string") {
856 o.unixPermissions = parseInt(o.unixPermissions, 8);
859 // UNX_IFDIR 0040000 see zipinfo.c
860 if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
864 if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
869 name = forceTrailingSlash(name);
872 if (o.createFolders && (parent = parentFolder(name))) {
873 folderAdd.call(this, parent, true);
876 if (o.dir || data === null || typeof data === "undefined") {
882 else if (dataType === "string") {
883 if (o.binary && !o.base64) {
884 // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
885 if (o.optimizedBinaryString !== true) {
886 // this is a string, not in a base64 format.
887 // Be sure that this is a correct "binary string"
888 data = utils.string2binary(data);
892 else { // arraybuffer, uint8array, ...
896 if (!dataType && !(data instanceof CompressedObject)) {
897 throw new Error("The data of '" + name + "' is in an unsupported format !");
900 // special case : it's way easier to work with Uint8Array than with ArrayBuffer
901 if (dataType === "arraybuffer") {
902 data = utils.transformTo("uint8array", data);
906 var object = new ZipObject(name, data, o);
907 this.files[name] = object;
912 * Find the parent folder of the path.
914 * @param {string} path the path to use
915 * @return {string} the parent folder, or ""
917 var parentFolder = function (path) {
918 if (path.slice(-1) == '/') {
919 path = path.substring(0, path.length - 1);
921 var lastSlash = path.lastIndexOf('/');
922 return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
927 * Returns the path with a slash at the end.
929 * @param {String} path the path to check.
930 * @return {String} the path with a trailing slash.
932 var forceTrailingSlash = function(path) {
933 // Check the name ends with a /
934 if (path.slice(-1) != "/") {
935 path += "/"; // IE doesn't like substr(-1)
940 * Add a (sub) folder in the current folder.
942 * @param {string} name the folder's name
943 * @param {boolean=} [createFolders] If true, automatically create sub
944 * folders. Defaults to false.
945 * @return {Object} the new folder.
947 var folderAdd = function(name, createFolders) {
948 createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
950 name = forceTrailingSlash(name);
952 // Does this folder already exist?
953 if (!this.files[name]) {
954 fileAdd.call(this, name, null, {
956 createFolders: createFolders
959 return this.files[name];
963 * Generate a JSZip.CompressedObject for a given zipOject.
964 * @param {ZipObject} file the object to read.
965 * @param {JSZip.compression} compression the compression to use.
966 * @param {Object} compressionOptions the options to use when compressing.
967 * @return {JSZip.CompressedObject} the compressed result.
969 var generateCompressedObjectFrom = function(file, compression, compressionOptions) {
970 var result = new CompressedObject(),
973 // the data has not been decompressed, we might reuse things !
974 if (file._data instanceof CompressedObject) {
975 result.uncompressedSize = file._data.uncompressedSize;
976 result.crc32 = file._data.crc32;
978 if (result.uncompressedSize === 0 || file.dir) {
979 compression = compressions['STORE'];
980 result.compressedContent = "";
983 else if (file._data.compressionMethod === compression.magic) {
984 result.compressedContent = file._data.getCompressedContent();
987 content = file._data.getContent();
988 // need to decompress / recompress
989 result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
993 // have uncompressed data
994 content = getBinaryData(file);
995 if (!content || content.length === 0 || file.dir) {
996 compression = compressions['STORE'];
999 result.uncompressedSize = content.length;
1000 result.crc32 = crc32(content);
1001 result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
1004 result.compressedSize = result.compressedContent.length;
1005 result.compressionMethod = compression.magic;
1014 * Generate the UNIX part of the external file attributes.
1015 * @param {Object} unixPermissions the unix permissions or null.
1016 * @param {Boolean} isDir true if the entry is a directory, false otherwise.
1017 * @return {Number} a 32 bit integer.
1019 * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
1021 * TTTTsstrwxrwxrwx0000000000ADVSHR
1022 * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
1023 * ^^^_________________________ setuid, setgid, sticky
1024 * ^^^^^^^^^________________ permissions
1025 * ^^^^^^^^^^______ not used ?
1026 * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
1028 var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
1030 var result = unixPermissions;
1031 if (!unixPermissions) {
1032 // I can't use octal values in strict mode, hence the hexa.
1034 // 0100664 => 0x81b4
1035 result = isDir ? 0x41fd : 0x81b4;
1038 return (result & 0xFFFF) << 16;
1042 * Generate the DOS part of the external file attributes.
1043 * @param {Object} dosPermissions the dos permissions or null.
1044 * @param {Boolean} isDir true if the entry is a directory, false otherwise.
1045 * @return {Number} a 32 bit integer.
1050 * Bit 3 Volume Label
1054 var generateDosExternalFileAttr = function (dosPermissions, isDir) {
1056 // the dir flag is already set for compatibility
1058 return (dosPermissions || 0) & 0x3F;
1062 * Generate the various parts used in the construction of the final zip file.
1063 * @param {string} name the file name.
1064 * @param {ZipObject} file the file content.
1065 * @param {JSZip.CompressedObject} compressedObject the compressed object.
1066 * @param {number} offset the current offset from the start of the zip file.
1067 * @param {String} platform let's pretend we are this platform (change platform dependents fields)
1068 * @return {object} the zip parts.
1070 var generateZipParts = function(name, file, compressedObject, offset, platform) {
1071 var data = compressedObject.compressedContent,
1072 utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
1073 comment = file.comment || "",
1074 utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
1075 useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
1076 useUTF8ForComment = utfEncodedComment.length !== comment.length,
1081 unicodePathExtraField = "",
1082 unicodeCommentExtraField = "",
1086 // handle the deprecated options.dir
1087 if (file._initialMetadata.dir !== file.dir) {
1093 // handle the deprecated options.date
1094 if(file._initialMetadata.date !== file.date) {
1100 var extFileAttr = 0;
1101 var versionMadeBy = 0;
1103 // dos or unix, we set the dos dir flag
1104 extFileAttr |= 0x00010;
1106 if(platform === "UNIX") {
1107 versionMadeBy = 0x031E; // UNIX, version 3.0
1108 extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
1109 } else { // DOS or other, fallback to DOS
1110 versionMadeBy = 0x0014; // DOS, version 2.0
1111 extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
1115 // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
1116 // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
1117 // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
1119 dosTime = date.getHours();
1120 dosTime = dosTime << 6;
1121 dosTime = dosTime | date.getMinutes();
1122 dosTime = dosTime << 5;
1123 dosTime = dosTime | date.getSeconds() / 2;
1125 dosDate = date.getFullYear() - 1980;
1126 dosDate = dosDate << 4;
1127 dosDate = dosDate | (date.getMonth() + 1);
1128 dosDate = dosDate << 5;
1129 dosDate = dosDate | date.getDate();
1131 if (useUTF8ForFileName) {
1132 // set the unicode path extra field. unzip needs at least one extra
1133 // field to correctly handle unicode path, so using the path is as good
1134 // as any other information. This could improve the situation with
1135 // other archive managers too.
1136 // This field is usually used without the utf8 flag, with a non
1137 // unicode path in the header (winrar, winzip). This helps (a bit)
1138 // with the messy Windows' default compressed folders feature but
1139 // breaks on p7zip which doesn't seek the unicode path extra field.
1140 // So for now, UTF-8 everywhere !
1141 unicodePathExtraField =
1145 decToHex(crc32(utfEncodedFileName), 4) +
1150 // Info-ZIP Unicode Path Extra Field
1153 decToHex(unicodePathExtraField.length, 2) +
1155 unicodePathExtraField;
1158 if(useUTF8ForComment) {
1160 unicodeCommentExtraField =
1164 decToHex(this.crc32(utfEncodedComment), 4) +
1169 // Info-ZIP Unicode Path Extra Field
1172 decToHex(unicodeCommentExtraField.length, 2) +
1174 unicodeCommentExtraField;
1179 // version needed to extract
1180 header += "\x0A\x00";
1181 // general purpose bit flag
1182 // set bit 11 if utf8
1183 header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
1184 // compression method
1185 header += compressedObject.compressionMethod;
1186 // last mod file time
1187 header += decToHex(dosTime, 2);
1188 // last mod file date
1189 header += decToHex(dosDate, 2);
1191 header += decToHex(compressedObject.crc32, 4);
1193 header += decToHex(compressedObject.compressedSize, 4);
1194 // uncompressed size
1195 header += decToHex(compressedObject.uncompressedSize, 4);
1197 header += decToHex(utfEncodedFileName.length, 2);
1198 // extra field length
1199 header += decToHex(extraFields.length, 2);
1202 var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields;
1204 var dirRecord = signature.CENTRAL_FILE_HEADER +
1205 // version made by (00: DOS)
1206 decToHex(versionMadeBy, 2) +
1207 // file header (common to file and central directory)
1209 // file comment length
1210 decToHex(utfEncodedComment.length, 2) +
1211 // disk number start
1213 // internal file attributes TODO
1215 // external file attributes
1216 decToHex(extFileAttr, 4) +
1217 // relative offset of local header
1218 decToHex(offset, 4) +
1220 utfEncodedFileName +
1227 fileRecord: fileRecord,
1228 dirRecord: dirRecord,
1229 compressedObject: compressedObject
1234 // return the actual prototype of JSZip
1237 * Read an existing zip and merge the data in the current JSZip object.
1238 * The implementation is in jszip-load.js, don't forget to include it.
1239 * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
1240 * @param {Object} options Options for loading the stream.
1241 * options.base64 : is the stream in base64 ? default : false
1242 * @return {JSZip} the current JSZip object
1244 load: function(stream, options) {
1245 throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
1249 * Filter nested files/folders with the specified function.
1250 * @param {Function} search the predicate to use :
1251 * function (relativePath, file) {...}
1252 * It takes 2 arguments : the relative path and the file.
1253 * @return {Array} An array of matching elements.
1255 filter: function(search) {
1257 filename, relativePath, file, fileClone;
1258 for (filename in this.files) {
1259 if (!this.files.hasOwnProperty(filename)) {
1262 file = this.files[filename];
1263 // return a new object, don't let the user mess with our internal objects :)
1264 fileClone = new ZipObject(file.name, file._data, extend(file.options));
1265 relativePath = filename.slice(this.root.length, filename.length);
1266 if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
1267 search(relativePath, fileClone)) { // and the file matches the function
1268 result.push(fileClone);
1275 * Add a file to the zip file, or search a file.
1276 * @param {string|RegExp} name The name of the file to add (if data is defined),
1277 * the name of the file to find (if no data) or a regex to match files.
1278 * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
1279 * @param {Object} o File options
1280 * @return {JSZip|Object|Array} this JSZip object (when adding a file),
1281 * a file (when searching by string) or an array of files (when searching by regex).
1283 file: function(name, data, o) {
1284 if (arguments.length === 1) {
1285 if (utils.isRegExp(name)) {
1287 return this.filter(function(relativePath, file) {
1288 return !file.dir && regexp.test(relativePath);
1292 return this.filter(function(relativePath, file) {
1293 return !file.dir && relativePath === name;
1297 else { // more than one argument : we have data !
1298 name = this.root + name;
1299 fileAdd.call(this, name, data, o);
1305 * Add a directory to the zip file, or search.
1306 * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
1307 * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
1309 folder: function(arg) {
1314 if (utils.isRegExp(arg)) {
1315 return this.filter(function(relativePath, file) {
1316 return file.dir && arg.test(relativePath);
1320 // else, name is a new folder
1321 var name = this.root + arg;
1322 var newFolder = folderAdd.call(this, name);
1324 // Allow chaining by returning a new object with this folder as the root
1325 var ret = this.clone();
1326 ret.root = newFolder.name;
1331 * Delete a file, or a directory and all sub-files, from the zip
1332 * @param {string} name the name of the file to delete
1333 * @return {JSZip} this JSZip object
1335 remove: function(name) {
1336 name = this.root + name;
1337 var file = this.files[name];
1339 // Look for any folders
1340 if (name.slice(-1) != "/") {
1343 file = this.files[name];
1346 if (file && !file.dir) {
1348 delete this.files[name];
1350 // maybe a folder, delete recursively
1351 var kids = this.filter(function(relativePath, file) {
1352 return file.name.slice(0, name.length) === name;
1354 for (var i = 0; i < kids.length; i++) {
1355 delete this.files[kids[i].name];
1363 * Generate the complete zip file
1364 * @param {Object} options the options to generate the zip file :
1365 * - base64, (deprecated, use type instead) true to generate base64.
1366 * - compression, "STORE" by default.
1367 * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
1368 * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
1370 generate: function(options) {
1371 options = extend(options || {}, {
1373 compression: "STORE",
1374 compressionOptions : null,
1378 mimeType: 'application/zip'
1381 utils.checkSupport(options.type);
1383 // accept nodejs `process.platform`
1385 options.platform === 'darwin' ||
1386 options.platform === 'freebsd' ||
1387 options.platform === 'linux' ||
1388 options.platform === 'sunos'
1390 options.platform = "UNIX";
1392 if (options.platform === 'win32') {
1393 options.platform = "DOS";
1398 centralDirLength = 0,
1400 utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || ""));
1402 // first, generate all the zip parts.
1403 for (var name in this.files) {
1404 if (!this.files.hasOwnProperty(name)) {
1407 var file = this.files[name];
1409 var compressionName = file.options.compression || options.compression.toUpperCase();
1410 var compression = compressions[compressionName];
1412 throw new Error(compressionName + " is not a valid compression method !");
1414 var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
1416 var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
1418 var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform);
1419 localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
1420 centralDirLength += zipPart.dirRecord.length;
1421 zipData.push(zipPart);
1426 // end of central dir signature
1427 dirEnd = signature.CENTRAL_DIRECTORY_END +
1428 // number of this disk
1430 // number of the disk with the start of the central directory
1432 // total number of entries in the central directory on this disk
1433 decToHex(zipData.length, 2) +
1434 // total number of entries in the central directory
1435 decToHex(zipData.length, 2) +
1436 // size of the central directory 4 bytes
1437 decToHex(centralDirLength, 4) +
1438 // offset of start of central directory with respect to the starting disk number
1439 decToHex(localDirLength, 4) +
1440 // .ZIP file comment length
1441 decToHex(utfEncodedComment.length, 2) +
1442 // .ZIP file comment
1446 // we have all the parts (and the total length)
1447 // time to create a writer !
1448 var typeName = options.type.toLowerCase();
1449 if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
1450 writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
1452 writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
1455 for (i = 0; i < zipData.length; i++) {
1456 writer.append(zipData[i].fileRecord);
1457 writer.append(zipData[i].compressedObject.compressedContent);
1459 for (i = 0; i < zipData.length; i++) {
1460 writer.append(zipData[i].dirRecord);
1463 writer.append(dirEnd);
1465 var zip = writer.finalize();
1469 switch(options.type.toLowerCase()) {
1470 // case "zip is an Uint8Array"
1472 case "arraybuffer" :
1474 return utils.transformTo(options.type.toLowerCase(), zip);
1476 return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
1477 // case "zip is a string"
1479 return (options.base64) ? base64.encode(zip) : zip;
1480 default : // case "string" :
1488 * This method will be removed in a future version without replacement.
1490 crc32: function (input, crc) {
1491 return crc32(input, crc);
1496 * This method will be removed in a future version without replacement.
1498 utf8encode: function (string) {
1499 return utils.transformTo("string", utf8.utf8encode(string));
1504 * This method will be removed in a future version without replacement.
1506 utf8decode: function (input) {
1507 return utf8.utf8decode(input);
1510 module.exports = out;
1512 },{"./base64":1,"./compressedObject":2,"./compressions":3,"./crc32":4,"./defaults":6,"./nodeBuffer":11,"./signature":14,"./stringWriter":16,"./support":17,"./uint8ArrayWriter":19,"./utf8":20,"./utils":21}],14:[function(_dereq_,module,exports){
1514 exports.LOCAL_FILE_HEADER = "PK\x03\x04";
1515 exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
1516 exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
1517 exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
1518 exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
1519 exports.DATA_DESCRIPTOR = "PK\x07\x08";
1521 },{}],15:[function(_dereq_,module,exports){
1523 var DataReader = _dereq_('./dataReader');
1524 var utils = _dereq_('./utils');
1526 function StringReader(data, optimizedBinaryString) {
1528 if (!optimizedBinaryString) {
1529 this.data = utils.string2binary(this.data);
1531 this.length = this.data.length;
1534 StringReader.prototype = new DataReader();
1536 * @see DataReader.byteAt
1538 StringReader.prototype.byteAt = function(i) {
1539 return this.data.charCodeAt(i);
1542 * @see DataReader.lastIndexOfSignature
1544 StringReader.prototype.lastIndexOfSignature = function(sig) {
1545 return this.data.lastIndexOf(sig);
1548 * @see DataReader.readData
1550 StringReader.prototype.readData = function(size) {
1551 this.checkOffset(size);
1552 // this will work because the constructor applied the "& 0xff" mask.
1553 var result = this.data.slice(this.index, this.index + size);
1557 module.exports = StringReader;
1559 },{"./dataReader":5,"./utils":21}],16:[function(_dereq_,module,exports){
1562 var utils = _dereq_('./utils');
1565 * An object to write any content to a string.
1568 var StringWriter = function() {
1571 StringWriter.prototype = {
1573 * Append any content to the current string.
1574 * @param {Object} input the content to add.
1576 append: function(input) {
1577 input = utils.transformTo("string", input);
1578 this.data.push(input);
1581 * Finalize the construction an return the result.
1582 * @return {string} the generated string.
1584 finalize: function() {
1585 return this.data.join("");
1589 module.exports = StringWriter;
1591 },{"./utils":21}],17:[function(_dereq_,module,exports){
1594 exports.base64 = true;
1595 exports.array = true;
1596 exports.string = true;
1597 exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
1598 // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
1599 // Browserify will provide a Buffer implementation for browsers, which is
1600 // an augmented Uint8Array (i.e., can be used as either Buffer or U8).
1601 exports.nodebuffer = typeof Buffer !== "undefined";
1602 // contains true if JSZip can read/generate Uint8Array, false otherwise.
1603 exports.uint8array = typeof Uint8Array !== "undefined";
1605 if (typeof ArrayBuffer === "undefined") {
1606 exports.blob = false;
1609 var buffer = new ArrayBuffer(0);
1611 exports.blob = new Blob([buffer], {
1612 type: "application/zip"
1617 var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
1618 var builder = new Builder();
1619 builder.append(buffer);
1620 exports.blob = builder.getBlob('application/zip').size === 0;
1623 exports.blob = false;
1628 }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
1629 },{}],18:[function(_dereq_,module,exports){
1631 var DataReader = _dereq_('./dataReader');
1633 function Uint8ArrayReader(data) {
1636 this.length = this.data.length;
1640 Uint8ArrayReader.prototype = new DataReader();
1642 * @see DataReader.byteAt
1644 Uint8ArrayReader.prototype.byteAt = function(i) {
1645 return this.data[i];
1648 * @see DataReader.lastIndexOfSignature
1650 Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) {
1651 var sig0 = sig.charCodeAt(0),
1652 sig1 = sig.charCodeAt(1),
1653 sig2 = sig.charCodeAt(2),
1654 sig3 = sig.charCodeAt(3);
1655 for (var i = this.length - 4; i >= 0; --i) {
1656 if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
1664 * @see DataReader.readData
1666 Uint8ArrayReader.prototype.readData = function(size) {
1667 this.checkOffset(size);
1669 // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
1670 return new Uint8Array(0);
1672 var result = this.data.subarray(this.index, this.index + size);
1676 module.exports = Uint8ArrayReader;
1678 },{"./dataReader":5}],19:[function(_dereq_,module,exports){
1681 var utils = _dereq_('./utils');
1684 * An object to write any content to an Uint8Array.
1686 * @param {number} length The length of the array.
1688 var Uint8ArrayWriter = function(length) {
1689 this.data = new Uint8Array(length);
1692 Uint8ArrayWriter.prototype = {
1694 * Append any content to the current array.
1695 * @param {Object} input the content to add.
1697 append: function(input) {
1698 if (input.length !== 0) {
1699 // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
1700 input = utils.transformTo("uint8array", input);
1701 this.data.set(input, this.index);
1702 this.index += input.length;
1706 * Finalize the construction an return the result.
1707 * @return {Uint8Array} the generated array.
1709 finalize: function() {
1714 module.exports = Uint8ArrayWriter;
1716 },{"./utils":21}],20:[function(_dereq_,module,exports){
1719 var utils = _dereq_('./utils');
1720 var support = _dereq_('./support');
1721 var nodeBuffer = _dereq_('./nodeBuffer');
1724 * The following functions come from pako, from pako/lib/utils/strings
1725 * released under the MIT license, see pako https://github.com/nodeca/pako/
1728 // Table with utf8 lengths (calculated by first byte of sequence)
1729 // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
1730 // because max possible codepoint is 0x10ffff
1731 var _utf8len = new Array(256);
1732 for (var i=0; i<256; i++) {
1733 _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
1735 _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
1737 // convert string to array (typed, when possible)
1738 var string2buf = function (str) {
1739 var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
1741 // count binary size
1742 for (m_pos = 0; m_pos < str_len; m_pos++) {
1743 c = str.charCodeAt(m_pos);
1744 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
1745 c2 = str.charCodeAt(m_pos+1);
1746 if ((c2 & 0xfc00) === 0xdc00) {
1747 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
1751 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
1755 if (support.uint8array) {
1756 buf = new Uint8Array(buf_len);
1758 buf = new Array(buf_len);
1762 for (i=0, m_pos = 0; i < buf_len; m_pos++) {
1763 c = str.charCodeAt(m_pos);
1764 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
1765 c2 = str.charCodeAt(m_pos+1);
1766 if ((c2 & 0xfc00) === 0xdc00) {
1767 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
1774 } else if (c < 0x800) {
1776 buf[i++] = 0xC0 | (c >>> 6);
1777 buf[i++] = 0x80 | (c & 0x3f);
1778 } else if (c < 0x10000) {
1780 buf[i++] = 0xE0 | (c >>> 12);
1781 buf[i++] = 0x80 | (c >>> 6 & 0x3f);
1782 buf[i++] = 0x80 | (c & 0x3f);
1785 buf[i++] = 0xf0 | (c >>> 18);
1786 buf[i++] = 0x80 | (c >>> 12 & 0x3f);
1787 buf[i++] = 0x80 | (c >>> 6 & 0x3f);
1788 buf[i++] = 0x80 | (c & 0x3f);
1795 // Calculate max possible position in utf8 buffer,
1796 // that will not break sequence. If that's not possible
1797 // - (very small limits) return max size as is.
1799 // buf[] - utf8 bytes array
1800 // max - length limit (mandatory);
1801 var utf8border = function(buf, max) {
1804 max = max || buf.length;
1805 if (max > buf.length) { max = buf.length; }
1807 // go back from last position, until start of sequence found
1809 while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
1811 // Fuckup - very small and broken sequence,
1812 // return max, because we should return something anyway.
1813 if (pos < 0) { return max; }
1815 // If we came to start of buffer - that means vuffer is too small,
1817 if (pos === 0) { return max; }
1819 return (pos + _utf8len[buf[pos]] > max) ? pos : max;
1822 // convert array to string
1823 var buf2string = function (buf) {
1824 var str, i, out, c, c_len;
1825 var len = buf.length;
1827 // Reserve max possible length (2 words per char)
1828 // NB: by unknown reasons, Array is significantly faster for
1829 // String.fromCharCode.apply than Uint16Array.
1830 var utf16buf = new Array(len*2);
1832 for (out=0, i=0; i<len;) {
1834 // quick process ascii
1835 if (c < 0x80) { utf16buf[out++] = c; continue; }
1837 c_len = _utf8len[c];
1838 // skip 5 & 6 byte codes
1839 if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
1841 // apply mask on first byte
1842 c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
1844 while (c_len > 1 && i < len) {
1845 c = (c << 6) | (buf[i++] & 0x3f);
1849 // terminated by end of string?
1850 if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
1853 utf16buf[out++] = c;
1856 utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
1857 utf16buf[out++] = 0xdc00 | (c & 0x3ff);
1861 // shrinkBuf(utf16buf, out)
1862 if (utf16buf.length !== out) {
1863 if(utf16buf.subarray) {
1864 utf16buf = utf16buf.subarray(0, out);
1866 utf16buf.length = out;
1870 // return String.fromCharCode.apply(null, utf16buf);
1871 return utils.applyFromCharCode(utf16buf);
1875 // That's all for the pako functions.
1879 * Transform a javascript string into an array (typed if possible) of bytes,
1881 * @param {String} str the string to encode
1882 * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
1884 exports.utf8encode = function utf8encode(str) {
1885 if (support.nodebuffer) {
1886 return nodeBuffer(str, "utf-8");
1889 return string2buf(str);
1894 * Transform a bytes array (or a representation) representing an UTF-8 encoded
1895 * string into a javascript string.
1896 * @param {Array|Uint8Array|Buffer} buf the data de decode
1897 * @return {String} the decoded string.
1899 exports.utf8decode = function utf8decode(buf) {
1900 if (support.nodebuffer) {
1901 return utils.transformTo("nodebuffer", buf).toString("utf-8");
1904 buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
1906 // return buf2string(buf);
1907 // Chrome prefers to work with "small" chunks of data
1908 // for the method buf2string.
1909 // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
1910 var result = [], k = 0, len = buf.length, chunk = 65536;
1912 var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
1913 if (support.uint8array) {
1914 result.push(buf2string(buf.subarray(k, nextBoundary)));
1916 result.push(buf2string(buf.slice(k, nextBoundary)));
1920 return result.join("");
1923 // vim: set shiftwidth=4 softtabstop=4:
1925 },{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(_dereq_,module,exports){
1927 var support = _dereq_('./support');
1928 var compressions = _dereq_('./compressions');
1929 var nodeBuffer = _dereq_('./nodeBuffer');
1931 * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
1932 * @param {string} str the string to transform.
1933 * @return {String} the binary string.
1935 exports.string2binary = function(str) {
1937 for (var i = 0; i < str.length; i++) {
1938 result += String.fromCharCode(str.charCodeAt(i) & 0xff);
1942 exports.arrayBuffer2Blob = function(buffer, mimeType) {
1943 exports.checkSupport("blob");
1944 mimeType = mimeType || 'application/zip';
1948 return new Blob([buffer], {
1955 // deprecated, browser only, old way
1956 var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
1957 var builder = new Builder();
1958 builder.append(buffer);
1959 return builder.getBlob(mimeType);
1964 throw new Error("Bug : can't construct the Blob.");
1971 * The identity function.
1972 * @param {Object} input the input.
1973 * @return {Object} the same input.
1975 function identity(input) {
1980 * Fill in an array with a string.
1981 * @param {String} str the string to use.
1982 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
1983 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
1985 function stringToArrayLike(str, array) {
1986 for (var i = 0; i < str.length; ++i) {
1987 array[i] = str.charCodeAt(i) & 0xFF;
1993 * Transform an array-like object to a string.
1994 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
1995 * @return {String} the result.
1997 function arrayLikeToString(array) {
1998 // Performances notes :
1999 // --------------------
2000 // String.fromCharCode.apply(null, array) is the fastest, see
2001 // see http://jsperf.com/converting-a-uint8array-to-a-string/2
2002 // but the stack is limited (and we can get huge arrays !).
2004 // result += String.fromCharCode(array[i]); generate too many strings !
2006 // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
2010 type = exports.getTypeOf(array),
2016 String.fromCharCode.apply(null, new Uint8Array(0));
2019 String.fromCharCode.apply(null, nodeBuffer(0));
2023 canUseApply = false;
2026 // no apply : slow and painful algorithm
2027 // default browser on android 4.*
2030 for(var i = 0; i < array.length;i++) {
2031 resultStr += String.fromCharCode(array[i]);
2035 while (k < len && chunk > 1) {
2037 if (type === "array" || type === "nodebuffer") {
2038 result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
2041 result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
2046 chunk = Math.floor(chunk / 2);
2049 return result.join("");
2052 exports.applyFromCharCode = arrayLikeToString;
2056 * Copy the data from an array-like to an other array-like.
2057 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
2058 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
2059 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
2061 function arrayLikeToArrayLike(arrayFrom, arrayTo) {
2062 for (var i = 0; i < arrayFrom.length; i++) {
2063 arrayTo[i] = arrayFrom[i];
2068 // a matrix containing functions to transform everything into everything.
2072 transform["string"] = {
2074 "array": function(input) {
2075 return stringToArrayLike(input, new Array(input.length));
2077 "arraybuffer": function(input) {
2078 return transform["string"]["uint8array"](input).buffer;
2080 "uint8array": function(input) {
2081 return stringToArrayLike(input, new Uint8Array(input.length));
2083 "nodebuffer": function(input) {
2084 return stringToArrayLike(input, nodeBuffer(input.length));
2089 transform["array"] = {
2090 "string": arrayLikeToString,
2092 "arraybuffer": function(input) {
2093 return (new Uint8Array(input)).buffer;
2095 "uint8array": function(input) {
2096 return new Uint8Array(input);
2098 "nodebuffer": function(input) {
2099 return nodeBuffer(input);
2104 transform["arraybuffer"] = {
2105 "string": function(input) {
2106 return arrayLikeToString(new Uint8Array(input));
2108 "array": function(input) {
2109 return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
2111 "arraybuffer": identity,
2112 "uint8array": function(input) {
2113 return new Uint8Array(input);
2115 "nodebuffer": function(input) {
2116 return nodeBuffer(new Uint8Array(input));
2121 transform["uint8array"] = {
2122 "string": arrayLikeToString,
2123 "array": function(input) {
2124 return arrayLikeToArrayLike(input, new Array(input.length));
2126 "arraybuffer": function(input) {
2127 return input.buffer;
2129 "uint8array": identity,
2130 "nodebuffer": function(input) {
2131 return nodeBuffer(input);
2136 transform["nodebuffer"] = {
2137 "string": arrayLikeToString,
2138 "array": function(input) {
2139 return arrayLikeToArrayLike(input, new Array(input.length));
2141 "arraybuffer": function(input) {
2142 return transform["nodebuffer"]["uint8array"](input).buffer;
2144 "uint8array": function(input) {
2145 return arrayLikeToArrayLike(input, new Uint8Array(input.length));
2147 "nodebuffer": identity
2151 * Transform an input into any type.
2152 * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
2153 * If no output type is specified, the unmodified input will be returned.
2154 * @param {String} outputType the output type.
2155 * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
2156 * @throws {Error} an Error if the browser doesn't support the requested output type.
2158 exports.transformTo = function(outputType, input) {
2160 // undefined, null, etc
2161 // an empty string won't harm.
2167 exports.checkSupport(outputType);
2168 var inputType = exports.getTypeOf(input);
2169 var result = transform[inputType][outputType](input);
2174 * Return the type of the input.
2175 * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
2176 * @param {Object} input the input to identify.
2177 * @return {String} the (lowercase) type of the input.
2179 exports.getTypeOf = function(input) {
2180 if (typeof input === "string") {
2183 if (Object.prototype.toString.call(input) === "[object Array]") {
2186 if (support.nodebuffer && nodeBuffer.test(input)) {
2187 return "nodebuffer";
2189 if (support.uint8array && input instanceof Uint8Array) {
2190 return "uint8array";
2192 if (support.arraybuffer && input instanceof ArrayBuffer) {
2193 return "arraybuffer";
2198 * Throw an exception if the type is not supported.
2199 * @param {String} type the type to check.
2200 * @throws {Error} an Error if the browser doesn't support the requested type.
2202 exports.checkSupport = function(type) {
2203 var supported = support[type.toLowerCase()];
2205 throw new Error(type + " is not supported by this browser");
2208 exports.MAX_VALUE_16BITS = 65535;
2209 exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
2212 * Prettify a string read as binary.
2213 * @param {string} str the string to prettify.
2214 * @return {string} a pretty string.
2216 exports.pretty = function(str) {
2219 for (i = 0; i < (str || "").length; i++) {
2220 code = str.charCodeAt(i);
2221 res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
2227 * Find a compression registered in JSZip.
2228 * @param {string} compressionMethod the method magic to find.
2229 * @return {Object|null} the JSZip compression object, null if none found.
2231 exports.findCompression = function(compressionMethod) {
2232 for (var method in compressions) {
2233 if (!compressions.hasOwnProperty(method)) {
2236 if (compressions[method].magic === compressionMethod) {
2237 return compressions[method];
2243 * Cross-window, cross-Node-context regular expression detection
2244 * @param {Object} object Anything
2245 * @return {Boolean} true if the object is a regular expression,
2248 exports.isRegExp = function (object) {
2249 return Object.prototype.toString.call(object) === "[object RegExp]";
2253 },{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(_dereq_,module,exports){
2255 var StringReader = _dereq_('./stringReader');
2256 var NodeBufferReader = _dereq_('./nodeBufferReader');
2257 var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
2258 var utils = _dereq_('./utils');
2259 var sig = _dereq_('./signature');
2260 var ZipEntry = _dereq_('./zipEntry');
2261 var support = _dereq_('./support');
2262 var jszipProto = _dereq_('./object');
2263 // class ZipEntries {{{
2265 * All the entries in the zip file.
2267 * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
2268 * @param {Object} loadOptions Options for loading the stream.
2270 function ZipEntries(data, loadOptions) {
2272 this.loadOptions = loadOptions;
2277 ZipEntries.prototype = {
2279 * Check that the reader is on the speficied signature.
2280 * @param {string} expectedSignature the expected signature.
2281 * @throws {Error} if it is an other signature.
2283 checkSignature: function(expectedSignature) {
2284 var signature = this.reader.readString(4);
2285 if (signature !== expectedSignature) {
2286 throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
2290 * Read the end of the central directory.
2292 readBlockEndOfCentral: function() {
2293 this.diskNumber = this.reader.readInt(2);
2294 this.diskWithCentralDirStart = this.reader.readInt(2);
2295 this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
2296 this.centralDirRecords = this.reader.readInt(2);
2297 this.centralDirSize = this.reader.readInt(4);
2298 this.centralDirOffset = this.reader.readInt(4);
2300 this.zipCommentLength = this.reader.readInt(2);
2301 // warning : the encoding depends of the system locale
2302 // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
2303 // On a windows machine, this field is encoded with the localized windows code page.
2304 this.zipComment = this.reader.readString(this.zipCommentLength);
2305 // To get consistent behavior with the generation part, we will assume that
2306 // this is utf8 encoded.
2307 this.zipComment = jszipProto.utf8decode(this.zipComment);
2310 * Read the end of the Zip 64 central directory.
2311 * Not merged with the method readEndOfCentral :
2312 * The end of central can coexist with its Zip64 brother,
2313 * I don't want to read the wrong number of bytes !
2315 readBlockZip64EndOfCentral: function() {
2316 this.zip64EndOfCentralSize = this.reader.readInt(8);
2317 this.versionMadeBy = this.reader.readString(2);
2318 this.versionNeeded = this.reader.readInt(2);
2319 this.diskNumber = this.reader.readInt(4);
2320 this.diskWithCentralDirStart = this.reader.readInt(4);
2321 this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
2322 this.centralDirRecords = this.reader.readInt(8);
2323 this.centralDirSize = this.reader.readInt(8);
2324 this.centralDirOffset = this.reader.readInt(8);
2326 this.zip64ExtensibleData = {};
2327 var extraDataSize = this.zip64EndOfCentralSize - 44,
2332 while (index < extraDataSize) {
2333 extraFieldId = this.reader.readInt(2);
2334 extraFieldLength = this.reader.readInt(4);
2335 extraFieldValue = this.reader.readString(extraFieldLength);
2336 this.zip64ExtensibleData[extraFieldId] = {
2338 length: extraFieldLength,
2339 value: extraFieldValue
2344 * Read the end of the Zip 64 central directory locator.
2346 readBlockZip64EndOfCentralLocator: function() {
2347 this.diskWithZip64CentralDirStart = this.reader.readInt(4);
2348 this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
2349 this.disksCount = this.reader.readInt(4);
2350 if (this.disksCount > 1) {
2351 throw new Error("Multi-volumes zip are not supported");
2355 * Read the local files, based on the offset read in the central part.
2357 readLocalFiles: function() {
2359 for (i = 0; i < this.files.length; i++) {
2360 file = this.files[i];
2361 this.reader.setIndex(file.localHeaderOffset);
2362 this.checkSignature(sig.LOCAL_FILE_HEADER);
2363 file.readLocalPart(this.reader);
2365 file.processAttributes();
2369 * Read the central directory.
2371 readCentralDir: function() {
2374 this.reader.setIndex(this.centralDirOffset);
2375 while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
2376 file = new ZipEntry({
2378 }, this.loadOptions);
2379 file.readCentralPart(this.reader);
2380 this.files.push(file);
2384 * Read the end of central directory.
2386 readEndOfCentral: function() {
2387 var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
2388 if (offset === -1) {
2389 // Check if the content is a truncated zip or complete garbage.
2390 // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
2391 // extractible zip for example) but it can give a good hint.
2392 // If an ajax request was used without responseType, we will also
2393 // get unreadable data.
2394 var isGarbage = true;
2396 this.reader.setIndex(0);
2397 this.checkSignature(sig.LOCAL_FILE_HEADER);
2402 throw new Error("Can't find end of central directory : is this a zip file ? " +
2403 "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
2405 throw new Error("Corrupted zip : can't find end of central directory");
2408 this.reader.setIndex(offset);
2409 this.checkSignature(sig.CENTRAL_DIRECTORY_END);
2410 this.readBlockEndOfCentral();
2413 /* extract from the zip spec :
2414 4) If one of the fields in the end of central directory
2415 record is too small to hold required data, the field
2416 should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
2417 ZIP64 format record should be created.
2418 5) The end of central directory record and the
2419 Zip64 end of central directory locator record must
2420 reside on the same disk when splitting or spanning
2423 if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) {
2427 Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
2428 the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
2429 all numbers as 64-bit double precision IEEE 754 floating point numbers.
2430 So, we have 53bits for integers and bitwise operations treat everything as 32bits.
2431 see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
2432 and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
2435 // should look for a zip64 EOCD locator
2436 offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
2437 if (offset === -1) {
2438 throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
2440 this.reader.setIndex(offset);
2441 this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
2442 this.readBlockZip64EndOfCentralLocator();
2444 // now the zip64 EOCD record
2445 this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
2446 this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
2447 this.readBlockZip64EndOfCentral();
2450 prepareReader: function(data) {
2451 var type = utils.getTypeOf(data);
2452 if (type === "string" && !support.uint8array) {
2453 this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
2455 else if (type === "nodebuffer") {
2456 this.reader = new NodeBufferReader(data);
2459 this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
2463 * Read a zip file and create ZipEntries.
2464 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
2466 load: function(data) {
2467 this.prepareReader(data);
2468 this.readEndOfCentral();
2469 this.readCentralDir();
2470 this.readLocalFiles();
2473 // }}} end of ZipEntries
2474 module.exports = ZipEntries;
2476 },{"./nodeBufferReader":12,"./object":13,"./signature":14,"./stringReader":15,"./support":17,"./uint8ArrayReader":18,"./utils":21,"./zipEntry":23}],23:[function(_dereq_,module,exports){
2478 var StringReader = _dereq_('./stringReader');
2479 var utils = _dereq_('./utils');
2480 var CompressedObject = _dereq_('./compressedObject');
2481 var jszipProto = _dereq_('./object');
2483 var MADE_BY_DOS = 0x00;
2484 var MADE_BY_UNIX = 0x03;
2486 // class ZipEntry {{{
2488 * An entry in the zip file.
2490 * @param {Object} options Options of the current file.
2491 * @param {Object} loadOptions Options for loading the stream.
2493 function ZipEntry(options, loadOptions) {
2494 this.options = options;
2495 this.loadOptions = loadOptions;
2497 ZipEntry.prototype = {
2499 * say if the file is encrypted.
2500 * @return {boolean} true if the file is encrypted, false otherwise.
2502 isEncrypted: function() {
2504 return (this.bitFlag & 0x0001) === 0x0001;
2507 * say if the file has utf-8 filename/comment.
2508 * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
2510 useUTF8: function() {
2512 return (this.bitFlag & 0x0800) === 0x0800;
2515 * Prepare the function used to generate the compressed content from this ZipFile.
2516 * @param {DataReader} reader the reader to use.
2517 * @param {number} from the offset from where we should read the data.
2518 * @param {number} length the length of the data to read.
2519 * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
2521 prepareCompressedContent: function(reader, from, length) {
2523 var previousIndex = reader.index;
2524 reader.setIndex(from);
2525 var compressedFileData = reader.readData(length);
2526 reader.setIndex(previousIndex);
2528 return compressedFileData;
2532 * Prepare the function used to generate the uncompressed content from this ZipFile.
2533 * @param {DataReader} reader the reader to use.
2534 * @param {number} from the offset from where we should read the data.
2535 * @param {number} length the length of the data to read.
2536 * @param {JSZip.compression} compression the compression used on this file.
2537 * @param {number} uncompressedSize the uncompressed size to expect.
2538 * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
2540 prepareContent: function(reader, from, length, compression, uncompressedSize) {
2543 var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
2544 var uncompressedFileData = compression.uncompress(compressedFileData);
2546 if (uncompressedFileData.length !== uncompressedSize) {
2547 throw new Error("Bug : uncompressed data size mismatch");
2550 return uncompressedFileData;
2554 * Read the local part of a zip file and add the info in this object.
2555 * @param {DataReader} reader the reader to use.
2557 readLocalPart: function(reader) {
2558 var compression, localExtraFieldsLength;
2560 // we already know everything from the central dir !
2561 // If the central dir data are false, we are doomed.
2562 // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
2563 // The less data we get here, the more reliable this should be.
2564 // Let's skip the whole header and dash to the data !
2566 // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
2567 // Strangely, the filename here is OK.
2568 // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
2569 // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
2570 // Search "unzip mismatching "local" filename continuing with "central" filename version" on
2573 // I think I see the logic here : the central directory is used to display
2574 // content and the local directory is used to extract the files. Mixing / and \
2575 // may be used to display \ to windows users and use / when extracting the files.
2576 // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
2577 this.fileNameLength = reader.readInt(2);
2578 localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
2579 this.fileName = reader.readString(this.fileNameLength);
2580 reader.skip(localExtraFieldsLength);
2582 if (this.compressedSize == -1 || this.uncompressedSize == -1) {
2583 throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
2586 compression = utils.findCompression(this.compressionMethod);
2587 if (compression === null) { // no compression found
2588 throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
2590 this.decompressed = new CompressedObject();
2591 this.decompressed.compressedSize = this.compressedSize;
2592 this.decompressed.uncompressedSize = this.uncompressedSize;
2593 this.decompressed.crc32 = this.crc32;
2594 this.decompressed.compressionMethod = this.compressionMethod;
2595 this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
2596 this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
2598 // we need to compute the crc32...
2599 if (this.loadOptions.checkCRC32) {
2600 this.decompressed = utils.transformTo("string", this.decompressed.getContent());
2601 if (jszipProto.crc32(this.decompressed) !== this.crc32) {
2602 throw new Error("Corrupted zip : CRC32 mismatch");
2608 * Read the central part of a zip file and add the info in this object.
2609 * @param {DataReader} reader the reader to use.
2611 readCentralPart: function(reader) {
2612 this.versionMadeBy = reader.readInt(2);
2613 this.versionNeeded = reader.readInt(2);
2614 this.bitFlag = reader.readInt(2);
2615 this.compressionMethod = reader.readString(2);
2616 this.date = reader.readDate();
2617 this.crc32 = reader.readInt(4);
2618 this.compressedSize = reader.readInt(4);
2619 this.uncompressedSize = reader.readInt(4);
2620 this.fileNameLength = reader.readInt(2);
2621 this.extraFieldsLength = reader.readInt(2);
2622 this.fileCommentLength = reader.readInt(2);
2623 this.diskNumberStart = reader.readInt(2);
2624 this.internalFileAttributes = reader.readInt(2);
2625 this.externalFileAttributes = reader.readInt(4);
2626 this.localHeaderOffset = reader.readInt(4);
2628 if (this.isEncrypted()) {
2629 throw new Error("Encrypted zip are not supported");
2632 this.fileName = reader.readString(this.fileNameLength);
2633 this.readExtraFields(reader);
2634 this.parseZIP64ExtraField(reader);
2635 this.fileComment = reader.readString(this.fileCommentLength);
2639 * Parse the external file attributes and get the unix/dos permissions.
2641 processAttributes: function () {
2642 this.unixPermissions = null;
2643 this.dosPermissions = null;
2644 var madeBy = this.versionMadeBy >> 8;
2646 // Check if we have the DOS directory flag set.
2647 // We look for it in the DOS and UNIX permissions
2648 // but some unknown platform could set it as a compatibility flag.
2649 this.dir = this.externalFileAttributes & 0x0010 ? true : false;
2651 if(madeBy === MADE_BY_DOS) {
2652 // first 6 bits (0 to 5)
2653 this.dosPermissions = this.externalFileAttributes & 0x3F;
2656 if(madeBy === MADE_BY_UNIX) {
2657 this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
2658 // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
2661 // fail safe : if the name ends with a / it probably means a folder
2662 if (!this.dir && this.fileName.slice(-1) === '/') {
2668 * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
2669 * @param {DataReader} reader the reader to use.
2671 parseZIP64ExtraField: function(reader) {
2673 if (!this.extraFields[0x0001]) {
2677 // should be something, preparing the extra reader
2678 var extraReader = new StringReader(this.extraFields[0x0001].value);
2680 // I really hope that these 64bits integer can fit in 32 bits integer, because js
2681 // won't let us have more.
2682 if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
2683 this.uncompressedSize = extraReader.readInt(8);
2685 if (this.compressedSize === utils.MAX_VALUE_32BITS) {
2686 this.compressedSize = extraReader.readInt(8);
2688 if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
2689 this.localHeaderOffset = extraReader.readInt(8);
2691 if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
2692 this.diskNumberStart = extraReader.readInt(4);
2696 * Read the central part of a zip file and add the info in this object.
2697 * @param {DataReader} reader the reader to use.
2699 readExtraFields: function(reader) {
2700 var start = reader.index,
2705 this.extraFields = this.extraFields || {};
2707 while (reader.index < start + this.extraFieldsLength) {
2708 extraFieldId = reader.readInt(2);
2709 extraFieldLength = reader.readInt(2);
2710 extraFieldValue = reader.readString(extraFieldLength);
2712 this.extraFields[extraFieldId] = {
2714 length: extraFieldLength,
2715 value: extraFieldValue
2720 * Apply an UTF8 transformation if needed.
2722 handleUTF8: function() {
2723 if (this.useUTF8()) {
2724 this.fileName = jszipProto.utf8decode(this.fileName);
2725 this.fileComment = jszipProto.utf8decode(this.fileComment);
2727 var upath = this.findExtraFieldUnicodePath();
2728 if (upath !== null) {
2729 this.fileName = upath;
2731 var ucomment = this.findExtraFieldUnicodeComment();
2732 if (ucomment !== null) {
2733 this.fileComment = ucomment;
2739 * Find the unicode path declared in the extra field, if any.
2740 * @return {String} the unicode path, null otherwise.
2742 findExtraFieldUnicodePath: function() {
2743 var upathField = this.extraFields[0x7075];
2745 var extraReader = new StringReader(upathField.value);
2748 if (extraReader.readInt(1) !== 1) {
2752 // the crc of the filename changed, this field is out of date.
2753 if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
2757 return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
2763 * Find the unicode comment declared in the extra field, if any.
2764 * @return {String} the unicode comment, null otherwise.
2766 findExtraFieldUnicodeComment: function() {
2767 var ucommentField = this.extraFields[0x6375];
2768 if (ucommentField) {
2769 var extraReader = new StringReader(ucommentField.value);
2772 if (extraReader.readInt(1) !== 1) {
2776 // the crc of the comment changed, this field is out of date.
2777 if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
2781 return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
2786 module.exports = ZipEntry;
2788 },{"./compressedObject":2,"./object":13,"./stringReader":15,"./utils":21}],24:[function(_dereq_,module,exports){
2789 // Top level file is just a mixin of submodules & constants
2792 var assign = _dereq_('./lib/utils/common').assign;
2794 var deflate = _dereq_('./lib/deflate');
2795 var inflate = _dereq_('./lib/inflate');
2796 var constants = _dereq_('./lib/zlib/constants');
2800 assign(pako, deflate, inflate, constants);
2802 module.exports = pako;
2803 },{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(_dereq_,module,exports){
2807 var zlib_deflate = _dereq_('./zlib/deflate.js');
2808 var utils = _dereq_('./utils/common');
2809 var strings = _dereq_('./utils/strings');
2810 var msg = _dereq_('./zlib/messages');
2811 var zstream = _dereq_('./zlib/zstream');
2814 /* Public constants ==========================================================*/
2815 /* ===========================================================================*/
2821 var Z_STREAM_END = 1;
2823 var Z_DEFAULT_COMPRESSION = -1;
2825 var Z_DEFAULT_STRATEGY = 0;
2829 /* ===========================================================================*/
2835 * Generic JS-style wrapper for zlib calls. If you don't need
2836 * streaming behaviour - use more simple functions: [[deflate]],
2837 * [[deflateRaw]] and [[gzip]].
2841 * Deflate.chunks -> Array
2843 * Chunks of output data, if [[Deflate#onData]] not overriden.
2847 * Deflate.result -> Uint8Array|Array
2849 * Compressed result, generated by default [[Deflate#onData]]
2850 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
2851 * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
2855 * Deflate.err -> Number
2857 * Error code after deflate finished. 0 (Z_OK) on success.
2858 * You will not need it in real life, because deflate errors
2859 * are possible only on wrong options or bad `onData` / `onEnd`
2864 * Deflate.msg -> String
2866 * Error message, if [[Deflate.err]] != 0
2871 * new Deflate(options)
2872 * - options (Object): zlib deflate options.
2874 * Creates new deflator instance with specified params. Throws exception
2875 * on bad params. Supported options:
2882 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
2883 * for more information on these.
2885 * Additional options, for internal needs:
2887 * - `chunkSize` - size of generated data chunks (16K by default)
2888 * - `raw` (Boolean) - do raw deflate
2889 * - `gzip` (Boolean) - create gzip wrapper
2890 * - `to` (String) - if equal to 'string', then result will be "binary string"
2891 * (each char code [0..255])
2892 * - `header` (Object) - custom header for gzip
2893 * - `text` (Boolean) - true if compressed data believed to be text
2894 * - `time` (Number) - modification time, unix timestamp
2895 * - `os` (Number) - operation system code
2896 * - `extra` (Array) - array of bytes with extra data (max 65536)
2897 * - `name` (String) - file name (binary string)
2898 * - `comment` (String) - comment (binary string)
2899 * - `hcrc` (Boolean) - true if header crc should be added
2904 * var pako = require('pako')
2905 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
2906 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
2908 * var deflate = new pako.Deflate({ level: 3});
2910 * deflate.push(chunk1, false);
2911 * deflate.push(chunk2, true); // true -> last chunk
2913 * if (deflate.err) { throw new Error(deflate.err); }
2915 * console.log(deflate.result);
2918 var Deflate = function(options) {
2920 this.options = utils.assign({
2921 level: Z_DEFAULT_COMPRESSION,
2926 strategy: Z_DEFAULT_STRATEGY,
2930 var opt = this.options;
2932 if (opt.raw && (opt.windowBits > 0)) {
2933 opt.windowBits = -opt.windowBits;
2936 else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
2937 opt.windowBits += 16;
2940 this.err = 0; // error code, if happens (0 = Z_OK)
2941 this.msg = ''; // error message
2942 this.ended = false; // used to avoid multiple onEnd() calls
2943 this.chunks = []; // chunks of compressed data
2945 this.strm = new zstream();
2946 this.strm.avail_out = 0;
2948 var status = zlib_deflate.deflateInit2(
2957 if (status !== Z_OK) {
2958 throw new Error(msg[status]);
2962 zlib_deflate.deflateSetHeader(this.strm, opt.header);
2967 * Deflate#push(data[, mode]) -> Boolean
2968 * - data (Uint8Array|Array|String): input data. Strings will be converted to
2969 * utf8 byte sequence.
2970 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
2971 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
2973 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
2974 * new compressed chunks. Returns `true` on success. The last data block must have
2975 * mode Z_FINISH (or `true`). That flush internal pending buffers and call
2976 * [[Deflate#onEnd]].
2978 * On fail call [[Deflate#onEnd]] with error code and return false.
2980 * We strongly recommend to use `Uint8Array` on input for best speed (output
2981 * array format is detected automatically). Also, don't skip last param and always
2982 * use the same type in your code (boolean or number). That will improve JS speed.
2984 * For regular `Array`-s make sure all elements are [0..255].
2989 * push(chunk, false); // push one of data chunks
2991 * push(chunk, true); // push last chunk
2994 Deflate.prototype.push = function(data, mode) {
2995 var strm = this.strm;
2996 var chunkSize = this.options.chunkSize;
2999 if (this.ended) { return false; }
3001 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
3003 // Convert data if needed
3004 if (typeof data === 'string') {
3005 // If we need to compress text, change encoding to utf8.
3006 strm.input = strings.string2buf(data);
3012 strm.avail_in = strm.input.length;
3015 if (strm.avail_out === 0) {
3016 strm.output = new utils.Buf8(chunkSize);
3018 strm.avail_out = chunkSize;
3020 status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
3022 if (status !== Z_STREAM_END && status !== Z_OK) {
3027 if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
3028 if (this.options.to === 'string') {
3029 this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
3031 this.onData(utils.shrinkBuf(strm.output, strm.next_out));
3034 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
3036 // Finalize on the last chunk.
3037 if (_mode === Z_FINISH) {
3038 status = zlib_deflate.deflateEnd(this.strm);
3041 return status === Z_OK;
3049 * Deflate#onData(chunk) -> Void
3050 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
3051 * on js engine support. When string output requested, each chunk
3054 * By default, stores data blocks in `chunks[]` property and glue
3055 * those in `onEnd`. Override this handler, if you need another behaviour.
3057 Deflate.prototype.onData = function(chunk) {
3058 this.chunks.push(chunk);
3063 * Deflate#onEnd(status) -> Void
3064 * - status (Number): deflate status. 0 (Z_OK) on success,
3067 * Called once after you tell deflate that input stream complete
3068 * or error happenned. By default - join collected chunks,
3069 * free memory and fill `results` / `err` properties.
3071 Deflate.prototype.onEnd = function(status) {
3072 // On success - join
3073 if (status === Z_OK) {
3074 if (this.options.to === 'string') {
3075 this.result = this.chunks.join('');
3077 this.result = utils.flattenChunks(this.chunks);
3082 this.msg = this.strm.msg;
3087 * deflate(data[, options]) -> Uint8Array|Array|String
3088 * - data (Uint8Array|Array|String): input data to compress.
3089 * - options (Object): zlib deflate options.
3091 * Compress `data` with deflate alrorythm and `options`.
3093 * Supported options are:
3100 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
3101 * for more information on these.
3105 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
3106 * negative windowBits implicitly.
3107 * - `to` (String) - if equal to 'string', then result will be "binary string"
3108 * (each char code [0..255])
3113 * var pako = require('pako')
3114 * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
3116 * console.log(pako.deflate(data));
3119 function deflate(input, options) {
3120 var deflator = new Deflate(options);
3122 deflator.push(input, true);
3124 // That will never happens, if you don't cheat with options :)
3125 if (deflator.err) { throw deflator.msg; }
3127 return deflator.result;
3132 * deflateRaw(data[, options]) -> Uint8Array|Array|String
3133 * - data (Uint8Array|Array|String): input data to compress.
3134 * - options (Object): zlib deflate options.
3136 * The same as [[deflate]], but creates raw data, without wrapper
3137 * (header and adler32 crc).
3139 function deflateRaw(input, options) {
3140 options = options || {};
3142 return deflate(input, options);
3147 * gzip(data[, options]) -> Uint8Array|Array|String
3148 * - data (Uint8Array|Array|String): input data to compress.
3149 * - options (Object): zlib deflate options.
3151 * The same as [[deflate]], but create gzip wrapper instead of
3154 function gzip(input, options) {
3155 options = options || {};
3156 options.gzip = true;
3157 return deflate(input, options);
3161 exports.Deflate = Deflate;
3162 exports.deflate = deflate;
3163 exports.deflateRaw = deflateRaw;
3164 exports.gzip = gzip;
3165 },{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(_dereq_,module,exports){
3169 var zlib_inflate = _dereq_('./zlib/inflate.js');
3170 var utils = _dereq_('./utils/common');
3171 var strings = _dereq_('./utils/strings');
3172 var c = _dereq_('./zlib/constants');
3173 var msg = _dereq_('./zlib/messages');
3174 var zstream = _dereq_('./zlib/zstream');
3175 var gzheader = _dereq_('./zlib/gzheader');
3181 * Generic JS-style wrapper for zlib calls. If you don't need
3182 * streaming behaviour - use more simple functions: [[inflate]]
3183 * and [[inflateRaw]].
3187 * inflate.chunks -> Array
3189 * Chunks of output data, if [[Inflate#onData]] not overriden.
3193 * Inflate.result -> Uint8Array|Array|String
3195 * Uncompressed result, generated by default [[Inflate#onData]]
3196 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
3197 * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
3201 * Inflate.err -> Number
3203 * Error code after inflate finished. 0 (Z_OK) on success.
3204 * Should be checked if broken data possible.
3208 * Inflate.msg -> String
3210 * Error message, if [[Inflate.err]] != 0
3215 * new Inflate(options)
3216 * - options (Object): zlib inflate options.
3218 * Creates new inflator instance with specified params. Throws exception
3219 * on bad params. Supported options:
3223 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
3224 * for more information on these.
3226 * Additional options, for internal needs:
3228 * - `chunkSize` - size of generated data chunks (16K by default)
3229 * - `raw` (Boolean) - do raw inflate
3230 * - `to` (String) - if equal to 'string', then result will be converted
3231 * from utf8 to utf16 (javascript) string. When string output requested,
3232 * chunk length can differ from `chunkSize`, depending on content.
3234 * By default, when no options set, autodetect deflate/gzip data format via
3240 * var pako = require('pako')
3241 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
3242 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
3244 * var inflate = new pako.Inflate({ level: 3});
3246 * inflate.push(chunk1, false);
3247 * inflate.push(chunk2, true); // true -> last chunk
3249 * if (inflate.err) { throw new Error(inflate.err); }
3251 * console.log(inflate.result);
3254 var Inflate = function(options) {
3256 this.options = utils.assign({
3262 var opt = this.options;
3264 // Force window size for `raw` data, if not set directly,
3265 // because we have no header for autodetect.
3266 if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
3267 opt.windowBits = -opt.windowBits;
3268 if (opt.windowBits === 0) { opt.windowBits = -15; }
3271 // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
3272 if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
3273 !(options && options.windowBits)) {
3274 opt.windowBits += 32;
3277 // Gzip header has no info about windows size, we can do autodetect only
3278 // for deflate. So, if window size not set, force it to max when gzip possible
3279 if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
3280 // bit 3 (16) -> gzipped data
3281 // bit 4 (32) -> autodetect gzip/deflate
3282 if ((opt.windowBits & 15) === 0) {
3283 opt.windowBits |= 15;
3287 this.err = 0; // error code, if happens (0 = Z_OK)
3288 this.msg = ''; // error message
3289 this.ended = false; // used to avoid multiple onEnd() calls
3290 this.chunks = []; // chunks of compressed data
3292 this.strm = new zstream();
3293 this.strm.avail_out = 0;
3295 var status = zlib_inflate.inflateInit2(
3300 if (status !== c.Z_OK) {
3301 throw new Error(msg[status]);
3304 this.header = new gzheader();
3306 zlib_inflate.inflateGetHeader(this.strm, this.header);
3310 * Inflate#push(data[, mode]) -> Boolean
3311 * - data (Uint8Array|Array|String): input data
3312 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
3313 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
3315 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
3316 * new output chunks. Returns `true` on success. The last data block must have
3317 * mode Z_FINISH (or `true`). That flush internal pending buffers and call
3318 * [[Inflate#onEnd]].
3320 * On fail call [[Inflate#onEnd]] with error code and return false.
3322 * We strongly recommend to use `Uint8Array` on input for best speed (output
3323 * format is detected automatically). Also, don't skip last param and always
3324 * use the same type in your code (boolean or number). That will improve JS speed.
3326 * For regular `Array`-s make sure all elements are [0..255].
3331 * push(chunk, false); // push one of data chunks
3333 * push(chunk, true); // push last chunk
3336 Inflate.prototype.push = function(data, mode) {
3337 var strm = this.strm;
3338 var chunkSize = this.options.chunkSize;
3340 var next_out_utf8, tail, utf8str;
3342 if (this.ended) { return false; }
3343 _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
3345 // Convert data if needed
3346 if (typeof data === 'string') {
3347 // Only binary strings can be decompressed on practice
3348 strm.input = strings.binstring2buf(data);
3354 strm.avail_in = strm.input.length;
3357 if (strm.avail_out === 0) {
3358 strm.output = new utils.Buf8(chunkSize);
3360 strm.avail_out = chunkSize;
3363 status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
3365 if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
3371 if (strm.next_out) {
3372 if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
3374 if (this.options.to === 'string') {
3376 next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
3378 tail = strm.next_out - next_out_utf8;
3379 utf8str = strings.buf2string(strm.output, next_out_utf8);
3382 strm.next_out = tail;
3383 strm.avail_out = chunkSize - tail;
3384 if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
3386 this.onData(utf8str);
3389 this.onData(utils.shrinkBuf(strm.output, strm.next_out));
3393 } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
3395 if (status === c.Z_STREAM_END) {
3398 // Finalize on the last chunk.
3399 if (_mode === c.Z_FINISH) {
3400 status = zlib_inflate.inflateEnd(this.strm);
3403 return status === c.Z_OK;
3411 * Inflate#onData(chunk) -> Void
3412 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
3413 * on js engine support. When string output requested, each chunk
3416 * By default, stores data blocks in `chunks[]` property and glue
3417 * those in `onEnd`. Override this handler, if you need another behaviour.
3419 Inflate.prototype.onData = function(chunk) {
3420 this.chunks.push(chunk);
3425 * Inflate#onEnd(status) -> Void
3426 * - status (Number): inflate status. 0 (Z_OK) on success,
3429 * Called once after you tell inflate that input stream complete
3430 * or error happenned. By default - join collected chunks,
3431 * free memory and fill `results` / `err` properties.
3433 Inflate.prototype.onEnd = function(status) {
3434 // On success - join
3435 if (status === c.Z_OK) {
3436 if (this.options.to === 'string') {
3437 // Glue & convert here, until we teach pako to send
3438 // utf8 alligned strings to onData
3439 this.result = this.chunks.join('');
3441 this.result = utils.flattenChunks(this.chunks);
3446 this.msg = this.strm.msg;
3451 * inflate(data[, options]) -> Uint8Array|Array|String
3452 * - data (Uint8Array|Array|String): input data to decompress.
3453 * - options (Object): zlib inflate options.
3455 * Decompress `data` with inflate/ungzip and `options`. Autodetect
3456 * format via wrapper header by default. That's why we don't provide
3457 * separate `ungzip` method.
3459 * Supported options are:
3463 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
3464 * for more information.
3468 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
3469 * negative windowBits implicitly.
3470 * - `to` (String) - if equal to 'string', then result will be converted
3471 * from utf8 to utf16 (javascript) string. When string output requested,
3472 * chunk length can differ from `chunkSize`, depending on content.
3478 * var pako = require('pako')
3479 * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
3483 * output = pako.inflate(input);
3489 function inflate(input, options) {
3490 var inflator = new Inflate(options);
3492 inflator.push(input, true);
3494 // That will never happens, if you don't cheat with options :)
3495 if (inflator.err) { throw inflator.msg; }
3497 return inflator.result;
3502 * inflateRaw(data[, options]) -> Uint8Array|Array|String
3503 * - data (Uint8Array|Array|String): input data to decompress.
3504 * - options (Object): zlib inflate options.
3506 * The same as [[inflate]], but creates raw data, without wrapper
3507 * (header and adler32 crc).
3509 function inflateRaw(input, options) {
3510 options = options || {};
3512 return inflate(input, options);
3517 * ungzip(data[, options]) -> Uint8Array|Array|String
3518 * - data (Uint8Array|Array|String): input data to decompress.
3519 * - options (Object): zlib inflate options.
3521 * Just shortcut to [[inflate]], because it autodetects format
3522 * by header.content. Done for convenience.
3526 exports.Inflate = Inflate;
3527 exports.inflate = inflate;
3528 exports.inflateRaw = inflateRaw;
3529 exports.ungzip = inflate;
3531 },{"./utils/common":27,"./utils/strings":28,"./zlib/constants":30,"./zlib/gzheader":33,"./zlib/inflate.js":35,"./zlib/messages":37,"./zlib/zstream":39}],27:[function(_dereq_,module,exports){
3535 var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
3536 (typeof Uint16Array !== 'undefined') &&
3537 (typeof Int32Array !== 'undefined');
3540 exports.assign = function (obj /*from1, from2, from3, ...*/) {
3541 var sources = Array.prototype.slice.call(arguments, 1);
3542 while (sources.length) {
3543 var source = sources.shift();
3544 if (!source) { continue; }
3546 if (typeof(source) !== 'object') {
3547 throw new TypeError(source + 'must be non-object');
3550 for (var p in source) {
3551 if (source.hasOwnProperty(p)) {
3561 // reduce buffer size, avoiding mem copy
3562 exports.shrinkBuf = function (buf, size) {
3563 if (buf.length === size) { return buf; }
3564 if (buf.subarray) { return buf.subarray(0, size); }
3571 arraySet: function (dest, src, src_offs, len, dest_offs) {
3572 if (src.subarray && dest.subarray) {
3573 dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
3576 // Fallback to ordinary array
3577 for(var i=0; i<len; i++) {
3578 dest[dest_offs + i] = src[src_offs + i];
3581 // Join array of chunks to single array.
3582 flattenChunks: function(chunks) {
3583 var i, l, len, pos, chunk, result;
3585 // calculate data length
3587 for (i=0, l=chunks.length; i<l; i++) {
3588 len += chunks[i].length;
3592 result = new Uint8Array(len);
3594 for (i=0, l=chunks.length; i<l; i++) {
3596 result.set(chunk, pos);
3597 pos += chunk.length;
3605 arraySet: function (dest, src, src_offs, len, dest_offs) {
3606 for(var i=0; i<len; i++) {
3607 dest[dest_offs + i] = src[src_offs + i];
3610 // Join array of chunks to single array.
3611 flattenChunks: function(chunks) {
3612 return [].concat.apply([], chunks);
3617 // Enable/Disable typed arrays use, for testing
3619 exports.setTyped = function (on) {
3621 exports.Buf8 = Uint8Array;
3622 exports.Buf16 = Uint16Array;
3623 exports.Buf32 = Int32Array;
3624 exports.assign(exports, fnTyped);
3626 exports.Buf8 = Array;
3627 exports.Buf16 = Array;
3628 exports.Buf32 = Array;
3629 exports.assign(exports, fnUntyped);
3633 exports.setTyped(TYPED_OK);
3634 },{}],28:[function(_dereq_,module,exports){
3635 // String encode/decode helpers
3639 var utils = _dereq_('./common');
3642 // Quick check if we can use fast array to bin string conversion
3644 // - apply(Array) can fail on Android 2.2
3645 // - apply(Uint8Array) can fail on iOS 5.1 Safary
3647 var STR_APPLY_OK = true;
3648 var STR_APPLY_UIA_OK = true;
3650 try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
3651 try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
3654 // Table with utf8 lengths (calculated by first byte of sequence)
3655 // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
3656 // because max possible codepoint is 0x10ffff
3657 var _utf8len = new utils.Buf8(256);
3658 for (var i=0; i<256; i++) {
3659 _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
3661 _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
3664 // convert string to array (typed, when possible)
3665 exports.string2buf = function (str) {
3666 var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
3668 // count binary size
3669 for (m_pos = 0; m_pos < str_len; m_pos++) {
3670 c = str.charCodeAt(m_pos);
3671 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
3672 c2 = str.charCodeAt(m_pos+1);
3673 if ((c2 & 0xfc00) === 0xdc00) {
3674 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
3678 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
3682 buf = new utils.Buf8(buf_len);
3685 for (i=0, m_pos = 0; i < buf_len; m_pos++) {
3686 c = str.charCodeAt(m_pos);
3687 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
3688 c2 = str.charCodeAt(m_pos+1);
3689 if ((c2 & 0xfc00) === 0xdc00) {
3690 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
3697 } else if (c < 0x800) {
3699 buf[i++] = 0xC0 | (c >>> 6);
3700 buf[i++] = 0x80 | (c & 0x3f);
3701 } else if (c < 0x10000) {
3703 buf[i++] = 0xE0 | (c >>> 12);
3704 buf[i++] = 0x80 | (c >>> 6 & 0x3f);
3705 buf[i++] = 0x80 | (c & 0x3f);
3708 buf[i++] = 0xf0 | (c >>> 18);
3709 buf[i++] = 0x80 | (c >>> 12 & 0x3f);
3710 buf[i++] = 0x80 | (c >>> 6 & 0x3f);
3711 buf[i++] = 0x80 | (c & 0x3f);
3718 // Helper (used in 2 places)
3719 function buf2binstring(buf, len) {
3720 // use fallback for big arrays to avoid stack overflow
3722 if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
3723 return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
3728 for(var i=0; i < len; i++) {
3729 result += String.fromCharCode(buf[i]);
3735 // Convert byte array to binary string
3736 exports.buf2binstring = function(buf) {
3737 return buf2binstring(buf, buf.length);
3741 // Convert binary string (typed, when possible)
3742 exports.binstring2buf = function(str) {
3743 var buf = new utils.Buf8(str.length);
3744 for(var i=0, len=buf.length; i < len; i++) {
3745 buf[i] = str.charCodeAt(i);
3751 // convert array to string
3752 exports.buf2string = function (buf, max) {
3753 var i, out, c, c_len;
3754 var len = max || buf.length;
3756 // Reserve max possible length (2 words per char)
3757 // NB: by unknown reasons, Array is significantly faster for
3758 // String.fromCharCode.apply than Uint16Array.
3759 var utf16buf = new Array(len*2);
3761 for (out=0, i=0; i<len;) {
3763 // quick process ascii
3764 if (c < 0x80) { utf16buf[out++] = c; continue; }
3766 c_len = _utf8len[c];
3767 // skip 5 & 6 byte codes
3768 if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
3770 // apply mask on first byte
3771 c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
3773 while (c_len > 1 && i < len) {
3774 c = (c << 6) | (buf[i++] & 0x3f);
3778 // terminated by end of string?
3779 if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
3782 utf16buf[out++] = c;
3785 utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
3786 utf16buf[out++] = 0xdc00 | (c & 0x3ff);
3790 return buf2binstring(utf16buf, out);
3794 // Calculate max possible position in utf8 buffer,
3795 // that will not break sequence. If that's not possible
3796 // - (very small limits) return max size as is.
3798 // buf[] - utf8 bytes array
3799 // max - length limit (mandatory);
3800 exports.utf8border = function(buf, max) {
3803 max = max || buf.length;
3804 if (max > buf.length) { max = buf.length; }
3806 // go back from last position, until start of sequence found
3808 while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
3810 // Fuckup - very small and broken sequence,
3811 // return max, because we should return something anyway.
3812 if (pos < 0) { return max; }
3814 // If we came to start of buffer - that means vuffer is too small,
3816 if (pos === 0) { return max; }
3818 return (pos + _utf8len[buf[pos]] > max) ? pos : max;
3821 },{"./common":27}],29:[function(_dereq_,module,exports){
3824 // Note: adler32 takes 12% for level 0 and 2% for level 6.
3825 // It doesn't worth to make additional optimizationa as in original.
3826 // Small size is preferable.
3828 function adler32(adler, buf, len, pos) {
3829 var s1 = (adler & 0xffff) |0
3830 , s2 = ((adler >>> 16) & 0xffff) |0
3834 // Set limit ~ twice less than 5552, to keep
3835 // s2 in 31-bits, because we force signed ints.
3836 // in other case %= will fail.
3837 n = len > 2000 ? 2000 : len;
3841 s1 = (s1 + buf[pos++]) |0;
3849 return (s1 | (s2 << 16)) |0;
3853 module.exports = adler32;
3854 },{}],30:[function(_dereq_,module,exports){
3857 /* Allowed flush values; see deflate() and inflate() below for details */
3866 /* Return codes for the compression/decompression functions. Negative values
3867 * are errors, positive values are used for special but normal events.
3877 //Z_VERSION_ERROR: -6,
3879 /* compression levels */
3880 Z_NO_COMPRESSION: 0,
3882 Z_BEST_COMPRESSION: 9,
3883 Z_DEFAULT_COMPRESSION: -1,
3890 Z_DEFAULT_STRATEGY: 0,
3892 /* Possible values of the data_type field (though see inflate()) */
3895 //Z_ASCII: 1, // = Z_TEXT (deprecated)
3898 /* The deflate compression method */
3900 //Z_NULL: null // Use -1 or null inline, depending on var type
3902 },{}],31:[function(_dereq_,module,exports){
3905 // Note: we can't get significant speed boost here.
3906 // So write code to minimize size - no pregenerated tables
3907 // and array tools dependencies.
3910 // Use ordinary array, since untyped makes no boost here
3911 function makeTable() {
3914 for(var n =0; n < 256; n++){
3916 for(var k =0; k < 8; k++){
3917 c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
3925 // Create table on load. Just 255 signed longs. Not a problem.
3926 var crcTable = makeTable();
3929 function crc32(crc, buf, len, pos) {
3935 for (var i = pos; i < end; i++ ) {
3936 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
3939 return (crc ^ (-1)); // >>> 0;
3943 module.exports = crc32;
3944 },{}],32:[function(_dereq_,module,exports){
3947 var utils = _dereq_('../utils/common');
3948 var trees = _dereq_('./trees');
3949 var adler32 = _dereq_('./adler32');
3950 var crc32 = _dereq_('./crc32');
3951 var msg = _dereq_('./messages');
3953 /* Public constants ==========================================================*/
3954 /* ===========================================================================*/
3957 /* Allowed flush values; see deflate() and inflate() below for details */
3959 var Z_PARTIAL_FLUSH = 1;
3960 //var Z_SYNC_FLUSH = 2;
3961 var Z_FULL_FLUSH = 3;
3967 /* Return codes for the compression/decompression functions. Negative values
3968 * are errors, positive values are used for special but normal events.
3971 var Z_STREAM_END = 1;
3972 //var Z_NEED_DICT = 2;
3974 var Z_STREAM_ERROR = -2;
3975 var Z_DATA_ERROR = -3;
3976 //var Z_MEM_ERROR = -4;
3977 var Z_BUF_ERROR = -5;
3978 //var Z_VERSION_ERROR = -6;
3981 /* compression levels */
3982 //var Z_NO_COMPRESSION = 0;
3983 //var Z_BEST_SPEED = 1;
3984 //var Z_BEST_COMPRESSION = 9;
3985 var Z_DEFAULT_COMPRESSION = -1;
3989 var Z_HUFFMAN_ONLY = 2;
3992 var Z_DEFAULT_STRATEGY = 0;
3994 /* Possible values of the data_type field (though see inflate()) */
3997 //var Z_ASCII = 1; // = Z_TEXT
4001 /* The deflate compression method */
4004 /*============================================================================*/
4007 var MAX_MEM_LEVEL = 9;
4008 /* Maximum value for memLevel in deflateInit2 */
4010 /* 32K LZ77 window */
4011 var DEF_MEM_LEVEL = 8;
4014 var LENGTH_CODES = 29;
4015 /* number of length codes, not counting the special END_BLOCK code */
4017 /* number of literal bytes 0..255 */
4018 var L_CODES = LITERALS + 1 + LENGTH_CODES;
4019 /* number of Literal or Length codes, including the END_BLOCK code */
4021 /* number of distance codes */
4023 /* number of codes used to transfer the bit lengths */
4024 var HEAP_SIZE = 2*L_CODES + 1;
4025 /* maximum heap size */
4027 /* All codes must not exceed MAX_BITS bits */
4030 var MAX_MATCH = 258;
4031 var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
4033 var PRESET_DICT = 0x20;
4035 var INIT_STATE = 42;
4036 var EXTRA_STATE = 69;
4037 var NAME_STATE = 73;
4038 var COMMENT_STATE = 91;
4039 var HCRC_STATE = 103;
4040 var BUSY_STATE = 113;
4041 var FINISH_STATE = 666;
4043 var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
4044 var BS_BLOCK_DONE = 2; /* block flush performed */
4045 var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
4046 var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
4048 var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
4050 function err(strm, errorCode) {
4051 strm.msg = msg[errorCode];
4056 return ((f) << 1) - ((f) > 4 ? 9 : 0);
4059 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
4062 /* =========================================================================
4063 * Flush as much pending output as possible. All deflate() output goes
4064 * through this function so some applications may wish to modify it
4065 * to avoid allocating a large strm->output buffer and copying into it.
4066 * (See also read_buf()).
4068 function flush_pending(strm) {
4071 //_tr_flush_bits(s);
4072 var len = s.pending;
4073 if (len > strm.avail_out) {
4074 len = strm.avail_out;
4076 if (len === 0) { return; }
4078 utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
4079 strm.next_out += len;
4080 s.pending_out += len;
4081 strm.total_out += len;
4082 strm.avail_out -= len;
4084 if (s.pending === 0) {
4090 function flush_block_only (s, last) {
4091 trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
4092 s.block_start = s.strstart;
4093 flush_pending(s.strm);
4097 function put_byte(s, b) {
4098 s.pending_buf[s.pending++] = b;
4102 /* =========================================================================
4103 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
4104 * IN assertion: the stream state is correct and there is enough room in
4107 function putShortMSB(s, b) {
4108 // put_byte(s, (Byte)(b >> 8));
4109 // put_byte(s, (Byte)(b & 0xff));
4110 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
4111 s.pending_buf[s.pending++] = b & 0xff;
4115 /* ===========================================================================
4116 * Read a new buffer from the current input stream, update the adler32
4117 * and total number of bytes read. All deflate() input goes through
4118 * this function so some applications may wish to modify it to avoid
4119 * allocating a large strm->input buffer and copying from it.
4120 * (See also flush_pending()).
4122 function read_buf(strm, buf, start, size) {
4123 var len = strm.avail_in;
4125 if (len > size) { len = size; }
4126 if (len === 0) { return 0; }
4128 strm.avail_in -= len;
4130 utils.arraySet(buf, strm.input, strm.next_in, len, start);
4131 if (strm.state.wrap === 1) {
4132 strm.adler = adler32(strm.adler, buf, len, start);
4135 else if (strm.state.wrap === 2) {
4136 strm.adler = crc32(strm.adler, buf, len, start);
4139 strm.next_in += len;
4140 strm.total_in += len;
4146 /* ===========================================================================
4147 * Set match_start to the longest match starting at the given string and
4148 * return its length. Matches shorter or equal to prev_length are discarded,
4149 * in which case the result is equal to prev_length and match_start is
4151 * IN assertions: cur_match is the head of the hash chain for the current
4152 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
4153 * OUT assertion: the match length is not greater than s->lookahead.
4155 function longest_match(s, cur_match) {
4156 var chain_length = s.max_chain_length; /* max hash chain length */
4157 var scan = s.strstart; /* current string */
4158 var match; /* matched string */
4159 var len; /* length of current match */
4160 var best_len = s.prev_length; /* best match length so far */
4161 var nice_match = s.nice_match; /* stop if match long enough */
4162 var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
4163 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
4165 var _win = s.window; // shortcut
4167 var wmask = s.w_mask;
4170 /* Stop when cur_match becomes <= limit. To simplify the code,
4171 * we prevent matches with the string of window index 0.
4174 var strend = s.strstart + MAX_MATCH;
4175 var scan_end1 = _win[scan + best_len - 1];
4176 var scan_end = _win[scan + best_len];
4178 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
4179 * It is easy to get rid of this optimization if necessary.
4181 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
4183 /* Do not waste too much time if we already have a good match: */
4184 if (s.prev_length >= s.good_match) {
4187 /* Do not look for matches beyond the end of the input. This is necessary
4188 * to make deflate deterministic.
4190 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
4192 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
4195 // Assert(cur_match < s->strstart, "no future");
4198 /* Skip to next match if the match length cannot increase
4199 * or if the match length is less than 2. Note that the checks below
4200 * for insufficient lookahead only occur occasionally for performance
4201 * reasons. Therefore uninitialized memory will be accessed, and
4202 * conditional jumps will be made that depend on those values.
4203 * However the length of the match is limited to the lookahead, so
4204 * the output of deflate is not affected by the uninitialized values.
4207 if (_win[match + best_len] !== scan_end ||
4208 _win[match + best_len - 1] !== scan_end1 ||
4209 _win[match] !== _win[scan] ||
4210 _win[++match] !== _win[scan + 1]) {
4214 /* The check at best_len-1 can be removed because it will be made
4215 * again later. (This heuristic is not always a win.)
4216 * It is not necessary to compare scan[2] and match[2] since they
4217 * are always equal when the other bytes match, given that
4218 * the hash keys are equal and that HASH_BITS >= 8.
4222 // Assert(*scan == *match, "match[2]?");
4224 /* We check for insufficient lookahead only every 8th comparison;
4225 * the 256th check will be made at strstart+258.
4228 /*jshint noempty:false*/
4229 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
4230 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
4231 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
4232 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
4235 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
4237 len = MAX_MATCH - (strend - scan);
4238 scan = strend - MAX_MATCH;
4240 if (len > best_len) {
4241 s.match_start = cur_match;
4243 if (len >= nice_match) {
4246 scan_end1 = _win[scan + best_len - 1];
4247 scan_end = _win[scan + best_len];
4249 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
4251 if (best_len <= s.lookahead) {
4258 /* ===========================================================================
4259 * Fill the window when the lookahead becomes insufficient.
4260 * Updates strstart and lookahead.
4262 * IN assertion: lookahead < MIN_LOOKAHEAD
4263 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
4264 * At least one byte has been read, or avail_in == 0; reads are
4265 * performed for at least two bytes (required for the zip translate_eol
4266 * option -- not supported here).
4268 function fill_window(s) {
4269 var _w_size = s.w_size;
4270 var p, n, m, more, str;
4272 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
4275 more = s.window_size - s.lookahead - s.strstart;
4277 // JS ints have 32 bit, block below not needed
4278 /* Deal with !@#$% 64K limit: */
4279 //if (sizeof(int) <= 2) {
4280 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
4283 // } else if (more == (unsigned)(-1)) {
4284 // /* Very unlikely, but possible on 16 bit machine if
4285 // * strstart == 0 && lookahead == 1 (input done a byte at time)
4292 /* If the window is almost full and there is insufficient lookahead,
4293 * move the upper half to the lower one to make room in the upper half.
4295 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
4297 utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
4298 s.match_start -= _w_size;
4299 s.strstart -= _w_size;
4300 /* we now have strstart >= MAX_DIST */
4301 s.block_start -= _w_size;
4303 /* Slide the hash table (could be avoided with 32 bit values
4304 at the expense of memory usage). We slide even when level == 0
4305 to keep the hash table consistent if we switch back to level > 0
4306 later. (Using level 0 permanently is not an optimal usage of
4307 zlib, so we don't care about this pathological case.)
4314 s.head[p] = (m >= _w_size ? m - _w_size : 0);
4321 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
4322 /* If n is not on any hash chain, prev[n] is garbage but
4323 * its value will never be used.
4329 if (s.strm.avail_in === 0) {
4333 /* If there was no sliding:
4334 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
4335 * more == window_size - lookahead - strstart
4336 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
4337 * => more >= window_size - 2*WSIZE + 2
4338 * In the BIG_MEM or MMAP case (not yet supported),
4339 * window_size == input_size + MIN_LOOKAHEAD &&
4340 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
4341 * Otherwise, window_size == 2*WSIZE so more >= 2.
4342 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
4344 //Assert(more >= 2, "more < 2");
4345 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
4348 /* Initialize the hash value now that we have some input: */
4349 if (s.lookahead + s.insert >= MIN_MATCH) {
4350 str = s.strstart - s.insert;
4351 s.ins_h = s.window[str];
4353 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
4354 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
4355 //#if MIN_MATCH != 3
4356 // Call update_hash() MIN_MATCH-3 more times
4359 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
4360 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
4362 s.prev[str & s.w_mask] = s.head[s.ins_h];
4363 s.head[s.ins_h] = str;
4366 if (s.lookahead + s.insert < MIN_MATCH) {
4371 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
4372 * but this is not important since only literal bytes will be emitted.
4375 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
4377 /* If the WIN_INIT bytes after the end of the current data have never been
4378 * written, then zero those bytes in order to avoid memory check reports of
4379 * the use of uninitialized (or uninitialised as Julian writes) bytes by
4380 * the longest match routines. Update the high water mark for the next
4381 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
4382 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
4384 // if (s.high_water < s.window_size) {
4385 // var curr = s.strstart + s.lookahead;
4388 // if (s.high_water < curr) {
4389 // /* Previous high water mark below current data -- zero WIN_INIT
4390 // * bytes or up to end of window, whichever is less.
4392 // init = s.window_size - curr;
4393 // if (init > WIN_INIT)
4395 // zmemzero(s->window + curr, (unsigned)init);
4396 // s->high_water = curr + init;
4398 // else if (s->high_water < (ulg)curr + WIN_INIT) {
4399 // /* High water mark at or above current data, but below current data
4400 // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
4401 // * to end of window, whichever is less.
4403 // init = (ulg)curr + WIN_INIT - s->high_water;
4404 // if (init > s->window_size - s->high_water)
4405 // init = s->window_size - s->high_water;
4406 // zmemzero(s->window + s->high_water, (unsigned)init);
4407 // s->high_water += init;
4411 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
4412 // "not enough room for search");
4415 /* ===========================================================================
4416 * Copy without compression as much as possible from the input stream, return
4417 * the current block state.
4418 * This function does not insert new strings in the dictionary since
4419 * uncompressible data is probably not useful. This function is used
4420 * only for the level=0 compression option.
4421 * NOTE: this function should be optimized to avoid extra copying from
4422 * window to pending_buf.
4424 function deflate_stored(s, flush) {
4425 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
4426 * to pending_buf_size, and each stored block has a 5 byte header:
4428 var max_block_size = 0xffff;
4430 if (max_block_size > s.pending_buf_size - 5) {
4431 max_block_size = s.pending_buf_size - 5;
4434 /* Copy as much as possible from input to output: */
4436 /* Fill the window as much as possible: */
4437 if (s.lookahead <= 1) {
4439 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
4440 // s->block_start >= (long)s->w_size, "slide too late");
4441 // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
4442 // s.block_start >= s.w_size)) {
4443 // throw new Error("slide too late");
4447 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
4448 return BS_NEED_MORE;
4451 if (s.lookahead === 0) {
4454 /* flush the current block */
4456 //Assert(s->block_start >= 0L, "block gone");
4457 // if (s.block_start < 0) throw new Error("block gone");
4459 s.strstart += s.lookahead;
4462 /* Emit a stored block if pending_buf will be full: */
4463 var max_start = s.block_start + max_block_size;
4465 if (s.strstart === 0 || s.strstart >= max_start) {
4466 /* strstart == 0 is possible when wraparound on 16-bit machine */
4467 s.lookahead = s.strstart - max_start;
4468 s.strstart = max_start;
4469 /*** FLUSH_BLOCK(s, 0); ***/
4470 flush_block_only(s, false);
4471 if (s.strm.avail_out === 0) {
4472 return BS_NEED_MORE;
4478 /* Flush if we may have to slide, otherwise block_start may become
4479 * negative and the data will be gone:
4481 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
4482 /*** FLUSH_BLOCK(s, 0); ***/
4483 flush_block_only(s, false);
4484 if (s.strm.avail_out === 0) {
4485 return BS_NEED_MORE;
4493 if (flush === Z_FINISH) {
4494 /*** FLUSH_BLOCK(s, 1); ***/
4495 flush_block_only(s, true);
4496 if (s.strm.avail_out === 0) {
4497 return BS_FINISH_STARTED;
4500 return BS_FINISH_DONE;
4503 if (s.strstart > s.block_start) {
4504 /*** FLUSH_BLOCK(s, 0); ***/
4505 flush_block_only(s, false);
4506 if (s.strm.avail_out === 0) {
4507 return BS_NEED_MORE;
4512 return BS_NEED_MORE;
4515 /* ===========================================================================
4516 * Compress as much as possible from the input stream, return the current
4518 * This function does not perform lazy evaluation of matches and inserts
4519 * new strings in the dictionary only for unmatched strings or for short
4520 * matches. It is used only for the fast compression options.
4522 function deflate_fast(s, flush) {
4523 var hash_head; /* head of the hash chain */
4524 var bflush; /* set if current block must be flushed */
4527 /* Make sure that we always have enough lookahead, except
4528 * at the end of the input file. We need MAX_MATCH bytes
4529 * for the next match, plus MIN_MATCH bytes to insert the
4530 * string following the next match.
4532 if (s.lookahead < MIN_LOOKAHEAD) {
4534 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
4535 return BS_NEED_MORE;
4537 if (s.lookahead === 0) {
4538 break; /* flush the current block */
4542 /* Insert the string window[strstart .. strstart+2] in the
4543 * dictionary, and set hash_head to the head of the hash chain:
4545 hash_head = 0/*NIL*/;
4546 if (s.lookahead >= MIN_MATCH) {
4547 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
4548 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
4549 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
4550 s.head[s.ins_h] = s.strstart;
4554 /* Find the longest match, discarding those <= prev_length.
4555 * At this point we have always match_length < MIN_MATCH
4557 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
4558 /* To simplify the code, we prevent matches with the string
4559 * of window index 0 (in particular we have to avoid a match
4560 * of the string with itself at the start of the input file).
4562 s.match_length = longest_match(s, hash_head);
4563 /* longest_match() sets match_start */
4565 if (s.match_length >= MIN_MATCH) {
4566 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
4568 /*** _tr_tally_dist(s, s.strstart - s.match_start,
4569 s.match_length - MIN_MATCH, bflush); ***/
4570 bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
4572 s.lookahead -= s.match_length;
4574 /* Insert new strings in the hash table only if the match length
4575 * is not too large. This saves time but degrades compression.
4577 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
4578 s.match_length--; /* string at strstart already in table */
4581 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
4582 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
4583 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
4584 s.head[s.ins_h] = s.strstart;
4586 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
4587 * always MIN_MATCH bytes ahead.
4589 } while (--s.match_length !== 0);
4593 s.strstart += s.match_length;
4595 s.ins_h = s.window[s.strstart];
4596 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
4597 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
4599 //#if MIN_MATCH != 3
4600 // Call UPDATE_HASH() MIN_MATCH-3 more times
4602 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
4603 * matter since it will be recomputed at next deflate call.
4607 /* No match, output a literal byte */
4608 //Tracevv((stderr,"%c", s.window[s.strstart]));
4609 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
4610 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
4616 /*** FLUSH_BLOCK(s, 0); ***/
4617 flush_block_only(s, false);
4618 if (s.strm.avail_out === 0) {
4619 return BS_NEED_MORE;
4624 s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
4625 if (flush === Z_FINISH) {
4626 /*** FLUSH_BLOCK(s, 1); ***/
4627 flush_block_only(s, true);
4628 if (s.strm.avail_out === 0) {
4629 return BS_FINISH_STARTED;
4632 return BS_FINISH_DONE;
4635 /*** FLUSH_BLOCK(s, 0); ***/
4636 flush_block_only(s, false);
4637 if (s.strm.avail_out === 0) {
4638 return BS_NEED_MORE;
4642 return BS_BLOCK_DONE;
4645 /* ===========================================================================
4646 * Same as above, but achieves better compression. We use a lazy
4647 * evaluation for matches: a match is finally adopted only if there is
4648 * no better match at the next window position.
4650 function deflate_slow(s, flush) {
4651 var hash_head; /* head of hash chain */
4652 var bflush; /* set if current block must be flushed */
4656 /* Process the input block. */
4658 /* Make sure that we always have enough lookahead, except
4659 * at the end of the input file. We need MAX_MATCH bytes
4660 * for the next match, plus MIN_MATCH bytes to insert the
4661 * string following the next match.
4663 if (s.lookahead < MIN_LOOKAHEAD) {
4665 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
4666 return BS_NEED_MORE;
4668 if (s.lookahead === 0) { break; } /* flush the current block */
4671 /* Insert the string window[strstart .. strstart+2] in the
4672 * dictionary, and set hash_head to the head of the hash chain:
4674 hash_head = 0/*NIL*/;
4675 if (s.lookahead >= MIN_MATCH) {
4676 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
4677 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
4678 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
4679 s.head[s.ins_h] = s.strstart;
4683 /* Find the longest match, discarding those <= prev_length.
4685 s.prev_length = s.match_length;
4686 s.prev_match = s.match_start;
4687 s.match_length = MIN_MATCH-1;
4689 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
4690 s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
4691 /* To simplify the code, we prevent matches with the string
4692 * of window index 0 (in particular we have to avoid a match
4693 * of the string with itself at the start of the input file).
4695 s.match_length = longest_match(s, hash_head);
4696 /* longest_match() sets match_start */
4698 if (s.match_length <= 5 &&
4699 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
4701 /* If prev_match is also MIN_MATCH, match_start is garbage
4702 * but we will ignore the current match anyway.
4704 s.match_length = MIN_MATCH-1;
4707 /* If there was a match at the previous step and the current
4708 * match is not better, output the previous match:
4710 if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
4711 max_insert = s.strstart + s.lookahead - MIN_MATCH;
4712 /* Do not insert strings in hash table beyond this. */
4714 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
4716 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
4717 s.prev_length - MIN_MATCH, bflush);***/
4718 bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
4719 /* Insert in hash table all strings up to the end of the match.
4720 * strstart-1 and strstart are already inserted. If there is not
4721 * enough lookahead, the last two strings are not inserted in
4724 s.lookahead -= s.prev_length-1;
4727 if (++s.strstart <= max_insert) {
4728 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
4729 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
4730 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
4731 s.head[s.ins_h] = s.strstart;
4734 } while (--s.prev_length !== 0);
4735 s.match_available = 0;
4736 s.match_length = MIN_MATCH-1;
4740 /*** FLUSH_BLOCK(s, 0); ***/
4741 flush_block_only(s, false);
4742 if (s.strm.avail_out === 0) {
4743 return BS_NEED_MORE;
4748 } else if (s.match_available) {
4749 /* If there was no match at the previous position, output a
4750 * single literal. If there was a match but the current match
4751 * is longer, truncate the previous match to a single literal.
4753 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
4754 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
4755 bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
4758 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
4759 flush_block_only(s, false);
4764 if (s.strm.avail_out === 0) {
4765 return BS_NEED_MORE;
4768 /* There is no previous match to compare with, wait for
4769 * the next step to decide.
4771 s.match_available = 1;
4776 //Assert (flush != Z_NO_FLUSH, "no flush?");
4777 if (s.match_available) {
4778 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
4779 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
4780 bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
4782 s.match_available = 0;
4784 s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
4785 if (flush === Z_FINISH) {
4786 /*** FLUSH_BLOCK(s, 1); ***/
4787 flush_block_only(s, true);
4788 if (s.strm.avail_out === 0) {
4789 return BS_FINISH_STARTED;
4792 return BS_FINISH_DONE;
4795 /*** FLUSH_BLOCK(s, 0); ***/
4796 flush_block_only(s, false);
4797 if (s.strm.avail_out === 0) {
4798 return BS_NEED_MORE;
4803 return BS_BLOCK_DONE;
4807 /* ===========================================================================
4808 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
4809 * one. Do not maintain a hash table. (It will be regenerated if this run of
4810 * deflate switches away from Z_RLE.)
4812 function deflate_rle(s, flush) {
4813 var bflush; /* set if current block must be flushed */
4814 var prev; /* byte at distance one to match */
4815 var scan, strend; /* scan goes up to strend for length of run */
4817 var _win = s.window;
4820 /* Make sure that we always have enough lookahead, except
4821 * at the end of the input file. We need MAX_MATCH bytes
4822 * for the longest run, plus one for the unrolled loop.
4824 if (s.lookahead <= MAX_MATCH) {
4826 if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
4827 return BS_NEED_MORE;
4829 if (s.lookahead === 0) { break; } /* flush the current block */
4832 /* See how many times the previous byte repeats */
4834 if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
4835 scan = s.strstart - 1;
4837 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
4838 strend = s.strstart + MAX_MATCH;
4840 /*jshint noempty:false*/
4841 } while (prev === _win[++scan] && prev === _win[++scan] &&
4842 prev === _win[++scan] && prev === _win[++scan] &&
4843 prev === _win[++scan] && prev === _win[++scan] &&
4844 prev === _win[++scan] && prev === _win[++scan] &&
4846 s.match_length = MAX_MATCH - (strend - scan);
4847 if (s.match_length > s.lookahead) {
4848 s.match_length = s.lookahead;
4851 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
4854 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
4855 if (s.match_length >= MIN_MATCH) {
4856 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
4858 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
4859 bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
4861 s.lookahead -= s.match_length;
4862 s.strstart += s.match_length;
4865 /* No match, output a literal byte */
4866 //Tracevv((stderr,"%c", s->window[s->strstart]));
4867 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
4868 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
4874 /*** FLUSH_BLOCK(s, 0); ***/
4875 flush_block_only(s, false);
4876 if (s.strm.avail_out === 0) {
4877 return BS_NEED_MORE;
4883 if (flush === Z_FINISH) {
4884 /*** FLUSH_BLOCK(s, 1); ***/
4885 flush_block_only(s, true);
4886 if (s.strm.avail_out === 0) {
4887 return BS_FINISH_STARTED;
4890 return BS_FINISH_DONE;
4893 /*** FLUSH_BLOCK(s, 0); ***/
4894 flush_block_only(s, false);
4895 if (s.strm.avail_out === 0) {
4896 return BS_NEED_MORE;
4900 return BS_BLOCK_DONE;
4903 /* ===========================================================================
4904 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
4905 * (It will be regenerated if this run of deflate switches away from Huffman.)
4907 function deflate_huff(s, flush) {
4908 var bflush; /* set if current block must be flushed */
4911 /* Make sure that we have a literal to write. */
4912 if (s.lookahead === 0) {
4914 if (s.lookahead === 0) {
4915 if (flush === Z_NO_FLUSH) {
4916 return BS_NEED_MORE;
4918 break; /* flush the current block */
4922 /* Output a literal byte */
4924 //Tracevv((stderr,"%c", s->window[s->strstart]));
4925 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
4926 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
4930 /*** FLUSH_BLOCK(s, 0); ***/
4931 flush_block_only(s, false);
4932 if (s.strm.avail_out === 0) {
4933 return BS_NEED_MORE;
4939 if (flush === Z_FINISH) {
4940 /*** FLUSH_BLOCK(s, 1); ***/
4941 flush_block_only(s, true);
4942 if (s.strm.avail_out === 0) {
4943 return BS_FINISH_STARTED;
4946 return BS_FINISH_DONE;
4949 /*** FLUSH_BLOCK(s, 0); ***/
4950 flush_block_only(s, false);
4951 if (s.strm.avail_out === 0) {
4952 return BS_NEED_MORE;
4956 return BS_BLOCK_DONE;
4959 /* Values for max_lazy_match, good_match and max_chain_length, depending on
4960 * the desired pack level (0..9). The values given below have been tuned to
4961 * exclude worst case performance for pathological files. Better values may be
4962 * found for specific files.
4964 var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
4965 this.good_length = good_length;
4966 this.max_lazy = max_lazy;
4967 this.nice_length = nice_length;
4968 this.max_chain = max_chain;
4972 var configuration_table;
4974 configuration_table = [
4975 /* good lazy nice chain */
4976 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
4977 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
4978 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
4979 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
4981 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
4982 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
4983 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
4984 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
4985 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
4986 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
4990 /* ===========================================================================
4991 * Initialize the "longest match" routines for a new zlib stream
4993 function lm_init(s) {
4994 s.window_size = 2 * s.w_size;
4996 /*** CLEAR_HASH(s); ***/
4997 zero(s.head); // Fill with NIL (= 0);
4999 /* Set the default configuration parameters:
5001 s.max_lazy_match = configuration_table[s.level].max_lazy;
5002 s.good_match = configuration_table[s.level].good_length;
5003 s.nice_match = configuration_table[s.level].nice_length;
5004 s.max_chain_length = configuration_table[s.level].max_chain;
5010 s.match_length = s.prev_length = MIN_MATCH - 1;
5011 s.match_available = 0;
5016 function DeflateState() {
5017 this.strm = null; /* pointer back to this zlib stream */
5018 this.status = 0; /* as the name implies */
5019 this.pending_buf = null; /* output still pending */
5020 this.pending_buf_size = 0; /* size of pending_buf */
5021 this.pending_out = 0; /* next pending byte to output to the stream */
5022 this.pending = 0; /* nb of bytes in the pending buffer */
5023 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
5024 this.gzhead = null; /* gzip header information to write */
5025 this.gzindex = 0; /* where in extra, name, or comment */
5026 this.method = Z_DEFLATED; /* can only be DEFLATED */
5027 this.last_flush = -1; /* value of flush param for previous deflate call */
5029 this.w_size = 0; /* LZ77 window size (32K by default) */
5030 this.w_bits = 0; /* log2(w_size) (8..16) */
5031 this.w_mask = 0; /* w_size - 1 */
5034 /* Sliding window. Input bytes are read into the second half of the window,
5035 * and move to the first half later to keep a dictionary of at least wSize
5036 * bytes. With this organization, matches are limited to a distance of
5037 * wSize-MAX_MATCH bytes, but this ensures that IO is always
5038 * performed with a length multiple of the block size.
5041 this.window_size = 0;
5042 /* Actual size of window: 2*wSize, except when the user input buffer
5043 * is directly used as sliding window.
5047 /* Link to older string with same hash index. To limit the size of this
5048 * array to 64K, this link is maintained only for the last 32K strings.
5049 * An index in this array is thus a window index modulo 32K.
5052 this.head = null; /* Heads of the hash chains or NIL. */
5054 this.ins_h = 0; /* hash index of string to be inserted */
5055 this.hash_size = 0; /* number of elements in hash table */
5056 this.hash_bits = 0; /* log2(hash_size) */
5057 this.hash_mask = 0; /* hash_size-1 */
5059 this.hash_shift = 0;
5060 /* Number of bits by which ins_h must be shifted at each input
5061 * step. It must be such that after MIN_MATCH steps, the oldest
5062 * byte no longer takes part in the hash key, that is:
5063 * hash_shift * MIN_MATCH >= hash_bits
5066 this.block_start = 0;
5067 /* Window position at the beginning of the current output block. Gets
5068 * negative when the window is moved backwards.
5071 this.match_length = 0; /* length of best match */
5072 this.prev_match = 0; /* previous match */
5073 this.match_available = 0; /* set if previous match exists */
5074 this.strstart = 0; /* start of string to insert */
5075 this.match_start = 0; /* start of matching string */
5076 this.lookahead = 0; /* number of valid bytes ahead in window */
5078 this.prev_length = 0;
5079 /* Length of the best match at previous step. Matches not greater than this
5080 * are discarded. This is used in the lazy match evaluation.
5083 this.max_chain_length = 0;
5084 /* To speed up deflation, hash chains are never searched beyond this
5085 * length. A higher limit improves compression ratio but degrades the
5089 this.max_lazy_match = 0;
5090 /* Attempt to find a better match only when the current match is strictly
5091 * smaller than this value. This mechanism is used only for compression
5094 // That's alias to max_lazy_match, don't use directly
5095 //this.max_insert_length = 0;
5096 /* Insert new strings in the hash table only if the match length is not
5097 * greater than this length. This saves time but degrades compression.
5098 * max_insert_length is used only for compression levels <= 3.
5101 this.level = 0; /* compression level (1..9) */
5102 this.strategy = 0; /* favor or force Huffman coding*/
5104 this.good_match = 0;
5105 /* Use a faster search when the previous match is longer than this */
5107 this.nice_match = 0; /* Stop searching when current match exceeds this */
5109 /* used by trees.c: */
5111 /* Didn't use ct_data typedef below to suppress compiler warning */
5113 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
5114 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
5115 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
5117 // Use flat array of DOUBLE size, with interleaved fata,
5118 // because JS does not support effective
5119 this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
5120 this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
5121 this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
5122 zero(this.dyn_ltree);
5123 zero(this.dyn_dtree);
5126 this.l_desc = null; /* desc. for literal tree */
5127 this.d_desc = null; /* desc. for distance tree */
5128 this.bl_desc = null; /* desc. for bit length tree */
5130 //ush bl_count[MAX_BITS+1];
5131 this.bl_count = new utils.Buf16(MAX_BITS+1);
5132 /* number of codes at each bit length for an optimal tree */
5134 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
5135 this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
5138 this.heap_len = 0; /* number of elements in the heap */
5139 this.heap_max = 0; /* element of largest frequency */
5140 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
5141 * The same heap array is used to build all trees.
5144 this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
5146 /* Depth of each subtree used as tie breaker for trees of equal frequency
5149 this.l_buf = 0; /* buffer index for literals or lengths */
5151 this.lit_bufsize = 0;
5152 /* Size of match buffer for literals/lengths. There are 4 reasons for
5153 * limiting lit_bufsize to 64K:
5154 * - frequencies can be kept in 16 bit counters
5155 * - if compression is not successful for the first block, all input
5156 * data is still in the window so we can still emit a stored block even
5157 * when input comes from standard input. (This can also be done for
5158 * all blocks if lit_bufsize is not greater than 32K.)
5159 * - if compression is not successful for a file smaller than 64K, we can
5160 * even emit a stored file instead of a stored block (saving 5 bytes).
5161 * This is applicable only for zip (not gzip or zlib).
5162 * - creating new Huffman trees less frequently may not provide fast
5163 * adaptation to changes in the input data statistics. (Take for
5164 * example a binary file with poorly compressible code followed by
5165 * a highly compressible string table.) Smaller buffer sizes give
5166 * fast adaptation but have of course the overhead of transmitting
5167 * trees more frequently.
5168 * - I can't count above 4
5171 this.last_lit = 0; /* running index in l_buf */
5174 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
5175 * the same number of elements. To use different lengths, an extra flag
5176 * array would be necessary.
5179 this.opt_len = 0; /* bit length of current block with optimal trees */
5180 this.static_len = 0; /* bit length of current block with static trees */
5181 this.matches = 0; /* number of string matches in current block */
5182 this.insert = 0; /* bytes at end of window left to insert */
5186 /* Output buffer. bits are inserted starting at the bottom (least
5187 * significant bits).
5190 /* Number of valid bits in bi_buf. All bits above the last valid bit
5194 // Used for window memory init. We safely ignore it for JS. That makes
5195 // sense only for pointers and memory check tools.
5196 //this.high_water = 0;
5197 /* High water mark offset in window for initialized bytes -- bytes above
5198 * this are set to zero in order to avoid memory check warnings when
5199 * longest match routines access bytes past the input. This is then
5200 * updated to the new high water mark.
5205 function deflateResetKeep(strm) {
5208 if (!strm || !strm.state) {
5209 return err(strm, Z_STREAM_ERROR);
5212 strm.total_in = strm.total_out = 0;
5213 strm.data_type = Z_UNKNOWN;
5221 /* was made negative by deflate(..., Z_FINISH); */
5223 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
5224 strm.adler = (s.wrap === 2) ?
5225 0 // crc32(0, Z_NULL, 0)
5227 1; // adler32(0, Z_NULL, 0)
5228 s.last_flush = Z_NO_FLUSH;
5234 function deflateReset(strm) {
5235 var ret = deflateResetKeep(strm);
5237 lm_init(strm.state);
5243 function deflateSetHeader(strm, head) {
5244 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
5245 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
5246 strm.state.gzhead = head;
5251 function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
5252 if (!strm) { // === Z_NULL
5253 return Z_STREAM_ERROR;
5257 if (level === Z_DEFAULT_COMPRESSION) {
5261 if (windowBits < 0) { /* suppress zlib wrapper */
5263 windowBits = -windowBits;
5266 else if (windowBits > 15) {
5267 wrap = 2; /* write gzip wrapper instead */
5272 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
5273 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
5274 strategy < 0 || strategy > Z_FIXED) {
5275 return err(strm, Z_STREAM_ERROR);
5279 if (windowBits === 8) {
5282 /* until 256-byte window bug fixed */
5284 var s = new DeflateState();
5291 s.w_bits = windowBits;
5292 s.w_size = 1 << s.w_bits;
5293 s.w_mask = s.w_size - 1;
5295 s.hash_bits = memLevel + 7;
5296 s.hash_size = 1 << s.hash_bits;
5297 s.hash_mask = s.hash_size - 1;
5298 s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
5300 s.window = new utils.Buf8(s.w_size * 2);
5301 s.head = new utils.Buf16(s.hash_size);
5302 s.prev = new utils.Buf16(s.w_size);
5304 // Don't need mem init magic for JS.
5305 //s.high_water = 0; /* nothing written to s->window yet */
5307 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
5309 s.pending_buf_size = s.lit_bufsize * 4;
5310 s.pending_buf = new utils.Buf8(s.pending_buf_size);
5312 s.d_buf = s.lit_bufsize >> 1;
5313 s.l_buf = (1 + 2) * s.lit_bufsize;
5316 s.strategy = strategy;
5319 return deflateReset(strm);
5322 function deflateInit(strm, level) {
5323 return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
5327 function deflate(strm, flush) {
5329 var beg, val; // for gzip header write only
5331 if (!strm || !strm.state ||
5332 flush > Z_BLOCK || flush < 0) {
5333 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
5339 (!strm.input && strm.avail_in !== 0) ||
5340 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
5341 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
5344 s.strm = strm; /* just in case */
5345 old_flush = s.last_flush;
5346 s.last_flush = flush;
5348 /* Write the header */
5349 if (s.status === INIT_STATE) {
5351 if (s.wrap === 2) { // GZIP header
5352 strm.adler = 0; //crc32(0L, Z_NULL, 0);
5356 if (!s.gzhead) { // s->gzhead == Z_NULL
5362 put_byte(s, s.level === 9 ? 2 :
5363 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
5365 put_byte(s, OS_CODE);
5366 s.status = BUSY_STATE;
5369 put_byte(s, (s.gzhead.text ? 1 : 0) +
5370 (s.gzhead.hcrc ? 2 : 0) +
5371 (!s.gzhead.extra ? 0 : 4) +
5372 (!s.gzhead.name ? 0 : 8) +
5373 (!s.gzhead.comment ? 0 : 16)
5375 put_byte(s, s.gzhead.time & 0xff);
5376 put_byte(s, (s.gzhead.time >> 8) & 0xff);
5377 put_byte(s, (s.gzhead.time >> 16) & 0xff);
5378 put_byte(s, (s.gzhead.time >> 24) & 0xff);
5379 put_byte(s, s.level === 9 ? 2 :
5380 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
5382 put_byte(s, s.gzhead.os & 0xff);
5383 if (s.gzhead.extra && s.gzhead.extra.length) {
5384 put_byte(s, s.gzhead.extra.length & 0xff);
5385 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
5387 if (s.gzhead.hcrc) {
5388 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
5391 s.status = EXTRA_STATE;
5394 else // DEFLATE header
5396 var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
5397 var level_flags = -1;
5399 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
5401 } else if (s.level < 6) {
5403 } else if (s.level === 6) {
5408 header |= (level_flags << 6);
5409 if (s.strstart !== 0) { header |= PRESET_DICT; }
5410 header += 31 - (header % 31);
5412 s.status = BUSY_STATE;
5413 putShortMSB(s, header);
5415 /* Save the adler32 of the preset dictionary: */
5416 if (s.strstart !== 0) {
5417 putShortMSB(s, strm.adler >>> 16);
5418 putShortMSB(s, strm.adler & 0xffff);
5420 strm.adler = 1; // adler32(0L, Z_NULL, 0);
5425 if (s.status === EXTRA_STATE) {
5426 if (s.gzhead.extra/* != Z_NULL*/) {
5427 beg = s.pending; /* start of bytes to update crc */
5429 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
5430 if (s.pending === s.pending_buf_size) {
5431 if (s.gzhead.hcrc && s.pending > beg) {
5432 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5434 flush_pending(strm);
5436 if (s.pending === s.pending_buf_size) {
5440 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
5443 if (s.gzhead.hcrc && s.pending > beg) {
5444 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5446 if (s.gzindex === s.gzhead.extra.length) {
5448 s.status = NAME_STATE;
5452 s.status = NAME_STATE;
5455 if (s.status === NAME_STATE) {
5456 if (s.gzhead.name/* != Z_NULL*/) {
5457 beg = s.pending; /* start of bytes to update crc */
5461 if (s.pending === s.pending_buf_size) {
5462 if (s.gzhead.hcrc && s.pending > beg) {
5463 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5465 flush_pending(strm);
5467 if (s.pending === s.pending_buf_size) {
5472 // JS specific: little magic to add zero terminator to end of string
5473 if (s.gzindex < s.gzhead.name.length) {
5474 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
5479 } while (val !== 0);
5481 if (s.gzhead.hcrc && s.pending > beg){
5482 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5486 s.status = COMMENT_STATE;
5490 s.status = COMMENT_STATE;
5493 if (s.status === COMMENT_STATE) {
5494 if (s.gzhead.comment/* != Z_NULL*/) {
5495 beg = s.pending; /* start of bytes to update crc */
5499 if (s.pending === s.pending_buf_size) {
5500 if (s.gzhead.hcrc && s.pending > beg) {
5501 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5503 flush_pending(strm);
5505 if (s.pending === s.pending_buf_size) {
5510 // JS specific: little magic to add zero terminator to end of string
5511 if (s.gzindex < s.gzhead.comment.length) {
5512 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
5517 } while (val !== 0);
5519 if (s.gzhead.hcrc && s.pending > beg) {
5520 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5523 s.status = HCRC_STATE;
5527 s.status = HCRC_STATE;
5530 if (s.status === HCRC_STATE) {
5531 if (s.gzhead.hcrc) {
5532 if (s.pending + 2 > s.pending_buf_size) {
5533 flush_pending(strm);
5535 if (s.pending + 2 <= s.pending_buf_size) {
5536 put_byte(s, strm.adler & 0xff);
5537 put_byte(s, (strm.adler >> 8) & 0xff);
5538 strm.adler = 0; //crc32(0L, Z_NULL, 0);
5539 s.status = BUSY_STATE;
5543 s.status = BUSY_STATE;
5548 /* Flush as much pending output as possible */
5549 if (s.pending !== 0) {
5550 flush_pending(strm);
5551 if (strm.avail_out === 0) {
5552 /* Since avail_out is 0, deflate will be called again with
5553 * more output space, but possibly with both pending and
5554 * avail_in equal to zero. There won't be anything to do,
5555 * but this is not an error situation so make sure we
5556 * return OK instead of BUF_ERROR at next call of deflate:
5562 /* Make sure there is something to do and avoid duplicate consecutive
5563 * flushes. For repeated and useless calls with Z_FINISH, we keep
5564 * returning Z_STREAM_END instead of Z_BUF_ERROR.
5566 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
5567 flush !== Z_FINISH) {
5568 return err(strm, Z_BUF_ERROR);
5571 /* User must not provide more input after the first FINISH: */
5572 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
5573 return err(strm, Z_BUF_ERROR);
5576 /* Start a new block or continue the current one.
5578 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
5579 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
5580 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
5581 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
5582 configuration_table[s.level].func(s, flush));
5584 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
5585 s.status = FINISH_STATE;
5587 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
5588 if (strm.avail_out === 0) {
5590 /* avoid BUF_ERROR next call, see above */
5593 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
5594 * of deflate should use the same flush parameter to make sure
5595 * that the flush is complete. So we don't have to output an
5596 * empty block here, this will be done at next call. This also
5597 * ensures that for a very small output buffer, we emit at most
5601 if (bstate === BS_BLOCK_DONE) {
5602 if (flush === Z_PARTIAL_FLUSH) {
5605 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
5607 trees._tr_stored_block(s, 0, 0, false);
5608 /* For a full flush, this empty block will be recognized
5609 * as a special marker by inflate_sync().
5611 if (flush === Z_FULL_FLUSH) {
5612 /*** CLEAR_HASH(s); ***/ /* forget history */
5613 zero(s.head); // Fill with NIL (= 0);
5615 if (s.lookahead === 0) {
5622 flush_pending(strm);
5623 if (strm.avail_out === 0) {
5624 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
5629 //Assert(strm->avail_out > 0, "bug2");
5630 //if (strm.avail_out <= 0) { throw new Error("bug2");}
5632 if (flush !== Z_FINISH) { return Z_OK; }
5633 if (s.wrap <= 0) { return Z_STREAM_END; }
5635 /* Write the trailer */
5637 put_byte(s, strm.adler & 0xff);
5638 put_byte(s, (strm.adler >> 8) & 0xff);
5639 put_byte(s, (strm.adler >> 16) & 0xff);
5640 put_byte(s, (strm.adler >> 24) & 0xff);
5641 put_byte(s, strm.total_in & 0xff);
5642 put_byte(s, (strm.total_in >> 8) & 0xff);
5643 put_byte(s, (strm.total_in >> 16) & 0xff);
5644 put_byte(s, (strm.total_in >> 24) & 0xff);
5648 putShortMSB(s, strm.adler >>> 16);
5649 putShortMSB(s, strm.adler & 0xffff);
5652 flush_pending(strm);
5653 /* If avail_out is zero, the application will call deflate again
5654 * to flush the rest.
5656 if (s.wrap > 0) { s.wrap = -s.wrap; }
5657 /* write the trailer only once! */
5658 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
5661 function deflateEnd(strm) {
5664 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
5665 return Z_STREAM_ERROR;
5668 status = strm.state.status;
5669 if (status !== INIT_STATE &&
5670 status !== EXTRA_STATE &&
5671 status !== NAME_STATE &&
5672 status !== COMMENT_STATE &&
5673 status !== HCRC_STATE &&
5674 status !== BUSY_STATE &&
5675 status !== FINISH_STATE
5677 return err(strm, Z_STREAM_ERROR);
5682 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
5685 /* =========================================================================
5686 * Copy the source state to the destination state
5688 //function deflateCopy(dest, source) {
5692 exports.deflateInit = deflateInit;
5693 exports.deflateInit2 = deflateInit2;
5694 exports.deflateReset = deflateReset;
5695 exports.deflateResetKeep = deflateResetKeep;
5696 exports.deflateSetHeader = deflateSetHeader;
5697 exports.deflate = deflate;
5698 exports.deflateEnd = deflateEnd;
5699 exports.deflateInfo = 'pako deflate (from Nodeca project)';
5702 exports.deflateBound = deflateBound;
5703 exports.deflateCopy = deflateCopy;
5704 exports.deflateSetDictionary = deflateSetDictionary;
5705 exports.deflateParams = deflateParams;
5706 exports.deflatePending = deflatePending;
5707 exports.deflatePrime = deflatePrime;
5708 exports.deflateTune = deflateTune;
5710 },{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(_dereq_,module,exports){
5714 function GZheader() {
5715 /* true if compressed data believed to be text */
5717 /* modification time */
5719 /* extra flags (not used when writing a gzip file) */
5721 /* operating system */
5723 /* pointer to extra field or Z_NULL if none */
5725 /* extra field length (valid if extra != Z_NULL) */
5726 this.extra_len = 0; // Actually, we don't need it in JS,
5727 // but leave for few code modifications
5730 // Setup limits is not necessary because in js we should not preallocate memory
5731 // for inflate use constant limit in 65536 bytes
5734 /* space at extra (only when reading header) */
5735 // this.extra_max = 0;
5736 /* pointer to zero-terminated file name or Z_NULL */
5738 /* space at name (only when reading header) */
5739 // this.name_max = 0;
5740 /* pointer to zero-terminated comment or Z_NULL */
5742 /* space at comment (only when reading header) */
5743 // this.comm_max = 0;
5744 /* true if there was or will be a header crc */
5746 /* true when done reading gzip header (not used when writing a gzip file) */
5750 module.exports = GZheader;
5751 },{}],34:[function(_dereq_,module,exports){
5754 // See state defs from inflate.js
5755 var BAD = 30; /* got a data error -- remain here until reset */
5756 var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
5759 Decode literal, length, and distance codes and write out the resulting
5760 literal and match bytes until either not enough input or output is
5761 available, an end-of-block is encountered, or a data error is encountered.
5762 When large enough input and output buffers are supplied to inflate(), for
5763 example, a 16K input buffer and a 64K output buffer, more than 95% of the
5764 inflate execution time is spent in this routine.
5770 strm.avail_out >= 258
5771 start >= strm.avail_out
5774 On return, state.mode is one of:
5776 LEN -- ran out of enough output space or enough available input
5777 TYPE -- reached end of block code, inflate() to interpret next block
5778 BAD -- error in block data
5782 - The maximum input bits used by a length/distance pair is 15 bits for the
5783 length code, 5 bits for the length extra, 15 bits for the distance code,
5784 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
5785 Therefore if strm.avail_in >= 6, then there is enough input to avoid
5786 checking for available input while decoding.
5788 - The maximum bytes that a single length/distance pair can output is 258
5789 bytes, which is the maximum length that can be coded. inflate_fast()
5790 requires strm.avail_out >= 258 for each loop to avoid checking for
5793 module.exports = function inflate_fast(strm, start) {
5795 var _in; /* local strm.input */
5796 var last; /* have enough input while in < last */
5797 var _out; /* local strm.output */
5798 var beg; /* inflate()'s initial strm.output */
5799 var end; /* while out < end, enough space available */
5800 //#ifdef INFLATE_STRICT
5801 var dmax; /* maximum distance from zlib header */
5803 var wsize; /* window size or zero if not using window */
5804 var whave; /* valid bytes in the window */
5805 var wnext; /* window write index */
5806 var window; /* allocated sliding window, if wsize != 0 */
5807 var hold; /* local strm.hold */
5808 var bits; /* local strm.bits */
5809 var lcode; /* local strm.lencode */
5810 var dcode; /* local strm.distcode */
5811 var lmask; /* mask for first level of length codes */
5812 var dmask; /* mask for first level of distance codes */
5813 var here; /* retrieved table entry */
5814 var op; /* code bits, operation, extra bits, or */
5815 /* window position, window bytes to copy */
5816 var len; /* match length, unused bytes */
5817 var dist; /* match distance */
5818 var from; /* where to copy match from */
5822 var input, output; // JS specific, because we have no pointers
5824 /* copy state to local variables */
5826 //here = state.here;
5829 last = _in + (strm.avail_in - 5);
5830 _out = strm.next_out;
5831 output = strm.output;
5832 beg = _out - (start - strm.avail_out);
5833 end = _out + (strm.avail_out - 257);
5834 //#ifdef INFLATE_STRICT
5837 wsize = state.wsize;
5838 whave = state.whave;
5839 wnext = state.wnext;
5840 window = state.window;
5843 lcode = state.lencode;
5844 dcode = state.distcode;
5845 lmask = (1 << state.lenbits) - 1;
5846 dmask = (1 << state.distbits) - 1;
5849 /* decode literals and length/distances until end-of-block or not enough
5850 input data or output space */
5855 hold += input[_in++] << bits;
5857 hold += input[_in++] << bits;
5861 here = lcode[hold & lmask];
5864 for (;;) { // Goto emulation
5865 op = here >>> 24/*here.bits*/;
5868 op = (here >>> 16) & 0xff/*here.op*/;
5869 if (op === 0) { /* literal */
5870 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
5871 // "inflate: literal '%c'\n" :
5872 // "inflate: literal 0x%02x\n", here.val));
5873 output[_out++] = here & 0xffff/*here.val*/;
5875 else if (op & 16) { /* length base */
5876 len = here & 0xffff/*here.val*/;
5877 op &= 15; /* number of extra bits */
5880 hold += input[_in++] << bits;
5883 len += hold & ((1 << op) - 1);
5887 //Tracevv((stderr, "inflate: length %u\n", len));
5889 hold += input[_in++] << bits;
5891 hold += input[_in++] << bits;
5894 here = dcode[hold & dmask];
5897 for (;;) { // goto emulation
5898 op = here >>> 24/*here.bits*/;
5901 op = (here >>> 16) & 0xff/*here.op*/;
5903 if (op & 16) { /* distance base */
5904 dist = here & 0xffff/*here.val*/;
5905 op &= 15; /* number of extra bits */
5907 hold += input[_in++] << bits;
5910 hold += input[_in++] << bits;
5914 dist += hold & ((1 << op) - 1);
5915 //#ifdef INFLATE_STRICT
5917 strm.msg = 'invalid distance too far back';
5924 //Tracevv((stderr, "inflate: distance %u\n", dist));
5925 op = _out - beg; /* max distance in output */
5926 if (dist > op) { /* see if copy from window */
5927 op = dist - op; /* distance back in window */
5930 strm.msg = 'invalid distance too far back';
5935 // (!) This block is disabled in zlib defailts,
5936 // don't enable it for binary compatibility
5937 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
5938 // if (len <= op - whave) {
5940 // output[_out++] = 0;
5944 // len -= op - whave;
5946 // output[_out++] = 0;
5947 // } while (--op > whave);
5949 // from = _out - dist;
5951 // output[_out++] = output[from++];
5957 from = 0; // window index
5958 from_source = window;
5959 if (wnext === 0) { /* very common case */
5961 if (op < len) { /* some from window */
5964 output[_out++] = window[from++];
5966 from = _out - dist; /* rest from output */
5967 from_source = output;
5970 else if (wnext < op) { /* wrap around window */
5971 from += wsize + wnext - op;
5973 if (op < len) { /* some from end of window */
5976 output[_out++] = window[from++];
5979 if (wnext < len) { /* some from start of window */
5983 output[_out++] = window[from++];
5985 from = _out - dist; /* rest from output */
5986 from_source = output;
5990 else { /* contiguous in window */
5992 if (op < len) { /* some from window */
5995 output[_out++] = window[from++];
5997 from = _out - dist; /* rest from output */
5998 from_source = output;
6002 output[_out++] = from_source[from++];
6003 output[_out++] = from_source[from++];
6004 output[_out++] = from_source[from++];
6008 output[_out++] = from_source[from++];
6010 output[_out++] = from_source[from++];
6015 from = _out - dist; /* copy direct from output */
6016 do { /* minimum length is three */
6017 output[_out++] = output[from++];
6018 output[_out++] = output[from++];
6019 output[_out++] = output[from++];
6023 output[_out++] = output[from++];
6025 output[_out++] = output[from++];
6030 else if ((op & 64) === 0) { /* 2nd level distance code */
6031 here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
6035 strm.msg = 'invalid distance code';
6040 break; // need to emulate goto via "continue"
6043 else if ((op & 64) === 0) { /* 2nd level length code */
6044 here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
6047 else if (op & 32) { /* end-of-block */
6048 //Tracevv((stderr, "inflate: end of block\n"));
6053 strm.msg = 'invalid literal/length code';
6058 break; // need to emulate goto via "continue"
6060 } while (_in < last && _out < end);
6062 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
6066 hold &= (1 << bits) - 1;
6068 /* update state and return */
6070 strm.next_out = _out;
6071 strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
6072 strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
6078 },{}],35:[function(_dereq_,module,exports){
6082 var utils = _dereq_('../utils/common');
6083 var adler32 = _dereq_('./adler32');
6084 var crc32 = _dereq_('./crc32');
6085 var inflate_fast = _dereq_('./inffast');
6086 var inflate_table = _dereq_('./inftrees');
6092 /* Public constants ==========================================================*/
6093 /* ===========================================================================*/
6096 /* Allowed flush values; see deflate() and inflate() below for details */
6097 //var Z_NO_FLUSH = 0;
6098 //var Z_PARTIAL_FLUSH = 1;
6099 //var Z_SYNC_FLUSH = 2;
6100 //var Z_FULL_FLUSH = 3;
6106 /* Return codes for the compression/decompression functions. Negative values
6107 * are errors, positive values are used for special but normal events.
6110 var Z_STREAM_END = 1;
6111 var Z_NEED_DICT = 2;
6113 var Z_STREAM_ERROR = -2;
6114 var Z_DATA_ERROR = -3;
6115 var Z_MEM_ERROR = -4;
6116 var Z_BUF_ERROR = -5;
6117 //var Z_VERSION_ERROR = -6;
6119 /* The deflate compression method */
6123 /* STATES ====================================================================*/
6124 /* ===========================================================================*/
6127 var HEAD = 1; /* i: waiting for magic header */
6128 var FLAGS = 2; /* i: waiting for method and flags (gzip) */
6129 var TIME = 3; /* i: waiting for modification time (gzip) */
6130 var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
6131 var EXLEN = 5; /* i: waiting for extra length (gzip) */
6132 var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
6133 var NAME = 7; /* i: waiting for end of file name (gzip) */
6134 var COMMENT = 8; /* i: waiting for end of comment (gzip) */
6135 var HCRC = 9; /* i: waiting for header crc (gzip) */
6136 var DICTID = 10; /* i: waiting for dictionary check value */
6137 var DICT = 11; /* waiting for inflateSetDictionary() call */
6138 var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
6139 var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
6140 var STORED = 14; /* i: waiting for stored size (length and complement) */
6141 var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
6142 var COPY = 16; /* i/o: waiting for input or output to copy stored block */
6143 var TABLE = 17; /* i: waiting for dynamic block table lengths */
6144 var LENLENS = 18; /* i: waiting for code length code lengths */
6145 var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
6146 var LEN_ = 20; /* i: same as LEN below, but only first time in */
6147 var LEN = 21; /* i: waiting for length/lit/eob code */
6148 var LENEXT = 22; /* i: waiting for length extra bits */
6149 var DIST = 23; /* i: waiting for distance code */
6150 var DISTEXT = 24; /* i: waiting for distance extra bits */
6151 var MATCH = 25; /* o: waiting for output space to copy string */
6152 var LIT = 26; /* o: waiting for output space to write literal */
6153 var CHECK = 27; /* i: waiting for 32-bit check value */
6154 var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
6155 var DONE = 29; /* finished check, done -- remain here until reset */
6156 var BAD = 30; /* got a data error -- remain here until reset */
6157 var MEM = 31; /* got an inflate() memory error -- remain here until reset */
6158 var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
6160 /* ===========================================================================*/
6164 var ENOUGH_LENS = 852;
6165 var ENOUGH_DISTS = 592;
6166 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
6169 /* 32K LZ77 window */
6170 var DEF_WBITS = MAX_WBITS;
6173 function ZSWAP32(q) {
6174 return (((q >>> 24) & 0xff) +
6175 ((q >>> 8) & 0xff00) +
6176 ((q & 0xff00) << 8) +
6177 ((q & 0xff) << 24));
6181 function InflateState() {
6182 this.mode = 0; /* current inflate mode */
6183 this.last = false; /* true if processing last block */
6184 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
6185 this.havedict = false; /* true if dictionary provided */
6186 this.flags = 0; /* gzip header method and flags (0 if zlib) */
6187 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
6188 this.check = 0; /* protected copy of check value */
6189 this.total = 0; /* protected copy of output count */
6191 this.head = null; /* where to save gzip header information */
6193 /* sliding window */
6194 this.wbits = 0; /* log base 2 of requested window size */
6195 this.wsize = 0; /* window size or zero if not using window */
6196 this.whave = 0; /* valid bytes in the window */
6197 this.wnext = 0; /* window write index */
6198 this.window = null; /* allocated sliding window, if needed */
6200 /* bit accumulator */
6201 this.hold = 0; /* input bit accumulator */
6202 this.bits = 0; /* number of bits in "in" */
6204 /* for string and stored block copying */
6205 this.length = 0; /* literal or length of data to copy */
6206 this.offset = 0; /* distance back to copy string from */
6208 /* for table and code decoding */
6209 this.extra = 0; /* extra bits needed */
6211 /* fixed and dynamic code tables */
6212 this.lencode = null; /* starting table for length/literal codes */
6213 this.distcode = null; /* starting table for distance codes */
6214 this.lenbits = 0; /* index bits for lencode */
6215 this.distbits = 0; /* index bits for distcode */
6217 /* dynamic table building */
6218 this.ncode = 0; /* number of code length code lengths */
6219 this.nlen = 0; /* number of length code lengths */
6220 this.ndist = 0; /* number of distance code lengths */
6221 this.have = 0; /* number of code lengths in lens[] */
6222 this.next = null; /* next available space in codes[] */
6224 this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
6225 this.work = new utils.Buf16(288); /* work area for code table building */
6228 because we don't have pointers in js, we use lencode and distcode directly
6229 as buffers so we don't need codes
6231 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
6232 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
6233 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
6234 this.sane = 0; /* if false, allow invalid distance too far */
6235 this.back = 0; /* bits back of last unprocessed length/lit */
6236 this.was = 0; /* initial length of match */
6239 function inflateResetKeep(strm) {
6242 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
6244 strm.total_in = strm.total_out = state.total = 0;
6245 strm.msg = ''; /*Z_NULL*/
6246 if (state.wrap) { /* to support ill-conceived Java test suite */
6247 strm.adler = state.wrap & 1;
6253 state.head = null/*Z_NULL*/;
6256 //state.lencode = state.distcode = state.next = state.codes;
6257 state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
6258 state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
6262 //Tracev((stderr, "inflate: reset\n"));
6266 function inflateReset(strm) {
6269 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
6274 return inflateResetKeep(strm);
6278 function inflateReset2(strm, windowBits) {
6283 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
6286 /* extract wrap request from windowBits parameter */
6287 if (windowBits < 0) {
6289 windowBits = -windowBits;
6292 wrap = (windowBits >> 4) + 1;
6293 if (windowBits < 48) {
6298 /* set number of window bits, free window if different */
6299 if (windowBits && (windowBits < 8 || windowBits > 15)) {
6300 return Z_STREAM_ERROR;
6302 if (state.window !== null && state.wbits !== windowBits) {
6303 state.window = null;
6306 /* update state and reset the rest of it */
6308 state.wbits = windowBits;
6309 return inflateReset(strm);
6312 function inflateInit2(strm, windowBits) {
6316 if (!strm) { return Z_STREAM_ERROR; }
6317 //strm.msg = Z_NULL; /* in case we return an error */
6319 state = new InflateState();
6321 //if (state === Z_NULL) return Z_MEM_ERROR;
6322 //Tracev((stderr, "inflate: allocated\n"));
6324 state.window = null/*Z_NULL*/;
6325 ret = inflateReset2(strm, windowBits);
6327 strm.state = null/*Z_NULL*/;
6332 function inflateInit(strm) {
6333 return inflateInit2(strm, DEF_WBITS);
6338 Return state with length and distance decoding tables and index sizes set to
6339 fixed code decoding. Normally this returns fixed tables from inffixed.h.
6340 If BUILDFIXED is defined, then instead this routine builds the tables the
6341 first time it's called, and returns those tables the first time and
6342 thereafter. This reduces the size of the code by about 2K bytes, in
6343 exchange for a little execution time. However, BUILDFIXED should not be
6344 used for threaded applications, since the rewriting of the tables and virgin
6345 may not be thread-safe.
6349 var lenfix, distfix; // We have no pointers in JS, so keep tables separate
6351 function fixedtables(state) {
6352 /* build fixed huffman tables if first call (may not be thread safe) */
6356 lenfix = new utils.Buf32(512);
6357 distfix = new utils.Buf32(32);
6359 /* literal/length table */
6361 while (sym < 144) { state.lens[sym++] = 8; }
6362 while (sym < 256) { state.lens[sym++] = 9; }
6363 while (sym < 280) { state.lens[sym++] = 7; }
6364 while (sym < 288) { state.lens[sym++] = 8; }
6366 inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
6368 /* distance table */
6370 while (sym < 32) { state.lens[sym++] = 5; }
6372 inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
6374 /* do this just once */
6378 state.lencode = lenfix;
6380 state.distcode = distfix;
6386 Update the window with the last wsize (normally 32K) bytes written before
6387 returning. If window does not exist yet, create it. This is only called
6388 when a window is already in use, or when output has been written during this
6389 inflate call, but the end of the deflate stream has not been reached yet.
6390 It is also called to create a window for dictionary data when a dictionary
6393 Providing output buffers larger than 32K to inflate() should provide a speed
6394 advantage, since only the last 32K of output is copied to the sliding window
6395 upon return from inflate(), and since all distances after the first 32K of
6396 output will fall in the output data, making match copies simpler and faster.
6397 The advantage may be dependent on the size of the processor's data caches.
6399 function updatewindow(strm, src, end, copy) {
6401 var state = strm.state;
6403 /* if it hasn't been done already, allocate space for the window */
6404 if (state.window === null) {
6405 state.wsize = 1 << state.wbits;
6409 state.window = new utils.Buf8(state.wsize);
6412 /* copy state->wsize or less output bytes into the circular window */
6413 if (copy >= state.wsize) {
6414 utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
6416 state.whave = state.wsize;
6419 dist = state.wsize - state.wnext;
6423 //zmemcpy(state->window + state->wnext, end - copy, dist);
6424 utils.arraySet(state.window,src, end - copy, dist, state.wnext);
6427 //zmemcpy(state->window, end - copy, copy);
6428 utils.arraySet(state.window,src, end - copy, copy, 0);
6430 state.whave = state.wsize;
6433 state.wnext += dist;
6434 if (state.wnext === state.wsize) { state.wnext = 0; }
6435 if (state.whave < state.wsize) { state.whave += dist; }
6441 function inflate(strm, flush) {
6443 var input, output; // input/output buffers
6444 var next; /* next input INDEX */
6445 var put; /* next output INDEX */
6446 var have, left; /* available input and output */
6447 var hold; /* bit buffer */
6448 var bits; /* bits in bit buffer */
6449 var _in, _out; /* save starting available input and output */
6450 var copy; /* number of stored or match bytes to copy */
6451 var from; /* where to copy match bytes from */
6453 var here = 0; /* current decoding table entry */
6454 var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
6455 //var last; /* parent table entry */
6456 var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
6457 var len; /* length to copy for repeats, bits to drop */
6458 var ret; /* return code */
6459 var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
6462 var n; // temporary var for NEED_BITS
6464 var order = /* permutation of code lengths */
6465 [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
6468 if (!strm || !strm.state || !strm.output ||
6469 (!strm.input && strm.avail_in !== 0)) {
6470 return Z_STREAM_ERROR;
6474 if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
6478 put = strm.next_out;
6479 output = strm.output;
6480 left = strm.avail_out;
6481 next = strm.next_in;
6483 have = strm.avail_in;
6492 inf_leave: // goto emulation
6494 switch (state.mode) {
6496 if (state.wrap === 0) {
6497 state.mode = TYPEDO;
6502 if (have === 0) { break inf_leave; }
6504 hold += input[next++] << bits;
6508 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
6509 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
6510 //=== CRC2(state.check, hold);
6511 hbuf[0] = hold & 0xff;
6512 hbuf[1] = (hold >>> 8) & 0xff;
6513 state.check = crc32(state.check, hbuf, 2, 0);
6523 state.flags = 0; /* expect zlib header */
6525 state.head.done = false;
6527 if (!(state.wrap & 1) || /* check if zlib header allowed */
6528 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
6529 strm.msg = 'incorrect header check';
6533 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
6534 strm.msg = 'unknown compression method';
6538 //--- DROPBITS(4) ---//
6542 len = (hold & 0x0f)/*BITS(4)*/ + 8;
6543 if (state.wbits === 0) {
6546 else if (len > state.wbits) {
6547 strm.msg = 'invalid window size';
6551 state.dmax = 1 << len;
6552 //Tracev((stderr, "inflate: zlib header ok\n"));
6553 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
6554 state.mode = hold & 0x200 ? DICTID : TYPE;
6561 //=== NEEDBITS(16); */
6563 if (have === 0) { break inf_leave; }
6565 hold += input[next++] << bits;
6570 if ((state.flags & 0xff) !== Z_DEFLATED) {
6571 strm.msg = 'unknown compression method';
6575 if (state.flags & 0xe000) {
6576 strm.msg = 'unknown header flags set';
6581 state.head.text = ((hold >> 8) & 1);
6583 if (state.flags & 0x0200) {
6584 //=== CRC2(state.check, hold);
6585 hbuf[0] = hold & 0xff;
6586 hbuf[1] = (hold >>> 8) & 0xff;
6587 state.check = crc32(state.check, hbuf, 2, 0);
6597 //=== NEEDBITS(32); */
6599 if (have === 0) { break inf_leave; }
6601 hold += input[next++] << bits;
6606 state.head.time = hold;
6608 if (state.flags & 0x0200) {
6609 //=== CRC4(state.check, hold)
6610 hbuf[0] = hold & 0xff;
6611 hbuf[1] = (hold >>> 8) & 0xff;
6612 hbuf[2] = (hold >>> 16) & 0xff;
6613 hbuf[3] = (hold >>> 24) & 0xff;
6614 state.check = crc32(state.check, hbuf, 4, 0);
6624 //=== NEEDBITS(16); */
6626 if (have === 0) { break inf_leave; }
6628 hold += input[next++] << bits;
6633 state.head.xflags = (hold & 0xff);
6634 state.head.os = (hold >> 8);
6636 if (state.flags & 0x0200) {
6637 //=== CRC2(state.check, hold);
6638 hbuf[0] = hold & 0xff;
6639 hbuf[1] = (hold >>> 8) & 0xff;
6640 state.check = crc32(state.check, hbuf, 2, 0);
6650 if (state.flags & 0x0400) {
6651 //=== NEEDBITS(16); */
6653 if (have === 0) { break inf_leave; }
6655 hold += input[next++] << bits;
6659 state.length = hold;
6661 state.head.extra_len = hold;
6663 if (state.flags & 0x0200) {
6664 //=== CRC2(state.check, hold);
6665 hbuf[0] = hold & 0xff;
6666 hbuf[1] = (hold >>> 8) & 0xff;
6667 state.check = crc32(state.check, hbuf, 2, 0);
6675 else if (state.head) {
6676 state.head.extra = null/*Z_NULL*/;
6681 if (state.flags & 0x0400) {
6682 copy = state.length;
6683 if (copy > have) { copy = have; }
6686 len = state.head.extra_len - state.length;
6687 if (!state.head.extra) {
6688 // Use untyped array for more conveniend processing later
6689 state.head.extra = new Array(state.head.extra_len);
6695 // extra field is limited to 65536 bytes
6696 // - no need for additional size check
6698 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
6701 //zmemcpy(state.head.extra + len, next,
6702 // len + copy > state.head.extra_max ?
6703 // state.head.extra_max - len : copy);
6705 if (state.flags & 0x0200) {
6706 state.check = crc32(state.check, input, copy, next);
6710 state.length -= copy;
6712 if (state.length) { break inf_leave; }
6718 if (state.flags & 0x0800) {
6719 if (have === 0) { break inf_leave; }
6722 // TODO: 2 or 1 bytes?
6723 len = input[next + copy++];
6724 /* use constant limit because in js we should not preallocate memory */
6725 if (state.head && len &&
6726 (state.length < 65536 /*state.head.name_max*/)) {
6727 state.head.name += String.fromCharCode(len);
6729 } while (len && copy < have);
6731 if (state.flags & 0x0200) {
6732 state.check = crc32(state.check, input, copy, next);
6736 if (len) { break inf_leave; }
6738 else if (state.head) {
6739 state.head.name = null;
6742 state.mode = COMMENT;
6745 if (state.flags & 0x1000) {
6746 if (have === 0) { break inf_leave; }
6749 len = input[next + copy++];
6750 /* use constant limit because in js we should not preallocate memory */
6751 if (state.head && len &&
6752 (state.length < 65536 /*state.head.comm_max*/)) {
6753 state.head.comment += String.fromCharCode(len);
6755 } while (len && copy < have);
6756 if (state.flags & 0x0200) {
6757 state.check = crc32(state.check, input, copy, next);
6761 if (len) { break inf_leave; }
6763 else if (state.head) {
6764 state.head.comment = null;
6769 if (state.flags & 0x0200) {
6770 //=== NEEDBITS(16); */
6772 if (have === 0) { break inf_leave; }
6774 hold += input[next++] << bits;
6778 if (hold !== (state.check & 0xffff)) {
6779 strm.msg = 'header crc mismatch';
6789 state.head.hcrc = ((state.flags >> 9) & 1);
6790 state.head.done = true;
6792 strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
6796 //=== NEEDBITS(32); */
6798 if (have === 0) { break inf_leave; }
6800 hold += input[next++] << bits;
6804 strm.adler = state.check = ZSWAP32(hold);
6812 if (state.havedict === 0) {
6814 strm.next_out = put;
6815 strm.avail_out = left;
6816 strm.next_in = next;
6817 strm.avail_in = have;
6823 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
6827 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
6831 //--- BYTEBITS() ---//
6838 //=== NEEDBITS(3); */
6840 if (have === 0) { break inf_leave; }
6842 hold += input[next++] << bits;
6846 state.last = (hold & 0x01)/*BITS(1)*/;
6847 //--- DROPBITS(1) ---//
6852 switch ((hold & 0x03)/*BITS(2)*/) {
6853 case 0: /* stored block */
6854 //Tracev((stderr, "inflate: stored block%s\n",
6855 // state.last ? " (last)" : ""));
6856 state.mode = STORED;
6858 case 1: /* fixed block */
6860 //Tracev((stderr, "inflate: fixed codes block%s\n",
6861 // state.last ? " (last)" : ""));
6862 state.mode = LEN_; /* decode codes */
6863 if (flush === Z_TREES) {
6864 //--- DROPBITS(2) ---//
6871 case 2: /* dynamic block */
6872 //Tracev((stderr, "inflate: dynamic codes block%s\n",
6873 // state.last ? " (last)" : ""));
6877 strm.msg = 'invalid block type';
6880 //--- DROPBITS(2) ---//
6886 //--- BYTEBITS() ---// /* go to byte boundary */
6890 //=== NEEDBITS(32); */
6892 if (have === 0) { break inf_leave; }
6894 hold += input[next++] << bits;
6898 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
6899 strm.msg = 'invalid stored block lengths';
6903 state.length = hold & 0xffff;
6904 //Tracev((stderr, "inflate: stored length %u\n",
6911 if (flush === Z_TREES) { break inf_leave; }
6917 copy = state.length;
6919 if (copy > have) { copy = have; }
6920 if (copy > left) { copy = left; }
6921 if (copy === 0) { break inf_leave; }
6922 //--- zmemcpy(put, next, copy); ---
6923 utils.arraySet(output, input, next, copy, put);
6929 state.length -= copy;
6932 //Tracev((stderr, "inflate: stored end\n"));
6936 //=== NEEDBITS(14); */
6938 if (have === 0) { break inf_leave; }
6940 hold += input[next++] << bits;
6944 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
6945 //--- DROPBITS(5) ---//
6949 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
6950 //--- DROPBITS(5) ---//
6954 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
6955 //--- DROPBITS(4) ---//
6959 //#ifndef PKZIP_BUG_WORKAROUND
6960 if (state.nlen > 286 || state.ndist > 30) {
6961 strm.msg = 'too many length or distance symbols';
6966 //Tracev((stderr, "inflate: table sizes ok\n"));
6968 state.mode = LENLENS;
6971 while (state.have < state.ncode) {
6974 if (have === 0) { break inf_leave; }
6976 hold += input[next++] << bits;
6980 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
6981 //--- DROPBITS(3) ---//
6986 while (state.have < 19) {
6987 state.lens[order[state.have++]] = 0;
6989 // We have separate tables & no pointers. 2 commented lines below not needed.
6990 //state.next = state.codes;
6991 //state.lencode = state.next;
6992 // Switch to use dynamic table
6993 state.lencode = state.lendyn;
6996 opts = {bits: state.lenbits};
6997 ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
6998 state.lenbits = opts.bits;
7001 strm.msg = 'invalid code lengths set';
7005 //Tracev((stderr, "inflate: code lengths ok\n"));
7007 state.mode = CODELENS;
7010 while (state.have < state.nlen + state.ndist) {
7012 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
7013 here_bits = here >>> 24;
7014 here_op = (here >>> 16) & 0xff;
7015 here_val = here & 0xffff;
7017 if ((here_bits) <= bits) { break; }
7018 //--- PULLBYTE() ---//
7019 if (have === 0) { break inf_leave; }
7021 hold += input[next++] << bits;
7025 if (here_val < 16) {
7026 //--- DROPBITS(here.bits) ---//
7027 hold >>>= here_bits;
7030 state.lens[state.have++] = here_val;
7033 if (here_val === 16) {
7034 //=== NEEDBITS(here.bits + 2);
7037 if (have === 0) { break inf_leave; }
7039 hold += input[next++] << bits;
7043 //--- DROPBITS(here.bits) ---//
7044 hold >>>= here_bits;
7047 if (state.have === 0) {
7048 strm.msg = 'invalid bit length repeat';
7052 len = state.lens[state.have - 1];
7053 copy = 3 + (hold & 0x03);//BITS(2);
7054 //--- DROPBITS(2) ---//
7059 else if (here_val === 17) {
7060 //=== NEEDBITS(here.bits + 3);
7063 if (have === 0) { break inf_leave; }
7065 hold += input[next++] << bits;
7069 //--- DROPBITS(here.bits) ---//
7070 hold >>>= here_bits;
7074 copy = 3 + (hold & 0x07);//BITS(3);
7075 //--- DROPBITS(3) ---//
7081 //=== NEEDBITS(here.bits + 7);
7084 if (have === 0) { break inf_leave; }
7086 hold += input[next++] << bits;
7090 //--- DROPBITS(here.bits) ---//
7091 hold >>>= here_bits;
7095 copy = 11 + (hold & 0x7f);//BITS(7);
7096 //--- DROPBITS(7) ---//
7101 if (state.have + copy > state.nlen + state.ndist) {
7102 strm.msg = 'invalid bit length repeat';
7107 state.lens[state.have++] = len;
7112 /* handle error breaks in while */
7113 if (state.mode === BAD) { break; }
7115 /* check for end-of-block code (better have one) */
7116 if (state.lens[256] === 0) {
7117 strm.msg = 'invalid code -- missing end-of-block';
7122 /* build code tables -- note: do not change the lenbits or distbits
7123 values here (9 and 6) without reading the comments in inftrees.h
7124 concerning the ENOUGH constants, which depend on those values */
7127 opts = {bits: state.lenbits};
7128 ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
7129 // We have separate tables & no pointers. 2 commented lines below not needed.
7130 // state.next_index = opts.table_index;
7131 state.lenbits = opts.bits;
7132 // state.lencode = state.next;
7135 strm.msg = 'invalid literal/lengths set';
7141 //state.distcode.copy(state.codes);
7142 // Switch to use dynamic table
7143 state.distcode = state.distdyn;
7144 opts = {bits: state.distbits};
7145 ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
7146 // We have separate tables & no pointers. 2 commented lines below not needed.
7147 // state.next_index = opts.table_index;
7148 state.distbits = opts.bits;
7149 // state.distcode = state.next;
7152 strm.msg = 'invalid distances set';
7156 //Tracev((stderr, 'inflate: codes ok\n'));
7158 if (flush === Z_TREES) { break inf_leave; }
7164 if (have >= 6 && left >= 258) {
7166 strm.next_out = put;
7167 strm.avail_out = left;
7168 strm.next_in = next;
7169 strm.avail_in = have;
7173 inflate_fast(strm, _out);
7175 put = strm.next_out;
7176 output = strm.output;
7177 left = strm.avail_out;
7178 next = strm.next_in;
7180 have = strm.avail_in;
7185 if (state.mode === TYPE) {
7192 here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
7193 here_bits = here >>> 24;
7194 here_op = (here >>> 16) & 0xff;
7195 here_val = here & 0xffff;
7197 if (here_bits <= bits) { break; }
7198 //--- PULLBYTE() ---//
7199 if (have === 0) { break inf_leave; }
7201 hold += input[next++] << bits;
7205 if (here_op && (here_op & 0xf0) === 0) {
7206 last_bits = here_bits;
7208 last_val = here_val;
7210 here = state.lencode[last_val +
7211 ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
7212 here_bits = here >>> 24;
7213 here_op = (here >>> 16) & 0xff;
7214 here_val = here & 0xffff;
7216 if ((last_bits + here_bits) <= bits) { break; }
7217 //--- PULLBYTE() ---//
7218 if (have === 0) { break inf_leave; }
7220 hold += input[next++] << bits;
7224 //--- DROPBITS(last.bits) ---//
7225 hold >>>= last_bits;
7228 state.back += last_bits;
7230 //--- DROPBITS(here.bits) ---//
7231 hold >>>= here_bits;
7234 state.back += here_bits;
7235 state.length = here_val;
7236 if (here_op === 0) {
7237 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
7238 // "inflate: literal '%c'\n" :
7239 // "inflate: literal 0x%02x\n", here.val));
7244 //Tracevv((stderr, "inflate: end of block\n"));
7250 strm.msg = 'invalid literal/length code';
7254 state.extra = here_op & 15;
7255 state.mode = LENEXT;
7259 //=== NEEDBITS(state.extra);
7262 if (have === 0) { break inf_leave; }
7264 hold += input[next++] << bits;
7268 state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
7269 //--- DROPBITS(state.extra) ---//
7270 hold >>>= state.extra;
7271 bits -= state.extra;
7273 state.back += state.extra;
7275 //Tracevv((stderr, "inflate: length %u\n", state.length));
7276 state.was = state.length;
7281 here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
7282 here_bits = here >>> 24;
7283 here_op = (here >>> 16) & 0xff;
7284 here_val = here & 0xffff;
7286 if ((here_bits) <= bits) { break; }
7287 //--- PULLBYTE() ---//
7288 if (have === 0) { break inf_leave; }
7290 hold += input[next++] << bits;
7294 if ((here_op & 0xf0) === 0) {
7295 last_bits = here_bits;
7297 last_val = here_val;
7299 here = state.distcode[last_val +
7300 ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
7301 here_bits = here >>> 24;
7302 here_op = (here >>> 16) & 0xff;
7303 here_val = here & 0xffff;
7305 if ((last_bits + here_bits) <= bits) { break; }
7306 //--- PULLBYTE() ---//
7307 if (have === 0) { break inf_leave; }
7309 hold += input[next++] << bits;
7313 //--- DROPBITS(last.bits) ---//
7314 hold >>>= last_bits;
7317 state.back += last_bits;
7319 //--- DROPBITS(here.bits) ---//
7320 hold >>>= here_bits;
7323 state.back += here_bits;
7325 strm.msg = 'invalid distance code';
7329 state.offset = here_val;
7330 state.extra = (here_op) & 15;
7331 state.mode = DISTEXT;
7335 //=== NEEDBITS(state.extra);
7338 if (have === 0) { break inf_leave; }
7340 hold += input[next++] << bits;
7344 state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
7345 //--- DROPBITS(state.extra) ---//
7346 hold >>>= state.extra;
7347 bits -= state.extra;
7349 state.back += state.extra;
7351 //#ifdef INFLATE_STRICT
7352 if (state.offset > state.dmax) {
7353 strm.msg = 'invalid distance too far back';
7358 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
7362 if (left === 0) { break inf_leave; }
7364 if (state.offset > copy) { /* copy from window */
7365 copy = state.offset - copy;
7366 if (copy > state.whave) {
7368 strm.msg = 'invalid distance too far back';
7372 // (!) This block is disabled in zlib defailts,
7373 // don't enable it for binary compatibility
7374 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
7375 // Trace((stderr, "inflate.c too far\n"));
7376 // copy -= state.whave;
7377 // if (copy > state.length) { copy = state.length; }
7378 // if (copy > left) { copy = left; }
7380 // state.length -= copy;
7382 // output[put++] = 0;
7383 // } while (--copy);
7384 // if (state.length === 0) { state.mode = LEN; }
7388 if (copy > state.wnext) {
7389 copy -= state.wnext;
7390 from = state.wsize - copy;
7393 from = state.wnext - copy;
7395 if (copy > state.length) { copy = state.length; }
7396 from_source = state.window;
7398 else { /* copy from output */
7399 from_source = output;
7400 from = put - state.offset;
7401 copy = state.length;
7403 if (copy > left) { copy = left; }
7405 state.length -= copy;
7407 output[put++] = from_source[from++];
7409 if (state.length === 0) { state.mode = LEN; }
7412 if (left === 0) { break inf_leave; }
7413 output[put++] = state.length;
7421 if (have === 0) { break inf_leave; }
7423 // Use '|' insdead of '+' to make sure that result is signed
7424 hold |= input[next++] << bits;
7429 strm.total_out += _out;
7430 state.total += _out;
7432 strm.adler = state.check =
7433 /*UPDATE(state.check, put - _out, _out);*/
7434 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
7438 // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
7439 if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
7440 strm.msg = 'incorrect data check';
7448 //Tracev((stderr, "inflate: check matches trailer\n"));
7450 state.mode = LENGTH;
7453 if (state.wrap && state.flags) {
7456 if (have === 0) { break inf_leave; }
7458 hold += input[next++] << bits;
7462 if (hold !== (state.total & 0xffffffff)) {
7463 strm.msg = 'incorrect length check';
7471 //Tracev((stderr, "inflate: length matches trailer\n"));
7486 return Z_STREAM_ERROR;
7490 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
7493 Return from inflate(), updating the total counts and the check value.
7494 If there was no progress during the inflate() call, return a buffer
7495 error. Call updatewindow() to create and/or update the window state.
7496 Note: a memory error from inflate() is non-recoverable.
7500 strm.next_out = put;
7501 strm.avail_out = left;
7502 strm.next_in = next;
7503 strm.avail_in = have;
7508 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
7509 (state.mode < CHECK || flush !== Z_FINISH))) {
7510 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
7515 _in -= strm.avail_in;
7516 _out -= strm.avail_out;
7517 strm.total_in += _in;
7518 strm.total_out += _out;
7519 state.total += _out;
7520 if (state.wrap && _out) {
7521 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
7522 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
7524 strm.data_type = state.bits + (state.last ? 64 : 0) +
7525 (state.mode === TYPE ? 128 : 0) +
7526 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
7527 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
7533 function inflateEnd(strm) {
7535 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
7536 return Z_STREAM_ERROR;
7539 var state = strm.state;
7541 state.window = null;
7547 function inflateGetHeader(strm, head) {
7551 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
7553 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
7555 /* save header structure */
7562 exports.inflateReset = inflateReset;
7563 exports.inflateReset2 = inflateReset2;
7564 exports.inflateResetKeep = inflateResetKeep;
7565 exports.inflateInit = inflateInit;
7566 exports.inflateInit2 = inflateInit2;
7567 exports.inflate = inflate;
7568 exports.inflateEnd = inflateEnd;
7569 exports.inflateGetHeader = inflateGetHeader;
7570 exports.inflateInfo = 'pako inflate (from Nodeca project)';
7573 exports.inflateCopy = inflateCopy;
7574 exports.inflateGetDictionary = inflateGetDictionary;
7575 exports.inflateMark = inflateMark;
7576 exports.inflatePrime = inflatePrime;
7577 exports.inflateSetDictionary = inflateSetDictionary;
7578 exports.inflateSync = inflateSync;
7579 exports.inflateSyncPoint = inflateSyncPoint;
7580 exports.inflateUndermine = inflateUndermine;
7582 },{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(_dereq_,module,exports){
7586 var utils = _dereq_('../utils/common');
7589 var ENOUGH_LENS = 852;
7590 var ENOUGH_DISTS = 592;
7591 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
7597 var lbase = [ /* Length codes 257..285 base */
7598 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
7599 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
7602 var lext = [ /* Length codes 257..285 extra */
7603 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
7604 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
7607 var dbase = [ /* Distance codes 0..29 base */
7608 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
7609 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
7610 8193, 12289, 16385, 24577, 0, 0
7613 var dext = [ /* Distance codes 0..29 extra */
7614 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
7615 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
7616 28, 28, 29, 29, 64, 64
7619 module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
7621 var bits = opts.bits;
7622 //here = opts.here; /* table entry for duplication */
7624 var len = 0; /* a code's length in bits */
7625 var sym = 0; /* index of code symbols */
7626 var min = 0, max = 0; /* minimum and maximum code lengths */
7627 var root = 0; /* number of index bits for root table */
7628 var curr = 0; /* number of index bits for current table */
7629 var drop = 0; /* code bits to drop for sub-table */
7630 var left = 0; /* number of prefix codes available */
7631 var used = 0; /* code entries in table used */
7632 var huff = 0; /* Huffman code */
7633 var incr; /* for incrementing code, index */
7634 var fill; /* index for replicating entries */
7635 var low; /* low bits for current root entry */
7636 var mask; /* mask for low root bits */
7637 var next; /* next available space in table */
7638 var base = null; /* base value table to use */
7640 // var shoextra; /* extra bits table to use */
7641 var end; /* use base and extra for symbol > end */
7642 var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
7643 var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
7645 var extra_index = 0;
7647 var here_bits, here_op, here_val;
7650 Process a set of code lengths to create a canonical Huffman code. The
7651 code lengths are lens[0..codes-1]. Each length corresponds to the
7652 symbols 0..codes-1. The Huffman code is generated by first sorting the
7653 symbols by length from short to long, and retaining the symbol order
7654 for codes with equal lengths. Then the code starts with all zero bits
7655 for the first code of the shortest length, and the codes are integer
7656 increments for the same length, and zeros are appended as the length
7657 increases. For the deflate format, these bits are stored backwards
7658 from their more natural integer increment ordering, and so when the
7659 decoding tables are built in the large loop below, the integer codes
7660 are incremented backwards.
7662 This routine assumes, but does not check, that all of the entries in
7663 lens[] are in the range 0..MAXBITS. The caller must assure this.
7664 1..MAXBITS is interpreted as that code length. zero means that that
7665 symbol does not occur in this code.
7667 The codes are sorted by computing a count of codes for each length,
7668 creating from that a table of starting indices for each length in the
7669 sorted table, and then entering the symbols in order in the sorted
7670 table. The sorted table is work[], with that space being provided by
7673 The length counts are used for other purposes as well, i.e. finding
7674 the minimum and maximum length codes, determining if there are any
7675 codes at all, checking for a valid set of lengths, and looking ahead
7676 at length counts to determine sub-table sizes when building the
7680 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
7681 for (len = 0; len <= MAXBITS; len++) {
7684 for (sym = 0; sym < codes; sym++) {
7685 count[lens[lens_index + sym]]++;
7688 /* bound code lengths, force root to be within code lengths */
7690 for (max = MAXBITS; max >= 1; max--) {
7691 if (count[max] !== 0) { break; }
7696 if (max === 0) { /* no symbols to code at all */
7697 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
7698 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
7699 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
7700 table[table_index++] = (1 << 24) | (64 << 16) | 0;
7703 //table.op[opts.table_index] = 64;
7704 //table.bits[opts.table_index] = 1;
7705 //table.val[opts.table_index++] = 0;
7706 table[table_index++] = (1 << 24) | (64 << 16) | 0;
7709 return 0; /* no symbols, but wait for decoding to report error */
7711 for (min = 1; min < max; min++) {
7712 if (count[min] !== 0) { break; }
7718 /* check for an over-subscribed or incomplete set of lengths */
7720 for (len = 1; len <= MAXBITS; len++) {
7725 } /* over-subscribed */
7727 if (left > 0 && (type === CODES || max !== 1)) {
7728 return -1; /* incomplete set */
7731 /* generate offsets into symbol table for each length for sorting */
7733 for (len = 1; len < MAXBITS; len++) {
7734 offs[len + 1] = offs[len] + count[len];
7737 /* sort symbols by length, by symbol order within each length */
7738 for (sym = 0; sym < codes; sym++) {
7739 if (lens[lens_index + sym] !== 0) {
7740 work[offs[lens[lens_index + sym]]++] = sym;
7745 Create and fill in decoding tables. In this loop, the table being
7746 filled is at next and has curr index bits. The code being used is huff
7747 with length len. That code is converted to an index by dropping drop
7748 bits off of the bottom. For codes where len is less than drop + curr,
7749 those top drop + curr - len bits are incremented through all values to
7750 fill the table with replicated entries.
7752 root is the number of index bits for the root table. When len exceeds
7753 root, sub-tables are created pointed to by the root entry with an index
7754 of the low root bits of huff. This is saved in low to check for when a
7755 new sub-table should be started. drop is zero when the root table is
7756 being filled, and drop is root when sub-tables are being filled.
7758 When a new sub-table is needed, it is necessary to look ahead in the
7759 code lengths to determine what size sub-table is needed. The length
7760 counts are used for this, and so count[] is decremented as codes are
7761 entered in the tables.
7763 used keeps track of how many table entries have been allocated from the
7764 provided *table space. It is checked for LENS and DIST tables against
7765 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
7766 the initial root table size constants. See the comments in inftrees.h
7767 for more information.
7769 sym increments through all symbols, and the loop terminates when
7770 all codes of length max, i.e. all codes, have been processed. This
7771 routine permits incomplete codes, so another loop after this one fills
7772 in the rest of the decoding tables with invalid code markers.
7775 /* set up for code type */
7776 // poor man optimization - use if-else instead of switch,
7777 // to avoid deopts in old v8
7778 if (type === CODES) {
7779 base = extra = work; /* dummy value--not used */
7781 } else if (type === LENS) {
7787 } else { /* DISTS */
7793 /* initialize opts for loop */
7794 huff = 0; /* starting code */
7795 sym = 0; /* starting code symbol */
7796 len = min; /* starting code length */
7797 next = table_index; /* current table to fill in */
7798 curr = root; /* current table index bits */
7799 drop = 0; /* current bits to drop from code for index */
7800 low = -1; /* trigger new sub-table when len > root */
7801 used = 1 << root; /* use root table entries */
7802 mask = used - 1; /* mask for comparing low */
7804 /* check available table space */
7805 if ((type === LENS && used > ENOUGH_LENS) ||
7806 (type === DISTS && used > ENOUGH_DISTS)) {
7811 /* process all codes and make table entries */
7814 /* create table entry */
7815 here_bits = len - drop;
7816 if (work[sym] < end) {
7818 here_val = work[sym];
7820 else if (work[sym] > end) {
7821 here_op = extra[extra_index + work[sym]];
7822 here_val = base[base_index + work[sym]];
7825 here_op = 32 + 64; /* end of block */
7829 /* replicate for those indices with low len bits equal to huff */
7830 incr = 1 << (len - drop);
7832 min = fill; /* save offset to next table */
7835 table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
7836 } while (fill !== 0);
7838 /* backwards increment the len-bit code huff */
7839 incr = 1 << (len - 1);
7840 while (huff & incr) {
7850 /* go to next symbol, update count, len */
7852 if (--count[len] === 0) {
7853 if (len === max) { break; }
7854 len = lens[lens_index + work[sym]];
7857 /* create new sub-table if needed */
7858 if (len > root && (huff & mask) !== low) {
7859 /* if first time, transition to sub-tables */
7864 /* increment past last table */
7865 next += min; /* here min is 1 << curr */
7867 /* determine length of next table */
7870 while (curr + drop < max) {
7871 left -= count[curr + drop];
7872 if (left <= 0) { break; }
7877 /* check for enough space */
7879 if ((type === LENS && used > ENOUGH_LENS) ||
7880 (type === DISTS && used > ENOUGH_DISTS)) {
7884 /* point entry in root table to sub-table */
7886 /*table.op[low] = curr;
7887 table.bits[low] = root;
7888 table.val[low] = next - opts.table_index;*/
7889 table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
7893 /* fill in remaining table entry if code is incomplete (guaranteed to have
7894 at most one remaining entry, since if the code is incomplete, the
7895 maximum code length that was allowed to get this far is one bit) */
7897 //table.op[next + huff] = 64; /* invalid code marker */
7898 //table.bits[next + huff] = len - drop;
7899 //table.val[next + huff] = 0;
7900 table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
7903 /* set return parameters */
7904 //opts.table_index += used;
7909 },{"../utils/common":27}],37:[function(_dereq_,module,exports){
7913 '2': 'need dictionary', /* Z_NEED_DICT 2 */
7914 '1': 'stream end', /* Z_STREAM_END 1 */
7915 '0': '', /* Z_OK 0 */
7916 '-1': 'file error', /* Z_ERRNO (-1) */
7917 '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
7918 '-3': 'data error', /* Z_DATA_ERROR (-3) */
7919 '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
7920 '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
7921 '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
7923 },{}],38:[function(_dereq_,module,exports){
7927 var utils = _dereq_('../utils/common');
7929 /* Public constants ==========================================================*/
7930 /* ===========================================================================*/
7933 //var Z_FILTERED = 1;
7934 //var Z_HUFFMAN_ONLY = 2;
7937 //var Z_DEFAULT_STRATEGY = 0;
7939 /* Possible values of the data_type field (though see inflate()) */
7942 //var Z_ASCII = 1; // = Z_TEXT
7945 /*============================================================================*/
7948 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
7952 var STORED_BLOCK = 0;
7953 var STATIC_TREES = 1;
7955 /* The three kinds of block type */
7958 var MAX_MATCH = 258;
7959 /* The minimum and maximum match lengths */
7962 /* ===========================================================================
7963 * Internal compression state.
7966 var LENGTH_CODES = 29;
7967 /* number of length codes, not counting the special END_BLOCK code */
7970 /* number of literal bytes 0..255 */
7972 var L_CODES = LITERALS + 1 + LENGTH_CODES;
7973 /* number of Literal or Length codes, including the END_BLOCK code */
7976 /* number of distance codes */
7979 /* number of codes used to transfer the bit lengths */
7981 var HEAP_SIZE = 2*L_CODES + 1;
7982 /* maximum heap size */
7985 /* All codes must not exceed MAX_BITS bits */
7988 /* size of bit buffer in bi_buf */
7991 /* ===========================================================================
7995 var MAX_BL_BITS = 7;
7996 /* Bit length codes must not exceed MAX_BL_BITS bits */
7998 var END_BLOCK = 256;
7999 /* end of block literal code */
8002 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
8005 /* repeat a zero length 3-10 times (3 bits of repeat count) */
8007 var REPZ_11_138 = 18;
8008 /* repeat a zero length 11-138 times (7 bits of repeat count) */
8010 var extra_lbits = /* extra bits for each length code */
8011 [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];
8013 var extra_dbits = /* extra bits for each distance code */
8014 [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];
8016 var extra_blbits = /* extra bits for each bit length code */
8017 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
8020 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
8021 /* The lengths of the bit length codes are sent in order of decreasing
8022 * probability, to avoid transmitting the lengths for unused bit length codes.
8025 /* ===========================================================================
8026 * Local data. These are initialized only once.
8029 // We pre-fill arrays with 0 to avoid uninitialized gaps
8031 var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
8033 // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
8034 var static_ltree = new Array((L_CODES+2) * 2);
8036 /* The static literal tree. Since the bit lengths are imposed, there is no
8037 * need for the L_CODES extra codes used during heap construction. However
8038 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
8042 var static_dtree = new Array(D_CODES * 2);
8044 /* The static distance tree. (Actually a trivial tree since all codes use
8048 var _dist_code = new Array(DIST_CODE_LEN);
8050 /* Distance codes. The first 256 values correspond to the distances
8051 * 3 .. 258, the last 256 values correspond to the top 8 bits of
8052 * the 15 bit distances.
8055 var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
8057 /* length code for each normalized match length (0 == MIN_MATCH) */
8059 var base_length = new Array(LENGTH_CODES);
8061 /* First normalized length for each code (0 = MIN_MATCH) */
8063 var base_dist = new Array(D_CODES);
8065 /* First normalized distance for each code (0 = distance of 1) */
8068 var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
8070 this.static_tree = static_tree; /* static tree or NULL */
8071 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
8072 this.extra_base = extra_base; /* base index for extra_bits */
8073 this.elems = elems; /* max number of elements in the tree */
8074 this.max_length = max_length; /* max bit length for the codes */
8076 // show if `static_tree` has data or dummy - needed for monomorphic objects
8077 this.has_stree = static_tree && static_tree.length;
8086 var TreeDesc = function(dyn_tree, stat_desc) {
8087 this.dyn_tree = dyn_tree; /* the dynamic tree */
8088 this.max_code = 0; /* largest code with non zero frequency */
8089 this.stat_desc = stat_desc; /* the corresponding static tree */
8094 function d_code(dist) {
8095 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
8099 /* ===========================================================================
8100 * Output a short LSB first on the stream.
8101 * IN assertion: there is enough room in pendingBuf.
8103 function put_short (s, w) {
8104 // put_byte(s, (uch)((w) & 0xff));
8105 // put_byte(s, (uch)((ush)(w) >> 8));
8106 s.pending_buf[s.pending++] = (w) & 0xff;
8107 s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
8111 /* ===========================================================================
8112 * Send a value on a given number of bits.
8113 * IN assertion: length <= 16 and value fits in length bits.
8115 function send_bits(s, value, length) {
8116 if (s.bi_valid > (Buf_size - length)) {
8117 s.bi_buf |= (value << s.bi_valid) & 0xffff;
8118 put_short(s, s.bi_buf);
8119 s.bi_buf = value >> (Buf_size - s.bi_valid);
8120 s.bi_valid += length - Buf_size;
8122 s.bi_buf |= (value << s.bi_valid) & 0xffff;
8123 s.bi_valid += length;
8128 function send_code(s, c, tree) {
8129 send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
8133 /* ===========================================================================
8134 * Reverse the first len bits of a code, using straightforward code (a faster
8135 * method would use a table)
8136 * IN assertion: 1 <= len <= 15
8138 function bi_reverse(code, len) {
8144 } while (--len > 0);
8149 /* ===========================================================================
8150 * Flush the bit buffer, keeping at most 7 bits in it.
8152 function bi_flush(s) {
8153 if (s.bi_valid === 16) {
8154 put_short(s, s.bi_buf);
8158 } else if (s.bi_valid >= 8) {
8159 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
8166 /* ===========================================================================
8167 * Compute the optimal bit lengths for a tree and update the total bit length
8168 * for the current block.
8169 * IN assertion: the fields freq and dad are set, heap[heap_max] and
8170 * above are the tree nodes sorted by increasing frequency.
8171 * OUT assertions: the field len is set to the optimal bit length, the
8172 * array bl_count contains the frequencies for each bit length.
8173 * The length opt_len is updated; static_len is also updated if stree is
8176 function gen_bitlen(s, desc)
8177 // deflate_state *s;
8178 // tree_desc *desc; /* the tree descriptor */
8180 var tree = desc.dyn_tree;
8181 var max_code = desc.max_code;
8182 var stree = desc.stat_desc.static_tree;
8183 var has_stree = desc.stat_desc.has_stree;
8184 var extra = desc.stat_desc.extra_bits;
8185 var base = desc.stat_desc.extra_base;
8186 var max_length = desc.stat_desc.max_length;
8187 var h; /* heap index */
8188 var n, m; /* iterate over the tree elements */
8189 var bits; /* bit length */
8190 var xbits; /* extra bits */
8191 var f; /* frequency */
8192 var overflow = 0; /* number of elements with bit length too large */
8194 for (bits = 0; bits <= MAX_BITS; bits++) {
8195 s.bl_count[bits] = 0;
8198 /* In a first pass, compute the optimal bit lengths (which may
8199 * overflow in the case of the bit length tree).
8201 tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
8203 for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
8205 bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
8206 if (bits > max_length) {
8210 tree[n*2 + 1]/*.Len*/ = bits;
8211 /* We overwrite tree[n].Dad which is no longer needed */
8213 if (n > max_code) { continue; } /* not a leaf node */
8218 xbits = extra[n-base];
8220 f = tree[n * 2]/*.Freq*/;
8221 s.opt_len += f * (bits + xbits);
8223 s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
8226 if (overflow === 0) { return; }
8228 // Trace((stderr,"\nbit length overflow\n"));
8229 /* This happens for example on obj2 and pic of the Calgary corpus */
8231 /* Find the first bit length which could increase: */
8233 bits = max_length-1;
8234 while (s.bl_count[bits] === 0) { bits--; }
8235 s.bl_count[bits]--; /* move one leaf down the tree */
8236 s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
8237 s.bl_count[max_length]--;
8238 /* The brother of the overflow item also moves one step up,
8239 * but this does not affect bl_count[max_length]
8242 } while (overflow > 0);
8244 /* Now recompute all bit lengths, scanning in increasing frequency.
8245 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
8246 * lengths instead of fixing only the wrong ones. This idea is taken
8247 * from 'ar' written by Haruhiko Okumura.)
8249 for (bits = max_length; bits !== 0; bits--) {
8250 n = s.bl_count[bits];
8253 if (m > max_code) { continue; }
8254 if (tree[m*2 + 1]/*.Len*/ !== bits) {
8255 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
8256 s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
8257 tree[m*2 + 1]/*.Len*/ = bits;
8265 /* ===========================================================================
8266 * Generate the codes for a given tree and bit counts (which need not be
8268 * IN assertion: the array bl_count contains the bit length statistics for
8269 * the given tree and the field len is set for all tree elements.
8270 * OUT assertion: the field code is set for all tree elements of non
8273 function gen_codes(tree, max_code, bl_count)
8274 // ct_data *tree; /* the tree to decorate */
8275 // int max_code; /* largest code with non zero frequency */
8276 // ushf *bl_count; /* number of codes at each bit length */
8278 var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
8279 var code = 0; /* running code value */
8280 var bits; /* bit index */
8281 var n; /* code index */
8283 /* The distribution counts are first used to generate the code values
8284 * without bit reversal.
8286 for (bits = 1; bits <= MAX_BITS; bits++) {
8287 next_code[bits] = code = (code + bl_count[bits-1]) << 1;
8289 /* Check that the bit counts in bl_count are consistent. The last code
8292 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
8293 // "inconsistent bit counts");
8294 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
8296 for (n = 0; n <= max_code; n++) {
8297 var len = tree[n*2 + 1]/*.Len*/;
8298 if (len === 0) { continue; }
8299 /* Now reverse the bits */
8300 tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
8302 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
8303 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
8308 /* ===========================================================================
8309 * Initialize the various 'constant' tables.
8311 function tr_static_init() {
8312 var n; /* iterates over tree elements */
8313 var bits; /* bit counter */
8314 var length; /* length value */
8315 var code; /* code value */
8316 var dist; /* distance index */
8317 var bl_count = new Array(MAX_BITS+1);
8318 /* number of codes at each bit length for an optimal tree */
8320 // do check in _tr_init()
8321 //if (static_init_done) return;
8323 /* For some embedded targets, global variables are not initialized: */
8324 /*#ifdef NO_INIT_GLOBAL_POINTERS
8325 static_l_desc.static_tree = static_ltree;
8326 static_l_desc.extra_bits = extra_lbits;
8327 static_d_desc.static_tree = static_dtree;
8328 static_d_desc.extra_bits = extra_dbits;
8329 static_bl_desc.extra_bits = extra_blbits;
8332 /* Initialize the mapping length (0..255) -> length code (0..28) */
8334 for (code = 0; code < LENGTH_CODES-1; code++) {
8335 base_length[code] = length;
8336 for (n = 0; n < (1<<extra_lbits[code]); n++) {
8337 _length_code[length++] = code;
8340 //Assert (length == 256, "tr_static_init: length != 256");
8341 /* Note that the length 255 (match length 258) can be represented
8342 * in two different ways: code 284 + 5 bits or code 285, so we
8343 * overwrite length_code[255] to use the best encoding:
8345 _length_code[length-1] = code;
8347 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
8349 for (code = 0 ; code < 16; code++) {
8350 base_dist[code] = dist;
8351 for (n = 0; n < (1<<extra_dbits[code]); n++) {
8352 _dist_code[dist++] = code;
8355 //Assert (dist == 256, "tr_static_init: dist != 256");
8356 dist >>= 7; /* from now on, all distances are divided by 128 */
8357 for ( ; code < D_CODES; code++) {
8358 base_dist[code] = dist << 7;
8359 for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
8360 _dist_code[256 + dist++] = code;
8363 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
8365 /* Construct the codes of the static literal tree */
8366 for (bits = 0; bits <= MAX_BITS; bits++) {
8372 static_ltree[n*2 + 1]/*.Len*/ = 8;
8377 static_ltree[n*2 + 1]/*.Len*/ = 9;
8382 static_ltree[n*2 + 1]/*.Len*/ = 7;
8387 static_ltree[n*2 + 1]/*.Len*/ = 8;
8391 /* Codes 286 and 287 do not exist, but we must include them in the
8392 * tree construction to get a canonical Huffman tree (longest code
8395 gen_codes(static_ltree, L_CODES+1, bl_count);
8397 /* The static distance tree is trivial: */
8398 for (n = 0; n < D_CODES; n++) {
8399 static_dtree[n*2 + 1]/*.Len*/ = 5;
8400 static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
8403 // Now data ready and we can init static trees
8404 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
8405 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
8406 static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
8408 //static_init_done = true;
8412 /* ===========================================================================
8413 * Initialize a new block.
8415 function init_block(s) {
8416 var n; /* iterates over tree elements */
8418 /* Initialize the trees. */
8419 for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
8420 for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
8421 for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
8423 s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
8424 s.opt_len = s.static_len = 0;
8425 s.last_lit = s.matches = 0;
8429 /* ===========================================================================
8430 * Flush the bit buffer and align the output on a byte boundary
8432 function bi_windup(s)
8434 if (s.bi_valid > 8) {
8435 put_short(s, s.bi_buf);
8436 } else if (s.bi_valid > 0) {
8437 //put_byte(s, (Byte)s->bi_buf);
8438 s.pending_buf[s.pending++] = s.bi_buf;
8444 /* ===========================================================================
8445 * Copy a stored block, storing first the length and its
8446 * one's complement if requested.
8448 function copy_block(s, buf, len, header)
8450 //charf *buf; /* the input data */
8451 //unsigned len; /* its length */
8452 //int header; /* true if block header must be written */
8454 bi_windup(s); /* align on byte boundary */
8461 // put_byte(s, *buf++);
8463 utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
8467 /* ===========================================================================
8468 * Compares to subtrees, using the tree depth as tie breaker when
8469 * the subtrees have equal frequency. This minimizes the worst case length.
8471 function smaller(tree, n, m, depth) {
8474 return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
8475 (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
8478 /* ===========================================================================
8479 * Restore the heap property by moving down the tree starting at node k,
8480 * exchanging a node with the smallest of its two sons if necessary, stopping
8481 * when the heap property is re-established (each father smaller than its
8484 function pqdownheap(s, tree, k)
8485 // deflate_state *s;
8486 // ct_data *tree; /* the tree to restore */
8487 // int k; /* node to move down */
8490 var j = k << 1; /* left son of k */
8491 while (j <= s.heap_len) {
8492 /* Set j to the smallest of the two sons: */
8493 if (j < s.heap_len &&
8494 smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
8497 /* Exit if v is smaller than both sons */
8498 if (smaller(tree, v, s.heap[j], s.depth)) { break; }
8500 /* Exchange v with the smallest son */
8501 s.heap[k] = s.heap[j];
8504 /* And continue down the tree, setting j to the left son of k */
8512 // var SMALLEST = 1;
8514 /* ===========================================================================
8515 * Send the block data compressed using the given Huffman trees
8517 function compress_block(s, ltree, dtree)
8518 // deflate_state *s;
8519 // const ct_data *ltree; /* literal tree */
8520 // const ct_data *dtree; /* distance tree */
8522 var dist; /* distance of matched string */
8523 var lc; /* match length or unmatched char (if dist == 0) */
8524 var lx = 0; /* running index in l_buf */
8525 var code; /* the code to send */
8526 var extra; /* number of extra bits to send */
8528 if (s.last_lit !== 0) {
8530 dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
8531 lc = s.pending_buf[s.l_buf + lx];
8535 send_code(s, lc, ltree); /* send a literal byte */
8536 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
8538 /* Here, lc is the match length - MIN_MATCH */
8539 code = _length_code[lc];
8540 send_code(s, code+LITERALS+1, ltree); /* send the length code */
8541 extra = extra_lbits[code];
8543 lc -= base_length[code];
8544 send_bits(s, lc, extra); /* send the extra length bits */
8546 dist--; /* dist is now the match distance - 1 */
8547 code = d_code(dist);
8548 //Assert (code < D_CODES, "bad d_code");
8550 send_code(s, code, dtree); /* send the distance code */
8551 extra = extra_dbits[code];
8553 dist -= base_dist[code];
8554 send_bits(s, dist, extra); /* send the extra distance bits */
8556 } /* literal or match pair ? */
8558 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
8559 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
8560 // "pendingBuf overflow");
8562 } while (lx < s.last_lit);
8565 send_code(s, END_BLOCK, ltree);
8569 /* ===========================================================================
8570 * Construct one Huffman tree and assigns the code bit strings and lengths.
8571 * Update the total bit length for the current block.
8572 * IN assertion: the field freq is set for all tree elements.
8573 * OUT assertions: the fields len and code are set to the optimal bit length
8574 * and corresponding code. The length opt_len is updated; static_len is
8575 * also updated if stree is not null. The field max_code is set.
8577 function build_tree(s, desc)
8578 // deflate_state *s;
8579 // tree_desc *desc; /* the tree descriptor */
8581 var tree = desc.dyn_tree;
8582 var stree = desc.stat_desc.static_tree;
8583 var has_stree = desc.stat_desc.has_stree;
8584 var elems = desc.stat_desc.elems;
8585 var n, m; /* iterate over heap elements */
8586 var max_code = -1; /* largest code with non zero frequency */
8587 var node; /* new node being created */
8589 /* Construct the initial heap, with least frequent element in
8590 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
8591 * heap[0] is not used.
8594 s.heap_max = HEAP_SIZE;
8596 for (n = 0; n < elems; n++) {
8597 if (tree[n * 2]/*.Freq*/ !== 0) {
8598 s.heap[++s.heap_len] = max_code = n;
8602 tree[n*2 + 1]/*.Len*/ = 0;
8606 /* The pkzip format requires that at least one distance code exists,
8607 * and that at least one bit should be sent even if there is only one
8608 * possible code. So to avoid special checks later on we force at least
8609 * two codes of non zero frequency.
8611 while (s.heap_len < 2) {
8612 node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
8613 tree[node * 2]/*.Freq*/ = 1;
8618 s.static_len -= stree[node*2 + 1]/*.Len*/;
8620 /* node is 0 or 1 so it does not have extra bits */
8622 desc.max_code = max_code;
8624 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
8625 * establish sub-heaps of increasing lengths:
8627 for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
8629 /* Construct the Huffman tree by repeatedly combining the least two
8632 node = elems; /* next internal node of the tree */
8634 //pqremove(s, tree, n); /* n = node of least frequency */
8636 n = s.heap[1/*SMALLEST*/];
8637 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
8638 pqdownheap(s, tree, 1/*SMALLEST*/);
8641 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
8643 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
8644 s.heap[--s.heap_max] = m;
8646 /* Create a new node father of n and m */
8647 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
8648 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
8649 tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
8651 /* and insert the new node in the heap */
8652 s.heap[1/*SMALLEST*/] = node++;
8653 pqdownheap(s, tree, 1/*SMALLEST*/);
8655 } while (s.heap_len >= 2);
8657 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
8659 /* At this point, the fields freq and dad are set. We can now
8660 * generate the bit lengths.
8662 gen_bitlen(s, desc);
8664 /* The field len is now set, we can generate the bit codes */
8665 gen_codes(tree, max_code, s.bl_count);
8669 /* ===========================================================================
8670 * Scan a literal or distance tree to determine the frequencies of the codes
8671 * in the bit length tree.
8673 function scan_tree(s, tree, max_code)
8674 // deflate_state *s;
8675 // ct_data *tree; /* the tree to be scanned */
8676 // int max_code; /* and its largest code of non zero frequency */
8678 var n; /* iterates over all tree elements */
8679 var prevlen = -1; /* last emitted length */
8680 var curlen; /* length of current code */
8682 var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
8684 var count = 0; /* repeat count of the current code */
8685 var max_count = 7; /* max repeat count */
8686 var min_count = 4; /* min repeat count */
8688 if (nextlen === 0) {
8692 tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
8694 for (n = 0; n <= max_code; n++) {
8696 nextlen = tree[(n+1)*2 + 1]/*.Len*/;
8698 if (++count < max_count && curlen === nextlen) {
8701 } else if (count < min_count) {
8702 s.bl_tree[curlen * 2]/*.Freq*/ += count;
8704 } else if (curlen !== 0) {
8706 if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
8707 s.bl_tree[REP_3_6*2]/*.Freq*/++;
8709 } else if (count <= 10) {
8710 s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
8713 s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
8719 if (nextlen === 0) {
8723 } else if (curlen === nextlen) {
8735 /* ===========================================================================
8736 * Send a literal or distance tree in compressed form, using the codes in
8739 function send_tree(s, tree, max_code)
8740 // deflate_state *s;
8741 // ct_data *tree; /* the tree to be scanned */
8742 // int max_code; /* and its largest code of non zero frequency */
8744 var n; /* iterates over all tree elements */
8745 var prevlen = -1; /* last emitted length */
8746 var curlen; /* length of current code */
8748 var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
8750 var count = 0; /* repeat count of the current code */
8751 var max_count = 7; /* max repeat count */
8752 var min_count = 4; /* min repeat count */
8754 /* tree[max_code+1].Len = -1; */ /* guard already set */
8755 if (nextlen === 0) {
8760 for (n = 0; n <= max_code; n++) {
8762 nextlen = tree[(n+1)*2 + 1]/*.Len*/;
8764 if (++count < max_count && curlen === nextlen) {
8767 } else if (count < min_count) {
8768 do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
8770 } else if (curlen !== 0) {
8771 if (curlen !== prevlen) {
8772 send_code(s, curlen, s.bl_tree);
8775 //Assert(count >= 3 && count <= 6, " 3_6?");
8776 send_code(s, REP_3_6, s.bl_tree);
8777 send_bits(s, count-3, 2);
8779 } else if (count <= 10) {
8780 send_code(s, REPZ_3_10, s.bl_tree);
8781 send_bits(s, count-3, 3);
8784 send_code(s, REPZ_11_138, s.bl_tree);
8785 send_bits(s, count-11, 7);
8790 if (nextlen === 0) {
8794 } else if (curlen === nextlen) {
8806 /* ===========================================================================
8807 * Construct the Huffman tree for the bit lengths and return the index in
8808 * bl_order of the last bit length code to send.
8810 function build_bl_tree(s) {
8811 var max_blindex; /* index of last bit length code of non zero freq */
8813 /* Determine the bit length frequencies for literal and distance trees */
8814 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
8815 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
8817 /* Build the bit length tree: */
8818 build_tree(s, s.bl_desc);
8819 /* opt_len now includes the length of the tree representations, except
8820 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
8823 /* Determine the number of bit length codes to send. The pkzip format
8824 * requires that at least 4 bit length codes be sent. (appnote.txt says
8825 * 3 but the actual value used is 4.)
8827 for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
8828 if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
8832 /* Update opt_len to include the bit length tree and counts */
8833 s.opt_len += 3*(max_blindex+1) + 5+5+4;
8834 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
8835 // s->opt_len, s->static_len));
8841 /* ===========================================================================
8842 * Send the header for a block using dynamic Huffman trees: the counts, the
8843 * lengths of the bit length codes, the literal tree and the distance tree.
8844 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
8846 function send_all_trees(s, lcodes, dcodes, blcodes)
8847 // deflate_state *s;
8848 // int lcodes, dcodes, blcodes; /* number of codes for each tree */
8850 var rank; /* index in bl_order */
8852 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
8853 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
8854 // "too many codes");
8855 //Tracev((stderr, "\nbl counts: "));
8856 send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
8857 send_bits(s, dcodes-1, 5);
8858 send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
8859 for (rank = 0; rank < blcodes; rank++) {
8860 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
8861 send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
8863 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
8865 send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
8866 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
8868 send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
8869 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
8873 /* ===========================================================================
8874 * Check if the data type is TEXT or BINARY, using the following algorithm:
8875 * - TEXT if the two conditions below are satisfied:
8876 * a) There are no non-portable control characters belonging to the
8877 * "black list" (0..6, 14..25, 28..31).
8878 * b) There is at least one printable character belonging to the
8879 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
8880 * - BINARY otherwise.
8881 * - The following partially-portable control characters form a
8882 * "gray list" that is ignored in this detection algorithm:
8883 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
8884 * IN assertion: the fields Freq of dyn_ltree are set.
8886 function detect_data_type(s) {
8887 /* black_mask is the bit mask of black-listed bytes
8888 * set bits 0..6, 14..25, and 28..31
8889 * 0xf3ffc07f = binary 11110011111111111100000001111111
8891 var black_mask = 0xf3ffc07f;
8894 /* Check for non-textual ("black-listed") bytes. */
8895 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
8896 if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
8901 /* Check for textual ("white-listed") bytes. */
8902 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
8903 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
8906 for (n = 32; n < LITERALS; n++) {
8907 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
8912 /* There are no "black-listed" or "white-listed" bytes:
8913 * this stream either is empty or has tolerated ("gray-listed") bytes only.
8919 var static_init_done = false;
8921 /* ===========================================================================
8922 * Initialize the tree data structures for a new zlib stream.
8924 function _tr_init(s)
8927 if (!static_init_done) {
8929 static_init_done = true;
8932 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
8933 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
8934 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
8939 /* Initialize the first block of the first file: */
8944 /* ===========================================================================
8945 * Send a stored block
8947 function _tr_stored_block(s, buf, stored_len, last)
8949 //charf *buf; /* input block */
8950 //ulg stored_len; /* length of input block */
8951 //int last; /* one if this is the last block for a file */
8953 send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
8954 copy_block(s, buf, stored_len, true); /* with header */
8958 /* ===========================================================================
8959 * Send one empty static block to give enough lookahead for inflate.
8960 * This takes 10 bits, of which 7 may remain in the bit buffer.
8962 function _tr_align(s) {
8963 send_bits(s, STATIC_TREES<<1, 3);
8964 send_code(s, END_BLOCK, static_ltree);
8969 /* ===========================================================================
8970 * Determine the best encoding for the current block: dynamic trees, static
8971 * trees or store, and output the encoded block to the zip file.
8973 function _tr_flush_block(s, buf, stored_len, last)
8975 //charf *buf; /* input block, or NULL if too old */
8976 //ulg stored_len; /* length of input block */
8977 //int last; /* one if this is the last block for a file */
8979 var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
8980 var max_blindex = 0; /* index of last bit length code of non zero freq */
8982 /* Build the Huffman trees unless a stored block is forced */
8985 /* Check if the file is binary or text */
8986 if (s.strm.data_type === Z_UNKNOWN) {
8987 s.strm.data_type = detect_data_type(s);
8990 /* Construct the literal and distance trees */
8991 build_tree(s, s.l_desc);
8992 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
8995 build_tree(s, s.d_desc);
8996 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
8998 /* At this point, opt_len and static_len are the total bit lengths of
8999 * the compressed block data, excluding the tree representations.
9002 /* Build the bit length tree for the above two trees, and get the index
9003 * in bl_order of the last bit length code to send.
9005 max_blindex = build_bl_tree(s);
9007 /* Determine the best encoding. Compute the block lengths in bytes. */
9008 opt_lenb = (s.opt_len+3+7) >>> 3;
9009 static_lenb = (s.static_len+3+7) >>> 3;
9011 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
9012 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
9015 if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
9018 // Assert(buf != (char*)0, "lost buf");
9019 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
9022 if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
9023 /* 4: two words for the lengths */
9025 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
9026 * Otherwise we can't have processed more than WSIZE input bytes since
9027 * the last block flush, because compression would have been
9028 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
9029 * transform a block into a stored block.
9031 _tr_stored_block(s, buf, stored_len, last);
9033 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
9035 send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
9036 compress_block(s, static_ltree, static_dtree);
9039 send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
9040 send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
9041 compress_block(s, s.dyn_ltree, s.dyn_dtree);
9043 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
9044 /* The above check is made mod 2^32, for files larger than 512 MB
9045 * and uLong implemented on 32 bits.
9052 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
9053 // s->compressed_len-7*last));
9056 /* ===========================================================================
9057 * Save the match info and tally the frequency counts. Return true if
9058 * the current block must be flushed.
9060 function _tr_tally(s, dist, lc)
9061 // deflate_state *s;
9062 // unsigned dist; /* distance of matched string */
9063 // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
9065 //var out_length, in_length, dcode;
9067 s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
9068 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
9070 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
9074 /* lc is the unmatched char */
9075 s.dyn_ltree[lc*2]/*.Freq*/++;
9078 /* Here, lc is the match length - MIN_MATCH */
9079 dist--; /* dist = match distance - 1 */
9080 //Assert((ush)dist < (ush)MAX_DIST(s) &&
9081 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
9082 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
9084 s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
9085 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
9088 // (!) This block is disabled in zlib defailts,
9089 // don't enable it for binary compatibility
9091 //#ifdef TRUNCATE_BLOCK
9092 // /* Try to guess if it is profitable to stop the current block here */
9093 // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
9094 // /* Compute an upper bound for the compressed length */
9095 // out_length = s.last_lit*8;
9096 // in_length = s.strstart - s.block_start;
9098 // for (dcode = 0; dcode < D_CODES; dcode++) {
9099 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
9101 // out_length >>>= 3;
9102 // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
9103 // // s->last_lit, in_length, out_length,
9104 // // 100L - out_length*100L/in_length));
9105 // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
9111 return (s.last_lit === s.lit_bufsize-1);
9112 /* We avoid equality with lit_bufsize because of wraparound at 64K
9113 * on 16 bit machines and because stored blocks are restricted to
9118 exports._tr_init = _tr_init;
9119 exports._tr_stored_block = _tr_stored_block;
9120 exports._tr_flush_block = _tr_flush_block;
9121 exports._tr_tally = _tr_tally;
9122 exports._tr_align = _tr_align;
9123 },{"../utils/common":27}],39:[function(_dereq_,module,exports){
9127 function ZStream() {
9128 /* next input byte */
9129 this.input = null; // JS specific, because we have no pointers
9131 /* number of bytes available at input */
9133 /* total number of input bytes read so far */
9135 /* next output byte should be put there */
9136 this.output = null; // JS specific, because we have no pointers
9138 /* remaining free space at output */
9140 /* total number of bytes output so far */
9142 /* last error message, NULL if no error */
9143 this.msg = ''/*Z_NULL*/;
9144 /* not visible by applications */
9146 /* best guess about the data type: binary or text */
9147 this.data_type = 2/*Z_UNKNOWN*/;
9148 /* adler32 value of the uncompressed data */
9152 module.exports = ZStream;