Pinterest.com Backup Original Files

Download all original images from your Pinterest.com profile. Creates an entry in the Greasemonkey menu, just go to one of your boards, scroll down to the last image and click the option in the menu.

目前为 2016-09-17 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Pinterest.com Backup Original Files
  3. // @description Download all original images from your Pinterest.com profile. Creates an entry in the Greasemonkey menu, just go to one of your boards, scroll down to the last image and click the option in the menu.
  4. // @namespace cuzi
  5. // @oujs:author cuzi
  6. // @version 5
  7. // @include https://*pinterest.com/*
  8. // @grant GM_xmlhttpRequest
  9. // @grant GM_registerMenuCommand
  10. // ==/UserScript==
  11.  
  12. function main() {
  13. window.scrollTo(0, document.body.scrollHeight);
  14. if(confirm("Did you scroll down to the last image on the page?\nOnly images that were already loaded can be downloaded!")) {
  15. downloadOriginals();
  16. } else {
  17. alert("Scroll down to the last image and try again!");
  18. window.scrollTo(0, document.body.scrollHeight);
  19. }
  20. }
  21.  
  22. function downloadOriginals() {
  23. var imgs = document.querySelectorAll(".locationBoardPageContentWrapper .Image.Module.pinUiImage img");
  24. var lst = [];
  25. for(var i = 0; i < imgs.length; i++) {
  26. lst.push([imgs[i].src.replace(/\/\d+x\//,"/originals/"),imgs[i].src]);
  27. }
  28. var total = lst.length;
  29. var zip = new JSZip();
  30. // Create folders
  31. var success = zip.folder("success");
  32. var error = zip.folder("error_thumbnails");
  33.  
  34. (function work() {
  35. document.title = (total-lst.length) + "/" + total + " downloaded";
  36. document.body.innerHTML = "<h1>" + (total-lst.length) + "/" + total + " downloaded</h1>";
  37. if(lst.length == 0) {
  38. document.title = "Generating zip file...";
  39. document.body.innerHTML = "<h1>Generating zip file...</h1>";
  40. }
  41. if(lst.length > 0) {
  42. var urls = lst.pop();
  43. GM_xmlhttpRequest({
  44. method: "GET",
  45. url: urls[0],
  46. responseType : "arraybuffer",
  47. onload: function(response) {
  48. var s = String.fromCharCode.apply(null, new Uint8Array(response.response.slice(0,125)));
  49. if(s.indexOf("<Error>") != -1) {
  50. // Download thumbnail to error folder
  51. if(urls.length == 2) {
  52. lst.push([urls[1]]);
  53. }
  54. } else {
  55. // Save file to zip
  56. var name = urls[0].split("/").pop();
  57. if(urls.length == 2) {
  58. success.file(name, response.response);
  59. } else {
  60. error.file(name, response.response);
  61. }
  62. }
  63. work();
  64. }
  65. });
  66. } else {
  67. // Done. Open ZIP file
  68. var content = zip.generate({type:"blob"});
  69. zip = null;
  70. var h = document.createElement("h1");
  71. h.appendChild(document.createTextNode("Click here to Download"));
  72. h.style = "cursor:pointer; color:blue; background:white; text-decoration:underline";
  73. document.body.appendChild(h);
  74. h.addEventListener("click",function() {
  75. saveAs(content, "images.zip");
  76. });
  77. saveAs(content, "images.zip");
  78. }
  79. })();
  80. }
  81.  
  82. function addButton() {
  83. if(document.querySelector(".downloadoriginal123button")) {
  84. return;
  85. }
  86. if((document.querySelector(".BoardHeader h1.boardTitle") || document.querySelector(".BoardHeader .boardName")) && document.querySelectorAll(".Image.Module.pinUiImage img").length) {
  87. var button = document.createElement("button");
  88. button.type = "button";
  89. button.setAttribute("class","downloadoriginal123button BoardFollowButton Button FollowButton Module boardFollowUnfollowButton btn hasText notNavigatable primary rounded");
  90. button.setAttribute("style","margin-left:10px;");
  91. button.innerHTML = '<span class="buttonText">Download originals</span>';
  92. button.addEventListener("click", main);
  93. if(document.querySelector(".dp-flex-auto")) {
  94. document.querySelector(".dp-flex-auto").appendChild(button);
  95. } else {
  96. document.querySelector(".thumbUserInfo").appendChild(button);
  97. }
  98. }
  99. }
  100.  
  101.  
  102. (function() {
  103. GM_registerMenuCommand("Pinterest.com - backup originals",main);
  104. addButton();
  105. window.setInterval(addButton,1000);
  106. })();
  107.  
  108.  
  109.  
  110.  
  111.  
  112.  
  113. /*!
  114.  
  115. JSZip - A Javascript class for generating and reading zip files
  116. <http://stuartk.com/jszip>
  117.  
  118. (c) 2009-2014 Stuart Knightley <stuart [at] stuartk.com>
  119. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
  120.  
  121. JSZip uses the library pako released under the MIT license :
  122. https://github.com/nodeca/pako/blob/master/LICENSE
  123. */
  124. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JSZip=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  125. 'use strict';
  126. // private property
  127. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  128.  
  129.  
  130. // public method for encoding
  131. exports.encode = function(input, utf8) {
  132. var output = "";
  133. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  134. var i = 0;
  135.  
  136. while (i < input.length) {
  137.  
  138. chr1 = input.charCodeAt(i++);
  139. chr2 = input.charCodeAt(i++);
  140. chr3 = input.charCodeAt(i++);
  141.  
  142. enc1 = chr1 >> 2;
  143. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  144. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  145. enc4 = chr3 & 63;
  146.  
  147. if (isNaN(chr2)) {
  148. enc3 = enc4 = 64;
  149. }
  150. else if (isNaN(chr3)) {
  151. enc4 = 64;
  152. }
  153.  
  154. output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  155.  
  156. }
  157.  
  158. return output;
  159. };
  160.  
  161. // public method for decoding
  162. exports.decode = function(input, utf8) {
  163. var output = "";
  164. var chr1, chr2, chr3;
  165. var enc1, enc2, enc3, enc4;
  166. var i = 0;
  167.  
  168. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  169.  
  170. while (i < input.length) {
  171.  
  172. enc1 = _keyStr.indexOf(input.charAt(i++));
  173. enc2 = _keyStr.indexOf(input.charAt(i++));
  174. enc3 = _keyStr.indexOf(input.charAt(i++));
  175. enc4 = _keyStr.indexOf(input.charAt(i++));
  176.  
  177. chr1 = (enc1 << 2) | (enc2 >> 4);
  178. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  179. chr3 = ((enc3 & 3) << 6) | enc4;
  180.  
  181. output = output + String.fromCharCode(chr1);
  182.  
  183. if (enc3 != 64) {
  184. output = output + String.fromCharCode(chr2);
  185. }
  186. if (enc4 != 64) {
  187. output = output + String.fromCharCode(chr3);
  188. }
  189.  
  190. }
  191.  
  192. return output;
  193.  
  194. };
  195.  
  196. },{}],2:[function(_dereq_,module,exports){
  197. 'use strict';
  198. function CompressedObject() {
  199. this.compressedSize = 0;
  200. this.uncompressedSize = 0;
  201. this.crc32 = 0;
  202. this.compressionMethod = null;
  203. this.compressedContent = null;
  204. }
  205.  
  206. CompressedObject.prototype = {
  207. /**
  208. * Return the decompressed content in an unspecified format.
  209. * The format will depend on the decompressor.
  210. * @return {Object} the decompressed content.
  211. */
  212. getContent: function() {
  213. return null; // see implementation
  214. },
  215. /**
  216. * Return the compressed content in an unspecified format.
  217. * The format will depend on the compressed conten source.
  218. * @return {Object} the compressed content.
  219. */
  220. getCompressedContent: function() {
  221. return null; // see implementation
  222. }
  223. };
  224. module.exports = CompressedObject;
  225.  
  226. },{}],3:[function(_dereq_,module,exports){
  227. 'use strict';
  228. exports.STORE = {
  229. magic: "\x00\x00",
  230. compress: function(content, compressionOptions) {
  231. return content; // no compression
  232. },
  233. uncompress: function(content) {
  234. return content; // no compression
  235. },
  236. compressInputType: null,
  237. uncompressInputType: null
  238. };
  239. exports.DEFLATE = _dereq_('./flate');
  240.  
  241. },{"./flate":8}],4:[function(_dereq_,module,exports){
  242. 'use strict';
  243.  
  244. var utils = _dereq_('./utils');
  245.  
  246. var table = [
  247. 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
  248. 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
  249. 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
  250. 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
  251. 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
  252. 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
  253. 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
  254. 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
  255. 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
  256. 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
  257. 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
  258. 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
  259. 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
  260. 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
  261. 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
  262. 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
  263. 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
  264. 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
  265. 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
  266. 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
  267. 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
  268. 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
  269. 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
  270. 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
  271. 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
  272. 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
  273. 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
  274. 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
  275. 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
  276. 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
  277. 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
  278. 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
  279. 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
  280. 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
  281. 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
  282. 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
  283. 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
  284. 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
  285. 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
  286. 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
  287. 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
  288. 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
  289. 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
  290. 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
  291. 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
  292. 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
  293. 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
  294. 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
  295. 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
  296. 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
  297. 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
  298. 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
  299. 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
  300. 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
  301. 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
  302. 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
  303. 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
  304. 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
  305. 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
  306. 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
  307. 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
  308. 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
  309. 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
  310. 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
  311. ];
  312.  
  313. /**
  314. *
  315. * Javascript crc32
  316. * http://www.webtoolkit.info/
  317. *
  318. */
  319. module.exports = function crc32(input, crc) {
  320. if (typeof input === "undefined" || !input.length) {
  321. return 0;
  322. }
  323.  
  324. var isArray = utils.getTypeOf(input) !== "string";
  325.  
  326. if (typeof(crc) == "undefined") {
  327. crc = 0;
  328. }
  329. var x = 0;
  330. var y = 0;
  331. var b = 0;
  332.  
  333. crc = crc ^ (-1);
  334. for (var i = 0, iTop = input.length; i < iTop; i++) {
  335. b = isArray ? input[i] : input.charCodeAt(i);
  336. y = (crc ^ b) & 0xFF;
  337. x = table[y];
  338. crc = (crc >>> 8) ^ x;
  339. }
  340.  
  341. return crc ^ (-1);
  342. };
  343. // vim: set shiftwidth=4 softtabstop=4:
  344.  
  345. },{"./utils":21}],5:[function(_dereq_,module,exports){
  346. 'use strict';
  347. var utils = _dereq_('./utils');
  348.  
  349. function DataReader(data) {
  350. this.data = null; // type : see implementation
  351. this.length = 0;
  352. this.index = 0;
  353. }
  354. DataReader.prototype = {
  355. /**
  356. * Check that the offset will not go too far.
  357. * @param {string} offset the additional offset to check.
  358. * @throws {Error} an Error if the offset is out of bounds.
  359. */
  360. checkOffset: function(offset) {
  361. this.checkIndex(this.index + offset);
  362. },
  363. /**
  364. * Check that the specifed index will not be too far.
  365. * @param {string} newIndex the index to check.
  366. * @throws {Error} an Error if the index is out of bounds.
  367. */
  368. checkIndex: function(newIndex) {
  369. if (this.length < newIndex || newIndex < 0) {
  370. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  371. }
  372. },
  373. /**
  374. * Change the index.
  375. * @param {number} newIndex The new index.
  376. * @throws {Error} if the new index is out of the data.
  377. */
  378. setIndex: function(newIndex) {
  379. this.checkIndex(newIndex);
  380. this.index = newIndex;
  381. },
  382. /**
  383. * Skip the next n bytes.
  384. * @param {number} n the number of bytes to skip.
  385. * @throws {Error} if the new index is out of the data.
  386. */
  387. skip: function(n) {
  388. this.setIndex(this.index + n);
  389. },
  390. /**
  391. * Get the byte at the specified index.
  392. * @param {number} i the index to use.
  393. * @return {number} a byte.
  394. */
  395. byteAt: function(i) {
  396. // see implementations
  397. },
  398. /**
  399. * Get the next number with a given byte size.
  400. * @param {number} size the number of bytes to read.
  401. * @return {number} the corresponding number.
  402. */
  403. readInt: function(size) {
  404. var result = 0,
  405. i;
  406. this.checkOffset(size);
  407. for (i = this.index + size - 1; i >= this.index; i--) {
  408. result = (result << 8) + this.byteAt(i);
  409. }
  410. this.index += size;
  411. return result;
  412. },
  413. /**
  414. * Get the next string with a given byte size.
  415. * @param {number} size the number of bytes to read.
  416. * @return {string} the corresponding string.
  417. */
  418. readString: function(size) {
  419. return utils.transformTo("string", this.readData(size));
  420. },
  421. /**
  422. * Get raw data without conversion, <size> bytes.
  423. * @param {number} size the number of bytes to read.
  424. * @return {Object} the raw data, implementation specific.
  425. */
  426. readData: function(size) {
  427. // see implementations
  428. },
  429. /**
  430. * Find the last occurence of a zip signature (4 bytes).
  431. * @param {string} sig the signature to find.
  432. * @return {number} the index of the last occurence, -1 if not found.
  433. */
  434. lastIndexOfSignature: function(sig) {
  435. // see implementations
  436. },
  437. /**
  438. * Get the next date.
  439. * @return {Date} the date.
  440. */
  441. readDate: function() {
  442. var dostime = this.readInt(4);
  443. return new Date(
  444. ((dostime >> 25) & 0x7f) + 1980, // year
  445. ((dostime >> 21) & 0x0f) - 1, // month
  446. (dostime >> 16) & 0x1f, // day
  447. (dostime >> 11) & 0x1f, // hour
  448. (dostime >> 5) & 0x3f, // minute
  449. (dostime & 0x1f) << 1); // second
  450. }
  451. };
  452. module.exports = DataReader;
  453.  
  454. },{"./utils":21}],6:[function(_dereq_,module,exports){
  455. 'use strict';
  456. exports.base64 = false;
  457. exports.binary = false;
  458. exports.dir = false;
  459. exports.createFolders = false;
  460. exports.date = null;
  461. exports.compression = null;
  462. exports.compressionOptions = null;
  463. exports.comment = null;
  464. exports.unixPermissions = null;
  465. exports.dosPermissions = null;
  466.  
  467. },{}],7:[function(_dereq_,module,exports){
  468. 'use strict';
  469. var utils = _dereq_('./utils');
  470.  
  471. /**
  472. * @deprecated
  473. * This function will be removed in a future version without replacement.
  474. */
  475. exports.string2binary = function(str) {
  476. return utils.string2binary(str);
  477. };
  478.  
  479. /**
  480. * @deprecated
  481. * This function will be removed in a future version without replacement.
  482. */
  483. exports.string2Uint8Array = function(str) {
  484. return utils.transformTo("uint8array", str);
  485. };
  486.  
  487. /**
  488. * @deprecated
  489. * This function will be removed in a future version without replacement.
  490. */
  491. exports.uint8Array2String = function(array) {
  492. return utils.transformTo("string", array);
  493. };
  494.  
  495. /**
  496. * @deprecated
  497. * This function will be removed in a future version without replacement.
  498. */
  499. exports.string2Blob = function(str) {
  500. var buffer = utils.transformTo("arraybuffer", str);
  501. return utils.arrayBuffer2Blob(buffer);
  502. };
  503.  
  504. /**
  505. * @deprecated
  506. * This function will be removed in a future version without replacement.
  507. */
  508. exports.arrayBuffer2Blob = function(buffer) {
  509. return utils.arrayBuffer2Blob(buffer);
  510. };
  511.  
  512. /**
  513. * @deprecated
  514. * This function will be removed in a future version without replacement.
  515. */
  516. exports.transformTo = function(outputType, input) {
  517. return utils.transformTo(outputType, input);
  518. };
  519.  
  520. /**
  521. * @deprecated
  522. * This function will be removed in a future version without replacement.
  523. */
  524. exports.getTypeOf = function(input) {
  525. return utils.getTypeOf(input);
  526. };
  527.  
  528. /**
  529. * @deprecated
  530. * This function will be removed in a future version without replacement.
  531. */
  532. exports.checkSupport = function(type) {
  533. return utils.checkSupport(type);
  534. };
  535.  
  536. /**
  537. * @deprecated
  538. * This value will be removed in a future version without replacement.
  539. */
  540. exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
  541.  
  542. /**
  543. * @deprecated
  544. * This value will be removed in a future version without replacement.
  545. */
  546. exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
  547.  
  548.  
  549. /**
  550. * @deprecated
  551. * This function will be removed in a future version without replacement.
  552. */
  553. exports.pretty = function(str) {
  554. return utils.pretty(str);
  555. };
  556.  
  557. /**
  558. * @deprecated
  559. * This function will be removed in a future version without replacement.
  560. */
  561. exports.findCompression = function(compressionMethod) {
  562. return utils.findCompression(compressionMethod);
  563. };
  564.  
  565. /**
  566. * @deprecated
  567. * This function will be removed in a future version without replacement.
  568. */
  569. exports.isRegExp = function (object) {
  570. return utils.isRegExp(object);
  571. };
  572.  
  573.  
  574. },{"./utils":21}],8:[function(_dereq_,module,exports){
  575. 'use strict';
  576. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  577.  
  578. var pako = _dereq_("pako");
  579. exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  580. exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  581.  
  582. exports.magic = "\x08\x00";
  583. exports.compress = function(input, compressionOptions) {
  584. return pako.deflateRaw(input, {
  585. level : compressionOptions.level || -1 // default compression
  586. });
  587. };
  588. exports.uncompress = function(input) {
  589. return pako.inflateRaw(input);
  590. };
  591.  
  592. },{"pako":24}],9:[function(_dereq_,module,exports){
  593. 'use strict';
  594.  
  595. var base64 = _dereq_('./base64');
  596.  
  597. /**
  598. Usage:
  599. zip = new JSZip();
  600. zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
  601. zip.folder("images").file("smile.gif", base64Data, {base64: true});
  602. zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
  603. zip.remove("tempfile");
  604.  
  605. base64zip = zip.generate();
  606.  
  607. **/
  608.  
  609. /**
  610. * Representation a of zip file in js
  611. * @constructor
  612. * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
  613. * @param {Object=} options the options for creating this objects (optional).
  614. */
  615. function JSZip(data, options) {
  616. // if this constructor is used without `new`, it adds `new` before itself:
  617. if(!(this instanceof JSZip)) return new JSZip(data, options);
  618.  
  619. // object containing the files :
  620. // {
  621. // "folder/" : {...},
  622. // "folder/data.txt" : {...}
  623. // }
  624. this.files = {};
  625.  
  626. this.comment = null;
  627.  
  628. // Where we are in the hierarchy
  629. this.root = "";
  630. if (data) {
  631. this.load(data, options);
  632. }
  633. this.clone = function() {
  634. var newObj = new JSZip();
  635. for (var i in this) {
  636. if (typeof this[i] !== "function") {
  637. newObj[i] = this[i];
  638. }
  639. }
  640. return newObj;
  641. };
  642. }
  643. JSZip.prototype = _dereq_('./object');
  644. JSZip.prototype.load = _dereq_('./load');
  645. JSZip.support = _dereq_('./support');
  646. JSZip.defaults = _dereq_('./defaults');
  647.  
  648. /**
  649. * @deprecated
  650. * This namespace will be removed in a future version without replacement.
  651. */
  652. JSZip.utils = _dereq_('./deprecatedPublicUtils');
  653.  
  654. JSZip.base64 = {
  655. /**
  656. * @deprecated
  657. * This method will be removed in a future version without replacement.
  658. */
  659. encode : function(input) {
  660. return base64.encode(input);
  661. },
  662. /**
  663. * @deprecated
  664. * This method will be removed in a future version without replacement.
  665. */
  666. decode : function(input) {
  667. return base64.decode(input);
  668. }
  669. };
  670. JSZip.compressions = _dereq_('./compressions');
  671. module.exports = JSZip;
  672.  
  673. },{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(_dereq_,module,exports){
  674. 'use strict';
  675. var base64 = _dereq_('./base64');
  676. var ZipEntries = _dereq_('./zipEntries');
  677. module.exports = function(data, options) {
  678. var files, zipEntries, i, input;
  679. options = options || {};
  680. if (options.base64) {
  681. data = base64.decode(data);
  682. }
  683.  
  684. zipEntries = new ZipEntries(data, options);
  685. files = zipEntries.files;
  686. for (i = 0; i < files.length; i++) {
  687. input = files[i];
  688. this.file(input.fileName, input.decompressed, {
  689. binary: true,
  690. optimizedBinaryString: true,
  691. date: input.date,
  692. dir: input.dir,
  693. comment : input.fileComment.length ? input.fileComment : null,
  694. unixPermissions : input.unixPermissions,
  695. dosPermissions : input.dosPermissions,
  696. createFolders: options.createFolders
  697. });
  698. }
  699. if (zipEntries.zipComment.length) {
  700. this.comment = zipEntries.zipComment;
  701. }
  702.  
  703. return this;
  704. };
  705.  
  706. },{"./base64":1,"./zipEntries":22}],11:[function(_dereq_,module,exports){
  707. (function (Buffer){
  708. 'use strict';
  709. module.exports = function(data, encoding){
  710. return new Buffer(data, encoding);
  711. };
  712. module.exports.test = function(b){
  713. return Buffer.isBuffer(b);
  714. };
  715.  
  716. }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
  717. },{}],12:[function(_dereq_,module,exports){
  718. 'use strict';
  719. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  720.  
  721. function NodeBufferReader(data) {
  722. this.data = data;
  723. this.length = this.data.length;
  724. this.index = 0;
  725. }
  726. NodeBufferReader.prototype = new Uint8ArrayReader();
  727.  
  728. /**
  729. * @see DataReader.readData
  730. */
  731. NodeBufferReader.prototype.readData = function(size) {
  732. this.checkOffset(size);
  733. var result = this.data.slice(this.index, this.index + size);
  734. this.index += size;
  735. return result;
  736. };
  737. module.exports = NodeBufferReader;
  738.  
  739. },{"./uint8ArrayReader":18}],13:[function(_dereq_,module,exports){
  740. 'use strict';
  741. var support = _dereq_('./support');
  742. var utils = _dereq_('./utils');
  743. var crc32 = _dereq_('./crc32');
  744. var signature = _dereq_('./signature');
  745. var defaults = _dereq_('./defaults');
  746. var base64 = _dereq_('./base64');
  747. var compressions = _dereq_('./compressions');
  748. var CompressedObject = _dereq_('./compressedObject');
  749. var nodeBuffer = _dereq_('./nodeBuffer');
  750. var utf8 = _dereq_('./utf8');
  751. var StringWriter = _dereq_('./stringWriter');
  752. var Uint8ArrayWriter = _dereq_('./uint8ArrayWriter');
  753.  
  754. /**
  755. * Returns the raw data of a ZipObject, decompress the content if necessary.
  756. * @param {ZipObject} file the file to use.
  757. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  758. */
  759. var getRawData = function(file) {
  760. if (file._data instanceof CompressedObject) {
  761. file._data = file._data.getContent();
  762. file.options.binary = true;
  763. file.options.base64 = false;
  764.  
  765. if (utils.getTypeOf(file._data) === "uint8array") {
  766. var copy = file._data;
  767. // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
  768. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
  769. file._data = new Uint8Array(copy.length);
  770. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  771. if (copy.length !== 0) {
  772. file._data.set(copy, 0);
  773. }
  774. }
  775. }
  776. return file._data;
  777. };
  778.  
  779. /**
  780. * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
  781. * @param {ZipObject} file the file to use.
  782. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  783. */
  784. var getBinaryData = function(file) {
  785. var result = getRawData(file),
  786. type = utils.getTypeOf(result);
  787. if (type === "string") {
  788. if (!file.options.binary) {
  789. // unicode text !
  790. // unicode string => binary string is a painful process, check if we can avoid it.
  791. if (support.nodebuffer) {
  792. return nodeBuffer(result, "utf-8");
  793. }
  794. }
  795. return file.asBinary();
  796. }
  797. return result;
  798. };
  799.  
  800. /**
  801. * Transform this._data into a string.
  802. * @param {function} filter a function String -> String, applied if not null on the result.
  803. * @return {String} the string representing this._data.
  804. */
  805. var dataToString = function(asUTF8) {
  806. var result = getRawData(this);
  807. if (result === null || typeof result === "undefined") {
  808. return "";
  809. }
  810. // if the data is a base64 string, we decode it before checking the encoding !
  811. if (this.options.base64) {
  812. result = base64.decode(result);
  813. }
  814. if (asUTF8 && this.options.binary) {
  815. // JSZip.prototype.utf8decode supports arrays as input
  816. // skip to array => string step, utf8decode will do it.
  817. result = out.utf8decode(result);
  818. }
  819. else {
  820. // no utf8 transformation, do the array => string step.
  821. result = utils.transformTo("string", result);
  822. }
  823.  
  824. if (!asUTF8 && !this.options.binary) {
  825. result = utils.transformTo("string", out.utf8encode(result));
  826. }
  827. return result;
  828. };
  829. /**
  830. * A simple object representing a file in the zip file.
  831. * @constructor
  832. * @param {string} name the name of the file
  833. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  834. * @param {Object} options the options of the file
  835. */
  836. var ZipObject = function(name, data, options) {
  837. this.name = name;
  838. this.dir = options.dir;
  839. this.date = options.date;
  840. this.comment = options.comment;
  841. this.unixPermissions = options.unixPermissions;
  842. this.dosPermissions = options.dosPermissions;
  843.  
  844. this._data = data;
  845. this.options = options;
  846.  
  847. /*
  848. * This object contains initial values for dir and date.
  849. * With them, we can check if the user changed the deprecated metadata in
  850. * `ZipObject#options` or not.
  851. */
  852. this._initialMetadata = {
  853. dir : options.dir,
  854. date : options.date
  855. };
  856. };
  857.  
  858. ZipObject.prototype = {
  859. /**
  860. * Return the content as UTF8 string.
  861. * @return {string} the UTF8 string.
  862. */
  863. asText: function() {
  864. return dataToString.call(this, true);
  865. },
  866. /**
  867. * Returns the binary content.
  868. * @return {string} the content as binary.
  869. */
  870. asBinary: function() {
  871. return dataToString.call(this, false);
  872. },
  873. /**
  874. * Returns the content as a nodejs Buffer.
  875. * @return {Buffer} the content as a Buffer.
  876. */
  877. asNodeBuffer: function() {
  878. var result = getBinaryData(this);
  879. return utils.transformTo("nodebuffer", result);
  880. },
  881. /**
  882. * Returns the content as an Uint8Array.
  883. * @return {Uint8Array} the content as an Uint8Array.
  884. */
  885. asUint8Array: function() {
  886. var result = getBinaryData(this);
  887. return utils.transformTo("uint8array", result);
  888. },
  889. /**
  890. * Returns the content as an ArrayBuffer.
  891. * @return {ArrayBuffer} the content as an ArrayBufer.
  892. */
  893. asArrayBuffer: function() {
  894. return this.asUint8Array().buffer;
  895. }
  896. };
  897.  
  898. /**
  899. * Transform an integer into a string in hexadecimal.
  900. * @private
  901. * @param {number} dec the number to convert.
  902. * @param {number} bytes the number of bytes to generate.
  903. * @returns {string} the result.
  904. */
  905. var decToHex = function(dec, bytes) {
  906. var hex = "",
  907. i;
  908. for (i = 0; i < bytes; i++) {
  909. hex += String.fromCharCode(dec & 0xff);
  910. dec = dec >>> 8;
  911. }
  912. return hex;
  913. };
  914.  
  915. /**
  916. * Merge the objects passed as parameters into a new one.
  917. * @private
  918. * @param {...Object} var_args All objects to merge.
  919. * @return {Object} a new object with the data of the others.
  920. */
  921. var extend = function() {
  922. var result = {}, i, attr;
  923. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  924. for (attr in arguments[i]) {
  925. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  926. result[attr] = arguments[i][attr];
  927. }
  928. }
  929. }
  930. return result;
  931. };
  932.  
  933. /**
  934. * Transforms the (incomplete) options from the user into the complete
  935. * set of options to create a file.
  936. * @private
  937. * @param {Object} o the options from the user.
  938. * @return {Object} the complete set of options.
  939. */
  940. var prepareFileAttrs = function(o) {
  941. o = o || {};
  942. if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
  943. o.binary = true;
  944. }
  945. o = extend(o, defaults);
  946. o.date = o.date || new Date();
  947. if (o.compression !== null) o.compression = o.compression.toUpperCase();
  948.  
  949. return o;
  950. };
  951.  
  952. /**
  953. * Add a file in the current folder.
  954. * @private
  955. * @param {string} name the name of the file
  956. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  957. * @param {Object} o the options of the file
  958. * @return {Object} the new file.
  959. */
  960. var fileAdd = function(name, data, o) {
  961. // be sure sub folders exist
  962. var dataType = utils.getTypeOf(data),
  963. parent;
  964.  
  965. o = prepareFileAttrs(o);
  966.  
  967. if (typeof o.unixPermissions === "string") {
  968. o.unixPermissions = parseInt(o.unixPermissions, 8);
  969. }
  970.  
  971. // UNX_IFDIR 0040000 see zipinfo.c
  972. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  973. o.dir = true;
  974. }
  975. // Bit 4 Directory
  976. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  977. o.dir = true;
  978. }
  979.  
  980. if (o.dir) {
  981. name = forceTrailingSlash(name);
  982. }
  983.  
  984. if (o.createFolders && (parent = parentFolder(name))) {
  985. folderAdd.call(this, parent, true);
  986. }
  987.  
  988. if (o.dir || data === null || typeof data === "undefined") {
  989. o.base64 = false;
  990. o.binary = false;
  991. data = null;
  992. dataType = null;
  993. }
  994. else if (dataType === "string") {
  995. if (o.binary && !o.base64) {
  996. // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
  997. if (o.optimizedBinaryString !== true) {
  998. // this is a string, not in a base64 format.
  999. // Be sure that this is a correct "binary string"
  1000. data = utils.string2binary(data);
  1001. }
  1002. }
  1003. }
  1004. else { // arraybuffer, uint8array, ...
  1005. o.base64 = false;
  1006. o.binary = true;
  1007.  
  1008. if (!dataType && !(data instanceof CompressedObject)) {
  1009. throw new Error("The data of '" + name + "' is in an unsupported format !");
  1010. }
  1011.  
  1012. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  1013. if (dataType === "arraybuffer") {
  1014. data = utils.transformTo("uint8array", data);
  1015. }
  1016. }
  1017.  
  1018. var object = new ZipObject(name, data, o);
  1019. this.files[name] = object;
  1020. return object;
  1021. };
  1022.  
  1023. /**
  1024. * Find the parent folder of the path.
  1025. * @private
  1026. * @param {string} path the path to use
  1027. * @return {string} the parent folder, or ""
  1028. */
  1029. var parentFolder = function (path) {
  1030. if (path.slice(-1) == '/') {
  1031. path = path.substring(0, path.length - 1);
  1032. }
  1033. var lastSlash = path.lastIndexOf('/');
  1034. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  1035. };
  1036.  
  1037.  
  1038. /**
  1039. * Returns the path with a slash at the end.
  1040. * @private
  1041. * @param {String} path the path to check.
  1042. * @return {String} the path with a trailing slash.
  1043. */
  1044. var forceTrailingSlash = function(path) {
  1045. // Check the name ends with a /
  1046. if (path.slice(-1) != "/") {
  1047. path += "/"; // IE doesn't like substr(-1)
  1048. }
  1049. return path;
  1050. };
  1051. /**
  1052. * Add a (sub) folder in the current folder.
  1053. * @private
  1054. * @param {string} name the folder's name
  1055. * @param {boolean=} [createFolders] If true, automatically create sub
  1056. * folders. Defaults to false.
  1057. * @return {Object} the new folder.
  1058. */
  1059. var folderAdd = function(name, createFolders) {
  1060. createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
  1061.  
  1062. name = forceTrailingSlash(name);
  1063.  
  1064. // Does this folder already exist?
  1065. if (!this.files[name]) {
  1066. fileAdd.call(this, name, null, {
  1067. dir: true,
  1068. createFolders: createFolders
  1069. });
  1070. }
  1071. return this.files[name];
  1072. };
  1073.  
  1074. /**
  1075. * Generate a JSZip.CompressedObject for a given zipOject.
  1076. * @param {ZipObject} file the object to read.
  1077. * @param {JSZip.compression} compression the compression to use.
  1078. * @param {Object} compressionOptions the options to use when compressing.
  1079. * @return {JSZip.CompressedObject} the compressed result.
  1080. */
  1081. var generateCompressedObjectFrom = function(file, compression, compressionOptions) {
  1082. var result = new CompressedObject(),
  1083. content;
  1084.  
  1085. // the data has not been decompressed, we might reuse things !
  1086. if (file._data instanceof CompressedObject) {
  1087. result.uncompressedSize = file._data.uncompressedSize;
  1088. result.crc32 = file._data.crc32;
  1089.  
  1090. if (result.uncompressedSize === 0 || file.dir) {
  1091. compression = compressions['STORE'];
  1092. result.compressedContent = "";
  1093. result.crc32 = 0;
  1094. }
  1095. else if (file._data.compressionMethod === compression.magic) {
  1096. result.compressedContent = file._data.getCompressedContent();
  1097. }
  1098. else {
  1099. content = file._data.getContent();
  1100. // need to decompress / recompress
  1101. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  1102. }
  1103. }
  1104. else {
  1105. // have uncompressed data
  1106. content = getBinaryData(file);
  1107. if (!content || content.length === 0 || file.dir) {
  1108. compression = compressions['STORE'];
  1109. content = "";
  1110. }
  1111. result.uncompressedSize = content.length;
  1112. result.crc32 = crc32(content);
  1113. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  1114. }
  1115.  
  1116. result.compressedSize = result.compressedContent.length;
  1117. result.compressionMethod = compression.magic;
  1118.  
  1119. return result;
  1120. };
  1121.  
  1122.  
  1123.  
  1124.  
  1125. /**
  1126. * Generate the UNIX part of the external file attributes.
  1127. * @param {Object} unixPermissions the unix permissions or null.
  1128. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  1129. * @return {Number} a 32 bit integer.
  1130. *
  1131. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  1132. *
  1133. * TTTTsstrwxrwxrwx0000000000ADVSHR
  1134. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  1135. * ^^^_________________________ setuid, setgid, sticky
  1136. * ^^^^^^^^^________________ permissions
  1137. * ^^^^^^^^^^______ not used ?
  1138. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  1139. */
  1140. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  1141.  
  1142. var result = unixPermissions;
  1143. if (!unixPermissions) {
  1144. // I can't use octal values in strict mode, hence the hexa.
  1145. // 040775 => 0x41fd
  1146. // 0100664 => 0x81b4
  1147. result = isDir ? 0x41fd : 0x81b4;
  1148. }
  1149.  
  1150. return (result & 0xFFFF) << 16;
  1151. };
  1152.  
  1153. /**
  1154. * Generate the DOS part of the external file attributes.
  1155. * @param {Object} dosPermissions the dos permissions or null.
  1156. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  1157. * @return {Number} a 32 bit integer.
  1158. *
  1159. * Bit 0 Read-Only
  1160. * Bit 1 Hidden
  1161. * Bit 2 System
  1162. * Bit 3 Volume Label
  1163. * Bit 4 Directory
  1164. * Bit 5 Archive
  1165. */
  1166. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  1167.  
  1168. // the dir flag is already set for compatibility
  1169.  
  1170. return (dosPermissions || 0) & 0x3F;
  1171. };
  1172.  
  1173. /**
  1174. * Generate the various parts used in the construction of the final zip file.
  1175. * @param {string} name the file name.
  1176. * @param {ZipObject} file the file content.
  1177. * @param {JSZip.CompressedObject} compressedObject the compressed object.
  1178. * @param {number} offset the current offset from the start of the zip file.
  1179. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  1180. * @return {object} the zip parts.
  1181. */
  1182. var generateZipParts = function(name, file, compressedObject, offset, platform) {
  1183. var data = compressedObject.compressedContent,
  1184. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  1185. comment = file.comment || "",
  1186. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  1187. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  1188. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  1189. o = file.options,
  1190. dosTime,
  1191. dosDate,
  1192. extraFields = "",
  1193. unicodePathExtraField = "",
  1194. unicodeCommentExtraField = "",
  1195. dir, date;
  1196.  
  1197.  
  1198. // handle the deprecated options.dir
  1199. if (file._initialMetadata.dir !== file.dir) {
  1200. dir = file.dir;
  1201. } else {
  1202. dir = o.dir;
  1203. }
  1204.  
  1205. // handle the deprecated options.date
  1206. if(file._initialMetadata.date !== file.date) {
  1207. date = file.date;
  1208. } else {
  1209. date = o.date;
  1210. }
  1211.  
  1212. var extFileAttr = 0;
  1213. var versionMadeBy = 0;
  1214. if (dir) {
  1215. // dos or unix, we set the dos dir flag
  1216. extFileAttr |= 0x00010;
  1217. }
  1218. if(platform === "UNIX") {
  1219. versionMadeBy = 0x031E; // UNIX, version 3.0
  1220. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  1221. } else { // DOS or other, fallback to DOS
  1222. versionMadeBy = 0x0014; // DOS, version 2.0
  1223. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  1224. }
  1225.  
  1226. // date
  1227. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  1228. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  1229. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  1230.  
  1231. dosTime = date.getHours();
  1232. dosTime = dosTime << 6;
  1233. dosTime = dosTime | date.getMinutes();
  1234. dosTime = dosTime << 5;
  1235. dosTime = dosTime | date.getSeconds() / 2;
  1236.  
  1237. dosDate = date.getFullYear() - 1980;
  1238. dosDate = dosDate << 4;
  1239. dosDate = dosDate | (date.getMonth() + 1);
  1240. dosDate = dosDate << 5;
  1241. dosDate = dosDate | date.getDate();
  1242.  
  1243. if (useUTF8ForFileName) {
  1244. // set the unicode path extra field. unzip needs at least one extra
  1245. // field to correctly handle unicode path, so using the path is as good
  1246. // as any other information. This could improve the situation with
  1247. // other archive managers too.
  1248. // This field is usually used without the utf8 flag, with a non
  1249. // unicode path in the header (winrar, winzip). This helps (a bit)
  1250. // with the messy Windows' default compressed folders feature but
  1251. // breaks on p7zip which doesn't seek the unicode path extra field.
  1252. // So for now, UTF-8 everywhere !
  1253. unicodePathExtraField =
  1254. // Version
  1255. decToHex(1, 1) +
  1256. // NameCRC32
  1257. decToHex(crc32(utfEncodedFileName), 4) +
  1258. // UnicodeName
  1259. utfEncodedFileName;
  1260.  
  1261. extraFields +=
  1262. // Info-ZIP Unicode Path Extra Field
  1263. "\x75\x70" +
  1264. // size
  1265. decToHex(unicodePathExtraField.length, 2) +
  1266. // content
  1267. unicodePathExtraField;
  1268. }
  1269.  
  1270. if(useUTF8ForComment) {
  1271.  
  1272. unicodeCommentExtraField =
  1273. // Version
  1274. decToHex(1, 1) +
  1275. // CommentCRC32
  1276. decToHex(this.crc32(utfEncodedComment), 4) +
  1277. // UnicodeName
  1278. utfEncodedComment;
  1279.  
  1280. extraFields +=
  1281. // Info-ZIP Unicode Path Extra Field
  1282. "\x75\x63" +
  1283. // size
  1284. decToHex(unicodeCommentExtraField.length, 2) +
  1285. // content
  1286. unicodeCommentExtraField;
  1287. }
  1288.  
  1289. var header = "";
  1290.  
  1291. // version needed to extract
  1292. header += "\x0A\x00";
  1293. // general purpose bit flag
  1294. // set bit 11 if utf8
  1295. header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
  1296. // compression method
  1297. header += compressedObject.compressionMethod;
  1298. // last mod file time
  1299. header += decToHex(dosTime, 2);
  1300. // last mod file date
  1301. header += decToHex(dosDate, 2);
  1302. // crc-32
  1303. header += decToHex(compressedObject.crc32, 4);
  1304. // compressed size
  1305. header += decToHex(compressedObject.compressedSize, 4);
  1306. // uncompressed size
  1307. header += decToHex(compressedObject.uncompressedSize, 4);
  1308. // file name length
  1309. header += decToHex(utfEncodedFileName.length, 2);
  1310. // extra field length
  1311. header += decToHex(extraFields.length, 2);
  1312.  
  1313.  
  1314. var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields;
  1315.  
  1316. var dirRecord = signature.CENTRAL_FILE_HEADER +
  1317. // version made by (00: DOS)
  1318. decToHex(versionMadeBy, 2) +
  1319. // file header (common to file and central directory)
  1320. header +
  1321. // file comment length
  1322. decToHex(utfEncodedComment.length, 2) +
  1323. // disk number start
  1324. "\x00\x00" +
  1325. // internal file attributes TODO
  1326. "\x00\x00" +
  1327. // external file attributes
  1328. decToHex(extFileAttr, 4) +
  1329. // relative offset of local header
  1330. decToHex(offset, 4) +
  1331. // file name
  1332. utfEncodedFileName +
  1333. // extra field
  1334. extraFields +
  1335. // file comment
  1336. utfEncodedComment;
  1337.  
  1338. return {
  1339. fileRecord: fileRecord,
  1340. dirRecord: dirRecord,
  1341. compressedObject: compressedObject
  1342. };
  1343. };
  1344.  
  1345.  
  1346. // return the actual prototype of JSZip
  1347. var out = {
  1348. /**
  1349. * Read an existing zip and merge the data in the current JSZip object.
  1350. * The implementation is in jszip-load.js, don't forget to include it.
  1351. * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
  1352. * @param {Object} options Options for loading the stream.
  1353. * options.base64 : is the stream in base64 ? default : false
  1354. * @return {JSZip} the current JSZip object
  1355. */
  1356. load: function(stream, options) {
  1357. throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
  1358. },
  1359.  
  1360. /**
  1361. * Filter nested files/folders with the specified function.
  1362. * @param {Function} search the predicate to use :
  1363. * function (relativePath, file) {...}
  1364. * It takes 2 arguments : the relative path and the file.
  1365. * @return {Array} An array of matching elements.
  1366. */
  1367. filter: function(search) {
  1368. var result = [],
  1369. filename, relativePath, file, fileClone;
  1370. for (filename in this.files) {
  1371. if (!this.files.hasOwnProperty(filename)) {
  1372. continue;
  1373. }
  1374. file = this.files[filename];
  1375. // return a new object, don't let the user mess with our internal objects :)
  1376. fileClone = new ZipObject(file.name, file._data, extend(file.options));
  1377. relativePath = filename.slice(this.root.length, filename.length);
  1378. if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
  1379. search(relativePath, fileClone)) { // and the file matches the function
  1380. result.push(fileClone);
  1381. }
  1382. }
  1383. return result;
  1384. },
  1385.  
  1386. /**
  1387. * Add a file to the zip file, or search a file.
  1388. * @param {string|RegExp} name The name of the file to add (if data is defined),
  1389. * the name of the file to find (if no data) or a regex to match files.
  1390. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  1391. * @param {Object} o File options
  1392. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  1393. * a file (when searching by string) or an array of files (when searching by regex).
  1394. */
  1395. file: function(name, data, o) {
  1396. if (arguments.length === 1) {
  1397. if (utils.isRegExp(name)) {
  1398. var regexp = name;
  1399. return this.filter(function(relativePath, file) {
  1400. return !file.dir && regexp.test(relativePath);
  1401. });
  1402. }
  1403. else { // text
  1404. return this.filter(function(relativePath, file) {
  1405. return !file.dir && relativePath === name;
  1406. })[0] || null;
  1407. }
  1408. }
  1409. else { // more than one argument : we have data !
  1410. name = this.root + name;
  1411. fileAdd.call(this, name, data, o);
  1412. }
  1413. return this;
  1414. },
  1415.  
  1416. /**
  1417. * Add a directory to the zip file, or search.
  1418. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  1419. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  1420. */
  1421. folder: function(arg) {
  1422. if (!arg) {
  1423. return this;
  1424. }
  1425.  
  1426. if (utils.isRegExp(arg)) {
  1427. return this.filter(function(relativePath, file) {
  1428. return file.dir && arg.test(relativePath);
  1429. });
  1430. }
  1431.  
  1432. // else, name is a new folder
  1433. var name = this.root + arg;
  1434. var newFolder = folderAdd.call(this, name);
  1435.  
  1436. // Allow chaining by returning a new object with this folder as the root
  1437. var ret = this.clone();
  1438. ret.root = newFolder.name;
  1439. return ret;
  1440. },
  1441.  
  1442. /**
  1443. * Delete a file, or a directory and all sub-files, from the zip
  1444. * @param {string} name the name of the file to delete
  1445. * @return {JSZip} this JSZip object
  1446. */
  1447. remove: function(name) {
  1448. name = this.root + name;
  1449. var file = this.files[name];
  1450. if (!file) {
  1451. // Look for any folders
  1452. if (name.slice(-1) != "/") {
  1453. name += "/";
  1454. }
  1455. file = this.files[name];
  1456. }
  1457.  
  1458. if (file && !file.dir) {
  1459. // file
  1460. delete this.files[name];
  1461. } else {
  1462. // maybe a folder, delete recursively
  1463. var kids = this.filter(function(relativePath, file) {
  1464. return file.name.slice(0, name.length) === name;
  1465. });
  1466. for (var i = 0; i < kids.length; i++) {
  1467. delete this.files[kids[i].name];
  1468. }
  1469. }
  1470.  
  1471. return this;
  1472. },
  1473.  
  1474. /**
  1475. * Generate the complete zip file
  1476. * @param {Object} options the options to generate the zip file :
  1477. * - base64, (deprecated, use type instead) true to generate base64.
  1478. * - compression, "STORE" by default.
  1479. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1480. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  1481. */
  1482. generate: function(options) {
  1483. options = extend(options || {}, {
  1484. base64: true,
  1485. compression: "STORE",
  1486. compressionOptions : null,
  1487. type: "base64",
  1488. platform: "DOS",
  1489. comment: null,
  1490. mimeType: 'application/zip'
  1491. });
  1492.  
  1493. utils.checkSupport(options.type);
  1494.  
  1495. // accept nodejs `process.platform`
  1496. if(
  1497. options.platform === 'darwin' ||
  1498. options.platform === 'freebsd' ||
  1499. options.platform === 'linux' ||
  1500. options.platform === 'sunos'
  1501. ) {
  1502. options.platform = "UNIX";
  1503. }
  1504. if (options.platform === 'win32') {
  1505. options.platform = "DOS";
  1506. }
  1507.  
  1508. var zipData = [],
  1509. localDirLength = 0,
  1510. centralDirLength = 0,
  1511. writer, i,
  1512. utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || ""));
  1513.  
  1514. // first, generate all the zip parts.
  1515. for (var name in this.files) {
  1516. if (!this.files.hasOwnProperty(name)) {
  1517. continue;
  1518. }
  1519. var file = this.files[name];
  1520.  
  1521. var compressionName = file.options.compression || options.compression.toUpperCase();
  1522. var compression = compressions[compressionName];
  1523. if (!compression) {
  1524. throw new Error(compressionName + " is not a valid compression method !");
  1525. }
  1526. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  1527.  
  1528. var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
  1529.  
  1530. var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform);
  1531. localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
  1532. centralDirLength += zipPart.dirRecord.length;
  1533. zipData.push(zipPart);
  1534. }
  1535.  
  1536. var dirEnd = "";
  1537.  
  1538. // end of central dir signature
  1539. dirEnd = signature.CENTRAL_DIRECTORY_END +
  1540. // number of this disk
  1541. "\x00\x00" +
  1542. // number of the disk with the start of the central directory
  1543. "\x00\x00" +
  1544. // total number of entries in the central directory on this disk
  1545. decToHex(zipData.length, 2) +
  1546. // total number of entries in the central directory
  1547. decToHex(zipData.length, 2) +
  1548. // size of the central directory 4 bytes
  1549. decToHex(centralDirLength, 4) +
  1550. // offset of start of central directory with respect to the starting disk number
  1551. decToHex(localDirLength, 4) +
  1552. // .ZIP file comment length
  1553. decToHex(utfEncodedComment.length, 2) +
  1554. // .ZIP file comment
  1555. utfEncodedComment;
  1556.  
  1557.  
  1558. // we have all the parts (and the total length)
  1559. // time to create a writer !
  1560. var typeName = options.type.toLowerCase();
  1561. if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
  1562. writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
  1563. }else{
  1564. writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
  1565. }
  1566.  
  1567. for (i = 0; i < zipData.length; i++) {
  1568. writer.append(zipData[i].fileRecord);
  1569. writer.append(zipData[i].compressedObject.compressedContent);
  1570. }
  1571. for (i = 0; i < zipData.length; i++) {
  1572. writer.append(zipData[i].dirRecord);
  1573. }
  1574.  
  1575. writer.append(dirEnd);
  1576.  
  1577. var zip = writer.finalize();
  1578.  
  1579.  
  1580.  
  1581. switch(options.type.toLowerCase()) {
  1582. // case "zip is an Uint8Array"
  1583. case "uint8array" :
  1584. case "arraybuffer" :
  1585. case "nodebuffer" :
  1586. return utils.transformTo(options.type.toLowerCase(), zip);
  1587. case "blob" :
  1588. return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
  1589. // case "zip is a string"
  1590. case "base64" :
  1591. return (options.base64) ? base64.encode(zip) : zip;
  1592. default : // case "string" :
  1593. return zip;
  1594. }
  1595.  
  1596. },
  1597.  
  1598. /**
  1599. * @deprecated
  1600. * This method will be removed in a future version without replacement.
  1601. */
  1602. crc32: function (input, crc) {
  1603. return crc32(input, crc);
  1604. },
  1605.  
  1606. /**
  1607. * @deprecated
  1608. * This method will be removed in a future version without replacement.
  1609. */
  1610. utf8encode: function (string) {
  1611. return utils.transformTo("string", utf8.utf8encode(string));
  1612. },
  1613.  
  1614. /**
  1615. * @deprecated
  1616. * This method will be removed in a future version without replacement.
  1617. */
  1618. utf8decode: function (input) {
  1619. return utf8.utf8decode(input);
  1620. }
  1621. };
  1622. module.exports = out;
  1623.  
  1624. },{"./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){
  1625. 'use strict';
  1626. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  1627. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  1628. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  1629. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  1630. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  1631. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  1632.  
  1633. },{}],15:[function(_dereq_,module,exports){
  1634. 'use strict';
  1635. var DataReader = _dereq_('./dataReader');
  1636. var utils = _dereq_('./utils');
  1637.  
  1638. function StringReader(data, optimizedBinaryString) {
  1639. this.data = data;
  1640. if (!optimizedBinaryString) {
  1641. this.data = utils.string2binary(this.data);
  1642. }
  1643. this.length = this.data.length;
  1644. this.index = 0;
  1645. }
  1646. StringReader.prototype = new DataReader();
  1647. /**
  1648. * @see DataReader.byteAt
  1649. */
  1650. StringReader.prototype.byteAt = function(i) {
  1651. return this.data.charCodeAt(i);
  1652. };
  1653. /**
  1654. * @see DataReader.lastIndexOfSignature
  1655. */
  1656. StringReader.prototype.lastIndexOfSignature = function(sig) {
  1657. return this.data.lastIndexOf(sig);
  1658. };
  1659. /**
  1660. * @see DataReader.readData
  1661. */
  1662. StringReader.prototype.readData = function(size) {
  1663. this.checkOffset(size);
  1664. // this will work because the constructor applied the "& 0xff" mask.
  1665. var result = this.data.slice(this.index, this.index + size);
  1666. this.index += size;
  1667. return result;
  1668. };
  1669. module.exports = StringReader;
  1670.  
  1671. },{"./dataReader":5,"./utils":21}],16:[function(_dereq_,module,exports){
  1672. 'use strict';
  1673.  
  1674. var utils = _dereq_('./utils');
  1675.  
  1676. /**
  1677. * An object to write any content to a string.
  1678. * @constructor
  1679. */
  1680. var StringWriter = function() {
  1681. this.data = [];
  1682. };
  1683. StringWriter.prototype = {
  1684. /**
  1685. * Append any content to the current string.
  1686. * @param {Object} input the content to add.
  1687. */
  1688. append: function(input) {
  1689. input = utils.transformTo("string", input);
  1690. this.data.push(input);
  1691. },
  1692. /**
  1693. * Finalize the construction an return the result.
  1694. * @return {string} the generated string.
  1695. */
  1696. finalize: function() {
  1697. return this.data.join("");
  1698. }
  1699. };
  1700.  
  1701. module.exports = StringWriter;
  1702.  
  1703. },{"./utils":21}],17:[function(_dereq_,module,exports){
  1704. (function (Buffer){
  1705. 'use strict';
  1706. exports.base64 = true;
  1707. exports.array = true;
  1708. exports.string = true;
  1709. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  1710. // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
  1711. // Browserify will provide a Buffer implementation for browsers, which is
  1712. // an augmented Uint8Array (i.e., can be used as either Buffer or U8).
  1713. exports.nodebuffer = typeof Buffer !== "undefined";
  1714. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  1715. exports.uint8array = typeof Uint8Array !== "undefined";
  1716.  
  1717. if (typeof ArrayBuffer === "undefined") {
  1718. exports.blob = false;
  1719. }
  1720. else {
  1721. var buffer = new ArrayBuffer(0);
  1722. try {
  1723. exports.blob = new Blob([buffer], {
  1724. type: "application/zip"
  1725. }).size === 0;
  1726. }
  1727. catch (e) {
  1728. try {
  1729. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  1730. var builder = new Builder();
  1731. builder.append(buffer);
  1732. exports.blob = builder.getBlob('application/zip').size === 0;
  1733. }
  1734. catch (e) {
  1735. exports.blob = false;
  1736. }
  1737. }
  1738. }
  1739.  
  1740. }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
  1741. },{}],18:[function(_dereq_,module,exports){
  1742. 'use strict';
  1743. var DataReader = _dereq_('./dataReader');
  1744.  
  1745. function Uint8ArrayReader(data) {
  1746. if (data) {
  1747. this.data = data;
  1748. this.length = this.data.length;
  1749. this.index = 0;
  1750. }
  1751. }
  1752. Uint8ArrayReader.prototype = new DataReader();
  1753. /**
  1754. * @see DataReader.byteAt
  1755. */
  1756. Uint8ArrayReader.prototype.byteAt = function(i) {
  1757. return this.data[i];
  1758. };
  1759. /**
  1760. * @see DataReader.lastIndexOfSignature
  1761. */
  1762. Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  1763. var sig0 = sig.charCodeAt(0),
  1764. sig1 = sig.charCodeAt(1),
  1765. sig2 = sig.charCodeAt(2),
  1766. sig3 = sig.charCodeAt(3);
  1767. for (var i = this.length - 4; i >= 0; --i) {
  1768. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  1769. return i;
  1770. }
  1771. }
  1772.  
  1773. return -1;
  1774. };
  1775. /**
  1776. * @see DataReader.readData
  1777. */
  1778. Uint8ArrayReader.prototype.readData = function(size) {
  1779. this.checkOffset(size);
  1780. if(size === 0) {
  1781. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  1782. return new Uint8Array(0);
  1783. }
  1784. var result = this.data.subarray(this.index, this.index + size);
  1785. this.index += size;
  1786. return result;
  1787. };
  1788. module.exports = Uint8ArrayReader;
  1789.  
  1790. },{"./dataReader":5}],19:[function(_dereq_,module,exports){
  1791. 'use strict';
  1792.  
  1793. var utils = _dereq_('./utils');
  1794.  
  1795. /**
  1796. * An object to write any content to an Uint8Array.
  1797. * @constructor
  1798. * @param {number} length The length of the array.
  1799. */
  1800. var Uint8ArrayWriter = function(length) {
  1801. this.data = new Uint8Array(length);
  1802. this.index = 0;
  1803. };
  1804. Uint8ArrayWriter.prototype = {
  1805. /**
  1806. * Append any content to the current array.
  1807. * @param {Object} input the content to add.
  1808. */
  1809. append: function(input) {
  1810. if (input.length !== 0) {
  1811. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  1812. input = utils.transformTo("uint8array", input);
  1813. this.data.set(input, this.index);
  1814. this.index += input.length;
  1815. }
  1816. },
  1817. /**
  1818. * Finalize the construction an return the result.
  1819. * @return {Uint8Array} the generated array.
  1820. */
  1821. finalize: function() {
  1822. return this.data;
  1823. }
  1824. };
  1825.  
  1826. module.exports = Uint8ArrayWriter;
  1827.  
  1828. },{"./utils":21}],20:[function(_dereq_,module,exports){
  1829. 'use strict';
  1830.  
  1831. var utils = _dereq_('./utils');
  1832. var support = _dereq_('./support');
  1833. var nodeBuffer = _dereq_('./nodeBuffer');
  1834.  
  1835. /**
  1836. * The following functions come from pako, from pako/lib/utils/strings
  1837. * released under the MIT license, see pako https://github.com/nodeca/pako/
  1838. */
  1839.  
  1840. // Table with utf8 lengths (calculated by first byte of sequence)
  1841. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  1842. // because max possible codepoint is 0x10ffff
  1843. var _utf8len = new Array(256);
  1844. for (var i=0; i<256; i++) {
  1845. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  1846. }
  1847. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  1848.  
  1849. // convert string to array (typed, when possible)
  1850. var string2buf = function (str) {
  1851. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  1852.  
  1853. // count binary size
  1854. for (m_pos = 0; m_pos < str_len; m_pos++) {
  1855. c = str.charCodeAt(m_pos);
  1856. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  1857. c2 = str.charCodeAt(m_pos+1);
  1858. if ((c2 & 0xfc00) === 0xdc00) {
  1859. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  1860. m_pos++;
  1861. }
  1862. }
  1863. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  1864. }
  1865.  
  1866. // allocate buffer
  1867. if (support.uint8array) {
  1868. buf = new Uint8Array(buf_len);
  1869. } else {
  1870. buf = new Array(buf_len);
  1871. }
  1872.  
  1873. // convert
  1874. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  1875. c = str.charCodeAt(m_pos);
  1876. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  1877. c2 = str.charCodeAt(m_pos+1);
  1878. if ((c2 & 0xfc00) === 0xdc00) {
  1879. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  1880. m_pos++;
  1881. }
  1882. }
  1883. if (c < 0x80) {
  1884. /* one byte */
  1885. buf[i++] = c;
  1886. } else if (c < 0x800) {
  1887. /* two bytes */
  1888. buf[i++] = 0xC0 | (c >>> 6);
  1889. buf[i++] = 0x80 | (c & 0x3f);
  1890. } else if (c < 0x10000) {
  1891. /* three bytes */
  1892. buf[i++] = 0xE0 | (c >>> 12);
  1893. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  1894. buf[i++] = 0x80 | (c & 0x3f);
  1895. } else {
  1896. /* four bytes */
  1897. buf[i++] = 0xf0 | (c >>> 18);
  1898. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  1899. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  1900. buf[i++] = 0x80 | (c & 0x3f);
  1901. }
  1902. }
  1903.  
  1904. return buf;
  1905. };
  1906.  
  1907. // Calculate max possible position in utf8 buffer,
  1908. // that will not break sequence. If that's not possible
  1909. // - (very small limits) return max size as is.
  1910. //
  1911. // buf[] - utf8 bytes array
  1912. // max - length limit (mandatory);
  1913. var utf8border = function(buf, max) {
  1914. var pos;
  1915.  
  1916. max = max || buf.length;
  1917. if (max > buf.length) { max = buf.length; }
  1918.  
  1919. // go back from last position, until start of sequence found
  1920. pos = max-1;
  1921. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  1922.  
  1923. // Fuckup - very small and broken sequence,
  1924. // return max, because we should return something anyway.
  1925. if (pos < 0) { return max; }
  1926.  
  1927. // If we came to start of buffer - that means vuffer is too small,
  1928. // return max too.
  1929. if (pos === 0) { return max; }
  1930.  
  1931. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  1932. };
  1933.  
  1934. // convert array to string
  1935. var buf2string = function (buf) {
  1936. var str, i, out, c, c_len;
  1937. var len = buf.length;
  1938.  
  1939. // Reserve max possible length (2 words per char)
  1940. // NB: by unknown reasons, Array is significantly faster for
  1941. // String.fromCharCode.apply than Uint16Array.
  1942. var utf16buf = new Array(len*2);
  1943.  
  1944. for (out=0, i=0; i<len;) {
  1945. c = buf[i++];
  1946. // quick process ascii
  1947. if (c < 0x80) { utf16buf[out++] = c; continue; }
  1948.  
  1949. c_len = _utf8len[c];
  1950. // skip 5 & 6 byte codes
  1951. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  1952.  
  1953. // apply mask on first byte
  1954. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  1955. // join the rest
  1956. while (c_len > 1 && i < len) {
  1957. c = (c << 6) | (buf[i++] & 0x3f);
  1958. c_len--;
  1959. }
  1960.  
  1961. // terminated by end of string?
  1962. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  1963.  
  1964. if (c < 0x10000) {
  1965. utf16buf[out++] = c;
  1966. } else {
  1967. c -= 0x10000;
  1968. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  1969. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  1970. }
  1971. }
  1972.  
  1973. // shrinkBuf(utf16buf, out)
  1974. if (utf16buf.length !== out) {
  1975. if(utf16buf.subarray) {
  1976. utf16buf = utf16buf.subarray(0, out);
  1977. } else {
  1978. utf16buf.length = out;
  1979. }
  1980. }
  1981.  
  1982. // return String.fromCharCode.apply(null, utf16buf);
  1983. return utils.applyFromCharCode(utf16buf);
  1984. };
  1985.  
  1986.  
  1987. // That's all for the pako functions.
  1988.  
  1989.  
  1990. /**
  1991. * Transform a javascript string into an array (typed if possible) of bytes,
  1992. * UTF-8 encoded.
  1993. * @param {String} str the string to encode
  1994. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  1995. */
  1996. exports.utf8encode = function utf8encode(str) {
  1997. if (support.nodebuffer) {
  1998. return nodeBuffer(str, "utf-8");
  1999. }
  2000.  
  2001. return string2buf(str);
  2002. };
  2003.  
  2004.  
  2005. /**
  2006. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  2007. * string into a javascript string.
  2008. * @param {Array|Uint8Array|Buffer} buf the data de decode
  2009. * @return {String} the decoded string.
  2010. */
  2011. exports.utf8decode = function utf8decode(buf) {
  2012. if (support.nodebuffer) {
  2013. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  2014. }
  2015.  
  2016. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  2017.  
  2018. // return buf2string(buf);
  2019. // Chrome prefers to work with "small" chunks of data
  2020. // for the method buf2string.
  2021. // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
  2022. var result = [], k = 0, len = buf.length, chunk = 65536;
  2023. while (k < len) {
  2024. var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
  2025. if (support.uint8array) {
  2026. result.push(buf2string(buf.subarray(k, nextBoundary)));
  2027. } else {
  2028. result.push(buf2string(buf.slice(k, nextBoundary)));
  2029. }
  2030. k = nextBoundary;
  2031. }
  2032. return result.join("");
  2033.  
  2034. };
  2035. // vim: set shiftwidth=4 softtabstop=4:
  2036.  
  2037. },{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(_dereq_,module,exports){
  2038. 'use strict';
  2039. var support = _dereq_('./support');
  2040. var compressions = _dereq_('./compressions');
  2041. var nodeBuffer = _dereq_('./nodeBuffer');
  2042. /**
  2043. * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
  2044. * @param {string} str the string to transform.
  2045. * @return {String} the binary string.
  2046. */
  2047. exports.string2binary = function(str) {
  2048. var result = "";
  2049. for (var i = 0; i < str.length; i++) {
  2050. result += String.fromCharCode(str.charCodeAt(i) & 0xff);
  2051. }
  2052. return result;
  2053. };
  2054. exports.arrayBuffer2Blob = function(buffer, mimeType) {
  2055. exports.checkSupport("blob");
  2056. mimeType = mimeType || 'application/zip';
  2057.  
  2058. try {
  2059. // Blob constructor
  2060. return new Blob([buffer], {
  2061. type: mimeType
  2062. });
  2063. }
  2064. catch (e) {
  2065.  
  2066. try {
  2067. // deprecated, browser only, old way
  2068. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  2069. var builder = new Builder();
  2070. builder.append(buffer);
  2071. return builder.getBlob(mimeType);
  2072. }
  2073. catch (e) {
  2074.  
  2075. // well, fuck ?!
  2076. throw new Error("Bug : can't construct the Blob.");
  2077. }
  2078. }
  2079.  
  2080.  
  2081. };
  2082. /**
  2083. * The identity function.
  2084. * @param {Object} input the input.
  2085. * @return {Object} the same input.
  2086. */
  2087. function identity(input) {
  2088. return input;
  2089. }
  2090.  
  2091. /**
  2092. * Fill in an array with a string.
  2093. * @param {String} str the string to use.
  2094. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  2095. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  2096. */
  2097. function stringToArrayLike(str, array) {
  2098. for (var i = 0; i < str.length; ++i) {
  2099. array[i] = str.charCodeAt(i) & 0xFF;
  2100. }
  2101. return array;
  2102. }
  2103.  
  2104. /**
  2105. * Transform an array-like object to a string.
  2106. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  2107. * @return {String} the result.
  2108. */
  2109. function arrayLikeToString(array) {
  2110. // Performances notes :
  2111. // --------------------
  2112. // String.fromCharCode.apply(null, array) is the fastest, see
  2113. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  2114. // but the stack is limited (and we can get huge arrays !).
  2115. //
  2116. // result += String.fromCharCode(array[i]); generate too many strings !
  2117. //
  2118. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  2119. var chunk = 65536;
  2120. var result = [],
  2121. len = array.length,
  2122. type = exports.getTypeOf(array),
  2123. k = 0,
  2124. canUseApply = true;
  2125. try {
  2126. switch(type) {
  2127. case "uint8array":
  2128. String.fromCharCode.apply(null, new Uint8Array(0));
  2129. break;
  2130. case "nodebuffer":
  2131. String.fromCharCode.apply(null, nodeBuffer(0));
  2132. break;
  2133. }
  2134. } catch(e) {
  2135. canUseApply = false;
  2136. }
  2137.  
  2138. // no apply : slow and painful algorithm
  2139. // default browser on android 4.*
  2140. if (!canUseApply) {
  2141. var resultStr = "";
  2142. for(var i = 0; i < array.length;i++) {
  2143. resultStr += String.fromCharCode(array[i]);
  2144. }
  2145. return resultStr;
  2146. }
  2147. while (k < len && chunk > 1) {
  2148. try {
  2149. if (type === "array" || type === "nodebuffer") {
  2150. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  2151. }
  2152. else {
  2153. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  2154. }
  2155. k += chunk;
  2156. }
  2157. catch (e) {
  2158. chunk = Math.floor(chunk / 2);
  2159. }
  2160. }
  2161. return result.join("");
  2162. }
  2163.  
  2164. exports.applyFromCharCode = arrayLikeToString;
  2165.  
  2166.  
  2167. /**
  2168. * Copy the data from an array-like to an other array-like.
  2169. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  2170. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  2171. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  2172. */
  2173. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  2174. for (var i = 0; i < arrayFrom.length; i++) {
  2175. arrayTo[i] = arrayFrom[i];
  2176. }
  2177. return arrayTo;
  2178. }
  2179.  
  2180. // a matrix containing functions to transform everything into everything.
  2181. var transform = {};
  2182.  
  2183. // string to ?
  2184. transform["string"] = {
  2185. "string": identity,
  2186. "array": function(input) {
  2187. return stringToArrayLike(input, new Array(input.length));
  2188. },
  2189. "arraybuffer": function(input) {
  2190. return transform["string"]["uint8array"](input).buffer;
  2191. },
  2192. "uint8array": function(input) {
  2193. return stringToArrayLike(input, new Uint8Array(input.length));
  2194. },
  2195. "nodebuffer": function(input) {
  2196. return stringToArrayLike(input, nodeBuffer(input.length));
  2197. }
  2198. };
  2199.  
  2200. // array to ?
  2201. transform["array"] = {
  2202. "string": arrayLikeToString,
  2203. "array": identity,
  2204. "arraybuffer": function(input) {
  2205. return (new Uint8Array(input)).buffer;
  2206. },
  2207. "uint8array": function(input) {
  2208. return new Uint8Array(input);
  2209. },
  2210. "nodebuffer": function(input) {
  2211. return nodeBuffer(input);
  2212. }
  2213. };
  2214.  
  2215. // arraybuffer to ?
  2216. transform["arraybuffer"] = {
  2217. "string": function(input) {
  2218. return arrayLikeToString(new Uint8Array(input));
  2219. },
  2220. "array": function(input) {
  2221. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  2222. },
  2223. "arraybuffer": identity,
  2224. "uint8array": function(input) {
  2225. return new Uint8Array(input);
  2226. },
  2227. "nodebuffer": function(input) {
  2228. return nodeBuffer(new Uint8Array(input));
  2229. }
  2230. };
  2231.  
  2232. // uint8array to ?
  2233. transform["uint8array"] = {
  2234. "string": arrayLikeToString,
  2235. "array": function(input) {
  2236. return arrayLikeToArrayLike(input, new Array(input.length));
  2237. },
  2238. "arraybuffer": function(input) {
  2239. return input.buffer;
  2240. },
  2241. "uint8array": identity,
  2242. "nodebuffer": function(input) {
  2243. return nodeBuffer(input);
  2244. }
  2245. };
  2246.  
  2247. // nodebuffer to ?
  2248. transform["nodebuffer"] = {
  2249. "string": arrayLikeToString,
  2250. "array": function(input) {
  2251. return arrayLikeToArrayLike(input, new Array(input.length));
  2252. },
  2253. "arraybuffer": function(input) {
  2254. return transform["nodebuffer"]["uint8array"](input).buffer;
  2255. },
  2256. "uint8array": function(input) {
  2257. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  2258. },
  2259. "nodebuffer": identity
  2260. };
  2261.  
  2262. /**
  2263. * Transform an input into any type.
  2264. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  2265. * If no output type is specified, the unmodified input will be returned.
  2266. * @param {String} outputType the output type.
  2267. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  2268. * @throws {Error} an Error if the browser doesn't support the requested output type.
  2269. */
  2270. exports.transformTo = function(outputType, input) {
  2271. if (!input) {
  2272. // undefined, null, etc
  2273. // an empty string won't harm.
  2274. input = "";
  2275. }
  2276. if (!outputType) {
  2277. return input;
  2278. }
  2279. exports.checkSupport(outputType);
  2280. var inputType = exports.getTypeOf(input);
  2281. var result = transform[inputType][outputType](input);
  2282. return result;
  2283. };
  2284.  
  2285. /**
  2286. * Return the type of the input.
  2287. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  2288. * @param {Object} input the input to identify.
  2289. * @return {String} the (lowercase) type of the input.
  2290. */
  2291. exports.getTypeOf = function(input) {
  2292. if (typeof input === "string") {
  2293. return "string";
  2294. }
  2295. if (Object.prototype.toString.call(input) === "[object Array]") {
  2296. return "array";
  2297. }
  2298. if (support.nodebuffer && nodeBuffer.test(input)) {
  2299. return "nodebuffer";
  2300. }
  2301. if (support.uint8array && input instanceof Uint8Array) {
  2302. return "uint8array";
  2303. }
  2304. if (support.arraybuffer && input instanceof ArrayBuffer) {
  2305. return "arraybuffer";
  2306. }
  2307. };
  2308.  
  2309. /**
  2310. * Throw an exception if the type is not supported.
  2311. * @param {String} type the type to check.
  2312. * @throws {Error} an Error if the browser doesn't support the requested type.
  2313. */
  2314. exports.checkSupport = function(type) {
  2315. var supported = support[type.toLowerCase()];
  2316. if (!supported) {
  2317. throw new Error(type + " is not supported by this browser");
  2318. }
  2319. };
  2320. exports.MAX_VALUE_16BITS = 65535;
  2321. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  2322.  
  2323. /**
  2324. * Prettify a string read as binary.
  2325. * @param {string} str the string to prettify.
  2326. * @return {string} a pretty string.
  2327. */
  2328. exports.pretty = function(str) {
  2329. var res = '',
  2330. code, i;
  2331. for (i = 0; i < (str || "").length; i++) {
  2332. code = str.charCodeAt(i);
  2333. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  2334. }
  2335. return res;
  2336. };
  2337.  
  2338. /**
  2339. * Find a compression registered in JSZip.
  2340. * @param {string} compressionMethod the method magic to find.
  2341. * @return {Object|null} the JSZip compression object, null if none found.
  2342. */
  2343. exports.findCompression = function(compressionMethod) {
  2344. for (var method in compressions) {
  2345. if (!compressions.hasOwnProperty(method)) {
  2346. continue;
  2347. }
  2348. if (compressions[method].magic === compressionMethod) {
  2349. return compressions[method];
  2350. }
  2351. }
  2352. return null;
  2353. };
  2354. /**
  2355. * Cross-window, cross-Node-context regular expression detection
  2356. * @param {Object} object Anything
  2357. * @return {Boolean} true if the object is a regular expression,
  2358. * false otherwise
  2359. */
  2360. exports.isRegExp = function (object) {
  2361. return Object.prototype.toString.call(object) === "[object RegExp]";
  2362. };
  2363.  
  2364.  
  2365. },{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(_dereq_,module,exports){
  2366. 'use strict';
  2367. var StringReader = _dereq_('./stringReader');
  2368. var NodeBufferReader = _dereq_('./nodeBufferReader');
  2369. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  2370. var utils = _dereq_('./utils');
  2371. var sig = _dereq_('./signature');
  2372. var ZipEntry = _dereq_('./zipEntry');
  2373. var support = _dereq_('./support');
  2374. var jszipProto = _dereq_('./object');
  2375. // class ZipEntries {{{
  2376. /**
  2377. * All the entries in the zip file.
  2378. * @constructor
  2379. * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
  2380. * @param {Object} loadOptions Options for loading the stream.
  2381. */
  2382. function ZipEntries(data, loadOptions) {
  2383. this.files = [];
  2384. this.loadOptions = loadOptions;
  2385. if (data) {
  2386. this.load(data);
  2387. }
  2388. }
  2389. ZipEntries.prototype = {
  2390. /**
  2391. * Check that the reader is on the speficied signature.
  2392. * @param {string} expectedSignature the expected signature.
  2393. * @throws {Error} if it is an other signature.
  2394. */
  2395. checkSignature: function(expectedSignature) {
  2396. var signature = this.reader.readString(4);
  2397. if (signature !== expectedSignature) {
  2398. throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  2399. }
  2400. },
  2401. /**
  2402. * Read the end of the central directory.
  2403. */
  2404. readBlockEndOfCentral: function() {
  2405. this.diskNumber = this.reader.readInt(2);
  2406. this.diskWithCentralDirStart = this.reader.readInt(2);
  2407. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  2408. this.centralDirRecords = this.reader.readInt(2);
  2409. this.centralDirSize = this.reader.readInt(4);
  2410. this.centralDirOffset = this.reader.readInt(4);
  2411.  
  2412. this.zipCommentLength = this.reader.readInt(2);
  2413. // warning : the encoding depends of the system locale
  2414. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  2415. // On a windows machine, this field is encoded with the localized windows code page.
  2416. this.zipComment = this.reader.readString(this.zipCommentLength);
  2417. // To get consistent behavior with the generation part, we will assume that
  2418. // this is utf8 encoded.
  2419. this.zipComment = jszipProto.utf8decode(this.zipComment);
  2420. },
  2421. /**
  2422. * Read the end of the Zip 64 central directory.
  2423. * Not merged with the method readEndOfCentral :
  2424. * The end of central can coexist with its Zip64 brother,
  2425. * I don't want to read the wrong number of bytes !
  2426. */
  2427. readBlockZip64EndOfCentral: function() {
  2428. this.zip64EndOfCentralSize = this.reader.readInt(8);
  2429. this.versionMadeBy = this.reader.readString(2);
  2430. this.versionNeeded = this.reader.readInt(2);
  2431. this.diskNumber = this.reader.readInt(4);
  2432. this.diskWithCentralDirStart = this.reader.readInt(4);
  2433. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  2434. this.centralDirRecords = this.reader.readInt(8);
  2435. this.centralDirSize = this.reader.readInt(8);
  2436. this.centralDirOffset = this.reader.readInt(8);
  2437.  
  2438. this.zip64ExtensibleData = {};
  2439. var extraDataSize = this.zip64EndOfCentralSize - 44,
  2440. index = 0,
  2441. extraFieldId,
  2442. extraFieldLength,
  2443. extraFieldValue;
  2444. while (index < extraDataSize) {
  2445. extraFieldId = this.reader.readInt(2);
  2446. extraFieldLength = this.reader.readInt(4);
  2447. extraFieldValue = this.reader.readString(extraFieldLength);
  2448. this.zip64ExtensibleData[extraFieldId] = {
  2449. id: extraFieldId,
  2450. length: extraFieldLength,
  2451. value: extraFieldValue
  2452. };
  2453. }
  2454. },
  2455. /**
  2456. * Read the end of the Zip 64 central directory locator.
  2457. */
  2458. readBlockZip64EndOfCentralLocator: function() {
  2459. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  2460. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  2461. this.disksCount = this.reader.readInt(4);
  2462. if (this.disksCount > 1) {
  2463. throw new Error("Multi-volumes zip are not supported");
  2464. }
  2465. },
  2466. /**
  2467. * Read the local files, based on the offset read in the central part.
  2468. */
  2469. readLocalFiles: function() {
  2470. var i, file;
  2471. for (i = 0; i < this.files.length; i++) {
  2472. file = this.files[i];
  2473. this.reader.setIndex(file.localHeaderOffset);
  2474. this.checkSignature(sig.LOCAL_FILE_HEADER);
  2475. file.readLocalPart(this.reader);
  2476. file.handleUTF8();
  2477. file.processAttributes();
  2478. }
  2479. },
  2480. /**
  2481. * Read the central directory.
  2482. */
  2483. readCentralDir: function() {
  2484. var file;
  2485.  
  2486. this.reader.setIndex(this.centralDirOffset);
  2487. while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
  2488. file = new ZipEntry({
  2489. zip64: this.zip64
  2490. }, this.loadOptions);
  2491. file.readCentralPart(this.reader);
  2492. this.files.push(file);
  2493. }
  2494. },
  2495. /**
  2496. * Read the end of central directory.
  2497. */
  2498. readEndOfCentral: function() {
  2499. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  2500. if (offset === -1) {
  2501. // Check if the content is a truncated zip or complete garbage.
  2502. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  2503. // extractible zip for example) but it can give a good hint.
  2504. // If an ajax request was used without responseType, we will also
  2505. // get unreadable data.
  2506. var isGarbage = true;
  2507. try {
  2508. this.reader.setIndex(0);
  2509. this.checkSignature(sig.LOCAL_FILE_HEADER);
  2510. isGarbage = false;
  2511. } catch (e) {}
  2512.  
  2513. if (isGarbage) {
  2514. throw new Error("Can't find end of central directory : is this a zip file ? " +
  2515. "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
  2516. } else {
  2517. throw new Error("Corrupted zip : can't find end of central directory");
  2518. }
  2519. }
  2520. this.reader.setIndex(offset);
  2521. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  2522. this.readBlockEndOfCentral();
  2523.  
  2524.  
  2525. /* extract from the zip spec :
  2526. 4) If one of the fields in the end of central directory
  2527. record is too small to hold required data, the field
  2528. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  2529. ZIP64 format record should be created.
  2530. 5) The end of central directory record and the
  2531. Zip64 end of central directory locator record must
  2532. reside on the same disk when splitting or spanning
  2533. an archive.
  2534. */
  2535. 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) {
  2536. this.zip64 = true;
  2537.  
  2538. /*
  2539. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  2540. the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
  2541. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  2542. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  2543. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  2544. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  2545. */
  2546.  
  2547. // should look for a zip64 EOCD locator
  2548. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  2549. if (offset === -1) {
  2550. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
  2551. }
  2552. this.reader.setIndex(offset);
  2553. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  2554. this.readBlockZip64EndOfCentralLocator();
  2555.  
  2556. // now the zip64 EOCD record
  2557. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  2558. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  2559. this.readBlockZip64EndOfCentral();
  2560. }
  2561. },
  2562. prepareReader: function(data) {
  2563. var type = utils.getTypeOf(data);
  2564. if (type === "string" && !support.uint8array) {
  2565. this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
  2566. }
  2567. else if (type === "nodebuffer") {
  2568. this.reader = new NodeBufferReader(data);
  2569. }
  2570. else {
  2571. this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
  2572. }
  2573. },
  2574. /**
  2575. * Read a zip file and create ZipEntries.
  2576. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  2577. */
  2578. load: function(data) {
  2579. this.prepareReader(data);
  2580. this.readEndOfCentral();
  2581. this.readCentralDir();
  2582. this.readLocalFiles();
  2583. }
  2584. };
  2585. // }}} end of ZipEntries
  2586. module.exports = ZipEntries;
  2587.  
  2588. },{"./nodeBufferReader":12,"./object":13,"./signature":14,"./stringReader":15,"./support":17,"./uint8ArrayReader":18,"./utils":21,"./zipEntry":23}],23:[function(_dereq_,module,exports){
  2589. 'use strict';
  2590. var StringReader = _dereq_('./stringReader');
  2591. var utils = _dereq_('./utils');
  2592. var CompressedObject = _dereq_('./compressedObject');
  2593. var jszipProto = _dereq_('./object');
  2594.  
  2595. var MADE_BY_DOS = 0x00;
  2596. var MADE_BY_UNIX = 0x03;
  2597.  
  2598. // class ZipEntry {{{
  2599. /**
  2600. * An entry in the zip file.
  2601. * @constructor
  2602. * @param {Object} options Options of the current file.
  2603. * @param {Object} loadOptions Options for loading the stream.
  2604. */
  2605. function ZipEntry(options, loadOptions) {
  2606. this.options = options;
  2607. this.loadOptions = loadOptions;
  2608. }
  2609. ZipEntry.prototype = {
  2610. /**
  2611. * say if the file is encrypted.
  2612. * @return {boolean} true if the file is encrypted, false otherwise.
  2613. */
  2614. isEncrypted: function() {
  2615. // bit 1 is set
  2616. return (this.bitFlag & 0x0001) === 0x0001;
  2617. },
  2618. /**
  2619. * say if the file has utf-8 filename/comment.
  2620. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  2621. */
  2622. useUTF8: function() {
  2623. // bit 11 is set
  2624. return (this.bitFlag & 0x0800) === 0x0800;
  2625. },
  2626. /**
  2627. * Prepare the function used to generate the compressed content from this ZipFile.
  2628. * @param {DataReader} reader the reader to use.
  2629. * @param {number} from the offset from where we should read the data.
  2630. * @param {number} length the length of the data to read.
  2631. * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
  2632. */
  2633. prepareCompressedContent: function(reader, from, length) {
  2634. return function() {
  2635. var previousIndex = reader.index;
  2636. reader.setIndex(from);
  2637. var compressedFileData = reader.readData(length);
  2638. reader.setIndex(previousIndex);
  2639.  
  2640. return compressedFileData;
  2641. };
  2642. },
  2643. /**
  2644. * Prepare the function used to generate the uncompressed content from this ZipFile.
  2645. * @param {DataReader} reader the reader to use.
  2646. * @param {number} from the offset from where we should read the data.
  2647. * @param {number} length the length of the data to read.
  2648. * @param {JSZip.compression} compression the compression used on this file.
  2649. * @param {number} uncompressedSize the uncompressed size to expect.
  2650. * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
  2651. */
  2652. prepareContent: function(reader, from, length, compression, uncompressedSize) {
  2653. return function() {
  2654.  
  2655. var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
  2656. var uncompressedFileData = compression.uncompress(compressedFileData);
  2657.  
  2658. if (uncompressedFileData.length !== uncompressedSize) {
  2659. throw new Error("Bug : uncompressed data size mismatch");
  2660. }
  2661.  
  2662. return uncompressedFileData;
  2663. };
  2664. },
  2665. /**
  2666. * Read the local part of a zip file and add the info in this object.
  2667. * @param {DataReader} reader the reader to use.
  2668. */
  2669. readLocalPart: function(reader) {
  2670. var compression, localExtraFieldsLength;
  2671.  
  2672. // we already know everything from the central dir !
  2673. // If the central dir data are false, we are doomed.
  2674. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  2675. // The less data we get here, the more reliable this should be.
  2676. // Let's skip the whole header and dash to the data !
  2677. reader.skip(22);
  2678. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  2679. // Strangely, the filename here is OK.
  2680. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  2681. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  2682. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  2683. // the internet.
  2684. //
  2685. // I think I see the logic here : the central directory is used to display
  2686. // content and the local directory is used to extract the files. Mixing / and \
  2687. // may be used to display \ to windows users and use / when extracting the files.
  2688. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  2689. this.fileNameLength = reader.readInt(2);
  2690. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  2691. this.fileName = reader.readString(this.fileNameLength);
  2692. reader.skip(localExtraFieldsLength);
  2693.  
  2694. if (this.compressedSize == -1 || this.uncompressedSize == -1) {
  2695. throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
  2696. }
  2697.  
  2698. compression = utils.findCompression(this.compressionMethod);
  2699. if (compression === null) { // no compression found
  2700. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
  2701. }
  2702. this.decompressed = new CompressedObject();
  2703. this.decompressed.compressedSize = this.compressedSize;
  2704. this.decompressed.uncompressedSize = this.uncompressedSize;
  2705. this.decompressed.crc32 = this.crc32;
  2706. this.decompressed.compressionMethod = this.compressionMethod;
  2707. this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
  2708. this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
  2709.  
  2710. // we need to compute the crc32...
  2711. if (this.loadOptions.checkCRC32) {
  2712. this.decompressed = utils.transformTo("string", this.decompressed.getContent());
  2713. if (jszipProto.crc32(this.decompressed) !== this.crc32) {
  2714. throw new Error("Corrupted zip : CRC32 mismatch");
  2715. }
  2716. }
  2717. },
  2718.  
  2719. /**
  2720. * Read the central part of a zip file and add the info in this object.
  2721. * @param {DataReader} reader the reader to use.
  2722. */
  2723. readCentralPart: function(reader) {
  2724. this.versionMadeBy = reader.readInt(2);
  2725. this.versionNeeded = reader.readInt(2);
  2726. this.bitFlag = reader.readInt(2);
  2727. this.compressionMethod = reader.readString(2);
  2728. this.date = reader.readDate();
  2729. this.crc32 = reader.readInt(4);
  2730. this.compressedSize = reader.readInt(4);
  2731. this.uncompressedSize = reader.readInt(4);
  2732. this.fileNameLength = reader.readInt(2);
  2733. this.extraFieldsLength = reader.readInt(2);
  2734. this.fileCommentLength = reader.readInt(2);
  2735. this.diskNumberStart = reader.readInt(2);
  2736. this.internalFileAttributes = reader.readInt(2);
  2737. this.externalFileAttributes = reader.readInt(4);
  2738. this.localHeaderOffset = reader.readInt(4);
  2739.  
  2740. if (this.isEncrypted()) {
  2741. throw new Error("Encrypted zip are not supported");
  2742. }
  2743.  
  2744. this.fileName = reader.readString(this.fileNameLength);
  2745. this.readExtraFields(reader);
  2746. this.parseZIP64ExtraField(reader);
  2747. this.fileComment = reader.readString(this.fileCommentLength);
  2748. },
  2749.  
  2750. /**
  2751. * Parse the external file attributes and get the unix/dos permissions.
  2752. */
  2753. processAttributes: function () {
  2754. this.unixPermissions = null;
  2755. this.dosPermissions = null;
  2756. var madeBy = this.versionMadeBy >> 8;
  2757.  
  2758. // Check if we have the DOS directory flag set.
  2759. // We look for it in the DOS and UNIX permissions
  2760. // but some unknown platform could set it as a compatibility flag.
  2761. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  2762.  
  2763. if(madeBy === MADE_BY_DOS) {
  2764. // first 6 bits (0 to 5)
  2765. this.dosPermissions = this.externalFileAttributes & 0x3F;
  2766. }
  2767.  
  2768. if(madeBy === MADE_BY_UNIX) {
  2769. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  2770. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  2771. }
  2772.  
  2773. // fail safe : if the name ends with a / it probably means a folder
  2774. if (!this.dir && this.fileName.slice(-1) === '/') {
  2775. this.dir = true;
  2776. }
  2777. },
  2778.  
  2779. /**
  2780. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  2781. * @param {DataReader} reader the reader to use.
  2782. */
  2783. parseZIP64ExtraField: function(reader) {
  2784.  
  2785. if (!this.extraFields[0x0001]) {
  2786. return;
  2787. }
  2788.  
  2789. // should be something, preparing the extra reader
  2790. var extraReader = new StringReader(this.extraFields[0x0001].value);
  2791.  
  2792. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  2793. // won't let us have more.
  2794. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  2795. this.uncompressedSize = extraReader.readInt(8);
  2796. }
  2797. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  2798. this.compressedSize = extraReader.readInt(8);
  2799. }
  2800. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  2801. this.localHeaderOffset = extraReader.readInt(8);
  2802. }
  2803. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  2804. this.diskNumberStart = extraReader.readInt(4);
  2805. }
  2806. },
  2807. /**
  2808. * Read the central part of a zip file and add the info in this object.
  2809. * @param {DataReader} reader the reader to use.
  2810. */
  2811. readExtraFields: function(reader) {
  2812. var start = reader.index,
  2813. extraFieldId,
  2814. extraFieldLength,
  2815. extraFieldValue;
  2816.  
  2817. this.extraFields = this.extraFields || {};
  2818.  
  2819. while (reader.index < start + this.extraFieldsLength) {
  2820. extraFieldId = reader.readInt(2);
  2821. extraFieldLength = reader.readInt(2);
  2822. extraFieldValue = reader.readString(extraFieldLength);
  2823.  
  2824. this.extraFields[extraFieldId] = {
  2825. id: extraFieldId,
  2826. length: extraFieldLength,
  2827. value: extraFieldValue
  2828. };
  2829. }
  2830. },
  2831. /**
  2832. * Apply an UTF8 transformation if needed.
  2833. */
  2834. handleUTF8: function() {
  2835. if (this.useUTF8()) {
  2836. this.fileName = jszipProto.utf8decode(this.fileName);
  2837. this.fileComment = jszipProto.utf8decode(this.fileComment);
  2838. } else {
  2839. var upath = this.findExtraFieldUnicodePath();
  2840. if (upath !== null) {
  2841. this.fileName = upath;
  2842. }
  2843. var ucomment = this.findExtraFieldUnicodeComment();
  2844. if (ucomment !== null) {
  2845. this.fileComment = ucomment;
  2846. }
  2847. }
  2848. },
  2849.  
  2850. /**
  2851. * Find the unicode path declared in the extra field, if any.
  2852. * @return {String} the unicode path, null otherwise.
  2853. */
  2854. findExtraFieldUnicodePath: function() {
  2855. var upathField = this.extraFields[0x7075];
  2856. if (upathField) {
  2857. var extraReader = new StringReader(upathField.value);
  2858.  
  2859. // wrong version
  2860. if (extraReader.readInt(1) !== 1) {
  2861. return null;
  2862. }
  2863.  
  2864. // the crc of the filename changed, this field is out of date.
  2865. if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
  2866. return null;
  2867. }
  2868.  
  2869. return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
  2870. }
  2871. return null;
  2872. },
  2873.  
  2874. /**
  2875. * Find the unicode comment declared in the extra field, if any.
  2876. * @return {String} the unicode comment, null otherwise.
  2877. */
  2878. findExtraFieldUnicodeComment: function() {
  2879. var ucommentField = this.extraFields[0x6375];
  2880. if (ucommentField) {
  2881. var extraReader = new StringReader(ucommentField.value);
  2882.  
  2883. // wrong version
  2884. if (extraReader.readInt(1) !== 1) {
  2885. return null;
  2886. }
  2887.  
  2888. // the crc of the comment changed, this field is out of date.
  2889. if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
  2890. return null;
  2891. }
  2892.  
  2893. return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
  2894. }
  2895. return null;
  2896. }
  2897. };
  2898. module.exports = ZipEntry;
  2899.  
  2900. },{"./compressedObject":2,"./object":13,"./stringReader":15,"./utils":21}],24:[function(_dereq_,module,exports){
  2901. // Top level file is just a mixin of submodules & constants
  2902. 'use strict';
  2903.  
  2904. var assign = _dereq_('./lib/utils/common').assign;
  2905.  
  2906. var deflate = _dereq_('./lib/deflate');
  2907. var inflate = _dereq_('./lib/inflate');
  2908. var constants = _dereq_('./lib/zlib/constants');
  2909.  
  2910. var pako = {};
  2911.  
  2912. assign(pako, deflate, inflate, constants);
  2913.  
  2914. module.exports = pako;
  2915. },{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(_dereq_,module,exports){
  2916. 'use strict';
  2917.  
  2918.  
  2919. var zlib_deflate = _dereq_('./zlib/deflate.js');
  2920. var utils = _dereq_('./utils/common');
  2921. var strings = _dereq_('./utils/strings');
  2922. var msg = _dereq_('./zlib/messages');
  2923. var zstream = _dereq_('./zlib/zstream');
  2924.  
  2925.  
  2926. /* Public constants ==========================================================*/
  2927. /* ===========================================================================*/
  2928.  
  2929. var Z_NO_FLUSH = 0;
  2930. var Z_FINISH = 4;
  2931.  
  2932. var Z_OK = 0;
  2933. var Z_STREAM_END = 1;
  2934.  
  2935. var Z_DEFAULT_COMPRESSION = -1;
  2936.  
  2937. var Z_DEFAULT_STRATEGY = 0;
  2938.  
  2939. var Z_DEFLATED = 8;
  2940.  
  2941. /* ===========================================================================*/
  2942.  
  2943.  
  2944. /**
  2945. * class Deflate
  2946. *
  2947. * Generic JS-style wrapper for zlib calls. If you don't need
  2948. * streaming behaviour - use more simple functions: [[deflate]],
  2949. * [[deflateRaw]] and [[gzip]].
  2950. **/
  2951.  
  2952. /* internal
  2953. * Deflate.chunks -> Array
  2954. *
  2955. * Chunks of output data, if [[Deflate#onData]] not overriden.
  2956. **/
  2957.  
  2958. /**
  2959. * Deflate.result -> Uint8Array|Array
  2960. *
  2961. * Compressed result, generated by default [[Deflate#onData]]
  2962. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  2963. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  2964. **/
  2965.  
  2966. /**
  2967. * Deflate.err -> Number
  2968. *
  2969. * Error code after deflate finished. 0 (Z_OK) on success.
  2970. * You will not need it in real life, because deflate errors
  2971. * are possible only on wrong options or bad `onData` / `onEnd`
  2972. * custom handlers.
  2973. **/
  2974.  
  2975. /**
  2976. * Deflate.msg -> String
  2977. *
  2978. * Error message, if [[Deflate.err]] != 0
  2979. **/
  2980.  
  2981.  
  2982. /**
  2983. * new Deflate(options)
  2984. * - options (Object): zlib deflate options.
  2985. *
  2986. * Creates new deflator instance with specified params. Throws exception
  2987. * on bad params. Supported options:
  2988. *
  2989. * - `level`
  2990. * - `windowBits`
  2991. * - `memLevel`
  2992. * - `strategy`
  2993. *
  2994. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  2995. * for more information on these.
  2996. *
  2997. * Additional options, for internal needs:
  2998. *
  2999. * - `chunkSize` - size of generated data chunks (16K by default)
  3000. * - `raw` (Boolean) - do raw deflate
  3001. * - `gzip` (Boolean) - create gzip wrapper
  3002. * - `to` (String) - if equal to 'string', then result will be "binary string"
  3003. * (each char code [0..255])
  3004. * - `header` (Object) - custom header for gzip
  3005. * - `text` (Boolean) - true if compressed data believed to be text
  3006. * - `time` (Number) - modification time, unix timestamp
  3007. * - `os` (Number) - operation system code
  3008. * - `extra` (Array) - array of bytes with extra data (max 65536)
  3009. * - `name` (String) - file name (binary string)
  3010. * - `comment` (String) - comment (binary string)
  3011. * - `hcrc` (Boolean) - true if header crc should be added
  3012. *
  3013. * ##### Example:
  3014. *
  3015. * ```javascript
  3016. * var pako = require('pako')
  3017. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  3018. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  3019. *
  3020. * var deflate = new pako.Deflate({ level: 3});
  3021. *
  3022. * deflate.push(chunk1, false);
  3023. * deflate.push(chunk2, true); // true -> last chunk
  3024. *
  3025. * if (deflate.err) { throw new Error(deflate.err); }
  3026. *
  3027. * console.log(deflate.result);
  3028. * ```
  3029. **/
  3030. var Deflate = function(options) {
  3031.  
  3032. this.options = utils.assign({
  3033. level: Z_DEFAULT_COMPRESSION,
  3034. method: Z_DEFLATED,
  3035. chunkSize: 16384,
  3036. windowBits: 15,
  3037. memLevel: 8,
  3038. strategy: Z_DEFAULT_STRATEGY,
  3039. to: ''
  3040. }, options || {});
  3041.  
  3042. var opt = this.options;
  3043.  
  3044. if (opt.raw && (opt.windowBits > 0)) {
  3045. opt.windowBits = -opt.windowBits;
  3046. }
  3047.  
  3048. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  3049. opt.windowBits += 16;
  3050. }
  3051.  
  3052. this.err = 0; // error code, if happens (0 = Z_OK)
  3053. this.msg = ''; // error message
  3054. this.ended = false; // used to avoid multiple onEnd() calls
  3055. this.chunks = []; // chunks of compressed data
  3056.  
  3057. this.strm = new zstream();
  3058. this.strm.avail_out = 0;
  3059.  
  3060. var status = zlib_deflate.deflateInit2(
  3061. this.strm,
  3062. opt.level,
  3063. opt.method,
  3064. opt.windowBits,
  3065. opt.memLevel,
  3066. opt.strategy
  3067. );
  3068.  
  3069. if (status !== Z_OK) {
  3070. throw new Error(msg[status]);
  3071. }
  3072.  
  3073. if (opt.header) {
  3074. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  3075. }
  3076. };
  3077.  
  3078. /**
  3079. * Deflate#push(data[, mode]) -> Boolean
  3080. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  3081. * utf8 byte sequence.
  3082. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  3083. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  3084. *
  3085. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  3086. * new compressed chunks. Returns `true` on success. The last data block must have
  3087. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  3088. * [[Deflate#onEnd]].
  3089. *
  3090. * On fail call [[Deflate#onEnd]] with error code and return false.
  3091. *
  3092. * We strongly recommend to use `Uint8Array` on input for best speed (output
  3093. * array format is detected automatically). Also, don't skip last param and always
  3094. * use the same type in your code (boolean or number). That will improve JS speed.
  3095. *
  3096. * For regular `Array`-s make sure all elements are [0..255].
  3097. *
  3098. * ##### Example
  3099. *
  3100. * ```javascript
  3101. * push(chunk, false); // push one of data chunks
  3102. * ...
  3103. * push(chunk, true); // push last chunk
  3104. * ```
  3105. **/
  3106. Deflate.prototype.push = function(data, mode) {
  3107. var strm = this.strm;
  3108. var chunkSize = this.options.chunkSize;
  3109. var status, _mode;
  3110.  
  3111. if (this.ended) { return false; }
  3112.  
  3113. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  3114.  
  3115. // Convert data if needed
  3116. if (typeof data === 'string') {
  3117. // If we need to compress text, change encoding to utf8.
  3118. strm.input = strings.string2buf(data);
  3119. } else {
  3120. strm.input = data;
  3121. }
  3122.  
  3123. strm.next_in = 0;
  3124. strm.avail_in = strm.input.length;
  3125.  
  3126. do {
  3127. if (strm.avail_out === 0) {
  3128. strm.output = new utils.Buf8(chunkSize);
  3129. strm.next_out = 0;
  3130. strm.avail_out = chunkSize;
  3131. }
  3132. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  3133.  
  3134. if (status !== Z_STREAM_END && status !== Z_OK) {
  3135. this.onEnd(status);
  3136. this.ended = true;
  3137. return false;
  3138. }
  3139. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  3140. if (this.options.to === 'string') {
  3141. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  3142. } else {
  3143. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  3144. }
  3145. }
  3146. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  3147.  
  3148. // Finalize on the last chunk.
  3149. if (_mode === Z_FINISH) {
  3150. status = zlib_deflate.deflateEnd(this.strm);
  3151. this.onEnd(status);
  3152. this.ended = true;
  3153. return status === Z_OK;
  3154. }
  3155.  
  3156. return true;
  3157. };
  3158.  
  3159.  
  3160. /**
  3161. * Deflate#onData(chunk) -> Void
  3162. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  3163. * on js engine support. When string output requested, each chunk
  3164. * will be string.
  3165. *
  3166. * By default, stores data blocks in `chunks[]` property and glue
  3167. * those in `onEnd`. Override this handler, if you need another behaviour.
  3168. **/
  3169. Deflate.prototype.onData = function(chunk) {
  3170. this.chunks.push(chunk);
  3171. };
  3172.  
  3173.  
  3174. /**
  3175. * Deflate#onEnd(status) -> Void
  3176. * - status (Number): deflate status. 0 (Z_OK) on success,
  3177. * other if not.
  3178. *
  3179. * Called once after you tell deflate that input stream complete
  3180. * or error happenned. By default - join collected chunks,
  3181. * free memory and fill `results` / `err` properties.
  3182. **/
  3183. Deflate.prototype.onEnd = function(status) {
  3184. // On success - join
  3185. if (status === Z_OK) {
  3186. if (this.options.to === 'string') {
  3187. this.result = this.chunks.join('');
  3188. } else {
  3189. this.result = utils.flattenChunks(this.chunks);
  3190. }
  3191. }
  3192. this.chunks = [];
  3193. this.err = status;
  3194. this.msg = this.strm.msg;
  3195. };
  3196.  
  3197.  
  3198. /**
  3199. * deflate(data[, options]) -> Uint8Array|Array|String
  3200. * - data (Uint8Array|Array|String): input data to compress.
  3201. * - options (Object): zlib deflate options.
  3202. *
  3203. * Compress `data` with deflate alrorythm and `options`.
  3204. *
  3205. * Supported options are:
  3206. *
  3207. * - level
  3208. * - windowBits
  3209. * - memLevel
  3210. * - strategy
  3211. *
  3212. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3213. * for more information on these.
  3214. *
  3215. * Sugar (options):
  3216. *
  3217. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  3218. * negative windowBits implicitly.
  3219. * - `to` (String) - if equal to 'string', then result will be "binary string"
  3220. * (each char code [0..255])
  3221. *
  3222. * ##### Example:
  3223. *
  3224. * ```javascript
  3225. * var pako = require('pako')
  3226. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  3227. *
  3228. * console.log(pako.deflate(data));
  3229. * ```
  3230. **/
  3231. function deflate(input, options) {
  3232. var deflator = new Deflate(options);
  3233.  
  3234. deflator.push(input, true);
  3235.  
  3236. // That will never happens, if you don't cheat with options :)
  3237. if (deflator.err) { throw deflator.msg; }
  3238.  
  3239. return deflator.result;
  3240. }
  3241.  
  3242.  
  3243. /**
  3244. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  3245. * - data (Uint8Array|Array|String): input data to compress.
  3246. * - options (Object): zlib deflate options.
  3247. *
  3248. * The same as [[deflate]], but creates raw data, without wrapper
  3249. * (header and adler32 crc).
  3250. **/
  3251. function deflateRaw(input, options) {
  3252. options = options || {};
  3253. options.raw = true;
  3254. return deflate(input, options);
  3255. }
  3256.  
  3257.  
  3258. /**
  3259. * gzip(data[, options]) -> Uint8Array|Array|String
  3260. * - data (Uint8Array|Array|String): input data to compress.
  3261. * - options (Object): zlib deflate options.
  3262. *
  3263. * The same as [[deflate]], but create gzip wrapper instead of
  3264. * deflate one.
  3265. **/
  3266. function gzip(input, options) {
  3267. options = options || {};
  3268. options.gzip = true;
  3269. return deflate(input, options);
  3270. }
  3271.  
  3272.  
  3273. exports.Deflate = Deflate;
  3274. exports.deflate = deflate;
  3275. exports.deflateRaw = deflateRaw;
  3276. exports.gzip = gzip;
  3277. },{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(_dereq_,module,exports){
  3278. 'use strict';
  3279.  
  3280.  
  3281. var zlib_inflate = _dereq_('./zlib/inflate.js');
  3282. var utils = _dereq_('./utils/common');
  3283. var strings = _dereq_('./utils/strings');
  3284. var c = _dereq_('./zlib/constants');
  3285. var msg = _dereq_('./zlib/messages');
  3286. var zstream = _dereq_('./zlib/zstream');
  3287. var gzheader = _dereq_('./zlib/gzheader');
  3288.  
  3289.  
  3290. /**
  3291. * class Inflate
  3292. *
  3293. * Generic JS-style wrapper for zlib calls. If you don't need
  3294. * streaming behaviour - use more simple functions: [[inflate]]
  3295. * and [[inflateRaw]].
  3296. **/
  3297.  
  3298. /* internal
  3299. * inflate.chunks -> Array
  3300. *
  3301. * Chunks of output data, if [[Inflate#onData]] not overriden.
  3302. **/
  3303.  
  3304. /**
  3305. * Inflate.result -> Uint8Array|Array|String
  3306. *
  3307. * Uncompressed result, generated by default [[Inflate#onData]]
  3308. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  3309. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  3310. **/
  3311.  
  3312. /**
  3313. * Inflate.err -> Number
  3314. *
  3315. * Error code after inflate finished. 0 (Z_OK) on success.
  3316. * Should be checked if broken data possible.
  3317. **/
  3318.  
  3319. /**
  3320. * Inflate.msg -> String
  3321. *
  3322. * Error message, if [[Inflate.err]] != 0
  3323. **/
  3324.  
  3325.  
  3326. /**
  3327. * new Inflate(options)
  3328. * - options (Object): zlib inflate options.
  3329. *
  3330. * Creates new inflator instance with specified params. Throws exception
  3331. * on bad params. Supported options:
  3332. *
  3333. * - `windowBits`
  3334. *
  3335. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3336. * for more information on these.
  3337. *
  3338. * Additional options, for internal needs:
  3339. *
  3340. * - `chunkSize` - size of generated data chunks (16K by default)
  3341. * - `raw` (Boolean) - do raw inflate
  3342. * - `to` (String) - if equal to 'string', then result will be converted
  3343. * from utf8 to utf16 (javascript) string. When string output requested,
  3344. * chunk length can differ from `chunkSize`, depending on content.
  3345. *
  3346. * By default, when no options set, autodetect deflate/gzip data format via
  3347. * wrapper header.
  3348. *
  3349. * ##### Example:
  3350. *
  3351. * ```javascript
  3352. * var pako = require('pako')
  3353. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  3354. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  3355. *
  3356. * var inflate = new pako.Inflate({ level: 3});
  3357. *
  3358. * inflate.push(chunk1, false);
  3359. * inflate.push(chunk2, true); // true -> last chunk
  3360. *
  3361. * if (inflate.err) { throw new Error(inflate.err); }
  3362. *
  3363. * console.log(inflate.result);
  3364. * ```
  3365. **/
  3366. var Inflate = function(options) {
  3367.  
  3368. this.options = utils.assign({
  3369. chunkSize: 16384,
  3370. windowBits: 0,
  3371. to: ''
  3372. }, options || {});
  3373.  
  3374. var opt = this.options;
  3375.  
  3376. // Force window size for `raw` data, if not set directly,
  3377. // because we have no header for autodetect.
  3378. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  3379. opt.windowBits = -opt.windowBits;
  3380. if (opt.windowBits === 0) { opt.windowBits = -15; }
  3381. }
  3382.  
  3383. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  3384. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  3385. !(options && options.windowBits)) {
  3386. opt.windowBits += 32;
  3387. }
  3388.  
  3389. // Gzip header has no info about windows size, we can do autodetect only
  3390. // for deflate. So, if window size not set, force it to max when gzip possible
  3391. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  3392. // bit 3 (16) -> gzipped data
  3393. // bit 4 (32) -> autodetect gzip/deflate
  3394. if ((opt.windowBits & 15) === 0) {
  3395. opt.windowBits |= 15;
  3396. }
  3397. }
  3398.  
  3399. this.err = 0; // error code, if happens (0 = Z_OK)
  3400. this.msg = ''; // error message
  3401. this.ended = false; // used to avoid multiple onEnd() calls
  3402. this.chunks = []; // chunks of compressed data
  3403.  
  3404. this.strm = new zstream();
  3405. this.strm.avail_out = 0;
  3406.  
  3407. var status = zlib_inflate.inflateInit2(
  3408. this.strm,
  3409. opt.windowBits
  3410. );
  3411.  
  3412. if (status !== c.Z_OK) {
  3413. throw new Error(msg[status]);
  3414. }
  3415.  
  3416. this.header = new gzheader();
  3417.  
  3418. zlib_inflate.inflateGetHeader(this.strm, this.header);
  3419. };
  3420.  
  3421. /**
  3422. * Inflate#push(data[, mode]) -> Boolean
  3423. * - data (Uint8Array|Array|String): input data
  3424. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  3425. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  3426. *
  3427. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  3428. * new output chunks. Returns `true` on success. The last data block must have
  3429. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  3430. * [[Inflate#onEnd]].
  3431. *
  3432. * On fail call [[Inflate#onEnd]] with error code and return false.
  3433. *
  3434. * We strongly recommend to use `Uint8Array` on input for best speed (output
  3435. * format is detected automatically). Also, don't skip last param and always
  3436. * use the same type in your code (boolean or number). That will improve JS speed.
  3437. *
  3438. * For regular `Array`-s make sure all elements are [0..255].
  3439. *
  3440. * ##### Example
  3441. *
  3442. * ```javascript
  3443. * push(chunk, false); // push one of data chunks
  3444. * ...
  3445. * push(chunk, true); // push last chunk
  3446. * ```
  3447. **/
  3448. Inflate.prototype.push = function(data, mode) {
  3449. var strm = this.strm;
  3450. var chunkSize = this.options.chunkSize;
  3451. var status, _mode;
  3452. var next_out_utf8, tail, utf8str;
  3453.  
  3454. if (this.ended) { return false; }
  3455. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  3456.  
  3457. // Convert data if needed
  3458. if (typeof data === 'string') {
  3459. // Only binary strings can be decompressed on practice
  3460. strm.input = strings.binstring2buf(data);
  3461. } else {
  3462. strm.input = data;
  3463. }
  3464.  
  3465. strm.next_in = 0;
  3466. strm.avail_in = strm.input.length;
  3467.  
  3468. do {
  3469. if (strm.avail_out === 0) {
  3470. strm.output = new utils.Buf8(chunkSize);
  3471. strm.next_out = 0;
  3472. strm.avail_out = chunkSize;
  3473. }
  3474.  
  3475. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  3476.  
  3477. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  3478. this.onEnd(status);
  3479. this.ended = true;
  3480. return false;
  3481. }
  3482.  
  3483. if (strm.next_out) {
  3484. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  3485.  
  3486. if (this.options.to === 'string') {
  3487.  
  3488. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  3489.  
  3490. tail = strm.next_out - next_out_utf8;
  3491. utf8str = strings.buf2string(strm.output, next_out_utf8);
  3492.  
  3493. // move tail
  3494. strm.next_out = tail;
  3495. strm.avail_out = chunkSize - tail;
  3496. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  3497.  
  3498. this.onData(utf8str);
  3499.  
  3500. } else {
  3501. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  3502. }
  3503. }
  3504. }
  3505. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  3506.  
  3507. if (status === c.Z_STREAM_END) {
  3508. _mode = c.Z_FINISH;
  3509. }
  3510. // Finalize on the last chunk.
  3511. if (_mode === c.Z_FINISH) {
  3512. status = zlib_inflate.inflateEnd(this.strm);
  3513. this.onEnd(status);
  3514. this.ended = true;
  3515. return status === c.Z_OK;
  3516. }
  3517.  
  3518. return true;
  3519. };
  3520.  
  3521.  
  3522. /**
  3523. * Inflate#onData(chunk) -> Void
  3524. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  3525. * on js engine support. When string output requested, each chunk
  3526. * will be string.
  3527. *
  3528. * By default, stores data blocks in `chunks[]` property and glue
  3529. * those in `onEnd`. Override this handler, if you need another behaviour.
  3530. **/
  3531. Inflate.prototype.onData = function(chunk) {
  3532. this.chunks.push(chunk);
  3533. };
  3534.  
  3535.  
  3536. /**
  3537. * Inflate#onEnd(status) -> Void
  3538. * - status (Number): inflate status. 0 (Z_OK) on success,
  3539. * other if not.
  3540. *
  3541. * Called once after you tell inflate that input stream complete
  3542. * or error happenned. By default - join collected chunks,
  3543. * free memory and fill `results` / `err` properties.
  3544. **/
  3545. Inflate.prototype.onEnd = function(status) {
  3546. // On success - join
  3547. if (status === c.Z_OK) {
  3548. if (this.options.to === 'string') {
  3549. // Glue & convert here, until we teach pako to send
  3550. // utf8 alligned strings to onData
  3551. this.result = this.chunks.join('');
  3552. } else {
  3553. this.result = utils.flattenChunks(this.chunks);
  3554. }
  3555. }
  3556. this.chunks = [];
  3557. this.err = status;
  3558. this.msg = this.strm.msg;
  3559. };
  3560.  
  3561.  
  3562. /**
  3563. * inflate(data[, options]) -> Uint8Array|Array|String
  3564. * - data (Uint8Array|Array|String): input data to decompress.
  3565. * - options (Object): zlib inflate options.
  3566. *
  3567. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  3568. * format via wrapper header by default. That's why we don't provide
  3569. * separate `ungzip` method.
  3570. *
  3571. * Supported options are:
  3572. *
  3573. * - windowBits
  3574. *
  3575. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3576. * for more information.
  3577. *
  3578. * Sugar (options):
  3579. *
  3580. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  3581. * negative windowBits implicitly.
  3582. * - `to` (String) - if equal to 'string', then result will be converted
  3583. * from utf8 to utf16 (javascript) string. When string output requested,
  3584. * chunk length can differ from `chunkSize`, depending on content.
  3585. *
  3586. *
  3587. * ##### Example:
  3588. *
  3589. * ```javascript
  3590. * var pako = require('pako')
  3591. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  3592. * , output;
  3593. *
  3594. * try {
  3595. * output = pako.inflate(input);
  3596. * } catch (err)
  3597. * console.log(err);
  3598. * }
  3599. * ```
  3600. **/
  3601. function inflate(input, options) {
  3602. var inflator = new Inflate(options);
  3603.  
  3604. inflator.push(input, true);
  3605.  
  3606. // That will never happens, if you don't cheat with options :)
  3607. if (inflator.err) { throw inflator.msg; }
  3608.  
  3609. return inflator.result;
  3610. }
  3611.  
  3612.  
  3613. /**
  3614. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  3615. * - data (Uint8Array|Array|String): input data to decompress.
  3616. * - options (Object): zlib inflate options.
  3617. *
  3618. * The same as [[inflate]], but creates raw data, without wrapper
  3619. * (header and adler32 crc).
  3620. **/
  3621. function inflateRaw(input, options) {
  3622. options = options || {};
  3623. options.raw = true;
  3624. return inflate(input, options);
  3625. }
  3626.  
  3627.  
  3628. /**
  3629. * ungzip(data[, options]) -> Uint8Array|Array|String
  3630. * - data (Uint8Array|Array|String): input data to decompress.
  3631. * - options (Object): zlib inflate options.
  3632. *
  3633. * Just shortcut to [[inflate]], because it autodetects format
  3634. * by header.content. Done for convenience.
  3635. **/
  3636.  
  3637.  
  3638. exports.Inflate = Inflate;
  3639. exports.inflate = inflate;
  3640. exports.inflateRaw = inflateRaw;
  3641. exports.ungzip = inflate;
  3642.  
  3643. },{"./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){
  3644. 'use strict';
  3645.  
  3646.  
  3647. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  3648. (typeof Uint16Array !== 'undefined') &&
  3649. (typeof Int32Array !== 'undefined');
  3650.  
  3651.  
  3652. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  3653. var sources = Array.prototype.slice.call(arguments, 1);
  3654. while (sources.length) {
  3655. var source = sources.shift();
  3656. if (!source) { continue; }
  3657.  
  3658. if (typeof(source) !== 'object') {
  3659. throw new TypeError(source + 'must be non-object');
  3660. }
  3661.  
  3662. for (var p in source) {
  3663. if (source.hasOwnProperty(p)) {
  3664. obj[p] = source[p];
  3665. }
  3666. }
  3667. }
  3668.  
  3669. return obj;
  3670. };
  3671.  
  3672.  
  3673. // reduce buffer size, avoiding mem copy
  3674. exports.shrinkBuf = function (buf, size) {
  3675. if (buf.length === size) { return buf; }
  3676. if (buf.subarray) { return buf.subarray(0, size); }
  3677. buf.length = size;
  3678. return buf;
  3679. };
  3680.  
  3681.  
  3682. var fnTyped = {
  3683. arraySet: function (dest, src, src_offs, len, dest_offs) {
  3684. if (src.subarray && dest.subarray) {
  3685. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  3686. return;
  3687. }
  3688. // Fallback to ordinary array
  3689. for(var i=0; i<len; i++) {
  3690. dest[dest_offs + i] = src[src_offs + i];
  3691. }
  3692. },
  3693. // Join array of chunks to single array.
  3694. flattenChunks: function(chunks) {
  3695. var i, l, len, pos, chunk, result;
  3696.  
  3697. // calculate data length
  3698. len = 0;
  3699. for (i=0, l=chunks.length; i<l; i++) {
  3700. len += chunks[i].length;
  3701. }
  3702.  
  3703. // join chunks
  3704. result = new Uint8Array(len);
  3705. pos = 0;
  3706. for (i=0, l=chunks.length; i<l; i++) {
  3707. chunk = chunks[i];
  3708. result.set(chunk, pos);
  3709. pos += chunk.length;
  3710. }
  3711.  
  3712. return result;
  3713. }
  3714. };
  3715.  
  3716. var fnUntyped = {
  3717. arraySet: function (dest, src, src_offs, len, dest_offs) {
  3718. for(var i=0; i<len; i++) {
  3719. dest[dest_offs + i] = src[src_offs + i];
  3720. }
  3721. },
  3722. // Join array of chunks to single array.
  3723. flattenChunks: function(chunks) {
  3724. return [].concat.apply([], chunks);
  3725. }
  3726. };
  3727.  
  3728.  
  3729. // Enable/Disable typed arrays use, for testing
  3730. //
  3731. exports.setTyped = function (on) {
  3732. if (on) {
  3733. exports.Buf8 = Uint8Array;
  3734. exports.Buf16 = Uint16Array;
  3735. exports.Buf32 = Int32Array;
  3736. exports.assign(exports, fnTyped);
  3737. } else {
  3738. exports.Buf8 = Array;
  3739. exports.Buf16 = Array;
  3740. exports.Buf32 = Array;
  3741. exports.assign(exports, fnUntyped);
  3742. }
  3743. };
  3744.  
  3745. exports.setTyped(TYPED_OK);
  3746. },{}],28:[function(_dereq_,module,exports){
  3747. // String encode/decode helpers
  3748. 'use strict';
  3749.  
  3750.  
  3751. var utils = _dereq_('./common');
  3752.  
  3753.  
  3754. // Quick check if we can use fast array to bin string conversion
  3755. //
  3756. // - apply(Array) can fail on Android 2.2
  3757. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  3758. //
  3759. var STR_APPLY_OK = true;
  3760. var STR_APPLY_UIA_OK = true;
  3761.  
  3762. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  3763. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  3764.  
  3765.  
  3766. // Table with utf8 lengths (calculated by first byte of sequence)
  3767. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  3768. // because max possible codepoint is 0x10ffff
  3769. var _utf8len = new utils.Buf8(256);
  3770. for (var i=0; i<256; i++) {
  3771. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  3772. }
  3773. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  3774.  
  3775.  
  3776. // convert string to array (typed, when possible)
  3777. exports.string2buf = function (str) {
  3778. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  3779.  
  3780. // count binary size
  3781. for (m_pos = 0; m_pos < str_len; m_pos++) {
  3782. c = str.charCodeAt(m_pos);
  3783. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3784. c2 = str.charCodeAt(m_pos+1);
  3785. if ((c2 & 0xfc00) === 0xdc00) {
  3786. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3787. m_pos++;
  3788. }
  3789. }
  3790. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  3791. }
  3792.  
  3793. // allocate buffer
  3794. buf = new utils.Buf8(buf_len);
  3795.  
  3796. // convert
  3797. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  3798. c = str.charCodeAt(m_pos);
  3799. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3800. c2 = str.charCodeAt(m_pos+1);
  3801. if ((c2 & 0xfc00) === 0xdc00) {
  3802. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3803. m_pos++;
  3804. }
  3805. }
  3806. if (c < 0x80) {
  3807. /* one byte */
  3808. buf[i++] = c;
  3809. } else if (c < 0x800) {
  3810. /* two bytes */
  3811. buf[i++] = 0xC0 | (c >>> 6);
  3812. buf[i++] = 0x80 | (c & 0x3f);
  3813. } else if (c < 0x10000) {
  3814. /* three bytes */
  3815. buf[i++] = 0xE0 | (c >>> 12);
  3816. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3817. buf[i++] = 0x80 | (c & 0x3f);
  3818. } else {
  3819. /* four bytes */
  3820. buf[i++] = 0xf0 | (c >>> 18);
  3821. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  3822. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3823. buf[i++] = 0x80 | (c & 0x3f);
  3824. }
  3825. }
  3826.  
  3827. return buf;
  3828. };
  3829.  
  3830. // Helper (used in 2 places)
  3831. function buf2binstring(buf, len) {
  3832. // use fallback for big arrays to avoid stack overflow
  3833. if (len < 65537) {
  3834. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  3835. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  3836. }
  3837. }
  3838.  
  3839. var result = '';
  3840. for(var i=0; i < len; i++) {
  3841. result += String.fromCharCode(buf[i]);
  3842. }
  3843. return result;
  3844. }
  3845.  
  3846.  
  3847. // Convert byte array to binary string
  3848. exports.buf2binstring = function(buf) {
  3849. return buf2binstring(buf, buf.length);
  3850. };
  3851.  
  3852.  
  3853. // Convert binary string (typed, when possible)
  3854. exports.binstring2buf = function(str) {
  3855. var buf = new utils.Buf8(str.length);
  3856. for(var i=0, len=buf.length; i < len; i++) {
  3857. buf[i] = str.charCodeAt(i);
  3858. }
  3859. return buf;
  3860. };
  3861.  
  3862.  
  3863. // convert array to string
  3864. exports.buf2string = function (buf, max) {
  3865. var i, out, c, c_len;
  3866. var len = max || buf.length;
  3867.  
  3868. // Reserve max possible length (2 words per char)
  3869. // NB: by unknown reasons, Array is significantly faster for
  3870. // String.fromCharCode.apply than Uint16Array.
  3871. var utf16buf = new Array(len*2);
  3872.  
  3873. for (out=0, i=0; i<len;) {
  3874. c = buf[i++];
  3875. // quick process ascii
  3876. if (c < 0x80) { utf16buf[out++] = c; continue; }
  3877.  
  3878. c_len = _utf8len[c];
  3879. // skip 5 & 6 byte codes
  3880. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  3881.  
  3882. // apply mask on first byte
  3883. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  3884. // join the rest
  3885. while (c_len > 1 && i < len) {
  3886. c = (c << 6) | (buf[i++] & 0x3f);
  3887. c_len--;
  3888. }
  3889.  
  3890. // terminated by end of string?
  3891. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  3892.  
  3893. if (c < 0x10000) {
  3894. utf16buf[out++] = c;
  3895. } else {
  3896. c -= 0x10000;
  3897. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  3898. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  3899. }
  3900. }
  3901.  
  3902. return buf2binstring(utf16buf, out);
  3903. };
  3904.  
  3905.  
  3906. // Calculate max possible position in utf8 buffer,
  3907. // that will not break sequence. If that's not possible
  3908. // - (very small limits) return max size as is.
  3909. //
  3910. // buf[] - utf8 bytes array
  3911. // max - length limit (mandatory);
  3912. exports.utf8border = function(buf, max) {
  3913. var pos;
  3914.  
  3915. max = max || buf.length;
  3916. if (max > buf.length) { max = buf.length; }
  3917.  
  3918. // go back from last position, until start of sequence found
  3919. pos = max-1;
  3920. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  3921.  
  3922. // Fuckup - very small and broken sequence,
  3923. // return max, because we should return something anyway.
  3924. if (pos < 0) { return max; }
  3925.  
  3926. // If we came to start of buffer - that means vuffer is too small,
  3927. // return max too.
  3928. if (pos === 0) { return max; }
  3929.  
  3930. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  3931. };
  3932.  
  3933. },{"./common":27}],29:[function(_dereq_,module,exports){
  3934. 'use strict';
  3935.  
  3936. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  3937. // It doesn't worth to make additional optimizationa as in original.
  3938. // Small size is preferable.
  3939.  
  3940. function adler32(adler, buf, len, pos) {
  3941. var s1 = (adler & 0xffff) |0
  3942. , s2 = ((adler >>> 16) & 0xffff) |0
  3943. , n = 0;
  3944.  
  3945. while (len !== 0) {
  3946. // Set limit ~ twice less than 5552, to keep
  3947. // s2 in 31-bits, because we force signed ints.
  3948. // in other case %= will fail.
  3949. n = len > 2000 ? 2000 : len;
  3950. len -= n;
  3951.  
  3952. do {
  3953. s1 = (s1 + buf[pos++]) |0;
  3954. s2 = (s2 + s1) |0;
  3955. } while (--n);
  3956.  
  3957. s1 %= 65521;
  3958. s2 %= 65521;
  3959. }
  3960.  
  3961. return (s1 | (s2 << 16)) |0;
  3962. }
  3963.  
  3964.  
  3965. module.exports = adler32;
  3966. },{}],30:[function(_dereq_,module,exports){
  3967. module.exports = {
  3968.  
  3969. /* Allowed flush values; see deflate() and inflate() below for details */
  3970. Z_NO_FLUSH: 0,
  3971. Z_PARTIAL_FLUSH: 1,
  3972. Z_SYNC_FLUSH: 2,
  3973. Z_FULL_FLUSH: 3,
  3974. Z_FINISH: 4,
  3975. Z_BLOCK: 5,
  3976. Z_TREES: 6,
  3977.  
  3978. /* Return codes for the compression/decompression functions. Negative values
  3979. * are errors, positive values are used for special but normal events.
  3980. */
  3981. Z_OK: 0,
  3982. Z_STREAM_END: 1,
  3983. Z_NEED_DICT: 2,
  3984. Z_ERRNO: -1,
  3985. Z_STREAM_ERROR: -2,
  3986. Z_DATA_ERROR: -3,
  3987. //Z_MEM_ERROR: -4,
  3988. Z_BUF_ERROR: -5,
  3989. //Z_VERSION_ERROR: -6,
  3990.  
  3991. /* compression levels */
  3992. Z_NO_COMPRESSION: 0,
  3993. Z_BEST_SPEED: 1,
  3994. Z_BEST_COMPRESSION: 9,
  3995. Z_DEFAULT_COMPRESSION: -1,
  3996.  
  3997.  
  3998. Z_FILTERED: 1,
  3999. Z_HUFFMAN_ONLY: 2,
  4000. Z_RLE: 3,
  4001. Z_FIXED: 4,
  4002. Z_DEFAULT_STRATEGY: 0,
  4003.  
  4004. /* Possible values of the data_type field (though see inflate()) */
  4005. Z_BINARY: 0,
  4006. Z_TEXT: 1,
  4007. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  4008. Z_UNKNOWN: 2,
  4009.  
  4010. /* The deflate compression method */
  4011. Z_DEFLATED: 8
  4012. //Z_NULL: null // Use -1 or null inline, depending on var type
  4013. };
  4014. },{}],31:[function(_dereq_,module,exports){
  4015. 'use strict';
  4016.  
  4017. // Note: we can't get significant speed boost here.
  4018. // So write code to minimize size - no pregenerated tables
  4019. // and array tools dependencies.
  4020.  
  4021.  
  4022. // Use ordinary array, since untyped makes no boost here
  4023. function makeTable() {
  4024. var c, table = [];
  4025.  
  4026. for(var n =0; n < 256; n++){
  4027. c = n;
  4028. for(var k =0; k < 8; k++){
  4029. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  4030. }
  4031. table[n] = c;
  4032. }
  4033.  
  4034. return table;
  4035. }
  4036.  
  4037. // Create table on load. Just 255 signed longs. Not a problem.
  4038. var crcTable = makeTable();
  4039.  
  4040.  
  4041. function crc32(crc, buf, len, pos) {
  4042. var t = crcTable
  4043. , end = pos + len;
  4044.  
  4045. crc = crc ^ (-1);
  4046.  
  4047. for (var i = pos; i < end; i++ ) {
  4048. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  4049. }
  4050.  
  4051. return (crc ^ (-1)); // >>> 0;
  4052. }
  4053.  
  4054.  
  4055. module.exports = crc32;
  4056. },{}],32:[function(_dereq_,module,exports){
  4057. 'use strict';
  4058.  
  4059. var utils = _dereq_('../utils/common');
  4060. var trees = _dereq_('./trees');
  4061. var adler32 = _dereq_('./adler32');
  4062. var crc32 = _dereq_('./crc32');
  4063. var msg = _dereq_('./messages');
  4064.  
  4065. /* Public constants ==========================================================*/
  4066. /* ===========================================================================*/
  4067.  
  4068.  
  4069. /* Allowed flush values; see deflate() and inflate() below for details */
  4070. var Z_NO_FLUSH = 0;
  4071. var Z_PARTIAL_FLUSH = 1;
  4072. //var Z_SYNC_FLUSH = 2;
  4073. var Z_FULL_FLUSH = 3;
  4074. var Z_FINISH = 4;
  4075. var Z_BLOCK = 5;
  4076. //var Z_TREES = 6;
  4077.  
  4078.  
  4079. /* Return codes for the compression/decompression functions. Negative values
  4080. * are errors, positive values are used for special but normal events.
  4081. */
  4082. var Z_OK = 0;
  4083. var Z_STREAM_END = 1;
  4084. //var Z_NEED_DICT = 2;
  4085. //var Z_ERRNO = -1;
  4086. var Z_STREAM_ERROR = -2;
  4087. var Z_DATA_ERROR = -3;
  4088. //var Z_MEM_ERROR = -4;
  4089. var Z_BUF_ERROR = -5;
  4090. //var Z_VERSION_ERROR = -6;
  4091.  
  4092.  
  4093. /* compression levels */
  4094. //var Z_NO_COMPRESSION = 0;
  4095. //var Z_BEST_SPEED = 1;
  4096. //var Z_BEST_COMPRESSION = 9;
  4097. var Z_DEFAULT_COMPRESSION = -1;
  4098.  
  4099.  
  4100. var Z_FILTERED = 1;
  4101. var Z_HUFFMAN_ONLY = 2;
  4102. var Z_RLE = 3;
  4103. var Z_FIXED = 4;
  4104. var Z_DEFAULT_STRATEGY = 0;
  4105.  
  4106. /* Possible values of the data_type field (though see inflate()) */
  4107. //var Z_BINARY = 0;
  4108. //var Z_TEXT = 1;
  4109. //var Z_ASCII = 1; // = Z_TEXT
  4110. var Z_UNKNOWN = 2;
  4111.  
  4112.  
  4113. /* The deflate compression method */
  4114. var Z_DEFLATED = 8;
  4115.  
  4116. /*============================================================================*/
  4117.  
  4118.  
  4119. var MAX_MEM_LEVEL = 9;
  4120. /* Maximum value for memLevel in deflateInit2 */
  4121. var MAX_WBITS = 15;
  4122. /* 32K LZ77 window */
  4123. var DEF_MEM_LEVEL = 8;
  4124.  
  4125.  
  4126. var LENGTH_CODES = 29;
  4127. /* number of length codes, not counting the special END_BLOCK code */
  4128. var LITERALS = 256;
  4129. /* number of literal bytes 0..255 */
  4130. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  4131. /* number of Literal or Length codes, including the END_BLOCK code */
  4132. var D_CODES = 30;
  4133. /* number of distance codes */
  4134. var BL_CODES = 19;
  4135. /* number of codes used to transfer the bit lengths */
  4136. var HEAP_SIZE = 2*L_CODES + 1;
  4137. /* maximum heap size */
  4138. var MAX_BITS = 15;
  4139. /* All codes must not exceed MAX_BITS bits */
  4140.  
  4141. var MIN_MATCH = 3;
  4142. var MAX_MATCH = 258;
  4143. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  4144.  
  4145. var PRESET_DICT = 0x20;
  4146.  
  4147. var INIT_STATE = 42;
  4148. var EXTRA_STATE = 69;
  4149. var NAME_STATE = 73;
  4150. var COMMENT_STATE = 91;
  4151. var HCRC_STATE = 103;
  4152. var BUSY_STATE = 113;
  4153. var FINISH_STATE = 666;
  4154.  
  4155. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  4156. var BS_BLOCK_DONE = 2; /* block flush performed */
  4157. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  4158. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  4159.  
  4160. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  4161.  
  4162. function err(strm, errorCode) {
  4163. strm.msg = msg[errorCode];
  4164. return errorCode;
  4165. }
  4166.  
  4167. function rank(f) {
  4168. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  4169. }
  4170.  
  4171. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  4172.  
  4173.  
  4174. /* =========================================================================
  4175. * Flush as much pending output as possible. All deflate() output goes
  4176. * through this function so some applications may wish to modify it
  4177. * to avoid allocating a large strm->output buffer and copying into it.
  4178. * (See also read_buf()).
  4179. */
  4180. function flush_pending(strm) {
  4181. var s = strm.state;
  4182.  
  4183. //_tr_flush_bits(s);
  4184. var len = s.pending;
  4185. if (len > strm.avail_out) {
  4186. len = strm.avail_out;
  4187. }
  4188. if (len === 0) { return; }
  4189.  
  4190. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  4191. strm.next_out += len;
  4192. s.pending_out += len;
  4193. strm.total_out += len;
  4194. strm.avail_out -= len;
  4195. s.pending -= len;
  4196. if (s.pending === 0) {
  4197. s.pending_out = 0;
  4198. }
  4199. }
  4200.  
  4201.  
  4202. function flush_block_only (s, last) {
  4203. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  4204. s.block_start = s.strstart;
  4205. flush_pending(s.strm);
  4206. }
  4207.  
  4208.  
  4209. function put_byte(s, b) {
  4210. s.pending_buf[s.pending++] = b;
  4211. }
  4212.  
  4213.  
  4214. /* =========================================================================
  4215. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  4216. * IN assertion: the stream state is correct and there is enough room in
  4217. * pending_buf.
  4218. */
  4219. function putShortMSB(s, b) {
  4220. // put_byte(s, (Byte)(b >> 8));
  4221. // put_byte(s, (Byte)(b & 0xff));
  4222. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  4223. s.pending_buf[s.pending++] = b & 0xff;
  4224. }
  4225.  
  4226.  
  4227. /* ===========================================================================
  4228. * Read a new buffer from the current input stream, update the adler32
  4229. * and total number of bytes read. All deflate() input goes through
  4230. * this function so some applications may wish to modify it to avoid
  4231. * allocating a large strm->input buffer and copying from it.
  4232. * (See also flush_pending()).
  4233. */
  4234. function read_buf(strm, buf, start, size) {
  4235. var len = strm.avail_in;
  4236.  
  4237. if (len > size) { len = size; }
  4238. if (len === 0) { return 0; }
  4239.  
  4240. strm.avail_in -= len;
  4241.  
  4242. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  4243. if (strm.state.wrap === 1) {
  4244. strm.adler = adler32(strm.adler, buf, len, start);
  4245. }
  4246.  
  4247. else if (strm.state.wrap === 2) {
  4248. strm.adler = crc32(strm.adler, buf, len, start);
  4249. }
  4250.  
  4251. strm.next_in += len;
  4252. strm.total_in += len;
  4253.  
  4254. return len;
  4255. }
  4256.  
  4257.  
  4258. /* ===========================================================================
  4259. * Set match_start to the longest match starting at the given string and
  4260. * return its length. Matches shorter or equal to prev_length are discarded,
  4261. * in which case the result is equal to prev_length and match_start is
  4262. * garbage.
  4263. * IN assertions: cur_match is the head of the hash chain for the current
  4264. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  4265. * OUT assertion: the match length is not greater than s->lookahead.
  4266. */
  4267. function longest_match(s, cur_match) {
  4268. var chain_length = s.max_chain_length; /* max hash chain length */
  4269. var scan = s.strstart; /* current string */
  4270. var match; /* matched string */
  4271. var len; /* length of current match */
  4272. var best_len = s.prev_length; /* best match length so far */
  4273. var nice_match = s.nice_match; /* stop if match long enough */
  4274. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  4275. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  4276.  
  4277. var _win = s.window; // shortcut
  4278.  
  4279. var wmask = s.w_mask;
  4280. var prev = s.prev;
  4281.  
  4282. /* Stop when cur_match becomes <= limit. To simplify the code,
  4283. * we prevent matches with the string of window index 0.
  4284. */
  4285.  
  4286. var strend = s.strstart + MAX_MATCH;
  4287. var scan_end1 = _win[scan + best_len - 1];
  4288. var scan_end = _win[scan + best_len];
  4289.  
  4290. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  4291. * It is easy to get rid of this optimization if necessary.
  4292. */
  4293. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  4294.  
  4295. /* Do not waste too much time if we already have a good match: */
  4296. if (s.prev_length >= s.good_match) {
  4297. chain_length >>= 2;
  4298. }
  4299. /* Do not look for matches beyond the end of the input. This is necessary
  4300. * to make deflate deterministic.
  4301. */
  4302. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  4303.  
  4304. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  4305.  
  4306. do {
  4307. // Assert(cur_match < s->strstart, "no future");
  4308. match = cur_match;
  4309.  
  4310. /* Skip to next match if the match length cannot increase
  4311. * or if the match length is less than 2. Note that the checks below
  4312. * for insufficient lookahead only occur occasionally for performance
  4313. * reasons. Therefore uninitialized memory will be accessed, and
  4314. * conditional jumps will be made that depend on those values.
  4315. * However the length of the match is limited to the lookahead, so
  4316. * the output of deflate is not affected by the uninitialized values.
  4317. */
  4318.  
  4319. if (_win[match + best_len] !== scan_end ||
  4320. _win[match + best_len - 1] !== scan_end1 ||
  4321. _win[match] !== _win[scan] ||
  4322. _win[++match] !== _win[scan + 1]) {
  4323. continue;
  4324. }
  4325.  
  4326. /* The check at best_len-1 can be removed because it will be made
  4327. * again later. (This heuristic is not always a win.)
  4328. * It is not necessary to compare scan[2] and match[2] since they
  4329. * are always equal when the other bytes match, given that
  4330. * the hash keys are equal and that HASH_BITS >= 8.
  4331. */
  4332. scan += 2;
  4333. match++;
  4334. // Assert(*scan == *match, "match[2]?");
  4335.  
  4336. /* We check for insufficient lookahead only every 8th comparison;
  4337. * the 256th check will be made at strstart+258.
  4338. */
  4339. do {
  4340. /*jshint noempty:false*/
  4341. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  4342. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  4343. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  4344. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  4345. scan < strend);
  4346.  
  4347. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  4348.  
  4349. len = MAX_MATCH - (strend - scan);
  4350. scan = strend - MAX_MATCH;
  4351.  
  4352. if (len > best_len) {
  4353. s.match_start = cur_match;
  4354. best_len = len;
  4355. if (len >= nice_match) {
  4356. break;
  4357. }
  4358. scan_end1 = _win[scan + best_len - 1];
  4359. scan_end = _win[scan + best_len];
  4360. }
  4361. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  4362.  
  4363. if (best_len <= s.lookahead) {
  4364. return best_len;
  4365. }
  4366. return s.lookahead;
  4367. }
  4368.  
  4369.  
  4370. /* ===========================================================================
  4371. * Fill the window when the lookahead becomes insufficient.
  4372. * Updates strstart and lookahead.
  4373. *
  4374. * IN assertion: lookahead < MIN_LOOKAHEAD
  4375. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  4376. * At least one byte has been read, or avail_in == 0; reads are
  4377. * performed for at least two bytes (required for the zip translate_eol
  4378. * option -- not supported here).
  4379. */
  4380. function fill_window(s) {
  4381. var _w_size = s.w_size;
  4382. var p, n, m, more, str;
  4383.  
  4384. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  4385.  
  4386. do {
  4387. more = s.window_size - s.lookahead - s.strstart;
  4388.  
  4389. // JS ints have 32 bit, block below not needed
  4390. /* Deal with !@#$% 64K limit: */
  4391. //if (sizeof(int) <= 2) {
  4392. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  4393. // more = wsize;
  4394. //
  4395. // } else if (more == (unsigned)(-1)) {
  4396. // /* Very unlikely, but possible on 16 bit machine if
  4397. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  4398. // */
  4399. // more--;
  4400. // }
  4401. //}
  4402.  
  4403.  
  4404. /* If the window is almost full and there is insufficient lookahead,
  4405. * move the upper half to the lower one to make room in the upper half.
  4406. */
  4407. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  4408.  
  4409. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  4410. s.match_start -= _w_size;
  4411. s.strstart -= _w_size;
  4412. /* we now have strstart >= MAX_DIST */
  4413. s.block_start -= _w_size;
  4414.  
  4415. /* Slide the hash table (could be avoided with 32 bit values
  4416. at the expense of memory usage). We slide even when level == 0
  4417. to keep the hash table consistent if we switch back to level > 0
  4418. later. (Using level 0 permanently is not an optimal usage of
  4419. zlib, so we don't care about this pathological case.)
  4420. */
  4421.  
  4422. n = s.hash_size;
  4423. p = n;
  4424. do {
  4425. m = s.head[--p];
  4426. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  4427. } while (--n);
  4428.  
  4429. n = _w_size;
  4430. p = n;
  4431. do {
  4432. m = s.prev[--p];
  4433. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  4434. /* If n is not on any hash chain, prev[n] is garbage but
  4435. * its value will never be used.
  4436. */
  4437. } while (--n);
  4438.  
  4439. more += _w_size;
  4440. }
  4441. if (s.strm.avail_in === 0) {
  4442. break;
  4443. }
  4444.  
  4445. /* If there was no sliding:
  4446. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  4447. * more == window_size - lookahead - strstart
  4448. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  4449. * => more >= window_size - 2*WSIZE + 2
  4450. * In the BIG_MEM or MMAP case (not yet supported),
  4451. * window_size == input_size + MIN_LOOKAHEAD &&
  4452. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  4453. * Otherwise, window_size == 2*WSIZE so more >= 2.
  4454. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  4455. */
  4456. //Assert(more >= 2, "more < 2");
  4457. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  4458. s.lookahead += n;
  4459.  
  4460. /* Initialize the hash value now that we have some input: */
  4461. if (s.lookahead + s.insert >= MIN_MATCH) {
  4462. str = s.strstart - s.insert;
  4463. s.ins_h = s.window[str];
  4464.  
  4465. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  4466. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  4467. //#if MIN_MATCH != 3
  4468. // Call update_hash() MIN_MATCH-3 more times
  4469. //#endif
  4470. while (s.insert) {
  4471. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  4472. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  4473.  
  4474. s.prev[str & s.w_mask] = s.head[s.ins_h];
  4475. s.head[s.ins_h] = str;
  4476. str++;
  4477. s.insert--;
  4478. if (s.lookahead + s.insert < MIN_MATCH) {
  4479. break;
  4480. }
  4481. }
  4482. }
  4483. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  4484. * but this is not important since only literal bytes will be emitted.
  4485. */
  4486.  
  4487. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  4488.  
  4489. /* If the WIN_INIT bytes after the end of the current data have never been
  4490. * written, then zero those bytes in order to avoid memory check reports of
  4491. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  4492. * the longest match routines. Update the high water mark for the next
  4493. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  4494. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  4495. */
  4496. // if (s.high_water < s.window_size) {
  4497. // var curr = s.strstart + s.lookahead;
  4498. // var init = 0;
  4499. //
  4500. // if (s.high_water < curr) {
  4501. // /* Previous high water mark below current data -- zero WIN_INIT
  4502. // * bytes or up to end of window, whichever is less.
  4503. // */
  4504. // init = s.window_size - curr;
  4505. // if (init > WIN_INIT)
  4506. // init = WIN_INIT;
  4507. // zmemzero(s->window + curr, (unsigned)init);
  4508. // s->high_water = curr + init;
  4509. // }
  4510. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  4511. // /* High water mark at or above current data, but below current data
  4512. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  4513. // * to end of window, whichever is less.
  4514. // */
  4515. // init = (ulg)curr + WIN_INIT - s->high_water;
  4516. // if (init > s->window_size - s->high_water)
  4517. // init = s->window_size - s->high_water;
  4518. // zmemzero(s->window + s->high_water, (unsigned)init);
  4519. // s->high_water += init;
  4520. // }
  4521. // }
  4522. //
  4523. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  4524. // "not enough room for search");
  4525. }
  4526.  
  4527. /* ===========================================================================
  4528. * Copy without compression as much as possible from the input stream, return
  4529. * the current block state.
  4530. * This function does not insert new strings in the dictionary since
  4531. * uncompressible data is probably not useful. This function is used
  4532. * only for the level=0 compression option.
  4533. * NOTE: this function should be optimized to avoid extra copying from
  4534. * window to pending_buf.
  4535. */
  4536. function deflate_stored(s, flush) {
  4537. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  4538. * to pending_buf_size, and each stored block has a 5 byte header:
  4539. */
  4540. var max_block_size = 0xffff;
  4541.  
  4542. if (max_block_size > s.pending_buf_size - 5) {
  4543. max_block_size = s.pending_buf_size - 5;
  4544. }
  4545.  
  4546. /* Copy as much as possible from input to output: */
  4547. for (;;) {
  4548. /* Fill the window as much as possible: */
  4549. if (s.lookahead <= 1) {
  4550.  
  4551. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  4552. // s->block_start >= (long)s->w_size, "slide too late");
  4553. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  4554. // s.block_start >= s.w_size)) {
  4555. // throw new Error("slide too late");
  4556. // }
  4557.  
  4558. fill_window(s);
  4559. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  4560. return BS_NEED_MORE;
  4561. }
  4562.  
  4563. if (s.lookahead === 0) {
  4564. break;
  4565. }
  4566. /* flush the current block */
  4567. }
  4568. //Assert(s->block_start >= 0L, "block gone");
  4569. // if (s.block_start < 0) throw new Error("block gone");
  4570.  
  4571. s.strstart += s.lookahead;
  4572. s.lookahead = 0;
  4573.  
  4574. /* Emit a stored block if pending_buf will be full: */
  4575. var max_start = s.block_start + max_block_size;
  4576.  
  4577. if (s.strstart === 0 || s.strstart >= max_start) {
  4578. /* strstart == 0 is possible when wraparound on 16-bit machine */
  4579. s.lookahead = s.strstart - max_start;
  4580. s.strstart = max_start;
  4581. /*** FLUSH_BLOCK(s, 0); ***/
  4582. flush_block_only(s, false);
  4583. if (s.strm.avail_out === 0) {
  4584. return BS_NEED_MORE;
  4585. }
  4586. /***/
  4587.  
  4588.  
  4589. }
  4590. /* Flush if we may have to slide, otherwise block_start may become
  4591. * negative and the data will be gone:
  4592. */
  4593. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  4594. /*** FLUSH_BLOCK(s, 0); ***/
  4595. flush_block_only(s, false);
  4596. if (s.strm.avail_out === 0) {
  4597. return BS_NEED_MORE;
  4598. }
  4599. /***/
  4600. }
  4601. }
  4602.  
  4603. s.insert = 0;
  4604.  
  4605. if (flush === Z_FINISH) {
  4606. /*** FLUSH_BLOCK(s, 1); ***/
  4607. flush_block_only(s, true);
  4608. if (s.strm.avail_out === 0) {
  4609. return BS_FINISH_STARTED;
  4610. }
  4611. /***/
  4612. return BS_FINISH_DONE;
  4613. }
  4614.  
  4615. if (s.strstart > s.block_start) {
  4616. /*** FLUSH_BLOCK(s, 0); ***/
  4617. flush_block_only(s, false);
  4618. if (s.strm.avail_out === 0) {
  4619. return BS_NEED_MORE;
  4620. }
  4621. /***/
  4622. }
  4623.  
  4624. return BS_NEED_MORE;
  4625. }
  4626.  
  4627. /* ===========================================================================
  4628. * Compress as much as possible from the input stream, return the current
  4629. * block state.
  4630. * This function does not perform lazy evaluation of matches and inserts
  4631. * new strings in the dictionary only for unmatched strings or for short
  4632. * matches. It is used only for the fast compression options.
  4633. */
  4634. function deflate_fast(s, flush) {
  4635. var hash_head; /* head of the hash chain */
  4636. var bflush; /* set if current block must be flushed */
  4637.  
  4638. for (;;) {
  4639. /* Make sure that we always have enough lookahead, except
  4640. * at the end of the input file. We need MAX_MATCH bytes
  4641. * for the next match, plus MIN_MATCH bytes to insert the
  4642. * string following the next match.
  4643. */
  4644. if (s.lookahead < MIN_LOOKAHEAD) {
  4645. fill_window(s);
  4646. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  4647. return BS_NEED_MORE;
  4648. }
  4649. if (s.lookahead === 0) {
  4650. break; /* flush the current block */
  4651. }
  4652. }
  4653.  
  4654. /* Insert the string window[strstart .. strstart+2] in the
  4655. * dictionary, and set hash_head to the head of the hash chain:
  4656. */
  4657. hash_head = 0/*NIL*/;
  4658. if (s.lookahead >= MIN_MATCH) {
  4659. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4660. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4661. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4662. s.head[s.ins_h] = s.strstart;
  4663. /***/
  4664. }
  4665.  
  4666. /* Find the longest match, discarding those <= prev_length.
  4667. * At this point we have always match_length < MIN_MATCH
  4668. */
  4669. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  4670. /* To simplify the code, we prevent matches with the string
  4671. * of window index 0 (in particular we have to avoid a match
  4672. * of the string with itself at the start of the input file).
  4673. */
  4674. s.match_length = longest_match(s, hash_head);
  4675. /* longest_match() sets match_start */
  4676. }
  4677. if (s.match_length >= MIN_MATCH) {
  4678. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  4679.  
  4680. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  4681. s.match_length - MIN_MATCH, bflush); ***/
  4682. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  4683.  
  4684. s.lookahead -= s.match_length;
  4685.  
  4686. /* Insert new strings in the hash table only if the match length
  4687. * is not too large. This saves time but degrades compression.
  4688. */
  4689. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  4690. s.match_length--; /* string at strstart already in table */
  4691. do {
  4692. s.strstart++;
  4693. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4694. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4695. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4696. s.head[s.ins_h] = s.strstart;
  4697. /***/
  4698. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  4699. * always MIN_MATCH bytes ahead.
  4700. */
  4701. } while (--s.match_length !== 0);
  4702. s.strstart++;
  4703. } else
  4704. {
  4705. s.strstart += s.match_length;
  4706. s.match_length = 0;
  4707. s.ins_h = s.window[s.strstart];
  4708. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  4709. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  4710.  
  4711. //#if MIN_MATCH != 3
  4712. // Call UPDATE_HASH() MIN_MATCH-3 more times
  4713. //#endif
  4714. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  4715. * matter since it will be recomputed at next deflate call.
  4716. */
  4717. }
  4718. } else {
  4719. /* No match, output a literal byte */
  4720. //Tracevv((stderr,"%c", s.window[s.strstart]));
  4721. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  4722. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  4723.  
  4724. s.lookahead--;
  4725. s.strstart++;
  4726. }
  4727. if (bflush) {
  4728. /*** FLUSH_BLOCK(s, 0); ***/
  4729. flush_block_only(s, false);
  4730. if (s.strm.avail_out === 0) {
  4731. return BS_NEED_MORE;
  4732. }
  4733. /***/
  4734. }
  4735. }
  4736. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  4737. if (flush === Z_FINISH) {
  4738. /*** FLUSH_BLOCK(s, 1); ***/
  4739. flush_block_only(s, true);
  4740. if (s.strm.avail_out === 0) {
  4741. return BS_FINISH_STARTED;
  4742. }
  4743. /***/
  4744. return BS_FINISH_DONE;
  4745. }
  4746. if (s.last_lit) {
  4747. /*** FLUSH_BLOCK(s, 0); ***/
  4748. flush_block_only(s, false);
  4749. if (s.strm.avail_out === 0) {
  4750. return BS_NEED_MORE;
  4751. }
  4752. /***/
  4753. }
  4754. return BS_BLOCK_DONE;
  4755. }
  4756.  
  4757. /* ===========================================================================
  4758. * Same as above, but achieves better compression. We use a lazy
  4759. * evaluation for matches: a match is finally adopted only if there is
  4760. * no better match at the next window position.
  4761. */
  4762. function deflate_slow(s, flush) {
  4763. var hash_head; /* head of hash chain */
  4764. var bflush; /* set if current block must be flushed */
  4765.  
  4766. var max_insert;
  4767.  
  4768. /* Process the input block. */
  4769. for (;;) {
  4770. /* Make sure that we always have enough lookahead, except
  4771. * at the end of the input file. We need MAX_MATCH bytes
  4772. * for the next match, plus MIN_MATCH bytes to insert the
  4773. * string following the next match.
  4774. */
  4775. if (s.lookahead < MIN_LOOKAHEAD) {
  4776. fill_window(s);
  4777. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  4778. return BS_NEED_MORE;
  4779. }
  4780. if (s.lookahead === 0) { break; } /* flush the current block */
  4781. }
  4782.  
  4783. /* Insert the string window[strstart .. strstart+2] in the
  4784. * dictionary, and set hash_head to the head of the hash chain:
  4785. */
  4786. hash_head = 0/*NIL*/;
  4787. if (s.lookahead >= MIN_MATCH) {
  4788. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4789. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4790. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4791. s.head[s.ins_h] = s.strstart;
  4792. /***/
  4793. }
  4794.  
  4795. /* Find the longest match, discarding those <= prev_length.
  4796. */
  4797. s.prev_length = s.match_length;
  4798. s.prev_match = s.match_start;
  4799. s.match_length = MIN_MATCH-1;
  4800.  
  4801. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  4802. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  4803. /* To simplify the code, we prevent matches with the string
  4804. * of window index 0 (in particular we have to avoid a match
  4805. * of the string with itself at the start of the input file).
  4806. */
  4807. s.match_length = longest_match(s, hash_head);
  4808. /* longest_match() sets match_start */
  4809.  
  4810. if (s.match_length <= 5 &&
  4811. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  4812.  
  4813. /* If prev_match is also MIN_MATCH, match_start is garbage
  4814. * but we will ignore the current match anyway.
  4815. */
  4816. s.match_length = MIN_MATCH-1;
  4817. }
  4818. }
  4819. /* If there was a match at the previous step and the current
  4820. * match is not better, output the previous match:
  4821. */
  4822. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  4823. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  4824. /* Do not insert strings in hash table beyond this. */
  4825.  
  4826. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  4827.  
  4828. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  4829. s.prev_length - MIN_MATCH, bflush);***/
  4830. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  4831. /* Insert in hash table all strings up to the end of the match.
  4832. * strstart-1 and strstart are already inserted. If there is not
  4833. * enough lookahead, the last two strings are not inserted in
  4834. * the hash table.
  4835. */
  4836. s.lookahead -= s.prev_length-1;
  4837. s.prev_length -= 2;
  4838. do {
  4839. if (++s.strstart <= max_insert) {
  4840. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4841. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4842. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4843. s.head[s.ins_h] = s.strstart;
  4844. /***/
  4845. }
  4846. } while (--s.prev_length !== 0);
  4847. s.match_available = 0;
  4848. s.match_length = MIN_MATCH-1;
  4849. s.strstart++;
  4850.  
  4851. if (bflush) {
  4852. /*** FLUSH_BLOCK(s, 0); ***/
  4853. flush_block_only(s, false);
  4854. if (s.strm.avail_out === 0) {
  4855. return BS_NEED_MORE;
  4856. }
  4857. /***/
  4858. }
  4859.  
  4860. } else if (s.match_available) {
  4861. /* If there was no match at the previous position, output a
  4862. * single literal. If there was a match but the current match
  4863. * is longer, truncate the previous match to a single literal.
  4864. */
  4865. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  4866. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  4867. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  4868.  
  4869. if (bflush) {
  4870. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  4871. flush_block_only(s, false);
  4872. /***/
  4873. }
  4874. s.strstart++;
  4875. s.lookahead--;
  4876. if (s.strm.avail_out === 0) {
  4877. return BS_NEED_MORE;
  4878. }
  4879. } else {
  4880. /* There is no previous match to compare with, wait for
  4881. * the next step to decide.
  4882. */
  4883. s.match_available = 1;
  4884. s.strstart++;
  4885. s.lookahead--;
  4886. }
  4887. }
  4888. //Assert (flush != Z_NO_FLUSH, "no flush?");
  4889. if (s.match_available) {
  4890. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  4891. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  4892. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  4893.  
  4894. s.match_available = 0;
  4895. }
  4896. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  4897. if (flush === Z_FINISH) {
  4898. /*** FLUSH_BLOCK(s, 1); ***/
  4899. flush_block_only(s, true);
  4900. if (s.strm.avail_out === 0) {
  4901. return BS_FINISH_STARTED;
  4902. }
  4903. /***/
  4904. return BS_FINISH_DONE;
  4905. }
  4906. if (s.last_lit) {
  4907. /*** FLUSH_BLOCK(s, 0); ***/
  4908. flush_block_only(s, false);
  4909. if (s.strm.avail_out === 0) {
  4910. return BS_NEED_MORE;
  4911. }
  4912. /***/
  4913. }
  4914.  
  4915. return BS_BLOCK_DONE;
  4916. }
  4917.  
  4918.  
  4919. /* ===========================================================================
  4920. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  4921. * one. Do not maintain a hash table. (It will be regenerated if this run of
  4922. * deflate switches away from Z_RLE.)
  4923. */
  4924. function deflate_rle(s, flush) {
  4925. var bflush; /* set if current block must be flushed */
  4926. var prev; /* byte at distance one to match */
  4927. var scan, strend; /* scan goes up to strend for length of run */
  4928.  
  4929. var _win = s.window;
  4930.  
  4931. for (;;) {
  4932. /* Make sure that we always have enough lookahead, except
  4933. * at the end of the input file. We need MAX_MATCH bytes
  4934. * for the longest run, plus one for the unrolled loop.
  4935. */
  4936. if (s.lookahead <= MAX_MATCH) {
  4937. fill_window(s);
  4938. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  4939. return BS_NEED_MORE;
  4940. }
  4941. if (s.lookahead === 0) { break; } /* flush the current block */
  4942. }
  4943.  
  4944. /* See how many times the previous byte repeats */
  4945. s.match_length = 0;
  4946. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  4947. scan = s.strstart - 1;
  4948. prev = _win[scan];
  4949. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  4950. strend = s.strstart + MAX_MATCH;
  4951. do {
  4952. /*jshint noempty:false*/
  4953. } while (prev === _win[++scan] && prev === _win[++scan] &&
  4954. prev === _win[++scan] && prev === _win[++scan] &&
  4955. prev === _win[++scan] && prev === _win[++scan] &&
  4956. prev === _win[++scan] && prev === _win[++scan] &&
  4957. scan < strend);
  4958. s.match_length = MAX_MATCH - (strend - scan);
  4959. if (s.match_length > s.lookahead) {
  4960. s.match_length = s.lookahead;
  4961. }
  4962. }
  4963. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  4964. }
  4965.  
  4966. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  4967. if (s.match_length >= MIN_MATCH) {
  4968. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  4969.  
  4970. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  4971. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  4972.  
  4973. s.lookahead -= s.match_length;
  4974. s.strstart += s.match_length;
  4975. s.match_length = 0;
  4976. } else {
  4977. /* No match, output a literal byte */
  4978. //Tracevv((stderr,"%c", s->window[s->strstart]));
  4979. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  4980. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  4981.  
  4982. s.lookahead--;
  4983. s.strstart++;
  4984. }
  4985. if (bflush) {
  4986. /*** FLUSH_BLOCK(s, 0); ***/
  4987. flush_block_only(s, false);
  4988. if (s.strm.avail_out === 0) {
  4989. return BS_NEED_MORE;
  4990. }
  4991. /***/
  4992. }
  4993. }
  4994. s.insert = 0;
  4995. if (flush === Z_FINISH) {
  4996. /*** FLUSH_BLOCK(s, 1); ***/
  4997. flush_block_only(s, true);
  4998. if (s.strm.avail_out === 0) {
  4999. return BS_FINISH_STARTED;
  5000. }
  5001. /***/
  5002. return BS_FINISH_DONE;
  5003. }
  5004. if (s.last_lit) {
  5005. /*** FLUSH_BLOCK(s, 0); ***/
  5006. flush_block_only(s, false);
  5007. if (s.strm.avail_out === 0) {
  5008. return BS_NEED_MORE;
  5009. }
  5010. /***/
  5011. }
  5012. return BS_BLOCK_DONE;
  5013. }
  5014.  
  5015. /* ===========================================================================
  5016. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  5017. * (It will be regenerated if this run of deflate switches away from Huffman.)
  5018. */
  5019. function deflate_huff(s, flush) {
  5020. var bflush; /* set if current block must be flushed */
  5021.  
  5022. for (;;) {
  5023. /* Make sure that we have a literal to write. */
  5024. if (s.lookahead === 0) {
  5025. fill_window(s);
  5026. if (s.lookahead === 0) {
  5027. if (flush === Z_NO_FLUSH) {
  5028. return BS_NEED_MORE;
  5029. }
  5030. break; /* flush the current block */
  5031. }
  5032. }
  5033.  
  5034. /* Output a literal byte */
  5035. s.match_length = 0;
  5036. //Tracevv((stderr,"%c", s->window[s->strstart]));
  5037. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  5038. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  5039. s.lookahead--;
  5040. s.strstart++;
  5041. if (bflush) {
  5042. /*** FLUSH_BLOCK(s, 0); ***/
  5043. flush_block_only(s, false);
  5044. if (s.strm.avail_out === 0) {
  5045. return BS_NEED_MORE;
  5046. }
  5047. /***/
  5048. }
  5049. }
  5050. s.insert = 0;
  5051. if (flush === Z_FINISH) {
  5052. /*** FLUSH_BLOCK(s, 1); ***/
  5053. flush_block_only(s, true);
  5054. if (s.strm.avail_out === 0) {
  5055. return BS_FINISH_STARTED;
  5056. }
  5057. /***/
  5058. return BS_FINISH_DONE;
  5059. }
  5060. if (s.last_lit) {
  5061. /*** FLUSH_BLOCK(s, 0); ***/
  5062. flush_block_only(s, false);
  5063. if (s.strm.avail_out === 0) {
  5064. return BS_NEED_MORE;
  5065. }
  5066. /***/
  5067. }
  5068. return BS_BLOCK_DONE;
  5069. }
  5070.  
  5071. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  5072. * the desired pack level (0..9). The values given below have been tuned to
  5073. * exclude worst case performance for pathological files. Better values may be
  5074. * found for specific files.
  5075. */
  5076. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  5077. this.good_length = good_length;
  5078. this.max_lazy = max_lazy;
  5079. this.nice_length = nice_length;
  5080. this.max_chain = max_chain;
  5081. this.func = func;
  5082. };
  5083.  
  5084. var configuration_table;
  5085.  
  5086. configuration_table = [
  5087. /* good lazy nice chain */
  5088. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  5089. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  5090. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  5091. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  5092.  
  5093. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  5094. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  5095. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  5096. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  5097. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  5098. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  5099. ];
  5100.  
  5101.  
  5102. /* ===========================================================================
  5103. * Initialize the "longest match" routines for a new zlib stream
  5104. */
  5105. function lm_init(s) {
  5106. s.window_size = 2 * s.w_size;
  5107.  
  5108. /*** CLEAR_HASH(s); ***/
  5109. zero(s.head); // Fill with NIL (= 0);
  5110.  
  5111. /* Set the default configuration parameters:
  5112. */
  5113. s.max_lazy_match = configuration_table[s.level].max_lazy;
  5114. s.good_match = configuration_table[s.level].good_length;
  5115. s.nice_match = configuration_table[s.level].nice_length;
  5116. s.max_chain_length = configuration_table[s.level].max_chain;
  5117.  
  5118. s.strstart = 0;
  5119. s.block_start = 0;
  5120. s.lookahead = 0;
  5121. s.insert = 0;
  5122. s.match_length = s.prev_length = MIN_MATCH - 1;
  5123. s.match_available = 0;
  5124. s.ins_h = 0;
  5125. }
  5126.  
  5127.  
  5128. function DeflateState() {
  5129. this.strm = null; /* pointer back to this zlib stream */
  5130. this.status = 0; /* as the name implies */
  5131. this.pending_buf = null; /* output still pending */
  5132. this.pending_buf_size = 0; /* size of pending_buf */
  5133. this.pending_out = 0; /* next pending byte to output to the stream */
  5134. this.pending = 0; /* nb of bytes in the pending buffer */
  5135. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  5136. this.gzhead = null; /* gzip header information to write */
  5137. this.gzindex = 0; /* where in extra, name, or comment */
  5138. this.method = Z_DEFLATED; /* can only be DEFLATED */
  5139. this.last_flush = -1; /* value of flush param for previous deflate call */
  5140.  
  5141. this.w_size = 0; /* LZ77 window size (32K by default) */
  5142. this.w_bits = 0; /* log2(w_size) (8..16) */
  5143. this.w_mask = 0; /* w_size - 1 */
  5144.  
  5145. this.window = null;
  5146. /* Sliding window. Input bytes are read into the second half of the window,
  5147. * and move to the first half later to keep a dictionary of at least wSize
  5148. * bytes. With this organization, matches are limited to a distance of
  5149. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  5150. * performed with a length multiple of the block size.
  5151. */
  5152.  
  5153. this.window_size = 0;
  5154. /* Actual size of window: 2*wSize, except when the user input buffer
  5155. * is directly used as sliding window.
  5156. */
  5157.  
  5158. this.prev = null;
  5159. /* Link to older string with same hash index. To limit the size of this
  5160. * array to 64K, this link is maintained only for the last 32K strings.
  5161. * An index in this array is thus a window index modulo 32K.
  5162. */
  5163.  
  5164. this.head = null; /* Heads of the hash chains or NIL. */
  5165.  
  5166. this.ins_h = 0; /* hash index of string to be inserted */
  5167. this.hash_size = 0; /* number of elements in hash table */
  5168. this.hash_bits = 0; /* log2(hash_size) */
  5169. this.hash_mask = 0; /* hash_size-1 */
  5170.  
  5171. this.hash_shift = 0;
  5172. /* Number of bits by which ins_h must be shifted at each input
  5173. * step. It must be such that after MIN_MATCH steps, the oldest
  5174. * byte no longer takes part in the hash key, that is:
  5175. * hash_shift * MIN_MATCH >= hash_bits
  5176. */
  5177.  
  5178. this.block_start = 0;
  5179. /* Window position at the beginning of the current output block. Gets
  5180. * negative when the window is moved backwards.
  5181. */
  5182.  
  5183. this.match_length = 0; /* length of best match */
  5184. this.prev_match = 0; /* previous match */
  5185. this.match_available = 0; /* set if previous match exists */
  5186. this.strstart = 0; /* start of string to insert */
  5187. this.match_start = 0; /* start of matching string */
  5188. this.lookahead = 0; /* number of valid bytes ahead in window */
  5189.  
  5190. this.prev_length = 0;
  5191. /* Length of the best match at previous step. Matches not greater than this
  5192. * are discarded. This is used in the lazy match evaluation.
  5193. */
  5194.  
  5195. this.max_chain_length = 0;
  5196. /* To speed up deflation, hash chains are never searched beyond this
  5197. * length. A higher limit improves compression ratio but degrades the
  5198. * speed.
  5199. */
  5200.  
  5201. this.max_lazy_match = 0;
  5202. /* Attempt to find a better match only when the current match is strictly
  5203. * smaller than this value. This mechanism is used only for compression
  5204. * levels >= 4.
  5205. */
  5206. // That's alias to max_lazy_match, don't use directly
  5207. //this.max_insert_length = 0;
  5208. /* Insert new strings in the hash table only if the match length is not
  5209. * greater than this length. This saves time but degrades compression.
  5210. * max_insert_length is used only for compression levels <= 3.
  5211. */
  5212.  
  5213. this.level = 0; /* compression level (1..9) */
  5214. this.strategy = 0; /* favor or force Huffman coding*/
  5215.  
  5216. this.good_match = 0;
  5217. /* Use a faster search when the previous match is longer than this */
  5218.  
  5219. this.nice_match = 0; /* Stop searching when current match exceeds this */
  5220.  
  5221. /* used by trees.c: */
  5222.  
  5223. /* Didn't use ct_data typedef below to suppress compiler warning */
  5224.  
  5225. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  5226. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  5227. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  5228.  
  5229. // Use flat array of DOUBLE size, with interleaved fata,
  5230. // because JS does not support effective
  5231. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  5232. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  5233. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  5234. zero(this.dyn_ltree);
  5235. zero(this.dyn_dtree);
  5236. zero(this.bl_tree);
  5237.  
  5238. this.l_desc = null; /* desc. for literal tree */
  5239. this.d_desc = null; /* desc. for distance tree */
  5240. this.bl_desc = null; /* desc. for bit length tree */
  5241.  
  5242. //ush bl_count[MAX_BITS+1];
  5243. this.bl_count = new utils.Buf16(MAX_BITS+1);
  5244. /* number of codes at each bit length for an optimal tree */
  5245.  
  5246. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  5247. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  5248. zero(this.heap);
  5249.  
  5250. this.heap_len = 0; /* number of elements in the heap */
  5251. this.heap_max = 0; /* element of largest frequency */
  5252. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  5253. * The same heap array is used to build all trees.
  5254. */
  5255.  
  5256. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  5257. zero(this.depth);
  5258. /* Depth of each subtree used as tie breaker for trees of equal frequency
  5259. */
  5260.  
  5261. this.l_buf = 0; /* buffer index for literals or lengths */
  5262.  
  5263. this.lit_bufsize = 0;
  5264. /* Size of match buffer for literals/lengths. There are 4 reasons for
  5265. * limiting lit_bufsize to 64K:
  5266. * - frequencies can be kept in 16 bit counters
  5267. * - if compression is not successful for the first block, all input
  5268. * data is still in the window so we can still emit a stored block even
  5269. * when input comes from standard input. (This can also be done for
  5270. * all blocks if lit_bufsize is not greater than 32K.)
  5271. * - if compression is not successful for a file smaller than 64K, we can
  5272. * even emit a stored file instead of a stored block (saving 5 bytes).
  5273. * This is applicable only for zip (not gzip or zlib).
  5274. * - creating new Huffman trees less frequently may not provide fast
  5275. * adaptation to changes in the input data statistics. (Take for
  5276. * example a binary file with poorly compressible code followed by
  5277. * a highly compressible string table.) Smaller buffer sizes give
  5278. * fast adaptation but have of course the overhead of transmitting
  5279. * trees more frequently.
  5280. * - I can't count above 4
  5281. */
  5282.  
  5283. this.last_lit = 0; /* running index in l_buf */
  5284.  
  5285. this.d_buf = 0;
  5286. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  5287. * the same number of elements. To use different lengths, an extra flag
  5288. * array would be necessary.
  5289. */
  5290.  
  5291. this.opt_len = 0; /* bit length of current block with optimal trees */
  5292. this.static_len = 0; /* bit length of current block with static trees */
  5293. this.matches = 0; /* number of string matches in current block */
  5294. this.insert = 0; /* bytes at end of window left to insert */
  5295.  
  5296.  
  5297. this.bi_buf = 0;
  5298. /* Output buffer. bits are inserted starting at the bottom (least
  5299. * significant bits).
  5300. */
  5301. this.bi_valid = 0;
  5302. /* Number of valid bits in bi_buf. All bits above the last valid bit
  5303. * are always zero.
  5304. */
  5305.  
  5306. // Used for window memory init. We safely ignore it for JS. That makes
  5307. // sense only for pointers and memory check tools.
  5308. //this.high_water = 0;
  5309. /* High water mark offset in window for initialized bytes -- bytes above
  5310. * this are set to zero in order to avoid memory check warnings when
  5311. * longest match routines access bytes past the input. This is then
  5312. * updated to the new high water mark.
  5313. */
  5314. }
  5315.  
  5316.  
  5317. function deflateResetKeep(strm) {
  5318. var s;
  5319.  
  5320. if (!strm || !strm.state) {
  5321. return err(strm, Z_STREAM_ERROR);
  5322. }
  5323.  
  5324. strm.total_in = strm.total_out = 0;
  5325. strm.data_type = Z_UNKNOWN;
  5326.  
  5327. s = strm.state;
  5328. s.pending = 0;
  5329. s.pending_out = 0;
  5330.  
  5331. if (s.wrap < 0) {
  5332. s.wrap = -s.wrap;
  5333. /* was made negative by deflate(..., Z_FINISH); */
  5334. }
  5335. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  5336. strm.adler = (s.wrap === 2) ?
  5337. 0 // crc32(0, Z_NULL, 0)
  5338. :
  5339. 1; // adler32(0, Z_NULL, 0)
  5340. s.last_flush = Z_NO_FLUSH;
  5341. trees._tr_init(s);
  5342. return Z_OK;
  5343. }
  5344.  
  5345.  
  5346. function deflateReset(strm) {
  5347. var ret = deflateResetKeep(strm);
  5348. if (ret === Z_OK) {
  5349. lm_init(strm.state);
  5350. }
  5351. return ret;
  5352. }
  5353.  
  5354.  
  5355. function deflateSetHeader(strm, head) {
  5356. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5357. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  5358. strm.state.gzhead = head;
  5359. return Z_OK;
  5360. }
  5361.  
  5362.  
  5363. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  5364. if (!strm) { // === Z_NULL
  5365. return Z_STREAM_ERROR;
  5366. }
  5367. var wrap = 1;
  5368.  
  5369. if (level === Z_DEFAULT_COMPRESSION) {
  5370. level = 6;
  5371. }
  5372.  
  5373. if (windowBits < 0) { /* suppress zlib wrapper */
  5374. wrap = 0;
  5375. windowBits = -windowBits;
  5376. }
  5377.  
  5378. else if (windowBits > 15) {
  5379. wrap = 2; /* write gzip wrapper instead */
  5380. windowBits -= 16;
  5381. }
  5382.  
  5383.  
  5384. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  5385. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  5386. strategy < 0 || strategy > Z_FIXED) {
  5387. return err(strm, Z_STREAM_ERROR);
  5388. }
  5389.  
  5390.  
  5391. if (windowBits === 8) {
  5392. windowBits = 9;
  5393. }
  5394. /* until 256-byte window bug fixed */
  5395.  
  5396. var s = new DeflateState();
  5397.  
  5398. strm.state = s;
  5399. s.strm = strm;
  5400.  
  5401. s.wrap = wrap;
  5402. s.gzhead = null;
  5403. s.w_bits = windowBits;
  5404. s.w_size = 1 << s.w_bits;
  5405. s.w_mask = s.w_size - 1;
  5406.  
  5407. s.hash_bits = memLevel + 7;
  5408. s.hash_size = 1 << s.hash_bits;
  5409. s.hash_mask = s.hash_size - 1;
  5410. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  5411.  
  5412. s.window = new utils.Buf8(s.w_size * 2);
  5413. s.head = new utils.Buf16(s.hash_size);
  5414. s.prev = new utils.Buf16(s.w_size);
  5415.  
  5416. // Don't need mem init magic for JS.
  5417. //s.high_water = 0; /* nothing written to s->window yet */
  5418.  
  5419. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  5420.  
  5421. s.pending_buf_size = s.lit_bufsize * 4;
  5422. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  5423.  
  5424. s.d_buf = s.lit_bufsize >> 1;
  5425. s.l_buf = (1 + 2) * s.lit_bufsize;
  5426.  
  5427. s.level = level;
  5428. s.strategy = strategy;
  5429. s.method = method;
  5430.  
  5431. return deflateReset(strm);
  5432. }
  5433.  
  5434. function deflateInit(strm, level) {
  5435. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  5436. }
  5437.  
  5438.  
  5439. function deflate(strm, flush) {
  5440. var old_flush, s;
  5441. var beg, val; // for gzip header write only
  5442.  
  5443. if (!strm || !strm.state ||
  5444. flush > Z_BLOCK || flush < 0) {
  5445. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  5446. }
  5447.  
  5448. s = strm.state;
  5449.  
  5450. if (!strm.output ||
  5451. (!strm.input && strm.avail_in !== 0) ||
  5452. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  5453. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  5454. }
  5455.  
  5456. s.strm = strm; /* just in case */
  5457. old_flush = s.last_flush;
  5458. s.last_flush = flush;
  5459.  
  5460. /* Write the header */
  5461. if (s.status === INIT_STATE) {
  5462.  
  5463. if (s.wrap === 2) { // GZIP header
  5464. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  5465. put_byte(s, 31);
  5466. put_byte(s, 139);
  5467. put_byte(s, 8);
  5468. if (!s.gzhead) { // s->gzhead == Z_NULL
  5469. put_byte(s, 0);
  5470. put_byte(s, 0);
  5471. put_byte(s, 0);
  5472. put_byte(s, 0);
  5473. put_byte(s, 0);
  5474. put_byte(s, s.level === 9 ? 2 :
  5475. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  5476. 4 : 0));
  5477. put_byte(s, OS_CODE);
  5478. s.status = BUSY_STATE;
  5479. }
  5480. else {
  5481. put_byte(s, (s.gzhead.text ? 1 : 0) +
  5482. (s.gzhead.hcrc ? 2 : 0) +
  5483. (!s.gzhead.extra ? 0 : 4) +
  5484. (!s.gzhead.name ? 0 : 8) +
  5485. (!s.gzhead.comment ? 0 : 16)
  5486. );
  5487. put_byte(s, s.gzhead.time & 0xff);
  5488. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  5489. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  5490. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  5491. put_byte(s, s.level === 9 ? 2 :
  5492. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  5493. 4 : 0));
  5494. put_byte(s, s.gzhead.os & 0xff);
  5495. if (s.gzhead.extra && s.gzhead.extra.length) {
  5496. put_byte(s, s.gzhead.extra.length & 0xff);
  5497. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  5498. }
  5499. if (s.gzhead.hcrc) {
  5500. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  5501. }
  5502. s.gzindex = 0;
  5503. s.status = EXTRA_STATE;
  5504. }
  5505. }
  5506. else // DEFLATE header
  5507. {
  5508. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  5509. var level_flags = -1;
  5510.  
  5511. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  5512. level_flags = 0;
  5513. } else if (s.level < 6) {
  5514. level_flags = 1;
  5515. } else if (s.level === 6) {
  5516. level_flags = 2;
  5517. } else {
  5518. level_flags = 3;
  5519. }
  5520. header |= (level_flags << 6);
  5521. if (s.strstart !== 0) { header |= PRESET_DICT; }
  5522. header += 31 - (header % 31);
  5523.  
  5524. s.status = BUSY_STATE;
  5525. putShortMSB(s, header);
  5526.  
  5527. /* Save the adler32 of the preset dictionary: */
  5528. if (s.strstart !== 0) {
  5529. putShortMSB(s, strm.adler >>> 16);
  5530. putShortMSB(s, strm.adler & 0xffff);
  5531. }
  5532. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  5533. }
  5534. }
  5535.  
  5536. //#ifdef GZIP
  5537. if (s.status === EXTRA_STATE) {
  5538. if (s.gzhead.extra/* != Z_NULL*/) {
  5539. beg = s.pending; /* start of bytes to update crc */
  5540.  
  5541. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  5542. if (s.pending === s.pending_buf_size) {
  5543. if (s.gzhead.hcrc && s.pending > beg) {
  5544. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5545. }
  5546. flush_pending(strm);
  5547. beg = s.pending;
  5548. if (s.pending === s.pending_buf_size) {
  5549. break;
  5550. }
  5551. }
  5552. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  5553. s.gzindex++;
  5554. }
  5555. if (s.gzhead.hcrc && s.pending > beg) {
  5556. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5557. }
  5558. if (s.gzindex === s.gzhead.extra.length) {
  5559. s.gzindex = 0;
  5560. s.status = NAME_STATE;
  5561. }
  5562. }
  5563. else {
  5564. s.status = NAME_STATE;
  5565. }
  5566. }
  5567. if (s.status === NAME_STATE) {
  5568. if (s.gzhead.name/* != Z_NULL*/) {
  5569. beg = s.pending; /* start of bytes to update crc */
  5570. //int val;
  5571.  
  5572. do {
  5573. if (s.pending === s.pending_buf_size) {
  5574. if (s.gzhead.hcrc && s.pending > beg) {
  5575. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5576. }
  5577. flush_pending(strm);
  5578. beg = s.pending;
  5579. if (s.pending === s.pending_buf_size) {
  5580. val = 1;
  5581. break;
  5582. }
  5583. }
  5584. // JS specific: little magic to add zero terminator to end of string
  5585. if (s.gzindex < s.gzhead.name.length) {
  5586. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  5587. } else {
  5588. val = 0;
  5589. }
  5590. put_byte(s, val);
  5591. } while (val !== 0);
  5592.  
  5593. if (s.gzhead.hcrc && s.pending > beg){
  5594. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5595. }
  5596. if (val === 0) {
  5597. s.gzindex = 0;
  5598. s.status = COMMENT_STATE;
  5599. }
  5600. }
  5601. else {
  5602. s.status = COMMENT_STATE;
  5603. }
  5604. }
  5605. if (s.status === COMMENT_STATE) {
  5606. if (s.gzhead.comment/* != Z_NULL*/) {
  5607. beg = s.pending; /* start of bytes to update crc */
  5608. //int val;
  5609.  
  5610. do {
  5611. if (s.pending === s.pending_buf_size) {
  5612. if (s.gzhead.hcrc && s.pending > beg) {
  5613. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5614. }
  5615. flush_pending(strm);
  5616. beg = s.pending;
  5617. if (s.pending === s.pending_buf_size) {
  5618. val = 1;
  5619. break;
  5620. }
  5621. }
  5622. // JS specific: little magic to add zero terminator to end of string
  5623. if (s.gzindex < s.gzhead.comment.length) {
  5624. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  5625. } else {
  5626. val = 0;
  5627. }
  5628. put_byte(s, val);
  5629. } while (val !== 0);
  5630.  
  5631. if (s.gzhead.hcrc && s.pending > beg) {
  5632. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5633. }
  5634. if (val === 0) {
  5635. s.status = HCRC_STATE;
  5636. }
  5637. }
  5638. else {
  5639. s.status = HCRC_STATE;
  5640. }
  5641. }
  5642. if (s.status === HCRC_STATE) {
  5643. if (s.gzhead.hcrc) {
  5644. if (s.pending + 2 > s.pending_buf_size) {
  5645. flush_pending(strm);
  5646. }
  5647. if (s.pending + 2 <= s.pending_buf_size) {
  5648. put_byte(s, strm.adler & 0xff);
  5649. put_byte(s, (strm.adler >> 8) & 0xff);
  5650. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  5651. s.status = BUSY_STATE;
  5652. }
  5653. }
  5654. else {
  5655. s.status = BUSY_STATE;
  5656. }
  5657. }
  5658. //#endif
  5659.  
  5660. /* Flush as much pending output as possible */
  5661. if (s.pending !== 0) {
  5662. flush_pending(strm);
  5663. if (strm.avail_out === 0) {
  5664. /* Since avail_out is 0, deflate will be called again with
  5665. * more output space, but possibly with both pending and
  5666. * avail_in equal to zero. There won't be anything to do,
  5667. * but this is not an error situation so make sure we
  5668. * return OK instead of BUF_ERROR at next call of deflate:
  5669. */
  5670. s.last_flush = -1;
  5671. return Z_OK;
  5672. }
  5673.  
  5674. /* Make sure there is something to do and avoid duplicate consecutive
  5675. * flushes. For repeated and useless calls with Z_FINISH, we keep
  5676. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  5677. */
  5678. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  5679. flush !== Z_FINISH) {
  5680. return err(strm, Z_BUF_ERROR);
  5681. }
  5682.  
  5683. /* User must not provide more input after the first FINISH: */
  5684. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  5685. return err(strm, Z_BUF_ERROR);
  5686. }
  5687.  
  5688. /* Start a new block or continue the current one.
  5689. */
  5690. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  5691. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  5692. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  5693. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  5694. configuration_table[s.level].func(s, flush));
  5695.  
  5696. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  5697. s.status = FINISH_STATE;
  5698. }
  5699. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  5700. if (strm.avail_out === 0) {
  5701. s.last_flush = -1;
  5702. /* avoid BUF_ERROR next call, see above */
  5703. }
  5704. return Z_OK;
  5705. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  5706. * of deflate should use the same flush parameter to make sure
  5707. * that the flush is complete. So we don't have to output an
  5708. * empty block here, this will be done at next call. This also
  5709. * ensures that for a very small output buffer, we emit at most
  5710. * one empty block.
  5711. */
  5712. }
  5713. if (bstate === BS_BLOCK_DONE) {
  5714. if (flush === Z_PARTIAL_FLUSH) {
  5715. trees._tr_align(s);
  5716. }
  5717. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  5718.  
  5719. trees._tr_stored_block(s, 0, 0, false);
  5720. /* For a full flush, this empty block will be recognized
  5721. * as a special marker by inflate_sync().
  5722. */
  5723. if (flush === Z_FULL_FLUSH) {
  5724. /*** CLEAR_HASH(s); ***/ /* forget history */
  5725. zero(s.head); // Fill with NIL (= 0);
  5726.  
  5727. if (s.lookahead === 0) {
  5728. s.strstart = 0;
  5729. s.block_start = 0;
  5730. s.insert = 0;
  5731. }
  5732. }
  5733. }
  5734. flush_pending(strm);
  5735. if (strm.avail_out === 0) {
  5736. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  5737. return Z_OK;
  5738. }
  5739. }
  5740. }
  5741. //Assert(strm->avail_out > 0, "bug2");
  5742. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  5743.  
  5744. if (flush !== Z_FINISH) { return Z_OK; }
  5745. if (s.wrap <= 0) { return Z_STREAM_END; }
  5746.  
  5747. /* Write the trailer */
  5748. if (s.wrap === 2) {
  5749. put_byte(s, strm.adler & 0xff);
  5750. put_byte(s, (strm.adler >> 8) & 0xff);
  5751. put_byte(s, (strm.adler >> 16) & 0xff);
  5752. put_byte(s, (strm.adler >> 24) & 0xff);
  5753. put_byte(s, strm.total_in & 0xff);
  5754. put_byte(s, (strm.total_in >> 8) & 0xff);
  5755. put_byte(s, (strm.total_in >> 16) & 0xff);
  5756. put_byte(s, (strm.total_in >> 24) & 0xff);
  5757. }
  5758. else
  5759. {
  5760. putShortMSB(s, strm.adler >>> 16);
  5761. putShortMSB(s, strm.adler & 0xffff);
  5762. }
  5763.  
  5764. flush_pending(strm);
  5765. /* If avail_out is zero, the application will call deflate again
  5766. * to flush the rest.
  5767. */
  5768. if (s.wrap > 0) { s.wrap = -s.wrap; }
  5769. /* write the trailer only once! */
  5770. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  5771. }
  5772.  
  5773. function deflateEnd(strm) {
  5774. var status;
  5775.  
  5776. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  5777. return Z_STREAM_ERROR;
  5778. }
  5779.  
  5780. status = strm.state.status;
  5781. if (status !== INIT_STATE &&
  5782. status !== EXTRA_STATE &&
  5783. status !== NAME_STATE &&
  5784. status !== COMMENT_STATE &&
  5785. status !== HCRC_STATE &&
  5786. status !== BUSY_STATE &&
  5787. status !== FINISH_STATE
  5788. ) {
  5789. return err(strm, Z_STREAM_ERROR);
  5790. }
  5791.  
  5792. strm.state = null;
  5793.  
  5794. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  5795. }
  5796.  
  5797. /* =========================================================================
  5798. * Copy the source state to the destination state
  5799. */
  5800. //function deflateCopy(dest, source) {
  5801. //
  5802. //}
  5803.  
  5804. exports.deflateInit = deflateInit;
  5805. exports.deflateInit2 = deflateInit2;
  5806. exports.deflateReset = deflateReset;
  5807. exports.deflateResetKeep = deflateResetKeep;
  5808. exports.deflateSetHeader = deflateSetHeader;
  5809. exports.deflate = deflate;
  5810. exports.deflateEnd = deflateEnd;
  5811. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  5812.  
  5813. /* Not implemented
  5814. exports.deflateBound = deflateBound;
  5815. exports.deflateCopy = deflateCopy;
  5816. exports.deflateSetDictionary = deflateSetDictionary;
  5817. exports.deflateParams = deflateParams;
  5818. exports.deflatePending = deflatePending;
  5819. exports.deflatePrime = deflatePrime;
  5820. exports.deflateTune = deflateTune;
  5821. */
  5822. },{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(_dereq_,module,exports){
  5823. 'use strict';
  5824.  
  5825.  
  5826. function GZheader() {
  5827. /* true if compressed data believed to be text */
  5828. this.text = 0;
  5829. /* modification time */
  5830. this.time = 0;
  5831. /* extra flags (not used when writing a gzip file) */
  5832. this.xflags = 0;
  5833. /* operating system */
  5834. this.os = 0;
  5835. /* pointer to extra field or Z_NULL if none */
  5836. this.extra = null;
  5837. /* extra field length (valid if extra != Z_NULL) */
  5838. this.extra_len = 0; // Actually, we don't need it in JS,
  5839. // but leave for few code modifications
  5840.  
  5841. //
  5842. // Setup limits is not necessary because in js we should not preallocate memory
  5843. // for inflate use constant limit in 65536 bytes
  5844. //
  5845.  
  5846. /* space at extra (only when reading header) */
  5847. // this.extra_max = 0;
  5848. /* pointer to zero-terminated file name or Z_NULL */
  5849. this.name = '';
  5850. /* space at name (only when reading header) */
  5851. // this.name_max = 0;
  5852. /* pointer to zero-terminated comment or Z_NULL */
  5853. this.comment = '';
  5854. /* space at comment (only when reading header) */
  5855. // this.comm_max = 0;
  5856. /* true if there was or will be a header crc */
  5857. this.hcrc = 0;
  5858. /* true when done reading gzip header (not used when writing a gzip file) */
  5859. this.done = false;
  5860. }
  5861.  
  5862. module.exports = GZheader;
  5863. },{}],34:[function(_dereq_,module,exports){
  5864. 'use strict';
  5865.  
  5866. // See state defs from inflate.js
  5867. var BAD = 30; /* got a data error -- remain here until reset */
  5868. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  5869.  
  5870. /*
  5871. Decode literal, length, and distance codes and write out the resulting
  5872. literal and match bytes until either not enough input or output is
  5873. available, an end-of-block is encountered, or a data error is encountered.
  5874. When large enough input and output buffers are supplied to inflate(), for
  5875. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  5876. inflate execution time is spent in this routine.
  5877.  
  5878. Entry assumptions:
  5879.  
  5880. state.mode === LEN
  5881. strm.avail_in >= 6
  5882. strm.avail_out >= 258
  5883. start >= strm.avail_out
  5884. state.bits < 8
  5885.  
  5886. On return, state.mode is one of:
  5887.  
  5888. LEN -- ran out of enough output space or enough available input
  5889. TYPE -- reached end of block code, inflate() to interpret next block
  5890. BAD -- error in block data
  5891.  
  5892. Notes:
  5893.  
  5894. - The maximum input bits used by a length/distance pair is 15 bits for the
  5895. length code, 5 bits for the length extra, 15 bits for the distance code,
  5896. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  5897. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  5898. checking for available input while decoding.
  5899.  
  5900. - The maximum bytes that a single length/distance pair can output is 258
  5901. bytes, which is the maximum length that can be coded. inflate_fast()
  5902. requires strm.avail_out >= 258 for each loop to avoid checking for
  5903. output space.
  5904. */
  5905. module.exports = function inflate_fast(strm, start) {
  5906. var state;
  5907. var _in; /* local strm.input */
  5908. var last; /* have enough input while in < last */
  5909. var _out; /* local strm.output */
  5910. var beg; /* inflate()'s initial strm.output */
  5911. var end; /* while out < end, enough space available */
  5912. //#ifdef INFLATE_STRICT
  5913. var dmax; /* maximum distance from zlib header */
  5914. //#endif
  5915. var wsize; /* window size or zero if not using window */
  5916. var whave; /* valid bytes in the window */
  5917. var wnext; /* window write index */
  5918. var window; /* allocated sliding window, if wsize != 0 */
  5919. var hold; /* local strm.hold */
  5920. var bits; /* local strm.bits */
  5921. var lcode; /* local strm.lencode */
  5922. var dcode; /* local strm.distcode */
  5923. var lmask; /* mask for first level of length codes */
  5924. var dmask; /* mask for first level of distance codes */
  5925. var here; /* retrieved table entry */
  5926. var op; /* code bits, operation, extra bits, or */
  5927. /* window position, window bytes to copy */
  5928. var len; /* match length, unused bytes */
  5929. var dist; /* match distance */
  5930. var from; /* where to copy match from */
  5931. var from_source;
  5932.  
  5933.  
  5934. var input, output; // JS specific, because we have no pointers
  5935.  
  5936. /* copy state to local variables */
  5937. state = strm.state;
  5938. //here = state.here;
  5939. _in = strm.next_in;
  5940. input = strm.input;
  5941. last = _in + (strm.avail_in - 5);
  5942. _out = strm.next_out;
  5943. output = strm.output;
  5944. beg = _out - (start - strm.avail_out);
  5945. end = _out + (strm.avail_out - 257);
  5946. //#ifdef INFLATE_STRICT
  5947. dmax = state.dmax;
  5948. //#endif
  5949. wsize = state.wsize;
  5950. whave = state.whave;
  5951. wnext = state.wnext;
  5952. window = state.window;
  5953. hold = state.hold;
  5954. bits = state.bits;
  5955. lcode = state.lencode;
  5956. dcode = state.distcode;
  5957. lmask = (1 << state.lenbits) - 1;
  5958. dmask = (1 << state.distbits) - 1;
  5959.  
  5960.  
  5961. /* decode literals and length/distances until end-of-block or not enough
  5962. input data or output space */
  5963.  
  5964. top:
  5965. do {
  5966. if (bits < 15) {
  5967. hold += input[_in++] << bits;
  5968. bits += 8;
  5969. hold += input[_in++] << bits;
  5970. bits += 8;
  5971. }
  5972.  
  5973. here = lcode[hold & lmask];
  5974.  
  5975. dolen:
  5976. for (;;) { // Goto emulation
  5977. op = here >>> 24/*here.bits*/;
  5978. hold >>>= op;
  5979. bits -= op;
  5980. op = (here >>> 16) & 0xff/*here.op*/;
  5981. if (op === 0) { /* literal */
  5982. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  5983. // "inflate: literal '%c'\n" :
  5984. // "inflate: literal 0x%02x\n", here.val));
  5985. output[_out++] = here & 0xffff/*here.val*/;
  5986. }
  5987. else if (op & 16) { /* length base */
  5988. len = here & 0xffff/*here.val*/;
  5989. op &= 15; /* number of extra bits */
  5990. if (op) {
  5991. if (bits < op) {
  5992. hold += input[_in++] << bits;
  5993. bits += 8;
  5994. }
  5995. len += hold & ((1 << op) - 1);
  5996. hold >>>= op;
  5997. bits -= op;
  5998. }
  5999. //Tracevv((stderr, "inflate: length %u\n", len));
  6000. if (bits < 15) {
  6001. hold += input[_in++] << bits;
  6002. bits += 8;
  6003. hold += input[_in++] << bits;
  6004. bits += 8;
  6005. }
  6006. here = dcode[hold & dmask];
  6007.  
  6008. dodist:
  6009. for (;;) { // goto emulation
  6010. op = here >>> 24/*here.bits*/;
  6011. hold >>>= op;
  6012. bits -= op;
  6013. op = (here >>> 16) & 0xff/*here.op*/;
  6014.  
  6015. if (op & 16) { /* distance base */
  6016. dist = here & 0xffff/*here.val*/;
  6017. op &= 15; /* number of extra bits */
  6018. if (bits < op) {
  6019. hold += input[_in++] << bits;
  6020. bits += 8;
  6021. if (bits < op) {
  6022. hold += input[_in++] << bits;
  6023. bits += 8;
  6024. }
  6025. }
  6026. dist += hold & ((1 << op) - 1);
  6027. //#ifdef INFLATE_STRICT
  6028. if (dist > dmax) {
  6029. strm.msg = 'invalid distance too far back';
  6030. state.mode = BAD;
  6031. break top;
  6032. }
  6033. //#endif
  6034. hold >>>= op;
  6035. bits -= op;
  6036. //Tracevv((stderr, "inflate: distance %u\n", dist));
  6037. op = _out - beg; /* max distance in output */
  6038. if (dist > op) { /* see if copy from window */
  6039. op = dist - op; /* distance back in window */
  6040. if (op > whave) {
  6041. if (state.sane) {
  6042. strm.msg = 'invalid distance too far back';
  6043. state.mode = BAD;
  6044. break top;
  6045. }
  6046.  
  6047. // (!) This block is disabled in zlib defailts,
  6048. // don't enable it for binary compatibility
  6049. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  6050. // if (len <= op - whave) {
  6051. // do {
  6052. // output[_out++] = 0;
  6053. // } while (--len);
  6054. // continue top;
  6055. // }
  6056. // len -= op - whave;
  6057. // do {
  6058. // output[_out++] = 0;
  6059. // } while (--op > whave);
  6060. // if (op === 0) {
  6061. // from = _out - dist;
  6062. // do {
  6063. // output[_out++] = output[from++];
  6064. // } while (--len);
  6065. // continue top;
  6066. // }
  6067. //#endif
  6068. }
  6069. from = 0; // window index
  6070. from_source = window;
  6071. if (wnext === 0) { /* very common case */
  6072. from += wsize - op;
  6073. if (op < len) { /* some from window */
  6074. len -= op;
  6075. do {
  6076. output[_out++] = window[from++];
  6077. } while (--op);
  6078. from = _out - dist; /* rest from output */
  6079. from_source = output;
  6080. }
  6081. }
  6082. else if (wnext < op) { /* wrap around window */
  6083. from += wsize + wnext - op;
  6084. op -= wnext;
  6085. if (op < len) { /* some from end of window */
  6086. len -= op;
  6087. do {
  6088. output[_out++] = window[from++];
  6089. } while (--op);
  6090. from = 0;
  6091. if (wnext < len) { /* some from start of window */
  6092. op = wnext;
  6093. len -= op;
  6094. do {
  6095. output[_out++] = window[from++];
  6096. } while (--op);
  6097. from = _out - dist; /* rest from output */
  6098. from_source = output;
  6099. }
  6100. }
  6101. }
  6102. else { /* contiguous in window */
  6103. from += wnext - op;
  6104. if (op < len) { /* some from window */
  6105. len -= op;
  6106. do {
  6107. output[_out++] = window[from++];
  6108. } while (--op);
  6109. from = _out - dist; /* rest from output */
  6110. from_source = output;
  6111. }
  6112. }
  6113. while (len > 2) {
  6114. output[_out++] = from_source[from++];
  6115. output[_out++] = from_source[from++];
  6116. output[_out++] = from_source[from++];
  6117. len -= 3;
  6118. }
  6119. if (len) {
  6120. output[_out++] = from_source[from++];
  6121. if (len > 1) {
  6122. output[_out++] = from_source[from++];
  6123. }
  6124. }
  6125. }
  6126. else {
  6127. from = _out - dist; /* copy direct from output */
  6128. do { /* minimum length is three */
  6129. output[_out++] = output[from++];
  6130. output[_out++] = output[from++];
  6131. output[_out++] = output[from++];
  6132. len -= 3;
  6133. } while (len > 2);
  6134. if (len) {
  6135. output[_out++] = output[from++];
  6136. if (len > 1) {
  6137. output[_out++] = output[from++];
  6138. }
  6139. }
  6140. }
  6141. }
  6142. else if ((op & 64) === 0) { /* 2nd level distance code */
  6143. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  6144. continue dodist;
  6145. }
  6146. else {
  6147. strm.msg = 'invalid distance code';
  6148. state.mode = BAD;
  6149. break top;
  6150. }
  6151.  
  6152. break; // need to emulate goto via "continue"
  6153. }
  6154. }
  6155. else if ((op & 64) === 0) { /* 2nd level length code */
  6156. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  6157. continue dolen;
  6158. }
  6159. else if (op & 32) { /* end-of-block */
  6160. //Tracevv((stderr, "inflate: end of block\n"));
  6161. state.mode = TYPE;
  6162. break top;
  6163. }
  6164. else {
  6165. strm.msg = 'invalid literal/length code';
  6166. state.mode = BAD;
  6167. break top;
  6168. }
  6169.  
  6170. break; // need to emulate goto via "continue"
  6171. }
  6172. } while (_in < last && _out < end);
  6173.  
  6174. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  6175. len = bits >> 3;
  6176. _in -= len;
  6177. bits -= len << 3;
  6178. hold &= (1 << bits) - 1;
  6179.  
  6180. /* update state and return */
  6181. strm.next_in = _in;
  6182. strm.next_out = _out;
  6183. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  6184. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  6185. state.hold = hold;
  6186. state.bits = bits;
  6187. return;
  6188. };
  6189.  
  6190. },{}],35:[function(_dereq_,module,exports){
  6191. 'use strict';
  6192.  
  6193.  
  6194. var utils = _dereq_('../utils/common');
  6195. var adler32 = _dereq_('./adler32');
  6196. var crc32 = _dereq_('./crc32');
  6197. var inflate_fast = _dereq_('./inffast');
  6198. var inflate_table = _dereq_('./inftrees');
  6199.  
  6200. var CODES = 0;
  6201. var LENS = 1;
  6202. var DISTS = 2;
  6203.  
  6204. /* Public constants ==========================================================*/
  6205. /* ===========================================================================*/
  6206.  
  6207.  
  6208. /* Allowed flush values; see deflate() and inflate() below for details */
  6209. //var Z_NO_FLUSH = 0;
  6210. //var Z_PARTIAL_FLUSH = 1;
  6211. //var Z_SYNC_FLUSH = 2;
  6212. //var Z_FULL_FLUSH = 3;
  6213. var Z_FINISH = 4;
  6214. var Z_BLOCK = 5;
  6215. var Z_TREES = 6;
  6216.  
  6217.  
  6218. /* Return codes for the compression/decompression functions. Negative values
  6219. * are errors, positive values are used for special but normal events.
  6220. */
  6221. var Z_OK = 0;
  6222. var Z_STREAM_END = 1;
  6223. var Z_NEED_DICT = 2;
  6224. //var Z_ERRNO = -1;
  6225. var Z_STREAM_ERROR = -2;
  6226. var Z_DATA_ERROR = -3;
  6227. var Z_MEM_ERROR = -4;
  6228. var Z_BUF_ERROR = -5;
  6229. //var Z_VERSION_ERROR = -6;
  6230.  
  6231. /* The deflate compression method */
  6232. var Z_DEFLATED = 8;
  6233.  
  6234.  
  6235. /* STATES ====================================================================*/
  6236. /* ===========================================================================*/
  6237.  
  6238.  
  6239. var HEAD = 1; /* i: waiting for magic header */
  6240. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  6241. var TIME = 3; /* i: waiting for modification time (gzip) */
  6242. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  6243. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  6244. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  6245. var NAME = 7; /* i: waiting for end of file name (gzip) */
  6246. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  6247. var HCRC = 9; /* i: waiting for header crc (gzip) */
  6248. var DICTID = 10; /* i: waiting for dictionary check value */
  6249. var DICT = 11; /* waiting for inflateSetDictionary() call */
  6250. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  6251. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  6252. var STORED = 14; /* i: waiting for stored size (length and complement) */
  6253. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  6254. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  6255. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  6256. var LENLENS = 18; /* i: waiting for code length code lengths */
  6257. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  6258. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  6259. var LEN = 21; /* i: waiting for length/lit/eob code */
  6260. var LENEXT = 22; /* i: waiting for length extra bits */
  6261. var DIST = 23; /* i: waiting for distance code */
  6262. var DISTEXT = 24; /* i: waiting for distance extra bits */
  6263. var MATCH = 25; /* o: waiting for output space to copy string */
  6264. var LIT = 26; /* o: waiting for output space to write literal */
  6265. var CHECK = 27; /* i: waiting for 32-bit check value */
  6266. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  6267. var DONE = 29; /* finished check, done -- remain here until reset */
  6268. var BAD = 30; /* got a data error -- remain here until reset */
  6269. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  6270. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  6271.  
  6272. /* ===========================================================================*/
  6273.  
  6274.  
  6275.  
  6276. var ENOUGH_LENS = 852;
  6277. var ENOUGH_DISTS = 592;
  6278. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  6279.  
  6280. var MAX_WBITS = 15;
  6281. /* 32K LZ77 window */
  6282. var DEF_WBITS = MAX_WBITS;
  6283.  
  6284.  
  6285. function ZSWAP32(q) {
  6286. return (((q >>> 24) & 0xff) +
  6287. ((q >>> 8) & 0xff00) +
  6288. ((q & 0xff00) << 8) +
  6289. ((q & 0xff) << 24));
  6290. }
  6291.  
  6292.  
  6293. function InflateState() {
  6294. this.mode = 0; /* current inflate mode */
  6295. this.last = false; /* true if processing last block */
  6296. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  6297. this.havedict = false; /* true if dictionary provided */
  6298. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  6299. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  6300. this.check = 0; /* protected copy of check value */
  6301. this.total = 0; /* protected copy of output count */
  6302. // TODO: may be {}
  6303. this.head = null; /* where to save gzip header information */
  6304.  
  6305. /* sliding window */
  6306. this.wbits = 0; /* log base 2 of requested window size */
  6307. this.wsize = 0; /* window size or zero if not using window */
  6308. this.whave = 0; /* valid bytes in the window */
  6309. this.wnext = 0; /* window write index */
  6310. this.window = null; /* allocated sliding window, if needed */
  6311.  
  6312. /* bit accumulator */
  6313. this.hold = 0; /* input bit accumulator */
  6314. this.bits = 0; /* number of bits in "in" */
  6315.  
  6316. /* for string and stored block copying */
  6317. this.length = 0; /* literal or length of data to copy */
  6318. this.offset = 0; /* distance back to copy string from */
  6319.  
  6320. /* for table and code decoding */
  6321. this.extra = 0; /* extra bits needed */
  6322.  
  6323. /* fixed and dynamic code tables */
  6324. this.lencode = null; /* starting table for length/literal codes */
  6325. this.distcode = null; /* starting table for distance codes */
  6326. this.lenbits = 0; /* index bits for lencode */
  6327. this.distbits = 0; /* index bits for distcode */
  6328.  
  6329. /* dynamic table building */
  6330. this.ncode = 0; /* number of code length code lengths */
  6331. this.nlen = 0; /* number of length code lengths */
  6332. this.ndist = 0; /* number of distance code lengths */
  6333. this.have = 0; /* number of code lengths in lens[] */
  6334. this.next = null; /* next available space in codes[] */
  6335.  
  6336. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  6337. this.work = new utils.Buf16(288); /* work area for code table building */
  6338.  
  6339. /*
  6340. because we don't have pointers in js, we use lencode and distcode directly
  6341. as buffers so we don't need codes
  6342. */
  6343. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  6344. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  6345. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  6346. this.sane = 0; /* if false, allow invalid distance too far */
  6347. this.back = 0; /* bits back of last unprocessed length/lit */
  6348. this.was = 0; /* initial length of match */
  6349. }
  6350.  
  6351. function inflateResetKeep(strm) {
  6352. var state;
  6353.  
  6354. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6355. state = strm.state;
  6356. strm.total_in = strm.total_out = state.total = 0;
  6357. strm.msg = ''; /*Z_NULL*/
  6358. if (state.wrap) { /* to support ill-conceived Java test suite */
  6359. strm.adler = state.wrap & 1;
  6360. }
  6361. state.mode = HEAD;
  6362. state.last = 0;
  6363. state.havedict = 0;
  6364. state.dmax = 32768;
  6365. state.head = null/*Z_NULL*/;
  6366. state.hold = 0;
  6367. state.bits = 0;
  6368. //state.lencode = state.distcode = state.next = state.codes;
  6369. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  6370. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  6371.  
  6372. state.sane = 1;
  6373. state.back = -1;
  6374. //Tracev((stderr, "inflate: reset\n"));
  6375. return Z_OK;
  6376. }
  6377.  
  6378. function inflateReset(strm) {
  6379. var state;
  6380.  
  6381. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6382. state = strm.state;
  6383. state.wsize = 0;
  6384. state.whave = 0;
  6385. state.wnext = 0;
  6386. return inflateResetKeep(strm);
  6387.  
  6388. }
  6389.  
  6390. function inflateReset2(strm, windowBits) {
  6391. var wrap;
  6392. var state;
  6393.  
  6394. /* get the state */
  6395. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6396. state = strm.state;
  6397.  
  6398. /* extract wrap request from windowBits parameter */
  6399. if (windowBits < 0) {
  6400. wrap = 0;
  6401. windowBits = -windowBits;
  6402. }
  6403. else {
  6404. wrap = (windowBits >> 4) + 1;
  6405. if (windowBits < 48) {
  6406. windowBits &= 15;
  6407. }
  6408. }
  6409.  
  6410. /* set number of window bits, free window if different */
  6411. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  6412. return Z_STREAM_ERROR;
  6413. }
  6414. if (state.window !== null && state.wbits !== windowBits) {
  6415. state.window = null;
  6416. }
  6417.  
  6418. /* update state and reset the rest of it */
  6419. state.wrap = wrap;
  6420. state.wbits = windowBits;
  6421. return inflateReset(strm);
  6422. }
  6423.  
  6424. function inflateInit2(strm, windowBits) {
  6425. var ret;
  6426. var state;
  6427.  
  6428. if (!strm) { return Z_STREAM_ERROR; }
  6429. //strm.msg = Z_NULL; /* in case we return an error */
  6430.  
  6431. state = new InflateState();
  6432.  
  6433. //if (state === Z_NULL) return Z_MEM_ERROR;
  6434. //Tracev((stderr, "inflate: allocated\n"));
  6435. strm.state = state;
  6436. state.window = null/*Z_NULL*/;
  6437. ret = inflateReset2(strm, windowBits);
  6438. if (ret !== Z_OK) {
  6439. strm.state = null/*Z_NULL*/;
  6440. }
  6441. return ret;
  6442. }
  6443.  
  6444. function inflateInit(strm) {
  6445. return inflateInit2(strm, DEF_WBITS);
  6446. }
  6447.  
  6448.  
  6449. /*
  6450. Return state with length and distance decoding tables and index sizes set to
  6451. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  6452. If BUILDFIXED is defined, then instead this routine builds the tables the
  6453. first time it's called, and returns those tables the first time and
  6454. thereafter. This reduces the size of the code by about 2K bytes, in
  6455. exchange for a little execution time. However, BUILDFIXED should not be
  6456. used for threaded applications, since the rewriting of the tables and virgin
  6457. may not be thread-safe.
  6458. */
  6459. var virgin = true;
  6460.  
  6461. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  6462.  
  6463. function fixedtables(state) {
  6464. /* build fixed huffman tables if first call (may not be thread safe) */
  6465. if (virgin) {
  6466. var sym;
  6467.  
  6468. lenfix = new utils.Buf32(512);
  6469. distfix = new utils.Buf32(32);
  6470.  
  6471. /* literal/length table */
  6472. sym = 0;
  6473. while (sym < 144) { state.lens[sym++] = 8; }
  6474. while (sym < 256) { state.lens[sym++] = 9; }
  6475. while (sym < 280) { state.lens[sym++] = 7; }
  6476. while (sym < 288) { state.lens[sym++] = 8; }
  6477.  
  6478. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  6479.  
  6480. /* distance table */
  6481. sym = 0;
  6482. while (sym < 32) { state.lens[sym++] = 5; }
  6483.  
  6484. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  6485.  
  6486. /* do this just once */
  6487. virgin = false;
  6488. }
  6489.  
  6490. state.lencode = lenfix;
  6491. state.lenbits = 9;
  6492. state.distcode = distfix;
  6493. state.distbits = 5;
  6494. }
  6495.  
  6496.  
  6497. /*
  6498. Update the window with the last wsize (normally 32K) bytes written before
  6499. returning. If window does not exist yet, create it. This is only called
  6500. when a window is already in use, or when output has been written during this
  6501. inflate call, but the end of the deflate stream has not been reached yet.
  6502. It is also called to create a window for dictionary data when a dictionary
  6503. is loaded.
  6504.  
  6505. Providing output buffers larger than 32K to inflate() should provide a speed
  6506. advantage, since only the last 32K of output is copied to the sliding window
  6507. upon return from inflate(), and since all distances after the first 32K of
  6508. output will fall in the output data, making match copies simpler and faster.
  6509. The advantage may be dependent on the size of the processor's data caches.
  6510. */
  6511. function updatewindow(strm, src, end, copy) {
  6512. var dist;
  6513. var state = strm.state;
  6514.  
  6515. /* if it hasn't been done already, allocate space for the window */
  6516. if (state.window === null) {
  6517. state.wsize = 1 << state.wbits;
  6518. state.wnext = 0;
  6519. state.whave = 0;
  6520.  
  6521. state.window = new utils.Buf8(state.wsize);
  6522. }
  6523.  
  6524. /* copy state->wsize or less output bytes into the circular window */
  6525. if (copy >= state.wsize) {
  6526. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  6527. state.wnext = 0;
  6528. state.whave = state.wsize;
  6529. }
  6530. else {
  6531. dist = state.wsize - state.wnext;
  6532. if (dist > copy) {
  6533. dist = copy;
  6534. }
  6535. //zmemcpy(state->window + state->wnext, end - copy, dist);
  6536. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  6537. copy -= dist;
  6538. if (copy) {
  6539. //zmemcpy(state->window, end - copy, copy);
  6540. utils.arraySet(state.window,src, end - copy, copy, 0);
  6541. state.wnext = copy;
  6542. state.whave = state.wsize;
  6543. }
  6544. else {
  6545. state.wnext += dist;
  6546. if (state.wnext === state.wsize) { state.wnext = 0; }
  6547. if (state.whave < state.wsize) { state.whave += dist; }
  6548. }
  6549. }
  6550. return 0;
  6551. }
  6552.  
  6553. function inflate(strm, flush) {
  6554. var state;
  6555. var input, output; // input/output buffers
  6556. var next; /* next input INDEX */
  6557. var put; /* next output INDEX */
  6558. var have, left; /* available input and output */
  6559. var hold; /* bit buffer */
  6560. var bits; /* bits in bit buffer */
  6561. var _in, _out; /* save starting available input and output */
  6562. var copy; /* number of stored or match bytes to copy */
  6563. var from; /* where to copy match bytes from */
  6564. var from_source;
  6565. var here = 0; /* current decoding table entry */
  6566. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  6567. //var last; /* parent table entry */
  6568. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  6569. var len; /* length to copy for repeats, bits to drop */
  6570. var ret; /* return code */
  6571. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  6572. var opts;
  6573.  
  6574. var n; // temporary var for NEED_BITS
  6575.  
  6576. var order = /* permutation of code lengths */
  6577. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  6578.  
  6579.  
  6580. if (!strm || !strm.state || !strm.output ||
  6581. (!strm.input && strm.avail_in !== 0)) {
  6582. return Z_STREAM_ERROR;
  6583. }
  6584.  
  6585. state = strm.state;
  6586. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  6587.  
  6588.  
  6589. //--- LOAD() ---
  6590. put = strm.next_out;
  6591. output = strm.output;
  6592. left = strm.avail_out;
  6593. next = strm.next_in;
  6594. input = strm.input;
  6595. have = strm.avail_in;
  6596. hold = state.hold;
  6597. bits = state.bits;
  6598. //---
  6599.  
  6600. _in = have;
  6601. _out = left;
  6602. ret = Z_OK;
  6603.  
  6604. inf_leave: // goto emulation
  6605. for (;;) {
  6606. switch (state.mode) {
  6607. case HEAD:
  6608. if (state.wrap === 0) {
  6609. state.mode = TYPEDO;
  6610. break;
  6611. }
  6612. //=== NEEDBITS(16);
  6613. while (bits < 16) {
  6614. if (have === 0) { break inf_leave; }
  6615. have--;
  6616. hold += input[next++] << bits;
  6617. bits += 8;
  6618. }
  6619. //===//
  6620. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  6621. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  6622. //=== CRC2(state.check, hold);
  6623. hbuf[0] = hold & 0xff;
  6624. hbuf[1] = (hold >>> 8) & 0xff;
  6625. state.check = crc32(state.check, hbuf, 2, 0);
  6626. //===//
  6627.  
  6628. //=== INITBITS();
  6629. hold = 0;
  6630. bits = 0;
  6631. //===//
  6632. state.mode = FLAGS;
  6633. break;
  6634. }
  6635. state.flags = 0; /* expect zlib header */
  6636. if (state.head) {
  6637. state.head.done = false;
  6638. }
  6639. if (!(state.wrap & 1) || /* check if zlib header allowed */
  6640. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  6641. strm.msg = 'incorrect header check';
  6642. state.mode = BAD;
  6643. break;
  6644. }
  6645. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  6646. strm.msg = 'unknown compression method';
  6647. state.mode = BAD;
  6648. break;
  6649. }
  6650. //--- DROPBITS(4) ---//
  6651. hold >>>= 4;
  6652. bits -= 4;
  6653. //---//
  6654. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  6655. if (state.wbits === 0) {
  6656. state.wbits = len;
  6657. }
  6658. else if (len > state.wbits) {
  6659. strm.msg = 'invalid window size';
  6660. state.mode = BAD;
  6661. break;
  6662. }
  6663. state.dmax = 1 << len;
  6664. //Tracev((stderr, "inflate: zlib header ok\n"));
  6665. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  6666. state.mode = hold & 0x200 ? DICTID : TYPE;
  6667. //=== INITBITS();
  6668. hold = 0;
  6669. bits = 0;
  6670. //===//
  6671. break;
  6672. case FLAGS:
  6673. //=== NEEDBITS(16); */
  6674. while (bits < 16) {
  6675. if (have === 0) { break inf_leave; }
  6676. have--;
  6677. hold += input[next++] << bits;
  6678. bits += 8;
  6679. }
  6680. //===//
  6681. state.flags = hold;
  6682. if ((state.flags & 0xff) !== Z_DEFLATED) {
  6683. strm.msg = 'unknown compression method';
  6684. state.mode = BAD;
  6685. break;
  6686. }
  6687. if (state.flags & 0xe000) {
  6688. strm.msg = 'unknown header flags set';
  6689. state.mode = BAD;
  6690. break;
  6691. }
  6692. if (state.head) {
  6693. state.head.text = ((hold >> 8) & 1);
  6694. }
  6695. if (state.flags & 0x0200) {
  6696. //=== CRC2(state.check, hold);
  6697. hbuf[0] = hold & 0xff;
  6698. hbuf[1] = (hold >>> 8) & 0xff;
  6699. state.check = crc32(state.check, hbuf, 2, 0);
  6700. //===//
  6701. }
  6702. //=== INITBITS();
  6703. hold = 0;
  6704. bits = 0;
  6705. //===//
  6706. state.mode = TIME;
  6707. /* falls through */
  6708. case TIME:
  6709. //=== NEEDBITS(32); */
  6710. while (bits < 32) {
  6711. if (have === 0) { break inf_leave; }
  6712. have--;
  6713. hold += input[next++] << bits;
  6714. bits += 8;
  6715. }
  6716. //===//
  6717. if (state.head) {
  6718. state.head.time = hold;
  6719. }
  6720. if (state.flags & 0x0200) {
  6721. //=== CRC4(state.check, hold)
  6722. hbuf[0] = hold & 0xff;
  6723. hbuf[1] = (hold >>> 8) & 0xff;
  6724. hbuf[2] = (hold >>> 16) & 0xff;
  6725. hbuf[3] = (hold >>> 24) & 0xff;
  6726. state.check = crc32(state.check, hbuf, 4, 0);
  6727. //===
  6728. }
  6729. //=== INITBITS();
  6730. hold = 0;
  6731. bits = 0;
  6732. //===//
  6733. state.mode = OS;
  6734. /* falls through */
  6735. case OS:
  6736. //=== NEEDBITS(16); */
  6737. while (bits < 16) {
  6738. if (have === 0) { break inf_leave; }
  6739. have--;
  6740. hold += input[next++] << bits;
  6741. bits += 8;
  6742. }
  6743. //===//
  6744. if (state.head) {
  6745. state.head.xflags = (hold & 0xff);
  6746. state.head.os = (hold >> 8);
  6747. }
  6748. if (state.flags & 0x0200) {
  6749. //=== CRC2(state.check, hold);
  6750. hbuf[0] = hold & 0xff;
  6751. hbuf[1] = (hold >>> 8) & 0xff;
  6752. state.check = crc32(state.check, hbuf, 2, 0);
  6753. //===//
  6754. }
  6755. //=== INITBITS();
  6756. hold = 0;
  6757. bits = 0;
  6758. //===//
  6759. state.mode = EXLEN;
  6760. /* falls through */
  6761. case EXLEN:
  6762. if (state.flags & 0x0400) {
  6763. //=== NEEDBITS(16); */
  6764. while (bits < 16) {
  6765. if (have === 0) { break inf_leave; }
  6766. have--;
  6767. hold += input[next++] << bits;
  6768. bits += 8;
  6769. }
  6770. //===//
  6771. state.length = hold;
  6772. if (state.head) {
  6773. state.head.extra_len = hold;
  6774. }
  6775. if (state.flags & 0x0200) {
  6776. //=== CRC2(state.check, hold);
  6777. hbuf[0] = hold & 0xff;
  6778. hbuf[1] = (hold >>> 8) & 0xff;
  6779. state.check = crc32(state.check, hbuf, 2, 0);
  6780. //===//
  6781. }
  6782. //=== INITBITS();
  6783. hold = 0;
  6784. bits = 0;
  6785. //===//
  6786. }
  6787. else if (state.head) {
  6788. state.head.extra = null/*Z_NULL*/;
  6789. }
  6790. state.mode = EXTRA;
  6791. /* falls through */
  6792. case EXTRA:
  6793. if (state.flags & 0x0400) {
  6794. copy = state.length;
  6795. if (copy > have) { copy = have; }
  6796. if (copy) {
  6797. if (state.head) {
  6798. len = state.head.extra_len - state.length;
  6799. if (!state.head.extra) {
  6800. // Use untyped array for more conveniend processing later
  6801. state.head.extra = new Array(state.head.extra_len);
  6802. }
  6803. utils.arraySet(
  6804. state.head.extra,
  6805. input,
  6806. next,
  6807. // extra field is limited to 65536 bytes
  6808. // - no need for additional size check
  6809. copy,
  6810. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  6811. len
  6812. );
  6813. //zmemcpy(state.head.extra + len, next,
  6814. // len + copy > state.head.extra_max ?
  6815. // state.head.extra_max - len : copy);
  6816. }
  6817. if (state.flags & 0x0200) {
  6818. state.check = crc32(state.check, input, copy, next);
  6819. }
  6820. have -= copy;
  6821. next += copy;
  6822. state.length -= copy;
  6823. }
  6824. if (state.length) { break inf_leave; }
  6825. }
  6826. state.length = 0;
  6827. state.mode = NAME;
  6828. /* falls through */
  6829. case NAME:
  6830. if (state.flags & 0x0800) {
  6831. if (have === 0) { break inf_leave; }
  6832. copy = 0;
  6833. do {
  6834. // TODO: 2 or 1 bytes?
  6835. len = input[next + copy++];
  6836. /* use constant limit because in js we should not preallocate memory */
  6837. if (state.head && len &&
  6838. (state.length < 65536 /*state.head.name_max*/)) {
  6839. state.head.name += String.fromCharCode(len);
  6840. }
  6841. } while (len && copy < have);
  6842.  
  6843. if (state.flags & 0x0200) {
  6844. state.check = crc32(state.check, input, copy, next);
  6845. }
  6846. have -= copy;
  6847. next += copy;
  6848. if (len) { break inf_leave; }
  6849. }
  6850. else if (state.head) {
  6851. state.head.name = null;
  6852. }
  6853. state.length = 0;
  6854. state.mode = COMMENT;
  6855. /* falls through */
  6856. case COMMENT:
  6857. if (state.flags & 0x1000) {
  6858. if (have === 0) { break inf_leave; }
  6859. copy = 0;
  6860. do {
  6861. len = input[next + copy++];
  6862. /* use constant limit because in js we should not preallocate memory */
  6863. if (state.head && len &&
  6864. (state.length < 65536 /*state.head.comm_max*/)) {
  6865. state.head.comment += String.fromCharCode(len);
  6866. }
  6867. } while (len && copy < have);
  6868. if (state.flags & 0x0200) {
  6869. state.check = crc32(state.check, input, copy, next);
  6870. }
  6871. have -= copy;
  6872. next += copy;
  6873. if (len) { break inf_leave; }
  6874. }
  6875. else if (state.head) {
  6876. state.head.comment = null;
  6877. }
  6878. state.mode = HCRC;
  6879. /* falls through */
  6880. case HCRC:
  6881. if (state.flags & 0x0200) {
  6882. //=== NEEDBITS(16); */
  6883. while (bits < 16) {
  6884. if (have === 0) { break inf_leave; }
  6885. have--;
  6886. hold += input[next++] << bits;
  6887. bits += 8;
  6888. }
  6889. //===//
  6890. if (hold !== (state.check & 0xffff)) {
  6891. strm.msg = 'header crc mismatch';
  6892. state.mode = BAD;
  6893. break;
  6894. }
  6895. //=== INITBITS();
  6896. hold = 0;
  6897. bits = 0;
  6898. //===//
  6899. }
  6900. if (state.head) {
  6901. state.head.hcrc = ((state.flags >> 9) & 1);
  6902. state.head.done = true;
  6903. }
  6904. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  6905. state.mode = TYPE;
  6906. break;
  6907. case DICTID:
  6908. //=== NEEDBITS(32); */
  6909. while (bits < 32) {
  6910. if (have === 0) { break inf_leave; }
  6911. have--;
  6912. hold += input[next++] << bits;
  6913. bits += 8;
  6914. }
  6915. //===//
  6916. strm.adler = state.check = ZSWAP32(hold);
  6917. //=== INITBITS();
  6918. hold = 0;
  6919. bits = 0;
  6920. //===//
  6921. state.mode = DICT;
  6922. /* falls through */
  6923. case DICT:
  6924. if (state.havedict === 0) {
  6925. //--- RESTORE() ---
  6926. strm.next_out = put;
  6927. strm.avail_out = left;
  6928. strm.next_in = next;
  6929. strm.avail_in = have;
  6930. state.hold = hold;
  6931. state.bits = bits;
  6932. //---
  6933. return Z_NEED_DICT;
  6934. }
  6935. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  6936. state.mode = TYPE;
  6937. /* falls through */
  6938. case TYPE:
  6939. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  6940. /* falls through */
  6941. case TYPEDO:
  6942. if (state.last) {
  6943. //--- BYTEBITS() ---//
  6944. hold >>>= bits & 7;
  6945. bits -= bits & 7;
  6946. //---//
  6947. state.mode = CHECK;
  6948. break;
  6949. }
  6950. //=== NEEDBITS(3); */
  6951. while (bits < 3) {
  6952. if (have === 0) { break inf_leave; }
  6953. have--;
  6954. hold += input[next++] << bits;
  6955. bits += 8;
  6956. }
  6957. //===//
  6958. state.last = (hold & 0x01)/*BITS(1)*/;
  6959. //--- DROPBITS(1) ---//
  6960. hold >>>= 1;
  6961. bits -= 1;
  6962. //---//
  6963.  
  6964. switch ((hold & 0x03)/*BITS(2)*/) {
  6965. case 0: /* stored block */
  6966. //Tracev((stderr, "inflate: stored block%s\n",
  6967. // state.last ? " (last)" : ""));
  6968. state.mode = STORED;
  6969. break;
  6970. case 1: /* fixed block */
  6971. fixedtables(state);
  6972. //Tracev((stderr, "inflate: fixed codes block%s\n",
  6973. // state.last ? " (last)" : ""));
  6974. state.mode = LEN_; /* decode codes */
  6975. if (flush === Z_TREES) {
  6976. //--- DROPBITS(2) ---//
  6977. hold >>>= 2;
  6978. bits -= 2;
  6979. //---//
  6980. break inf_leave;
  6981. }
  6982. break;
  6983. case 2: /* dynamic block */
  6984. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  6985. // state.last ? " (last)" : ""));
  6986. state.mode = TABLE;
  6987. break;
  6988. case 3:
  6989. strm.msg = 'invalid block type';
  6990. state.mode = BAD;
  6991. }
  6992. //--- DROPBITS(2) ---//
  6993. hold >>>= 2;
  6994. bits -= 2;
  6995. //---//
  6996. break;
  6997. case STORED:
  6998. //--- BYTEBITS() ---// /* go to byte boundary */
  6999. hold >>>= bits & 7;
  7000. bits -= bits & 7;
  7001. //---//
  7002. //=== NEEDBITS(32); */
  7003. while (bits < 32) {
  7004. if (have === 0) { break inf_leave; }
  7005. have--;
  7006. hold += input[next++] << bits;
  7007. bits += 8;
  7008. }
  7009. //===//
  7010. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  7011. strm.msg = 'invalid stored block lengths';
  7012. state.mode = BAD;
  7013. break;
  7014. }
  7015. state.length = hold & 0xffff;
  7016. //Tracev((stderr, "inflate: stored length %u\n",
  7017. // state.length));
  7018. //=== INITBITS();
  7019. hold = 0;
  7020. bits = 0;
  7021. //===//
  7022. state.mode = COPY_;
  7023. if (flush === Z_TREES) { break inf_leave; }
  7024. /* falls through */
  7025. case COPY_:
  7026. state.mode = COPY;
  7027. /* falls through */
  7028. case COPY:
  7029. copy = state.length;
  7030. if (copy) {
  7031. if (copy > have) { copy = have; }
  7032. if (copy > left) { copy = left; }
  7033. if (copy === 0) { break inf_leave; }
  7034. //--- zmemcpy(put, next, copy); ---
  7035. utils.arraySet(output, input, next, copy, put);
  7036. //---//
  7037. have -= copy;
  7038. next += copy;
  7039. left -= copy;
  7040. put += copy;
  7041. state.length -= copy;
  7042. break;
  7043. }
  7044. //Tracev((stderr, "inflate: stored end\n"));
  7045. state.mode = TYPE;
  7046. break;
  7047. case TABLE:
  7048. //=== NEEDBITS(14); */
  7049. while (bits < 14) {
  7050. if (have === 0) { break inf_leave; }
  7051. have--;
  7052. hold += input[next++] << bits;
  7053. bits += 8;
  7054. }
  7055. //===//
  7056. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  7057. //--- DROPBITS(5) ---//
  7058. hold >>>= 5;
  7059. bits -= 5;
  7060. //---//
  7061. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  7062. //--- DROPBITS(5) ---//
  7063. hold >>>= 5;
  7064. bits -= 5;
  7065. //---//
  7066. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  7067. //--- DROPBITS(4) ---//
  7068. hold >>>= 4;
  7069. bits -= 4;
  7070. //---//
  7071. //#ifndef PKZIP_BUG_WORKAROUND
  7072. if (state.nlen > 286 || state.ndist > 30) {
  7073. strm.msg = 'too many length or distance symbols';
  7074. state.mode = BAD;
  7075. break;
  7076. }
  7077. //#endif
  7078. //Tracev((stderr, "inflate: table sizes ok\n"));
  7079. state.have = 0;
  7080. state.mode = LENLENS;
  7081. /* falls through */
  7082. case LENLENS:
  7083. while (state.have < state.ncode) {
  7084. //=== NEEDBITS(3);
  7085. while (bits < 3) {
  7086. if (have === 0) { break inf_leave; }
  7087. have--;
  7088. hold += input[next++] << bits;
  7089. bits += 8;
  7090. }
  7091. //===//
  7092. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  7093. //--- DROPBITS(3) ---//
  7094. hold >>>= 3;
  7095. bits -= 3;
  7096. //---//
  7097. }
  7098. while (state.have < 19) {
  7099. state.lens[order[state.have++]] = 0;
  7100. }
  7101. // We have separate tables & no pointers. 2 commented lines below not needed.
  7102. //state.next = state.codes;
  7103. //state.lencode = state.next;
  7104. // Switch to use dynamic table
  7105. state.lencode = state.lendyn;
  7106. state.lenbits = 7;
  7107.  
  7108. opts = {bits: state.lenbits};
  7109. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  7110. state.lenbits = opts.bits;
  7111.  
  7112. if (ret) {
  7113. strm.msg = 'invalid code lengths set';
  7114. state.mode = BAD;
  7115. break;
  7116. }
  7117. //Tracev((stderr, "inflate: code lengths ok\n"));
  7118. state.have = 0;
  7119. state.mode = CODELENS;
  7120. /* falls through */
  7121. case CODELENS:
  7122. while (state.have < state.nlen + state.ndist) {
  7123. for (;;) {
  7124. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  7125. here_bits = here >>> 24;
  7126. here_op = (here >>> 16) & 0xff;
  7127. here_val = here & 0xffff;
  7128.  
  7129. if ((here_bits) <= bits) { break; }
  7130. //--- PULLBYTE() ---//
  7131. if (have === 0) { break inf_leave; }
  7132. have--;
  7133. hold += input[next++] << bits;
  7134. bits += 8;
  7135. //---//
  7136. }
  7137. if (here_val < 16) {
  7138. //--- DROPBITS(here.bits) ---//
  7139. hold >>>= here_bits;
  7140. bits -= here_bits;
  7141. //---//
  7142. state.lens[state.have++] = here_val;
  7143. }
  7144. else {
  7145. if (here_val === 16) {
  7146. //=== NEEDBITS(here.bits + 2);
  7147. n = here_bits + 2;
  7148. while (bits < n) {
  7149. if (have === 0) { break inf_leave; }
  7150. have--;
  7151. hold += input[next++] << bits;
  7152. bits += 8;
  7153. }
  7154. //===//
  7155. //--- DROPBITS(here.bits) ---//
  7156. hold >>>= here_bits;
  7157. bits -= here_bits;
  7158. //---//
  7159. if (state.have === 0) {
  7160. strm.msg = 'invalid bit length repeat';
  7161. state.mode = BAD;
  7162. break;
  7163. }
  7164. len = state.lens[state.have - 1];
  7165. copy = 3 + (hold & 0x03);//BITS(2);
  7166. //--- DROPBITS(2) ---//
  7167. hold >>>= 2;
  7168. bits -= 2;
  7169. //---//
  7170. }
  7171. else if (here_val === 17) {
  7172. //=== NEEDBITS(here.bits + 3);
  7173. n = here_bits + 3;
  7174. while (bits < n) {
  7175. if (have === 0) { break inf_leave; }
  7176. have--;
  7177. hold += input[next++] << bits;
  7178. bits += 8;
  7179. }
  7180. //===//
  7181. //--- DROPBITS(here.bits) ---//
  7182. hold >>>= here_bits;
  7183. bits -= here_bits;
  7184. //---//
  7185. len = 0;
  7186. copy = 3 + (hold & 0x07);//BITS(3);
  7187. //--- DROPBITS(3) ---//
  7188. hold >>>= 3;
  7189. bits -= 3;
  7190. //---//
  7191. }
  7192. else {
  7193. //=== NEEDBITS(here.bits + 7);
  7194. n = here_bits + 7;
  7195. while (bits < n) {
  7196. if (have === 0) { break inf_leave; }
  7197. have--;
  7198. hold += input[next++] << bits;
  7199. bits += 8;
  7200. }
  7201. //===//
  7202. //--- DROPBITS(here.bits) ---//
  7203. hold >>>= here_bits;
  7204. bits -= here_bits;
  7205. //---//
  7206. len = 0;
  7207. copy = 11 + (hold & 0x7f);//BITS(7);
  7208. //--- DROPBITS(7) ---//
  7209. hold >>>= 7;
  7210. bits -= 7;
  7211. //---//
  7212. }
  7213. if (state.have + copy > state.nlen + state.ndist) {
  7214. strm.msg = 'invalid bit length repeat';
  7215. state.mode = BAD;
  7216. break;
  7217. }
  7218. while (copy--) {
  7219. state.lens[state.have++] = len;
  7220. }
  7221. }
  7222. }
  7223.  
  7224. /* handle error breaks in while */
  7225. if (state.mode === BAD) { break; }
  7226.  
  7227. /* check for end-of-block code (better have one) */
  7228. if (state.lens[256] === 0) {
  7229. strm.msg = 'invalid code -- missing end-of-block';
  7230. state.mode = BAD;
  7231. break;
  7232. }
  7233.  
  7234. /* build code tables -- note: do not change the lenbits or distbits
  7235. values here (9 and 6) without reading the comments in inftrees.h
  7236. concerning the ENOUGH constants, which depend on those values */
  7237. state.lenbits = 9;
  7238.  
  7239. opts = {bits: state.lenbits};
  7240. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  7241. // We have separate tables & no pointers. 2 commented lines below not needed.
  7242. // state.next_index = opts.table_index;
  7243. state.lenbits = opts.bits;
  7244. // state.lencode = state.next;
  7245.  
  7246. if (ret) {
  7247. strm.msg = 'invalid literal/lengths set';
  7248. state.mode = BAD;
  7249. break;
  7250. }
  7251.  
  7252. state.distbits = 6;
  7253. //state.distcode.copy(state.codes);
  7254. // Switch to use dynamic table
  7255. state.distcode = state.distdyn;
  7256. opts = {bits: state.distbits};
  7257. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  7258. // We have separate tables & no pointers. 2 commented lines below not needed.
  7259. // state.next_index = opts.table_index;
  7260. state.distbits = opts.bits;
  7261. // state.distcode = state.next;
  7262.  
  7263. if (ret) {
  7264. strm.msg = 'invalid distances set';
  7265. state.mode = BAD;
  7266. break;
  7267. }
  7268. //Tracev((stderr, 'inflate: codes ok\n'));
  7269. state.mode = LEN_;
  7270. if (flush === Z_TREES) { break inf_leave; }
  7271. /* falls through */
  7272. case LEN_:
  7273. state.mode = LEN;
  7274. /* falls through */
  7275. case LEN:
  7276. if (have >= 6 && left >= 258) {
  7277. //--- RESTORE() ---
  7278. strm.next_out = put;
  7279. strm.avail_out = left;
  7280. strm.next_in = next;
  7281. strm.avail_in = have;
  7282. state.hold = hold;
  7283. state.bits = bits;
  7284. //---
  7285. inflate_fast(strm, _out);
  7286. //--- LOAD() ---
  7287. put = strm.next_out;
  7288. output = strm.output;
  7289. left = strm.avail_out;
  7290. next = strm.next_in;
  7291. input = strm.input;
  7292. have = strm.avail_in;
  7293. hold = state.hold;
  7294. bits = state.bits;
  7295. //---
  7296.  
  7297. if (state.mode === TYPE) {
  7298. state.back = -1;
  7299. }
  7300. break;
  7301. }
  7302. state.back = 0;
  7303. for (;;) {
  7304. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  7305. here_bits = here >>> 24;
  7306. here_op = (here >>> 16) & 0xff;
  7307. here_val = here & 0xffff;
  7308.  
  7309. if (here_bits <= bits) { break; }
  7310. //--- PULLBYTE() ---//
  7311. if (have === 0) { break inf_leave; }
  7312. have--;
  7313. hold += input[next++] << bits;
  7314. bits += 8;
  7315. //---//
  7316. }
  7317. if (here_op && (here_op & 0xf0) === 0) {
  7318. last_bits = here_bits;
  7319. last_op = here_op;
  7320. last_val = here_val;
  7321. for (;;) {
  7322. here = state.lencode[last_val +
  7323. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  7324. here_bits = here >>> 24;
  7325. here_op = (here >>> 16) & 0xff;
  7326. here_val = here & 0xffff;
  7327.  
  7328. if ((last_bits + here_bits) <= bits) { break; }
  7329. //--- PULLBYTE() ---//
  7330. if (have === 0) { break inf_leave; }
  7331. have--;
  7332. hold += input[next++] << bits;
  7333. bits += 8;
  7334. //---//
  7335. }
  7336. //--- DROPBITS(last.bits) ---//
  7337. hold >>>= last_bits;
  7338. bits -= last_bits;
  7339. //---//
  7340. state.back += last_bits;
  7341. }
  7342. //--- DROPBITS(here.bits) ---//
  7343. hold >>>= here_bits;
  7344. bits -= here_bits;
  7345. //---//
  7346. state.back += here_bits;
  7347. state.length = here_val;
  7348. if (here_op === 0) {
  7349. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  7350. // "inflate: literal '%c'\n" :
  7351. // "inflate: literal 0x%02x\n", here.val));
  7352. state.mode = LIT;
  7353. break;
  7354. }
  7355. if (here_op & 32) {
  7356. //Tracevv((stderr, "inflate: end of block\n"));
  7357. state.back = -1;
  7358. state.mode = TYPE;
  7359. break;
  7360. }
  7361. if (here_op & 64) {
  7362. strm.msg = 'invalid literal/length code';
  7363. state.mode = BAD;
  7364. break;
  7365. }
  7366. state.extra = here_op & 15;
  7367. state.mode = LENEXT;
  7368. /* falls through */
  7369. case LENEXT:
  7370. if (state.extra) {
  7371. //=== NEEDBITS(state.extra);
  7372. n = state.extra;
  7373. while (bits < n) {
  7374. if (have === 0) { break inf_leave; }
  7375. have--;
  7376. hold += input[next++] << bits;
  7377. bits += 8;
  7378. }
  7379. //===//
  7380. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  7381. //--- DROPBITS(state.extra) ---//
  7382. hold >>>= state.extra;
  7383. bits -= state.extra;
  7384. //---//
  7385. state.back += state.extra;
  7386. }
  7387. //Tracevv((stderr, "inflate: length %u\n", state.length));
  7388. state.was = state.length;
  7389. state.mode = DIST;
  7390. /* falls through */
  7391. case DIST:
  7392. for (;;) {
  7393. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  7394. here_bits = here >>> 24;
  7395. here_op = (here >>> 16) & 0xff;
  7396. here_val = here & 0xffff;
  7397.  
  7398. if ((here_bits) <= bits) { break; }
  7399. //--- PULLBYTE() ---//
  7400. if (have === 0) { break inf_leave; }
  7401. have--;
  7402. hold += input[next++] << bits;
  7403. bits += 8;
  7404. //---//
  7405. }
  7406. if ((here_op & 0xf0) === 0) {
  7407. last_bits = here_bits;
  7408. last_op = here_op;
  7409. last_val = here_val;
  7410. for (;;) {
  7411. here = state.distcode[last_val +
  7412. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  7413. here_bits = here >>> 24;
  7414. here_op = (here >>> 16) & 0xff;
  7415. here_val = here & 0xffff;
  7416.  
  7417. if ((last_bits + here_bits) <= bits) { break; }
  7418. //--- PULLBYTE() ---//
  7419. if (have === 0) { break inf_leave; }
  7420. have--;
  7421. hold += input[next++] << bits;
  7422. bits += 8;
  7423. //---//
  7424. }
  7425. //--- DROPBITS(last.bits) ---//
  7426. hold >>>= last_bits;
  7427. bits -= last_bits;
  7428. //---//
  7429. state.back += last_bits;
  7430. }
  7431. //--- DROPBITS(here.bits) ---//
  7432. hold >>>= here_bits;
  7433. bits -= here_bits;
  7434. //---//
  7435. state.back += here_bits;
  7436. if (here_op & 64) {
  7437. strm.msg = 'invalid distance code';
  7438. state.mode = BAD;
  7439. break;
  7440. }
  7441. state.offset = here_val;
  7442. state.extra = (here_op) & 15;
  7443. state.mode = DISTEXT;
  7444. /* falls through */
  7445. case DISTEXT:
  7446. if (state.extra) {
  7447. //=== NEEDBITS(state.extra);
  7448. n = state.extra;
  7449. while (bits < n) {
  7450. if (have === 0) { break inf_leave; }
  7451. have--;
  7452. hold += input[next++] << bits;
  7453. bits += 8;
  7454. }
  7455. //===//
  7456. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  7457. //--- DROPBITS(state.extra) ---//
  7458. hold >>>= state.extra;
  7459. bits -= state.extra;
  7460. //---//
  7461. state.back += state.extra;
  7462. }
  7463. //#ifdef INFLATE_STRICT
  7464. if (state.offset > state.dmax) {
  7465. strm.msg = 'invalid distance too far back';
  7466. state.mode = BAD;
  7467. break;
  7468. }
  7469. //#endif
  7470. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  7471. state.mode = MATCH;
  7472. /* falls through */
  7473. case MATCH:
  7474. if (left === 0) { break inf_leave; }
  7475. copy = _out - left;
  7476. if (state.offset > copy) { /* copy from window */
  7477. copy = state.offset - copy;
  7478. if (copy > state.whave) {
  7479. if (state.sane) {
  7480. strm.msg = 'invalid distance too far back';
  7481. state.mode = BAD;
  7482. break;
  7483. }
  7484. // (!) This block is disabled in zlib defailts,
  7485. // don't enable it for binary compatibility
  7486. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  7487. // Trace((stderr, "inflate.c too far\n"));
  7488. // copy -= state.whave;
  7489. // if (copy > state.length) { copy = state.length; }
  7490. // if (copy > left) { copy = left; }
  7491. // left -= copy;
  7492. // state.length -= copy;
  7493. // do {
  7494. // output[put++] = 0;
  7495. // } while (--copy);
  7496. // if (state.length === 0) { state.mode = LEN; }
  7497. // break;
  7498. //#endif
  7499. }
  7500. if (copy > state.wnext) {
  7501. copy -= state.wnext;
  7502. from = state.wsize - copy;
  7503. }
  7504. else {
  7505. from = state.wnext - copy;
  7506. }
  7507. if (copy > state.length) { copy = state.length; }
  7508. from_source = state.window;
  7509. }
  7510. else { /* copy from output */
  7511. from_source = output;
  7512. from = put - state.offset;
  7513. copy = state.length;
  7514. }
  7515. if (copy > left) { copy = left; }
  7516. left -= copy;
  7517. state.length -= copy;
  7518. do {
  7519. output[put++] = from_source[from++];
  7520. } while (--copy);
  7521. if (state.length === 0) { state.mode = LEN; }
  7522. break;
  7523. case LIT:
  7524. if (left === 0) { break inf_leave; }
  7525. output[put++] = state.length;
  7526. left--;
  7527. state.mode = LEN;
  7528. break;
  7529. case CHECK:
  7530. if (state.wrap) {
  7531. //=== NEEDBITS(32);
  7532. while (bits < 32) {
  7533. if (have === 0) { break inf_leave; }
  7534. have--;
  7535. // Use '|' insdead of '+' to make sure that result is signed
  7536. hold |= input[next++] << bits;
  7537. bits += 8;
  7538. }
  7539. //===//
  7540. _out -= left;
  7541. strm.total_out += _out;
  7542. state.total += _out;
  7543. if (_out) {
  7544. strm.adler = state.check =
  7545. /*UPDATE(state.check, put - _out, _out);*/
  7546. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  7547.  
  7548. }
  7549. _out = left;
  7550. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  7551. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  7552. strm.msg = 'incorrect data check';
  7553. state.mode = BAD;
  7554. break;
  7555. }
  7556. //=== INITBITS();
  7557. hold = 0;
  7558. bits = 0;
  7559. //===//
  7560. //Tracev((stderr, "inflate: check matches trailer\n"));
  7561. }
  7562. state.mode = LENGTH;
  7563. /* falls through */
  7564. case LENGTH:
  7565. if (state.wrap && state.flags) {
  7566. //=== NEEDBITS(32);
  7567. while (bits < 32) {
  7568. if (have === 0) { break inf_leave; }
  7569. have--;
  7570. hold += input[next++] << bits;
  7571. bits += 8;
  7572. }
  7573. //===//
  7574. if (hold !== (state.total & 0xffffffff)) {
  7575. strm.msg = 'incorrect length check';
  7576. state.mode = BAD;
  7577. break;
  7578. }
  7579. //=== INITBITS();
  7580. hold = 0;
  7581. bits = 0;
  7582. //===//
  7583. //Tracev((stderr, "inflate: length matches trailer\n"));
  7584. }
  7585. state.mode = DONE;
  7586. /* falls through */
  7587. case DONE:
  7588. ret = Z_STREAM_END;
  7589. break inf_leave;
  7590. case BAD:
  7591. ret = Z_DATA_ERROR;
  7592. break inf_leave;
  7593. case MEM:
  7594. return Z_MEM_ERROR;
  7595. case SYNC:
  7596. /* falls through */
  7597. default:
  7598. return Z_STREAM_ERROR;
  7599. }
  7600. }
  7601.  
  7602. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  7603.  
  7604. /*
  7605. Return from inflate(), updating the total counts and the check value.
  7606. If there was no progress during the inflate() call, return a buffer
  7607. error. Call updatewindow() to create and/or update the window state.
  7608. Note: a memory error from inflate() is non-recoverable.
  7609. */
  7610.  
  7611. //--- RESTORE() ---
  7612. strm.next_out = put;
  7613. strm.avail_out = left;
  7614. strm.next_in = next;
  7615. strm.avail_in = have;
  7616. state.hold = hold;
  7617. state.bits = bits;
  7618. //---
  7619.  
  7620. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  7621. (state.mode < CHECK || flush !== Z_FINISH))) {
  7622. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  7623. state.mode = MEM;
  7624. return Z_MEM_ERROR;
  7625. }
  7626. }
  7627. _in -= strm.avail_in;
  7628. _out -= strm.avail_out;
  7629. strm.total_in += _in;
  7630. strm.total_out += _out;
  7631. state.total += _out;
  7632. if (state.wrap && _out) {
  7633. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  7634. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  7635. }
  7636. strm.data_type = state.bits + (state.last ? 64 : 0) +
  7637. (state.mode === TYPE ? 128 : 0) +
  7638. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  7639. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  7640. ret = Z_BUF_ERROR;
  7641. }
  7642. return ret;
  7643. }
  7644.  
  7645. function inflateEnd(strm) {
  7646.  
  7647. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  7648. return Z_STREAM_ERROR;
  7649. }
  7650.  
  7651. var state = strm.state;
  7652. if (state.window) {
  7653. state.window = null;
  7654. }
  7655. strm.state = null;
  7656. return Z_OK;
  7657. }
  7658.  
  7659. function inflateGetHeader(strm, head) {
  7660. var state;
  7661.  
  7662. /* check state */
  7663. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7664. state = strm.state;
  7665. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  7666.  
  7667. /* save header structure */
  7668. state.head = head;
  7669. head.done = false;
  7670. return Z_OK;
  7671. }
  7672.  
  7673.  
  7674. exports.inflateReset = inflateReset;
  7675. exports.inflateReset2 = inflateReset2;
  7676. exports.inflateResetKeep = inflateResetKeep;
  7677. exports.inflateInit = inflateInit;
  7678. exports.inflateInit2 = inflateInit2;
  7679. exports.inflate = inflate;
  7680. exports.inflateEnd = inflateEnd;
  7681. exports.inflateGetHeader = inflateGetHeader;
  7682. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  7683.  
  7684. /* Not implemented
  7685. exports.inflateCopy = inflateCopy;
  7686. exports.inflateGetDictionary = inflateGetDictionary;
  7687. exports.inflateMark = inflateMark;
  7688. exports.inflatePrime = inflatePrime;
  7689. exports.inflateSetDictionary = inflateSetDictionary;
  7690. exports.inflateSync = inflateSync;
  7691. exports.inflateSyncPoint = inflateSyncPoint;
  7692. exports.inflateUndermine = inflateUndermine;
  7693. */
  7694. },{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(_dereq_,module,exports){
  7695. 'use strict';
  7696.  
  7697.  
  7698. var utils = _dereq_('../utils/common');
  7699.  
  7700. var MAXBITS = 15;
  7701. var ENOUGH_LENS = 852;
  7702. var ENOUGH_DISTS = 592;
  7703. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  7704.  
  7705. var CODES = 0;
  7706. var LENS = 1;
  7707. var DISTS = 2;
  7708.  
  7709. var lbase = [ /* Length codes 257..285 base */
  7710. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  7711. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  7712. ];
  7713.  
  7714. var lext = [ /* Length codes 257..285 extra */
  7715. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  7716. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  7717. ];
  7718.  
  7719. var dbase = [ /* Distance codes 0..29 base */
  7720. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  7721. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  7722. 8193, 12289, 16385, 24577, 0, 0
  7723. ];
  7724.  
  7725. var dext = [ /* Distance codes 0..29 extra */
  7726. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  7727. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  7728. 28, 28, 29, 29, 64, 64
  7729. ];
  7730.  
  7731. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  7732. {
  7733. var bits = opts.bits;
  7734. //here = opts.here; /* table entry for duplication */
  7735.  
  7736. var len = 0; /* a code's length in bits */
  7737. var sym = 0; /* index of code symbols */
  7738. var min = 0, max = 0; /* minimum and maximum code lengths */
  7739. var root = 0; /* number of index bits for root table */
  7740. var curr = 0; /* number of index bits for current table */
  7741. var drop = 0; /* code bits to drop for sub-table */
  7742. var left = 0; /* number of prefix codes available */
  7743. var used = 0; /* code entries in table used */
  7744. var huff = 0; /* Huffman code */
  7745. var incr; /* for incrementing code, index */
  7746. var fill; /* index for replicating entries */
  7747. var low; /* low bits for current root entry */
  7748. var mask; /* mask for low root bits */
  7749. var next; /* next available space in table */
  7750. var base = null; /* base value table to use */
  7751. var base_index = 0;
  7752. // var shoextra; /* extra bits table to use */
  7753. var end; /* use base and extra for symbol > end */
  7754. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  7755. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  7756. var extra = null;
  7757. var extra_index = 0;
  7758.  
  7759. var here_bits, here_op, here_val;
  7760.  
  7761. /*
  7762. Process a set of code lengths to create a canonical Huffman code. The
  7763. code lengths are lens[0..codes-1]. Each length corresponds to the
  7764. symbols 0..codes-1. The Huffman code is generated by first sorting the
  7765. symbols by length from short to long, and retaining the symbol order
  7766. for codes with equal lengths. Then the code starts with all zero bits
  7767. for the first code of the shortest length, and the codes are integer
  7768. increments for the same length, and zeros are appended as the length
  7769. increases. For the deflate format, these bits are stored backwards
  7770. from their more natural integer increment ordering, and so when the
  7771. decoding tables are built in the large loop below, the integer codes
  7772. are incremented backwards.
  7773.  
  7774. This routine assumes, but does not check, that all of the entries in
  7775. lens[] are in the range 0..MAXBITS. The caller must assure this.
  7776. 1..MAXBITS is interpreted as that code length. zero means that that
  7777. symbol does not occur in this code.
  7778.  
  7779. The codes are sorted by computing a count of codes for each length,
  7780. creating from that a table of starting indices for each length in the
  7781. sorted table, and then entering the symbols in order in the sorted
  7782. table. The sorted table is work[], with that space being provided by
  7783. the caller.
  7784.  
  7785. The length counts are used for other purposes as well, i.e. finding
  7786. the minimum and maximum length codes, determining if there are any
  7787. codes at all, checking for a valid set of lengths, and looking ahead
  7788. at length counts to determine sub-table sizes when building the
  7789. decoding tables.
  7790. */
  7791.  
  7792. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  7793. for (len = 0; len <= MAXBITS; len++) {
  7794. count[len] = 0;
  7795. }
  7796. for (sym = 0; sym < codes; sym++) {
  7797. count[lens[lens_index + sym]]++;
  7798. }
  7799.  
  7800. /* bound code lengths, force root to be within code lengths */
  7801. root = bits;
  7802. for (max = MAXBITS; max >= 1; max--) {
  7803. if (count[max] !== 0) { break; }
  7804. }
  7805. if (root > max) {
  7806. root = max;
  7807. }
  7808. if (max === 0) { /* no symbols to code at all */
  7809. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  7810. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  7811. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  7812. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  7813.  
  7814.  
  7815. //table.op[opts.table_index] = 64;
  7816. //table.bits[opts.table_index] = 1;
  7817. //table.val[opts.table_index++] = 0;
  7818. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  7819.  
  7820. opts.bits = 1;
  7821. return 0; /* no symbols, but wait for decoding to report error */
  7822. }
  7823. for (min = 1; min < max; min++) {
  7824. if (count[min] !== 0) { break; }
  7825. }
  7826. if (root < min) {
  7827. root = min;
  7828. }
  7829.  
  7830. /* check for an over-subscribed or incomplete set of lengths */
  7831. left = 1;
  7832. for (len = 1; len <= MAXBITS; len++) {
  7833. left <<= 1;
  7834. left -= count[len];
  7835. if (left < 0) {
  7836. return -1;
  7837. } /* over-subscribed */
  7838. }
  7839. if (left > 0 && (type === CODES || max !== 1)) {
  7840. return -1; /* incomplete set */
  7841. }
  7842.  
  7843. /* generate offsets into symbol table for each length for sorting */
  7844. offs[1] = 0;
  7845. for (len = 1; len < MAXBITS; len++) {
  7846. offs[len + 1] = offs[len] + count[len];
  7847. }
  7848.  
  7849. /* sort symbols by length, by symbol order within each length */
  7850. for (sym = 0; sym < codes; sym++) {
  7851. if (lens[lens_index + sym] !== 0) {
  7852. work[offs[lens[lens_index + sym]]++] = sym;
  7853. }
  7854. }
  7855.  
  7856. /*
  7857. Create and fill in decoding tables. In this loop, the table being
  7858. filled is at next and has curr index bits. The code being used is huff
  7859. with length len. That code is converted to an index by dropping drop
  7860. bits off of the bottom. For codes where len is less than drop + curr,
  7861. those top drop + curr - len bits are incremented through all values to
  7862. fill the table with replicated entries.
  7863.  
  7864. root is the number of index bits for the root table. When len exceeds
  7865. root, sub-tables are created pointed to by the root entry with an index
  7866. of the low root bits of huff. This is saved in low to check for when a
  7867. new sub-table should be started. drop is zero when the root table is
  7868. being filled, and drop is root when sub-tables are being filled.
  7869.  
  7870. When a new sub-table is needed, it is necessary to look ahead in the
  7871. code lengths to determine what size sub-table is needed. The length
  7872. counts are used for this, and so count[] is decremented as codes are
  7873. entered in the tables.
  7874.  
  7875. used keeps track of how many table entries have been allocated from the
  7876. provided *table space. It is checked for LENS and DIST tables against
  7877. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  7878. the initial root table size constants. See the comments in inftrees.h
  7879. for more information.
  7880.  
  7881. sym increments through all symbols, and the loop terminates when
  7882. all codes of length max, i.e. all codes, have been processed. This
  7883. routine permits incomplete codes, so another loop after this one fills
  7884. in the rest of the decoding tables with invalid code markers.
  7885. */
  7886.  
  7887. /* set up for code type */
  7888. // poor man optimization - use if-else instead of switch,
  7889. // to avoid deopts in old v8
  7890. if (type === CODES) {
  7891. base = extra = work; /* dummy value--not used */
  7892. end = 19;
  7893. } else if (type === LENS) {
  7894. base = lbase;
  7895. base_index -= 257;
  7896. extra = lext;
  7897. extra_index -= 257;
  7898. end = 256;
  7899. } else { /* DISTS */
  7900. base = dbase;
  7901. extra = dext;
  7902. end = -1;
  7903. }
  7904.  
  7905. /* initialize opts for loop */
  7906. huff = 0; /* starting code */
  7907. sym = 0; /* starting code symbol */
  7908. len = min; /* starting code length */
  7909. next = table_index; /* current table to fill in */
  7910. curr = root; /* current table index bits */
  7911. drop = 0; /* current bits to drop from code for index */
  7912. low = -1; /* trigger new sub-table when len > root */
  7913. used = 1 << root; /* use root table entries */
  7914. mask = used - 1; /* mask for comparing low */
  7915.  
  7916. /* check available table space */
  7917. if ((type === LENS && used > ENOUGH_LENS) ||
  7918. (type === DISTS && used > ENOUGH_DISTS)) {
  7919. return 1;
  7920. }
  7921.  
  7922. var i=0;
  7923. /* process all codes and make table entries */
  7924. for (;;) {
  7925. i++;
  7926. /* create table entry */
  7927. here_bits = len - drop;
  7928. if (work[sym] < end) {
  7929. here_op = 0;
  7930. here_val = work[sym];
  7931. }
  7932. else if (work[sym] > end) {
  7933. here_op = extra[extra_index + work[sym]];
  7934. here_val = base[base_index + work[sym]];
  7935. }
  7936. else {
  7937. here_op = 32 + 64; /* end of block */
  7938. here_val = 0;
  7939. }
  7940.  
  7941. /* replicate for those indices with low len bits equal to huff */
  7942. incr = 1 << (len - drop);
  7943. fill = 1 << curr;
  7944. min = fill; /* save offset to next table */
  7945. do {
  7946. fill -= incr;
  7947. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  7948. } while (fill !== 0);
  7949.  
  7950. /* backwards increment the len-bit code huff */
  7951. incr = 1 << (len - 1);
  7952. while (huff & incr) {
  7953. incr >>= 1;
  7954. }
  7955. if (incr !== 0) {
  7956. huff &= incr - 1;
  7957. huff += incr;
  7958. } else {
  7959. huff = 0;
  7960. }
  7961.  
  7962. /* go to next symbol, update count, len */
  7963. sym++;
  7964. if (--count[len] === 0) {
  7965. if (len === max) { break; }
  7966. len = lens[lens_index + work[sym]];
  7967. }
  7968.  
  7969. /* create new sub-table if needed */
  7970. if (len > root && (huff & mask) !== low) {
  7971. /* if first time, transition to sub-tables */
  7972. if (drop === 0) {
  7973. drop = root;
  7974. }
  7975.  
  7976. /* increment past last table */
  7977. next += min; /* here min is 1 << curr */
  7978.  
  7979. /* determine length of next table */
  7980. curr = len - drop;
  7981. left = 1 << curr;
  7982. while (curr + drop < max) {
  7983. left -= count[curr + drop];
  7984. if (left <= 0) { break; }
  7985. curr++;
  7986. left <<= 1;
  7987. }
  7988.  
  7989. /* check for enough space */
  7990. used += 1 << curr;
  7991. if ((type === LENS && used > ENOUGH_LENS) ||
  7992. (type === DISTS && used > ENOUGH_DISTS)) {
  7993. return 1;
  7994. }
  7995.  
  7996. /* point entry in root table to sub-table */
  7997. low = huff & mask;
  7998. /*table.op[low] = curr;
  7999. table.bits[low] = root;
  8000. table.val[low] = next - opts.table_index;*/
  8001. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  8002. }
  8003. }
  8004.  
  8005. /* fill in remaining table entry if code is incomplete (guaranteed to have
  8006. at most one remaining entry, since if the code is incomplete, the
  8007. maximum code length that was allowed to get this far is one bit) */
  8008. if (huff !== 0) {
  8009. //table.op[next + huff] = 64; /* invalid code marker */
  8010. //table.bits[next + huff] = len - drop;
  8011. //table.val[next + huff] = 0;
  8012. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  8013. }
  8014.  
  8015. /* set return parameters */
  8016. //opts.table_index += used;
  8017. opts.bits = root;
  8018. return 0;
  8019. };
  8020.  
  8021. },{"../utils/common":27}],37:[function(_dereq_,module,exports){
  8022. 'use strict';
  8023.  
  8024. module.exports = {
  8025. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  8026. '1': 'stream end', /* Z_STREAM_END 1 */
  8027. '0': '', /* Z_OK 0 */
  8028. '-1': 'file error', /* Z_ERRNO (-1) */
  8029. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  8030. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  8031. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  8032. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  8033. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  8034. };
  8035. },{}],38:[function(_dereq_,module,exports){
  8036. 'use strict';
  8037.  
  8038.  
  8039. var utils = _dereq_('../utils/common');
  8040.  
  8041. /* Public constants ==========================================================*/
  8042. /* ===========================================================================*/
  8043.  
  8044.  
  8045. //var Z_FILTERED = 1;
  8046. //var Z_HUFFMAN_ONLY = 2;
  8047. //var Z_RLE = 3;
  8048. var Z_FIXED = 4;
  8049. //var Z_DEFAULT_STRATEGY = 0;
  8050.  
  8051. /* Possible values of the data_type field (though see inflate()) */
  8052. var Z_BINARY = 0;
  8053. var Z_TEXT = 1;
  8054. //var Z_ASCII = 1; // = Z_TEXT
  8055. var Z_UNKNOWN = 2;
  8056.  
  8057. /*============================================================================*/
  8058.  
  8059.  
  8060. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  8061.  
  8062. // From zutil.h
  8063.  
  8064. var STORED_BLOCK = 0;
  8065. var STATIC_TREES = 1;
  8066. var DYN_TREES = 2;
  8067. /* The three kinds of block type */
  8068.  
  8069. var MIN_MATCH = 3;
  8070. var MAX_MATCH = 258;
  8071. /* The minimum and maximum match lengths */
  8072.  
  8073. // From deflate.h
  8074. /* ===========================================================================
  8075. * Internal compression state.
  8076. */
  8077.  
  8078. var LENGTH_CODES = 29;
  8079. /* number of length codes, not counting the special END_BLOCK code */
  8080.  
  8081. var LITERALS = 256;
  8082. /* number of literal bytes 0..255 */
  8083.  
  8084. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  8085. /* number of Literal or Length codes, including the END_BLOCK code */
  8086.  
  8087. var D_CODES = 30;
  8088. /* number of distance codes */
  8089.  
  8090. var BL_CODES = 19;
  8091. /* number of codes used to transfer the bit lengths */
  8092.  
  8093. var HEAP_SIZE = 2*L_CODES + 1;
  8094. /* maximum heap size */
  8095.  
  8096. var MAX_BITS = 15;
  8097. /* All codes must not exceed MAX_BITS bits */
  8098.  
  8099. var Buf_size = 16;
  8100. /* size of bit buffer in bi_buf */
  8101.  
  8102.  
  8103. /* ===========================================================================
  8104. * Constants
  8105. */
  8106.  
  8107. var MAX_BL_BITS = 7;
  8108. /* Bit length codes must not exceed MAX_BL_BITS bits */
  8109.  
  8110. var END_BLOCK = 256;
  8111. /* end of block literal code */
  8112.  
  8113. var REP_3_6 = 16;
  8114. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  8115.  
  8116. var REPZ_3_10 = 17;
  8117. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  8118.  
  8119. var REPZ_11_138 = 18;
  8120. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  8121.  
  8122. var extra_lbits = /* extra bits for each length code */
  8123. [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];
  8124.  
  8125. var extra_dbits = /* extra bits for each distance code */
  8126. [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];
  8127.  
  8128. var extra_blbits = /* extra bits for each bit length code */
  8129. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  8130.  
  8131. var bl_order =
  8132. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  8133. /* The lengths of the bit length codes are sent in order of decreasing
  8134. * probability, to avoid transmitting the lengths for unused bit length codes.
  8135. */
  8136.  
  8137. /* ===========================================================================
  8138. * Local data. These are initialized only once.
  8139. */
  8140.  
  8141. // We pre-fill arrays with 0 to avoid uninitialized gaps
  8142.  
  8143. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  8144.  
  8145. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  8146. var static_ltree = new Array((L_CODES+2) * 2);
  8147. zero(static_ltree);
  8148. /* The static literal tree. Since the bit lengths are imposed, there is no
  8149. * need for the L_CODES extra codes used during heap construction. However
  8150. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  8151. * below).
  8152. */
  8153.  
  8154. var static_dtree = new Array(D_CODES * 2);
  8155. zero(static_dtree);
  8156. /* The static distance tree. (Actually a trivial tree since all codes use
  8157. * 5 bits.)
  8158. */
  8159.  
  8160. var _dist_code = new Array(DIST_CODE_LEN);
  8161. zero(_dist_code);
  8162. /* Distance codes. The first 256 values correspond to the distances
  8163. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  8164. * the 15 bit distances.
  8165. */
  8166.  
  8167. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  8168. zero(_length_code);
  8169. /* length code for each normalized match length (0 == MIN_MATCH) */
  8170.  
  8171. var base_length = new Array(LENGTH_CODES);
  8172. zero(base_length);
  8173. /* First normalized length for each code (0 = MIN_MATCH) */
  8174.  
  8175. var base_dist = new Array(D_CODES);
  8176. zero(base_dist);
  8177. /* First normalized distance for each code (0 = distance of 1) */
  8178.  
  8179.  
  8180. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  8181.  
  8182. this.static_tree = static_tree; /* static tree or NULL */
  8183. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  8184. this.extra_base = extra_base; /* base index for extra_bits */
  8185. this.elems = elems; /* max number of elements in the tree */
  8186. this.max_length = max_length; /* max bit length for the codes */
  8187.  
  8188. // show if `static_tree` has data or dummy - needed for monomorphic objects
  8189. this.has_stree = static_tree && static_tree.length;
  8190. };
  8191.  
  8192.  
  8193. var static_l_desc;
  8194. var static_d_desc;
  8195. var static_bl_desc;
  8196.  
  8197.  
  8198. var TreeDesc = function(dyn_tree, stat_desc) {
  8199. this.dyn_tree = dyn_tree; /* the dynamic tree */
  8200. this.max_code = 0; /* largest code with non zero frequency */
  8201. this.stat_desc = stat_desc; /* the corresponding static tree */
  8202. };
  8203.  
  8204.  
  8205.  
  8206. function d_code(dist) {
  8207. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  8208. }
  8209.  
  8210.  
  8211. /* ===========================================================================
  8212. * Output a short LSB first on the stream.
  8213. * IN assertion: there is enough room in pendingBuf.
  8214. */
  8215. function put_short (s, w) {
  8216. // put_byte(s, (uch)((w) & 0xff));
  8217. // put_byte(s, (uch)((ush)(w) >> 8));
  8218. s.pending_buf[s.pending++] = (w) & 0xff;
  8219. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  8220. }
  8221.  
  8222.  
  8223. /* ===========================================================================
  8224. * Send a value on a given number of bits.
  8225. * IN assertion: length <= 16 and value fits in length bits.
  8226. */
  8227. function send_bits(s, value, length) {
  8228. if (s.bi_valid > (Buf_size - length)) {
  8229. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  8230. put_short(s, s.bi_buf);
  8231. s.bi_buf = value >> (Buf_size - s.bi_valid);
  8232. s.bi_valid += length - Buf_size;
  8233. } else {
  8234. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  8235. s.bi_valid += length;
  8236. }
  8237. }
  8238.  
  8239.  
  8240. function send_code(s, c, tree) {
  8241. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  8242. }
  8243.  
  8244.  
  8245. /* ===========================================================================
  8246. * Reverse the first len bits of a code, using straightforward code (a faster
  8247. * method would use a table)
  8248. * IN assertion: 1 <= len <= 15
  8249. */
  8250. function bi_reverse(code, len) {
  8251. var res = 0;
  8252. do {
  8253. res |= code & 1;
  8254. code >>>= 1;
  8255. res <<= 1;
  8256. } while (--len > 0);
  8257. return res >>> 1;
  8258. }
  8259.  
  8260.  
  8261. /* ===========================================================================
  8262. * Flush the bit buffer, keeping at most 7 bits in it.
  8263. */
  8264. function bi_flush(s) {
  8265. if (s.bi_valid === 16) {
  8266. put_short(s, s.bi_buf);
  8267. s.bi_buf = 0;
  8268. s.bi_valid = 0;
  8269.  
  8270. } else if (s.bi_valid >= 8) {
  8271. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  8272. s.bi_buf >>= 8;
  8273. s.bi_valid -= 8;
  8274. }
  8275. }
  8276.  
  8277.  
  8278. /* ===========================================================================
  8279. * Compute the optimal bit lengths for a tree and update the total bit length
  8280. * for the current block.
  8281. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  8282. * above are the tree nodes sorted by increasing frequency.
  8283. * OUT assertions: the field len is set to the optimal bit length, the
  8284. * array bl_count contains the frequencies for each bit length.
  8285. * The length opt_len is updated; static_len is also updated if stree is
  8286. * not null.
  8287. */
  8288. function gen_bitlen(s, desc)
  8289. // deflate_state *s;
  8290. // tree_desc *desc; /* the tree descriptor */
  8291. {
  8292. var tree = desc.dyn_tree;
  8293. var max_code = desc.max_code;
  8294. var stree = desc.stat_desc.static_tree;
  8295. var has_stree = desc.stat_desc.has_stree;
  8296. var extra = desc.stat_desc.extra_bits;
  8297. var base = desc.stat_desc.extra_base;
  8298. var max_length = desc.stat_desc.max_length;
  8299. var h; /* heap index */
  8300. var n, m; /* iterate over the tree elements */
  8301. var bits; /* bit length */
  8302. var xbits; /* extra bits */
  8303. var f; /* frequency */
  8304. var overflow = 0; /* number of elements with bit length too large */
  8305.  
  8306. for (bits = 0; bits <= MAX_BITS; bits++) {
  8307. s.bl_count[bits] = 0;
  8308. }
  8309.  
  8310. /* In a first pass, compute the optimal bit lengths (which may
  8311. * overflow in the case of the bit length tree).
  8312. */
  8313. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  8314.  
  8315. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  8316. n = s.heap[h];
  8317. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  8318. if (bits > max_length) {
  8319. bits = max_length;
  8320. overflow++;
  8321. }
  8322. tree[n*2 + 1]/*.Len*/ = bits;
  8323. /* We overwrite tree[n].Dad which is no longer needed */
  8324.  
  8325. if (n > max_code) { continue; } /* not a leaf node */
  8326.  
  8327. s.bl_count[bits]++;
  8328. xbits = 0;
  8329. if (n >= base) {
  8330. xbits = extra[n-base];
  8331. }
  8332. f = tree[n * 2]/*.Freq*/;
  8333. s.opt_len += f * (bits + xbits);
  8334. if (has_stree) {
  8335. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  8336. }
  8337. }
  8338. if (overflow === 0) { return; }
  8339.  
  8340. // Trace((stderr,"\nbit length overflow\n"));
  8341. /* This happens for example on obj2 and pic of the Calgary corpus */
  8342.  
  8343. /* Find the first bit length which could increase: */
  8344. do {
  8345. bits = max_length-1;
  8346. while (s.bl_count[bits] === 0) { bits--; }
  8347. s.bl_count[bits]--; /* move one leaf down the tree */
  8348. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  8349. s.bl_count[max_length]--;
  8350. /* The brother of the overflow item also moves one step up,
  8351. * but this does not affect bl_count[max_length]
  8352. */
  8353. overflow -= 2;
  8354. } while (overflow > 0);
  8355.  
  8356. /* Now recompute all bit lengths, scanning in increasing frequency.
  8357. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  8358. * lengths instead of fixing only the wrong ones. This idea is taken
  8359. * from 'ar' written by Haruhiko Okumura.)
  8360. */
  8361. for (bits = max_length; bits !== 0; bits--) {
  8362. n = s.bl_count[bits];
  8363. while (n !== 0) {
  8364. m = s.heap[--h];
  8365. if (m > max_code) { continue; }
  8366. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  8367. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  8368. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  8369. tree[m*2 + 1]/*.Len*/ = bits;
  8370. }
  8371. n--;
  8372. }
  8373. }
  8374. }
  8375.  
  8376.  
  8377. /* ===========================================================================
  8378. * Generate the codes for a given tree and bit counts (which need not be
  8379. * optimal).
  8380. * IN assertion: the array bl_count contains the bit length statistics for
  8381. * the given tree and the field len is set for all tree elements.
  8382. * OUT assertion: the field code is set for all tree elements of non
  8383. * zero code length.
  8384. */
  8385. function gen_codes(tree, max_code, bl_count)
  8386. // ct_data *tree; /* the tree to decorate */
  8387. // int max_code; /* largest code with non zero frequency */
  8388. // ushf *bl_count; /* number of codes at each bit length */
  8389. {
  8390. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  8391. var code = 0; /* running code value */
  8392. var bits; /* bit index */
  8393. var n; /* code index */
  8394.  
  8395. /* The distribution counts are first used to generate the code values
  8396. * without bit reversal.
  8397. */
  8398. for (bits = 1; bits <= MAX_BITS; bits++) {
  8399. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  8400. }
  8401. /* Check that the bit counts in bl_count are consistent. The last code
  8402. * must be all ones.
  8403. */
  8404. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  8405. // "inconsistent bit counts");
  8406. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  8407.  
  8408. for (n = 0; n <= max_code; n++) {
  8409. var len = tree[n*2 + 1]/*.Len*/;
  8410. if (len === 0) { continue; }
  8411. /* Now reverse the bits */
  8412. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  8413.  
  8414. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  8415. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  8416. }
  8417. }
  8418.  
  8419.  
  8420. /* ===========================================================================
  8421. * Initialize the various 'constant' tables.
  8422. */
  8423. function tr_static_init() {
  8424. var n; /* iterates over tree elements */
  8425. var bits; /* bit counter */
  8426. var length; /* length value */
  8427. var code; /* code value */
  8428. var dist; /* distance index */
  8429. var bl_count = new Array(MAX_BITS+1);
  8430. /* number of codes at each bit length for an optimal tree */
  8431.  
  8432. // do check in _tr_init()
  8433. //if (static_init_done) return;
  8434.  
  8435. /* For some embedded targets, global variables are not initialized: */
  8436. /*#ifdef NO_INIT_GLOBAL_POINTERS
  8437. static_l_desc.static_tree = static_ltree;
  8438. static_l_desc.extra_bits = extra_lbits;
  8439. static_d_desc.static_tree = static_dtree;
  8440. static_d_desc.extra_bits = extra_dbits;
  8441. static_bl_desc.extra_bits = extra_blbits;
  8442. #endif*/
  8443.  
  8444. /* Initialize the mapping length (0..255) -> length code (0..28) */
  8445. length = 0;
  8446. for (code = 0; code < LENGTH_CODES-1; code++) {
  8447. base_length[code] = length;
  8448. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  8449. _length_code[length++] = code;
  8450. }
  8451. }
  8452. //Assert (length == 256, "tr_static_init: length != 256");
  8453. /* Note that the length 255 (match length 258) can be represented
  8454. * in two different ways: code 284 + 5 bits or code 285, so we
  8455. * overwrite length_code[255] to use the best encoding:
  8456. */
  8457. _length_code[length-1] = code;
  8458.  
  8459. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  8460. dist = 0;
  8461. for (code = 0 ; code < 16; code++) {
  8462. base_dist[code] = dist;
  8463. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  8464. _dist_code[dist++] = code;
  8465. }
  8466. }
  8467. //Assert (dist == 256, "tr_static_init: dist != 256");
  8468. dist >>= 7; /* from now on, all distances are divided by 128 */
  8469. for ( ; code < D_CODES; code++) {
  8470. base_dist[code] = dist << 7;
  8471. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  8472. _dist_code[256 + dist++] = code;
  8473. }
  8474. }
  8475. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  8476.  
  8477. /* Construct the codes of the static literal tree */
  8478. for (bits = 0; bits <= MAX_BITS; bits++) {
  8479. bl_count[bits] = 0;
  8480. }
  8481.  
  8482. n = 0;
  8483. while (n <= 143) {
  8484. static_ltree[n*2 + 1]/*.Len*/ = 8;
  8485. n++;
  8486. bl_count[8]++;
  8487. }
  8488. while (n <= 255) {
  8489. static_ltree[n*2 + 1]/*.Len*/ = 9;
  8490. n++;
  8491. bl_count[9]++;
  8492. }
  8493. while (n <= 279) {
  8494. static_ltree[n*2 + 1]/*.Len*/ = 7;
  8495. n++;
  8496. bl_count[7]++;
  8497. }
  8498. while (n <= 287) {
  8499. static_ltree[n*2 + 1]/*.Len*/ = 8;
  8500. n++;
  8501. bl_count[8]++;
  8502. }
  8503. /* Codes 286 and 287 do not exist, but we must include them in the
  8504. * tree construction to get a canonical Huffman tree (longest code
  8505. * all ones)
  8506. */
  8507. gen_codes(static_ltree, L_CODES+1, bl_count);
  8508.  
  8509. /* The static distance tree is trivial: */
  8510. for (n = 0; n < D_CODES; n++) {
  8511. static_dtree[n*2 + 1]/*.Len*/ = 5;
  8512. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  8513. }
  8514.  
  8515. // Now data ready and we can init static trees
  8516. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  8517. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  8518. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  8519.  
  8520. //static_init_done = true;
  8521. }
  8522.  
  8523.  
  8524. /* ===========================================================================
  8525. * Initialize a new block.
  8526. */
  8527. function init_block(s) {
  8528. var n; /* iterates over tree elements */
  8529.  
  8530. /* Initialize the trees. */
  8531. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  8532. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  8533. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  8534.  
  8535. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  8536. s.opt_len = s.static_len = 0;
  8537. s.last_lit = s.matches = 0;
  8538. }
  8539.  
  8540.  
  8541. /* ===========================================================================
  8542. * Flush the bit buffer and align the output on a byte boundary
  8543. */
  8544. function bi_windup(s)
  8545. {
  8546. if (s.bi_valid > 8) {
  8547. put_short(s, s.bi_buf);
  8548. } else if (s.bi_valid > 0) {
  8549. //put_byte(s, (Byte)s->bi_buf);
  8550. s.pending_buf[s.pending++] = s.bi_buf;
  8551. }
  8552. s.bi_buf = 0;
  8553. s.bi_valid = 0;
  8554. }
  8555.  
  8556. /* ===========================================================================
  8557. * Copy a stored block, storing first the length and its
  8558. * one's complement if requested.
  8559. */
  8560. function copy_block(s, buf, len, header)
  8561. //DeflateState *s;
  8562. //charf *buf; /* the input data */
  8563. //unsigned len; /* its length */
  8564. //int header; /* true if block header must be written */
  8565. {
  8566. bi_windup(s); /* align on byte boundary */
  8567.  
  8568. if (header) {
  8569. put_short(s, len);
  8570. put_short(s, ~len);
  8571. }
  8572. // while (len--) {
  8573. // put_byte(s, *buf++);
  8574. // }
  8575. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  8576. s.pending += len;
  8577. }
  8578.  
  8579. /* ===========================================================================
  8580. * Compares to subtrees, using the tree depth as tie breaker when
  8581. * the subtrees have equal frequency. This minimizes the worst case length.
  8582. */
  8583. function smaller(tree, n, m, depth) {
  8584. var _n2 = n*2;
  8585. var _m2 = m*2;
  8586. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  8587. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  8588. }
  8589.  
  8590. /* ===========================================================================
  8591. * Restore the heap property by moving down the tree starting at node k,
  8592. * exchanging a node with the smallest of its two sons if necessary, stopping
  8593. * when the heap property is re-established (each father smaller than its
  8594. * two sons).
  8595. */
  8596. function pqdownheap(s, tree, k)
  8597. // deflate_state *s;
  8598. // ct_data *tree; /* the tree to restore */
  8599. // int k; /* node to move down */
  8600. {
  8601. var v = s.heap[k];
  8602. var j = k << 1; /* left son of k */
  8603. while (j <= s.heap_len) {
  8604. /* Set j to the smallest of the two sons: */
  8605. if (j < s.heap_len &&
  8606. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  8607. j++;
  8608. }
  8609. /* Exit if v is smaller than both sons */
  8610. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  8611.  
  8612. /* Exchange v with the smallest son */
  8613. s.heap[k] = s.heap[j];
  8614. k = j;
  8615.  
  8616. /* And continue down the tree, setting j to the left son of k */
  8617. j <<= 1;
  8618. }
  8619. s.heap[k] = v;
  8620. }
  8621.  
  8622.  
  8623. // inlined manually
  8624. // var SMALLEST = 1;
  8625.  
  8626. /* ===========================================================================
  8627. * Send the block data compressed using the given Huffman trees
  8628. */
  8629. function compress_block(s, ltree, dtree)
  8630. // deflate_state *s;
  8631. // const ct_data *ltree; /* literal tree */
  8632. // const ct_data *dtree; /* distance tree */
  8633. {
  8634. var dist; /* distance of matched string */
  8635. var lc; /* match length or unmatched char (if dist == 0) */
  8636. var lx = 0; /* running index in l_buf */
  8637. var code; /* the code to send */
  8638. var extra; /* number of extra bits to send */
  8639.  
  8640. if (s.last_lit !== 0) {
  8641. do {
  8642. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  8643. lc = s.pending_buf[s.l_buf + lx];
  8644. lx++;
  8645.  
  8646. if (dist === 0) {
  8647. send_code(s, lc, ltree); /* send a literal byte */
  8648. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  8649. } else {
  8650. /* Here, lc is the match length - MIN_MATCH */
  8651. code = _length_code[lc];
  8652. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  8653. extra = extra_lbits[code];
  8654. if (extra !== 0) {
  8655. lc -= base_length[code];
  8656. send_bits(s, lc, extra); /* send the extra length bits */
  8657. }
  8658. dist--; /* dist is now the match distance - 1 */
  8659. code = d_code(dist);
  8660. //Assert (code < D_CODES, "bad d_code");
  8661.  
  8662. send_code(s, code, dtree); /* send the distance code */
  8663. extra = extra_dbits[code];
  8664. if (extra !== 0) {
  8665. dist -= base_dist[code];
  8666. send_bits(s, dist, extra); /* send the extra distance bits */
  8667. }
  8668. } /* literal or match pair ? */
  8669.  
  8670. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  8671. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  8672. // "pendingBuf overflow");
  8673.  
  8674. } while (lx < s.last_lit);
  8675. }
  8676.  
  8677. send_code(s, END_BLOCK, ltree);
  8678. }
  8679.  
  8680.  
  8681. /* ===========================================================================
  8682. * Construct one Huffman tree and assigns the code bit strings and lengths.
  8683. * Update the total bit length for the current block.
  8684. * IN assertion: the field freq is set for all tree elements.
  8685. * OUT assertions: the fields len and code are set to the optimal bit length
  8686. * and corresponding code. The length opt_len is updated; static_len is
  8687. * also updated if stree is not null. The field max_code is set.
  8688. */
  8689. function build_tree(s, desc)
  8690. // deflate_state *s;
  8691. // tree_desc *desc; /* the tree descriptor */
  8692. {
  8693. var tree = desc.dyn_tree;
  8694. var stree = desc.stat_desc.static_tree;
  8695. var has_stree = desc.stat_desc.has_stree;
  8696. var elems = desc.stat_desc.elems;
  8697. var n, m; /* iterate over heap elements */
  8698. var max_code = -1; /* largest code with non zero frequency */
  8699. var node; /* new node being created */
  8700.  
  8701. /* Construct the initial heap, with least frequent element in
  8702. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  8703. * heap[0] is not used.
  8704. */
  8705. s.heap_len = 0;
  8706. s.heap_max = HEAP_SIZE;
  8707.  
  8708. for (n = 0; n < elems; n++) {
  8709. if (tree[n * 2]/*.Freq*/ !== 0) {
  8710. s.heap[++s.heap_len] = max_code = n;
  8711. s.depth[n] = 0;
  8712.  
  8713. } else {
  8714. tree[n*2 + 1]/*.Len*/ = 0;
  8715. }
  8716. }
  8717.  
  8718. /* The pkzip format requires that at least one distance code exists,
  8719. * and that at least one bit should be sent even if there is only one
  8720. * possible code. So to avoid special checks later on we force at least
  8721. * two codes of non zero frequency.
  8722. */
  8723. while (s.heap_len < 2) {
  8724. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  8725. tree[node * 2]/*.Freq*/ = 1;
  8726. s.depth[node] = 0;
  8727. s.opt_len--;
  8728.  
  8729. if (has_stree) {
  8730. s.static_len -= stree[node*2 + 1]/*.Len*/;
  8731. }
  8732. /* node is 0 or 1 so it does not have extra bits */
  8733. }
  8734. desc.max_code = max_code;
  8735.  
  8736. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  8737. * establish sub-heaps of increasing lengths:
  8738. */
  8739. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  8740.  
  8741. /* Construct the Huffman tree by repeatedly combining the least two
  8742. * frequent nodes.
  8743. */
  8744. node = elems; /* next internal node of the tree */
  8745. do {
  8746. //pqremove(s, tree, n); /* n = node of least frequency */
  8747. /*** pqremove ***/
  8748. n = s.heap[1/*SMALLEST*/];
  8749. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  8750. pqdownheap(s, tree, 1/*SMALLEST*/);
  8751. /***/
  8752.  
  8753. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  8754.  
  8755. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  8756. s.heap[--s.heap_max] = m;
  8757.  
  8758. /* Create a new node father of n and m */
  8759. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  8760. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  8761. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  8762.  
  8763. /* and insert the new node in the heap */
  8764. s.heap[1/*SMALLEST*/] = node++;
  8765. pqdownheap(s, tree, 1/*SMALLEST*/);
  8766.  
  8767. } while (s.heap_len >= 2);
  8768.  
  8769. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  8770.  
  8771. /* At this point, the fields freq and dad are set. We can now
  8772. * generate the bit lengths.
  8773. */
  8774. gen_bitlen(s, desc);
  8775.  
  8776. /* The field len is now set, we can generate the bit codes */
  8777. gen_codes(tree, max_code, s.bl_count);
  8778. }
  8779.  
  8780.  
  8781. /* ===========================================================================
  8782. * Scan a literal or distance tree to determine the frequencies of the codes
  8783. * in the bit length tree.
  8784. */
  8785. function scan_tree(s, tree, max_code)
  8786. // deflate_state *s;
  8787. // ct_data *tree; /* the tree to be scanned */
  8788. // int max_code; /* and its largest code of non zero frequency */
  8789. {
  8790. var n; /* iterates over all tree elements */
  8791. var prevlen = -1; /* last emitted length */
  8792. var curlen; /* length of current code */
  8793.  
  8794. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  8795.  
  8796. var count = 0; /* repeat count of the current code */
  8797. var max_count = 7; /* max repeat count */
  8798. var min_count = 4; /* min repeat count */
  8799.  
  8800. if (nextlen === 0) {
  8801. max_count = 138;
  8802. min_count = 3;
  8803. }
  8804. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  8805.  
  8806. for (n = 0; n <= max_code; n++) {
  8807. curlen = nextlen;
  8808. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  8809.  
  8810. if (++count < max_count && curlen === nextlen) {
  8811. continue;
  8812.  
  8813. } else if (count < min_count) {
  8814. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  8815.  
  8816. } else if (curlen !== 0) {
  8817.  
  8818. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  8819. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  8820.  
  8821. } else if (count <= 10) {
  8822. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  8823.  
  8824. } else {
  8825. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  8826. }
  8827.  
  8828. count = 0;
  8829. prevlen = curlen;
  8830.  
  8831. if (nextlen === 0) {
  8832. max_count = 138;
  8833. min_count = 3;
  8834.  
  8835. } else if (curlen === nextlen) {
  8836. max_count = 6;
  8837. min_count = 3;
  8838.  
  8839. } else {
  8840. max_count = 7;
  8841. min_count = 4;
  8842. }
  8843. }
  8844. }
  8845.  
  8846.  
  8847. /* ===========================================================================
  8848. * Send a literal or distance tree in compressed form, using the codes in
  8849. * bl_tree.
  8850. */
  8851. function send_tree(s, tree, max_code)
  8852. // deflate_state *s;
  8853. // ct_data *tree; /* the tree to be scanned */
  8854. // int max_code; /* and its largest code of non zero frequency */
  8855. {
  8856. var n; /* iterates over all tree elements */
  8857. var prevlen = -1; /* last emitted length */
  8858. var curlen; /* length of current code */
  8859.  
  8860. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  8861.  
  8862. var count = 0; /* repeat count of the current code */
  8863. var max_count = 7; /* max repeat count */
  8864. var min_count = 4; /* min repeat count */
  8865.  
  8866. /* tree[max_code+1].Len = -1; */ /* guard already set */
  8867. if (nextlen === 0) {
  8868. max_count = 138;
  8869. min_count = 3;
  8870. }
  8871.  
  8872. for (n = 0; n <= max_code; n++) {
  8873. curlen = nextlen;
  8874. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  8875.  
  8876. if (++count < max_count && curlen === nextlen) {
  8877. continue;
  8878.  
  8879. } else if (count < min_count) {
  8880. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  8881.  
  8882. } else if (curlen !== 0) {
  8883. if (curlen !== prevlen) {
  8884. send_code(s, curlen, s.bl_tree);
  8885. count--;
  8886. }
  8887. //Assert(count >= 3 && count <= 6, " 3_6?");
  8888. send_code(s, REP_3_6, s.bl_tree);
  8889. send_bits(s, count-3, 2);
  8890.  
  8891. } else if (count <= 10) {
  8892. send_code(s, REPZ_3_10, s.bl_tree);
  8893. send_bits(s, count-3, 3);
  8894.  
  8895. } else {
  8896. send_code(s, REPZ_11_138, s.bl_tree);
  8897. send_bits(s, count-11, 7);
  8898. }
  8899.  
  8900. count = 0;
  8901. prevlen = curlen;
  8902. if (nextlen === 0) {
  8903. max_count = 138;
  8904. min_count = 3;
  8905.  
  8906. } else if (curlen === nextlen) {
  8907. max_count = 6;
  8908. min_count = 3;
  8909.  
  8910. } else {
  8911. max_count = 7;
  8912. min_count = 4;
  8913. }
  8914. }
  8915. }
  8916.  
  8917.  
  8918. /* ===========================================================================
  8919. * Construct the Huffman tree for the bit lengths and return the index in
  8920. * bl_order of the last bit length code to send.
  8921. */
  8922. function build_bl_tree(s) {
  8923. var max_blindex; /* index of last bit length code of non zero freq */
  8924.  
  8925. /* Determine the bit length frequencies for literal and distance trees */
  8926. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  8927. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  8928.  
  8929. /* Build the bit length tree: */
  8930. build_tree(s, s.bl_desc);
  8931. /* opt_len now includes the length of the tree representations, except
  8932. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  8933. */
  8934.  
  8935. /* Determine the number of bit length codes to send. The pkzip format
  8936. * requires that at least 4 bit length codes be sent. (appnote.txt says
  8937. * 3 but the actual value used is 4.)
  8938. */
  8939. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  8940. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  8941. break;
  8942. }
  8943. }
  8944. /* Update opt_len to include the bit length tree and counts */
  8945. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  8946. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  8947. // s->opt_len, s->static_len));
  8948.  
  8949. return max_blindex;
  8950. }
  8951.  
  8952.  
  8953. /* ===========================================================================
  8954. * Send the header for a block using dynamic Huffman trees: the counts, the
  8955. * lengths of the bit length codes, the literal tree and the distance tree.
  8956. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  8957. */
  8958. function send_all_trees(s, lcodes, dcodes, blcodes)
  8959. // deflate_state *s;
  8960. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  8961. {
  8962. var rank; /* index in bl_order */
  8963.  
  8964. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  8965. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  8966. // "too many codes");
  8967. //Tracev((stderr, "\nbl counts: "));
  8968. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  8969. send_bits(s, dcodes-1, 5);
  8970. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  8971. for (rank = 0; rank < blcodes; rank++) {
  8972. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  8973. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  8974. }
  8975. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  8976.  
  8977. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  8978. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  8979.  
  8980. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  8981. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  8982. }
  8983.  
  8984.  
  8985. /* ===========================================================================
  8986. * Check if the data type is TEXT or BINARY, using the following algorithm:
  8987. * - TEXT if the two conditions below are satisfied:
  8988. * a) There are no non-portable control characters belonging to the
  8989. * "black list" (0..6, 14..25, 28..31).
  8990. * b) There is at least one printable character belonging to the
  8991. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  8992. * - BINARY otherwise.
  8993. * - The following partially-portable control characters form a
  8994. * "gray list" that is ignored in this detection algorithm:
  8995. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  8996. * IN assertion: the fields Freq of dyn_ltree are set.
  8997. */
  8998. function detect_data_type(s) {
  8999. /* black_mask is the bit mask of black-listed bytes
  9000. * set bits 0..6, 14..25, and 28..31
  9001. * 0xf3ffc07f = binary 11110011111111111100000001111111
  9002. */
  9003. var black_mask = 0xf3ffc07f;
  9004. var n;
  9005.  
  9006. /* Check for non-textual ("black-listed") bytes. */
  9007. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  9008. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  9009. return Z_BINARY;
  9010. }
  9011. }
  9012.  
  9013. /* Check for textual ("white-listed") bytes. */
  9014. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  9015. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  9016. return Z_TEXT;
  9017. }
  9018. for (n = 32; n < LITERALS; n++) {
  9019. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  9020. return Z_TEXT;
  9021. }
  9022. }
  9023.  
  9024. /* There are no "black-listed" or "white-listed" bytes:
  9025. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  9026. */
  9027. return Z_BINARY;
  9028. }
  9029.  
  9030.  
  9031. var static_init_done = false;
  9032.  
  9033. /* ===========================================================================
  9034. * Initialize the tree data structures for a new zlib stream.
  9035. */
  9036. function _tr_init(s)
  9037. {
  9038.  
  9039. if (!static_init_done) {
  9040. tr_static_init();
  9041. static_init_done = true;
  9042. }
  9043.  
  9044. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  9045. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  9046. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  9047.  
  9048. s.bi_buf = 0;
  9049. s.bi_valid = 0;
  9050.  
  9051. /* Initialize the first block of the first file: */
  9052. init_block(s);
  9053. }
  9054.  
  9055.  
  9056. /* ===========================================================================
  9057. * Send a stored block
  9058. */
  9059. function _tr_stored_block(s, buf, stored_len, last)
  9060. //DeflateState *s;
  9061. //charf *buf; /* input block */
  9062. //ulg stored_len; /* length of input block */
  9063. //int last; /* one if this is the last block for a file */
  9064. {
  9065. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  9066. copy_block(s, buf, stored_len, true); /* with header */
  9067. }
  9068.  
  9069.  
  9070. /* ===========================================================================
  9071. * Send one empty static block to give enough lookahead for inflate.
  9072. * This takes 10 bits, of which 7 may remain in the bit buffer.
  9073. */
  9074. function _tr_align(s) {
  9075. send_bits(s, STATIC_TREES<<1, 3);
  9076. send_code(s, END_BLOCK, static_ltree);
  9077. bi_flush(s);
  9078. }
  9079.  
  9080.  
  9081. /* ===========================================================================
  9082. * Determine the best encoding for the current block: dynamic trees, static
  9083. * trees or store, and output the encoded block to the zip file.
  9084. */
  9085. function _tr_flush_block(s, buf, stored_len, last)
  9086. //DeflateState *s;
  9087. //charf *buf; /* input block, or NULL if too old */
  9088. //ulg stored_len; /* length of input block */
  9089. //int last; /* one if this is the last block for a file */
  9090. {
  9091. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  9092. var max_blindex = 0; /* index of last bit length code of non zero freq */
  9093.  
  9094. /* Build the Huffman trees unless a stored block is forced */
  9095. if (s.level > 0) {
  9096.  
  9097. /* Check if the file is binary or text */
  9098. if (s.strm.data_type === Z_UNKNOWN) {
  9099. s.strm.data_type = detect_data_type(s);
  9100. }
  9101.  
  9102. /* Construct the literal and distance trees */
  9103. build_tree(s, s.l_desc);
  9104. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  9105. // s->static_len));
  9106.  
  9107. build_tree(s, s.d_desc);
  9108. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  9109. // s->static_len));
  9110. /* At this point, opt_len and static_len are the total bit lengths of
  9111. * the compressed block data, excluding the tree representations.
  9112. */
  9113.  
  9114. /* Build the bit length tree for the above two trees, and get the index
  9115. * in bl_order of the last bit length code to send.
  9116. */
  9117. max_blindex = build_bl_tree(s);
  9118.  
  9119. /* Determine the best encoding. Compute the block lengths in bytes. */
  9120. opt_lenb = (s.opt_len+3+7) >>> 3;
  9121. static_lenb = (s.static_len+3+7) >>> 3;
  9122.  
  9123. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  9124. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  9125. // s->last_lit));
  9126.  
  9127. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  9128.  
  9129. } else {
  9130. // Assert(buf != (char*)0, "lost buf");
  9131. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  9132. }
  9133.  
  9134. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  9135. /* 4: two words for the lengths */
  9136.  
  9137. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  9138. * Otherwise we can't have processed more than WSIZE input bytes since
  9139. * the last block flush, because compression would have been
  9140. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  9141. * transform a block into a stored block.
  9142. */
  9143. _tr_stored_block(s, buf, stored_len, last);
  9144.  
  9145. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  9146.  
  9147. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  9148. compress_block(s, static_ltree, static_dtree);
  9149.  
  9150. } else {
  9151. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  9152. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  9153. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  9154. }
  9155. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  9156. /* The above check is made mod 2^32, for files larger than 512 MB
  9157. * and uLong implemented on 32 bits.
  9158. */
  9159. init_block(s);
  9160.  
  9161. if (last) {
  9162. bi_windup(s);
  9163. }
  9164. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  9165. // s->compressed_len-7*last));
  9166. }
  9167.  
  9168. /* ===========================================================================
  9169. * Save the match info and tally the frequency counts. Return true if
  9170. * the current block must be flushed.
  9171. */
  9172. function _tr_tally(s, dist, lc)
  9173. // deflate_state *s;
  9174. // unsigned dist; /* distance of matched string */
  9175. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  9176. {
  9177. //var out_length, in_length, dcode;
  9178.  
  9179. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  9180. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  9181.  
  9182. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  9183. s.last_lit++;
  9184.  
  9185. if (dist === 0) {
  9186. /* lc is the unmatched char */
  9187. s.dyn_ltree[lc*2]/*.Freq*/++;
  9188. } else {
  9189. s.matches++;
  9190. /* Here, lc is the match length - MIN_MATCH */
  9191. dist--; /* dist = match distance - 1 */
  9192. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  9193. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  9194. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  9195.  
  9196. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  9197. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  9198. }
  9199.  
  9200. // (!) This block is disabled in zlib defailts,
  9201. // don't enable it for binary compatibility
  9202.  
  9203. //#ifdef TRUNCATE_BLOCK
  9204. // /* Try to guess if it is profitable to stop the current block here */
  9205. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  9206. // /* Compute an upper bound for the compressed length */
  9207. // out_length = s.last_lit*8;
  9208. // in_length = s.strstart - s.block_start;
  9209. //
  9210. // for (dcode = 0; dcode < D_CODES; dcode++) {
  9211. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  9212. // }
  9213. // out_length >>>= 3;
  9214. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  9215. // // s->last_lit, in_length, out_length,
  9216. // // 100L - out_length*100L/in_length));
  9217. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  9218. // return true;
  9219. // }
  9220. // }
  9221. //#endif
  9222.  
  9223. return (s.last_lit === s.lit_bufsize-1);
  9224. /* We avoid equality with lit_bufsize because of wraparound at 64K
  9225. * on 16 bit machines and because stored blocks are restricted to
  9226. * 64K-1 bytes.
  9227. */
  9228. }
  9229.  
  9230. exports._tr_init = _tr_init;
  9231. exports._tr_stored_block = _tr_stored_block;
  9232. exports._tr_flush_block = _tr_flush_block;
  9233. exports._tr_tally = _tr_tally;
  9234. exports._tr_align = _tr_align;
  9235. },{"../utils/common":27}],39:[function(_dereq_,module,exports){
  9236. 'use strict';
  9237.  
  9238.  
  9239. function ZStream() {
  9240. /* next input byte */
  9241. this.input = null; // JS specific, because we have no pointers
  9242. this.next_in = 0;
  9243. /* number of bytes available at input */
  9244. this.avail_in = 0;
  9245. /* total number of input bytes read so far */
  9246. this.total_in = 0;
  9247. /* next output byte should be put there */
  9248. this.output = null; // JS specific, because we have no pointers
  9249. this.next_out = 0;
  9250. /* remaining free space at output */
  9251. this.avail_out = 0;
  9252. /* total number of bytes output so far */
  9253. this.total_out = 0;
  9254. /* last error message, NULL if no error */
  9255. this.msg = ''/*Z_NULL*/;
  9256. /* not visible by applications */
  9257. this.state = null;
  9258. /* best guess about the data type: binary or text */
  9259. this.data_type = 2/*Z_UNKNOWN*/;
  9260. /* adler32 value of the uncompressed data */
  9261. this.adler = 0;
  9262. }
  9263.  
  9264. module.exports = ZStream;
  9265. },{}]},{},[9])
  9266. (9)
  9267. });
  9268.  
  9269. /* FileSaver.js
  9270. * A saveAs() FileSaver implementation.
  9271. * 1.1.20151003
  9272. *
  9273. * By Eli Grey, http://eligrey.com
  9274. * License: MIT
  9275. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  9276. */
  9277.  
  9278. /*global self */
  9279. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  9280.  
  9281. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  9282.  
  9283. var saveAs = saveAs || (function(view) {
  9284. "use strict";
  9285. // IE <10 is explicitly unsupported
  9286. if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  9287. return;
  9288. }
  9289. var
  9290. doc = view.document
  9291. // only get URL when necessary in case Blob.js hasn't overridden it yet
  9292. , get_URL = function() {
  9293. return view.URL || view.webkitURL || view;
  9294. }
  9295. , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  9296. , can_use_save_link = "download" in save_link
  9297. , click = function(node) {
  9298. var event = new MouseEvent("click");
  9299. node.dispatchEvent(event);
  9300. }
  9301. , is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent)
  9302. , webkit_req_fs = view.webkitRequestFileSystem
  9303. , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
  9304. , throw_outside = function(ex) {
  9305. (view.setImmediate || view.setTimeout)(function() {
  9306. throw ex;
  9307. }, 0);
  9308. }
  9309. , force_saveable_type = "application/octet-stream"
  9310. , fs_min_size = 0
  9311. // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
  9312. // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
  9313. // for the reasoning behind the timeout and revocation flow
  9314. , arbitrary_revoke_timeout = 500 // in ms
  9315. , revoke = function(file) {
  9316. var revoker = function() {
  9317. if (typeof file === "string") { // file is an object URL
  9318. get_URL().revokeObjectURL(file);
  9319. } else { // file is a File
  9320. file.remove();
  9321. }
  9322. };
  9323. if (view.chrome) {
  9324. revoker();
  9325. } else {
  9326. setTimeout(revoker, arbitrary_revoke_timeout);
  9327. }
  9328. }
  9329. , dispatch = function(filesaver, event_types, event) {
  9330. event_types = [].concat(event_types);
  9331. var i = event_types.length;
  9332. while (i--) {
  9333. var listener = filesaver["on" + event_types[i]];
  9334. if (typeof listener === "function") {
  9335. try {
  9336. listener.call(filesaver, event || filesaver);
  9337. } catch (ex) {
  9338. throw_outside(ex);
  9339. }
  9340. }
  9341. }
  9342. }
  9343. , auto_bom = function(blob) {
  9344. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  9345. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  9346. return new Blob(["\ufeff", blob], {type: blob.type});
  9347. }
  9348. return blob;
  9349. }
  9350. , FileSaver = function(blob, name, no_auto_bom) {
  9351. if (!no_auto_bom) {
  9352. blob = auto_bom(blob);
  9353. }
  9354. // First try a.download, then web filesystem, then object URLs
  9355. var
  9356. filesaver = this
  9357. , type = blob.type
  9358. , blob_changed = false
  9359. , object_url
  9360. , target_view
  9361. , dispatch_all = function() {
  9362. dispatch(filesaver, "writestart progress write writeend".split(" "));
  9363. }
  9364. // on any filesys errors revert to saving with object URLs
  9365. , fs_error = function() {
  9366. if (target_view && is_safari && typeof FileReader !== "undefined") {
  9367. // Safari doesn't allow downloading of blob urls
  9368. var reader = new FileReader();
  9369. reader.onloadend = function() {
  9370. var base64Data = reader.result;
  9371. target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
  9372. filesaver.readyState = filesaver.DONE;
  9373. dispatch_all();
  9374. };
  9375. reader.readAsDataURL(blob);
  9376. filesaver.readyState = filesaver.INIT;
  9377. return;
  9378. }
  9379. // don't create more object URLs than needed
  9380. if (blob_changed || !object_url) {
  9381. object_url = get_URL().createObjectURL(blob);
  9382. }
  9383. if (target_view) {
  9384. target_view.location.href = object_url;
  9385. } else {
  9386. var new_tab = view.open(object_url, "_blank");
  9387. if (new_tab == undefined && is_safari) {
  9388. //Apple do not allow window.open, see http://bit.ly/1kZffRI
  9389. view.location.href = object_url
  9390. }
  9391. }
  9392. filesaver.readyState = filesaver.DONE;
  9393. dispatch_all();
  9394. revoke(object_url);
  9395. }
  9396. , abortable = function(func) {
  9397. return function() {
  9398. if (filesaver.readyState !== filesaver.DONE) {
  9399. return func.apply(this, arguments);
  9400. }
  9401. };
  9402. }
  9403. , create_if_not_found = {create: true, exclusive: false}
  9404. , slice
  9405. ;
  9406. filesaver.readyState = filesaver.INIT;
  9407. if (!name) {
  9408. name = "download";
  9409. }
  9410. if (can_use_save_link) {
  9411. object_url = get_URL().createObjectURL(blob);
  9412. setTimeout(function() {
  9413. save_link.href = object_url;
  9414. save_link.download = name;
  9415. click(save_link);
  9416. dispatch_all();
  9417. revoke(object_url);
  9418. filesaver.readyState = filesaver.DONE;
  9419. });
  9420. return;
  9421. }
  9422. // Object and web filesystem URLs have a problem saving in Google Chrome when
  9423. // viewed in a tab, so I force save with application/octet-stream
  9424. // http://code.google.com/p/chromium/issues/detail?id=91158
  9425. // Update: Google errantly closed 91158, I submitted it again:
  9426. // https://code.google.com/p/chromium/issues/detail?id=389642
  9427. if (view.chrome && type && type !== force_saveable_type) {
  9428. slice = blob.slice || blob.webkitSlice;
  9429. blob = slice.call(blob, 0, blob.size, force_saveable_type);
  9430. blob_changed = true;
  9431. }
  9432. // Since I can't be sure that the guessed media type will trigger a download
  9433. // in WebKit, I append .download to the filename.
  9434. // https://bugs.webkit.org/show_bug.cgi?id=65440
  9435. if (webkit_req_fs && name !== "download") {
  9436. name += ".download";
  9437. }
  9438. if (type === force_saveable_type || webkit_req_fs) {
  9439. target_view = view;
  9440. }
  9441. if (!req_fs) {
  9442. fs_error();
  9443. return;
  9444. }
  9445. fs_min_size += blob.size;
  9446. req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
  9447. fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
  9448. var save = function() {
  9449. dir.getFile(name, create_if_not_found, abortable(function(file) {
  9450. file.createWriter(abortable(function(writer) {
  9451. writer.onwriteend = function(event) {
  9452. target_view.location.href = file.toURL();
  9453. filesaver.readyState = filesaver.DONE;
  9454. dispatch(filesaver, "writeend", event);
  9455. revoke(file);
  9456. };
  9457. writer.onerror = function() {
  9458. var error = writer.error;
  9459. if (error.code !== error.ABORT_ERR) {
  9460. fs_error();
  9461. }
  9462. };
  9463. "writestart progress write abort".split(" ").forEach(function(event) {
  9464. writer["on" + event] = filesaver["on" + event];
  9465. });
  9466. writer.write(blob);
  9467. filesaver.abort = function() {
  9468. writer.abort();
  9469. filesaver.readyState = filesaver.DONE;
  9470. };
  9471. filesaver.readyState = filesaver.WRITING;
  9472. }), fs_error);
  9473. }), fs_error);
  9474. };
  9475. dir.getFile(name, {create: false}, abortable(function(file) {
  9476. // delete file if it already exists
  9477. file.remove();
  9478. save();
  9479. }), abortable(function(ex) {
  9480. if (ex.code === ex.NOT_FOUND_ERR) {
  9481. save();
  9482. } else {
  9483. fs_error();
  9484. }
  9485. }));
  9486. }), fs_error);
  9487. }), fs_error);
  9488. }
  9489. , FS_proto = FileSaver.prototype
  9490. , saveAs = function(blob, name, no_auto_bom) {
  9491. return new FileSaver(blob, name, no_auto_bom);
  9492. }
  9493. ;
  9494. // IE 10+ (native saveAs)
  9495. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  9496. return function(blob, name, no_auto_bom) {
  9497. if (!no_auto_bom) {
  9498. blob = auto_bom(blob);
  9499. }
  9500. return navigator.msSaveOrOpenBlob(blob, name || "download");
  9501. };
  9502. }
  9503.  
  9504. FS_proto.abort = function() {
  9505. var filesaver = this;
  9506. filesaver.readyState = filesaver.DONE;
  9507. dispatch(filesaver, "abort");
  9508. };
  9509. FS_proto.readyState = FS_proto.INIT = 0;
  9510. FS_proto.WRITING = 1;
  9511. FS_proto.DONE = 2;
  9512.  
  9513. FS_proto.error =
  9514. FS_proto.onwritestart =
  9515. FS_proto.onprogress =
  9516. FS_proto.onwrite =
  9517. FS_proto.onabort =
  9518. FS_proto.onerror =
  9519. FS_proto.onwriteend =
  9520. null;
  9521.  
  9522. return saveAs;
  9523. }(
  9524. typeof self !== "undefined" && self
  9525. || typeof window !== "undefined" && window
  9526. || this.content
  9527. ));
  9528. // `self` is undefined in Firefox for Android content script context
  9529. // while `this` is nsIContentFrameMessageManager
  9530. // with an attribute `content` that corresponds to the window
  9531.  
  9532. if (typeof module !== "undefined" && module.exports) {
  9533. module.exports.saveAs = saveAs;
  9534. } else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
  9535. define([], function() {
  9536. return saveAs;
  9537. });
  9538. }