1 /** 2 * @license 3 * @licstart 4 JSZip - A Javascript class for generating and reading zip files 5 <http://stuartk.com/jszip> 6 7 (c) 2009-2014 Stuart Knightley <stuart [at] stuartk.com> 8 Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown. 9 10 JSZip uses the library pako released under the MIT license : 11 https://github.com/nodeca/pako/blob/master/LICENSE 12 * @licend 13 */ 14 !function(e){ 15 // 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()} 16 var globalScope = typeof window !== "undefined" ? window : (typeof global !== "undefined" ? global : {}), 17 externs = globalScope.externs || (globalScope.externs = {}); 18 externs.JSZip = e(); 19 }(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){ 20 'use strict'; 21 // private property 22 var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 23 24 25 // public method for encoding 26 exports.encode = function(input, utf8) { 27 var output = ""; 28 var chr1, chr2, chr3, enc1, enc2, enc3, enc4; 29 var i = 0; 30 31 while (i < input.length) { 32 33 chr1 = input.charCodeAt(i++); 34 chr2 = input.charCodeAt(i++); 35 chr3 = input.charCodeAt(i++); 36 37 enc1 = chr1 >> 2; 38 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); 39 enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); 40 enc4 = chr3 & 63; 41 42 if (isNaN(chr2)) { 43 enc3 = enc4 = 64; 44 } 45 else if (isNaN(chr3)) { 46 enc4 = 64; 47 } 48 49 output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); 50 51 } 52 53 return output; 54 }; 55 56 // public method for decoding 57 exports.decode = function(input, utf8) { 58 var output = ""; 59 var chr1, chr2, chr3; 60 var enc1, enc2, enc3, enc4; 61 var i = 0; 62 63 input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); 64 65 while (i < input.length) { 66 67 enc1 = _keyStr.indexOf(input.charAt(i++)); 68 enc2 = _keyStr.indexOf(input.charAt(i++)); 69 enc3 = _keyStr.indexOf(input.charAt(i++)); 70 enc4 = _keyStr.indexOf(input.charAt(i++)); 71 72 chr1 = (enc1 << 2) | (enc2 >> 4); 73 chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); 74 chr3 = ((enc3 & 3) << 6) | enc4; 75 76 output = output + String.fromCharCode(chr1); 77 78 if (enc3 != 64) { 79 output = output + String.fromCharCode(chr2); 80 } 81 if (enc4 != 64) { 82 output = output + String.fromCharCode(chr3); 83 } 84 85 } 86 87 return output; 88 89 }; 90 91 },{}],2:[function(_dereq_,module,exports){ 92 'use strict'; 93 function CompressedObject() { 94 this.compressedSize = 0; 95 this.uncompressedSize = 0; 96 this.crc32 = 0; 97 this.compressionMethod = null; 98 this.compressedContent = null; 99 } 100 101 CompressedObject.prototype = { 102 /** 103 * Return the decompressed content in an unspecified format. 104 * The format will depend on the decompressor. 105 * @return {Object} the decompressed content. 106 */ 107 getContent: function() { 108 return null; // see implementation 109 }, 110 /** 111 * Return the compressed content in an unspecified format. 112 * The format will depend on the compressed conten source. 113 * @return {Object} the compressed content. 114 */ 115 getCompressedContent: function() { 116 return null; // see implementation 117 } 118 }; 119 module.exports = CompressedObject; 120 121 },{}],3:[function(_dereq_,module,exports){ 122 'use strict'; 123 exports.STORE = { 124 magic: "\x00\x00", 125 compress: function(content) { 126 return content; // no compression 127 }, 128 uncompress: function(content) { 129 return content; // no compression 130 }, 131 compressInputType: null, 132 uncompressInputType: null 133 }; 134 exports.DEFLATE = _dereq_('./flate'); 135 136 },{"./flate":8}],4:[function(_dereq_,module,exports){ 137 'use strict'; 138 139 var utils = _dereq_('./utils'); 140 141 var table = [ 142 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 143 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 144 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 145 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 146 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 147 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 148 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 149 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 150 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 151 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 152 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 153 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 154 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 155 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 156 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 157 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 158 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 159 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 160 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 161 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 162 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 163 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 164 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 165 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 166 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 167 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 168 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 169 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 170 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 171 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 172 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 173 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 174 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 175 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 176 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 177 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 178 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 179 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 180 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 181 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 182 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 183 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 184 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 185 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 186 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 187 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 188 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 189 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 190 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 191 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 192 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 193 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 194 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 195 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 196 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 197 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 198 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 199 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 200 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 201 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 202 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 203 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 204 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 205 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D 206 ]; 207 208 /** 209 * 210 * Javascript crc32 211 * http://www.webtoolkit.info/ 212 * 213 */ 214 module.exports = function crc32(input, crc) { 215 if (typeof input === "undefined" || !input.length) { 216 return 0; 217 } 218 219 var isArray = utils.getTypeOf(input) !== "string"; 220 221 if (typeof(crc) == "undefined") { 222 crc = 0; 223 } 224 var x = 0; 225 var y = 0; 226 var b = 0; 227 228 crc = crc ^ (-1); 229 for (var i = 0, iTop = input.length; i < iTop; i++) { 230 b = isArray ? input[i] : input.charCodeAt(i); 231 y = (crc ^ b) & 0xFF; 232 x = table[y]; 233 crc = (crc >>> 8) ^ x; 234 } 235 236 return crc ^ (-1); 237 }; 238 // vim: set shiftwidth=4 softtabstop=4: 239 240 },{"./utils":21}],5:[function(_dereq_,module,exports){ 241 'use strict'; 242 var utils = _dereq_('./utils'); 243 244 function DataReader(data) { 245 this.data = null; // type : see implementation 246 this.length = 0; 247 this.index = 0; 248 } 249 DataReader.prototype = { 250 /** 251 * Check that the offset will not go too far. 252 * @param {string} offset the additional offset to check. 253 * @throws {Error} an Error if the offset is out of bounds. 254 */ 255 checkOffset: function(offset) { 256 this.checkIndex(this.index + offset); 257 }, 258 /** 259 * Check that the specifed index will not be too far. 260 * @param {string} newIndex the index to check. 261 * @throws {Error} an Error if the index is out of bounds. 262 */ 263 checkIndex: function(newIndex) { 264 if (this.length < newIndex || newIndex < 0) { 265 throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?"); 266 } 267 }, 268 /** 269 * Change the index. 270 * @param {number} newIndex The new index. 271 * @throws {Error} if the new index is out of the data. 272 */ 273 setIndex: function(newIndex) { 274 this.checkIndex(newIndex); 275 this.index = newIndex; 276 }, 277 /** 278 * Skip the next n bytes. 279 * @param {number} n the number of bytes to skip. 280 * @throws {Error} if the new index is out of the data. 281 */ 282 skip: function(n) { 283 this.setIndex(this.index + n); 284 }, 285 /** 286 * Get the byte at the specified index. 287 * @param {number} i the index to use. 288 * @return {number} a byte. 289 */ 290 byteAt: function(i) { 291 // see implementations 292 }, 293 /** 294 * Get the next number with a given byte size. 295 * @param {number} size the number of bytes to read. 296 * @return {number} the corresponding number. 297 */ 298 readInt: function(size) { 299 var result = 0, 300 i; 301 this.checkOffset(size); 302 for (i = this.index + size - 1; i >= this.index; i--) { 303 result = (result << 8) + this.byteAt(i); 304 } 305 this.index += size; 306 return result; 307 }, 308 /** 309 * Get the next string with a given byte size. 310 * @param {number} size the number of bytes to read. 311 * @return {string} the corresponding string. 312 */ 313 readString: function(size) { 314 return utils.transformTo("string", this.readData(size)); 315 }, 316 /** 317 * Get raw data without conversion, <size> bytes. 318 * @param {number} size the number of bytes to read. 319 * @return {Object} the raw data, implementation specific. 320 */ 321 readData: function(size) { 322 // see implementations 323 }, 324 /** 325 * Find the last occurence of a zip signature (4 bytes). 326 * @param {string} sig the signature to find. 327 * @return {number} the index of the last occurence, -1 if not found. 328 */ 329 lastIndexOfSignature: function(sig) { 330 // see implementations 331 }, 332 /** 333 * Get the next date. 334 * @return {Date} the date. 335 */ 336 readDate: function() { 337 var dostime = this.readInt(4); 338 return new Date( 339 ((dostime >> 25) & 0x7f) + 1980, // year 340 ((dostime >> 21) & 0x0f) - 1, // month 341 (dostime >> 16) & 0x1f, // day 342 (dostime >> 11) & 0x1f, // hour 343 (dostime >> 5) & 0x3f, // minute 344 (dostime & 0x1f) << 1); // second 345 } 346 }; 347 module.exports = DataReader; 348 349 },{"./utils":21}],6:[function(_dereq_,module,exports){ 350 'use strict'; 351 exports.base64 = false; 352 exports.binary = false; 353 exports.dir = false; 354 exports.createFolders = false; 355 exports.date = null; 356 exports.compression = null; 357 exports.comment = null; 358 359 },{}],7:[function(_dereq_,module,exports){ 360 'use strict'; 361 var utils = _dereq_('./utils'); 362 363 /** 364 * @deprecated 365 * This function will be removed in a future version without replacement. 366 */ 367 exports.string2binary = function(str) { 368 return utils.string2binary(str); 369 }; 370 371 /** 372 * @deprecated 373 * This function will be removed in a future version without replacement. 374 */ 375 exports.string2Uint8Array = function(str) { 376 return utils.transformTo("uint8array", str); 377 }; 378 379 /** 380 * @deprecated 381 * This function will be removed in a future version without replacement. 382 */ 383 exports.uint8Array2String = function(array) { 384 return utils.transformTo("string", array); 385 }; 386 387 /** 388 * @deprecated 389 * This function will be removed in a future version without replacement. 390 */ 391 exports.string2Blob = function(str) { 392 var buffer = utils.transformTo("arraybuffer", str); 393 return utils.arrayBuffer2Blob(buffer); 394 }; 395 396 /** 397 * @deprecated 398 * This function will be removed in a future version without replacement. 399 */ 400 exports.arrayBuffer2Blob = function(buffer) { 401 return utils.arrayBuffer2Blob(buffer); 402 }; 403 404 /** 405 * @deprecated 406 * This function will be removed in a future version without replacement. 407 */ 408 exports.transformTo = function(outputType, input) { 409 return utils.transformTo(outputType, input); 410 }; 411 412 /** 413 * @deprecated 414 * This function will be removed in a future version without replacement. 415 */ 416 exports.getTypeOf = function(input) { 417 return utils.getTypeOf(input); 418 }; 419 420 /** 421 * @deprecated 422 * This function will be removed in a future version without replacement. 423 */ 424 exports.checkSupport = function(type) { 425 return utils.checkSupport(type); 426 }; 427 428 /** 429 * @deprecated 430 * This value will be removed in a future version without replacement. 431 */ 432 exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS; 433 434 /** 435 * @deprecated 436 * This value will be removed in a future version without replacement. 437 */ 438 exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS; 439 440 441 /** 442 * @deprecated 443 * This function will be removed in a future version without replacement. 444 */ 445 exports.pretty = function(str) { 446 return utils.pretty(str); 447 }; 448 449 /** 450 * @deprecated 451 * This function will be removed in a future version without replacement. 452 */ 453 exports.findCompression = function(compressionMethod) { 454 return utils.findCompression(compressionMethod); 455 }; 456 457 /** 458 * @deprecated 459 * This function will be removed in a future version without replacement. 460 */ 461 exports.isRegExp = function (object) { 462 return utils.isRegExp(object); 463 }; 464 465 466 },{"./utils":21}],8:[function(_dereq_,module,exports){ 467 'use strict'; 468 var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined'); 469 470 var pako = _dereq_("pako"); 471 exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array"; 472 exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array"; 473 474 exports.magic = "\x08\x00"; 475 exports.compress = function(input) { 476 return pako.deflateRaw(input); 477 }; 478 exports.uncompress = function(input) { 479 return pako.inflateRaw(input); 480 }; 481 482 },{"pako":24}],9:[function(_dereq_,module,exports){ 483 'use strict'; 484 485 var base64 = _dereq_('./base64'); 486 487 /** 488 Usage: 489 zip = new JSZip(); 490 zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing"); 491 zip.folder("images").file("smile.gif", base64Data, {base64: true}); 492 zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")}); 493 zip.remove("tempfile"); 494 495 base64zip = zip.generate(); 496 497 **/ 498 499 /** 500 * Representation a of zip file in js 501 * @constructor 502 * @param {(String|ArrayBuffer|Uint8Array)=} data the data to load, if any (optional). 503 * @param {Object=} options the options for creating this objects (optional). 504 */ 505 function JSZip(data, options) { 506 // if this constructor is used without `new`, it adds `new` before itself: 507 if(!(this instanceof JSZip)) return new JSZip(data, options); 508 509 // object containing the files : 510 // { 511 // "folder/" : {...}, 512 // "folder/data.txt" : {...} 513 // } 514 this.files = {}; 515 516 this.comment = null; 517 518 // Where we are in the hierarchy 519 this.root = ""; 520 if (data) { 521 this.load(data, options); 522 } 523 this.clone = function() { 524 var newObj = new JSZip(); 525 for (var i in this) { 526 if (typeof this[i] !== "function") { 527 newObj[i] = this[i]; 528 } 529 } 530 return newObj; 531 }; 532 } 533 JSZip.prototype = _dereq_('./object'); 534 JSZip.prototype.load = _dereq_('./load'); 535 JSZip.support = _dereq_('./support'); 536 JSZip.defaults = _dereq_('./defaults'); 537 538 /** 539 * @deprecated 540 * This namespace will be removed in a future version without replacement. 541 */ 542 JSZip.utils = _dereq_('./deprecatedPublicUtils'); 543 544 JSZip.base64 = { 545 /** 546 * @deprecated 547 * This method will be removed in a future version without replacement. 548 */ 549 encode : function(input) { 550 return base64.encode(input); 551 }, 552 /** 553 * @deprecated 554 * This method will be removed in a future version without replacement. 555 */ 556 decode : function(input) { 557 return base64.decode(input); 558 } 559 }; 560 JSZip.compressions = _dereq_('./compressions'); 561 module.exports = JSZip; 562 563 },{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(_dereq_,module,exports){ 564 'use strict'; 565 var base64 = _dereq_('./base64'); 566 var ZipEntries = _dereq_('./zipEntries'); 567 module.exports = function(data, options) { 568 var files, zipEntries, i, input; 569 options = options || {}; 570 if (options.base64) { 571 data = base64.decode(data); 572 } 573 574 zipEntries = new ZipEntries(data, options); 575 files = zipEntries.files; 576 for (i = 0; i < files.length; i++) { 577 input = files[i]; 578 this.file(input.fileName, input.decompressed, { 579 binary: true, 580 optimizedBinaryString: true, 581 date: input.date, 582 dir: input.dir, 583 comment : input.fileComment.length ? input.fileComment : null, 584 createFolders: options.createFolders 585 }); 586 } 587 if (zipEntries.zipComment.length) { 588 this.comment = zipEntries.zipComment; 589 } 590 591 return this; 592 }; 593 594 },{"./base64":1,"./zipEntries":22}],11:[function(_dereq_,module,exports){ 595 (function (Buffer){ 596 'use strict'; 597 module.exports = function(data, encoding){ 598 return new Buffer(data, encoding); 599 }; 600 module.exports.test = function(b){ 601 return Buffer.isBuffer(b); 602 }; 603 }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined)) 604 },{}],12:[function(_dereq_,module,exports){ 605 'use strict'; 606 var Uint8ArrayReader = _dereq_('./uint8ArrayReader'); 607 608 function NodeBufferReader(data) { 609 this.data = data; 610 this.length = this.data.length; 611 this.index = 0; 612 } 613 NodeBufferReader.prototype = new Uint8ArrayReader(); 614 615 /** 616 * @see DataReader.readData 617 */ 618 NodeBufferReader.prototype.readData = function(size) { 619 this.checkOffset(size); 620 var result = this.data.slice(this.index, this.index + size); 621 this.index += size; 622 return result; 623 }; 624 module.exports = NodeBufferReader; 625 626 },{"./uint8ArrayReader":18}],13:[function(_dereq_,module,exports){ 627 'use strict'; 628 var support = _dereq_('./support'); 629 var utils = _dereq_('./utils'); 630 var crc32 = _dereq_('./crc32'); 631 var signature = _dereq_('./signature'); 632 var defaults = _dereq_('./defaults'); 633 var base64 = _dereq_('./base64'); 634 var compressions = _dereq_('./compressions'); 635 var CompressedObject = _dereq_('./compressedObject'); 636 var nodeBuffer = _dereq_('./nodeBuffer'); 637 var utf8 = _dereq_('./utf8'); 638 var StringWriter = _dereq_('./stringWriter'); 639 var Uint8ArrayWriter = _dereq_('./uint8ArrayWriter'); 640 641 /** 642 * Returns the raw data of a ZipObject, decompress the content if necessary. 643 * @param {ZipObject} file the file to use. 644 * @return {String|ArrayBuffer|Uint8Array|Buffer} the data. 645 */ 646 var getRawData = function(file) { 647 if (file._data instanceof CompressedObject) { 648 file._data = file._data.getContent(); 649 file.options.binary = true; 650 file.options.base64 = false; 651 652 if (utils.getTypeOf(file._data) === "uint8array") { 653 var copy = file._data; 654 // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array. 655 // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file). 656 file._data = new Uint8Array(copy.length); 657 // with an empty Uint8Array, Opera fails with a "Offset larger than array size" 658 if (copy.length !== 0) { 659 file._data.set(copy, 0); 660 } 661 } 662 } 663 return file._data; 664 }; 665 666 /** 667 * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it. 668 * @param {ZipObject} file the file to use. 669 * @return {String|ArrayBuffer|Uint8Array|Buffer} the data. 670 */ 671 var getBinaryData = function(file) { 672 var result = getRawData(file), 673 type = utils.getTypeOf(result); 674 if (type === "string") { 675 if (!file.options.binary) { 676 // unicode text ! 677 // unicode string => binary string is a painful process, check if we can avoid it. 678 if (support.nodebuffer) { 679 return nodeBuffer(result, "utf-8"); 680 } 681 } 682 return file.asBinary(); 683 } 684 return result; 685 }; 686 687 /** 688 * Transform this._data into a string. 689 * @param {function(!string):!string} filter a function String -> String, applied if not null on the result. 690 * @return {String} the string representing this._data. 691 */ 692 var dataToString = function(asUTF8) { 693 var result = getRawData(this); 694 if (result === null || typeof result === "undefined") { 695 return ""; 696 } 697 // if the data is a base64 string, we decode it before checking the encoding ! 698 if (this.options.base64) { 699 result = base64.decode(result); 700 } 701 if (asUTF8 && this.options.binary) { 702 // JSZip.prototype.utf8decode supports arrays as input 703 // skip to array => string step, utf8decode will do it. 704 result = out.utf8decode(result); 705 } 706 else { 707 // no utf8 transformation, do the array => string step. 708 result = utils.transformTo("string", result); 709 } 710 711 if (!asUTF8 && !this.options.binary) { 712 result = utils.transformTo("string", out.utf8encode(result)); 713 } 714 return result; 715 }; 716 /** 717 * A simple object representing a file in the zip file. 718 * @constructor 719 * @param {string} name the name of the file 720 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data 721 * @param {Object} options the options of the file 722 */ 723 var ZipObject = function(name, data, options) { 724 this.name = name; 725 this.dir = options.dir; 726 this.date = options.date; 727 this.comment = options.comment; 728 729 this._data = data; 730 this.options = options; 731 732 /* 733 * This object contains initial values for dir and date. 734 * With them, we can check if the user changed the deprecated metadata in 735 * `ZipObject#options` or not. 736 */ 737 this._initialMetadata = { 738 dir : options.dir, 739 date : options.date 740 }; 741 }; 742 743 ZipObject.prototype = { 744 /** 745 * Return the content as UTF8 string. 746 * @return {string} the UTF8 string. 747 */ 748 asText: function() { 749 return dataToString.call(this, true); 750 }, 751 /** 752 * Returns the binary content. 753 * @return {string} the content as binary. 754 */ 755 asBinary: function() { 756 return dataToString.call(this, false); 757 }, 758 /** 759 * Returns the content as a nodejs Buffer. 760 * @return {Buffer} the content as a Buffer. 761 */ 762 asNodeBuffer: function() { 763 var result = getBinaryData(this); 764 return utils.transformTo("nodebuffer", result); 765 }, 766 /** 767 * Returns the content as an Uint8Array. 768 * @return {Uint8Array} the content as an Uint8Array. 769 */ 770 asUint8Array: function() { 771 var result = getBinaryData(this); 772 return utils.transformTo("uint8array", result); 773 }, 774 /** 775 * Returns the content as an ArrayBuffer. 776 * @return {ArrayBuffer} the content as an ArrayBufer. 777 */ 778 asArrayBuffer: function() { 779 return this.asUint8Array().buffer; 780 } 781 }; 782 783 /** 784 * Transform an integer into a string in hexadecimal. 785 * @private 786 * @param {number} dec the number to convert. 787 * @param {number} bytes the number of bytes to generate. 788 * @returns {string} the result. 789 */ 790 var decToHex = function(dec, bytes) { 791 var hex = "", 792 i; 793 for (i = 0; i < bytes; i++) { 794 hex += String.fromCharCode(dec & 0xff); 795 dec = dec >>> 8; 796 } 797 return hex; 798 }; 799 800 /** 801 * Merge the objects passed as parameters into a new one. 802 * @private 803 * @param {...Object} var_args All objects to merge. 804 * @return {Object} a new object with the data of the others. 805 */ 806 var extend = function() { 807 var result = {}, i, attr; 808 for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers 809 for (attr in arguments[i]) { 810 if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") { 811 result[attr] = arguments[i][attr]; 812 } 813 } 814 } 815 return result; 816 }; 817 818 /** 819 * Transforms the (incomplete) options from the user into the complete 820 * set of options to create a file. 821 * @private 822 * @param {Object} o the options from the user. 823 * @return {Object} the complete set of options. 824 */ 825 var prepareFileAttrs = function(o) { 826 o = o || {}; 827 if (o.base64 === true && (o.binary === null || o.binary === undefined)) { 828 o.binary = true; 829 } 830 o = extend(o, defaults); 831 o.date = o.date || new Date(); 832 if (o.compression !== null) o.compression = o.compression.toUpperCase(); 833 834 return o; 835 }; 836 837 /** 838 * Add a file in the current folder. 839 * @private 840 * @param {string} name the name of the file 841 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file 842 * @param {Object} o the options of the file 843 * @return {Object} the new file. 844 */ 845 var fileAdd = function(name, data, o) { 846 // be sure sub folders exist 847 var dataType = utils.getTypeOf(data), 848 parent; 849 850 o = prepareFileAttrs(o); 851 852 if (o.createFolders && (parent = parentFolder(name))) { 853 folderAdd.call(this, parent, true); 854 } 855 856 if (o.dir || data === null || typeof data === "undefined") { 857 o.base64 = false; 858 o.binary = false; 859 data = null; 860 } 861 else if (dataType === "string") { 862 if (o.binary && !o.base64) { 863 // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask 864 if (o.optimizedBinaryString !== true) { 865 // this is a string, not in a base64 format. 866 // Be sure that this is a correct "binary string" 867 data = utils.string2binary(data); 868 } 869 } 870 } 871 else { // arraybuffer, uint8array, ... 872 o.base64 = false; 873 o.binary = true; 874 875 if (!dataType && !(data instanceof CompressedObject)) { 876 throw new Error("The data of '" + name + "' is in an unsupported format !"); 877 } 878 879 // special case : it's way easier to work with Uint8Array than with ArrayBuffer 880 if (dataType === "arraybuffer") { 881 data = utils.transformTo("uint8array", data); 882 } 883 } 884 885 var object = new ZipObject(name, data, o); 886 this.files[name] = object; 887 return object; 888 }; 889 890 /** 891 * Find the parent folder of the path. 892 * @private 893 * @param {string} path the path to use 894 * @return {string} the parent folder, or "" 895 */ 896 var parentFolder = function (path) { 897 if (path.slice(-1) == '/') { 898 path = path.substring(0, path.length - 1); 899 } 900 var lastSlash = path.lastIndexOf('/'); 901 return (lastSlash > 0) ? path.substring(0, lastSlash) : ""; 902 }; 903 904 /** 905 * Add a (sub) folder in the current folder. 906 * @private 907 * @param {string} name the folder's name 908 * @param {boolean=} [createFolders] If true, automatically create sub 909 * folders. Defaults to false. 910 * @return {Object} the new folder. 911 */ 912 var folderAdd = function(name, createFolders) { 913 // Check the name ends with a / 914 if (name.slice(-1) != "/") { 915 name += "/"; // IE doesn't like substr(-1) 916 } 917 918 createFolders = (typeof createFolders !== 'undefined') ? createFolders : false; 919 920 // Does this folder already exist? 921 if (!this.files[name]) { 922 fileAdd.call(this, name, null, { 923 dir: true, 924 createFolders: createFolders 925 }); 926 } 927 return this.files[name]; 928 }; 929 930 /** 931 * Generate a JSZip.CompressedObject for a given zipOject. 932 * @param {ZipObject} file the object to read. 933 * @param {JSZip.compression} compression the compression to use. 934 * @return {JSZip.CompressedObject} the compressed result. 935 */ 936 var generateCompressedObjectFrom = function(file, compression) { 937 var result = new CompressedObject(), 938 content; 939 940 // the data has not been decompressed, we might reuse things ! 941 if (file._data instanceof CompressedObject) { 942 result.uncompressedSize = file._data.uncompressedSize; 943 result.crc32 = file._data.crc32; 944 945 if (result.uncompressedSize === 0 || file.dir) { 946 compression = compressions['STORE']; 947 result.compressedContent = ""; 948 result.crc32 = 0; 949 } 950 else if (file._data.compressionMethod === compression.magic) { 951 result.compressedContent = file._data.getCompressedContent(); 952 } 953 else { 954 content = file._data.getContent(); 955 // need to decompress / recompress 956 result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content)); 957 } 958 } 959 else { 960 // have uncompressed data 961 content = getBinaryData(file); 962 if (!content || content.length === 0 || file.dir) { 963 compression = compressions['STORE']; 964 content = ""; 965 } 966 result.uncompressedSize = content.length; 967 result.crc32 = crc32(content); 968 result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content)); 969 } 970 971 result.compressedSize = result.compressedContent.length; 972 result.compressionMethod = compression.magic; 973 974 return result; 975 }; 976 977 /** 978 * Generate the various parts used in the construction of the final zip file. 979 * @param {string} name the file name. 980 * @param {ZipObject} file the file content. 981 * @param {JSZip.CompressedObject} compressedObject the compressed object. 982 * @param {number} offset the current offset from the start of the zip file. 983 * @return {object} the zip parts. 984 */ 985 var generateZipParts = function(name, file, compressedObject, offset) { 986 var data = compressedObject.compressedContent, 987 utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), 988 comment = file.comment || "", 989 utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), 990 useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, 991 useUTF8ForComment = utfEncodedComment.length !== comment.length, 992 o = file.options, 993 dosTime, 994 dosDate, 995 extraFields = "", 996 unicodePathExtraField = "", 997 unicodeCommentExtraField = "", 998 dir, date; 999 1000 1001 // handle the deprecated options.dir 1002 if (file._initialMetadata.dir !== file.dir) { 1003 dir = file.dir; 1004 } else { 1005 dir = o.dir; 1006 } 1007 1008 // handle the deprecated options.date 1009 if(file._initialMetadata.date !== file.date) { 1010 date = file.date; 1011 } else { 1012 date = o.date; 1013 } 1014 1015 // date 1016 // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html 1017 // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html 1018 // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html 1019 1020 dosTime = date.getHours(); 1021 dosTime = dosTime << 6; 1022 dosTime = dosTime | date.getMinutes(); 1023 dosTime = dosTime << 5; 1024 dosTime = dosTime | date.getSeconds() / 2; 1025 1026 dosDate = date.getFullYear() - 1980; 1027 dosDate = dosDate << 4; 1028 dosDate = dosDate | (date.getMonth() + 1); 1029 dosDate = dosDate << 5; 1030 dosDate = dosDate | date.getDate(); 1031 1032 if (useUTF8ForFileName) { 1033 // set the unicode path extra field. unzip needs at least one extra 1034 // field to correctly handle unicode path, so using the path is as good 1035 // as any other information. This could improve the situation with 1036 // other archive managers too. 1037 // This field is usually used without the utf8 flag, with a non 1038 // unicode path in the header (winrar, winzip). This helps (a bit) 1039 // with the messy Windows' default compressed folders feature but 1040 // breaks on p7zip which doesn't seek the unicode path extra field. 1041 // So for now, UTF-8 everywhere ! 1042 unicodePathExtraField = 1043 // Version 1044 decToHex(1, 1) + 1045 // NameCRC32 1046 decToHex(crc32(utfEncodedFileName), 4) + 1047 // UnicodeName 1048 utfEncodedFileName; 1049 1050 extraFields += 1051 // Info-ZIP Unicode Path Extra Field 1052 "\x75\x70" + 1053 // size 1054 decToHex(unicodePathExtraField.length, 2) + 1055 // content 1056 unicodePathExtraField; 1057 } 1058 1059 if(useUTF8ForComment) { 1060 1061 unicodeCommentExtraField = 1062 // Version 1063 decToHex(1, 1) + 1064 // CommentCRC32 1065 decToHex(this.crc32(utfEncodedComment), 4) + 1066 // UnicodeName 1067 utfEncodedComment; 1068 1069 extraFields += 1070 // Info-ZIP Unicode Path Extra Field 1071 "\x75\x63" + 1072 // size 1073 decToHex(unicodeCommentExtraField.length, 2) + 1074 // content 1075 unicodeCommentExtraField; 1076 } 1077 1078 var header = ""; 1079 1080 // version needed to extract 1081 header += "\x0A\x00"; 1082 // general purpose bit flag 1083 // set bit 11 if utf8 1084 header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00"; 1085 // compression method 1086 header += compressedObject.compressionMethod; 1087 // last mod file time 1088 header += decToHex(dosTime, 2); 1089 // last mod file date 1090 header += decToHex(dosDate, 2); 1091 // crc-32 1092 header += decToHex(compressedObject.crc32, 4); 1093 // compressed size 1094 header += decToHex(compressedObject.compressedSize, 4); 1095 // uncompressed size 1096 header += decToHex(compressedObject.uncompressedSize, 4); 1097 // file name length 1098 header += decToHex(utfEncodedFileName.length, 2); 1099 // extra field length 1100 header += decToHex(extraFields.length, 2); 1101 1102 1103 var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields; 1104 1105 var dirRecord = signature.CENTRAL_FILE_HEADER + 1106 // version made by (00: DOS) 1107 "\x14\x00" + 1108 // file header (common to file and central directory) 1109 header + 1110 // file comment length 1111 decToHex(utfEncodedComment.length, 2) + 1112 // disk number start 1113 "\x00\x00" + 1114 // internal file attributes TODO 1115 "\x00\x00" + 1116 // external file attributes 1117 (dir === true ? "\x10\x00\x00\x00" : "\x00\x00\x00\x00") + 1118 // relative offset of local header 1119 decToHex(offset, 4) + 1120 // file name 1121 utfEncodedFileName + 1122 // extra field 1123 extraFields + 1124 // file comment 1125 utfEncodedComment; 1126 1127 return { 1128 fileRecord: fileRecord, 1129 dirRecord: dirRecord, 1130 compressedObject: compressedObject 1131 }; 1132 }; 1133 1134 1135 // return the actual prototype of JSZip 1136 var out = { 1137 /** 1138 * Read an existing zip and merge the data in the current JSZip object. 1139 * The implementation is in jszip-load.js, don't forget to include it. 1140 * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load 1141 * @param {Object} options Options for loading the stream. 1142 * options.base64 : is the stream in base64 ? default : false 1143 * @return {JSZip} the current JSZip object 1144 */ 1145 load: function(stream, options) { 1146 throw new Error("Load method is not defined. Is the file jszip-load.js included ?"); 1147 }, 1148 1149 /** 1150 * Filter nested files/folders with the specified function. 1151 * @param {Function} search the predicate to use : 1152 * function (relativePath, file) {...} 1153 * It takes 2 arguments : the relative path and the file. 1154 * @return {Array} An array of matching elements. 1155 */ 1156 filter: function(search) { 1157 var result = [], 1158 filename, relativePath, file, fileClone; 1159 for (filename in this.files) { 1160 if (!this.files.hasOwnProperty(filename)) { 1161 continue; 1162 } 1163 file = this.files[filename]; 1164 // return a new object, don't let the user mess with our internal objects :) 1165 fileClone = new ZipObject(file.name, file._data, extend(file.options)); 1166 relativePath = filename.slice(this.root.length, filename.length); 1167 if (filename.slice(0, this.root.length) === this.root && // the file is in the current root 1168 search(relativePath, fileClone)) { // and the file matches the function 1169 result.push(fileClone); 1170 } 1171 } 1172 return result; 1173 }, 1174 1175 /** 1176 * Add a file to the zip file, or search a file. 1177 * @param {string|RegExp} name The name of the file to add (if data is defined), 1178 * the name of the file to find (if no data) or a regex to match files. 1179 * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded 1180 * @param {Object} o File options 1181 * @return {JSZip|Object|Array} this JSZip object (when adding a file), 1182 * a file (when searching by string) or an array of files (when searching by regex). 1183 */ 1184 file: function(name, data, o) { 1185 if (arguments.length === 1) { 1186 if (utils.isRegExp(name)) { 1187 var regexp = name; 1188 return this.filter(function(relativePath, file) { 1189 return !file.dir && regexp.test(relativePath); 1190 }); 1191 } 1192 else { // text 1193 return this.filter(function(relativePath, file) { 1194 return !file.dir && relativePath === name; 1195 })[0] || null; 1196 } 1197 } 1198 else { // more than one argument : we have data ! 1199 name = this.root + name; 1200 fileAdd.call(this, name, data, o); 1201 } 1202 return this; 1203 }, 1204 1205 /** 1206 * Add a directory to the zip file, or search. 1207 * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders. 1208 * @return {JSZip} an object with the new directory as the root, or an array containing matching folders. 1209 */ 1210 folder: function(arg) { 1211 if (!arg) { 1212 return this; 1213 } 1214 1215 if (utils.isRegExp(arg)) { 1216 return this.filter(function(relativePath, file) { 1217 return file.dir && arg.test(relativePath); 1218 }); 1219 } 1220 1221 // else, name is a new folder 1222 var name = this.root + arg; 1223 var newFolder = folderAdd.call(this, name); 1224 1225 // Allow chaining by returning a new object with this folder as the root 1226 var ret = this.clone(); 1227 ret.root = newFolder.name; 1228 return ret; 1229 }, 1230 1231 /** 1232 * Delete a file, or a directory and all sub-files, from the zip 1233 * @param {string} name the name of the file to delete 1234 * @return {JSZip} this JSZip object 1235 */ 1236 remove: function(name) { 1237 name = this.root + name; 1238 var file = this.files[name]; 1239 if (!file) { 1240 // Look for any folders 1241 if (name.slice(-1) != "/") { 1242 name += "/"; 1243 } 1244 file = this.files[name]; 1245 } 1246 1247 if (file && !file.dir) { 1248 // file 1249 delete this.files[name]; 1250 } else { 1251 // maybe a folder, delete recursively 1252 var kids = this.filter(function(relativePath, file) { 1253 return file.name.slice(0, name.length) === name; 1254 }); 1255 for (var i = 0; i < kids.length; i++) { 1256 delete this.files[kids[i].name]; 1257 } 1258 } 1259 1260 return this; 1261 }, 1262 1263 /** 1264 * Generate the complete zip file 1265 * @param {Object} options the options to generate the zip file : 1266 * - base64, (deprecated, use type instead) true to generate base64. 1267 * - compression, "STORE" by default. 1268 * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob. 1269 * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file 1270 */ 1271 generate: function(options) { 1272 options = extend(options || {}, { 1273 base64: true, 1274 compression: "STORE", 1275 type: "base64", 1276 comment: null 1277 }); 1278 1279 utils.checkSupport(options.type); 1280 1281 var zipData = [], 1282 localDirLength = 0, 1283 centralDirLength = 0, 1284 writer, i, 1285 utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || "")); 1286 1287 // first, generate all the zip parts. 1288 for (var name in this.files) { 1289 if (!this.files.hasOwnProperty(name)) { 1290 continue; 1291 } 1292 var file = this.files[name]; 1293 1294 var compressionName = file.options.compression || options.compression.toUpperCase(); 1295 var compression = compressions[compressionName]; 1296 if (!compression) { 1297 throw new Error(compressionName + " is not a valid compression method !"); 1298 } 1299 1300 var compressedObject = generateCompressedObjectFrom.call(this, file, compression); 1301 1302 var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength); 1303 localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize; 1304 centralDirLength += zipPart.dirRecord.length; 1305 zipData.push(zipPart); 1306 } 1307 1308 var dirEnd = ""; 1309 1310 // end of central dir signature 1311 dirEnd = signature.CENTRAL_DIRECTORY_END + 1312 // number of this disk 1313 "\x00\x00" + 1314 // number of the disk with the start of the central directory 1315 "\x00\x00" + 1316 // total number of entries in the central directory on this disk 1317 decToHex(zipData.length, 2) + 1318 // total number of entries in the central directory 1319 decToHex(zipData.length, 2) + 1320 // size of the central directory 4 bytes 1321 decToHex(centralDirLength, 4) + 1322 // offset of start of central directory with respect to the starting disk number 1323 decToHex(localDirLength, 4) + 1324 // .ZIP file comment length 1325 decToHex(utfEncodedComment.length, 2) + 1326 // .ZIP file comment 1327 utfEncodedComment; 1328 1329 1330 // we have all the parts (and the total length) 1331 // time to create a writer ! 1332 var typeName = options.type.toLowerCase(); 1333 if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") { 1334 writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length); 1335 }else{ 1336 writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length); 1337 } 1338 1339 for (i = 0; i < zipData.length; i++) { 1340 writer.append(zipData[i].fileRecord); 1341 writer.append(zipData[i].compressedObject.compressedContent); 1342 } 1343 for (i = 0; i < zipData.length; i++) { 1344 writer.append(zipData[i].dirRecord); 1345 } 1346 1347 writer.append(dirEnd); 1348 1349 var zip = writer.finalize(); 1350 1351 1352 1353 switch(options.type.toLowerCase()) { 1354 // case "zip is an Uint8Array" 1355 case "uint8array" : 1356 case "arraybuffer" : 1357 case "nodebuffer" : 1358 return utils.transformTo(options.type.toLowerCase(), zip); 1359 case "blob" : 1360 return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip)); 1361 // case "zip is a string" 1362 case "base64" : 1363 return (options.base64) ? base64.encode(zip) : zip; 1364 default : // case "string" : 1365 return zip; 1366 } 1367 1368 }, 1369 1370 /** 1371 * @deprecated 1372 * This method will be removed in a future version without replacement. 1373 */ 1374 crc32: function (input, crc) { 1375 return crc32(input, crc); 1376 }, 1377 1378 /** 1379 * @deprecated 1380 * This method will be removed in a future version without replacement. 1381 */ 1382 utf8encode: function (string) { 1383 return utils.transformTo("string", utf8.utf8encode(string)); 1384 }, 1385 1386 /** 1387 * @deprecated 1388 * This method will be removed in a future version without replacement. 1389 */ 1390 utf8decode: function (input) { 1391 return utf8.utf8decode(input); 1392 } 1393 }; 1394 module.exports = out; 1395 1396 },{"./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){ 1397 'use strict'; 1398 exports.LOCAL_FILE_HEADER = "PK\x03\x04"; 1399 exports.CENTRAL_FILE_HEADER = "PK\x01\x02"; 1400 exports.CENTRAL_DIRECTORY_END = "PK\x05\x06"; 1401 exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07"; 1402 exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06"; 1403 exports.DATA_DESCRIPTOR = "PK\x07\x08"; 1404 1405 },{}],15:[function(_dereq_,module,exports){ 1406 'use strict'; 1407 var DataReader = _dereq_('./dataReader'); 1408 var utils = _dereq_('./utils'); 1409 1410 function StringReader(data, optimizedBinaryString) { 1411 this.data = data; 1412 if (!optimizedBinaryString) { 1413 this.data = utils.string2binary(this.data); 1414 } 1415 this.length = this.data.length; 1416 this.index = 0; 1417 } 1418 StringReader.prototype = new DataReader(); 1419 /** 1420 * @see DataReader.byteAt 1421 */ 1422 StringReader.prototype.byteAt = function(i) { 1423 return this.data.charCodeAt(i); 1424 }; 1425 /** 1426 * @see DataReader.lastIndexOfSignature 1427 */ 1428 StringReader.prototype.lastIndexOfSignature = function(sig) { 1429 return this.data.lastIndexOf(sig); 1430 }; 1431 /** 1432 * @see DataReader.readData 1433 */ 1434 StringReader.prototype.readData = function(size) { 1435 this.checkOffset(size); 1436 // this will work because the constructor applied the "& 0xff" mask. 1437 var result = this.data.slice(this.index, this.index + size); 1438 this.index += size; 1439 return result; 1440 }; 1441 module.exports = StringReader; 1442 1443 },{"./dataReader":5,"./utils":21}],16:[function(_dereq_,module,exports){ 1444 'use strict'; 1445 1446 var utils = _dereq_('./utils'); 1447 1448 /** 1449 * An object to write any content to a string. 1450 * @constructor 1451 */ 1452 var StringWriter = function() { 1453 this.data = []; 1454 }; 1455 StringWriter.prototype = { 1456 /** 1457 * Append any content to the current string. 1458 * @param {Object} input the content to add. 1459 */ 1460 append: function(input) { 1461 input = utils.transformTo("string", input); 1462 this.data.push(input); 1463 }, 1464 /** 1465 * Finalize the construction an return the result. 1466 * @return {string} the generated string. 1467 */ 1468 finalize: function() { 1469 return this.data.join(""); 1470 } 1471 }; 1472 1473 module.exports = StringWriter; 1474 1475 },{"./utils":21}],17:[function(_dereq_,module,exports){ 1476 (function (Buffer){ 1477 'use strict'; 1478 exports.base64 = true; 1479 exports.array = true; 1480 exports.string = true; 1481 exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; 1482 // contains true if JSZip can read/generate nodejs Buffer, false otherwise. 1483 // Browserify will provide a Buffer implementation for browsers, which is 1484 // an augmented Uint8Array (i.e., can be used as either Buffer or U8). 1485 exports.nodebuffer = typeof Buffer !== "undefined"; 1486 // contains true if JSZip can read/generate Uint8Array, false otherwise. 1487 exports.uint8array = typeof Uint8Array !== "undefined"; 1488 1489 if (typeof ArrayBuffer === "undefined") { 1490 exports.blob = false; 1491 } 1492 else { 1493 var buffer = new ArrayBuffer(0); 1494 try { 1495 exports.blob = new Blob([buffer], { 1496 type: "application/zip" 1497 }).size === 0; 1498 } 1499 catch (e) { 1500 try { 1501 var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; 1502 var builder = new Builder(); 1503 builder.append(buffer); 1504 exports.blob = builder.getBlob('application/zip').size === 0; 1505 } 1506 catch (e) { 1507 exports.blob = false; 1508 } 1509 } 1510 } 1511 1512 }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined)) 1513 },{}],18:[function(_dereq_,module,exports){ 1514 'use strict'; 1515 var DataReader = _dereq_('./dataReader'); 1516 1517 function Uint8ArrayReader(data) { 1518 if (data) { 1519 this.data = data; 1520 this.length = this.data.length; 1521 this.index = 0; 1522 } 1523 } 1524 Uint8ArrayReader.prototype = new DataReader(); 1525 /** 1526 * @see DataReader.byteAt 1527 */ 1528 Uint8ArrayReader.prototype.byteAt = function(i) { 1529 return this.data[i]; 1530 }; 1531 /** 1532 * @see DataReader.lastIndexOfSignature 1533 */ 1534 Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) { 1535 var sig0 = sig.charCodeAt(0), 1536 sig1 = sig.charCodeAt(1), 1537 sig2 = sig.charCodeAt(2), 1538 sig3 = sig.charCodeAt(3); 1539 for (var i = this.length - 4; i >= 0; --i) { 1540 if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) { 1541 return i; 1542 } 1543 } 1544 1545 return -1; 1546 }; 1547 /** 1548 * @see DataReader.readData 1549 */ 1550 Uint8ArrayReader.prototype.readData = function(size) { 1551 this.checkOffset(size); 1552 if(size === 0) { 1553 // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of []. 1554 return new Uint8Array(0); 1555 } 1556 var result = this.data.subarray(this.index, this.index + size); 1557 this.index += size; 1558 return result; 1559 }; 1560 module.exports = Uint8ArrayReader; 1561 1562 },{"./dataReader":5}],19:[function(_dereq_,module,exports){ 1563 'use strict'; 1564 1565 var utils = _dereq_('./utils'); 1566 1567 /** 1568 * An object to write any content to an Uint8Array. 1569 * @constructor 1570 * @param {number} length The length of the array. 1571 */ 1572 var Uint8ArrayWriter = function(length) { 1573 this.data = new Uint8Array(length); 1574 this.index = 0; 1575 }; 1576 Uint8ArrayWriter.prototype = { 1577 /** 1578 * Append any content to the current array. 1579 * @param {Object} input the content to add. 1580 */ 1581 append: function(input) { 1582 if (input.length !== 0) { 1583 // with an empty Uint8Array, Opera fails with a "Offset larger than array size" 1584 input = utils.transformTo("uint8array", input); 1585 this.data.set(input, this.index); 1586 this.index += input.length; 1587 } 1588 }, 1589 /** 1590 * Finalize the construction an return the result. 1591 * @return {Uint8Array} the generated array. 1592 */ 1593 finalize: function() { 1594 return this.data; 1595 } 1596 }; 1597 1598 module.exports = Uint8ArrayWriter; 1599 1600 },{"./utils":21}],20:[function(_dereq_,module,exports){ 1601 'use strict'; 1602 1603 var utils = _dereq_('./utils'); 1604 var support = _dereq_('./support'); 1605 var nodeBuffer = _dereq_('./nodeBuffer'); 1606 1607 /** 1608 * The following functions come from pako, from pako/lib/utils/strings 1609 * released under the MIT license, see pako https://github.com/nodeca/pako/ 1610 */ 1611 1612 // Table with utf8 lengths (calculated by first byte of sequence) 1613 // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, 1614 // because max possible codepoint is 0x10ffff 1615 var _utf8len = new Array(256); 1616 for (var i=0; i<256; i++) { 1617 _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1); 1618 } 1619 _utf8len[254]=_utf8len[254]=1; // Invalid sequence start 1620 1621 // convert string to array (typed, when possible) 1622 var string2buf = function (str) { 1623 var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; 1624 1625 // count binary size 1626 for (m_pos = 0; m_pos < str_len; m_pos++) { 1627 c = str.charCodeAt(m_pos); 1628 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { 1629 c2 = str.charCodeAt(m_pos+1); 1630 if ((c2 & 0xfc00) === 0xdc00) { 1631 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); 1632 m_pos++; 1633 } 1634 } 1635 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; 1636 } 1637 1638 // allocate buffer 1639 if (support.uint8array) { 1640 buf = new Uint8Array(buf_len); 1641 } else { 1642 buf = new Array(buf_len); 1643 } 1644 1645 // convert 1646 for (i=0, m_pos = 0; i < buf_len; m_pos++) { 1647 c = str.charCodeAt(m_pos); 1648 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { 1649 c2 = str.charCodeAt(m_pos+1); 1650 if ((c2 & 0xfc00) === 0xdc00) { 1651 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); 1652 m_pos++; 1653 } 1654 } 1655 if (c < 0x80) { 1656 /* one byte */ 1657 buf[i++] = c; 1658 } else if (c < 0x800) { 1659 /* two bytes */ 1660 buf[i++] = 0xC0 | (c >>> 6); 1661 buf[i++] = 0x80 | (c & 0x3f); 1662 } else if (c < 0x10000) { 1663 /* three bytes */ 1664 buf[i++] = 0xE0 | (c >>> 12); 1665 buf[i++] = 0x80 | (c >>> 6 & 0x3f); 1666 buf[i++] = 0x80 | (c & 0x3f); 1667 } else { 1668 /* four bytes */ 1669 buf[i++] = 0xf0 | (c >>> 18); 1670 buf[i++] = 0x80 | (c >>> 12 & 0x3f); 1671 buf[i++] = 0x80 | (c >>> 6 & 0x3f); 1672 buf[i++] = 0x80 | (c & 0x3f); 1673 } 1674 } 1675 1676 return buf; 1677 }; 1678 1679 // Calculate max possible position in utf8 buffer, 1680 // that will not break sequence. If that's not possible 1681 // - (very small limits) return max size as is. 1682 // 1683 // buf[] - utf8 bytes array 1684 // max - length limit (mandatory); 1685 var utf8border = function(buf, max) { 1686 var pos; 1687 1688 max = max || buf.length; 1689 if (max > buf.length) { max = buf.length; } 1690 1691 // go back from last position, until start of sequence found 1692 pos = max-1; 1693 while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } 1694 1695 // Fuckup - very small and broken sequence, 1696 // return max, because we should return something anyway. 1697 if (pos < 0) { return max; } 1698 1699 // If we came to start of buffer - that means vuffer is too small, 1700 // return max too. 1701 if (pos === 0) { return max; } 1702 1703 return (pos + _utf8len[buf[pos]] > max) ? pos : max; 1704 }; 1705 1706 // convert array to string 1707 var buf2string = function (buf) { 1708 var str, i, out, c, c_len; 1709 var len = buf.length; 1710 1711 // Reserve max possible length (2 words per char) 1712 // NB: by unknown reasons, Array is significantly faster for 1713 // String.fromCharCode.apply than Uint16Array. 1714 var utf16buf = new Array(len*2); 1715 1716 for (out=0, i=0; i<len;) { 1717 c = buf[i++]; 1718 // quick process ascii 1719 if (c < 0x80) { utf16buf[out++] = c; continue; } 1720 1721 c_len = _utf8len[c]; 1722 // skip 5 & 6 byte codes 1723 if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } 1724 1725 // apply mask on first byte 1726 c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; 1727 // join the rest 1728 while (c_len > 1 && i < len) { 1729 c = (c << 6) | (buf[i++] & 0x3f); 1730 c_len--; 1731 } 1732 1733 // terminated by end of string? 1734 if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } 1735 1736 if (c < 0x10000) { 1737 utf16buf[out++] = c; 1738 } else { 1739 c -= 0x10000; 1740 utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); 1741 utf16buf[out++] = 0xdc00 | (c & 0x3ff); 1742 } 1743 } 1744 1745 // shrinkBuf(utf16buf, out) 1746 if (utf16buf.length !== out) { 1747 if(utf16buf.subarray) { 1748 utf16buf = utf16buf.subarray(0, out); 1749 } else { 1750 utf16buf.length = out; 1751 } 1752 } 1753 1754 // return String.fromCharCode.apply(null, utf16buf); 1755 return utils.applyFromCharCode(utf16buf); 1756 }; 1757 1758 1759 // That's all for the pako functions. 1760 1761 1762 /** 1763 * Transform a javascript string into an array (typed if possible) of bytes, 1764 * UTF-8 encoded. 1765 * @param {String} str the string to encode 1766 * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string. 1767 */ 1768 exports.utf8encode = function utf8encode(str) { 1769 if (support.nodebuffer) { 1770 return nodeBuffer(str, "utf-8"); 1771 } 1772 1773 return string2buf(str); 1774 }; 1775 1776 1777 /** 1778 * Transform a bytes array (or a representation) representing an UTF-8 encoded 1779 * string into a javascript string. 1780 * @param {Array|Uint8Array|Buffer} buf the data de decode 1781 * @return {String} the decoded string. 1782 */ 1783 exports.utf8decode = function utf8decode(buf) { 1784 if (support.nodebuffer) { 1785 return utils.transformTo("nodebuffer", buf).toString("utf-8"); 1786 } 1787 1788 buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); 1789 1790 // return buf2string(buf); 1791 // Chrome prefers to work with "small" chunks of data 1792 // for the method buf2string. 1793 // Firefox and Chrome has their own shortcut, IE doesn't seem to really care. 1794 var result = [], k = 0, len = buf.length, chunk = 65536; 1795 while (k < len) { 1796 var nextBoundary = utf8border(buf, Math.min(k + chunk, len)); 1797 if (support.uint8array) { 1798 result.push(buf2string(buf.subarray(k, nextBoundary))); 1799 } else { 1800 result.push(buf2string(buf.slice(k, nextBoundary))); 1801 } 1802 k = nextBoundary; 1803 } 1804 return result.join(""); 1805 1806 }; 1807 // vim: set shiftwidth=4 softtabstop=4: 1808 1809 },{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(_dereq_,module,exports){ 1810 'use strict'; 1811 var support = _dereq_('./support'); 1812 var compressions = _dereq_('./compressions'); 1813 var nodeBuffer = _dereq_('./nodeBuffer'); 1814 /** 1815 * Convert a string to a "binary string" : a string containing only char codes between 0 and 255. 1816 * @param {string} str the string to transform. 1817 * @return {String} the binary string. 1818 */ 1819 exports.string2binary = function(str) { 1820 var result = ""; 1821 for (var i = 0; i < str.length; i++) { 1822 result += String.fromCharCode(str.charCodeAt(i) & 0xff); 1823 } 1824 return result; 1825 }; 1826 exports.arrayBuffer2Blob = function(buffer) { 1827 exports.checkSupport("blob"); 1828 1829 try { 1830 // Blob constructor 1831 return new Blob([buffer], { 1832 type: "application/zip" 1833 }); 1834 } 1835 catch (e) { 1836 1837 try { 1838 // deprecated, browser only, old way 1839 var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; 1840 var builder = new Builder(); 1841 builder.append(buffer); 1842 return builder.getBlob('application/zip'); 1843 } 1844 catch (e) { 1845 1846 // well, fuck ?! 1847 throw new Error("Bug : can't construct the Blob."); 1848 } 1849 } 1850 1851 1852 }; 1853 /** 1854 * The identity function. 1855 * @param {Object} input the input. 1856 * @return {Object} the same input. 1857 */ 1858 function identity(input) { 1859 return input; 1860 } 1861 1862 /** 1863 * Fill in an array with a string. 1864 * @param {String} str the string to use. 1865 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated). 1866 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array. 1867 */ 1868 function stringToArrayLike(str, array) { 1869 for (var i = 0; i < str.length; ++i) { 1870 array[i] = str.charCodeAt(i) & 0xFF; 1871 } 1872 return array; 1873 } 1874 1875 /** 1876 * Transform an array-like object to a string. 1877 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. 1878 * @return {String} the result. 1879 */ 1880 function arrayLikeToString(array) { 1881 // Performances notes : 1882 // -------------------- 1883 // String.fromCharCode.apply(null, array) is the fastest, see 1884 // see http://jsperf.com/converting-a-uint8array-to-a-string/2 1885 // but the stack is limited (and we can get huge arrays !). 1886 // 1887 // result += String.fromCharCode(array[i]); generate too many strings ! 1888 // 1889 // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2 1890 var chunk = 65536; 1891 var result = [], 1892 len = array.length, 1893 type = exports.getTypeOf(array), 1894 k = 0, 1895 canUseApply = true; 1896 try { 1897 switch(type) { 1898 case "uint8array": 1899 String.fromCharCode.apply(null, new Uint8Array(0)); 1900 break; 1901 case "nodebuffer": 1902 String.fromCharCode.apply(null, nodeBuffer(0)); 1903 break; 1904 } 1905 } catch(e) { 1906 canUseApply = false; 1907 } 1908 1909 // no apply : slow and painful algorithm 1910 // default browser on android 4.* 1911 if (!canUseApply) { 1912 var resultStr = ""; 1913 for(var i = 0; i < array.length;i++) { 1914 resultStr += String.fromCharCode(array[i]); 1915 } 1916 return resultStr; 1917 } 1918 while (k < len && chunk > 1) { 1919 try { 1920 if (type === "array" || type === "nodebuffer") { 1921 result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len)))); 1922 } 1923 else { 1924 result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len)))); 1925 } 1926 k += chunk; 1927 } 1928 catch (e) { 1929 chunk = Math.floor(chunk / 2); 1930 } 1931 } 1932 return result.join(""); 1933 } 1934 1935 exports.applyFromCharCode = arrayLikeToString; 1936 1937 1938 /** 1939 * Copy the data from an array-like to an other array-like. 1940 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array. 1941 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated. 1942 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array. 1943 */ 1944 function arrayLikeToArrayLike(arrayFrom, arrayTo) { 1945 for (var i = 0; i < arrayFrom.length; i++) { 1946 arrayTo[i] = arrayFrom[i]; 1947 } 1948 return arrayTo; 1949 } 1950 1951 // a matrix containing functions to transform everything into everything. 1952 var transform = {}; 1953 1954 // string to ? 1955 transform["string"] = { 1956 "string": identity, 1957 "array": function(input) { 1958 return stringToArrayLike(input, new Array(input.length)); 1959 }, 1960 "arraybuffer": function(input) { 1961 return transform["string"]["uint8array"](input).buffer; 1962 }, 1963 "uint8array": function(input) { 1964 return stringToArrayLike(input, new Uint8Array(input.length)); 1965 }, 1966 "nodebuffer": function(input) { 1967 return stringToArrayLike(input, nodeBuffer(input.length)); 1968 } 1969 }; 1970 1971 // array to ? 1972 transform["array"] = { 1973 "string": arrayLikeToString, 1974 "array": identity, 1975 "arraybuffer": function(input) { 1976 return (new Uint8Array(input)).buffer; 1977 }, 1978 "uint8array": function(input) { 1979 return new Uint8Array(input); 1980 }, 1981 "nodebuffer": function(input) { 1982 return nodeBuffer(input); 1983 } 1984 }; 1985 1986 // arraybuffer to ? 1987 transform["arraybuffer"] = { 1988 "string": function(input) { 1989 return arrayLikeToString(new Uint8Array(input)); 1990 }, 1991 "array": function(input) { 1992 return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); 1993 }, 1994 "arraybuffer": identity, 1995 "uint8array": function(input) { 1996 return new Uint8Array(input); 1997 }, 1998 "nodebuffer": function(input) { 1999 return nodeBuffer(new Uint8Array(input)); 2000 } 2001 }; 2002 2003 // uint8array to ? 2004 transform["uint8array"] = { 2005 "string": arrayLikeToString, 2006 "array": function(input) { 2007 return arrayLikeToArrayLike(input, new Array(input.length)); 2008 }, 2009 "arraybuffer": function(input) { 2010 return input.buffer; 2011 }, 2012 "uint8array": identity, 2013 "nodebuffer": function(input) { 2014 return nodeBuffer(input); 2015 } 2016 }; 2017 2018 // nodebuffer to ? 2019 transform["nodebuffer"] = { 2020 "string": arrayLikeToString, 2021 "array": function(input) { 2022 return arrayLikeToArrayLike(input, new Array(input.length)); 2023 }, 2024 "arraybuffer": function(input) { 2025 return transform["nodebuffer"]["uint8array"](input).buffer; 2026 }, 2027 "uint8array": function(input) { 2028 return arrayLikeToArrayLike(input, new Uint8Array(input.length)); 2029 }, 2030 "nodebuffer": identity 2031 }; 2032 2033 /** 2034 * Transform an input into any type. 2035 * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer. 2036 * If no output type is specified, the unmodified input will be returned. 2037 * @param {String} outputType the output type. 2038 * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert. 2039 * @throws {Error} an Error if the browser doesn't support the requested output type. 2040 */ 2041 exports.transformTo = function(outputType, input) { 2042 if (!input) { 2043 // undefined, null, etc 2044 // an empty string won't harm. 2045 input = ""; 2046 } 2047 if (!outputType) { 2048 return input; 2049 } 2050 exports.checkSupport(outputType); 2051 var inputType = exports.getTypeOf(input); 2052 var result = transform[inputType][outputType](input); 2053 return result; 2054 }; 2055 2056 /** 2057 * Return the type of the input. 2058 * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer. 2059 * @param {Object} input the input to identify. 2060 * @return {String} the (lowercase) type of the input. 2061 */ 2062 exports.getTypeOf = function(input) { 2063 if (typeof input === "string") { 2064 return "string"; 2065 } 2066 if (Object.prototype.toString.call(input) === "[object Array]") { 2067 return "array"; 2068 } 2069 if (support.nodebuffer && nodeBuffer.test(input)) { 2070 return "nodebuffer"; 2071 } 2072 if (support.uint8array && input instanceof Uint8Array) { 2073 return "uint8array"; 2074 } 2075 if (support.arraybuffer && input instanceof ArrayBuffer) { 2076 return "arraybuffer"; 2077 } 2078 }; 2079 2080 /** 2081 * Throw an exception if the type is not supported. 2082 * @param {String} type the type to check. 2083 * @throws {Error} an Error if the browser doesn't support the requested type. 2084 */ 2085 exports.checkSupport = function(type) { 2086 var supported = support[type.toLowerCase()]; 2087 if (!supported) { 2088 throw new Error(type + " is not supported by this browser"); 2089 } 2090 }; 2091 exports.MAX_VALUE_16BITS = 65535; 2092 exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1 2093 2094 /** 2095 * Prettify a string read as binary. 2096 * @param {string} str the string to prettify. 2097 * @return {string} a pretty string. 2098 */ 2099 exports.pretty = function(str) { 2100 var res = '', 2101 code, i; 2102 for (i = 0; i < (str || "").length; i++) { 2103 code = str.charCodeAt(i); 2104 res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); 2105 } 2106 return res; 2107 }; 2108 2109 /** 2110 * Find a compression registered in JSZip. 2111 * @param {string} compressionMethod the method magic to find. 2112 * @return {Object|null} the JSZip compression object, null if none found. 2113 */ 2114 exports.findCompression = function(compressionMethod) { 2115 for (var method in compressions) { 2116 if (!compressions.hasOwnProperty(method)) { 2117 continue; 2118 } 2119 if (compressions[method].magic === compressionMethod) { 2120 return compressions[method]; 2121 } 2122 } 2123 return null; 2124 }; 2125 /** 2126 * Cross-window, cross-Node-context regular expression detection 2127 * @param {Object} object Anything 2128 * @return {Boolean} true if the object is a regular expression, 2129 * false otherwise 2130 */ 2131 exports.isRegExp = function (object) { 2132 return Object.prototype.toString.call(object) === "[object RegExp]"; 2133 }; 2134 2135 2136 },{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(_dereq_,module,exports){ 2137 'use strict'; 2138 var StringReader = _dereq_('./stringReader'); 2139 var NodeBufferReader = _dereq_('./nodeBufferReader'); 2140 var Uint8ArrayReader = _dereq_('./uint8ArrayReader'); 2141 var utils = _dereq_('./utils'); 2142 var sig = _dereq_('./signature'); 2143 var ZipEntry = _dereq_('./zipEntry'); 2144 var support = _dereq_('./support'); 2145 var jszipProto = _dereq_('./object'); 2146 // class ZipEntries {{{ 2147 /** 2148 * All the entries in the zip file. 2149 * @constructor 2150 * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load. 2151 * @param {Object} loadOptions Options for loading the stream. 2152 */ 2153 function ZipEntries(data, loadOptions) { 2154 this.files = []; 2155 this.loadOptions = loadOptions; 2156 if (data) { 2157 this.load(data); 2158 } 2159 } 2160 ZipEntries.prototype = { 2161 /** 2162 * Check that the reader is on the speficied signature. 2163 * @param {string} expectedSignature the expected signature. 2164 * @throws {Error} if it is an other signature. 2165 */ 2166 checkSignature: function(expectedSignature) { 2167 var signature = this.reader.readString(4); 2168 if (signature !== expectedSignature) { 2169 throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); 2170 } 2171 }, 2172 /** 2173 * Read the end of the central directory. 2174 */ 2175 readBlockEndOfCentral: function() { 2176 this.diskNumber = this.reader.readInt(2); 2177 this.diskWithCentralDirStart = this.reader.readInt(2); 2178 this.centralDirRecordsOnThisDisk = this.reader.readInt(2); 2179 this.centralDirRecords = this.reader.readInt(2); 2180 this.centralDirSize = this.reader.readInt(4); 2181 this.centralDirOffset = this.reader.readInt(4); 2182 2183 this.zipCommentLength = this.reader.readInt(2); 2184 // warning : the encoding depends of the system locale 2185 // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded. 2186 // On a windows machine, this field is encoded with the localized windows code page. 2187 this.zipComment = this.reader.readString(this.zipCommentLength); 2188 // To get consistent behavior with the generation part, we will assume that 2189 // this is utf8 encoded. 2190 this.zipComment = jszipProto.utf8decode(this.zipComment); 2191 }, 2192 /** 2193 * Read the end of the Zip 64 central directory. 2194 * Not merged with the method readEndOfCentral : 2195 * The end of central can coexist with its Zip64 brother, 2196 * I don't want to read the wrong number of bytes ! 2197 */ 2198 readBlockZip64EndOfCentral: function() { 2199 this.zip64EndOfCentralSize = this.reader.readInt(8); 2200 this.versionMadeBy = this.reader.readString(2); 2201 this.versionNeeded = this.reader.readInt(2); 2202 this.diskNumber = this.reader.readInt(4); 2203 this.diskWithCentralDirStart = this.reader.readInt(4); 2204 this.centralDirRecordsOnThisDisk = this.reader.readInt(8); 2205 this.centralDirRecords = this.reader.readInt(8); 2206 this.centralDirSize = this.reader.readInt(8); 2207 this.centralDirOffset = this.reader.readInt(8); 2208 2209 this.zip64ExtensibleData = {}; 2210 var extraDataSize = this.zip64EndOfCentralSize - 44, 2211 index = 0, 2212 extraFieldId, 2213 extraFieldLength, 2214 extraFieldValue; 2215 while (index < extraDataSize) { 2216 extraFieldId = this.reader.readInt(2); 2217 extraFieldLength = this.reader.readInt(4); 2218 extraFieldValue = this.reader.readString(extraFieldLength); 2219 this.zip64ExtensibleData[extraFieldId] = { 2220 id: extraFieldId, 2221 length: extraFieldLength, 2222 value: extraFieldValue 2223 }; 2224 } 2225 }, 2226 /** 2227 * Read the end of the Zip 64 central directory locator. 2228 */ 2229 readBlockZip64EndOfCentralLocator: function() { 2230 this.diskWithZip64CentralDirStart = this.reader.readInt(4); 2231 this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); 2232 this.disksCount = this.reader.readInt(4); 2233 if (this.disksCount > 1) { 2234 throw new Error("Multi-volumes zip are not supported"); 2235 } 2236 }, 2237 /** 2238 * Read the local files, based on the offset read in the central part. 2239 */ 2240 readLocalFiles: function() { 2241 var i, file; 2242 for (i = 0; i < this.files.length; i++) { 2243 file = this.files[i]; 2244 this.reader.setIndex(file.localHeaderOffset); 2245 this.checkSignature(sig.LOCAL_FILE_HEADER); 2246 file.readLocalPart(this.reader); 2247 file.handleUTF8(); 2248 } 2249 }, 2250 /** 2251 * Read the central directory. 2252 */ 2253 readCentralDir: function() { 2254 var file; 2255 2256 this.reader.setIndex(this.centralDirOffset); 2257 while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) { 2258 file = new ZipEntry({ 2259 zip64: this.zip64 2260 }, this.loadOptions); 2261 file.readCentralPart(this.reader); 2262 this.files.push(file); 2263 } 2264 }, 2265 /** 2266 * Read the end of central directory. 2267 */ 2268 readEndOfCentral: function() { 2269 var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); 2270 if (offset === -1) { 2271 throw new Error("Corrupted zip : can't find end of central directory"); 2272 } 2273 this.reader.setIndex(offset); 2274 this.checkSignature(sig.CENTRAL_DIRECTORY_END); 2275 this.readBlockEndOfCentral(); 2276 2277 2278 /* extract from the zip spec : 2279 4) If one of the fields in the end of central directory 2280 record is too small to hold required data, the field 2281 should be set to -1 (0xFFFF or 0xFFFFFFFF) and the 2282 ZIP64 format record should be created. 2283 5) The end of central directory record and the 2284 Zip64 end of central directory locator record must 2285 reside on the same disk when splitting or spanning 2286 an archive. 2287 */ 2288 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) { 2289 this.zip64 = true; 2290 2291 /* 2292 Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from 2293 the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents 2294 all numbers as 64-bit double precision IEEE 754 floating point numbers. 2295 So, we have 53bits for integers and bitwise operations treat everything as 32bits. 2296 see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators 2297 and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5 2298 */ 2299 2300 // should look for a zip64 EOCD locator 2301 offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); 2302 if (offset === -1) { 2303 throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator"); 2304 } 2305 this.reader.setIndex(offset); 2306 this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); 2307 this.readBlockZip64EndOfCentralLocator(); 2308 2309 // now the zip64 EOCD record 2310 this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); 2311 this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); 2312 this.readBlockZip64EndOfCentral(); 2313 } 2314 }, 2315 prepareReader: function(data) { 2316 var type = utils.getTypeOf(data); 2317 if (type === "string" && !support.uint8array) { 2318 this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString); 2319 } 2320 else if (type === "nodebuffer") { 2321 this.reader = new NodeBufferReader(data); 2322 } 2323 else { 2324 this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data)); 2325 } 2326 }, 2327 /** 2328 * Read a zip file and create ZipEntries. 2329 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file. 2330 */ 2331 load: function(data) { 2332 this.prepareReader(data); 2333 this.readEndOfCentral(); 2334 this.readCentralDir(); 2335 this.readLocalFiles(); 2336 } 2337 }; 2338 // }}} end of ZipEntries 2339 module.exports = ZipEntries; 2340 2341 },{"./nodeBufferReader":12,"./object":13,"./signature":14,"./stringReader":15,"./support":17,"./uint8ArrayReader":18,"./utils":21,"./zipEntry":23}],23:[function(_dereq_,module,exports){ 2342 'use strict'; 2343 var StringReader = _dereq_('./stringReader'); 2344 var utils = _dereq_('./utils'); 2345 var CompressedObject = _dereq_('./compressedObject'); 2346 var jszipProto = _dereq_('./object'); 2347 // class ZipEntry {{{ 2348 /** 2349 * An entry in the zip file. 2350 * @constructor 2351 * @param {Object} options Options of the current file. 2352 * @param {Object} loadOptions Options for loading the stream. 2353 */ 2354 function ZipEntry(options, loadOptions) { 2355 this.options = options; 2356 this.loadOptions = loadOptions; 2357 } 2358 ZipEntry.prototype = { 2359 /** 2360 * say if the file is encrypted. 2361 * @return {boolean} true if the file is encrypted, false otherwise. 2362 */ 2363 isEncrypted: function() { 2364 // bit 1 is set 2365 return (this.bitFlag & 0x0001) === 0x0001; 2366 }, 2367 /** 2368 * say if the file has utf-8 filename/comment. 2369 * @return {boolean} true if the filename/comment is in utf-8, false otherwise. 2370 */ 2371 useUTF8: function() { 2372 // bit 11 is set 2373 return (this.bitFlag & 0x0800) === 0x0800; 2374 }, 2375 /** 2376 * Prepare the function used to generate the compressed content from this ZipFile. 2377 * @param {DataReader} reader the reader to use. 2378 * @param {number} from the offset from where we should read the data. 2379 * @param {number} length the length of the data to read. 2380 * @return {Function} the callback to get the compressed content (the type depends of the DataReader class). 2381 */ 2382 prepareCompressedContent: function(reader, from, length) { 2383 return function() { 2384 var previousIndex = reader.index; 2385 reader.setIndex(from); 2386 var compressedFileData = reader.readData(length); 2387 reader.setIndex(previousIndex); 2388 2389 return compressedFileData; 2390 }; 2391 }, 2392 /** 2393 * Prepare the function used to generate the uncompressed content from this ZipFile. 2394 * @param {DataReader} reader the reader to use. 2395 * @param {number} from the offset from where we should read the data. 2396 * @param {number} length the length of the data to read. 2397 * @param {JSZip.compression} compression the compression used on this file. 2398 * @param {number} uncompressedSize the uncompressed size to expect. 2399 * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class). 2400 */ 2401 prepareContent: function(reader, from, length, compression, uncompressedSize) { 2402 return function() { 2403 2404 var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent()); 2405 var uncompressedFileData = compression.uncompress(compressedFileData); 2406 2407 if (uncompressedFileData.length !== uncompressedSize) { 2408 throw new Error("Bug : uncompressed data size mismatch"); 2409 } 2410 2411 return uncompressedFileData; 2412 }; 2413 }, 2414 /** 2415 * Read the local part of a zip file and add the info in this object. 2416 * @param {DataReader} reader the reader to use. 2417 */ 2418 readLocalPart: function(reader) { 2419 var compression, localExtraFieldsLength; 2420 2421 // we already know everything from the central dir ! 2422 // If the central dir data are false, we are doomed. 2423 // On the bright side, the local part is scary : zip64, data descriptors, both, etc. 2424 // The less data we get here, the more reliable this should be. 2425 // Let's skip the whole header and dash to the data ! 2426 reader.skip(22); 2427 // in some zip created on windows, the filename stored in the central dir contains \ instead of /. 2428 // Strangely, the filename here is OK. 2429 // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes 2430 // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators... 2431 // Search "unzip mismatching "local" filename continuing with "central" filename version" on 2432 // the internet. 2433 // 2434 // I think I see the logic here : the central directory is used to display 2435 // content and the local directory is used to extract the files. Mixing / and \ 2436 // may be used to display \ to windows users and use / when extracting the files. 2437 // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394 2438 this.fileNameLength = reader.readInt(2); 2439 localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir 2440 this.fileName = reader.readString(this.fileNameLength); 2441 reader.skip(localExtraFieldsLength); 2442 2443 if (this.compressedSize == -1 || this.uncompressedSize == -1) { 2444 throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)"); 2445 } 2446 2447 compression = utils.findCompression(this.compressionMethod); 2448 if (compression === null) { // no compression found 2449 throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")"); 2450 } 2451 this.decompressed = new CompressedObject(); 2452 this.decompressed.compressedSize = this.compressedSize; 2453 this.decompressed.uncompressedSize = this.uncompressedSize; 2454 this.decompressed.crc32 = this.crc32; 2455 this.decompressed.compressionMethod = this.compressionMethod; 2456 this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression); 2457 this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize); 2458 2459 // we need to compute the crc32... 2460 if (this.loadOptions.checkCRC32) { 2461 this.decompressed = utils.transformTo("string", this.decompressed.getContent()); 2462 if (jszipProto.crc32(this.decompressed) !== this.crc32) { 2463 throw new Error("Corrupted zip : CRC32 mismatch"); 2464 } 2465 } 2466 }, 2467 2468 /** 2469 * Read the central part of a zip file and add the info in this object. 2470 * @param {DataReader} reader the reader to use. 2471 */ 2472 readCentralPart: function(reader) { 2473 this.versionMadeBy = reader.readString(2); 2474 this.versionNeeded = reader.readInt(2); 2475 this.bitFlag = reader.readInt(2); 2476 this.compressionMethod = reader.readString(2); 2477 this.date = reader.readDate(); 2478 this.crc32 = reader.readInt(4); 2479 this.compressedSize = reader.readInt(4); 2480 this.uncompressedSize = reader.readInt(4); 2481 this.fileNameLength = reader.readInt(2); 2482 this.extraFieldsLength = reader.readInt(2); 2483 this.fileCommentLength = reader.readInt(2); 2484 this.diskNumberStart = reader.readInt(2); 2485 this.internalFileAttributes = reader.readInt(2); 2486 this.externalFileAttributes = reader.readInt(4); 2487 this.localHeaderOffset = reader.readInt(4); 2488 2489 if (this.isEncrypted()) { 2490 throw new Error("Encrypted zip are not supported"); 2491 } 2492 2493 this.fileName = reader.readString(this.fileNameLength); 2494 this.readExtraFields(reader); 2495 this.parseZIP64ExtraField(reader); 2496 this.fileComment = reader.readString(this.fileCommentLength); 2497 2498 // warning, this is true only for zip with madeBy == DOS (plateform dependent feature) 2499 this.dir = this.externalFileAttributes & 0x00000010 ? true : false; 2500 }, 2501 /** 2502 * Parse the ZIP64 extra field and merge the info in the current ZipEntry. 2503 * @param {DataReader} reader the reader to use. 2504 */ 2505 parseZIP64ExtraField: function(reader) { 2506 2507 if (!this.extraFields[0x0001]) { 2508 return; 2509 } 2510 2511 // should be something, preparing the extra reader 2512 var extraReader = new StringReader(this.extraFields[0x0001].value); 2513 2514 // I really hope that these 64bits integer can fit in 32 bits integer, because js 2515 // won't let us have more. 2516 if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { 2517 this.uncompressedSize = extraReader.readInt(8); 2518 } 2519 if (this.compressedSize === utils.MAX_VALUE_32BITS) { 2520 this.compressedSize = extraReader.readInt(8); 2521 } 2522 if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { 2523 this.localHeaderOffset = extraReader.readInt(8); 2524 } 2525 if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { 2526 this.diskNumberStart = extraReader.readInt(4); 2527 } 2528 }, 2529 /** 2530 * Read the central part of a zip file and add the info in this object. 2531 * @param {DataReader} reader the reader to use. 2532 */ 2533 readExtraFields: function(reader) { 2534 var start = reader.index, 2535 extraFieldId, 2536 extraFieldLength, 2537 extraFieldValue; 2538 2539 this.extraFields = this.extraFields || {}; 2540 2541 while (reader.index < start + this.extraFieldsLength) { 2542 extraFieldId = reader.readInt(2); 2543 extraFieldLength = reader.readInt(2); 2544 extraFieldValue = reader.readString(extraFieldLength); 2545 2546 this.extraFields[extraFieldId] = { 2547 id: extraFieldId, 2548 length: extraFieldLength, 2549 value: extraFieldValue 2550 }; 2551 } 2552 }, 2553 /** 2554 * Apply an UTF8 transformation if needed. 2555 */ 2556 handleUTF8: function() { 2557 if (this.useUTF8()) { 2558 this.fileName = jszipProto.utf8decode(this.fileName); 2559 this.fileComment = jszipProto.utf8decode(this.fileComment); 2560 } else { 2561 var upath = this.findExtraFieldUnicodePath(); 2562 if (upath !== null) { 2563 this.fileName = upath; 2564 } 2565 var ucomment = this.findExtraFieldUnicodeComment(); 2566 if (ucomment !== null) { 2567 this.fileComment = ucomment; 2568 } 2569 } 2570 }, 2571 2572 /** 2573 * Find the unicode path declared in the extra field, if any. 2574 * @return {String} the unicode path, null otherwise. 2575 */ 2576 findExtraFieldUnicodePath: function() { 2577 var upathField = this.extraFields[0x7075]; 2578 if (upathField) { 2579 var extraReader = new StringReader(upathField.value); 2580 2581 // wrong version 2582 if (extraReader.readInt(1) !== 1) { 2583 return null; 2584 } 2585 2586 // the crc of the filename changed, this field is out of date. 2587 if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) { 2588 return null; 2589 } 2590 2591 return jszipProto.utf8decode(extraReader.readString(upathField.length - 5)); 2592 } 2593 return null; 2594 }, 2595 2596 /** 2597 * Find the unicode comment declared in the extra field, if any. 2598 * @return {String} the unicode comment, null otherwise. 2599 */ 2600 findExtraFieldUnicodeComment: function() { 2601 var ucommentField = this.extraFields[0x6375]; 2602 if (ucommentField) { 2603 var extraReader = new StringReader(ucommentField.value); 2604 2605 // wrong version 2606 if (extraReader.readInt(1) !== 1) { 2607 return null; 2608 } 2609 2610 // the crc of the comment changed, this field is out of date. 2611 if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) { 2612 return null; 2613 } 2614 2615 return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5)); 2616 } 2617 return null; 2618 } 2619 }; 2620 module.exports = ZipEntry; 2621 2622 },{"./compressedObject":2,"./object":13,"./stringReader":15,"./utils":21}],24:[function(_dereq_,module,exports){ 2623 // Top level file is just a mixin of submodules & constants 2624 'use strict'; 2625 2626 var assign = _dereq_('./lib/utils/common').assign; 2627 2628 var deflate = _dereq_('./lib/deflate'); 2629 var inflate = _dereq_('./lib/inflate'); 2630 var constants = _dereq_('./lib/zlib/constants'); 2631 2632 var pako = {}; 2633 2634 assign(pako, deflate, inflate, constants); 2635 2636 module.exports = pako; 2637 },{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(_dereq_,module,exports){ 2638 'use strict'; 2639 2640 2641 var zlib_deflate = _dereq_('./zlib/deflate.js'); 2642 var utils = _dereq_('./utils/common'); 2643 var strings = _dereq_('./utils/strings'); 2644 var msg = _dereq_('./zlib/messages'); 2645 var zstream = _dereq_('./zlib/zstream'); 2646 2647 2648 /* Public constants ==========================================================*/ 2649 /* ===========================================================================*/ 2650 2651 var Z_NO_FLUSH = 0; 2652 var Z_FINISH = 4; 2653 2654 var Z_OK = 0; 2655 var Z_STREAM_END = 1; 2656 2657 var Z_DEFAULT_COMPRESSION = -1; 2658 2659 var Z_DEFAULT_STRATEGY = 0; 2660 2661 var Z_DEFLATED = 8; 2662 2663 /* ===========================================================================*/ 2664 2665 2666 /** 2667 * class Deflate 2668 * 2669 * Generic JS-style wrapper for zlib calls. If you don't need 2670 * streaming behaviour - use more simple functions: [[deflate]], 2671 * [[deflateRaw]] and [[gzip]]. 2672 **/ 2673 2674 /* internal 2675 * Deflate.chunks -> Array 2676 * 2677 * Chunks of output data, if [[Deflate#onData]] not overriden. 2678 **/ 2679 2680 /** 2681 * Deflate.result -> Uint8Array|Array 2682 * 2683 * Compressed result, generated by default [[Deflate#onData]] 2684 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk 2685 * (call [[Deflate#push]] with `Z_FINISH` / `true` param). 2686 **/ 2687 2688 /** 2689 * Deflate.err -> Number 2690 * 2691 * Error code after deflate finished. 0 (Z_OK) on success. 2692 * You will not need it in real life, because deflate errors 2693 * are possible only on wrong options or bad `onData` / `onEnd` 2694 * custom handlers. 2695 **/ 2696 2697 /** 2698 * Deflate.msg -> String 2699 * 2700 * Error message, if [[Deflate.err]] != 0 2701 **/ 2702 2703 2704 /** 2705 * new Deflate(options) 2706 * - options (Object): zlib deflate options. 2707 * 2708 * Creates new deflator instance with specified params. Throws exception 2709 * on bad params. Supported options: 2710 * 2711 * - `level` 2712 * - `windowBits` 2713 * - `memLevel` 2714 * - `strategy` 2715 * 2716 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) 2717 * for more information on these. 2718 * 2719 * Additional options, for internal needs: 2720 * 2721 * - `chunkSize` - size of generated data chunks (16K by default) 2722 * - `raw` (Boolean) - do raw deflate 2723 * - `gzip` (Boolean) - create gzip wrapper 2724 * - `to` (String) - if equal to 'string', then result will be "binary string" 2725 * (each char code [0..255]) 2726 * - `header` (Object) - custom header for gzip 2727 * - `text` (Boolean) - true if compressed data believed to be text 2728 * - `time` (Number) - modification time, unix timestamp 2729 * - `os` (Number) - operation system code 2730 * - `extra` (Array) - array of bytes with extra data (max 65536) 2731 * - `name` (String) - file name (binary string) 2732 * - `comment` (String) - comment (binary string) 2733 * - `hcrc` (Boolean) - true if header crc should be added 2734 * 2735 * ##### Example: 2736 * 2737 * ```javascript 2738 * var pako = require('pako') 2739 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) 2740 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); 2741 * 2742 * var deflate = new pako.Deflate({ level: 3}); 2743 * 2744 * deflate.push(chunk1, false); 2745 * deflate.push(chunk2, true); // true -> last chunk 2746 * 2747 * if (deflate.err) { throw new Error(deflate.err); } 2748 * 2749 * console.log(deflate.result); 2750 * ``` 2751 **/ 2752 var Deflate = function(options) { 2753 2754 this.options = utils.assign({ 2755 level: Z_DEFAULT_COMPRESSION, 2756 method: Z_DEFLATED, 2757 chunkSize: 16384, 2758 windowBits: 15, 2759 memLevel: 8, 2760 strategy: Z_DEFAULT_STRATEGY, 2761 to: '' 2762 }, options || {}); 2763 2764 var opt = this.options; 2765 2766 if (opt.raw && (opt.windowBits > 0)) { 2767 opt.windowBits = -opt.windowBits; 2768 } 2769 2770 else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { 2771 opt.windowBits += 16; 2772 } 2773 2774 this.err = 0; // error code, if happens (0 = Z_OK) 2775 this.msg = ''; // error message 2776 this.ended = false; // used to avoid multiple onEnd() calls 2777 this.chunks = []; // chunks of compressed data 2778 2779 this.strm = new zstream(); 2780 this.strm.avail_out = 0; 2781 2782 var status = zlib_deflate.deflateInit2( 2783 this.strm, 2784 opt.level, 2785 opt.method, 2786 opt.windowBits, 2787 opt.memLevel, 2788 opt.strategy 2789 ); 2790 2791 if (status !== Z_OK) { 2792 throw new Error(msg[status]); 2793 } 2794 2795 if (opt.header) { 2796 zlib_deflate.deflateSetHeader(this.strm, opt.header); 2797 } 2798 }; 2799 2800 /** 2801 * Deflate#push(data[, mode]) -> Boolean 2802 * - data (Uint8Array|Array|String): input data. Strings will be converted to 2803 * utf8 byte sequence. 2804 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. 2805 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. 2806 * 2807 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with 2808 * new compressed chunks. Returns `true` on success. The last data block must have 2809 * mode Z_FINISH (or `true`). That flush internal pending buffers and call 2810 * [[Deflate#onEnd]]. 2811 * 2812 * On fail call [[Deflate#onEnd]] with error code and return false. 2813 * 2814 * We strongly recommend to use `Uint8Array` on input for best speed (output 2815 * array format is detected automatically). Also, don't skip last param and always 2816 * use the same type in your code (boolean or number). That will improve JS speed. 2817 * 2818 * For regular `Array`-s make sure all elements are [0..255]. 2819 * 2820 * ##### Example 2821 * 2822 * ```javascript 2823 * push(chunk, false); // push one of data chunks 2824 * ... 2825 * push(chunk, true); // push last chunk 2826 * ``` 2827 **/ 2828 Deflate.prototype.push = function(data, mode) { 2829 var strm = this.strm; 2830 var chunkSize = this.options.chunkSize; 2831 var status, _mode; 2832 2833 if (this.ended) { return false; } 2834 2835 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); 2836 2837 // Convert data if needed 2838 if (typeof data === 'string') { 2839 // If we need to compress text, change encoding to utf8. 2840 strm.input = strings.string2buf(data); 2841 } else { 2842 strm.input = data; 2843 } 2844 2845 strm.next_in = 0; 2846 strm.avail_in = strm.input.length; 2847 2848 do { 2849 if (strm.avail_out === 0) { 2850 strm.output = new utils.Buf8(chunkSize); 2851 strm.next_out = 0; 2852 strm.avail_out = chunkSize; 2853 } 2854 status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ 2855 2856 if (status !== Z_STREAM_END && status !== Z_OK) { 2857 this.onEnd(status); 2858 this.ended = true; 2859 return false; 2860 } 2861 if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) { 2862 if (this.options.to === 'string') { 2863 this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); 2864 } else { 2865 this.onData(utils.shrinkBuf(strm.output, strm.next_out)); 2866 } 2867 } 2868 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); 2869 2870 // Finalize on the last chunk. 2871 if (_mode === Z_FINISH) { 2872 status = zlib_deflate.deflateEnd(this.strm); 2873 this.onEnd(status); 2874 this.ended = true; 2875 return status === Z_OK; 2876 } 2877 2878 return true; 2879 }; 2880 2881 2882 /** 2883 * Deflate#onData(chunk) -> Void 2884 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends 2885 * on js engine support. When string output requested, each chunk 2886 * will be string. 2887 * 2888 * By default, stores data blocks in `chunks[]` property and glue 2889 * those in `onEnd`. Override this handler, if you need another behaviour. 2890 **/ 2891 Deflate.prototype.onData = function(chunk) { 2892 this.chunks.push(chunk); 2893 }; 2894 2895 2896 /** 2897 * Deflate#onEnd(status) -> Void 2898 * - status (Number): deflate status. 0 (Z_OK) on success, 2899 * other if not. 2900 * 2901 * Called once after you tell deflate that input stream complete 2902 * or error happenned. By default - join collected chunks, 2903 * free memory and fill `results` / `err` properties. 2904 **/ 2905 Deflate.prototype.onEnd = function(status) { 2906 // On success - join 2907 if (status === Z_OK) { 2908 if (this.options.to === 'string') { 2909 this.result = this.chunks.join(''); 2910 } else { 2911 this.result = utils.flattenChunks(this.chunks); 2912 } 2913 } 2914 this.chunks = []; 2915 this.err = status; 2916 this.msg = this.strm.msg; 2917 }; 2918 2919 2920 /** 2921 * deflate(data[, options]) -> Uint8Array|Array|String 2922 * - data (Uint8Array|Array|String): input data to compress. 2923 * - options (Object): zlib deflate options. 2924 * 2925 * Compress `data` with deflate alrorythm and `options`. 2926 * 2927 * Supported options are: 2928 * 2929 * - level 2930 * - windowBits 2931 * - memLevel 2932 * - strategy 2933 * 2934 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) 2935 * for more information on these. 2936 * 2937 * Sugar (options): 2938 * 2939 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify 2940 * negative windowBits implicitly. 2941 * - `to` (String) - if equal to 'string', then result will be "binary string" 2942 * (each char code [0..255]) 2943 * 2944 * ##### Example: 2945 * 2946 * ```javascript 2947 * var pako = require('pako') 2948 * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); 2949 * 2950 * console.log(pako.deflate(data)); 2951 * ``` 2952 **/ 2953 function deflate(input, options) { 2954 var deflator = new Deflate(options); 2955 2956 deflator.push(input, true); 2957 2958 // That will never happens, if you don't cheat with options :) 2959 if (deflator.err) { throw deflator.msg; } 2960 2961 return deflator.result; 2962 } 2963 2964 2965 /** 2966 * deflateRaw(data[, options]) -> Uint8Array|Array|String 2967 * - data (Uint8Array|Array|String): input data to compress. 2968 * - options (Object): zlib deflate options. 2969 * 2970 * The same as [[deflate]], but creates raw data, without wrapper 2971 * (header and adler32 crc). 2972 **/ 2973 function deflateRaw(input, options) { 2974 options = options || {}; 2975 options.raw = true; 2976 return deflate(input, options); 2977 } 2978 2979 2980 /** 2981 * gzip(data[, options]) -> Uint8Array|Array|String 2982 * - data (Uint8Array|Array|String): input data to compress. 2983 * - options (Object): zlib deflate options. 2984 * 2985 * The same as [[deflate]], but create gzip wrapper instead of 2986 * deflate one. 2987 **/ 2988 function gzip(input, options) { 2989 options = options || {}; 2990 options.gzip = true; 2991 return deflate(input, options); 2992 } 2993 2994 2995 exports.Deflate = Deflate; 2996 exports.deflate = deflate; 2997 exports.deflateRaw = deflateRaw; 2998 exports.gzip = gzip; 2999 },{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(_dereq_,module,exports){ 3000 'use strict'; 3001 3002 3003 var zlib_inflate = _dereq_('./zlib/inflate.js'); 3004 var utils = _dereq_('./utils/common'); 3005 var strings = _dereq_('./utils/strings'); 3006 var c = _dereq_('./zlib/constants'); 3007 var msg = _dereq_('./zlib/messages'); 3008 var zstream = _dereq_('./zlib/zstream'); 3009 var gzheader = _dereq_('./zlib/gzheader'); 3010 3011 3012 /** 3013 * class Inflate 3014 * 3015 * Generic JS-style wrapper for zlib calls. If you don't need 3016 * streaming behaviour - use more simple functions: [[inflate]] 3017 * and [[inflateRaw]]. 3018 **/ 3019 3020 /* internal 3021 * inflate.chunks -> Array 3022 * 3023 * Chunks of output data, if [[Inflate#onData]] not overriden. 3024 **/ 3025 3026 /** 3027 * Inflate.result -> Uint8Array|Array|String 3028 * 3029 * Uncompressed result, generated by default [[Inflate#onData]] 3030 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk 3031 * (call [[Inflate#push]] with `Z_FINISH` / `true` param). 3032 **/ 3033 3034 /** 3035 * Inflate.err -> Number 3036 * 3037 * Error code after inflate finished. 0 (Z_OK) on success. 3038 * Should be checked if broken data possible. 3039 **/ 3040 3041 /** 3042 * Inflate.msg -> String 3043 * 3044 * Error message, if [[Inflate.err]] != 0 3045 **/ 3046 3047 3048 /** 3049 * new Inflate(options) 3050 * - options (Object): zlib inflate options. 3051 * 3052 * Creates new inflator instance with specified params. Throws exception 3053 * on bad params. Supported options: 3054 * 3055 * - `windowBits` 3056 * 3057 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) 3058 * for more information on these. 3059 * 3060 * Additional options, for internal needs: 3061 * 3062 * - `chunkSize` - size of generated data chunks (16K by default) 3063 * - `raw` (Boolean) - do raw inflate 3064 * - `to` (String) - if equal to 'string', then result will be converted 3065 * from utf8 to utf16 (javascript) string. When string output requested, 3066 * chunk length can differ from `chunkSize`, depending on content. 3067 * 3068 * By default, when no options set, autodetect deflate/gzip data format via 3069 * wrapper header. 3070 * 3071 * ##### Example: 3072 * 3073 * ```javascript 3074 * var pako = require('pako') 3075 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) 3076 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); 3077 * 3078 * var inflate = new pako.Inflate({ level: 3}); 3079 * 3080 * inflate.push(chunk1, false); 3081 * inflate.push(chunk2, true); // true -> last chunk 3082 * 3083 * if (inflate.err) { throw new Error(inflate.err); } 3084 * 3085 * console.log(inflate.result); 3086 * ``` 3087 **/ 3088 var Inflate = function(options) { 3089 3090 this.options = utils.assign({ 3091 chunkSize: 16384, 3092 windowBits: 0, 3093 to: '' 3094 }, options || {}); 3095 3096 var opt = this.options; 3097 3098 // Force window size for `raw` data, if not set directly, 3099 // because we have no header for autodetect. 3100 if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { 3101 opt.windowBits = -opt.windowBits; 3102 if (opt.windowBits === 0) { opt.windowBits = -15; } 3103 } 3104 3105 // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate 3106 if ((opt.windowBits >= 0) && (opt.windowBits < 16) && 3107 !(options && options.windowBits)) { 3108 opt.windowBits += 32; 3109 } 3110 3111 // Gzip header has no info about windows size, we can do autodetect only 3112 // for deflate. So, if window size not set, force it to max when gzip possible 3113 if ((opt.windowBits > 15) && (opt.windowBits < 48)) { 3114 // bit 3 (16) -> gzipped data 3115 // bit 4 (32) -> autodetect gzip/deflate 3116 if ((opt.windowBits & 15) === 0) { 3117 opt.windowBits |= 15; 3118 } 3119 } 3120 3121 this.err = 0; // error code, if happens (0 = Z_OK) 3122 this.msg = ''; // error message 3123 this.ended = false; // used to avoid multiple onEnd() calls 3124 this.chunks = []; // chunks of compressed data 3125 3126 this.strm = new zstream(); 3127 this.strm.avail_out = 0; 3128 3129 var status = zlib_inflate.inflateInit2( 3130 this.strm, 3131 opt.windowBits 3132 ); 3133 3134 if (status !== c.Z_OK) { 3135 throw new Error(msg[status]); 3136 } 3137 3138 this.header = new gzheader(); 3139 3140 zlib_inflate.inflateGetHeader(this.strm, this.header); 3141 }; 3142 3143 /** 3144 * Inflate#push(data[, mode]) -> Boolean 3145 * - data (Uint8Array|Array|String): input data 3146 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. 3147 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. 3148 * 3149 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with 3150 * new output chunks. Returns `true` on success. The last data block must have 3151 * mode Z_FINISH (or `true`). That flush internal pending buffers and call 3152 * [[Inflate#onEnd]]. 3153 * 3154 * On fail call [[Inflate#onEnd]] with error code and return false. 3155 * 3156 * We strongly recommend to use `Uint8Array` on input for best speed (output 3157 * format is detected automatically). Also, don't skip last param and always 3158 * use the same type in your code (boolean or number). That will improve JS speed. 3159 * 3160 * For regular `Array`-s make sure all elements are [0..255]. 3161 * 3162 * ##### Example 3163 * 3164 * ```javascript 3165 * push(chunk, false); // push one of data chunks 3166 * ... 3167 * push(chunk, true); // push last chunk 3168 * ``` 3169 **/ 3170 Inflate.prototype.push = function(data, mode) { 3171 var strm = this.strm; 3172 var chunkSize = this.options.chunkSize; 3173 var status, _mode; 3174 var next_out_utf8, tail, utf8str; 3175 3176 if (this.ended) { return false; } 3177 _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); 3178 3179 // Convert data if needed 3180 if (typeof data === 'string') { 3181 // Only binary strings can be decompressed on practice 3182 strm.input = strings.binstring2buf(data); 3183 } else { 3184 strm.input = data; 3185 } 3186 3187 strm.next_in = 0; 3188 strm.avail_in = strm.input.length; 3189 3190 do { 3191 if (strm.avail_out === 0) { 3192 strm.output = new utils.Buf8(chunkSize); 3193 strm.next_out = 0; 3194 strm.avail_out = chunkSize; 3195 } 3196 3197 status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ 3198 3199 if (status !== c.Z_STREAM_END && status !== c.Z_OK) { 3200 this.onEnd(status); 3201 this.ended = true; 3202 return false; 3203 } 3204 3205 if (strm.next_out) { 3206 if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) { 3207 3208 if (this.options.to === 'string') { 3209 3210 next_out_utf8 = strings.utf8border(strm.output, strm.next_out); 3211 3212 tail = strm.next_out - next_out_utf8; 3213 utf8str = strings.buf2string(strm.output, next_out_utf8); 3214 3215 // move tail 3216 strm.next_out = tail; 3217 strm.avail_out = chunkSize - tail; 3218 if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } 3219 3220 this.onData(utf8str); 3221 3222 } else { 3223 this.onData(utils.shrinkBuf(strm.output, strm.next_out)); 3224 } 3225 } 3226 } 3227 } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END); 3228 3229 if (status === c.Z_STREAM_END) { 3230 _mode = c.Z_FINISH; 3231 } 3232 // Finalize on the last chunk. 3233 if (_mode === c.Z_FINISH) { 3234 status = zlib_inflate.inflateEnd(this.strm); 3235 this.onEnd(status); 3236 this.ended = true; 3237 return status === c.Z_OK; 3238 } 3239 3240 return true; 3241 }; 3242 3243 3244 /** 3245 * Inflate#onData(chunk) -> Void 3246 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends 3247 * on js engine support. When string output requested, each chunk 3248 * will be string. 3249 * 3250 * By default, stores data blocks in `chunks[]` property and glue 3251 * those in `onEnd`. Override this handler, if you need another behaviour. 3252 **/ 3253 Inflate.prototype.onData = function(chunk) { 3254 this.chunks.push(chunk); 3255 }; 3256 3257 3258 /** 3259 * Inflate#onEnd(status) -> Void 3260 * - status (Number): inflate status. 0 (Z_OK) on success, 3261 * other if not. 3262 * 3263 * Called once after you tell inflate that input stream complete 3264 * or error happenned. By default - join collected chunks, 3265 * free memory and fill `results` / `err` properties. 3266 **/ 3267 Inflate.prototype.onEnd = function(status) { 3268 // On success - join 3269 if (status === c.Z_OK) { 3270 if (this.options.to === 'string') { 3271 // Glue & convert here, until we teach pako to send 3272 // utf8 alligned strings to onData 3273 this.result = this.chunks.join(''); 3274 } else { 3275 this.result = utils.flattenChunks(this.chunks); 3276 } 3277 } 3278 this.chunks = []; 3279 this.err = status; 3280 this.msg = this.strm.msg; 3281 }; 3282 3283 3284 /** 3285 * inflate(data[, options]) -> Uint8Array|Array|String 3286 * - data (Uint8Array|Array|String): input data to decompress. 3287 * - options (Object): zlib inflate options. 3288 * 3289 * Decompress `data` with inflate/ungzip and `options`. Autodetect 3290 * format via wrapper header by default. That's why we don't provide 3291 * separate `ungzip` method. 3292 * 3293 * Supported options are: 3294 * 3295 * - windowBits 3296 * 3297 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) 3298 * for more information. 3299 * 3300 * Sugar (options): 3301 * 3302 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify 3303 * negative windowBits implicitly. 3304 * - `to` (String) - if equal to 'string', then result will be converted 3305 * from utf8 to utf16 (javascript) string. When string output requested, 3306 * chunk length can differ from `chunkSize`, depending on content. 3307 * 3308 * 3309 * ##### Example: 3310 * 3311 * ```javascript 3312 * var pako = require('pako') 3313 * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) 3314 * , output; 3315 * 3316 * try { 3317 * output = pako.inflate(input); 3318 * } catch (err) 3319 * console.log(err); 3320 * } 3321 * ``` 3322 **/ 3323 function inflate(input, options) { 3324 var inflator = new Inflate(options); 3325 3326 inflator.push(input, true); 3327 3328 // That will never happens, if you don't cheat with options :) 3329 if (inflator.err) { throw inflator.msg; } 3330 3331 return inflator.result; 3332 } 3333 3334 3335 /** 3336 * inflateRaw(data[, options]) -> Uint8Array|Array|String 3337 * - data (Uint8Array|Array|String): input data to decompress. 3338 * - options (Object): zlib inflate options. 3339 * 3340 * The same as [[inflate]], but creates raw data, without wrapper 3341 * (header and adler32 crc). 3342 **/ 3343 function inflateRaw(input, options) { 3344 options = options || {}; 3345 options.raw = true; 3346 return inflate(input, options); 3347 } 3348 3349 3350 /** 3351 * ungzip(data[, options]) -> Uint8Array|Array|String 3352 * - data (Uint8Array|Array|String): input data to decompress. 3353 * - options (Object): zlib inflate options. 3354 * 3355 * Just shortcut to [[inflate]], because it autodetects format 3356 * by header.content. Done for convenience. 3357 **/ 3358 3359 3360 exports.Inflate = Inflate; 3361 exports.inflate = inflate; 3362 exports.inflateRaw = inflateRaw; 3363 exports.ungzip = inflate; 3364 3365 },{"./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){ 3366 'use strict'; 3367 3368 3369 var TYPED_OK = (typeof Uint8Array !== 'undefined') && 3370 (typeof Uint16Array !== 'undefined') && 3371 (typeof Int32Array !== 'undefined'); 3372 3373 3374 exports.assign = function (obj /*from1, from2, from3, ...*/) { 3375 var sources = Array.prototype.slice.call(arguments, 1); 3376 while (sources.length) { 3377 var source = sources.shift(); 3378 if (!source) { continue; } 3379 3380 if (typeof(source) !== 'object') { 3381 throw new TypeError(source + 'must be non-object'); 3382 } 3383 3384 for (var p in source) { 3385 if (source.hasOwnProperty(p)) { 3386 obj[p] = source[p]; 3387 } 3388 } 3389 } 3390 3391 return obj; 3392 }; 3393 3394 3395 // reduce buffer size, avoiding mem copy 3396 exports.shrinkBuf = function (buf, size) { 3397 if (buf.length === size) { return buf; } 3398 if (buf.subarray) { return buf.subarray(0, size); } 3399 buf.length = size; 3400 return buf; 3401 }; 3402 3403 3404 var fnTyped = { 3405 arraySet: function (dest, src, src_offs, len, dest_offs) { 3406 if (src.subarray && dest.subarray) { 3407 dest.set(src.subarray(src_offs, src_offs+len), dest_offs); 3408 return; 3409 } 3410 // Fallback to ordinary array 3411 for(var i=0; i<len; i++) { 3412 dest[dest_offs + i] = src[src_offs + i]; 3413 } 3414 }, 3415 // Join array of chunks to single array. 3416 flattenChunks: function(chunks) { 3417 var i, l, len, pos, chunk, result; 3418 3419 // calculate data length 3420 len = 0; 3421 for (i=0, l=chunks.length; i<l; i++) { 3422 len += chunks[i].length; 3423 } 3424 3425 // join chunks 3426 result = new Uint8Array(len); 3427 pos = 0; 3428 for (i=0, l=chunks.length; i<l; i++) { 3429 chunk = chunks[i]; 3430 result.set(chunk, pos); 3431 pos += chunk.length; 3432 } 3433 3434 return result; 3435 } 3436 }; 3437 3438 var fnUntyped = { 3439 arraySet: function (dest, src, src_offs, len, dest_offs) { 3440 for(var i=0; i<len; i++) { 3441 dest[dest_offs + i] = src[src_offs + i]; 3442 } 3443 }, 3444 // Join array of chunks to single array. 3445 flattenChunks: function(chunks) { 3446 return [].concat.apply([], chunks); 3447 } 3448 }; 3449 3450 3451 // Enable/Disable typed arrays use, for testing 3452 // 3453 exports.setTyped = function (on) { 3454 if (on) { 3455 exports.Buf8 = Uint8Array; 3456 exports.Buf16 = Uint16Array; 3457 exports.Buf32 = Int32Array; 3458 exports.assign(exports, fnTyped); 3459 } else { 3460 exports.Buf8 = Array; 3461 exports.Buf16 = Array; 3462 exports.Buf32 = Array; 3463 exports.assign(exports, fnUntyped); 3464 } 3465 }; 3466 3467 exports.setTyped(TYPED_OK); 3468 },{}],28:[function(_dereq_,module,exports){ 3469 // String encode/decode helpers 3470 'use strict'; 3471 3472 3473 var utils = _dereq_('./common'); 3474 3475 3476 // Quick check if we can use fast array to bin string conversion 3477 // 3478 // - apply(Array) can fail on Android 2.2 3479 // - apply(Uint8Array) can fail on iOS 5.1 Safary 3480 // 3481 var STR_APPLY_OK = true; 3482 var STR_APPLY_UIA_OK = true; 3483 3484 try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; } 3485 try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; } 3486 3487 3488 // Table with utf8 lengths (calculated by first byte of sequence) 3489 // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, 3490 // because max possible codepoint is 0x10ffff 3491 var _utf8len = new utils.Buf8(256); 3492 for (var i=0; i<256; i++) { 3493 _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1); 3494 } 3495 _utf8len[254]=_utf8len[254]=1; // Invalid sequence start 3496 3497 3498 // convert string to array (typed, when possible) 3499 exports.string2buf = function (str) { 3500 var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; 3501 3502 // count binary size 3503 for (m_pos = 0; m_pos < str_len; m_pos++) { 3504 c = str.charCodeAt(m_pos); 3505 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { 3506 c2 = str.charCodeAt(m_pos+1); 3507 if ((c2 & 0xfc00) === 0xdc00) { 3508 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); 3509 m_pos++; 3510 } 3511 } 3512 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; 3513 } 3514 3515 // allocate buffer 3516 buf = new utils.Buf8(buf_len); 3517 3518 // convert 3519 for (i=0, m_pos = 0; i < buf_len; m_pos++) { 3520 c = str.charCodeAt(m_pos); 3521 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { 3522 c2 = str.charCodeAt(m_pos+1); 3523 if ((c2 & 0xfc00) === 0xdc00) { 3524 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); 3525 m_pos++; 3526 } 3527 } 3528 if (c < 0x80) { 3529 /* one byte */ 3530 buf[i++] = c; 3531 } else if (c < 0x800) { 3532 /* two bytes */ 3533 buf[i++] = 0xC0 | (c >>> 6); 3534 buf[i++] = 0x80 | (c & 0x3f); 3535 } else if (c < 0x10000) { 3536 /* three bytes */ 3537 buf[i++] = 0xE0 | (c >>> 12); 3538 buf[i++] = 0x80 | (c >>> 6 & 0x3f); 3539 buf[i++] = 0x80 | (c & 0x3f); 3540 } else { 3541 /* four bytes */ 3542 buf[i++] = 0xf0 | (c >>> 18); 3543 buf[i++] = 0x80 | (c >>> 12 & 0x3f); 3544 buf[i++] = 0x80 | (c >>> 6 & 0x3f); 3545 buf[i++] = 0x80 | (c & 0x3f); 3546 } 3547 } 3548 3549 return buf; 3550 }; 3551 3552 // Helper (used in 2 places) 3553 function buf2binstring(buf, len) { 3554 // use fallback for big arrays to avoid stack overflow 3555 if (len < 65537) { 3556 if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { 3557 return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); 3558 } 3559 } 3560 3561 var result = ''; 3562 for(var i=0; i < len; i++) { 3563 result += String.fromCharCode(buf[i]); 3564 } 3565 return result; 3566 } 3567 3568 3569 // Convert byte array to binary string 3570 exports.buf2binstring = function(buf) { 3571 return buf2binstring(buf, buf.length); 3572 }; 3573 3574 3575 // Convert binary string (typed, when possible) 3576 exports.binstring2buf = function(str) { 3577 var buf = new utils.Buf8(str.length); 3578 for(var i=0, len=buf.length; i < len; i++) { 3579 buf[i] = str.charCodeAt(i); 3580 } 3581 return buf; 3582 }; 3583 3584 3585 // convert array to string 3586 exports.buf2string = function (buf, max) { 3587 var i, out, c, c_len; 3588 var len = max || buf.length; 3589 3590 // Reserve max possible length (2 words per char) 3591 // NB: by unknown reasons, Array is significantly faster for 3592 // String.fromCharCode.apply than Uint16Array. 3593 var utf16buf = new Array(len*2); 3594 3595 for (out=0, i=0; i<len;) { 3596 c = buf[i++]; 3597 // quick process ascii 3598 if (c < 0x80) { utf16buf[out++] = c; continue; } 3599 3600 c_len = _utf8len[c]; 3601 // skip 5 & 6 byte codes 3602 if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } 3603 3604 // apply mask on first byte 3605 c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; 3606 // join the rest 3607 while (c_len > 1 && i < len) { 3608 c = (c << 6) | (buf[i++] & 0x3f); 3609 c_len--; 3610 } 3611 3612 // terminated by end of string? 3613 if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } 3614 3615 if (c < 0x10000) { 3616 utf16buf[out++] = c; 3617 } else { 3618 c -= 0x10000; 3619 utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); 3620 utf16buf[out++] = 0xdc00 | (c & 0x3ff); 3621 } 3622 } 3623 3624 return buf2binstring(utf16buf, out); 3625 }; 3626 3627 3628 // Calculate max possible position in utf8 buffer, 3629 // that will not break sequence. If that's not possible 3630 // - (very small limits) return max size as is. 3631 // 3632 // buf[] - utf8 bytes array 3633 // max - length limit (mandatory); 3634 exports.utf8border = function(buf, max) { 3635 var pos; 3636 3637 max = max || buf.length; 3638 if (max > buf.length) { max = buf.length; } 3639 3640 // go back from last position, until start of sequence found 3641 pos = max-1; 3642 while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } 3643 3644 // Fuckup - very small and broken sequence, 3645 // return max, because we should return something anyway. 3646 if (pos < 0) { return max; } 3647 3648 // If we came to start of buffer - that means vuffer is too small, 3649 // return max too. 3650 if (pos === 0) { return max; } 3651 3652 return (pos + _utf8len[buf[pos]] > max) ? pos : max; 3653 }; 3654 3655 },{"./common":27}],29:[function(_dereq_,module,exports){ 3656 'use strict'; 3657 3658 // Note: adler32 takes 12% for level 0 and 2% for level 6. 3659 // It doesn't worth to make additional optimizationa as in original. 3660 // Small size is preferable. 3661 3662 function adler32(adler, buf, len, pos) { 3663 var s1 = (adler & 0xffff) |0 3664 , s2 = ((adler >>> 16) & 0xffff) |0 3665 , n = 0; 3666 3667 while (len !== 0) { 3668 // Set limit ~ twice less than 5552, to keep 3669 // s2 in 31-bits, because we force signed ints. 3670 // in other case %= will fail. 3671 n = len > 2000 ? 2000 : len; 3672 len -= n; 3673 3674 do { 3675 s1 = (s1 + buf[pos++]) |0; 3676 s2 = (s2 + s1) |0; 3677 } while (--n); 3678 3679 s1 %= 65521; 3680 s2 %= 65521; 3681 } 3682 3683 return (s1 | (s2 << 16)) |0; 3684 } 3685 3686 3687 module.exports = adler32; 3688 },{}],30:[function(_dereq_,module,exports){ 3689 module.exports = { 3690 3691 /* Allowed flush values; see deflate() and inflate() below for details */ 3692 Z_NO_FLUSH: 0, 3693 Z_PARTIAL_FLUSH: 1, 3694 Z_SYNC_FLUSH: 2, 3695 Z_FULL_FLUSH: 3, 3696 Z_FINISH: 4, 3697 Z_BLOCK: 5, 3698 Z_TREES: 6, 3699 3700 /* Return codes for the compression/decompression functions. Negative values 3701 * are errors, positive values are used for special but normal events. 3702 */ 3703 Z_OK: 0, 3704 Z_STREAM_END: 1, 3705 Z_NEED_DICT: 2, 3706 Z_ERRNO: -1, 3707 Z_STREAM_ERROR: -2, 3708 Z_DATA_ERROR: -3, 3709 //Z_MEM_ERROR: -4, 3710 Z_BUF_ERROR: -5, 3711 //Z_VERSION_ERROR: -6, 3712 3713 /* compression levels */ 3714 Z_NO_COMPRESSION: 0, 3715 Z_BEST_SPEED: 1, 3716 Z_BEST_COMPRESSION: 9, 3717 Z_DEFAULT_COMPRESSION: -1, 3718 3719 3720 Z_FILTERED: 1, 3721 Z_HUFFMAN_ONLY: 2, 3722 Z_RLE: 3, 3723 Z_FIXED: 4, 3724 Z_DEFAULT_STRATEGY: 0, 3725 3726 /* Possible values of the data_type field (though see inflate()) */ 3727 Z_BINARY: 0, 3728 Z_TEXT: 1, 3729 //Z_ASCII: 1, // = Z_TEXT (deprecated) 3730 Z_UNKNOWN: 2, 3731 3732 /* The deflate compression method */ 3733 Z_DEFLATED: 8 3734 //Z_NULL: null // Use -1 or null inline, depending on var type 3735 }; 3736 },{}],31:[function(_dereq_,module,exports){ 3737 'use strict'; 3738 3739 // Note: we can't get significant speed boost here. 3740 // So write code to minimize size - no pregenerated tables 3741 // and array tools dependencies. 3742 3743 3744 // Use ordinary array, since untyped makes no boost here 3745 function makeTable() { 3746 var c, table = []; 3747 3748 for(var n =0; n < 256; n++){ 3749 c = n; 3750 for(var k =0; k < 8; k++){ 3751 c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); 3752 } 3753 table[n] = c; 3754 } 3755 3756 return table; 3757 } 3758 3759 // Create table on load. Just 255 signed longs. Not a problem. 3760 var crcTable = makeTable(); 3761 3762 3763 function crc32(crc, buf, len, pos) { 3764 var t = crcTable 3765 , end = pos + len; 3766 3767 crc = crc ^ (-1); 3768 3769 for (var i = pos; i < end; i++ ) { 3770 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; 3771 } 3772 3773 return (crc ^ (-1)); // >>> 0; 3774 } 3775 3776 3777 module.exports = crc32; 3778 },{}],32:[function(_dereq_,module,exports){ 3779 'use strict'; 3780 3781 var utils = _dereq_('../utils/common'); 3782 var trees = _dereq_('./trees'); 3783 var adler32 = _dereq_('./adler32'); 3784 var crc32 = _dereq_('./crc32'); 3785 var msg = _dereq_('./messages'); 3786 3787 /* Public constants ==========================================================*/ 3788 /* ===========================================================================*/ 3789 3790 3791 /* Allowed flush values; see deflate() and inflate() below for details */ 3792 var Z_NO_FLUSH = 0; 3793 var Z_PARTIAL_FLUSH = 1; 3794 //var Z_SYNC_FLUSH = 2; 3795 var Z_FULL_FLUSH = 3; 3796 var Z_FINISH = 4; 3797 var Z_BLOCK = 5; 3798 //var Z_TREES = 6; 3799 3800 3801 /* Return codes for the compression/decompression functions. Negative values 3802 * are errors, positive values are used for special but normal events. 3803 */ 3804 var Z_OK = 0; 3805 var Z_STREAM_END = 1; 3806 //var Z_NEED_DICT = 2; 3807 //var Z_ERRNO = -1; 3808 var Z_STREAM_ERROR = -2; 3809 var Z_DATA_ERROR = -3; 3810 //var Z_MEM_ERROR = -4; 3811 var Z_BUF_ERROR = -5; 3812 //var Z_VERSION_ERROR = -6; 3813 3814 3815 /* compression levels */ 3816 //var Z_NO_COMPRESSION = 0; 3817 //var Z_BEST_SPEED = 1; 3818 //var Z_BEST_COMPRESSION = 9; 3819 var Z_DEFAULT_COMPRESSION = -1; 3820 3821 3822 var Z_FILTERED = 1; 3823 var Z_HUFFMAN_ONLY = 2; 3824 var Z_RLE = 3; 3825 var Z_FIXED = 4; 3826 var Z_DEFAULT_STRATEGY = 0; 3827 3828 /* Possible values of the data_type field (though see inflate()) */ 3829 //var Z_BINARY = 0; 3830 //var Z_TEXT = 1; 3831 //var Z_ASCII = 1; // = Z_TEXT 3832 var Z_UNKNOWN = 2; 3833 3834 3835 /* The deflate compression method */ 3836 var Z_DEFLATED = 8; 3837 3838 /*============================================================================*/ 3839 3840 3841 var MAX_MEM_LEVEL = 9; 3842 /* Maximum value for memLevel in deflateInit2 */ 3843 var MAX_WBITS = 15; 3844 /* 32K LZ77 window */ 3845 var DEF_MEM_LEVEL = 8; 3846 3847 3848 var LENGTH_CODES = 29; 3849 /* number of length codes, not counting the special END_BLOCK code */ 3850 var LITERALS = 256; 3851 /* number of literal bytes 0..255 */ 3852 var L_CODES = LITERALS + 1 + LENGTH_CODES; 3853 /* number of Literal or Length codes, including the END_BLOCK code */ 3854 var D_CODES = 30; 3855 /* number of distance codes */ 3856 var BL_CODES = 19; 3857 /* number of codes used to transfer the bit lengths */ 3858 var HEAP_SIZE = 2*L_CODES + 1; 3859 /* maximum heap size */ 3860 var MAX_BITS = 15; 3861 /* All codes must not exceed MAX_BITS bits */ 3862 3863 var MIN_MATCH = 3; 3864 var MAX_MATCH = 258; 3865 var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); 3866 3867 var PRESET_DICT = 0x20; 3868 3869 var INIT_STATE = 42; 3870 var EXTRA_STATE = 69; 3871 var NAME_STATE = 73; 3872 var COMMENT_STATE = 91; 3873 var HCRC_STATE = 103; 3874 var BUSY_STATE = 113; 3875 var FINISH_STATE = 666; 3876 3877 var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ 3878 var BS_BLOCK_DONE = 2; /* block flush performed */ 3879 var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ 3880 var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ 3881 3882 var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. 3883 3884 function err(strm, errorCode) { 3885 strm.msg = msg[errorCode]; 3886 return errorCode; 3887 } 3888 3889 function rank(f) { 3890 return ((f) << 1) - ((f) > 4 ? 9 : 0); 3891 } 3892 3893 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } 3894 3895 3896 /* ========================================================================= 3897 * Flush as much pending output as possible. All deflate() output goes 3898 * through this function so some applications may wish to modify it 3899 * to avoid allocating a large strm->output buffer and copying into it. 3900 * (See also read_buf()). 3901 */ 3902 function flush_pending(strm) { 3903 var s = strm.state; 3904 3905 //_tr_flush_bits(s); 3906 var len = s.pending; 3907 if (len > strm.avail_out) { 3908 len = strm.avail_out; 3909 } 3910 if (len === 0) { return; } 3911 3912 utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); 3913 strm.next_out += len; 3914 s.pending_out += len; 3915 strm.total_out += len; 3916 strm.avail_out -= len; 3917 s.pending -= len; 3918 if (s.pending === 0) { 3919 s.pending_out = 0; 3920 } 3921 } 3922 3923 3924 function flush_block_only (s, last) { 3925 trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); 3926 s.block_start = s.strstart; 3927 flush_pending(s.strm); 3928 } 3929 3930 3931 function put_byte(s, b) { 3932 s.pending_buf[s.pending++] = b; 3933 } 3934 3935 3936 /* ========================================================================= 3937 * Put a short in the pending buffer. The 16-bit value is put in MSB order. 3938 * IN assertion: the stream state is correct and there is enough room in 3939 * pending_buf. 3940 */ 3941 function putShortMSB(s, b) { 3942 // put_byte(s, (Byte)(b >> 8)); 3943 // put_byte(s, (Byte)(b & 0xff)); 3944 s.pending_buf[s.pending++] = (b >>> 8) & 0xff; 3945 s.pending_buf[s.pending++] = b & 0xff; 3946 } 3947 3948 3949 /* =========================================================================== 3950 * Read a new buffer from the current input stream, update the adler32 3951 * and total number of bytes read. All deflate() input goes through 3952 * this function so some applications may wish to modify it to avoid 3953 * allocating a large strm->input buffer and copying from it. 3954 * (See also flush_pending()). 3955 */ 3956 function read_buf(strm, buf, start, size) { 3957 var len = strm.avail_in; 3958 3959 if (len > size) { len = size; } 3960 if (len === 0) { return 0; } 3961 3962 strm.avail_in -= len; 3963 3964 utils.arraySet(buf, strm.input, strm.next_in, len, start); 3965 if (strm.state.wrap === 1) { 3966 strm.adler = adler32(strm.adler, buf, len, start); 3967 } 3968 3969 else if (strm.state.wrap === 2) { 3970 strm.adler = crc32(strm.adler, buf, len, start); 3971 } 3972 3973 strm.next_in += len; 3974 strm.total_in += len; 3975 3976 return len; 3977 } 3978 3979 3980 /* =========================================================================== 3981 * Set match_start to the longest match starting at the given string and 3982 * return its length. Matches shorter or equal to prev_length are discarded, 3983 * in which case the result is equal to prev_length and match_start is 3984 * garbage. 3985 * IN assertions: cur_match is the head of the hash chain for the current 3986 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 3987 * OUT assertion: the match length is not greater than s->lookahead. 3988 */ 3989 function longest_match(s, cur_match) { 3990 var chain_length = s.max_chain_length; /* max hash chain length */ 3991 var scan = s.strstart; /* current string */ 3992 var match; /* matched string */ 3993 var len; /* length of current match */ 3994 var best_len = s.prev_length; /* best match length so far */ 3995 var nice_match = s.nice_match; /* stop if match long enough */ 3996 var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? 3997 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; 3998 3999 var _win = s.window; // shortcut 4000 4001 var wmask = s.w_mask; 4002 var prev = s.prev; 4003 4004 /* Stop when cur_match becomes <= limit. To simplify the code, 4005 * we prevent matches with the string of window index 0. 4006 */ 4007 4008 var strend = s.strstart + MAX_MATCH; 4009 var scan_end1 = _win[scan + best_len - 1]; 4010 var scan_end = _win[scan + best_len]; 4011 4012 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. 4013 * It is easy to get rid of this optimization if necessary. 4014 */ 4015 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); 4016 4017 /* Do not waste too much time if we already have a good match: */ 4018 if (s.prev_length >= s.good_match) { 4019 chain_length >>= 2; 4020 } 4021 /* Do not look for matches beyond the end of the input. This is necessary 4022 * to make deflate deterministic. 4023 */ 4024 if (nice_match > s.lookahead) { nice_match = s.lookahead; } 4025 4026 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); 4027 4028 do { 4029 // Assert(cur_match < s->strstart, "no future"); 4030 match = cur_match; 4031 4032 /* Skip to next match if the match length cannot increase 4033 * or if the match length is less than 2. Note that the checks below 4034 * for insufficient lookahead only occur occasionally for performance 4035 * reasons. Therefore uninitialized memory will be accessed, and 4036 * conditional jumps will be made that depend on those values. 4037 * However the length of the match is limited to the lookahead, so 4038 * the output of deflate is not affected by the uninitialized values. 4039 */ 4040 4041 if (_win[match + best_len] !== scan_end || 4042 _win[match + best_len - 1] !== scan_end1 || 4043 _win[match] !== _win[scan] || 4044 _win[++match] !== _win[scan + 1]) { 4045 continue; 4046 } 4047 4048 /* The check at best_len-1 can be removed because it will be made 4049 * again later. (This heuristic is not always a win.) 4050 * It is not necessary to compare scan[2] and match[2] since they 4051 * are always equal when the other bytes match, given that 4052 * the hash keys are equal and that HASH_BITS >= 8. 4053 */ 4054 scan += 2; 4055 match++; 4056 // Assert(*scan == *match, "match[2]?"); 4057 4058 /* We check for insufficient lookahead only every 8th comparison; 4059 * the 256th check will be made at strstart+258. 4060 */ 4061 do { 4062 /*jshint noempty:false*/ 4063 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && 4064 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && 4065 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && 4066 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && 4067 scan < strend); 4068 4069 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); 4070 4071 len = MAX_MATCH - (strend - scan); 4072 scan = strend - MAX_MATCH; 4073 4074 if (len > best_len) { 4075 s.match_start = cur_match; 4076 best_len = len; 4077 if (len >= nice_match) { 4078 break; 4079 } 4080 scan_end1 = _win[scan + best_len - 1]; 4081 scan_end = _win[scan + best_len]; 4082 } 4083 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); 4084 4085 if (best_len <= s.lookahead) { 4086 return best_len; 4087 } 4088 return s.lookahead; 4089 } 4090 4091 4092 /* =========================================================================== 4093 * Fill the window when the lookahead becomes insufficient. 4094 * Updates strstart and lookahead. 4095 * 4096 * IN assertion: lookahead < MIN_LOOKAHEAD 4097 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD 4098 * At least one byte has been read, or avail_in == 0; reads are 4099 * performed for at least two bytes (required for the zip translate_eol 4100 * option -- not supported here). 4101 */ 4102 function fill_window(s) { 4103 var _w_size = s.w_size; 4104 var p, n, m, more, str; 4105 4106 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); 4107 4108 do { 4109 more = s.window_size - s.lookahead - s.strstart; 4110 4111 // JS ints have 32 bit, block below not needed 4112 /* Deal with !@#$% 64K limit: */ 4113 //if (sizeof(int) <= 2) { 4114 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { 4115 // more = wsize; 4116 // 4117 // } else if (more == (unsigned)(-1)) { 4118 // /* Very unlikely, but possible on 16 bit machine if 4119 // * strstart == 0 && lookahead == 1 (input done a byte at time) 4120 // */ 4121 // more--; 4122 // } 4123 //} 4124 4125 4126 /* If the window is almost full and there is insufficient lookahead, 4127 * move the upper half to the lower one to make room in the upper half. 4128 */ 4129 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { 4130 4131 utils.arraySet(s.window, s.window, _w_size, _w_size, 0); 4132 s.match_start -= _w_size; 4133 s.strstart -= _w_size; 4134 /* we now have strstart >= MAX_DIST */ 4135 s.block_start -= _w_size; 4136 4137 /* Slide the hash table (could be avoided with 32 bit values 4138 at the expense of memory usage). We slide even when level == 0 4139 to keep the hash table consistent if we switch back to level > 0 4140 later. (Using level 0 permanently is not an optimal usage of 4141 zlib, so we don't care about this pathological case.) 4142 */ 4143 4144 n = s.hash_size; 4145 p = n; 4146 do { 4147 m = s.head[--p]; 4148 s.head[p] = (m >= _w_size ? m - _w_size : 0); 4149 } while (--n); 4150 4151 n = _w_size; 4152 p = n; 4153 do { 4154 m = s.prev[--p]; 4155 s.prev[p] = (m >= _w_size ? m - _w_size : 0); 4156 /* If n is not on any hash chain, prev[n] is garbage but 4157 * its value will never be used. 4158 */ 4159 } while (--n); 4160 4161 more += _w_size; 4162 } 4163 if (s.strm.avail_in === 0) { 4164 break; 4165 } 4166 4167 /* If there was no sliding: 4168 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && 4169 * more == window_size - lookahead - strstart 4170 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) 4171 * => more >= window_size - 2*WSIZE + 2 4172 * In the BIG_MEM or MMAP case (not yet supported), 4173 * window_size == input_size + MIN_LOOKAHEAD && 4174 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. 4175 * Otherwise, window_size == 2*WSIZE so more >= 2. 4176 * If there was sliding, more >= WSIZE. So in all cases, more >= 2. 4177 */ 4178 //Assert(more >= 2, "more < 2"); 4179 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); 4180 s.lookahead += n; 4181 4182 /* Initialize the hash value now that we have some input: */ 4183 if (s.lookahead + s.insert >= MIN_MATCH) { 4184 str = s.strstart - s.insert; 4185 s.ins_h = s.window[str]; 4186 4187 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ 4188 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; 4189 //#if MIN_MATCH != 3 4190 // Call update_hash() MIN_MATCH-3 more times 4191 //#endif 4192 while (s.insert) { 4193 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ 4194 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; 4195 4196 s.prev[str & s.w_mask] = s.head[s.ins_h]; 4197 s.head[s.ins_h] = str; 4198 str++; 4199 s.insert--; 4200 if (s.lookahead + s.insert < MIN_MATCH) { 4201 break; 4202 } 4203 } 4204 } 4205 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, 4206 * but this is not important since only literal bytes will be emitted. 4207 */ 4208 4209 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); 4210 4211 /* If the WIN_INIT bytes after the end of the current data have never been 4212 * written, then zero those bytes in order to avoid memory check reports of 4213 * the use of uninitialized (or uninitialised as Julian writes) bytes by 4214 * the longest match routines. Update the high water mark for the next 4215 * time through here. WIN_INIT is set to MAX_MATCH since the longest match 4216 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. 4217 */ 4218 // if (s.high_water < s.window_size) { 4219 // var curr = s.strstart + s.lookahead; 4220 // var init = 0; 4221 // 4222 // if (s.high_water < curr) { 4223 // /* Previous high water mark below current data -- zero WIN_INIT 4224 // * bytes or up to end of window, whichever is less. 4225 // */ 4226 // init = s.window_size - curr; 4227 // if (init > WIN_INIT) 4228 // init = WIN_INIT; 4229 // zmemzero(s->window + curr, (unsigned)init); 4230 // s->high_water = curr + init; 4231 // } 4232 // else if (s->high_water < (ulg)curr + WIN_INIT) { 4233 // /* High water mark at or above current data, but below current data 4234 // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up 4235 // * to end of window, whichever is less. 4236 // */ 4237 // init = (ulg)curr + WIN_INIT - s->high_water; 4238 // if (init > s->window_size - s->high_water) 4239 // init = s->window_size - s->high_water; 4240 // zmemzero(s->window + s->high_water, (unsigned)init); 4241 // s->high_water += init; 4242 // } 4243 // } 4244 // 4245 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, 4246 // "not enough room for search"); 4247 } 4248 4249 /* =========================================================================== 4250 * Copy without compression as much as possible from the input stream, return 4251 * the current block state. 4252 * This function does not insert new strings in the dictionary since 4253 * uncompressible data is probably not useful. This function is used 4254 * only for the level=0 compression option. 4255 * NOTE: this function should be optimized to avoid extra copying from 4256 * window to pending_buf. 4257 */ 4258 function deflate_stored(s, flush) { 4259 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited 4260 * to pending_buf_size, and each stored block has a 5 byte header: 4261 */ 4262 var max_block_size = 0xffff; 4263 4264 if (max_block_size > s.pending_buf_size - 5) { 4265 max_block_size = s.pending_buf_size - 5; 4266 } 4267 4268 /* Copy as much as possible from input to output: */ 4269 for (;;) { 4270 /* Fill the window as much as possible: */ 4271 if (s.lookahead <= 1) { 4272 4273 //Assert(s->strstart < s->w_size+MAX_DIST(s) || 4274 // s->block_start >= (long)s->w_size, "slide too late"); 4275 // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || 4276 // s.block_start >= s.w_size)) { 4277 // throw new Error("slide too late"); 4278 // } 4279 4280 fill_window(s); 4281 if (s.lookahead === 0 && flush === Z_NO_FLUSH) { 4282 return BS_NEED_MORE; 4283 } 4284 4285 if (s.lookahead === 0) { 4286 break; 4287 } 4288 /* flush the current block */ 4289 } 4290 //Assert(s->block_start >= 0L, "block gone"); 4291 // if (s.block_start < 0) throw new Error("block gone"); 4292 4293 s.strstart += s.lookahead; 4294 s.lookahead = 0; 4295 4296 /* Emit a stored block if pending_buf will be full: */ 4297 var max_start = s.block_start + max_block_size; 4298 4299 if (s.strstart === 0 || s.strstart >= max_start) { 4300 /* strstart == 0 is possible when wraparound on 16-bit machine */ 4301 s.lookahead = s.strstart - max_start; 4302 s.strstart = max_start; 4303 /*** FLUSH_BLOCK(s, 0); ***/ 4304 flush_block_only(s, false); 4305 if (s.strm.avail_out === 0) { 4306 return BS_NEED_MORE; 4307 } 4308 /***/ 4309 4310 4311 } 4312 /* Flush if we may have to slide, otherwise block_start may become 4313 * negative and the data will be gone: 4314 */ 4315 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { 4316 /*** FLUSH_BLOCK(s, 0); ***/ 4317 flush_block_only(s, false); 4318 if (s.strm.avail_out === 0) { 4319 return BS_NEED_MORE; 4320 } 4321 /***/ 4322 } 4323 } 4324 4325 s.insert = 0; 4326 4327 if (flush === Z_FINISH) { 4328 /*** FLUSH_BLOCK(s, 1); ***/ 4329 flush_block_only(s, true); 4330 if (s.strm.avail_out === 0) { 4331 return BS_FINISH_STARTED; 4332 } 4333 /***/ 4334 return BS_FINISH_DONE; 4335 } 4336 4337 if (s.strstart > s.block_start) { 4338 /*** FLUSH_BLOCK(s, 0); ***/ 4339 flush_block_only(s, false); 4340 if (s.strm.avail_out === 0) { 4341 return BS_NEED_MORE; 4342 } 4343 /***/ 4344 } 4345 4346 return BS_NEED_MORE; 4347 } 4348 4349 /* =========================================================================== 4350 * Compress as much as possible from the input stream, return the current 4351 * block state. 4352 * This function does not perform lazy evaluation of matches and inserts 4353 * new strings in the dictionary only for unmatched strings or for short 4354 * matches. It is used only for the fast compression options. 4355 */ 4356 function deflate_fast(s, flush) { 4357 var hash_head; /* head of the hash chain */ 4358 var bflush; /* set if current block must be flushed */ 4359 4360 for (;;) { 4361 /* Make sure that we always have enough lookahead, except 4362 * at the end of the input file. We need MAX_MATCH bytes 4363 * for the next match, plus MIN_MATCH bytes to insert the 4364 * string following the next match. 4365 */ 4366 if (s.lookahead < MIN_LOOKAHEAD) { 4367 fill_window(s); 4368 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { 4369 return BS_NEED_MORE; 4370 } 4371 if (s.lookahead === 0) { 4372 break; /* flush the current block */ 4373 } 4374 } 4375 4376 /* Insert the string window[strstart .. strstart+2] in the 4377 * dictionary, and set hash_head to the head of the hash chain: 4378 */ 4379 hash_head = 0/*NIL*/; 4380 if (s.lookahead >= MIN_MATCH) { 4381 /*** INSERT_STRING(s, s.strstart, hash_head); ***/ 4382 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; 4383 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; 4384 s.head[s.ins_h] = s.strstart; 4385 /***/ 4386 } 4387 4388 /* Find the longest match, discarding those <= prev_length. 4389 * At this point we have always match_length < MIN_MATCH 4390 */ 4391 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { 4392 /* To simplify the code, we prevent matches with the string 4393 * of window index 0 (in particular we have to avoid a match 4394 * of the string with itself at the start of the input file). 4395 */ 4396 s.match_length = longest_match(s, hash_head); 4397 /* longest_match() sets match_start */ 4398 } 4399 if (s.match_length >= MIN_MATCH) { 4400 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only 4401 4402 /*** _tr_tally_dist(s, s.strstart - s.match_start, 4403 s.match_length - MIN_MATCH, bflush); ***/ 4404 bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); 4405 4406 s.lookahead -= s.match_length; 4407 4408 /* Insert new strings in the hash table only if the match length 4409 * is not too large. This saves time but degrades compression. 4410 */ 4411 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { 4412 s.match_length--; /* string at strstart already in table */ 4413 do { 4414 s.strstart++; 4415 /*** INSERT_STRING(s, s.strstart, hash_head); ***/ 4416 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; 4417 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; 4418 s.head[s.ins_h] = s.strstart; 4419 /***/ 4420 /* strstart never exceeds WSIZE-MAX_MATCH, so there are 4421 * always MIN_MATCH bytes ahead. 4422 */ 4423 } while (--s.match_length !== 0); 4424 s.strstart++; 4425 } else 4426 { 4427 s.strstart += s.match_length; 4428 s.match_length = 0; 4429 s.ins_h = s.window[s.strstart]; 4430 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ 4431 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; 4432 4433 //#if MIN_MATCH != 3 4434 // Call UPDATE_HASH() MIN_MATCH-3 more times 4435 //#endif 4436 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not 4437 * matter since it will be recomputed at next deflate call. 4438 */ 4439 } 4440 } else { 4441 /* No match, output a literal byte */ 4442 //Tracevv((stderr,"%c", s.window[s.strstart])); 4443 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ 4444 bflush = trees._tr_tally(s, 0, s.window[s.strstart]); 4445 4446 s.lookahead--; 4447 s.strstart++; 4448 } 4449 if (bflush) { 4450 /*** FLUSH_BLOCK(s, 0); ***/ 4451 flush_block_only(s, false); 4452 if (s.strm.avail_out === 0) { 4453 return BS_NEED_MORE; 4454 } 4455 /***/ 4456 } 4457 } 4458 s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); 4459 if (flush === Z_FINISH) { 4460 /*** FLUSH_BLOCK(s, 1); ***/ 4461 flush_block_only(s, true); 4462 if (s.strm.avail_out === 0) { 4463 return BS_FINISH_STARTED; 4464 } 4465 /***/ 4466 return BS_FINISH_DONE; 4467 } 4468 if (s.last_lit) { 4469 /*** FLUSH_BLOCK(s, 0); ***/ 4470 flush_block_only(s, false); 4471 if (s.strm.avail_out === 0) { 4472 return BS_NEED_MORE; 4473 } 4474 /***/ 4475 } 4476 return BS_BLOCK_DONE; 4477 } 4478 4479 /* =========================================================================== 4480 * Same as above, but achieves better compression. We use a lazy 4481 * evaluation for matches: a match is finally adopted only if there is 4482 * no better match at the next window position. 4483 */ 4484 function deflate_slow(s, flush) { 4485 var hash_head; /* head of hash chain */ 4486 var bflush; /* set if current block must be flushed */ 4487 4488 var max_insert; 4489 4490 /* Process the input block. */ 4491 for (;;) { 4492 /* Make sure that we always have enough lookahead, except 4493 * at the end of the input file. We need MAX_MATCH bytes 4494 * for the next match, plus MIN_MATCH bytes to insert the 4495 * string following the next match. 4496 */ 4497 if (s.lookahead < MIN_LOOKAHEAD) { 4498 fill_window(s); 4499 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { 4500 return BS_NEED_MORE; 4501 } 4502 if (s.lookahead === 0) { break; } /* flush the current block */ 4503 } 4504 4505 /* Insert the string window[strstart .. strstart+2] in the 4506 * dictionary, and set hash_head to the head of the hash chain: 4507 */ 4508 hash_head = 0/*NIL*/; 4509 if (s.lookahead >= MIN_MATCH) { 4510 /*** INSERT_STRING(s, s.strstart, hash_head); ***/ 4511 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; 4512 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; 4513 s.head[s.ins_h] = s.strstart; 4514 /***/ 4515 } 4516 4517 /* Find the longest match, discarding those <= prev_length. 4518 */ 4519 s.prev_length = s.match_length; 4520 s.prev_match = s.match_start; 4521 s.match_length = MIN_MATCH-1; 4522 4523 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && 4524 s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { 4525 /* To simplify the code, we prevent matches with the string 4526 * of window index 0 (in particular we have to avoid a match 4527 * of the string with itself at the start of the input file). 4528 */ 4529 s.match_length = longest_match(s, hash_head); 4530 /* longest_match() sets match_start */ 4531 4532 if (s.match_length <= 5 && 4533 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { 4534 4535 /* If prev_match is also MIN_MATCH, match_start is garbage 4536 * but we will ignore the current match anyway. 4537 */ 4538 s.match_length = MIN_MATCH-1; 4539 } 4540 } 4541 /* If there was a match at the previous step and the current 4542 * match is not better, output the previous match: 4543 */ 4544 if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { 4545 max_insert = s.strstart + s.lookahead - MIN_MATCH; 4546 /* Do not insert strings in hash table beyond this. */ 4547 4548 //check_match(s, s.strstart-1, s.prev_match, s.prev_length); 4549 4550 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, 4551 s.prev_length - MIN_MATCH, bflush);***/ 4552 bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); 4553 /* Insert in hash table all strings up to the end of the match. 4554 * strstart-1 and strstart are already inserted. If there is not 4555 * enough lookahead, the last two strings are not inserted in 4556 * the hash table. 4557 */ 4558 s.lookahead -= s.prev_length-1; 4559 s.prev_length -= 2; 4560 do { 4561 if (++s.strstart <= max_insert) { 4562 /*** INSERT_STRING(s, s.strstart, hash_head); ***/ 4563 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; 4564 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; 4565 s.head[s.ins_h] = s.strstart; 4566 /***/ 4567 } 4568 } while (--s.prev_length !== 0); 4569 s.match_available = 0; 4570 s.match_length = MIN_MATCH-1; 4571 s.strstart++; 4572 4573 if (bflush) { 4574 /*** FLUSH_BLOCK(s, 0); ***/ 4575 flush_block_only(s, false); 4576 if (s.strm.avail_out === 0) { 4577 return BS_NEED_MORE; 4578 } 4579 /***/ 4580 } 4581 4582 } else if (s.match_available) { 4583 /* If there was no match at the previous position, output a 4584 * single literal. If there was a match but the current match 4585 * is longer, truncate the previous match to a single literal. 4586 */ 4587 //Tracevv((stderr,"%c", s->window[s->strstart-1])); 4588 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ 4589 bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); 4590 4591 if (bflush) { 4592 /*** FLUSH_BLOCK_ONLY(s, 0) ***/ 4593 flush_block_only(s, false); 4594 /***/ 4595 } 4596 s.strstart++; 4597 s.lookahead--; 4598 if (s.strm.avail_out === 0) { 4599 return BS_NEED_MORE; 4600 } 4601 } else { 4602 /* There is no previous match to compare with, wait for 4603 * the next step to decide. 4604 */ 4605 s.match_available = 1; 4606 s.strstart++; 4607 s.lookahead--; 4608 } 4609 } 4610 //Assert (flush != Z_NO_FLUSH, "no flush?"); 4611 if (s.match_available) { 4612 //Tracevv((stderr,"%c", s->window[s->strstart-1])); 4613 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ 4614 bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); 4615 4616 s.match_available = 0; 4617 } 4618 s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; 4619 if (flush === Z_FINISH) { 4620 /*** FLUSH_BLOCK(s, 1); ***/ 4621 flush_block_only(s, true); 4622 if (s.strm.avail_out === 0) { 4623 return BS_FINISH_STARTED; 4624 } 4625 /***/ 4626 return BS_FINISH_DONE; 4627 } 4628 if (s.last_lit) { 4629 /*** FLUSH_BLOCK(s, 0); ***/ 4630 flush_block_only(s, false); 4631 if (s.strm.avail_out === 0) { 4632 return BS_NEED_MORE; 4633 } 4634 /***/ 4635 } 4636 4637 return BS_BLOCK_DONE; 4638 } 4639 4640 4641 /* =========================================================================== 4642 * For Z_RLE, simply look for runs of bytes, generate matches only of distance 4643 * one. Do not maintain a hash table. (It will be regenerated if this run of 4644 * deflate switches away from Z_RLE.) 4645 */ 4646 function deflate_rle(s, flush) { 4647 var bflush; /* set if current block must be flushed */ 4648 var prev; /* byte at distance one to match */ 4649 var scan, strend; /* scan goes up to strend for length of run */ 4650 4651 var _win = s.window; 4652 4653 for (;;) { 4654 /* Make sure that we always have enough lookahead, except 4655 * at the end of the input file. We need MAX_MATCH bytes 4656 * for the longest run, plus one for the unrolled loop. 4657 */ 4658 if (s.lookahead <= MAX_MATCH) { 4659 fill_window(s); 4660 if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { 4661 return BS_NEED_MORE; 4662 } 4663 if (s.lookahead === 0) { break; } /* flush the current block */ 4664 } 4665 4666 /* See how many times the previous byte repeats */ 4667 s.match_length = 0; 4668 if (s.lookahead >= MIN_MATCH && s.strstart > 0) { 4669 scan = s.strstart - 1; 4670 prev = _win[scan]; 4671 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { 4672 strend = s.strstart + MAX_MATCH; 4673 do { 4674 /*jshint noempty:false*/ 4675 } while (prev === _win[++scan] && prev === _win[++scan] && 4676 prev === _win[++scan] && prev === _win[++scan] && 4677 prev === _win[++scan] && prev === _win[++scan] && 4678 prev === _win[++scan] && prev === _win[++scan] && 4679 scan < strend); 4680 s.match_length = MAX_MATCH - (strend - scan); 4681 if (s.match_length > s.lookahead) { 4682 s.match_length = s.lookahead; 4683 } 4684 } 4685 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); 4686 } 4687 4688 /* Emit match if have run of MIN_MATCH or longer, else emit literal */ 4689 if (s.match_length >= MIN_MATCH) { 4690 //check_match(s, s.strstart, s.strstart - 1, s.match_length); 4691 4692 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ 4693 bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); 4694 4695 s.lookahead -= s.match_length; 4696 s.strstart += s.match_length; 4697 s.match_length = 0; 4698 } else { 4699 /* No match, output a literal byte */ 4700 //Tracevv((stderr,"%c", s->window[s->strstart])); 4701 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ 4702 bflush = trees._tr_tally(s, 0, s.window[s.strstart]); 4703 4704 s.lookahead--; 4705 s.strstart++; 4706 } 4707 if (bflush) { 4708 /*** FLUSH_BLOCK(s, 0); ***/ 4709 flush_block_only(s, false); 4710 if (s.strm.avail_out === 0) { 4711 return BS_NEED_MORE; 4712 } 4713 /***/ 4714 } 4715 } 4716 s.insert = 0; 4717 if (flush === Z_FINISH) { 4718 /*** FLUSH_BLOCK(s, 1); ***/ 4719 flush_block_only(s, true); 4720 if (s.strm.avail_out === 0) { 4721 return BS_FINISH_STARTED; 4722 } 4723 /***/ 4724 return BS_FINISH_DONE; 4725 } 4726 if (s.last_lit) { 4727 /*** FLUSH_BLOCK(s, 0); ***/ 4728 flush_block_only(s, false); 4729 if (s.strm.avail_out === 0) { 4730 return BS_NEED_MORE; 4731 } 4732 /***/ 4733 } 4734 return BS_BLOCK_DONE; 4735 } 4736 4737 /* =========================================================================== 4738 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. 4739 * (It will be regenerated if this run of deflate switches away from Huffman.) 4740 */ 4741 function deflate_huff(s, flush) { 4742 var bflush; /* set if current block must be flushed */ 4743 4744 for (;;) { 4745 /* Make sure that we have a literal to write. */ 4746 if (s.lookahead === 0) { 4747 fill_window(s); 4748 if (s.lookahead === 0) { 4749 if (flush === Z_NO_FLUSH) { 4750 return BS_NEED_MORE; 4751 } 4752 break; /* flush the current block */ 4753 } 4754 } 4755 4756 /* Output a literal byte */ 4757 s.match_length = 0; 4758 //Tracevv((stderr,"%c", s->window[s->strstart])); 4759 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ 4760 bflush = trees._tr_tally(s, 0, s.window[s.strstart]); 4761 s.lookahead--; 4762 s.strstart++; 4763 if (bflush) { 4764 /*** FLUSH_BLOCK(s, 0); ***/ 4765 flush_block_only(s, false); 4766 if (s.strm.avail_out === 0) { 4767 return BS_NEED_MORE; 4768 } 4769 /***/ 4770 } 4771 } 4772 s.insert = 0; 4773 if (flush === Z_FINISH) { 4774 /*** FLUSH_BLOCK(s, 1); ***/ 4775 flush_block_only(s, true); 4776 if (s.strm.avail_out === 0) { 4777 return BS_FINISH_STARTED; 4778 } 4779 /***/ 4780 return BS_FINISH_DONE; 4781 } 4782 if (s.last_lit) { 4783 /*** FLUSH_BLOCK(s, 0); ***/ 4784 flush_block_only(s, false); 4785 if (s.strm.avail_out === 0) { 4786 return BS_NEED_MORE; 4787 } 4788 /***/ 4789 } 4790 return BS_BLOCK_DONE; 4791 } 4792 4793 /* Values for max_lazy_match, good_match and max_chain_length, depending on 4794 * the desired pack level (0..9). The values given below have been tuned to 4795 * exclude worst case performance for pathological files. Better values may be 4796 * found for specific files. 4797 */ 4798 var Config = function (good_length, max_lazy, nice_length, max_chain, func) { 4799 this.good_length = good_length; 4800 this.max_lazy = max_lazy; 4801 this.nice_length = nice_length; 4802 this.max_chain = max_chain; 4803 this.func = func; 4804 }; 4805 4806 var configuration_table; 4807 4808 configuration_table = [ 4809 /* good lazy nice chain */ 4810 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ 4811 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ 4812 new Config(4, 5, 16, 8, deflate_fast), /* 2 */ 4813 new Config(4, 6, 32, 32, deflate_fast), /* 3 */ 4814 4815 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ 4816 new Config(8, 16, 32, 32, deflate_slow), /* 5 */ 4817 new Config(8, 16, 128, 128, deflate_slow), /* 6 */ 4818 new Config(8, 32, 128, 256, deflate_slow), /* 7 */ 4819 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ 4820 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ 4821 ]; 4822 4823 4824 /* =========================================================================== 4825 * Initialize the "longest match" routines for a new zlib stream 4826 */ 4827 function lm_init(s) { 4828 s.window_size = 2 * s.w_size; 4829 4830 /*** CLEAR_HASH(s); ***/ 4831 zero(s.head); // Fill with NIL (= 0); 4832 4833 /* Set the default configuration parameters: 4834 */ 4835 s.max_lazy_match = configuration_table[s.level].max_lazy; 4836 s.good_match = configuration_table[s.level].good_length; 4837 s.nice_match = configuration_table[s.level].nice_length; 4838 s.max_chain_length = configuration_table[s.level].max_chain; 4839 4840 s.strstart = 0; 4841 s.block_start = 0; 4842 s.lookahead = 0; 4843 s.insert = 0; 4844 s.match_length = s.prev_length = MIN_MATCH - 1; 4845 s.match_available = 0; 4846 s.ins_h = 0; 4847 } 4848 4849 4850 function DeflateState() { 4851 this.strm = null; /* pointer back to this zlib stream */ 4852 this.status = 0; /* as the name implies */ 4853 this.pending_buf = null; /* output still pending */ 4854 this.pending_buf_size = 0; /* size of pending_buf */ 4855 this.pending_out = 0; /* next pending byte to output to the stream */ 4856 this.pending = 0; /* nb of bytes in the pending buffer */ 4857 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ 4858 this.gzhead = null; /* gzip header information to write */ 4859 this.gzindex = 0; /* where in extra, name, or comment */ 4860 this.method = Z_DEFLATED; /* can only be DEFLATED */ 4861 this.last_flush = -1; /* value of flush param for previous deflate call */ 4862 4863 this.w_size = 0; /* LZ77 window size (32K by default) */ 4864 this.w_bits = 0; /* log2(w_size) (8..16) */ 4865 this.w_mask = 0; /* w_size - 1 */ 4866 4867 this.window = null; 4868 /* Sliding window. Input bytes are read into the second half of the window, 4869 * and move to the first half later to keep a dictionary of at least wSize 4870 * bytes. With this organization, matches are limited to a distance of 4871 * wSize-MAX_MATCH bytes, but this ensures that IO is always 4872 * performed with a length multiple of the block size. 4873 */ 4874 4875 this.window_size = 0; 4876 /* Actual size of window: 2*wSize, except when the user input buffer 4877 * is directly used as sliding window. 4878 */ 4879 4880 this.prev = null; 4881 /* Link to older string with same hash index. To limit the size of this 4882 * array to 64K, this link is maintained only for the last 32K strings. 4883 * An index in this array is thus a window index modulo 32K. 4884 */ 4885 4886 this.head = null; /* Heads of the hash chains or NIL. */ 4887 4888 this.ins_h = 0; /* hash index of string to be inserted */ 4889 this.hash_size = 0; /* number of elements in hash table */ 4890 this.hash_bits = 0; /* log2(hash_size) */ 4891 this.hash_mask = 0; /* hash_size-1 */ 4892 4893 this.hash_shift = 0; 4894 /* Number of bits by which ins_h must be shifted at each input 4895 * step. It must be such that after MIN_MATCH steps, the oldest 4896 * byte no longer takes part in the hash key, that is: 4897 * hash_shift * MIN_MATCH >= hash_bits 4898 */ 4899 4900 this.block_start = 0; 4901 /* Window position at the beginning of the current output block. Gets 4902 * negative when the window is moved backwards. 4903 */ 4904 4905 this.match_length = 0; /* length of best match */ 4906 this.prev_match = 0; /* previous match */ 4907 this.match_available = 0; /* set if previous match exists */ 4908 this.strstart = 0; /* start of string to insert */ 4909 this.match_start = 0; /* start of matching string */ 4910 this.lookahead = 0; /* number of valid bytes ahead in window */ 4911 4912 this.prev_length = 0; 4913 /* Length of the best match at previous step. Matches not greater than this 4914 * are discarded. This is used in the lazy match evaluation. 4915 */ 4916 4917 this.max_chain_length = 0; 4918 /* To speed up deflation, hash chains are never searched beyond this 4919 * length. A higher limit improves compression ratio but degrades the 4920 * speed. 4921 */ 4922 4923 this.max_lazy_match = 0; 4924 /* Attempt to find a better match only when the current match is strictly 4925 * smaller than this value. This mechanism is used only for compression 4926 * levels >= 4. 4927 */ 4928 // That's alias to max_lazy_match, don't use directly 4929 //this.max_insert_length = 0; 4930 /* Insert new strings in the hash table only if the match length is not 4931 * greater than this length. This saves time but degrades compression. 4932 * max_insert_length is used only for compression levels <= 3. 4933 */ 4934 4935 this.level = 0; /* compression level (1..9) */ 4936 this.strategy = 0; /* favor or force Huffman coding*/ 4937 4938 this.good_match = 0; 4939 /* Use a faster search when the previous match is longer than this */ 4940 4941 this.nice_match = 0; /* Stop searching when current match exceeds this */ 4942 4943 /* used by trees.c: */ 4944 4945 /* Didn't use ct_data typedef below to suppress compiler warning */ 4946 4947 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ 4948 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ 4949 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ 4950 4951 // Use flat array of DOUBLE size, with interleaved fata, 4952 // because JS does not support effective 4953 this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); 4954 this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); 4955 this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); 4956 zero(this.dyn_ltree); 4957 zero(this.dyn_dtree); 4958 zero(this.bl_tree); 4959 4960 this.l_desc = null; /* desc. for literal tree */ 4961 this.d_desc = null; /* desc. for distance tree */ 4962 this.bl_desc = null; /* desc. for bit length tree */ 4963 4964 //ush bl_count[MAX_BITS+1]; 4965 this.bl_count = new utils.Buf16(MAX_BITS+1); 4966 /* number of codes at each bit length for an optimal tree */ 4967 4968 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ 4969 this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ 4970 zero(this.heap); 4971 4972 this.heap_len = 0; /* number of elements in the heap */ 4973 this.heap_max = 0; /* element of largest frequency */ 4974 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. 4975 * The same heap array is used to build all trees. 4976 */ 4977 4978 this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; 4979 zero(this.depth); 4980 /* Depth of each subtree used as tie breaker for trees of equal frequency 4981 */ 4982 4983 this.l_buf = 0; /* buffer index for literals or lengths */ 4984 4985 this.lit_bufsize = 0; 4986 /* Size of match buffer for literals/lengths. There are 4 reasons for 4987 * limiting lit_bufsize to 64K: 4988 * - frequencies can be kept in 16 bit counters 4989 * - if compression is not successful for the first block, all input 4990 * data is still in the window so we can still emit a stored block even 4991 * when input comes from standard input. (This can also be done for 4992 * all blocks if lit_bufsize is not greater than 32K.) 4993 * - if compression is not successful for a file smaller than 64K, we can 4994 * even emit a stored file instead of a stored block (saving 5 bytes). 4995 * This is applicable only for zip (not gzip or zlib). 4996 * - creating new Huffman trees less frequently may not provide fast 4997 * adaptation to changes in the input data statistics. (Take for 4998 * example a binary file with poorly compressible code followed by 4999 * a highly compressible string table.) Smaller buffer sizes give 5000 * fast adaptation but have of course the overhead of transmitting 5001 * trees more frequently. 5002 * - I can't count above 4 5003 */ 5004 5005 this.last_lit = 0; /* running index in l_buf */ 5006 5007 this.d_buf = 0; 5008 /* Buffer index for distances. To simplify the code, d_buf and l_buf have 5009 * the same number of elements. To use different lengths, an extra flag 5010 * array would be necessary. 5011 */ 5012 5013 this.opt_len = 0; /* bit length of current block with optimal trees */ 5014 this.static_len = 0; /* bit length of current block with static trees */ 5015 this.matches = 0; /* number of string matches in current block */ 5016 this.insert = 0; /* bytes at end of window left to insert */ 5017 5018 5019 this.bi_buf = 0; 5020 /* Output buffer. bits are inserted starting at the bottom (least 5021 * significant bits). 5022 */ 5023 this.bi_valid = 0; 5024 /* Number of valid bits in bi_buf. All bits above the last valid bit 5025 * are always zero. 5026 */ 5027 5028 // Used for window memory init. We safely ignore it for JS. That makes 5029 // sense only for pointers and memory check tools. 5030 //this.high_water = 0; 5031 /* High water mark offset in window for initialized bytes -- bytes above 5032 * this are set to zero in order to avoid memory check warnings when 5033 * longest match routines access bytes past the input. This is then 5034 * updated to the new high water mark. 5035 */ 5036 } 5037 5038 5039 function deflateResetKeep(strm) { 5040 var s; 5041 5042 if (!strm || !strm.state) { 5043 return err(strm, Z_STREAM_ERROR); 5044 } 5045 5046 strm.total_in = strm.total_out = 0; 5047 strm.data_type = Z_UNKNOWN; 5048 5049 s = strm.state; 5050 s.pending = 0; 5051 s.pending_out = 0; 5052 5053 if (s.wrap < 0) { 5054 s.wrap = -s.wrap; 5055 /* was made negative by deflate(..., Z_FINISH); */ 5056 } 5057 s.status = (s.wrap ? INIT_STATE : BUSY_STATE); 5058 strm.adler = (s.wrap === 2) ? 5059 0 // crc32(0, Z_NULL, 0) 5060 : 5061 1; // adler32(0, Z_NULL, 0) 5062 s.last_flush = Z_NO_FLUSH; 5063 trees._tr_init(s); 5064 return Z_OK; 5065 } 5066 5067 5068 function deflateReset(strm) { 5069 var ret = deflateResetKeep(strm); 5070 if (ret === Z_OK) { 5071 lm_init(strm.state); 5072 } 5073 return ret; 5074 } 5075 5076 5077 function deflateSetHeader(strm, head) { 5078 if (!strm || !strm.state) { return Z_STREAM_ERROR; } 5079 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } 5080 strm.state.gzhead = head; 5081 return Z_OK; 5082 } 5083 5084 5085 function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { 5086 if (!strm) { // === Z_NULL 5087 return Z_STREAM_ERROR; 5088 } 5089 var wrap = 1; 5090 5091 if (level === Z_DEFAULT_COMPRESSION) { 5092 level = 6; 5093 } 5094 5095 if (windowBits < 0) { /* suppress zlib wrapper */ 5096 wrap = 0; 5097 windowBits = -windowBits; 5098 } 5099 5100 else if (windowBits > 15) { 5101 wrap = 2; /* write gzip wrapper instead */ 5102 windowBits -= 16; 5103 } 5104 5105 5106 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || 5107 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || 5108 strategy < 0 || strategy > Z_FIXED) { 5109 return err(strm, Z_STREAM_ERROR); 5110 } 5111 5112 5113 if (windowBits === 8) { 5114 windowBits = 9; 5115 } 5116 /* until 256-byte window bug fixed */ 5117 5118 var s = new DeflateState(); 5119 5120 strm.state = s; 5121 s.strm = strm; 5122 5123 s.wrap = wrap; 5124 s.gzhead = null; 5125 s.w_bits = windowBits; 5126 s.w_size = 1 << s.w_bits; 5127 s.w_mask = s.w_size - 1; 5128 5129 s.hash_bits = memLevel + 7; 5130 s.hash_size = 1 << s.hash_bits; 5131 s.hash_mask = s.hash_size - 1; 5132 s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); 5133 5134 s.window = new utils.Buf8(s.w_size * 2); 5135 s.head = new utils.Buf16(s.hash_size); 5136 s.prev = new utils.Buf16(s.w_size); 5137 5138 // Don't need mem init magic for JS. 5139 //s.high_water = 0; /* nothing written to s->window yet */ 5140 5141 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ 5142 5143 s.pending_buf_size = s.lit_bufsize * 4; 5144 s.pending_buf = new utils.Buf8(s.pending_buf_size); 5145 5146 s.d_buf = s.lit_bufsize >> 1; 5147 s.l_buf = (1 + 2) * s.lit_bufsize; 5148 5149 s.level = level; 5150 s.strategy = strategy; 5151 s.method = method; 5152 5153 return deflateReset(strm); 5154 } 5155 5156 function deflateInit(strm, level) { 5157 return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); 5158 } 5159 5160 5161 function deflate(strm, flush) { 5162 var old_flush, s; 5163 var beg, val; // for gzip header write only 5164 5165 if (!strm || !strm.state || 5166 flush > Z_BLOCK || flush < 0) { 5167 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; 5168 } 5169 5170 s = strm.state; 5171 5172 if (!strm.output || 5173 (!strm.input && strm.avail_in !== 0) || 5174 (s.status === FINISH_STATE && flush !== Z_FINISH)) { 5175 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); 5176 } 5177 5178 s.strm = strm; /* just in case */ 5179 old_flush = s.last_flush; 5180 s.last_flush = flush; 5181 5182 /* Write the header */ 5183 if (s.status === INIT_STATE) { 5184 5185 if (s.wrap === 2) { // GZIP header 5186 strm.adler = 0; //crc32(0L, Z_NULL, 0); 5187 put_byte(s, 31); 5188 put_byte(s, 139); 5189 put_byte(s, 8); 5190 if (!s.gzhead) { // s->gzhead == Z_NULL 5191 put_byte(s, 0); 5192 put_byte(s, 0); 5193 put_byte(s, 0); 5194 put_byte(s, 0); 5195 put_byte(s, 0); 5196 put_byte(s, s.level === 9 ? 2 : 5197 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 5198 4 : 0)); 5199 put_byte(s, OS_CODE); 5200 s.status = BUSY_STATE; 5201 } 5202 else { 5203 put_byte(s, (s.gzhead.text ? 1 : 0) + 5204 (s.gzhead.hcrc ? 2 : 0) + 5205 (!s.gzhead.extra ? 0 : 4) + 5206 (!s.gzhead.name ? 0 : 8) + 5207 (!s.gzhead.comment ? 0 : 16) 5208 ); 5209 put_byte(s, s.gzhead.time & 0xff); 5210 put_byte(s, (s.gzhead.time >> 8) & 0xff); 5211 put_byte(s, (s.gzhead.time >> 16) & 0xff); 5212 put_byte(s, (s.gzhead.time >> 24) & 0xff); 5213 put_byte(s, s.level === 9 ? 2 : 5214 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 5215 4 : 0)); 5216 put_byte(s, s.gzhead.os & 0xff); 5217 if (s.gzhead.extra && s.gzhead.extra.length) { 5218 put_byte(s, s.gzhead.extra.length & 0xff); 5219 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); 5220 } 5221 if (s.gzhead.hcrc) { 5222 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); 5223 } 5224 s.gzindex = 0; 5225 s.status = EXTRA_STATE; 5226 } 5227 } 5228 else // DEFLATE header 5229 { 5230 var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; 5231 var level_flags = -1; 5232 5233 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { 5234 level_flags = 0; 5235 } else if (s.level < 6) { 5236 level_flags = 1; 5237 } else if (s.level === 6) { 5238 level_flags = 2; 5239 } else { 5240 level_flags = 3; 5241 } 5242 header |= (level_flags << 6); 5243 if (s.strstart !== 0) { header |= PRESET_DICT; } 5244 header += 31 - (header % 31); 5245 5246 s.status = BUSY_STATE; 5247 putShortMSB(s, header); 5248 5249 /* Save the adler32 of the preset dictionary: */ 5250 if (s.strstart !== 0) { 5251 putShortMSB(s, strm.adler >>> 16); 5252 putShortMSB(s, strm.adler & 0xffff); 5253 } 5254 strm.adler = 1; // adler32(0L, Z_NULL, 0); 5255 } 5256 } 5257 5258 //#ifdef GZIP 5259 if (s.status === EXTRA_STATE) { 5260 if (s.gzhead.extra/* != Z_NULL*/) { 5261 beg = s.pending; /* start of bytes to update crc */ 5262 5263 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { 5264 if (s.pending === s.pending_buf_size) { 5265 if (s.gzhead.hcrc && s.pending > beg) { 5266 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 5267 } 5268 flush_pending(strm); 5269 beg = s.pending; 5270 if (s.pending === s.pending_buf_size) { 5271 break; 5272 } 5273 } 5274 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); 5275 s.gzindex++; 5276 } 5277 if (s.gzhead.hcrc && s.pending > beg) { 5278 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 5279 } 5280 if (s.gzindex === s.gzhead.extra.length) { 5281 s.gzindex = 0; 5282 s.status = NAME_STATE; 5283 } 5284 } 5285 else { 5286 s.status = NAME_STATE; 5287 } 5288 } 5289 if (s.status === NAME_STATE) { 5290 if (s.gzhead.name/* != Z_NULL*/) { 5291 beg = s.pending; /* start of bytes to update crc */ 5292 //int val; 5293 5294 do { 5295 if (s.pending === s.pending_buf_size) { 5296 if (s.gzhead.hcrc && s.pending > beg) { 5297 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 5298 } 5299 flush_pending(strm); 5300 beg = s.pending; 5301 if (s.pending === s.pending_buf_size) { 5302 val = 1; 5303 break; 5304 } 5305 } 5306 // JS specific: little magic to add zero terminator to end of string 5307 if (s.gzindex < s.gzhead.name.length) { 5308 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; 5309 } else { 5310 val = 0; 5311 } 5312 put_byte(s, val); 5313 } while (val !== 0); 5314 5315 if (s.gzhead.hcrc && s.pending > beg){ 5316 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 5317 } 5318 if (val === 0) { 5319 s.gzindex = 0; 5320 s.status = COMMENT_STATE; 5321 } 5322 } 5323 else { 5324 s.status = COMMENT_STATE; 5325 } 5326 } 5327 if (s.status === COMMENT_STATE) { 5328 if (s.gzhead.comment/* != Z_NULL*/) { 5329 beg = s.pending; /* start of bytes to update crc */ 5330 //int val; 5331 5332 do { 5333 if (s.pending === s.pending_buf_size) { 5334 if (s.gzhead.hcrc && s.pending > beg) { 5335 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 5336 } 5337 flush_pending(strm); 5338 beg = s.pending; 5339 if (s.pending === s.pending_buf_size) { 5340 val = 1; 5341 break; 5342 } 5343 } 5344 // JS specific: little magic to add zero terminator to end of string 5345 if (s.gzindex < s.gzhead.comment.length) { 5346 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; 5347 } else { 5348 val = 0; 5349 } 5350 put_byte(s, val); 5351 } while (val !== 0); 5352 5353 if (s.gzhead.hcrc && s.pending > beg) { 5354 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 5355 } 5356 if (val === 0) { 5357 s.status = HCRC_STATE; 5358 } 5359 } 5360 else { 5361 s.status = HCRC_STATE; 5362 } 5363 } 5364 if (s.status === HCRC_STATE) { 5365 if (s.gzhead.hcrc) { 5366 if (s.pending + 2 > s.pending_buf_size) { 5367 flush_pending(strm); 5368 } 5369 if (s.pending + 2 <= s.pending_buf_size) { 5370 put_byte(s, strm.adler & 0xff); 5371 put_byte(s, (strm.adler >> 8) & 0xff); 5372 strm.adler = 0; //crc32(0L, Z_NULL, 0); 5373 s.status = BUSY_STATE; 5374 } 5375 } 5376 else { 5377 s.status = BUSY_STATE; 5378 } 5379 } 5380 //#endif 5381 5382 /* Flush as much pending output as possible */ 5383 if (s.pending !== 0) { 5384 flush_pending(strm); 5385 if (strm.avail_out === 0) { 5386 /* Since avail_out is 0, deflate will be called again with 5387 * more output space, but possibly with both pending and 5388 * avail_in equal to zero. There won't be anything to do, 5389 * but this is not an error situation so make sure we 5390 * return OK instead of BUF_ERROR at next call of deflate: 5391 */ 5392 s.last_flush = -1; 5393 return Z_OK; 5394 } 5395 5396 /* Make sure there is something to do and avoid duplicate consecutive 5397 * flushes. For repeated and useless calls with Z_FINISH, we keep 5398 * returning Z_STREAM_END instead of Z_BUF_ERROR. 5399 */ 5400 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && 5401 flush !== Z_FINISH) { 5402 return err(strm, Z_BUF_ERROR); 5403 } 5404 5405 /* User must not provide more input after the first FINISH: */ 5406 if (s.status === FINISH_STATE && strm.avail_in !== 0) { 5407 return err(strm, Z_BUF_ERROR); 5408 } 5409 5410 /* Start a new block or continue the current one. 5411 */ 5412 if (strm.avail_in !== 0 || s.lookahead !== 0 || 5413 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { 5414 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : 5415 (s.strategy === Z_RLE ? deflate_rle(s, flush) : 5416 configuration_table[s.level].func(s, flush)); 5417 5418 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { 5419 s.status = FINISH_STATE; 5420 } 5421 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { 5422 if (strm.avail_out === 0) { 5423 s.last_flush = -1; 5424 /* avoid BUF_ERROR next call, see above */ 5425 } 5426 return Z_OK; 5427 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call 5428 * of deflate should use the same flush parameter to make sure 5429 * that the flush is complete. So we don't have to output an 5430 * empty block here, this will be done at next call. This also 5431 * ensures that for a very small output buffer, we emit at most 5432 * one empty block. 5433 */ 5434 } 5435 if (bstate === BS_BLOCK_DONE) { 5436 if (flush === Z_PARTIAL_FLUSH) { 5437 trees._tr_align(s); 5438 } 5439 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ 5440 5441 trees._tr_stored_block(s, 0, 0, false); 5442 /* For a full flush, this empty block will be recognized 5443 * as a special marker by inflate_sync(). 5444 */ 5445 if (flush === Z_FULL_FLUSH) { 5446 /*** CLEAR_HASH(s); ***/ /* forget history */ 5447 zero(s.head); // Fill with NIL (= 0); 5448 5449 if (s.lookahead === 0) { 5450 s.strstart = 0; 5451 s.block_start = 0; 5452 s.insert = 0; 5453 } 5454 } 5455 } 5456 flush_pending(strm); 5457 if (strm.avail_out === 0) { 5458 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ 5459 return Z_OK; 5460 } 5461 } 5462 } 5463 //Assert(strm->avail_out > 0, "bug2"); 5464 //if (strm.avail_out <= 0) { throw new Error("bug2");} 5465 5466 if (flush !== Z_FINISH) { return Z_OK; } 5467 if (s.wrap <= 0) { return Z_STREAM_END; } 5468 5469 /* Write the trailer */ 5470 if (s.wrap === 2) { 5471 put_byte(s, strm.adler & 0xff); 5472 put_byte(s, (strm.adler >> 8) & 0xff); 5473 put_byte(s, (strm.adler >> 16) & 0xff); 5474 put_byte(s, (strm.adler >> 24) & 0xff); 5475 put_byte(s, strm.total_in & 0xff); 5476 put_byte(s, (strm.total_in >> 8) & 0xff); 5477 put_byte(s, (strm.total_in >> 16) & 0xff); 5478 put_byte(s, (strm.total_in >> 24) & 0xff); 5479 } 5480 else 5481 { 5482 putShortMSB(s, strm.adler >>> 16); 5483 putShortMSB(s, strm.adler & 0xffff); 5484 } 5485 5486 flush_pending(strm); 5487 /* If avail_out is zero, the application will call deflate again 5488 * to flush the rest. 5489 */ 5490 if (s.wrap > 0) { s.wrap = -s.wrap; } 5491 /* write the trailer only once! */ 5492 return s.pending !== 0 ? Z_OK : Z_STREAM_END; 5493 } 5494 5495 function deflateEnd(strm) { 5496 var status; 5497 5498 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { 5499 return Z_STREAM_ERROR; 5500 } 5501 5502 status = strm.state.status; 5503 if (status !== INIT_STATE && 5504 status !== EXTRA_STATE && 5505 status !== NAME_STATE && 5506 status !== COMMENT_STATE && 5507 status !== HCRC_STATE && 5508 status !== BUSY_STATE && 5509 status !== FINISH_STATE 5510 ) { 5511 return err(strm, Z_STREAM_ERROR); 5512 } 5513 5514 strm.state = null; 5515 5516 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; 5517 } 5518 5519 /* ========================================================================= 5520 * Copy the source state to the destination state 5521 */ 5522 //function deflateCopy(dest, source) { 5523 // 5524 //} 5525 5526 exports.deflateInit = deflateInit; 5527 exports.deflateInit2 = deflateInit2; 5528 exports.deflateReset = deflateReset; 5529 exports.deflateResetKeep = deflateResetKeep; 5530 exports.deflateSetHeader = deflateSetHeader; 5531 exports.deflate = deflate; 5532 exports.deflateEnd = deflateEnd; 5533 exports.deflateInfo = 'pako deflate (from Nodeca project)'; 5534 5535 /* Not implemented 5536 exports.deflateBound = deflateBound; 5537 exports.deflateCopy = deflateCopy; 5538 exports.deflateSetDictionary = deflateSetDictionary; 5539 exports.deflateParams = deflateParams; 5540 exports.deflatePending = deflatePending; 5541 exports.deflatePrime = deflatePrime; 5542 exports.deflateTune = deflateTune; 5543 */ 5544 },{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(_dereq_,module,exports){ 5545 'use strict'; 5546 5547 5548 function GZheader() { 5549 /* true if compressed data believed to be text */ 5550 this.text = 0; 5551 /* modification time */ 5552 this.time = 0; 5553 /* extra flags (not used when writing a gzip file) */ 5554 this.xflags = 0; 5555 /* operating system */ 5556 this.os = 0; 5557 /* pointer to extra field or Z_NULL if none */ 5558 this.extra = null; 5559 /* extra field length (valid if extra != Z_NULL) */ 5560 this.extra_len = 0; // Actually, we don't need it in JS, 5561 // but leave for few code modifications 5562 5563 // 5564 // Setup limits is not necessary because in js we should not preallocate memory 5565 // for inflate use constant limit in 65536 bytes 5566 // 5567 5568 /* space at extra (only when reading header) */ 5569 // this.extra_max = 0; 5570 /* pointer to zero-terminated file name or Z_NULL */ 5571 this.name = ''; 5572 /* space at name (only when reading header) */ 5573 // this.name_max = 0; 5574 /* pointer to zero-terminated comment or Z_NULL */ 5575 this.comment = ''; 5576 /* space at comment (only when reading header) */ 5577 // this.comm_max = 0; 5578 /* true if there was or will be a header crc */ 5579 this.hcrc = 0; 5580 /* true when done reading gzip header (not used when writing a gzip file) */ 5581 this.done = false; 5582 } 5583 5584 module.exports = GZheader; 5585 },{}],34:[function(_dereq_,module,exports){ 5586 'use strict'; 5587 5588 // See state defs from inflate.js 5589 var BAD = 30; /* got a data error -- remain here until reset */ 5590 var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ 5591 5592 /* 5593 Decode literal, length, and distance codes and write out the resulting 5594 literal and match bytes until either not enough input or output is 5595 available, an end-of-block is encountered, or a data error is encountered. 5596 When large enough input and output buffers are supplied to inflate(), for 5597 example, a 16K input buffer and a 64K output buffer, more than 95% of the 5598 inflate execution time is spent in this routine. 5599 5600 Entry assumptions: 5601 5602 state.mode === LEN 5603 strm.avail_in >= 6 5604 strm.avail_out >= 258 5605 start >= strm.avail_out 5606 state.bits < 8 5607 5608 On return, state.mode is one of: 5609 5610 LEN -- ran out of enough output space or enough available input 5611 TYPE -- reached end of block code, inflate() to interpret next block 5612 BAD -- error in block data 5613 5614 Notes: 5615 5616 - The maximum input bits used by a length/distance pair is 15 bits for the 5617 length code, 5 bits for the length extra, 15 bits for the distance code, 5618 and 13 bits for the distance extra. This totals 48 bits, or six bytes. 5619 Therefore if strm.avail_in >= 6, then there is enough input to avoid 5620 checking for available input while decoding. 5621 5622 - The maximum bytes that a single length/distance pair can output is 258 5623 bytes, which is the maximum length that can be coded. inflate_fast() 5624 requires strm.avail_out >= 258 for each loop to avoid checking for 5625 output space. 5626 */ 5627 module.exports = function inflate_fast(strm, start) { 5628 var state; 5629 var _in; /* local strm.input */ 5630 var last; /* have enough input while in < last */ 5631 var _out; /* local strm.output */ 5632 var beg; /* inflate()'s initial strm.output */ 5633 var end; /* while out < end, enough space available */ 5634 //#ifdef INFLATE_STRICT 5635 var dmax; /* maximum distance from zlib header */ 5636 //#endif 5637 var wsize; /* window size or zero if not using window */ 5638 var whave; /* valid bytes in the window */ 5639 var wnext; /* window write index */ 5640 var window; /* allocated sliding window, if wsize != 0 */ 5641 var hold; /* local strm.hold */ 5642 var bits; /* local strm.bits */ 5643 var lcode; /* local strm.lencode */ 5644 var dcode; /* local strm.distcode */ 5645 var lmask; /* mask for first level of length codes */ 5646 var dmask; /* mask for first level of distance codes */ 5647 var here; /* retrieved table entry */ 5648 var op; /* code bits, operation, extra bits, or */ 5649 /* window position, window bytes to copy */ 5650 var len; /* match length, unused bytes */ 5651 var dist; /* match distance */ 5652 var from; /* where to copy match from */ 5653 var from_source; 5654 5655 5656 var input, output; // JS specific, because we have no pointers 5657 5658 /* copy state to local variables */ 5659 state = strm.state; 5660 //here = state.here; 5661 _in = strm.next_in; 5662 input = strm.input; 5663 last = _in + (strm.avail_in - 5); 5664 _out = strm.next_out; 5665 output = strm.output; 5666 beg = _out - (start - strm.avail_out); 5667 end = _out + (strm.avail_out - 257); 5668 //#ifdef INFLATE_STRICT 5669 dmax = state.dmax; 5670 //#endif 5671 wsize = state.wsize; 5672 whave = state.whave; 5673 wnext = state.wnext; 5674 window = state.window; 5675 hold = state.hold; 5676 bits = state.bits; 5677 lcode = state.lencode; 5678 dcode = state.distcode; 5679 lmask = (1 << state.lenbits) - 1; 5680 dmask = (1 << state.distbits) - 1; 5681 5682 5683 /* decode literals and length/distances until end-of-block or not enough 5684 input data or output space */ 5685 5686 top: 5687 do { 5688 if (bits < 15) { 5689 hold += input[_in++] << bits; 5690 bits += 8; 5691 hold += input[_in++] << bits; 5692 bits += 8; 5693 } 5694 5695 here = lcode[hold & lmask]; 5696 5697 dolen: 5698 for (;;) { // Goto emulation 5699 op = here >>> 24/*here.bits*/; 5700 hold >>>= op; 5701 bits -= op; 5702 op = (here >>> 16) & 0xff/*here.op*/; 5703 if (op === 0) { /* literal */ 5704 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? 5705 // "inflate: literal '%c'\n" : 5706 // "inflate: literal 0x%02x\n", here.val)); 5707 output[_out++] = here & 0xffff/*here.val*/; 5708 } 5709 else if (op & 16) { /* length base */ 5710 len = here & 0xffff/*here.val*/; 5711 op &= 15; /* number of extra bits */ 5712 if (op) { 5713 if (bits < op) { 5714 hold += input[_in++] << bits; 5715 bits += 8; 5716 } 5717 len += hold & ((1 << op) - 1); 5718 hold >>>= op; 5719 bits -= op; 5720 } 5721 //Tracevv((stderr, "inflate: length %u\n", len)); 5722 if (bits < 15) { 5723 hold += input[_in++] << bits; 5724 bits += 8; 5725 hold += input[_in++] << bits; 5726 bits += 8; 5727 } 5728 here = dcode[hold & dmask]; 5729 5730 dodist: 5731 for (;;) { // goto emulation 5732 op = here >>> 24/*here.bits*/; 5733 hold >>>= op; 5734 bits -= op; 5735 op = (here >>> 16) & 0xff/*here.op*/; 5736 5737 if (op & 16) { /* distance base */ 5738 dist = here & 0xffff/*here.val*/; 5739 op &= 15; /* number of extra bits */ 5740 if (bits < op) { 5741 hold += input[_in++] << bits; 5742 bits += 8; 5743 if (bits < op) { 5744 hold += input[_in++] << bits; 5745 bits += 8; 5746 } 5747 } 5748 dist += hold & ((1 << op) - 1); 5749 //#ifdef INFLATE_STRICT 5750 if (dist > dmax) { 5751 strm.msg = 'invalid distance too far back'; 5752 state.mode = BAD; 5753 break top; 5754 } 5755 //#endif 5756 hold >>>= op; 5757 bits -= op; 5758 //Tracevv((stderr, "inflate: distance %u\n", dist)); 5759 op = _out - beg; /* max distance in output */ 5760 if (dist > op) { /* see if copy from window */ 5761 op = dist - op; /* distance back in window */ 5762 if (op > whave) { 5763 if (state.sane) { 5764 strm.msg = 'invalid distance too far back'; 5765 state.mode = BAD; 5766 break top; 5767 } 5768 5769 // (!) This block is disabled in zlib defailts, 5770 // don't enable it for binary compatibility 5771 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR 5772 // if (len <= op - whave) { 5773 // do { 5774 // output[_out++] = 0; 5775 // } while (--len); 5776 // continue top; 5777 // } 5778 // len -= op - whave; 5779 // do { 5780 // output[_out++] = 0; 5781 // } while (--op > whave); 5782 // if (op === 0) { 5783 // from = _out - dist; 5784 // do { 5785 // output[_out++] = output[from++]; 5786 // } while (--len); 5787 // continue top; 5788 // } 5789 //#endif 5790 } 5791 from = 0; // window index 5792 from_source = window; 5793 if (wnext === 0) { /* very common case */ 5794 from += wsize - op; 5795 if (op < len) { /* some from window */ 5796 len -= op; 5797 do { 5798 output[_out++] = window[from++]; 5799 } while (--op); 5800 from = _out - dist; /* rest from output */ 5801 from_source = output; 5802 } 5803 } 5804 else if (wnext < op) { /* wrap around window */ 5805 from += wsize + wnext - op; 5806 op -= wnext; 5807 if (op < len) { /* some from end of window */ 5808 len -= op; 5809 do { 5810 output[_out++] = window[from++]; 5811 } while (--op); 5812 from = 0; 5813 if (wnext < len) { /* some from start of window */ 5814 op = wnext; 5815 len -= op; 5816 do { 5817 output[_out++] = window[from++]; 5818 } while (--op); 5819 from = _out - dist; /* rest from output */ 5820 from_source = output; 5821 } 5822 } 5823 } 5824 else { /* contiguous in window */ 5825 from += wnext - op; 5826 if (op < len) { /* some from window */ 5827 len -= op; 5828 do { 5829 output[_out++] = window[from++]; 5830 } while (--op); 5831 from = _out - dist; /* rest from output */ 5832 from_source = output; 5833 } 5834 } 5835 while (len > 2) { 5836 output[_out++] = from_source[from++]; 5837 output[_out++] = from_source[from++]; 5838 output[_out++] = from_source[from++]; 5839 len -= 3; 5840 } 5841 if (len) { 5842 output[_out++] = from_source[from++]; 5843 if (len > 1) { 5844 output[_out++] = from_source[from++]; 5845 } 5846 } 5847 } 5848 else { 5849 from = _out - dist; /* copy direct from output */ 5850 do { /* minimum length is three */ 5851 output[_out++] = output[from++]; 5852 output[_out++] = output[from++]; 5853 output[_out++] = output[from++]; 5854 len -= 3; 5855 } while (len > 2); 5856 if (len) { 5857 output[_out++] = output[from++]; 5858 if (len > 1) { 5859 output[_out++] = output[from++]; 5860 } 5861 } 5862 } 5863 } 5864 else if ((op & 64) === 0) { /* 2nd level distance code */ 5865 here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; 5866 continue dodist; 5867 } 5868 else { 5869 strm.msg = 'invalid distance code'; 5870 state.mode = BAD; 5871 break top; 5872 } 5873 5874 break; // need to emulate goto via "continue" 5875 } 5876 } 5877 else if ((op & 64) === 0) { /* 2nd level length code */ 5878 here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; 5879 continue dolen; 5880 } 5881 else if (op & 32) { /* end-of-block */ 5882 //Tracevv((stderr, "inflate: end of block\n")); 5883 state.mode = TYPE; 5884 break top; 5885 } 5886 else { 5887 strm.msg = 'invalid literal/length code'; 5888 state.mode = BAD; 5889 break top; 5890 } 5891 5892 break; // need to emulate goto via "continue" 5893 } 5894 } while (_in < last && _out < end); 5895 5896 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ 5897 len = bits >> 3; 5898 _in -= len; 5899 bits -= len << 3; 5900 hold &= (1 << bits) - 1; 5901 5902 /* update state and return */ 5903 strm.next_in = _in; 5904 strm.next_out = _out; 5905 strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); 5906 strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); 5907 state.hold = hold; 5908 state.bits = bits; 5909 return; 5910 }; 5911 5912 },{}],35:[function(_dereq_,module,exports){ 5913 'use strict'; 5914 5915 5916 var utils = _dereq_('../utils/common'); 5917 var adler32 = _dereq_('./adler32'); 5918 var crc32 = _dereq_('./crc32'); 5919 var inflate_fast = _dereq_('./inffast'); 5920 var inflate_table = _dereq_('./inftrees'); 5921 5922 var CODES = 0; 5923 var LENS = 1; 5924 var DISTS = 2; 5925 5926 /* Public constants ==========================================================*/ 5927 /* ===========================================================================*/ 5928 5929 5930 /* Allowed flush values; see deflate() and inflate() below for details */ 5931 //var Z_NO_FLUSH = 0; 5932 //var Z_PARTIAL_FLUSH = 1; 5933 //var Z_SYNC_FLUSH = 2; 5934 //var Z_FULL_FLUSH = 3; 5935 var Z_FINISH = 4; 5936 var Z_BLOCK = 5; 5937 var Z_TREES = 6; 5938 5939 5940 /* Return codes for the compression/decompression functions. Negative values 5941 * are errors, positive values are used for special but normal events. 5942 */ 5943 var Z_OK = 0; 5944 var Z_STREAM_END = 1; 5945 var Z_NEED_DICT = 2; 5946 //var Z_ERRNO = -1; 5947 var Z_STREAM_ERROR = -2; 5948 var Z_DATA_ERROR = -3; 5949 var Z_MEM_ERROR = -4; 5950 var Z_BUF_ERROR = -5; 5951 //var Z_VERSION_ERROR = -6; 5952 5953 /* The deflate compression method */ 5954 var Z_DEFLATED = 8; 5955 5956 5957 /* STATES ====================================================================*/ 5958 /* ===========================================================================*/ 5959 5960 5961 var HEAD = 1; /* i: waiting for magic header */ 5962 var FLAGS = 2; /* i: waiting for method and flags (gzip) */ 5963 var TIME = 3; /* i: waiting for modification time (gzip) */ 5964 var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ 5965 var EXLEN = 5; /* i: waiting for extra length (gzip) */ 5966 var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ 5967 var NAME = 7; /* i: waiting for end of file name (gzip) */ 5968 var COMMENT = 8; /* i: waiting for end of comment (gzip) */ 5969 var HCRC = 9; /* i: waiting for header crc (gzip) */ 5970 var DICTID = 10; /* i: waiting for dictionary check value */ 5971 var DICT = 11; /* waiting for inflateSetDictionary() call */ 5972 var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ 5973 var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ 5974 var STORED = 14; /* i: waiting for stored size (length and complement) */ 5975 var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ 5976 var COPY = 16; /* i/o: waiting for input or output to copy stored block */ 5977 var TABLE = 17; /* i: waiting for dynamic block table lengths */ 5978 var LENLENS = 18; /* i: waiting for code length code lengths */ 5979 var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ 5980 var LEN_ = 20; /* i: same as LEN below, but only first time in */ 5981 var LEN = 21; /* i: waiting for length/lit/eob code */ 5982 var LENEXT = 22; /* i: waiting for length extra bits */ 5983 var DIST = 23; /* i: waiting for distance code */ 5984 var DISTEXT = 24; /* i: waiting for distance extra bits */ 5985 var MATCH = 25; /* o: waiting for output space to copy string */ 5986 var LIT = 26; /* o: waiting for output space to write literal */ 5987 var CHECK = 27; /* i: waiting for 32-bit check value */ 5988 var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ 5989 var DONE = 29; /* finished check, done -- remain here until reset */ 5990 var BAD = 30; /* got a data error -- remain here until reset */ 5991 var MEM = 31; /* got an inflate() memory error -- remain here until reset */ 5992 var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ 5993 5994 /* ===========================================================================*/ 5995 5996 5997 5998 var ENOUGH_LENS = 852; 5999 var ENOUGH_DISTS = 592; 6000 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); 6001 6002 var MAX_WBITS = 15; 6003 /* 32K LZ77 window */ 6004 var DEF_WBITS = MAX_WBITS; 6005 6006 6007 function ZSWAP32(q) { 6008 return (((q >>> 24) & 0xff) + 6009 ((q >>> 8) & 0xff00) + 6010 ((q & 0xff00) << 8) + 6011 ((q & 0xff) << 24)); 6012 } 6013 6014 6015 function InflateState() { 6016 this.mode = 0; /* current inflate mode */ 6017 this.last = false; /* true if processing last block */ 6018 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ 6019 this.havedict = false; /* true if dictionary provided */ 6020 this.flags = 0; /* gzip header method and flags (0 if zlib) */ 6021 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ 6022 this.check = 0; /* protected copy of check value */ 6023 this.total = 0; /* protected copy of output count */ 6024 // TODO: may be {} 6025 this.head = null; /* where to save gzip header information */ 6026 6027 /* sliding window */ 6028 this.wbits = 0; /* log base 2 of requested window size */ 6029 this.wsize = 0; /* window size or zero if not using window */ 6030 this.whave = 0; /* valid bytes in the window */ 6031 this.wnext = 0; /* window write index */ 6032 this.window = null; /* allocated sliding window, if needed */ 6033 6034 /* bit accumulator */ 6035 this.hold = 0; /* input bit accumulator */ 6036 this.bits = 0; /* number of bits in "in" */ 6037 6038 /* for string and stored block copying */ 6039 this.length = 0; /* literal or length of data to copy */ 6040 this.offset = 0; /* distance back to copy string from */ 6041 6042 /* for table and code decoding */ 6043 this.extra = 0; /* extra bits needed */ 6044 6045 /* fixed and dynamic code tables */ 6046 this.lencode = null; /* starting table for length/literal codes */ 6047 this.distcode = null; /* starting table for distance codes */ 6048 this.lenbits = 0; /* index bits for lencode */ 6049 this.distbits = 0; /* index bits for distcode */ 6050 6051 /* dynamic table building */ 6052 this.ncode = 0; /* number of code length code lengths */ 6053 this.nlen = 0; /* number of length code lengths */ 6054 this.ndist = 0; /* number of distance code lengths */ 6055 this.have = 0; /* number of code lengths in lens[] */ 6056 this.next = null; /* next available space in codes[] */ 6057 6058 this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ 6059 this.work = new utils.Buf16(288); /* work area for code table building */ 6060 6061 /* 6062 because we don't have pointers in js, we use lencode and distcode directly 6063 as buffers so we don't need codes 6064 */ 6065 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ 6066 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ 6067 this.distdyn = null; /* dynamic table for distance codes (JS specific) */ 6068 this.sane = 0; /* if false, allow invalid distance too far */ 6069 this.back = 0; /* bits back of last unprocessed length/lit */ 6070 this.was = 0; /* initial length of match */ 6071 } 6072 6073 function inflateResetKeep(strm) { 6074 var state; 6075 6076 if (!strm || !strm.state) { return Z_STREAM_ERROR; } 6077 state = strm.state; 6078 strm.total_in = strm.total_out = state.total = 0; 6079 strm.msg = ''; /*Z_NULL*/ 6080 if (state.wrap) { /* to support ill-conceived Java test suite */ 6081 strm.adler = state.wrap & 1; 6082 } 6083 state.mode = HEAD; 6084 state.last = 0; 6085 state.havedict = 0; 6086 state.dmax = 32768; 6087 state.head = null/*Z_NULL*/; 6088 state.hold = 0; 6089 state.bits = 0; 6090 //state.lencode = state.distcode = state.next = state.codes; 6091 state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); 6092 state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); 6093 6094 state.sane = 1; 6095 state.back = -1; 6096 //Tracev((stderr, "inflate: reset\n")); 6097 return Z_OK; 6098 } 6099 6100 function inflateReset(strm) { 6101 var state; 6102 6103 if (!strm || !strm.state) { return Z_STREAM_ERROR; } 6104 state = strm.state; 6105 state.wsize = 0; 6106 state.whave = 0; 6107 state.wnext = 0; 6108 return inflateResetKeep(strm); 6109 6110 } 6111 6112 function inflateReset2(strm, windowBits) { 6113 var wrap; 6114 var state; 6115 6116 /* get the state */ 6117 if (!strm || !strm.state) { return Z_STREAM_ERROR; } 6118 state = strm.state; 6119 6120 /* extract wrap request from windowBits parameter */ 6121 if (windowBits < 0) { 6122 wrap = 0; 6123 windowBits = -windowBits; 6124 } 6125 else { 6126 wrap = (windowBits >> 4) + 1; 6127 if (windowBits < 48) { 6128 windowBits &= 15; 6129 } 6130 } 6131 6132 /* set number of window bits, free window if different */ 6133 if (windowBits && (windowBits < 8 || windowBits > 15)) { 6134 return Z_STREAM_ERROR; 6135 } 6136 if (state.window !== null && state.wbits !== windowBits) { 6137 state.window = null; 6138 } 6139 6140 /* update state and reset the rest of it */ 6141 state.wrap = wrap; 6142 state.wbits = windowBits; 6143 return inflateReset(strm); 6144 } 6145 6146 function inflateInit2(strm, windowBits) { 6147 var ret; 6148 var state; 6149 6150 if (!strm) { return Z_STREAM_ERROR; } 6151 //strm.msg = Z_NULL; /* in case we return an error */ 6152 6153 state = new InflateState(); 6154 6155 //if (state === Z_NULL) return Z_MEM_ERROR; 6156 //Tracev((stderr, "inflate: allocated\n")); 6157 strm.state = state; 6158 state.window = null/*Z_NULL*/; 6159 ret = inflateReset2(strm, windowBits); 6160 if (ret !== Z_OK) { 6161 strm.state = null/*Z_NULL*/; 6162 } 6163 return ret; 6164 } 6165 6166 function inflateInit(strm) { 6167 return inflateInit2(strm, DEF_WBITS); 6168 } 6169 6170 6171 /* 6172 Return state with length and distance decoding tables and index sizes set to 6173 fixed code decoding. Normally this returns fixed tables from inffixed.h. 6174 If BUILDFIXED is defined, then instead this routine builds the tables the 6175 first time it's called, and returns those tables the first time and 6176 thereafter. This reduces the size of the code by about 2K bytes, in 6177 exchange for a little execution time. However, BUILDFIXED should not be 6178 used for threaded applications, since the rewriting of the tables and virgin 6179 may not be thread-safe. 6180 */ 6181 var virgin = true; 6182 6183 var lenfix, distfix; // We have no pointers in JS, so keep tables separate 6184 6185 function fixedtables(state) { 6186 /* build fixed huffman tables if first call (may not be thread safe) */ 6187 if (virgin) { 6188 var sym; 6189 6190 lenfix = new utils.Buf32(512); 6191 distfix = new utils.Buf32(32); 6192 6193 /* literal/length table */ 6194 sym = 0; 6195 while (sym < 144) { state.lens[sym++] = 8; } 6196 while (sym < 256) { state.lens[sym++] = 9; } 6197 while (sym < 280) { state.lens[sym++] = 7; } 6198 while (sym < 288) { state.lens[sym++] = 8; } 6199 6200 inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); 6201 6202 /* distance table */ 6203 sym = 0; 6204 while (sym < 32) { state.lens[sym++] = 5; } 6205 6206 inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); 6207 6208 /* do this just once */ 6209 virgin = false; 6210 } 6211 6212 state.lencode = lenfix; 6213 state.lenbits = 9; 6214 state.distcode = distfix; 6215 state.distbits = 5; 6216 } 6217 6218 6219 /* 6220 Update the window with the last wsize (normally 32K) bytes written before 6221 returning. If window does not exist yet, create it. This is only called 6222 when a window is already in use, or when output has been written during this 6223 inflate call, but the end of the deflate stream has not been reached yet. 6224 It is also called to create a window for dictionary data when a dictionary 6225 is loaded. 6226 6227 Providing output buffers larger than 32K to inflate() should provide a speed 6228 advantage, since only the last 32K of output is copied to the sliding window 6229 upon return from inflate(), and since all distances after the first 32K of 6230 output will fall in the output data, making match copies simpler and faster. 6231 The advantage may be dependent on the size of the processor's data caches. 6232 */ 6233 function updatewindow(strm, src, end, copy) { 6234 var dist; 6235 var state = strm.state; 6236 6237 /* if it hasn't been done already, allocate space for the window */ 6238 if (state.window === null) { 6239 state.wsize = 1 << state.wbits; 6240 state.wnext = 0; 6241 state.whave = 0; 6242 6243 state.window = new utils.Buf8(state.wsize); 6244 } 6245 6246 /* copy state->wsize or less output bytes into the circular window */ 6247 if (copy >= state.wsize) { 6248 utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); 6249 state.wnext = 0; 6250 state.whave = state.wsize; 6251 } 6252 else { 6253 dist = state.wsize - state.wnext; 6254 if (dist > copy) { 6255 dist = copy; 6256 } 6257 //zmemcpy(state->window + state->wnext, end - copy, dist); 6258 utils.arraySet(state.window,src, end - copy, dist, state.wnext); 6259 copy -= dist; 6260 if (copy) { 6261 //zmemcpy(state->window, end - copy, copy); 6262 utils.arraySet(state.window,src, end - copy, copy, 0); 6263 state.wnext = copy; 6264 state.whave = state.wsize; 6265 } 6266 else { 6267 state.wnext += dist; 6268 if (state.wnext === state.wsize) { state.wnext = 0; } 6269 if (state.whave < state.wsize) { state.whave += dist; } 6270 } 6271 } 6272 return 0; 6273 } 6274 6275 function inflate(strm, flush) { 6276 var state; 6277 var input, output; // input/output buffers 6278 var next; /* next input INDEX */ 6279 var put; /* next output INDEX */ 6280 var have, left; /* available input and output */ 6281 var hold; /* bit buffer */ 6282 var bits; /* bits in bit buffer */ 6283 var _in, _out; /* save starting available input and output */ 6284 var copy; /* number of stored or match bytes to copy */ 6285 var from; /* where to copy match bytes from */ 6286 var from_source; 6287 var here = 0; /* current decoding table entry */ 6288 var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) 6289 //var last; /* parent table entry */ 6290 var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) 6291 var len; /* length to copy for repeats, bits to drop */ 6292 var ret; /* return code */ 6293 var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ 6294 var opts; 6295 6296 var n; // temporary var for NEED_BITS 6297 6298 var order = /* permutation of code lengths */ 6299 [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; 6300 6301 6302 if (!strm || !strm.state || !strm.output || 6303 (!strm.input && strm.avail_in !== 0)) { 6304 return Z_STREAM_ERROR; 6305 } 6306 6307 state = strm.state; 6308 if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ 6309 6310 6311 //--- LOAD() --- 6312 put = strm.next_out; 6313 output = strm.output; 6314 left = strm.avail_out; 6315 next = strm.next_in; 6316 input = strm.input; 6317 have = strm.avail_in; 6318 hold = state.hold; 6319 bits = state.bits; 6320 //--- 6321 6322 _in = have; 6323 _out = left; 6324 ret = Z_OK; 6325 6326 inf_leave: // goto emulation 6327 for (;;) { 6328 switch (state.mode) { 6329 case HEAD: 6330 if (state.wrap === 0) { 6331 state.mode = TYPEDO; 6332 break; 6333 } 6334 //=== NEEDBITS(16); 6335 while (bits < 16) { 6336 if (have === 0) { break inf_leave; } 6337 have--; 6338 hold += input[next++] << bits; 6339 bits += 8; 6340 } 6341 //===// 6342 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ 6343 state.check = 0/*crc32(0L, Z_NULL, 0)*/; 6344 //=== CRC2(state.check, hold); 6345 hbuf[0] = hold & 0xff; 6346 hbuf[1] = (hold >>> 8) & 0xff; 6347 state.check = crc32(state.check, hbuf, 2, 0); 6348 //===// 6349 6350 //=== INITBITS(); 6351 hold = 0; 6352 bits = 0; 6353 //===// 6354 state.mode = FLAGS; 6355 break; 6356 } 6357 state.flags = 0; /* expect zlib header */ 6358 if (state.head) { 6359 state.head.done = false; 6360 } 6361 if (!(state.wrap & 1) || /* check if zlib header allowed */ 6362 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { 6363 strm.msg = 'incorrect header check'; 6364 state.mode = BAD; 6365 break; 6366 } 6367 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { 6368 strm.msg = 'unknown compression method'; 6369 state.mode = BAD; 6370 break; 6371 } 6372 //--- DROPBITS(4) ---// 6373 hold >>>= 4; 6374 bits -= 4; 6375 //---// 6376 len = (hold & 0x0f)/*BITS(4)*/ + 8; 6377 if (state.wbits === 0) { 6378 state.wbits = len; 6379 } 6380 else if (len > state.wbits) { 6381 strm.msg = 'invalid window size'; 6382 state.mode = BAD; 6383 break; 6384 } 6385 state.dmax = 1 << len; 6386 //Tracev((stderr, "inflate: zlib header ok\n")); 6387 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; 6388 state.mode = hold & 0x200 ? DICTID : TYPE; 6389 //=== INITBITS(); 6390 hold = 0; 6391 bits = 0; 6392 //===// 6393 break; 6394 case FLAGS: 6395 //=== NEEDBITS(16); */ 6396 while (bits < 16) { 6397 if (have === 0) { break inf_leave; } 6398 have--; 6399 hold += input[next++] << bits; 6400 bits += 8; 6401 } 6402 //===// 6403 state.flags = hold; 6404 if ((state.flags & 0xff) !== Z_DEFLATED) { 6405 strm.msg = 'unknown compression method'; 6406 state.mode = BAD; 6407 break; 6408 } 6409 if (state.flags & 0xe000) { 6410 strm.msg = 'unknown header flags set'; 6411 state.mode = BAD; 6412 break; 6413 } 6414 if (state.head) { 6415 state.head.text = ((hold >> 8) & 1); 6416 } 6417 if (state.flags & 0x0200) { 6418 //=== CRC2(state.check, hold); 6419 hbuf[0] = hold & 0xff; 6420 hbuf[1] = (hold >>> 8) & 0xff; 6421 state.check = crc32(state.check, hbuf, 2, 0); 6422 //===// 6423 } 6424 //=== INITBITS(); 6425 hold = 0; 6426 bits = 0; 6427 //===// 6428 state.mode = TIME; 6429 /* falls through */ 6430 case TIME: 6431 //=== NEEDBITS(32); */ 6432 while (bits < 32) { 6433 if (have === 0) { break inf_leave; } 6434 have--; 6435 hold += input[next++] << bits; 6436 bits += 8; 6437 } 6438 //===// 6439 if (state.head) { 6440 state.head.time = hold; 6441 } 6442 if (state.flags & 0x0200) { 6443 //=== CRC4(state.check, hold) 6444 hbuf[0] = hold & 0xff; 6445 hbuf[1] = (hold >>> 8) & 0xff; 6446 hbuf[2] = (hold >>> 16) & 0xff; 6447 hbuf[3] = (hold >>> 24) & 0xff; 6448 state.check = crc32(state.check, hbuf, 4, 0); 6449 //=== 6450 } 6451 //=== INITBITS(); 6452 hold = 0; 6453 bits = 0; 6454 //===// 6455 state.mode = OS; 6456 /* falls through */ 6457 case OS: 6458 //=== NEEDBITS(16); */ 6459 while (bits < 16) { 6460 if (have === 0) { break inf_leave; } 6461 have--; 6462 hold += input[next++] << bits; 6463 bits += 8; 6464 } 6465 //===// 6466 if (state.head) { 6467 state.head.xflags = (hold & 0xff); 6468 state.head.os = (hold >> 8); 6469 } 6470 if (state.flags & 0x0200) { 6471 //=== CRC2(state.check, hold); 6472 hbuf[0] = hold & 0xff; 6473 hbuf[1] = (hold >>> 8) & 0xff; 6474 state.check = crc32(state.check, hbuf, 2, 0); 6475 //===// 6476 } 6477 //=== INITBITS(); 6478 hold = 0; 6479 bits = 0; 6480 //===// 6481 state.mode = EXLEN; 6482 /* falls through */ 6483 case EXLEN: 6484 if (state.flags & 0x0400) { 6485 //=== NEEDBITS(16); */ 6486 while (bits < 16) { 6487 if (have === 0) { break inf_leave; } 6488 have--; 6489 hold += input[next++] << bits; 6490 bits += 8; 6491 } 6492 //===// 6493 state.length = hold; 6494 if (state.head) { 6495 state.head.extra_len = hold; 6496 } 6497 if (state.flags & 0x0200) { 6498 //=== CRC2(state.check, hold); 6499 hbuf[0] = hold & 0xff; 6500 hbuf[1] = (hold >>> 8) & 0xff; 6501 state.check = crc32(state.check, hbuf, 2, 0); 6502 //===// 6503 } 6504 //=== INITBITS(); 6505 hold = 0; 6506 bits = 0; 6507 //===// 6508 } 6509 else if (state.head) { 6510 state.head.extra = null/*Z_NULL*/; 6511 } 6512 state.mode = EXTRA; 6513 /* falls through */ 6514 case EXTRA: 6515 if (state.flags & 0x0400) { 6516 copy = state.length; 6517 if (copy > have) { copy = have; } 6518 if (copy) { 6519 if (state.head) { 6520 len = state.head.extra_len - state.length; 6521 if (!state.head.extra) { 6522 // Use untyped array for more conveniend processing later 6523 state.head.extra = new Array(state.head.extra_len); 6524 } 6525 utils.arraySet( 6526 state.head.extra, 6527 input, 6528 next, 6529 // extra field is limited to 65536 bytes 6530 // - no need for additional size check 6531 copy, 6532 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ 6533 len 6534 ); 6535 //zmemcpy(state.head.extra + len, next, 6536 // len + copy > state.head.extra_max ? 6537 // state.head.extra_max - len : copy); 6538 } 6539 if (state.flags & 0x0200) { 6540 state.check = crc32(state.check, input, copy, next); 6541 } 6542 have -= copy; 6543 next += copy; 6544 state.length -= copy; 6545 } 6546 if (state.length) { break inf_leave; } 6547 } 6548 state.length = 0; 6549 state.mode = NAME; 6550 /* falls through */ 6551 case NAME: 6552 if (state.flags & 0x0800) { 6553 if (have === 0) { break inf_leave; } 6554 copy = 0; 6555 do { 6556 // TODO: 2 or 1 bytes? 6557 len = input[next + copy++]; 6558 /* use constant limit because in js we should not preallocate memory */ 6559 if (state.head && len && 6560 (state.length < 65536 /*state.head.name_max*/)) { 6561 state.head.name += String.fromCharCode(len); 6562 } 6563 } while (len && copy < have); 6564 6565 if (state.flags & 0x0200) { 6566 state.check = crc32(state.check, input, copy, next); 6567 } 6568 have -= copy; 6569 next += copy; 6570 if (len) { break inf_leave; } 6571 } 6572 else if (state.head) { 6573 state.head.name = null; 6574 } 6575 state.length = 0; 6576 state.mode = COMMENT; 6577 /* falls through */ 6578 case COMMENT: 6579 if (state.flags & 0x1000) { 6580 if (have === 0) { break inf_leave; } 6581 copy = 0; 6582 do { 6583 len = input[next + copy++]; 6584 /* use constant limit because in js we should not preallocate memory */ 6585 if (state.head && len && 6586 (state.length < 65536 /*state.head.comm_max*/)) { 6587 state.head.comment += String.fromCharCode(len); 6588 } 6589 } while (len && copy < have); 6590 if (state.flags & 0x0200) { 6591 state.check = crc32(state.check, input, copy, next); 6592 } 6593 have -= copy; 6594 next += copy; 6595 if (len) { break inf_leave; } 6596 } 6597 else if (state.head) { 6598 state.head.comment = null; 6599 } 6600 state.mode = HCRC; 6601 /* falls through */ 6602 case HCRC: 6603 if (state.flags & 0x0200) { 6604 //=== NEEDBITS(16); */ 6605 while (bits < 16) { 6606 if (have === 0) { break inf_leave; } 6607 have--; 6608 hold += input[next++] << bits; 6609 bits += 8; 6610 } 6611 //===// 6612 if (hold !== (state.check & 0xffff)) { 6613 strm.msg = 'header crc mismatch'; 6614 state.mode = BAD; 6615 break; 6616 } 6617 //=== INITBITS(); 6618 hold = 0; 6619 bits = 0; 6620 //===// 6621 } 6622 if (state.head) { 6623 state.head.hcrc = ((state.flags >> 9) & 1); 6624 state.head.done = true; 6625 } 6626 strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; 6627 state.mode = TYPE; 6628 break; 6629 case DICTID: 6630 //=== NEEDBITS(32); */ 6631 while (bits < 32) { 6632 if (have === 0) { break inf_leave; } 6633 have--; 6634 hold += input[next++] << bits; 6635 bits += 8; 6636 } 6637 //===// 6638 strm.adler = state.check = ZSWAP32(hold); 6639 //=== INITBITS(); 6640 hold = 0; 6641 bits = 0; 6642 //===// 6643 state.mode = DICT; 6644 /* falls through */ 6645 case DICT: 6646 if (state.havedict === 0) { 6647 //--- RESTORE() --- 6648 strm.next_out = put; 6649 strm.avail_out = left; 6650 strm.next_in = next; 6651 strm.avail_in = have; 6652 state.hold = hold; 6653 state.bits = bits; 6654 //--- 6655 return Z_NEED_DICT; 6656 } 6657 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; 6658 state.mode = TYPE; 6659 /* falls through */ 6660 case TYPE: 6661 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } 6662 /* falls through */ 6663 case TYPEDO: 6664 if (state.last) { 6665 //--- BYTEBITS() ---// 6666 hold >>>= bits & 7; 6667 bits -= bits & 7; 6668 //---// 6669 state.mode = CHECK; 6670 break; 6671 } 6672 //=== NEEDBITS(3); */ 6673 while (bits < 3) { 6674 if (have === 0) { break inf_leave; } 6675 have--; 6676 hold += input[next++] << bits; 6677 bits += 8; 6678 } 6679 //===// 6680 state.last = (hold & 0x01)/*BITS(1)*/; 6681 //--- DROPBITS(1) ---// 6682 hold >>>= 1; 6683 bits -= 1; 6684 //---// 6685 6686 switch ((hold & 0x03)/*BITS(2)*/) { 6687 case 0: /* stored block */ 6688 //Tracev((stderr, "inflate: stored block%s\n", 6689 // state.last ? " (last)" : "")); 6690 state.mode = STORED; 6691 break; 6692 case 1: /* fixed block */ 6693 fixedtables(state); 6694 //Tracev((stderr, "inflate: fixed codes block%s\n", 6695 // state.last ? " (last)" : "")); 6696 state.mode = LEN_; /* decode codes */ 6697 if (flush === Z_TREES) { 6698 //--- DROPBITS(2) ---// 6699 hold >>>= 2; 6700 bits -= 2; 6701 //---// 6702 break inf_leave; 6703 } 6704 break; 6705 case 2: /* dynamic block */ 6706 //Tracev((stderr, "inflate: dynamic codes block%s\n", 6707 // state.last ? " (last)" : "")); 6708 state.mode = TABLE; 6709 break; 6710 case 3: 6711 strm.msg = 'invalid block type'; 6712 state.mode = BAD; 6713 } 6714 //--- DROPBITS(2) ---// 6715 hold >>>= 2; 6716 bits -= 2; 6717 //---// 6718 break; 6719 case STORED: 6720 //--- BYTEBITS() ---// /* go to byte boundary */ 6721 hold >>>= bits & 7; 6722 bits -= bits & 7; 6723 //---// 6724 //=== NEEDBITS(32); */ 6725 while (bits < 32) { 6726 if (have === 0) { break inf_leave; } 6727 have--; 6728 hold += input[next++] << bits; 6729 bits += 8; 6730 } 6731 //===// 6732 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { 6733 strm.msg = 'invalid stored block lengths'; 6734 state.mode = BAD; 6735 break; 6736 } 6737 state.length = hold & 0xffff; 6738 //Tracev((stderr, "inflate: stored length %u\n", 6739 // state.length)); 6740 //=== INITBITS(); 6741 hold = 0; 6742 bits = 0; 6743 //===// 6744 state.mode = COPY_; 6745 if (flush === Z_TREES) { break inf_leave; } 6746 /* falls through */ 6747 case COPY_: 6748 state.mode = COPY; 6749 /* falls through */ 6750 case COPY: 6751 copy = state.length; 6752 if (copy) { 6753 if (copy > have) { copy = have; } 6754 if (copy > left) { copy = left; } 6755 if (copy === 0) { break inf_leave; } 6756 //--- zmemcpy(put, next, copy); --- 6757 utils.arraySet(output, input, next, copy, put); 6758 //---// 6759 have -= copy; 6760 next += copy; 6761 left -= copy; 6762 put += copy; 6763 state.length -= copy; 6764 break; 6765 } 6766 //Tracev((stderr, "inflate: stored end\n")); 6767 state.mode = TYPE; 6768 break; 6769 case TABLE: 6770 //=== NEEDBITS(14); */ 6771 while (bits < 14) { 6772 if (have === 0) { break inf_leave; } 6773 have--; 6774 hold += input[next++] << bits; 6775 bits += 8; 6776 } 6777 //===// 6778 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; 6779 //--- DROPBITS(5) ---// 6780 hold >>>= 5; 6781 bits -= 5; 6782 //---// 6783 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; 6784 //--- DROPBITS(5) ---// 6785 hold >>>= 5; 6786 bits -= 5; 6787 //---// 6788 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; 6789 //--- DROPBITS(4) ---// 6790 hold >>>= 4; 6791 bits -= 4; 6792 //---// 6793 //#ifndef PKZIP_BUG_WORKAROUND 6794 if (state.nlen > 286 || state.ndist > 30) { 6795 strm.msg = 'too many length or distance symbols'; 6796 state.mode = BAD; 6797 break; 6798 } 6799 //#endif 6800 //Tracev((stderr, "inflate: table sizes ok\n")); 6801 state.have = 0; 6802 state.mode = LENLENS; 6803 /* falls through */ 6804 case LENLENS: 6805 while (state.have < state.ncode) { 6806 //=== NEEDBITS(3); 6807 while (bits < 3) { 6808 if (have === 0) { break inf_leave; } 6809 have--; 6810 hold += input[next++] << bits; 6811 bits += 8; 6812 } 6813 //===// 6814 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); 6815 //--- DROPBITS(3) ---// 6816 hold >>>= 3; 6817 bits -= 3; 6818 //---// 6819 } 6820 while (state.have < 19) { 6821 state.lens[order[state.have++]] = 0; 6822 } 6823 // We have separate tables & no pointers. 2 commented lines below not needed. 6824 //state.next = state.codes; 6825 //state.lencode = state.next; 6826 // Switch to use dynamic table 6827 state.lencode = state.lendyn; 6828 state.lenbits = 7; 6829 6830 opts = {bits: state.lenbits}; 6831 ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); 6832 state.lenbits = opts.bits; 6833 6834 if (ret) { 6835 strm.msg = 'invalid code lengths set'; 6836 state.mode = BAD; 6837 break; 6838 } 6839 //Tracev((stderr, "inflate: code lengths ok\n")); 6840 state.have = 0; 6841 state.mode = CODELENS; 6842 /* falls through */ 6843 case CODELENS: 6844 while (state.have < state.nlen + state.ndist) { 6845 for (;;) { 6846 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ 6847 here_bits = here >>> 24; 6848 here_op = (here >>> 16) & 0xff; 6849 here_val = here & 0xffff; 6850 6851 if ((here_bits) <= bits) { break; } 6852 //--- PULLBYTE() ---// 6853 if (have === 0) { break inf_leave; } 6854 have--; 6855 hold += input[next++] << bits; 6856 bits += 8; 6857 //---// 6858 } 6859 if (here_val < 16) { 6860 //--- DROPBITS(here.bits) ---// 6861 hold >>>= here_bits; 6862 bits -= here_bits; 6863 //---// 6864 state.lens[state.have++] = here_val; 6865 } 6866 else { 6867 if (here_val === 16) { 6868 //=== NEEDBITS(here.bits + 2); 6869 n = here_bits + 2; 6870 while (bits < n) { 6871 if (have === 0) { break inf_leave; } 6872 have--; 6873 hold += input[next++] << bits; 6874 bits += 8; 6875 } 6876 //===// 6877 //--- DROPBITS(here.bits) ---// 6878 hold >>>= here_bits; 6879 bits -= here_bits; 6880 //---// 6881 if (state.have === 0) { 6882 strm.msg = 'invalid bit length repeat'; 6883 state.mode = BAD; 6884 break; 6885 } 6886 len = state.lens[state.have - 1]; 6887 copy = 3 + (hold & 0x03);//BITS(2); 6888 //--- DROPBITS(2) ---// 6889 hold >>>= 2; 6890 bits -= 2; 6891 //---// 6892 } 6893 else if (here_val === 17) { 6894 //=== NEEDBITS(here.bits + 3); 6895 n = here_bits + 3; 6896 while (bits < n) { 6897 if (have === 0) { break inf_leave; } 6898 have--; 6899 hold += input[next++] << bits; 6900 bits += 8; 6901 } 6902 //===// 6903 //--- DROPBITS(here.bits) ---// 6904 hold >>>= here_bits; 6905 bits -= here_bits; 6906 //---// 6907 len = 0; 6908 copy = 3 + (hold & 0x07);//BITS(3); 6909 //--- DROPBITS(3) ---// 6910 hold >>>= 3; 6911 bits -= 3; 6912 //---// 6913 } 6914 else { 6915 //=== NEEDBITS(here.bits + 7); 6916 n = here_bits + 7; 6917 while (bits < n) { 6918 if (have === 0) { break inf_leave; } 6919 have--; 6920 hold += input[next++] << bits; 6921 bits += 8; 6922 } 6923 //===// 6924 //--- DROPBITS(here.bits) ---// 6925 hold >>>= here_bits; 6926 bits -= here_bits; 6927 //---// 6928 len = 0; 6929 copy = 11 + (hold & 0x7f);//BITS(7); 6930 //--- DROPBITS(7) ---// 6931 hold >>>= 7; 6932 bits -= 7; 6933 //---// 6934 } 6935 if (state.have + copy > state.nlen + state.ndist) { 6936 strm.msg = 'invalid bit length repeat'; 6937 state.mode = BAD; 6938 break; 6939 } 6940 while (copy--) { 6941 state.lens[state.have++] = len; 6942 } 6943 } 6944 } 6945 6946 /* handle error breaks in while */ 6947 if (state.mode === BAD) { break; } 6948 6949 /* check for end-of-block code (better have one) */ 6950 if (state.lens[256] === 0) { 6951 strm.msg = 'invalid code -- missing end-of-block'; 6952 state.mode = BAD; 6953 break; 6954 } 6955 6956 /* build code tables -- note: do not change the lenbits or distbits 6957 values here (9 and 6) without reading the comments in inftrees.h 6958 concerning the ENOUGH constants, which depend on those values */ 6959 state.lenbits = 9; 6960 6961 opts = {bits: state.lenbits}; 6962 ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); 6963 // We have separate tables & no pointers. 2 commented lines below not needed. 6964 // state.next_index = opts.table_index; 6965 state.lenbits = opts.bits; 6966 // state.lencode = state.next; 6967 6968 if (ret) { 6969 strm.msg = 'invalid literal/lengths set'; 6970 state.mode = BAD; 6971 break; 6972 } 6973 6974 state.distbits = 6; 6975 //state.distcode.copy(state.codes); 6976 // Switch to use dynamic table 6977 state.distcode = state.distdyn; 6978 opts = {bits: state.distbits}; 6979 ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); 6980 // We have separate tables & no pointers. 2 commented lines below not needed. 6981 // state.next_index = opts.table_index; 6982 state.distbits = opts.bits; 6983 // state.distcode = state.next; 6984 6985 if (ret) { 6986 strm.msg = 'invalid distances set'; 6987 state.mode = BAD; 6988 break; 6989 } 6990 //Tracev((stderr, 'inflate: codes ok\n')); 6991 state.mode = LEN_; 6992 if (flush === Z_TREES) { break inf_leave; } 6993 /* falls through */ 6994 case LEN_: 6995 state.mode = LEN; 6996 /* falls through */ 6997 case LEN: 6998 if (have >= 6 && left >= 258) { 6999 //--- RESTORE() --- 7000 strm.next_out = put; 7001 strm.avail_out = left; 7002 strm.next_in = next; 7003 strm.avail_in = have; 7004 state.hold = hold; 7005 state.bits = bits; 7006 //--- 7007 inflate_fast(strm, _out); 7008 //--- LOAD() --- 7009 put = strm.next_out; 7010 output = strm.output; 7011 left = strm.avail_out; 7012 next = strm.next_in; 7013 input = strm.input; 7014 have = strm.avail_in; 7015 hold = state.hold; 7016 bits = state.bits; 7017 //--- 7018 7019 if (state.mode === TYPE) { 7020 state.back = -1; 7021 } 7022 break; 7023 } 7024 state.back = 0; 7025 for (;;) { 7026 here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ 7027 here_bits = here >>> 24; 7028 here_op = (here >>> 16) & 0xff; 7029 here_val = here & 0xffff; 7030 7031 if (here_bits <= bits) { break; } 7032 //--- PULLBYTE() ---// 7033 if (have === 0) { break inf_leave; } 7034 have--; 7035 hold += input[next++] << bits; 7036 bits += 8; 7037 //---// 7038 } 7039 if (here_op && (here_op & 0xf0) === 0) { 7040 last_bits = here_bits; 7041 last_op = here_op; 7042 last_val = here_val; 7043 for (;;) { 7044 here = state.lencode[last_val + 7045 ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; 7046 here_bits = here >>> 24; 7047 here_op = (here >>> 16) & 0xff; 7048 here_val = here & 0xffff; 7049 7050 if ((last_bits + here_bits) <= bits) { break; } 7051 //--- PULLBYTE() ---// 7052 if (have === 0) { break inf_leave; } 7053 have--; 7054 hold += input[next++] << bits; 7055 bits += 8; 7056 //---// 7057 } 7058 //--- DROPBITS(last.bits) ---// 7059 hold >>>= last_bits; 7060 bits -= last_bits; 7061 //---// 7062 state.back += last_bits; 7063 } 7064 //--- DROPBITS(here.bits) ---// 7065 hold >>>= here_bits; 7066 bits -= here_bits; 7067 //---// 7068 state.back += here_bits; 7069 state.length = here_val; 7070 if (here_op === 0) { 7071 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? 7072 // "inflate: literal '%c'\n" : 7073 // "inflate: literal 0x%02x\n", here.val)); 7074 state.mode = LIT; 7075 break; 7076 } 7077 if (here_op & 32) { 7078 //Tracevv((stderr, "inflate: end of block\n")); 7079 state.back = -1; 7080 state.mode = TYPE; 7081 break; 7082 } 7083 if (here_op & 64) { 7084 strm.msg = 'invalid literal/length code'; 7085 state.mode = BAD; 7086 break; 7087 } 7088 state.extra = here_op & 15; 7089 state.mode = LENEXT; 7090 /* falls through */ 7091 case LENEXT: 7092 if (state.extra) { 7093 //=== NEEDBITS(state.extra); 7094 n = state.extra; 7095 while (bits < n) { 7096 if (have === 0) { break inf_leave; } 7097 have--; 7098 hold += input[next++] << bits; 7099 bits += 8; 7100 } 7101 //===// 7102 state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; 7103 //--- DROPBITS(state.extra) ---// 7104 hold >>>= state.extra; 7105 bits -= state.extra; 7106 //---// 7107 state.back += state.extra; 7108 } 7109 //Tracevv((stderr, "inflate: length %u\n", state.length)); 7110 state.was = state.length; 7111 state.mode = DIST; 7112 /* falls through */ 7113 case DIST: 7114 for (;;) { 7115 here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ 7116 here_bits = here >>> 24; 7117 here_op = (here >>> 16) & 0xff; 7118 here_val = here & 0xffff; 7119 7120 if ((here_bits) <= bits) { break; } 7121 //--- PULLBYTE() ---// 7122 if (have === 0) { break inf_leave; } 7123 have--; 7124 hold += input[next++] << bits; 7125 bits += 8; 7126 //---// 7127 } 7128 if ((here_op & 0xf0) === 0) { 7129 last_bits = here_bits; 7130 last_op = here_op; 7131 last_val = here_val; 7132 for (;;) { 7133 here = state.distcode[last_val + 7134 ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; 7135 here_bits = here >>> 24; 7136 here_op = (here >>> 16) & 0xff; 7137 here_val = here & 0xffff; 7138 7139 if ((last_bits + here_bits) <= bits) { break; } 7140 //--- PULLBYTE() ---// 7141 if (have === 0) { break inf_leave; } 7142 have--; 7143 hold += input[next++] << bits; 7144 bits += 8; 7145 //---// 7146 } 7147 //--- DROPBITS(last.bits) ---// 7148 hold >>>= last_bits; 7149 bits -= last_bits; 7150 //---// 7151 state.back += last_bits; 7152 } 7153 //--- DROPBITS(here.bits) ---// 7154 hold >>>= here_bits; 7155 bits -= here_bits; 7156 //---// 7157 state.back += here_bits; 7158 if (here_op & 64) { 7159 strm.msg = 'invalid distance code'; 7160 state.mode = BAD; 7161 break; 7162 } 7163 state.offset = here_val; 7164 state.extra = (here_op) & 15; 7165 state.mode = DISTEXT; 7166 /* falls through */ 7167 case DISTEXT: 7168 if (state.extra) { 7169 //=== NEEDBITS(state.extra); 7170 n = state.extra; 7171 while (bits < n) { 7172 if (have === 0) { break inf_leave; } 7173 have--; 7174 hold += input[next++] << bits; 7175 bits += 8; 7176 } 7177 //===// 7178 state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; 7179 //--- DROPBITS(state.extra) ---// 7180 hold >>>= state.extra; 7181 bits -= state.extra; 7182 //---// 7183 state.back += state.extra; 7184 } 7185 //#ifdef INFLATE_STRICT 7186 if (state.offset > state.dmax) { 7187 strm.msg = 'invalid distance too far back'; 7188 state.mode = BAD; 7189 break; 7190 } 7191 //#endif 7192 //Tracevv((stderr, "inflate: distance %u\n", state.offset)); 7193 state.mode = MATCH; 7194 /* falls through */ 7195 case MATCH: 7196 if (left === 0) { break inf_leave; } 7197 copy = _out - left; 7198 if (state.offset > copy) { /* copy from window */ 7199 copy = state.offset - copy; 7200 if (copy > state.whave) { 7201 if (state.sane) { 7202 strm.msg = 'invalid distance too far back'; 7203 state.mode = BAD; 7204 break; 7205 } 7206 // (!) This block is disabled in zlib defailts, 7207 // don't enable it for binary compatibility 7208 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR 7209 // Trace((stderr, "inflate.c too far\n")); 7210 // copy -= state.whave; 7211 // if (copy > state.length) { copy = state.length; } 7212 // if (copy > left) { copy = left; } 7213 // left -= copy; 7214 // state.length -= copy; 7215 // do { 7216 // output[put++] = 0; 7217 // } while (--copy); 7218 // if (state.length === 0) { state.mode = LEN; } 7219 // break; 7220 //#endif 7221 } 7222 if (copy > state.wnext) { 7223 copy -= state.wnext; 7224 from = state.wsize - copy; 7225 } 7226 else { 7227 from = state.wnext - copy; 7228 } 7229 if (copy > state.length) { copy = state.length; } 7230 from_source = state.window; 7231 } 7232 else { /* copy from output */ 7233 from_source = output; 7234 from = put - state.offset; 7235 copy = state.length; 7236 } 7237 if (copy > left) { copy = left; } 7238 left -= copy; 7239 state.length -= copy; 7240 do { 7241 output[put++] = from_source[from++]; 7242 } while (--copy); 7243 if (state.length === 0) { state.mode = LEN; } 7244 break; 7245 case LIT: 7246 if (left === 0) { break inf_leave; } 7247 output[put++] = state.length; 7248 left--; 7249 state.mode = LEN; 7250 break; 7251 case CHECK: 7252 if (state.wrap) { 7253 //=== NEEDBITS(32); 7254 while (bits < 32) { 7255 if (have === 0) { break inf_leave; } 7256 have--; 7257 // Use '|' insdead of '+' to make sure that result is signed 7258 hold |= input[next++] << bits; 7259 bits += 8; 7260 } 7261 //===// 7262 _out -= left; 7263 strm.total_out += _out; 7264 state.total += _out; 7265 if (_out) { 7266 strm.adler = state.check = 7267 /*UPDATE(state.check, put - _out, _out);*/ 7268 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); 7269 7270 } 7271 _out = left; 7272 // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too 7273 if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { 7274 strm.msg = 'incorrect data check'; 7275 state.mode = BAD; 7276 break; 7277 } 7278 //=== INITBITS(); 7279 hold = 0; 7280 bits = 0; 7281 //===// 7282 //Tracev((stderr, "inflate: check matches trailer\n")); 7283 } 7284 state.mode = LENGTH; 7285 /* falls through */ 7286 case LENGTH: 7287 if (state.wrap && state.flags) { 7288 //=== NEEDBITS(32); 7289 while (bits < 32) { 7290 if (have === 0) { break inf_leave; } 7291 have--; 7292 hold += input[next++] << bits; 7293 bits += 8; 7294 } 7295 //===// 7296 if (hold !== (state.total & 0xffffffff)) { 7297 strm.msg = 'incorrect length check'; 7298 state.mode = BAD; 7299 break; 7300 } 7301 //=== INITBITS(); 7302 hold = 0; 7303 bits = 0; 7304 //===// 7305 //Tracev((stderr, "inflate: length matches trailer\n")); 7306 } 7307 state.mode = DONE; 7308 /* falls through */ 7309 case DONE: 7310 ret = Z_STREAM_END; 7311 break inf_leave; 7312 case BAD: 7313 ret = Z_DATA_ERROR; 7314 break inf_leave; 7315 case MEM: 7316 return Z_MEM_ERROR; 7317 case SYNC: 7318 /* falls through */ 7319 default: 7320 return Z_STREAM_ERROR; 7321 } 7322 } 7323 7324 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" 7325 7326 /* 7327 Return from inflate(), updating the total counts and the check value. 7328 If there was no progress during the inflate() call, return a buffer 7329 error. Call updatewindow() to create and/or update the window state. 7330 Note: a memory error from inflate() is non-recoverable. 7331 */ 7332 7333 //--- RESTORE() --- 7334 strm.next_out = put; 7335 strm.avail_out = left; 7336 strm.next_in = next; 7337 strm.avail_in = have; 7338 state.hold = hold; 7339 state.bits = bits; 7340 //--- 7341 7342 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && 7343 (state.mode < CHECK || flush !== Z_FINISH))) { 7344 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { 7345 state.mode = MEM; 7346 return Z_MEM_ERROR; 7347 } 7348 } 7349 _in -= strm.avail_in; 7350 _out -= strm.avail_out; 7351 strm.total_in += _in; 7352 strm.total_out += _out; 7353 state.total += _out; 7354 if (state.wrap && _out) { 7355 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ 7356 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); 7357 } 7358 strm.data_type = state.bits + (state.last ? 64 : 0) + 7359 (state.mode === TYPE ? 128 : 0) + 7360 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); 7361 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { 7362 ret = Z_BUF_ERROR; 7363 } 7364 return ret; 7365 } 7366 7367 function inflateEnd(strm) { 7368 7369 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { 7370 return Z_STREAM_ERROR; 7371 } 7372 7373 var state = strm.state; 7374 if (state.window) { 7375 state.window = null; 7376 } 7377 strm.state = null; 7378 return Z_OK; 7379 } 7380 7381 function inflateGetHeader(strm, head) { 7382 var state; 7383 7384 /* check state */ 7385 if (!strm || !strm.state) { return Z_STREAM_ERROR; } 7386 state = strm.state; 7387 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } 7388 7389 /* save header structure */ 7390 state.head = head; 7391 head.done = false; 7392 return Z_OK; 7393 } 7394 7395 7396 exports.inflateReset = inflateReset; 7397 exports.inflateReset2 = inflateReset2; 7398 exports.inflateResetKeep = inflateResetKeep; 7399 exports.inflateInit = inflateInit; 7400 exports.inflateInit2 = inflateInit2; 7401 exports.inflate = inflate; 7402 exports.inflateEnd = inflateEnd; 7403 exports.inflateGetHeader = inflateGetHeader; 7404 exports.inflateInfo = 'pako inflate (from Nodeca project)'; 7405 7406 /* Not implemented 7407 exports.inflateCopy = inflateCopy; 7408 exports.inflateGetDictionary = inflateGetDictionary; 7409 exports.inflateMark = inflateMark; 7410 exports.inflatePrime = inflatePrime; 7411 exports.inflateSetDictionary = inflateSetDictionary; 7412 exports.inflateSync = inflateSync; 7413 exports.inflateSyncPoint = inflateSyncPoint; 7414 exports.inflateUndermine = inflateUndermine; 7415 */ 7416 },{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(_dereq_,module,exports){ 7417 'use strict'; 7418 7419 7420 var utils = _dereq_('../utils/common'); 7421 7422 var MAXBITS = 15; 7423 var ENOUGH_LENS = 852; 7424 var ENOUGH_DISTS = 592; 7425 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); 7426 7427 var CODES = 0; 7428 var LENS = 1; 7429 var DISTS = 2; 7430 7431 var lbase = [ /* Length codes 257..285 base */ 7432 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 7433 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 7434 ]; 7435 7436 var lext = [ /* Length codes 257..285 extra */ 7437 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 7438 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 7439 ]; 7440 7441 var dbase = [ /* Distance codes 0..29 base */ 7442 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 7443 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 7444 8193, 12289, 16385, 24577, 0, 0 7445 ]; 7446 7447 var dext = [ /* Distance codes 0..29 extra */ 7448 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 7449 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 7450 28, 28, 29, 29, 64, 64 7451 ]; 7452 7453 module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) 7454 { 7455 var bits = opts.bits; 7456 //here = opts.here; /* table entry for duplication */ 7457 7458 var len = 0; /* a code's length in bits */ 7459 var sym = 0; /* index of code symbols */ 7460 var min = 0, max = 0; /* minimum and maximum code lengths */ 7461 var root = 0; /* number of index bits for root table */ 7462 var curr = 0; /* number of index bits for current table */ 7463 var drop = 0; /* code bits to drop for sub-table */ 7464 var left = 0; /* number of prefix codes available */ 7465 var used = 0; /* code entries in table used */ 7466 var huff = 0; /* Huffman code */ 7467 var incr; /* for incrementing code, index */ 7468 var fill; /* index for replicating entries */ 7469 var low; /* low bits for current root entry */ 7470 var mask; /* mask for low root bits */ 7471 var next; /* next available space in table */ 7472 var base = null; /* base value table to use */ 7473 var base_index = 0; 7474 // var shoextra; /* extra bits table to use */ 7475 var end; /* use base and extra for symbol > end */ 7476 var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ 7477 var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ 7478 var extra = null; 7479 var extra_index = 0; 7480 7481 var here_bits, here_op, here_val; 7482 7483 /* 7484 Process a set of code lengths to create a canonical Huffman code. The 7485 code lengths are lens[0..codes-1]. Each length corresponds to the 7486 symbols 0..codes-1. The Huffman code is generated by first sorting the 7487 symbols by length from short to long, and retaining the symbol order 7488 for codes with equal lengths. Then the code starts with all zero bits 7489 for the first code of the shortest length, and the codes are integer 7490 increments for the same length, and zeros are appended as the length 7491 increases. For the deflate format, these bits are stored backwards 7492 from their more natural integer increment ordering, and so when the 7493 decoding tables are built in the large loop below, the integer codes 7494 are incremented backwards. 7495 7496 This routine assumes, but does not check, that all of the entries in 7497 lens[] are in the range 0..MAXBITS. The caller must assure this. 7498 1..MAXBITS is interpreted as that code length. zero means that that 7499 symbol does not occur in this code. 7500 7501 The codes are sorted by computing a count of codes for each length, 7502 creating from that a table of starting indices for each length in the 7503 sorted table, and then entering the symbols in order in the sorted 7504 table. The sorted table is work[], with that space being provided by 7505 the caller. 7506 7507 The length counts are used for other purposes as well, i.e. finding 7508 the minimum and maximum length codes, determining if there are any 7509 codes at all, checking for a valid set of lengths, and looking ahead 7510 at length counts to determine sub-table sizes when building the 7511 decoding tables. 7512 */ 7513 7514 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ 7515 for (len = 0; len <= MAXBITS; len++) { 7516 count[len] = 0; 7517 } 7518 for (sym = 0; sym < codes; sym++) { 7519 count[lens[lens_index + sym]]++; 7520 } 7521 7522 /* bound code lengths, force root to be within code lengths */ 7523 root = bits; 7524 for (max = MAXBITS; max >= 1; max--) { 7525 if (count[max] !== 0) { break; } 7526 } 7527 if (root > max) { 7528 root = max; 7529 } 7530 if (max === 0) { /* no symbols to code at all */ 7531 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ 7532 //table.bits[opts.table_index] = 1; //here.bits = (var char)1; 7533 //table.val[opts.table_index++] = 0; //here.val = (var short)0; 7534 table[table_index++] = (1 << 24) | (64 << 16) | 0; 7535 7536 7537 //table.op[opts.table_index] = 64; 7538 //table.bits[opts.table_index] = 1; 7539 //table.val[opts.table_index++] = 0; 7540 table[table_index++] = (1 << 24) | (64 << 16) | 0; 7541 7542 opts.bits = 1; 7543 return 0; /* no symbols, but wait for decoding to report error */ 7544 } 7545 for (min = 1; min < max; min++) { 7546 if (count[min] !== 0) { break; } 7547 } 7548 if (root < min) { 7549 root = min; 7550 } 7551 7552 /* check for an over-subscribed or incomplete set of lengths */ 7553 left = 1; 7554 for (len = 1; len <= MAXBITS; len++) { 7555 left <<= 1; 7556 left -= count[len]; 7557 if (left < 0) { 7558 return -1; 7559 } /* over-subscribed */ 7560 } 7561 if (left > 0 && (type === CODES || max !== 1)) { 7562 return -1; /* incomplete set */ 7563 } 7564 7565 /* generate offsets into symbol table for each length for sorting */ 7566 offs[1] = 0; 7567 for (len = 1; len < MAXBITS; len++) { 7568 offs[len + 1] = offs[len] + count[len]; 7569 } 7570 7571 /* sort symbols by length, by symbol order within each length */ 7572 for (sym = 0; sym < codes; sym++) { 7573 if (lens[lens_index + sym] !== 0) { 7574 work[offs[lens[lens_index + sym]]++] = sym; 7575 } 7576 } 7577 7578 /* 7579 Create and fill in decoding tables. In this loop, the table being 7580 filled is at next and has curr index bits. The code being used is huff 7581 with length len. That code is converted to an index by dropping drop 7582 bits off of the bottom. For codes where len is less than drop + curr, 7583 those top drop + curr - len bits are incremented through all values to 7584 fill the table with replicated entries. 7585 7586 root is the number of index bits for the root table. When len exceeds 7587 root, sub-tables are created pointed to by the root entry with an index 7588 of the low root bits of huff. This is saved in low to check for when a 7589 new sub-table should be started. drop is zero when the root table is 7590 being filled, and drop is root when sub-tables are being filled. 7591 7592 When a new sub-table is needed, it is necessary to look ahead in the 7593 code lengths to determine what size sub-table is needed. The length 7594 counts are used for this, and so count[] is decremented as codes are 7595 entered in the tables. 7596 7597 used keeps track of how many table entries have been allocated from the 7598 provided *table space. It is checked for LENS and DIST tables against 7599 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in 7600 the initial root table size constants. See the comments in inftrees.h 7601 for more information. 7602 7603 sym increments through all symbols, and the loop terminates when 7604 all codes of length max, i.e. all codes, have been processed. This 7605 routine permits incomplete codes, so another loop after this one fills 7606 in the rest of the decoding tables with invalid code markers. 7607 */ 7608 7609 /* set up for code type */ 7610 // poor man optimization - use if-else instead of switch, 7611 // to avoid deopts in old v8 7612 if (type === CODES) { 7613 base = extra = work; /* dummy value--not used */ 7614 end = 19; 7615 } else if (type === LENS) { 7616 base = lbase; 7617 base_index -= 257; 7618 extra = lext; 7619 extra_index -= 257; 7620 end = 256; 7621 } else { /* DISTS */ 7622 base = dbase; 7623 extra = dext; 7624 end = -1; 7625 } 7626 7627 /* initialize opts for loop */ 7628 huff = 0; /* starting code */ 7629 sym = 0; /* starting code symbol */ 7630 len = min; /* starting code length */ 7631 next = table_index; /* current table to fill in */ 7632 curr = root; /* current table index bits */ 7633 drop = 0; /* current bits to drop from code for index */ 7634 low = -1; /* trigger new sub-table when len > root */ 7635 used = 1 << root; /* use root table entries */ 7636 mask = used - 1; /* mask for comparing low */ 7637 7638 /* check available table space */ 7639 if ((type === LENS && used > ENOUGH_LENS) || 7640 (type === DISTS && used > ENOUGH_DISTS)) { 7641 return 1; 7642 } 7643 7644 var i=0; 7645 /* process all codes and make table entries */ 7646 for (;;) { 7647 i++; 7648 /* create table entry */ 7649 here_bits = len - drop; 7650 if (work[sym] < end) { 7651 here_op = 0; 7652 here_val = work[sym]; 7653 } 7654 else if (work[sym] > end) { 7655 here_op = extra[extra_index + work[sym]]; 7656 here_val = base[base_index + work[sym]]; 7657 } 7658 else { 7659 here_op = 32 + 64; /* end of block */ 7660 here_val = 0; 7661 } 7662 7663 /* replicate for those indices with low len bits equal to huff */ 7664 incr = 1 << (len - drop); 7665 fill = 1 << curr; 7666 min = fill; /* save offset to next table */ 7667 do { 7668 fill -= incr; 7669 table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; 7670 } while (fill !== 0); 7671 7672 /* backwards increment the len-bit code huff */ 7673 incr = 1 << (len - 1); 7674 while (huff & incr) { 7675 incr >>= 1; 7676 } 7677 if (incr !== 0) { 7678 huff &= incr - 1; 7679 huff += incr; 7680 } else { 7681 huff = 0; 7682 } 7683 7684 /* go to next symbol, update count, len */ 7685 sym++; 7686 if (--count[len] === 0) { 7687 if (len === max) { break; } 7688 len = lens[lens_index + work[sym]]; 7689 } 7690 7691 /* create new sub-table if needed */ 7692 if (len > root && (huff & mask) !== low) { 7693 /* if first time, transition to sub-tables */ 7694 if (drop === 0) { 7695 drop = root; 7696 } 7697 7698 /* increment past last table */ 7699 next += min; /* here min is 1 << curr */ 7700 7701 /* determine length of next table */ 7702 curr = len - drop; 7703 left = 1 << curr; 7704 while (curr + drop < max) { 7705 left -= count[curr + drop]; 7706 if (left <= 0) { break; } 7707 curr++; 7708 left <<= 1; 7709 } 7710 7711 /* check for enough space */ 7712 used += 1 << curr; 7713 if ((type === LENS && used > ENOUGH_LENS) || 7714 (type === DISTS && used > ENOUGH_DISTS)) { 7715 return 1; 7716 } 7717 7718 /* point entry in root table to sub-table */ 7719 low = huff & mask; 7720 /*table.op[low] = curr; 7721 table.bits[low] = root; 7722 table.val[low] = next - opts.table_index;*/ 7723 table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; 7724 } 7725 } 7726 7727 /* fill in remaining table entry if code is incomplete (guaranteed to have 7728 at most one remaining entry, since if the code is incomplete, the 7729 maximum code length that was allowed to get this far is one bit) */ 7730 if (huff !== 0) { 7731 //table.op[next + huff] = 64; /* invalid code marker */ 7732 //table.bits[next + huff] = len - drop; 7733 //table.val[next + huff] = 0; 7734 table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; 7735 } 7736 7737 /* set return parameters */ 7738 //opts.table_index += used; 7739 opts.bits = root; 7740 return 0; 7741 }; 7742 7743 },{"../utils/common":27}],37:[function(_dereq_,module,exports){ 7744 'use strict'; 7745 7746 module.exports = { 7747 '2': 'need dictionary', /* Z_NEED_DICT 2 */ 7748 '1': 'stream end', /* Z_STREAM_END 1 */ 7749 '0': '', /* Z_OK 0 */ 7750 '-1': 'file error', /* Z_ERRNO (-1) */ 7751 '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ 7752 '-3': 'data error', /* Z_DATA_ERROR (-3) */ 7753 '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ 7754 '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ 7755 '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ 7756 }; 7757 },{}],38:[function(_dereq_,module,exports){ 7758 'use strict'; 7759 7760 7761 var utils = _dereq_('../utils/common'); 7762 7763 /* Public constants ==========================================================*/ 7764 /* ===========================================================================*/ 7765 7766 7767 //var Z_FILTERED = 1; 7768 //var Z_HUFFMAN_ONLY = 2; 7769 //var Z_RLE = 3; 7770 var Z_FIXED = 4; 7771 //var Z_DEFAULT_STRATEGY = 0; 7772 7773 /* Possible values of the data_type field (though see inflate()) */ 7774 var Z_BINARY = 0; 7775 var Z_TEXT = 1; 7776 //var Z_ASCII = 1; // = Z_TEXT 7777 var Z_UNKNOWN = 2; 7778 7779 /*============================================================================*/ 7780 7781 7782 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } 7783 7784 // From zutil.h 7785 7786 var STORED_BLOCK = 0; 7787 var STATIC_TREES = 1; 7788 var DYN_TREES = 2; 7789 /* The three kinds of block type */ 7790 7791 var MIN_MATCH = 3; 7792 var MAX_MATCH = 258; 7793 /* The minimum and maximum match lengths */ 7794 7795 // From deflate.h 7796 /* =========================================================================== 7797 * Internal compression state. 7798 */ 7799 7800 var LENGTH_CODES = 29; 7801 /* number of length codes, not counting the special END_BLOCK code */ 7802 7803 var LITERALS = 256; 7804 /* number of literal bytes 0..255 */ 7805 7806 var L_CODES = LITERALS + 1 + LENGTH_CODES; 7807 /* number of Literal or Length codes, including the END_BLOCK code */ 7808 7809 var D_CODES = 30; 7810 /* number of distance codes */ 7811 7812 var BL_CODES = 19; 7813 /* number of codes used to transfer the bit lengths */ 7814 7815 var HEAP_SIZE = 2*L_CODES + 1; 7816 /* maximum heap size */ 7817 7818 var MAX_BITS = 15; 7819 /* All codes must not exceed MAX_BITS bits */ 7820 7821 var Buf_size = 16; 7822 /* size of bit buffer in bi_buf */ 7823 7824 7825 /* =========================================================================== 7826 * Constants 7827 */ 7828 7829 var MAX_BL_BITS = 7; 7830 /* Bit length codes must not exceed MAX_BL_BITS bits */ 7831 7832 var END_BLOCK = 256; 7833 /* end of block literal code */ 7834 7835 var REP_3_6 = 16; 7836 /* repeat previous bit length 3-6 times (2 bits of repeat count) */ 7837 7838 var REPZ_3_10 = 17; 7839 /* repeat a zero length 3-10 times (3 bits of repeat count) */ 7840 7841 var REPZ_11_138 = 18; 7842 /* repeat a zero length 11-138 times (7 bits of repeat count) */ 7843 7844 var extra_lbits = /* extra bits for each length code */ 7845 [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]; 7846 7847 var extra_dbits = /* extra bits for each distance code */ 7848 [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]; 7849 7850 var extra_blbits = /* extra bits for each bit length code */ 7851 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; 7852 7853 var bl_order = 7854 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; 7855 /* The lengths of the bit length codes are sent in order of decreasing 7856 * probability, to avoid transmitting the lengths for unused bit length codes. 7857 */ 7858 7859 /* =========================================================================== 7860 * Local data. These are initialized only once. 7861 */ 7862 7863 // We pre-fill arrays with 0 to avoid uninitialized gaps 7864 7865 var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ 7866 7867 // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 7868 var static_ltree = new Array((L_CODES+2) * 2); 7869 zero(static_ltree); 7870 /* The static literal tree. Since the bit lengths are imposed, there is no 7871 * need for the L_CODES extra codes used during heap construction. However 7872 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init 7873 * below). 7874 */ 7875 7876 var static_dtree = new Array(D_CODES * 2); 7877 zero(static_dtree); 7878 /* The static distance tree. (Actually a trivial tree since all codes use 7879 * 5 bits.) 7880 */ 7881 7882 var _dist_code = new Array(DIST_CODE_LEN); 7883 zero(_dist_code); 7884 /* Distance codes. The first 256 values correspond to the distances 7885 * 3 .. 258, the last 256 values correspond to the top 8 bits of 7886 * the 15 bit distances. 7887 */ 7888 7889 var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); 7890 zero(_length_code); 7891 /* length code for each normalized match length (0 == MIN_MATCH) */ 7892 7893 var base_length = new Array(LENGTH_CODES); 7894 zero(base_length); 7895 /* First normalized length for each code (0 = MIN_MATCH) */ 7896 7897 var base_dist = new Array(D_CODES); 7898 zero(base_dist); 7899 /* First normalized distance for each code (0 = distance of 1) */ 7900 7901 7902 var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { 7903 7904 this.static_tree = static_tree; /* static tree or NULL */ 7905 this.extra_bits = extra_bits; /* extra bits for each code or NULL */ 7906 this.extra_base = extra_base; /* base index for extra_bits */ 7907 this.elems = elems; /* max number of elements in the tree */ 7908 this.max_length = max_length; /* max bit length for the codes */ 7909 7910 // show if `static_tree` has data or dummy - needed for monomorphic objects 7911 this.has_stree = static_tree && static_tree.length; 7912 }; 7913 7914 7915 var static_l_desc; 7916 var static_d_desc; 7917 var static_bl_desc; 7918 7919 7920 var TreeDesc = function(dyn_tree, stat_desc) { 7921 this.dyn_tree = dyn_tree; /* the dynamic tree */ 7922 this.max_code = 0; /* largest code with non zero frequency */ 7923 this.stat_desc = stat_desc; /* the corresponding static tree */ 7924 }; 7925 7926 7927 7928 function d_code(dist) { 7929 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; 7930 } 7931 7932 7933 /* =========================================================================== 7934 * Output a short LSB first on the stream. 7935 * IN assertion: there is enough room in pendingBuf. 7936 */ 7937 function put_short (s, w) { 7938 // put_byte(s, (uch)((w) & 0xff)); 7939 // put_byte(s, (uch)((ush)(w) >> 8)); 7940 s.pending_buf[s.pending++] = (w) & 0xff; 7941 s.pending_buf[s.pending++] = (w >>> 8) & 0xff; 7942 } 7943 7944 7945 /* =========================================================================== 7946 * Send a value on a given number of bits. 7947 * IN assertion: length <= 16 and value fits in length bits. 7948 */ 7949 function send_bits(s, value, length) { 7950 if (s.bi_valid > (Buf_size - length)) { 7951 s.bi_buf |= (value << s.bi_valid) & 0xffff; 7952 put_short(s, s.bi_buf); 7953 s.bi_buf = value >> (Buf_size - s.bi_valid); 7954 s.bi_valid += length - Buf_size; 7955 } else { 7956 s.bi_buf |= (value << s.bi_valid) & 0xffff; 7957 s.bi_valid += length; 7958 } 7959 } 7960 7961 7962 function send_code(s, c, tree) { 7963 send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); 7964 } 7965 7966 7967 /* =========================================================================== 7968 * Reverse the first len bits of a code, using straightforward code (a faster 7969 * method would use a table) 7970 * IN assertion: 1 <= len <= 15 7971 */ 7972 function bi_reverse(code, len) { 7973 var res = 0; 7974 do { 7975 res |= code & 1; 7976 code >>>= 1; 7977 res <<= 1; 7978 } while (--len > 0); 7979 return res >>> 1; 7980 } 7981 7982 7983 /* =========================================================================== 7984 * Flush the bit buffer, keeping at most 7 bits in it. 7985 */ 7986 function bi_flush(s) { 7987 if (s.bi_valid === 16) { 7988 put_short(s, s.bi_buf); 7989 s.bi_buf = 0; 7990 s.bi_valid = 0; 7991 7992 } else if (s.bi_valid >= 8) { 7993 s.pending_buf[s.pending++] = s.bi_buf & 0xff; 7994 s.bi_buf >>= 8; 7995 s.bi_valid -= 8; 7996 } 7997 } 7998 7999 8000 /* =========================================================================== 8001 * Compute the optimal bit lengths for a tree and update the total bit length 8002 * for the current block. 8003 * IN assertion: the fields freq and dad are set, heap[heap_max] and 8004 * above are the tree nodes sorted by increasing frequency. 8005 * OUT assertions: the field len is set to the optimal bit length, the 8006 * array bl_count contains the frequencies for each bit length. 8007 * The length opt_len is updated; static_len is also updated if stree is 8008 * not null. 8009 */ 8010 function gen_bitlen(s, desc) 8011 // deflate_state *s; 8012 // tree_desc *desc; /* the tree descriptor */ 8013 { 8014 var tree = desc.dyn_tree; 8015 var max_code = desc.max_code; 8016 var stree = desc.stat_desc.static_tree; 8017 var has_stree = desc.stat_desc.has_stree; 8018 var extra = desc.stat_desc.extra_bits; 8019 var base = desc.stat_desc.extra_base; 8020 var max_length = desc.stat_desc.max_length; 8021 var h; /* heap index */ 8022 var n, m; /* iterate over the tree elements */ 8023 var bits; /* bit length */ 8024 var xbits; /* extra bits */ 8025 var f; /* frequency */ 8026 var overflow = 0; /* number of elements with bit length too large */ 8027 8028 for (bits = 0; bits <= MAX_BITS; bits++) { 8029 s.bl_count[bits] = 0; 8030 } 8031 8032 /* In a first pass, compute the optimal bit lengths (which may 8033 * overflow in the case of the bit length tree). 8034 */ 8035 tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ 8036 8037 for (h = s.heap_max+1; h < HEAP_SIZE; h++) { 8038 n = s.heap[h]; 8039 bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; 8040 if (bits > max_length) { 8041 bits = max_length; 8042 overflow++; 8043 } 8044 tree[n*2 + 1]/*.Len*/ = bits; 8045 /* We overwrite tree[n].Dad which is no longer needed */ 8046 8047 if (n > max_code) { continue; } /* not a leaf node */ 8048 8049 s.bl_count[bits]++; 8050 xbits = 0; 8051 if (n >= base) { 8052 xbits = extra[n-base]; 8053 } 8054 f = tree[n * 2]/*.Freq*/; 8055 s.opt_len += f * (bits + xbits); 8056 if (has_stree) { 8057 s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); 8058 } 8059 } 8060 if (overflow === 0) { return; } 8061 8062 // Trace((stderr,"\nbit length overflow\n")); 8063 /* This happens for example on obj2 and pic of the Calgary corpus */ 8064 8065 /* Find the first bit length which could increase: */ 8066 do { 8067 bits = max_length-1; 8068 while (s.bl_count[bits] === 0) { bits--; } 8069 s.bl_count[bits]--; /* move one leaf down the tree */ 8070 s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ 8071 s.bl_count[max_length]--; 8072 /* The brother of the overflow item also moves one step up, 8073 * but this does not affect bl_count[max_length] 8074 */ 8075 overflow -= 2; 8076 } while (overflow > 0); 8077 8078 /* Now recompute all bit lengths, scanning in increasing frequency. 8079 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all 8080 * lengths instead of fixing only the wrong ones. This idea is taken 8081 * from 'ar' written by Haruhiko Okumura.) 8082 */ 8083 for (bits = max_length; bits !== 0; bits--) { 8084 n = s.bl_count[bits]; 8085 while (n !== 0) { 8086 m = s.heap[--h]; 8087 if (m > max_code) { continue; } 8088 if (tree[m*2 + 1]/*.Len*/ !== bits) { 8089 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); 8090 s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; 8091 tree[m*2 + 1]/*.Len*/ = bits; 8092 } 8093 n--; 8094 } 8095 } 8096 } 8097 8098 8099 /* =========================================================================== 8100 * Generate the codes for a given tree and bit counts (which need not be 8101 * optimal). 8102 * IN assertion: the array bl_count contains the bit length statistics for 8103 * the given tree and the field len is set for all tree elements. 8104 * OUT assertion: the field code is set for all tree elements of non 8105 * zero code length. 8106 */ 8107 function gen_codes(tree, max_code, bl_count) 8108 // ct_data *tree; /* the tree to decorate */ 8109 // int max_code; /* largest code with non zero frequency */ 8110 // ushf *bl_count; /* number of codes at each bit length */ 8111 { 8112 var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ 8113 var code = 0; /* running code value */ 8114 var bits; /* bit index */ 8115 var n; /* code index */ 8116 8117 /* The distribution counts are first used to generate the code values 8118 * without bit reversal. 8119 */ 8120 for (bits = 1; bits <= MAX_BITS; bits++) { 8121 next_code[bits] = code = (code + bl_count[bits-1]) << 1; 8122 } 8123 /* Check that the bit counts in bl_count are consistent. The last code 8124 * must be all ones. 8125 */ 8126 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, 8127 // "inconsistent bit counts"); 8128 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); 8129 8130 for (n = 0; n <= max_code; n++) { 8131 var len = tree[n*2 + 1]/*.Len*/; 8132 if (len === 0) { continue; } 8133 /* Now reverse the bits */ 8134 tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len); 8135 8136 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", 8137 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); 8138 } 8139 } 8140 8141 8142 /* =========================================================================== 8143 * Initialize the various 'constant' tables. 8144 */ 8145 function tr_static_init() { 8146 var n; /* iterates over tree elements */ 8147 var bits; /* bit counter */ 8148 var length; /* length value */ 8149 var code; /* code value */ 8150 var dist; /* distance index */ 8151 var bl_count = new Array(MAX_BITS+1); 8152 /* number of codes at each bit length for an optimal tree */ 8153 8154 // do check in _tr_init() 8155 //if (static_init_done) return; 8156 8157 /* For some embedded targets, global variables are not initialized: */ 8158 /*#ifdef NO_INIT_GLOBAL_POINTERS 8159 static_l_desc.static_tree = static_ltree; 8160 static_l_desc.extra_bits = extra_lbits; 8161 static_d_desc.static_tree = static_dtree; 8162 static_d_desc.extra_bits = extra_dbits; 8163 static_bl_desc.extra_bits = extra_blbits; 8164 #endif*/ 8165 8166 /* Initialize the mapping length (0..255) -> length code (0..28) */ 8167 length = 0; 8168 for (code = 0; code < LENGTH_CODES-1; code++) { 8169 base_length[code] = length; 8170 for (n = 0; n < (1<<extra_lbits[code]); n++) { 8171 _length_code[length++] = code; 8172 } 8173 } 8174 //Assert (length == 256, "tr_static_init: length != 256"); 8175 /* Note that the length 255 (match length 258) can be represented 8176 * in two different ways: code 284 + 5 bits or code 285, so we 8177 * overwrite length_code[255] to use the best encoding: 8178 */ 8179 _length_code[length-1] = code; 8180 8181 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ 8182 dist = 0; 8183 for (code = 0 ; code < 16; code++) { 8184 base_dist[code] = dist; 8185 for (n = 0; n < (1<<extra_dbits[code]); n++) { 8186 _dist_code[dist++] = code; 8187 } 8188 } 8189 //Assert (dist == 256, "tr_static_init: dist != 256"); 8190 dist >>= 7; /* from now on, all distances are divided by 128 */ 8191 for ( ; code < D_CODES; code++) { 8192 base_dist[code] = dist << 7; 8193 for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { 8194 _dist_code[256 + dist++] = code; 8195 } 8196 } 8197 //Assert (dist == 256, "tr_static_init: 256+dist != 512"); 8198 8199 /* Construct the codes of the static literal tree */ 8200 for (bits = 0; bits <= MAX_BITS; bits++) { 8201 bl_count[bits] = 0; 8202 } 8203 8204 n = 0; 8205 while (n <= 143) { 8206 static_ltree[n*2 + 1]/*.Len*/ = 8; 8207 n++; 8208 bl_count[8]++; 8209 } 8210 while (n <= 255) { 8211 static_ltree[n*2 + 1]/*.Len*/ = 9; 8212 n++; 8213 bl_count[9]++; 8214 } 8215 while (n <= 279) { 8216 static_ltree[n*2 + 1]/*.Len*/ = 7; 8217 n++; 8218 bl_count[7]++; 8219 } 8220 while (n <= 287) { 8221 static_ltree[n*2 + 1]/*.Len*/ = 8; 8222 n++; 8223 bl_count[8]++; 8224 } 8225 /* Codes 286 and 287 do not exist, but we must include them in the 8226 * tree construction to get a canonical Huffman tree (longest code 8227 * all ones) 8228 */ 8229 gen_codes(static_ltree, L_CODES+1, bl_count); 8230 8231 /* The static distance tree is trivial: */ 8232 for (n = 0; n < D_CODES; n++) { 8233 static_dtree[n*2 + 1]/*.Len*/ = 5; 8234 static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); 8235 } 8236 8237 // Now data ready and we can init static trees 8238 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); 8239 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); 8240 static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); 8241 8242 //static_init_done = true; 8243 } 8244 8245 8246 /* =========================================================================== 8247 * Initialize a new block. 8248 */ 8249 function init_block(s) { 8250 var n; /* iterates over tree elements */ 8251 8252 /* Initialize the trees. */ 8253 for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } 8254 for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } 8255 for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } 8256 8257 s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; 8258 s.opt_len = s.static_len = 0; 8259 s.last_lit = s.matches = 0; 8260 } 8261 8262 8263 /* =========================================================================== 8264 * Flush the bit buffer and align the output on a byte boundary 8265 */ 8266 function bi_windup(s) 8267 { 8268 if (s.bi_valid > 8) { 8269 put_short(s, s.bi_buf); 8270 } else if (s.bi_valid > 0) { 8271 //put_byte(s, (Byte)s->bi_buf); 8272 s.pending_buf[s.pending++] = s.bi_buf; 8273 } 8274 s.bi_buf = 0; 8275 s.bi_valid = 0; 8276 } 8277 8278 /* =========================================================================== 8279 * Copy a stored block, storing first the length and its 8280 * one's complement if requested. 8281 */ 8282 function copy_block(s, buf, len, header) 8283 //DeflateState *s; 8284 //charf *buf; /* the input data */ 8285 //unsigned len; /* its length */ 8286 //int header; /* true if block header must be written */ 8287 { 8288 bi_windup(s); /* align on byte boundary */ 8289 8290 if (header) { 8291 put_short(s, len); 8292 put_short(s, ~len); 8293 } 8294 // while (len--) { 8295 // put_byte(s, *buf++); 8296 // } 8297 utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); 8298 s.pending += len; 8299 } 8300 8301 /* =========================================================================== 8302 * Compares to subtrees, using the tree depth as tie breaker when 8303 * the subtrees have equal frequency. This minimizes the worst case length. 8304 */ 8305 function smaller(tree, n, m, depth) { 8306 var _n2 = n*2; 8307 var _m2 = m*2; 8308 return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || 8309 (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); 8310 } 8311 8312 /* =========================================================================== 8313 * Restore the heap property by moving down the tree starting at node k, 8314 * exchanging a node with the smallest of its two sons if necessary, stopping 8315 * when the heap property is re-established (each father smaller than its 8316 * two sons). 8317 */ 8318 function pqdownheap(s, tree, k) 8319 // deflate_state *s; 8320 // ct_data *tree; /* the tree to restore */ 8321 // int k; /* node to move down */ 8322 { 8323 var v = s.heap[k]; 8324 var j = k << 1; /* left son of k */ 8325 while (j <= s.heap_len) { 8326 /* Set j to the smallest of the two sons: */ 8327 if (j < s.heap_len && 8328 smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { 8329 j++; 8330 } 8331 /* Exit if v is smaller than both sons */ 8332 if (smaller(tree, v, s.heap[j], s.depth)) { break; } 8333 8334 /* Exchange v with the smallest son */ 8335 s.heap[k] = s.heap[j]; 8336 k = j; 8337 8338 /* And continue down the tree, setting j to the left son of k */ 8339 j <<= 1; 8340 } 8341 s.heap[k] = v; 8342 } 8343 8344 8345 // inlined manually 8346 // var SMALLEST = 1; 8347 8348 /* =========================================================================== 8349 * Send the block data compressed using the given Huffman trees 8350 */ 8351 function compress_block(s, ltree, dtree) 8352 // deflate_state *s; 8353 // const ct_data *ltree; /* literal tree */ 8354 // const ct_data *dtree; /* distance tree */ 8355 { 8356 var dist; /* distance of matched string */ 8357 var lc; /* match length or unmatched char (if dist == 0) */ 8358 var lx = 0; /* running index in l_buf */ 8359 var code; /* the code to send */ 8360 var extra; /* number of extra bits to send */ 8361 8362 if (s.last_lit !== 0) { 8363 do { 8364 dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); 8365 lc = s.pending_buf[s.l_buf + lx]; 8366 lx++; 8367 8368 if (dist === 0) { 8369 send_code(s, lc, ltree); /* send a literal byte */ 8370 //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); 8371 } else { 8372 /* Here, lc is the match length - MIN_MATCH */ 8373 code = _length_code[lc]; 8374 send_code(s, code+LITERALS+1, ltree); /* send the length code */ 8375 extra = extra_lbits[code]; 8376 if (extra !== 0) { 8377 lc -= base_length[code]; 8378 send_bits(s, lc, extra); /* send the extra length bits */ 8379 } 8380 dist--; /* dist is now the match distance - 1 */ 8381 code = d_code(dist); 8382 //Assert (code < D_CODES, "bad d_code"); 8383 8384 send_code(s, code, dtree); /* send the distance code */ 8385 extra = extra_dbits[code]; 8386 if (extra !== 0) { 8387 dist -= base_dist[code]; 8388 send_bits(s, dist, extra); /* send the extra distance bits */ 8389 } 8390 } /* literal or match pair ? */ 8391 8392 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ 8393 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, 8394 // "pendingBuf overflow"); 8395 8396 } while (lx < s.last_lit); 8397 } 8398 8399 send_code(s, END_BLOCK, ltree); 8400 } 8401 8402 8403 /* =========================================================================== 8404 * Construct one Huffman tree and assigns the code bit strings and lengths. 8405 * Update the total bit length for the current block. 8406 * IN assertion: the field freq is set for all tree elements. 8407 * OUT assertions: the fields len and code are set to the optimal bit length 8408 * and corresponding code. The length opt_len is updated; static_len is 8409 * also updated if stree is not null. The field max_code is set. 8410 */ 8411 function build_tree(s, desc) 8412 // deflate_state *s; 8413 // tree_desc *desc; /* the tree descriptor */ 8414 { 8415 var tree = desc.dyn_tree; 8416 var stree = desc.stat_desc.static_tree; 8417 var has_stree = desc.stat_desc.has_stree; 8418 var elems = desc.stat_desc.elems; 8419 var n, m; /* iterate over heap elements */ 8420 var max_code = -1; /* largest code with non zero frequency */ 8421 var node; /* new node being created */ 8422 8423 /* Construct the initial heap, with least frequent element in 8424 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. 8425 * heap[0] is not used. 8426 */ 8427 s.heap_len = 0; 8428 s.heap_max = HEAP_SIZE; 8429 8430 for (n = 0; n < elems; n++) { 8431 if (tree[n * 2]/*.Freq*/ !== 0) { 8432 s.heap[++s.heap_len] = max_code = n; 8433 s.depth[n] = 0; 8434 8435 } else { 8436 tree[n*2 + 1]/*.Len*/ = 0; 8437 } 8438 } 8439 8440 /* The pkzip format requires that at least one distance code exists, 8441 * and that at least one bit should be sent even if there is only one 8442 * possible code. So to avoid special checks later on we force at least 8443 * two codes of non zero frequency. 8444 */ 8445 while (s.heap_len < 2) { 8446 node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); 8447 tree[node * 2]/*.Freq*/ = 1; 8448 s.depth[node] = 0; 8449 s.opt_len--; 8450 8451 if (has_stree) { 8452 s.static_len -= stree[node*2 + 1]/*.Len*/; 8453 } 8454 /* node is 0 or 1 so it does not have extra bits */ 8455 } 8456 desc.max_code = max_code; 8457 8458 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, 8459 * establish sub-heaps of increasing lengths: 8460 */ 8461 for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } 8462 8463 /* Construct the Huffman tree by repeatedly combining the least two 8464 * frequent nodes. 8465 */ 8466 node = elems; /* next internal node of the tree */ 8467 do { 8468 //pqremove(s, tree, n); /* n = node of least frequency */ 8469 /*** pqremove ***/ 8470 n = s.heap[1/*SMALLEST*/]; 8471 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; 8472 pqdownheap(s, tree, 1/*SMALLEST*/); 8473 /***/ 8474 8475 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ 8476 8477 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ 8478 s.heap[--s.heap_max] = m; 8479 8480 /* Create a new node father of n and m */ 8481 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; 8482 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; 8483 tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; 8484 8485 /* and insert the new node in the heap */ 8486 s.heap[1/*SMALLEST*/] = node++; 8487 pqdownheap(s, tree, 1/*SMALLEST*/); 8488 8489 } while (s.heap_len >= 2); 8490 8491 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; 8492 8493 /* At this point, the fields freq and dad are set. We can now 8494 * generate the bit lengths. 8495 */ 8496 gen_bitlen(s, desc); 8497 8498 /* The field len is now set, we can generate the bit codes */ 8499 gen_codes(tree, max_code, s.bl_count); 8500 } 8501 8502 8503 /* =========================================================================== 8504 * Scan a literal or distance tree to determine the frequencies of the codes 8505 * in the bit length tree. 8506 */ 8507 function scan_tree(s, tree, max_code) 8508 // deflate_state *s; 8509 // ct_data *tree; /* the tree to be scanned */ 8510 // int max_code; /* and its largest code of non zero frequency */ 8511 { 8512 var n; /* iterates over all tree elements */ 8513 var prevlen = -1; /* last emitted length */ 8514 var curlen; /* length of current code */ 8515 8516 var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ 8517 8518 var count = 0; /* repeat count of the current code */ 8519 var max_count = 7; /* max repeat count */ 8520 var min_count = 4; /* min repeat count */ 8521 8522 if (nextlen === 0) { 8523 max_count = 138; 8524 min_count = 3; 8525 } 8526 tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ 8527 8528 for (n = 0; n <= max_code; n++) { 8529 curlen = nextlen; 8530 nextlen = tree[(n+1)*2 + 1]/*.Len*/; 8531 8532 if (++count < max_count && curlen === nextlen) { 8533 continue; 8534 8535 } else if (count < min_count) { 8536 s.bl_tree[curlen * 2]/*.Freq*/ += count; 8537 8538 } else if (curlen !== 0) { 8539 8540 if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } 8541 s.bl_tree[REP_3_6*2]/*.Freq*/++; 8542 8543 } else if (count <= 10) { 8544 s.bl_tree[REPZ_3_10*2]/*.Freq*/++; 8545 8546 } else { 8547 s.bl_tree[REPZ_11_138*2]/*.Freq*/++; 8548 } 8549 8550 count = 0; 8551 prevlen = curlen; 8552 8553 if (nextlen === 0) { 8554 max_count = 138; 8555 min_count = 3; 8556 8557 } else if (curlen === nextlen) { 8558 max_count = 6; 8559 min_count = 3; 8560 8561 } else { 8562 max_count = 7; 8563 min_count = 4; 8564 } 8565 } 8566 } 8567 8568 8569 /* =========================================================================== 8570 * Send a literal or distance tree in compressed form, using the codes in 8571 * bl_tree. 8572 */ 8573 function send_tree(s, tree, max_code) 8574 // deflate_state *s; 8575 // ct_data *tree; /* the tree to be scanned */ 8576 // int max_code; /* and its largest code of non zero frequency */ 8577 { 8578 var n; /* iterates over all tree elements */ 8579 var prevlen = -1; /* last emitted length */ 8580 var curlen; /* length of current code */ 8581 8582 var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ 8583 8584 var count = 0; /* repeat count of the current code */ 8585 var max_count = 7; /* max repeat count */ 8586 var min_count = 4; /* min repeat count */ 8587 8588 /* tree[max_code+1].Len = -1; */ /* guard already set */ 8589 if (nextlen === 0) { 8590 max_count = 138; 8591 min_count = 3; 8592 } 8593 8594 for (n = 0; n <= max_code; n++) { 8595 curlen = nextlen; 8596 nextlen = tree[(n+1)*2 + 1]/*.Len*/; 8597 8598 if (++count < max_count && curlen === nextlen) { 8599 continue; 8600 8601 } else if (count < min_count) { 8602 do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); 8603 8604 } else if (curlen !== 0) { 8605 if (curlen !== prevlen) { 8606 send_code(s, curlen, s.bl_tree); 8607 count--; 8608 } 8609 //Assert(count >= 3 && count <= 6, " 3_6?"); 8610 send_code(s, REP_3_6, s.bl_tree); 8611 send_bits(s, count-3, 2); 8612 8613 } else if (count <= 10) { 8614 send_code(s, REPZ_3_10, s.bl_tree); 8615 send_bits(s, count-3, 3); 8616 8617 } else { 8618 send_code(s, REPZ_11_138, s.bl_tree); 8619 send_bits(s, count-11, 7); 8620 } 8621 8622 count = 0; 8623 prevlen = curlen; 8624 if (nextlen === 0) { 8625 max_count = 138; 8626 min_count = 3; 8627 8628 } else if (curlen === nextlen) { 8629 max_count = 6; 8630 min_count = 3; 8631 8632 } else { 8633 max_count = 7; 8634 min_count = 4; 8635 } 8636 } 8637 } 8638 8639 8640 /* =========================================================================== 8641 * Construct the Huffman tree for the bit lengths and return the index in 8642 * bl_order of the last bit length code to send. 8643 */ 8644 function build_bl_tree(s) { 8645 var max_blindex; /* index of last bit length code of non zero freq */ 8646 8647 /* Determine the bit length frequencies for literal and distance trees */ 8648 scan_tree(s, s.dyn_ltree, s.l_desc.max_code); 8649 scan_tree(s, s.dyn_dtree, s.d_desc.max_code); 8650 8651 /* Build the bit length tree: */ 8652 build_tree(s, s.bl_desc); 8653 /* opt_len now includes the length of the tree representations, except 8654 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. 8655 */ 8656 8657 /* Determine the number of bit length codes to send. The pkzip format 8658 * requires that at least 4 bit length codes be sent. (appnote.txt says 8659 * 3 but the actual value used is 4.) 8660 */ 8661 for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { 8662 if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { 8663 break; 8664 } 8665 } 8666 /* Update opt_len to include the bit length tree and counts */ 8667 s.opt_len += 3*(max_blindex+1) + 5+5+4; 8668 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", 8669 // s->opt_len, s->static_len)); 8670 8671 return max_blindex; 8672 } 8673 8674 8675 /* =========================================================================== 8676 * Send the header for a block using dynamic Huffman trees: the counts, the 8677 * lengths of the bit length codes, the literal tree and the distance tree. 8678 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. 8679 */ 8680 function send_all_trees(s, lcodes, dcodes, blcodes) 8681 // deflate_state *s; 8682 // int lcodes, dcodes, blcodes; /* number of codes for each tree */ 8683 { 8684 var rank; /* index in bl_order */ 8685 8686 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); 8687 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, 8688 // "too many codes"); 8689 //Tracev((stderr, "\nbl counts: ")); 8690 send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ 8691 send_bits(s, dcodes-1, 5); 8692 send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ 8693 for (rank = 0; rank < blcodes; rank++) { 8694 //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); 8695 send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); 8696 } 8697 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); 8698 8699 send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ 8700 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); 8701 8702 send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ 8703 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); 8704 } 8705 8706 8707 /* =========================================================================== 8708 * Check if the data type is TEXT or BINARY, using the following algorithm: 8709 * - TEXT if the two conditions below are satisfied: 8710 * a) There are no non-portable control characters belonging to the 8711 * "black list" (0..6, 14..25, 28..31). 8712 * b) There is at least one printable character belonging to the 8713 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). 8714 * - BINARY otherwise. 8715 * - The following partially-portable control characters form a 8716 * "gray list" that is ignored in this detection algorithm: 8717 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). 8718 * IN assertion: the fields Freq of dyn_ltree are set. 8719 */ 8720 function detect_data_type(s) { 8721 /* black_mask is the bit mask of black-listed bytes 8722 * set bits 0..6, 14..25, and 28..31 8723 * 0xf3ffc07f = binary 11110011111111111100000001111111 8724 */ 8725 var black_mask = 0xf3ffc07f; 8726 var n; 8727 8728 /* Check for non-textual ("black-listed") bytes. */ 8729 for (n = 0; n <= 31; n++, black_mask >>>= 1) { 8730 if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { 8731 return Z_BINARY; 8732 } 8733 } 8734 8735 /* Check for textual ("white-listed") bytes. */ 8736 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || 8737 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { 8738 return Z_TEXT; 8739 } 8740 for (n = 32; n < LITERALS; n++) { 8741 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { 8742 return Z_TEXT; 8743 } 8744 } 8745 8746 /* There are no "black-listed" or "white-listed" bytes: 8747 * this stream either is empty or has tolerated ("gray-listed") bytes only. 8748 */ 8749 return Z_BINARY; 8750 } 8751 8752 8753 var static_init_done = false; 8754 8755 /* =========================================================================== 8756 * Initialize the tree data structures for a new zlib stream. 8757 */ 8758 function _tr_init(s) 8759 { 8760 8761 if (!static_init_done) { 8762 tr_static_init(); 8763 static_init_done = true; 8764 } 8765 8766 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); 8767 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); 8768 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); 8769 8770 s.bi_buf = 0; 8771 s.bi_valid = 0; 8772 8773 /* Initialize the first block of the first file: */ 8774 init_block(s); 8775 } 8776 8777 8778 /* =========================================================================== 8779 * Send a stored block 8780 */ 8781 function _tr_stored_block(s, buf, stored_len, last) 8782 //DeflateState *s; 8783 //charf *buf; /* input block */ 8784 //ulg stored_len; /* length of input block */ 8785 //int last; /* one if this is the last block for a file */ 8786 { 8787 send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ 8788 copy_block(s, buf, stored_len, true); /* with header */ 8789 } 8790 8791 8792 /* =========================================================================== 8793 * Send one empty static block to give enough lookahead for inflate. 8794 * This takes 10 bits, of which 7 may remain in the bit buffer. 8795 */ 8796 function _tr_align(s) { 8797 send_bits(s, STATIC_TREES<<1, 3); 8798 send_code(s, END_BLOCK, static_ltree); 8799 bi_flush(s); 8800 } 8801 8802 8803 /* =========================================================================== 8804 * Determine the best encoding for the current block: dynamic trees, static 8805 * trees or store, and output the encoded block to the zip file. 8806 */ 8807 function _tr_flush_block(s, buf, stored_len, last) 8808 //DeflateState *s; 8809 //charf *buf; /* input block, or NULL if too old */ 8810 //ulg stored_len; /* length of input block */ 8811 //int last; /* one if this is the last block for a file */ 8812 { 8813 var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ 8814 var max_blindex = 0; /* index of last bit length code of non zero freq */ 8815 8816 /* Build the Huffman trees unless a stored block is forced */ 8817 if (s.level > 0) { 8818 8819 /* Check if the file is binary or text */ 8820 if (s.strm.data_type === Z_UNKNOWN) { 8821 s.strm.data_type = detect_data_type(s); 8822 } 8823 8824 /* Construct the literal and distance trees */ 8825 build_tree(s, s.l_desc); 8826 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, 8827 // s->static_len)); 8828 8829 build_tree(s, s.d_desc); 8830 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, 8831 // s->static_len)); 8832 /* At this point, opt_len and static_len are the total bit lengths of 8833 * the compressed block data, excluding the tree representations. 8834 */ 8835 8836 /* Build the bit length tree for the above two trees, and get the index 8837 * in bl_order of the last bit length code to send. 8838 */ 8839 max_blindex = build_bl_tree(s); 8840 8841 /* Determine the best encoding. Compute the block lengths in bytes. */ 8842 opt_lenb = (s.opt_len+3+7) >>> 3; 8843 static_lenb = (s.static_len+3+7) >>> 3; 8844 8845 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", 8846 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, 8847 // s->last_lit)); 8848 8849 if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } 8850 8851 } else { 8852 // Assert(buf != (char*)0, "lost buf"); 8853 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ 8854 } 8855 8856 if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { 8857 /* 4: two words for the lengths */ 8858 8859 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. 8860 * Otherwise we can't have processed more than WSIZE input bytes since 8861 * the last block flush, because compression would have been 8862 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to 8863 * transform a block into a stored block. 8864 */ 8865 _tr_stored_block(s, buf, stored_len, last); 8866 8867 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { 8868 8869 send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); 8870 compress_block(s, static_ltree, static_dtree); 8871 8872 } else { 8873 send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); 8874 send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); 8875 compress_block(s, s.dyn_ltree, s.dyn_dtree); 8876 } 8877 // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); 8878 /* The above check is made mod 2^32, for files larger than 512 MB 8879 * and uLong implemented on 32 bits. 8880 */ 8881 init_block(s); 8882 8883 if (last) { 8884 bi_windup(s); 8885 } 8886 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, 8887 // s->compressed_len-7*last)); 8888 } 8889 8890 /* =========================================================================== 8891 * Save the match info and tally the frequency counts. Return true if 8892 * the current block must be flushed. 8893 */ 8894 function _tr_tally(s, dist, lc) 8895 // deflate_state *s; 8896 // unsigned dist; /* distance of matched string */ 8897 // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ 8898 { 8899 //var out_length, in_length, dcode; 8900 8901 s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; 8902 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; 8903 8904 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; 8905 s.last_lit++; 8906 8907 if (dist === 0) { 8908 /* lc is the unmatched char */ 8909 s.dyn_ltree[lc*2]/*.Freq*/++; 8910 } else { 8911 s.matches++; 8912 /* Here, lc is the match length - MIN_MATCH */ 8913 dist--; /* dist = match distance - 1 */ 8914 //Assert((ush)dist < (ush)MAX_DIST(s) && 8915 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && 8916 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); 8917 8918 s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; 8919 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; 8920 } 8921 8922 // (!) This block is disabled in zlib defailts, 8923 // don't enable it for binary compatibility 8924 8925 //#ifdef TRUNCATE_BLOCK 8926 // /* Try to guess if it is profitable to stop the current block here */ 8927 // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { 8928 // /* Compute an upper bound for the compressed length */ 8929 // out_length = s.last_lit*8; 8930 // in_length = s.strstart - s.block_start; 8931 // 8932 // for (dcode = 0; dcode < D_CODES; dcode++) { 8933 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); 8934 // } 8935 // out_length >>>= 3; 8936 // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", 8937 // // s->last_lit, in_length, out_length, 8938 // // 100L - out_length*100L/in_length)); 8939 // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { 8940 // return true; 8941 // } 8942 // } 8943 //#endif 8944 8945 return (s.last_lit === s.lit_bufsize-1); 8946 /* We avoid equality with lit_bufsize because of wraparound at 64K 8947 * on 16 bit machines and because stored blocks are restricted to 8948 * 64K-1 bytes. 8949 */ 8950 } 8951 8952 exports._tr_init = _tr_init; 8953 exports._tr_stored_block = _tr_stored_block; 8954 exports._tr_flush_block = _tr_flush_block; 8955 exports._tr_tally = _tr_tally; 8956 exports._tr_align = _tr_align; 8957 },{"../utils/common":27}],39:[function(_dereq_,module,exports){ 8958 'use strict'; 8959 8960 8961 function ZStream() { 8962 /* next input byte */ 8963 this.input = null; // JS specific, because we have no pointers 8964 this.next_in = 0; 8965 /* number of bytes available at input */ 8966 this.avail_in = 0; 8967 /* total number of input bytes read so far */ 8968 this.total_in = 0; 8969 /* next output byte should be put there */ 8970 this.output = null; // JS specific, because we have no pointers 8971 this.next_out = 0; 8972 /* remaining free space at output */ 8973 this.avail_out = 0; 8974 /* total number of bytes output so far */ 8975 this.total_out = 0; 8976 /* last error message, NULL if no error */ 8977 this.msg = ''/*Z_NULL*/; 8978 /* not visible by applications */ 8979 this.state = null; 8980 /* best guess about the data type: binary or text */ 8981 this.data_type = 2/*Z_UNKNOWN*/; 8982 /* adler32 value of the uncompressed data */ 8983 this.adler = 0; 8984 } 8985 8986 module.exports = ZStream; 8987 },{}]},{},[9]) 8988 (9) 8989 }); 8990