E-Hentai Downloader

Download E-Hentai archive as zip file

As of 25.08.2019. See ბოლო ვერსია.

  1. // ==UserScript==
  2. // @name E-Hentai Downloader
  3. // @version 1.31.5
  4. // @description Download E-Hentai archive as zip file
  5. // @author 864907600cc
  6. // @icon https://secure.gravatar.com/avatar/147834caf9ccb0a66b2505c753747867
  7. // @include http://exhentai.org/g/*
  8. // @include http://e-hentai.org/g/*
  9. // @include http://g.e-hentai.org/g/*
  10. // @include http://r.e-hentai.org/g/*
  11. // @include https://exhentai.org/g/*
  12. // @include https://e-hentai.org/g/*
  13. // @include https://g.e-hentai.org/g/*
  14. // @include https://r.e-hentai.org/g/*
  15. // @namespace http://ext.ccloli.com
  16. // @supportURL https://github.com/ccloli/E-Hentai-Downloader/issues
  17. // @connect *
  18. // @grant GM_getValue
  19. // @grant GM_setValue
  20. // @grant GM_xmlhttpRequest
  21. // @grant GM_info
  22. // @grant GM.getValue
  23. // @grant GM.setValue
  24. // @grant GM.xmlHttpRequest
  25. // @grant GM.info
  26. // ==/UserScript==
  27.  
  28. // This script using JSZip & FileSaver.js
  29.  
  30. 'use strict';
  31.  
  32. console.log('[EHD] E-Hentai Downloader is running.');
  33. console.log('[EHD] Bugs Report >', 'https://github.com/ccloli/E-Hentai-Downloader/issues | https://greasyfork.org/scripts/10379-e-hentai-downloader/feedback');
  34. console.log('[EHD] To report a bug, it\'s recommended to provide the logs started with "[EHD]", thanks. =w=');
  35.  
  36. // GreaseMonkey 4.x compatible
  37. if (typeof GM_getValue === 'undefined' && typeof GM !== 'undefined') {
  38. var loadSetting = GM.getValue.bind(this, 'ehD-setting');
  39. self.GM_setValue = GM.setValue;
  40. self.GM_xmlhttpRequest = GM.xmlHttpRequest;
  41. self.GM_info = GM.info;
  42. }
  43. else {
  44. var loadSetting = function(key, init) {
  45. return new Promise(function(resolve, reject){
  46. try {
  47. resolve(GM_getValue('ehD-setting'));
  48. }
  49. catch(e) {
  50. reject(e);
  51. }
  52. });
  53. };
  54. }
  55.  
  56. // Opera 12- (Presto) doesn't support generating blob url, and if generate as data url, it may cause crashes.
  57. if (navigator.userAgent.indexOf('Presto') >= 0) {
  58. alert('Your Opera doesn\'t support E-Hentai Downloader. You need to upgrade it to Opera 15+.');
  59. console.error('[EHD] Opera 12- (Presto) doesn\'t support E-Hentai Downloader. UserAgent > ' + navigator.userAgent);
  60. }
  61.  
  62. // Remove IE support
  63. else if (navigator.userAgent.indexOf('Trident') >= 0) {
  64. alert('Your browser doesn\'t support E-Hentai Downloader. You need to switch to other browsers.');
  65. console.error('[EHD] IE doesn\'t support E-Hentai Downloader. UserAgent > ' + navigator.userAgent);
  66. }
  67.  
  68. // GreaseMonkey 3.2 beta 1 and older version can't load content of GM_xhr.response, and this can't be fix.
  69. else if (
  70. (!GM_info.scriptHandler || GM_info.scriptHandler.indexOf('GreaseMonkey') >= 0) && GM_info.version != null && (
  71. GM_info.version.split('.')[0] - 0 < 3 || (
  72. GM_info.version.split('.')[0] - 0 == 3 && (
  73. GM_info.version.split('.')[1].split('beta')[0] - 0 <= 2 &&
  74. GM_info.version.indexOf('beta') >= 0 &&
  75. GM_info.version.split('beta')[1] - 0 < 2
  76. )
  77. )
  78. )
  79. ) {
  80. alert('Your GreaseMonkey doesn\'t support E-Hentai Downloader. The first supported version is GreaseMonkey 3.2 beta 2. Please update your GreaseMonkey to enjoy. =w=');
  81. console.error('[EHD] GreaseMonkey doesn\'t support E-Hentai Downloader. GreaseMonkey Version > ' + GM_info.version);
  82. }
  83.  
  84. // GreasyFork doesn't allow obfuscated or minified script, so if you want to see the main function, please see src/main.js at GitHub
  85. /*!
  86.  
  87. JSZip v3.1.5 - A JavaScript class for generating and reading zip files
  88. <http://stuartk.com/jszip>
  89.  
  90. (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
  91. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
  92.  
  93. JSZip uses the library pako released under the MIT license :
  94. https://github.com/nodeca/pako/blob/master/LICENSE
  95. */
  96.  
  97. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSZip = f()}})(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);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.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(require,module,exports){
  98. 'use strict';
  99. var utils = require('./utils');
  100. var support = require('./support');
  101. // private property
  102. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  103.  
  104.  
  105. // public method for encoding
  106. exports.encode = function(input) {
  107. var output = [];
  108. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  109. var i = 0, len = input.length, remainingBytes = len;
  110.  
  111. var isArray = utils.getTypeOf(input) !== "string";
  112. while (i < input.length) {
  113. remainingBytes = len - i;
  114.  
  115. if (!isArray) {
  116. chr1 = input.charCodeAt(i++);
  117. chr2 = i < len ? input.charCodeAt(i++) : 0;
  118. chr3 = i < len ? input.charCodeAt(i++) : 0;
  119. } else {
  120. chr1 = input[i++];
  121. chr2 = i < len ? input[i++] : 0;
  122. chr3 = i < len ? input[i++] : 0;
  123. }
  124.  
  125. enc1 = chr1 >> 2;
  126. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  127. enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;
  128. enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;
  129.  
  130. output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));
  131.  
  132. }
  133.  
  134. return output.join("");
  135. };
  136.  
  137. // public method for decoding
  138. exports.decode = function(input) {
  139. var chr1, chr2, chr3;
  140. var enc1, enc2, enc3, enc4;
  141. var i = 0, resultIndex = 0;
  142.  
  143. var dataUrlPrefix = "data:";
  144.  
  145. if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {
  146. // This is a common error: people give a data url
  147. // (data:image/png;base64,iVBOR...) with a {base64: true} and
  148. // wonders why things don't work.
  149. // We can detect that the string input looks like a data url but we
  150. // *can't* be sure it is one: removing everything up to the comma would
  151. // be too dangerous.
  152. throw new Error("Invalid base64 input, it looks like a data url.");
  153. }
  154.  
  155. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  156.  
  157. var totalLength = input.length * 3 / 4;
  158. if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {
  159. totalLength--;
  160. }
  161. if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {
  162. totalLength--;
  163. }
  164. if (totalLength % 1 !== 0) {
  165. // totalLength is not an integer, the length does not match a valid
  166. // base64 content. That can happen if:
  167. // - the input is not a base64 content
  168. // - the input is *almost* a base64 content, with a extra chars at the
  169. // beginning or at the end
  170. // - the input uses a base64 variant (base64url for example)
  171. throw new Error("Invalid base64 input, bad content length.");
  172. }
  173. var output;
  174. if (support.uint8array) {
  175. output = new Uint8Array(totalLength|0);
  176. } else {
  177. output = new Array(totalLength|0);
  178. }
  179.  
  180. while (i < input.length) {
  181.  
  182. enc1 = _keyStr.indexOf(input.charAt(i++));
  183. enc2 = _keyStr.indexOf(input.charAt(i++));
  184. enc3 = _keyStr.indexOf(input.charAt(i++));
  185. enc4 = _keyStr.indexOf(input.charAt(i++));
  186.  
  187. chr1 = (enc1 << 2) | (enc2 >> 4);
  188. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  189. chr3 = ((enc3 & 3) << 6) | enc4;
  190.  
  191. output[resultIndex++] = chr1;
  192.  
  193. if (enc3 !== 64) {
  194. output[resultIndex++] = chr2;
  195. }
  196. if (enc4 !== 64) {
  197. output[resultIndex++] = chr3;
  198. }
  199.  
  200. }
  201.  
  202. return output;
  203. };
  204.  
  205. },{"./support":30,"./utils":32}],2:[function(require,module,exports){
  206. 'use strict';
  207.  
  208. var external = require("./external");
  209. var DataWorker = require('./stream/DataWorker');
  210. var DataLengthProbe = require('./stream/DataLengthProbe');
  211. var Crc32Probe = require('./stream/Crc32Probe');
  212. var DataLengthProbe = require('./stream/DataLengthProbe');
  213.  
  214. /**
  215. * Represent a compressed object, with everything needed to decompress it.
  216. * @constructor
  217. * @param {number} compressedSize the size of the data compressed.
  218. * @param {number} uncompressedSize the size of the data after decompression.
  219. * @param {number} crc32 the crc32 of the decompressed file.
  220. * @param {object} compression the type of compression, see lib/compressions.js.
  221. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
  222. */
  223. function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
  224. this.compressedSize = compressedSize;
  225. this.uncompressedSize = uncompressedSize;
  226. this.crc32 = crc32;
  227. this.compression = compression;
  228. this.compressedContent = data;
  229. }
  230.  
  231. CompressedObject.prototype = {
  232. /**
  233. * Create a worker to get the uncompressed content.
  234. * @return {GenericWorker} the worker.
  235. */
  236. getContentWorker : function () {
  237. var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
  238. .pipe(this.compression.uncompressWorker())
  239. .pipe(new DataLengthProbe("data_length"));
  240.  
  241. var that = this;
  242. worker.on("end", function () {
  243. if(this.streamInfo['data_length'] !== that.uncompressedSize) {
  244. throw new Error("Bug : uncompressed data size mismatch");
  245. }
  246. });
  247. return worker;
  248. },
  249. /**
  250. * Create a worker to get the compressed content.
  251. * @return {GenericWorker} the worker.
  252. */
  253. getCompressedWorker : function () {
  254. return new DataWorker(external.Promise.resolve(this.compressedContent))
  255. .withStreamInfo("compressedSize", this.compressedSize)
  256. .withStreamInfo("uncompressedSize", this.uncompressedSize)
  257. .withStreamInfo("crc32", this.crc32)
  258. .withStreamInfo("compression", this.compression)
  259. ;
  260. }
  261. };
  262.  
  263. /**
  264. * Chain the given worker with other workers to compress the content with the
  265. * given compresion.
  266. * @param {GenericWorker} uncompressedWorker the worker to pipe.
  267. * @param {Object} compression the compression object.
  268. * @param {Object} compressionOptions the options to use when compressing.
  269. * @return {GenericWorker} the new worker compressing the content.
  270. */
  271. CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
  272. return uncompressedWorker
  273. .pipe(new Crc32Probe())
  274. .pipe(new DataLengthProbe("uncompressedSize"))
  275. .pipe(compression.compressWorker(compressionOptions))
  276. .pipe(new DataLengthProbe("compressedSize"))
  277. .withStreamInfo("compression", compression);
  278. };
  279.  
  280. module.exports = CompressedObject;
  281.  
  282. },{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){
  283. 'use strict';
  284.  
  285. var GenericWorker = require("./stream/GenericWorker");
  286.  
  287. exports.STORE = {
  288. magic: "\x00\x00",
  289. compressWorker : function (compressionOptions) {
  290. return new GenericWorker("STORE compression");
  291. },
  292. uncompressWorker : function () {
  293. return new GenericWorker("STORE decompression");
  294. }
  295. };
  296. exports.DEFLATE = require('./flate');
  297.  
  298. },{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){
  299. 'use strict';
  300.  
  301. var utils = require('./utils');
  302.  
  303. /**
  304. * The following functions come from pako, from pako/lib/zlib/crc32.js
  305. * released under the MIT license, see pako https://github.com/nodeca/pako/
  306. */
  307.  
  308. // Use ordinary array, since untyped makes no boost here
  309. function makeTable() {
  310. var c, table = [];
  311.  
  312. for(var n =0; n < 256; n++){
  313. c = n;
  314. for(var k =0; k < 8; k++){
  315. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  316. }
  317. table[n] = c;
  318. }
  319.  
  320. return table;
  321. }
  322.  
  323. // Create table on load. Just 255 signed longs. Not a problem.
  324. var crcTable = makeTable();
  325.  
  326.  
  327. function crc32(crc, buf, len, pos) {
  328. var t = crcTable, end = pos + len;
  329.  
  330. crc = crc ^ (-1);
  331.  
  332. for (var i = pos; i < end; i++ ) {
  333. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  334. }
  335.  
  336. return (crc ^ (-1)); // >>> 0;
  337. }
  338.  
  339. // That's all for the pako functions.
  340.  
  341. /**
  342. * Compute the crc32 of a string.
  343. * This is almost the same as the function crc32, but for strings. Using the
  344. * same function for the two use cases leads to horrible performances.
  345. * @param {Number} crc the starting value of the crc.
  346. * @param {String} str the string to use.
  347. * @param {Number} len the length of the string.
  348. * @param {Number} pos the starting position for the crc32 computation.
  349. * @return {Number} the computed crc32.
  350. */
  351. function crc32str(crc, str, len, pos) {
  352. var t = crcTable, end = pos + len;
  353.  
  354. crc = crc ^ (-1);
  355.  
  356. for (var i = pos; i < end; i++ ) {
  357. crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
  358. }
  359.  
  360. return (crc ^ (-1)); // >>> 0;
  361. }
  362.  
  363. module.exports = function crc32wrapper(input, crc) {
  364. if (typeof input === "undefined" || !input.length) {
  365. return 0;
  366. }
  367.  
  368. var isArray = utils.getTypeOf(input) !== "string";
  369.  
  370. if(isArray) {
  371. return crc32(crc|0, input, input.length, 0);
  372. } else {
  373. return crc32str(crc|0, input, input.length, 0);
  374. }
  375. };
  376.  
  377. },{"./utils":32}],5:[function(require,module,exports){
  378. 'use strict';
  379. exports.base64 = false;
  380. exports.binary = false;
  381. exports.dir = false;
  382. exports.createFolders = true;
  383. exports.date = null;
  384. exports.compression = null;
  385. exports.compressionOptions = null;
  386. exports.comment = null;
  387. exports.unixPermissions = null;
  388. exports.dosPermissions = null;
  389.  
  390. },{}],6:[function(require,module,exports){
  391. /* global Promise */
  392. 'use strict';
  393.  
  394. // load the global object first:
  395. // - it should be better integrated in the system (unhandledRejection in node)
  396. // - the environment may have a custom Promise implementation (see zone.js)
  397. var ES6Promise = null;
  398. if (typeof Promise !== "undefined") {
  399. ES6Promise = Promise;
  400. } else {
  401. ES6Promise = require("lie");
  402. }
  403.  
  404. /**
  405. * Let the user use/change some implementations.
  406. */
  407. module.exports = {
  408. Promise: ES6Promise
  409. };
  410.  
  411. },{"lie":58}],7:[function(require,module,exports){
  412. 'use strict';
  413. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  414.  
  415. var pako = require("pako");
  416. var utils = require("./utils");
  417. var GenericWorker = require("./stream/GenericWorker");
  418.  
  419. var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
  420.  
  421. exports.magic = "\x08\x00";
  422.  
  423. /**
  424. * Create a worker that uses pako to inflate/deflate.
  425. * @constructor
  426. * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
  427. * @param {Object} options the options to use when (de)compressing.
  428. */
  429. function FlateWorker(action, options) {
  430. GenericWorker.call(this, "FlateWorker/" + action);
  431.  
  432. this._pako = null;
  433. this._pakoAction = action;
  434. this._pakoOptions = options;
  435. // the `meta` object from the last chunk received
  436. // this allow this worker to pass around metadata
  437. this.meta = {};
  438. }
  439.  
  440. utils.inherits(FlateWorker, GenericWorker);
  441.  
  442. /**
  443. * @see GenericWorker.processChunk
  444. */
  445. FlateWorker.prototype.processChunk = function (chunk) {
  446. this.meta = chunk.meta;
  447. if (this._pako === null) {
  448. this._createPako();
  449. }
  450. this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
  451. };
  452.  
  453. /**
  454. * @see GenericWorker.flush
  455. */
  456. FlateWorker.prototype.flush = function () {
  457. GenericWorker.prototype.flush.call(this);
  458. if (this._pako === null) {
  459. this._createPako();
  460. }
  461. this._pako.push([], true);
  462. };
  463. /**
  464. * @see GenericWorker.cleanUp
  465. */
  466. FlateWorker.prototype.cleanUp = function () {
  467. GenericWorker.prototype.cleanUp.call(this);
  468. this._pako = null;
  469. };
  470.  
  471. /**
  472. * Create the _pako object.
  473. * TODO: lazy-loading this object isn't the best solution but it's the
  474. * quickest. The best solution is to lazy-load the worker list. See also the
  475. * issue #446.
  476. */
  477. FlateWorker.prototype._createPako = function () {
  478. this._pako = new pako[this._pakoAction]({
  479. raw: true,
  480. level: this._pakoOptions.level || -1 // default compression
  481. });
  482. var self = this;
  483. this._pako.onData = function(data) {
  484. self.push({
  485. data : data,
  486. meta : self.meta
  487. });
  488. };
  489. };
  490.  
  491. exports.compressWorker = function (compressionOptions) {
  492. return new FlateWorker("Deflate", compressionOptions);
  493. };
  494. exports.uncompressWorker = function () {
  495. return new FlateWorker("Inflate", {});
  496. };
  497.  
  498. },{"./stream/GenericWorker":28,"./utils":32,"pako":59}],8:[function(require,module,exports){
  499. 'use strict';
  500.  
  501. var utils = require('../utils');
  502. var GenericWorker = require('../stream/GenericWorker');
  503. var utf8 = require('../utf8');
  504. var crc32 = require('../crc32');
  505. var signature = require('../signature');
  506.  
  507. /**
  508. * Transform an integer into a string in hexadecimal.
  509. * @private
  510. * @param {number} dec the number to convert.
  511. * @param {number} bytes the number of bytes to generate.
  512. * @returns {string} the result.
  513. */
  514. var decToHex = function(dec, bytes) {
  515. var hex = "", i;
  516. for (i = 0; i < bytes; i++) {
  517. hex += String.fromCharCode(dec & 0xff);
  518. dec = dec >>> 8;
  519. }
  520. return hex;
  521. };
  522.  
  523. /**
  524. * Generate the UNIX part of the external file attributes.
  525. * @param {Object} unixPermissions the unix permissions or null.
  526. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  527. * @return {Number} a 32 bit integer.
  528. *
  529. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  530. *
  531. * TTTTsstrwxrwxrwx0000000000ADVSHR
  532. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  533. * ^^^_________________________ setuid, setgid, sticky
  534. * ^^^^^^^^^________________ permissions
  535. * ^^^^^^^^^^______ not used ?
  536. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  537. */
  538. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  539.  
  540. var result = unixPermissions;
  541. if (!unixPermissions) {
  542. // I can't use octal values in strict mode, hence the hexa.
  543. // 040775 => 0x41fd
  544. // 0100664 => 0x81b4
  545. result = isDir ? 0x41fd : 0x81b4;
  546. }
  547. return (result & 0xFFFF) << 16;
  548. };
  549.  
  550. /**
  551. * Generate the DOS part of the external file attributes.
  552. * @param {Object} dosPermissions the dos permissions or null.
  553. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  554. * @return {Number} a 32 bit integer.
  555. *
  556. * Bit 0 Read-Only
  557. * Bit 1 Hidden
  558. * Bit 2 System
  559. * Bit 3 Volume Label
  560. * Bit 4 Directory
  561. * Bit 5 Archive
  562. */
  563. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  564.  
  565. // the dir flag is already set for compatibility
  566. return (dosPermissions || 0) & 0x3F;
  567. };
  568.  
  569. /**
  570. * Generate the various parts used in the construction of the final zip file.
  571. * @param {Object} streamInfo the hash with informations about the compressed file.
  572. * @param {Boolean} streamedContent is the content streamed ?
  573. * @param {Boolean} streamingEnded is the stream finished ?
  574. * @param {number} offset the current offset from the start of the zip file.
  575. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  576. * @param {Function} encodeFileName the function to encode the file name / comment.
  577. * @return {Object} the zip parts.
  578. */
  579. var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
  580. var file = streamInfo['file'],
  581. compression = streamInfo['compression'],
  582. useCustomEncoding = encodeFileName !== utf8.utf8encode,
  583. encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
  584. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  585. comment = file.comment,
  586. encodedComment = utils.transformTo("string", encodeFileName(comment)),
  587. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  588. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  589. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  590. dosTime,
  591. dosDate,
  592. extraFields = "",
  593. unicodePathExtraField = "",
  594. unicodeCommentExtraField = "",
  595. dir = file.dir,
  596. date = file.date;
  597.  
  598.  
  599. var dataInfo = {
  600. crc32 : 0,
  601. compressedSize : 0,
  602. uncompressedSize : 0
  603. };
  604.  
  605. // if the content is streamed, the sizes/crc32 are only available AFTER
  606. // the end of the stream.
  607. if (!streamedContent || streamingEnded) {
  608. dataInfo.crc32 = streamInfo['crc32'];
  609. dataInfo.compressedSize = streamInfo['compressedSize'];
  610. dataInfo.uncompressedSize = streamInfo['uncompressedSize'];
  611. }
  612.  
  613. var bitflag = 0;
  614. if (streamedContent) {
  615. // Bit 3: the sizes/crc32 are set to zero in the local header.
  616. // The correct values are put in the data descriptor immediately
  617. // following the compressed data.
  618. bitflag |= 0x0008;
  619. }
  620. if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
  621. // Bit 11: Language encoding flag (EFS).
  622. bitflag |= 0x0800;
  623. }
  624.  
  625.  
  626. var extFileAttr = 0;
  627. var versionMadeBy = 0;
  628. if (dir) {
  629. // dos or unix, we set the dos dir flag
  630. extFileAttr |= 0x00010;
  631. }
  632. if(platform === "UNIX") {
  633. versionMadeBy = 0x031E; // UNIX, version 3.0
  634. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  635. } else { // DOS or other, fallback to DOS
  636. versionMadeBy = 0x0014; // DOS, version 2.0
  637. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  638. }
  639.  
  640. // date
  641. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  642. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  643. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  644.  
  645. dosTime = date.getUTCHours();
  646. dosTime = dosTime << 6;
  647. dosTime = dosTime | date.getUTCMinutes();
  648. dosTime = dosTime << 5;
  649. dosTime = dosTime | date.getUTCSeconds() / 2;
  650.  
  651. dosDate = date.getUTCFullYear() - 1980;
  652. dosDate = dosDate << 4;
  653. dosDate = dosDate | (date.getUTCMonth() + 1);
  654. dosDate = dosDate << 5;
  655. dosDate = dosDate | date.getUTCDate();
  656.  
  657. if (useUTF8ForFileName) {
  658. // set the unicode path extra field. unzip needs at least one extra
  659. // field to correctly handle unicode path, so using the path is as good
  660. // as any other information. This could improve the situation with
  661. // other archive managers too.
  662. // This field is usually used without the utf8 flag, with a non
  663. // unicode path in the header (winrar, winzip). This helps (a bit)
  664. // with the messy Windows' default compressed folders feature but
  665. // breaks on p7zip which doesn't seek the unicode path extra field.
  666. // So for now, UTF-8 everywhere !
  667. unicodePathExtraField =
  668. // Version
  669. decToHex(1, 1) +
  670. // NameCRC32
  671. decToHex(crc32(encodedFileName), 4) +
  672. // UnicodeName
  673. utfEncodedFileName;
  674.  
  675. extraFields +=
  676. // Info-ZIP Unicode Path Extra Field
  677. "\x75\x70" +
  678. // size
  679. decToHex(unicodePathExtraField.length, 2) +
  680. // content
  681. unicodePathExtraField;
  682. }
  683.  
  684. if(useUTF8ForComment) {
  685.  
  686. unicodeCommentExtraField =
  687. // Version
  688. decToHex(1, 1) +
  689. // CommentCRC32
  690. decToHex(crc32(encodedComment), 4) +
  691. // UnicodeName
  692. utfEncodedComment;
  693.  
  694. extraFields +=
  695. // Info-ZIP Unicode Path Extra Field
  696. "\x75\x63" +
  697. // size
  698. decToHex(unicodeCommentExtraField.length, 2) +
  699. // content
  700. unicodeCommentExtraField;
  701. }
  702.  
  703. var header = "";
  704.  
  705. // version needed to extract
  706. header += "\x0A\x00";
  707. // general purpose bit flag
  708. header += decToHex(bitflag, 2);
  709. // compression method
  710. header += compression.magic;
  711. // last mod file time
  712. header += decToHex(dosTime, 2);
  713. // last mod file date
  714. header += decToHex(dosDate, 2);
  715. // crc-32
  716. header += decToHex(dataInfo.crc32, 4);
  717. // compressed size
  718. header += decToHex(dataInfo.compressedSize, 4);
  719. // uncompressed size
  720. header += decToHex(dataInfo.uncompressedSize, 4);
  721. // file name length
  722. header += decToHex(encodedFileName.length, 2);
  723. // extra field length
  724. header += decToHex(extraFields.length, 2);
  725.  
  726.  
  727. var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  728.  
  729. var dirRecord = signature.CENTRAL_FILE_HEADER +
  730. // version made by (00: DOS)
  731. decToHex(versionMadeBy, 2) +
  732. // file header (common to file and central directory)
  733. header +
  734. // file comment length
  735. decToHex(encodedComment.length, 2) +
  736. // disk number start
  737. "\x00\x00" +
  738. // internal file attributes TODO
  739. "\x00\x00" +
  740. // external file attributes
  741. decToHex(extFileAttr, 4) +
  742. // relative offset of local header
  743. decToHex(offset, 4) +
  744. // file name
  745. encodedFileName +
  746. // extra field
  747. extraFields +
  748. // file comment
  749. encodedComment;
  750.  
  751. return {
  752. fileRecord: fileRecord,
  753. dirRecord: dirRecord
  754. };
  755. };
  756.  
  757. /**
  758. * Generate the EOCD record.
  759. * @param {Number} entriesCount the number of entries in the zip file.
  760. * @param {Number} centralDirLength the length (in bytes) of the central dir.
  761. * @param {Number} localDirLength the length (in bytes) of the local dir.
  762. * @param {String} comment the zip file comment as a binary string.
  763. * @param {Function} encodeFileName the function to encode the comment.
  764. * @return {String} the EOCD record.
  765. */
  766. var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
  767. var dirEnd = "";
  768. var encodedComment = utils.transformTo("string", encodeFileName(comment));
  769.  
  770. // end of central dir signature
  771. dirEnd = signature.CENTRAL_DIRECTORY_END +
  772. // number of this disk
  773. "\x00\x00" +
  774. // number of the disk with the start of the central directory
  775. "\x00\x00" +
  776. // total number of entries in the central directory on this disk
  777. decToHex(entriesCount, 2) +
  778. // total number of entries in the central directory
  779. decToHex(entriesCount, 2) +
  780. // size of the central directory 4 bytes
  781. decToHex(centralDirLength, 4) +
  782. // offset of start of central directory with respect to the starting disk number
  783. decToHex(localDirLength, 4) +
  784. // .ZIP file comment length
  785. decToHex(encodedComment.length, 2) +
  786. // .ZIP file comment
  787. encodedComment;
  788.  
  789. return dirEnd;
  790. };
  791.  
  792. /**
  793. * Generate data descriptors for a file entry.
  794. * @param {Object} streamInfo the hash generated by a worker, containing informations
  795. * on the file entry.
  796. * @return {String} the data descriptors.
  797. */
  798. var generateDataDescriptors = function (streamInfo) {
  799. var descriptor = "";
  800. descriptor = signature.DATA_DESCRIPTOR +
  801. // crc-32 4 bytes
  802. decToHex(streamInfo['crc32'], 4) +
  803. // compressed size 4 bytes
  804. decToHex(streamInfo['compressedSize'], 4) +
  805. // uncompressed size 4 bytes
  806. decToHex(streamInfo['uncompressedSize'], 4);
  807.  
  808. return descriptor;
  809. };
  810.  
  811.  
  812. /**
  813. * A worker to concatenate other workers to create a zip file.
  814. * @param {Boolean} streamFiles `true` to stream the content of the files,
  815. * `false` to accumulate it.
  816. * @param {String} comment the comment to use.
  817. * @param {String} platform the platform to use, "UNIX" or "DOS".
  818. * @param {Function} encodeFileName the function to encode file names and comments.
  819. */
  820. function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
  821. GenericWorker.call(this, "ZipFileWorker");
  822. // The number of bytes written so far. This doesn't count accumulated chunks.
  823. this.bytesWritten = 0;
  824. // The comment of the zip file
  825. this.zipComment = comment;
  826. // The platform "generating" the zip file.
  827. this.zipPlatform = platform;
  828. // the function to encode file names and comments.
  829. this.encodeFileName = encodeFileName;
  830. // Should we stream the content of the files ?
  831. this.streamFiles = streamFiles;
  832. // If `streamFiles` is false, we will need to accumulate the content of the
  833. // files to calculate sizes / crc32 (and write them *before* the content).
  834. // This boolean indicates if we are accumulating chunks (it will change a lot
  835. // during the lifetime of this worker).
  836. this.accumulate = false;
  837. // The buffer receiving chunks when accumulating content.
  838. this.contentBuffer = [];
  839. // The list of generated directory records.
  840. this.dirRecords = [];
  841. // The offset (in bytes) from the beginning of the zip file for the current source.
  842. this.currentSourceOffset = 0;
  843. // The total number of entries in this zip file.
  844. this.entriesCount = 0;
  845. // the name of the file currently being added, null when handling the end of the zip file.
  846. // Used for the emited metadata.
  847. this.currentFile = null;
  848.  
  849.  
  850.  
  851. this._sources = [];
  852. }
  853. utils.inherits(ZipFileWorker, GenericWorker);
  854.  
  855. /**
  856. * @see GenericWorker.push
  857. */
  858. ZipFileWorker.prototype.push = function (chunk) {
  859.  
  860. var currentFilePercent = chunk.meta.percent || 0;
  861. var entriesCount = this.entriesCount;
  862. var remainingFiles = this._sources.length;
  863.  
  864. if(this.accumulate) {
  865. this.contentBuffer.push(chunk);
  866. } else {
  867. this.bytesWritten += chunk.data.length;
  868.  
  869. GenericWorker.prototype.push.call(this, {
  870. data : chunk.data,
  871. meta : {
  872. currentFile : this.currentFile,
  873. percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
  874. }
  875. });
  876. }
  877. };
  878.  
  879. /**
  880. * The worker started a new source (an other worker).
  881. * @param {Object} streamInfo the streamInfo object from the new source.
  882. */
  883. ZipFileWorker.prototype.openedSource = function (streamInfo) {
  884. this.currentSourceOffset = this.bytesWritten;
  885. this.currentFile = streamInfo['file'].name;
  886.  
  887. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  888.  
  889. // don't stream folders (because they don't have any content)
  890. if(streamedContent) {
  891. var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  892. this.push({
  893. data : record.fileRecord,
  894. meta : {percent:0}
  895. });
  896. } else {
  897. // we need to wait for the whole file before pushing anything
  898. this.accumulate = true;
  899. }
  900. };
  901.  
  902. /**
  903. * The worker finished a source (an other worker).
  904. * @param {Object} streamInfo the streamInfo object from the finished source.
  905. */
  906. ZipFileWorker.prototype.closedSource = function (streamInfo) {
  907. this.accumulate = false;
  908. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  909. var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  910.  
  911. this.dirRecords.push(record.dirRecord);
  912. if(streamedContent) {
  913. // after the streamed file, we put data descriptors
  914. this.push({
  915. data : generateDataDescriptors(streamInfo),
  916. meta : {percent:100}
  917. });
  918. } else {
  919. // the content wasn't streamed, we need to push everything now
  920. // first the file record, then the content
  921. this.push({
  922. data : record.fileRecord,
  923. meta : {percent:0}
  924. });
  925. while(this.contentBuffer.length) {
  926. this.push(this.contentBuffer.shift());
  927. }
  928. }
  929. this.currentFile = null;
  930. };
  931.  
  932. /**
  933. * @see GenericWorker.flush
  934. */
  935. ZipFileWorker.prototype.flush = function () {
  936.  
  937. var localDirLength = this.bytesWritten;
  938. for(var i = 0; i < this.dirRecords.length; i++) {
  939. this.push({
  940. data : this.dirRecords[i],
  941. meta : {percent:100}
  942. });
  943. }
  944. var centralDirLength = this.bytesWritten - localDirLength;
  945.  
  946. var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
  947.  
  948. this.push({
  949. data : dirEnd,
  950. meta : {percent:100}
  951. });
  952. };
  953.  
  954. /**
  955. * Prepare the next source to be read.
  956. */
  957. ZipFileWorker.prototype.prepareNextSource = function () {
  958. this.previous = this._sources.shift();
  959. this.openedSource(this.previous.streamInfo);
  960. if (this.isPaused) {
  961. this.previous.pause();
  962. } else {
  963. this.previous.resume();
  964. }
  965. };
  966.  
  967. /**
  968. * @see GenericWorker.registerPrevious
  969. */
  970. ZipFileWorker.prototype.registerPrevious = function (previous) {
  971. this._sources.push(previous);
  972. var self = this;
  973.  
  974. previous.on('data', function (chunk) {
  975. self.processChunk(chunk);
  976. });
  977. previous.on('end', function () {
  978. self.closedSource(self.previous.streamInfo);
  979. if(self._sources.length) {
  980. self.prepareNextSource();
  981. } else {
  982. self.end();
  983. }
  984. });
  985. previous.on('error', function (e) {
  986. self.error(e);
  987. });
  988. return this;
  989. };
  990.  
  991. /**
  992. * @see GenericWorker.resume
  993. */
  994. ZipFileWorker.prototype.resume = function () {
  995. if(!GenericWorker.prototype.resume.call(this)) {
  996. return false;
  997. }
  998.  
  999. if (!this.previous && this._sources.length) {
  1000. this.prepareNextSource();
  1001. return true;
  1002. }
  1003. if (!this.previous && !this._sources.length && !this.generatedError) {
  1004. this.end();
  1005. return true;
  1006. }
  1007. };
  1008.  
  1009. /**
  1010. * @see GenericWorker.error
  1011. */
  1012. ZipFileWorker.prototype.error = function (e) {
  1013. var sources = this._sources;
  1014. if(!GenericWorker.prototype.error.call(this, e)) {
  1015. return false;
  1016. }
  1017. for(var i = 0; i < sources.length; i++) {
  1018. try {
  1019. sources[i].error(e);
  1020. } catch(e) {
  1021. // the `error` exploded, nothing to do
  1022. }
  1023. }
  1024. return true;
  1025. };
  1026.  
  1027. /**
  1028. * @see GenericWorker.lock
  1029. */
  1030. ZipFileWorker.prototype.lock = function () {
  1031. GenericWorker.prototype.lock.call(this);
  1032. var sources = this._sources;
  1033. for(var i = 0; i < sources.length; i++) {
  1034. sources[i].lock();
  1035. }
  1036. };
  1037.  
  1038. module.exports = ZipFileWorker;
  1039.  
  1040. },{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){
  1041. 'use strict';
  1042.  
  1043. var compressions = require('../compressions');
  1044. var ZipFileWorker = require('./ZipFileWorker');
  1045.  
  1046. /**
  1047. * Find the compression to use.
  1048. * @param {String} fileCompression the compression defined at the file level, if any.
  1049. * @param {String} zipCompression the compression defined at the load() level.
  1050. * @return {Object} the compression object to use.
  1051. */
  1052. var getCompression = function (fileCompression, zipCompression) {
  1053.  
  1054. var compressionName = fileCompression || zipCompression;
  1055. var compression = compressions[compressionName];
  1056. if (!compression) {
  1057. throw new Error(compressionName + " is not a valid compression method !");
  1058. }
  1059. return compression;
  1060. };
  1061.  
  1062. /**
  1063. * Create a worker to generate a zip file.
  1064. * @param {JSZip} zip the JSZip instance at the right root level.
  1065. * @param {Object} options to generate the zip file.
  1066. * @param {String} comment the comment to use.
  1067. */
  1068. exports.generateWorker = function (zip, options, comment) {
  1069.  
  1070. var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
  1071. var entriesCount = 0;
  1072. try {
  1073.  
  1074. zip.forEach(function (relativePath, file) {
  1075. entriesCount++;
  1076. var compression = getCompression(file.options.compression, options.compression);
  1077. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  1078. var dir = file.dir, date = file.date;
  1079.  
  1080. file._compressWorker(compression, compressionOptions)
  1081. .withStreamInfo("file", {
  1082. name : relativePath,
  1083. dir : dir,
  1084. date : date,
  1085. comment : file.comment || "",
  1086. unixPermissions : file.unixPermissions,
  1087. dosPermissions : file.dosPermissions
  1088. })
  1089. .pipe(zipFileWorker);
  1090. });
  1091. zipFileWorker.entriesCount = entriesCount;
  1092. } catch (e) {
  1093. zipFileWorker.error(e);
  1094. }
  1095.  
  1096. return zipFileWorker;
  1097. };
  1098.  
  1099. },{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){
  1100. 'use strict';
  1101.  
  1102. /**
  1103. * Representation a of zip file in js
  1104. * @constructor
  1105. */
  1106. function JSZip() {
  1107. // if this constructor is used without `new`, it adds `new` before itself:
  1108. if(!(this instanceof JSZip)) {
  1109. return new JSZip();
  1110. }
  1111.  
  1112. if(arguments.length) {
  1113. throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
  1114. }
  1115.  
  1116. // object containing the files :
  1117. // {
  1118. // "folder/" : {...},
  1119. // "folder/data.txt" : {...}
  1120. // }
  1121. this.files = {};
  1122.  
  1123. this.comment = null;
  1124.  
  1125. // Where we are in the hierarchy
  1126. this.root = "";
  1127. this.clone = function() {
  1128. var newObj = new JSZip();
  1129. for (var i in this) {
  1130. if (typeof this[i] !== "function") {
  1131. newObj[i] = this[i];
  1132. }
  1133. }
  1134. return newObj;
  1135. };
  1136. }
  1137. JSZip.prototype = require('./object');
  1138. JSZip.prototype.loadAsync = require('./load');
  1139. JSZip.support = require('./support');
  1140. JSZip.defaults = require('./defaults');
  1141.  
  1142. // TODO find a better way to handle this version,
  1143. // a require('package.json').version doesn't work with webpack, see #327
  1144. JSZip.version = "3.1.5";
  1145.  
  1146. JSZip.loadAsync = function (content, options) {
  1147. return new JSZip().loadAsync(content, options);
  1148. };
  1149.  
  1150. JSZip.external = require("./external");
  1151. module.exports = JSZip;
  1152.  
  1153. },{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){
  1154. 'use strict';
  1155. var utils = require('./utils');
  1156. var external = require("./external");
  1157. var utf8 = require('./utf8');
  1158. var utils = require('./utils');
  1159. var ZipEntries = require('./zipEntries');
  1160. var Crc32Probe = require('./stream/Crc32Probe');
  1161. var nodejsUtils = require("./nodejsUtils");
  1162.  
  1163. /**
  1164. * Check the CRC32 of an entry.
  1165. * @param {ZipEntry} zipEntry the zip entry to check.
  1166. * @return {Promise} the result.
  1167. */
  1168. function checkEntryCRC32(zipEntry) {
  1169. return new external.Promise(function (resolve, reject) {
  1170. var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
  1171. worker.on("error", function (e) {
  1172. reject(e);
  1173. })
  1174. .on("end", function () {
  1175. if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
  1176. reject(new Error("Corrupted zip : CRC32 mismatch"));
  1177. } else {
  1178. resolve();
  1179. }
  1180. })
  1181. .resume();
  1182. });
  1183. }
  1184.  
  1185. module.exports = function(data, options) {
  1186. var zip = this;
  1187. options = utils.extend(options || {}, {
  1188. base64: false,
  1189. checkCRC32: false,
  1190. optimizedBinaryString: false,
  1191. createFolders: false,
  1192. decodeFileName: utf8.utf8decode
  1193. });
  1194.  
  1195. if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1196. return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
  1197. }
  1198.  
  1199. return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
  1200. .then(function(data) {
  1201. var zipEntries = new ZipEntries(options);
  1202. zipEntries.load(data);
  1203. return zipEntries;
  1204. }).then(function checkCRC32(zipEntries) {
  1205. var promises = [external.Promise.resolve(zipEntries)];
  1206. var files = zipEntries.files;
  1207. if (options.checkCRC32) {
  1208. for (var i = 0; i < files.length; i++) {
  1209. promises.push(checkEntryCRC32(files[i]));
  1210. }
  1211. }
  1212. return external.Promise.all(promises);
  1213. }).then(function addFiles(results) {
  1214. var zipEntries = results.shift();
  1215. var files = zipEntries.files;
  1216. for (var i = 0; i < files.length; i++) {
  1217. var input = files[i];
  1218. zip.file(input.fileNameStr, input.decompressed, {
  1219. binary: true,
  1220. optimizedBinaryString: true,
  1221. date: input.date,
  1222. dir: input.dir,
  1223. comment : input.fileCommentStr.length ? input.fileCommentStr : null,
  1224. unixPermissions : input.unixPermissions,
  1225. dosPermissions : input.dosPermissions,
  1226. createFolders: options.createFolders
  1227. });
  1228. }
  1229. if (zipEntries.zipComment.length) {
  1230. zip.comment = zipEntries.zipComment;
  1231. }
  1232.  
  1233. return zip;
  1234. });
  1235. };
  1236.  
  1237. },{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){
  1238. "use strict";
  1239.  
  1240. var utils = require('../utils');
  1241. var GenericWorker = require('../stream/GenericWorker');
  1242.  
  1243. /**
  1244. * A worker that use a nodejs stream as source.
  1245. * @constructor
  1246. * @param {String} filename the name of the file entry for this stream.
  1247. * @param {Readable} stream the nodejs stream.
  1248. */
  1249. function NodejsStreamInputAdapter(filename, stream) {
  1250. GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
  1251. this._upstreamEnded = false;
  1252. this._bindStream(stream);
  1253. }
  1254.  
  1255. utils.inherits(NodejsStreamInputAdapter, GenericWorker);
  1256.  
  1257. /**
  1258. * Prepare the stream and bind the callbacks on it.
  1259. * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
  1260. * @param {Stream} stream the nodejs stream to use.
  1261. */
  1262. NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
  1263. var self = this;
  1264. this._stream = stream;
  1265. stream.pause();
  1266. stream
  1267. .on("data", function (chunk) {
  1268. self.push({
  1269. data: chunk,
  1270. meta : {
  1271. percent : 0
  1272. }
  1273. });
  1274. })
  1275. .on("error", function (e) {
  1276. if(self.isPaused) {
  1277. this.generatedError = e;
  1278. } else {
  1279. self.error(e);
  1280. }
  1281. })
  1282. .on("end", function () {
  1283. if(self.isPaused) {
  1284. self._upstreamEnded = true;
  1285. } else {
  1286. self.end();
  1287. }
  1288. });
  1289. };
  1290. NodejsStreamInputAdapter.prototype.pause = function () {
  1291. if(!GenericWorker.prototype.pause.call(this)) {
  1292. return false;
  1293. }
  1294. this._stream.pause();
  1295. return true;
  1296. };
  1297. NodejsStreamInputAdapter.prototype.resume = function () {
  1298. if(!GenericWorker.prototype.resume.call(this)) {
  1299. return false;
  1300. }
  1301.  
  1302. if(this._upstreamEnded) {
  1303. this.end();
  1304. } else {
  1305. this._stream.resume();
  1306. }
  1307.  
  1308. return true;
  1309. };
  1310.  
  1311. module.exports = NodejsStreamInputAdapter;
  1312.  
  1313. },{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){
  1314. 'use strict';
  1315.  
  1316. var Readable = require('readable-stream').Readable;
  1317.  
  1318. var utils = require('../utils');
  1319. utils.inherits(NodejsStreamOutputAdapter, Readable);
  1320.  
  1321. /**
  1322. * A nodejs stream using a worker as source.
  1323. * @see the SourceWrapper in http://nodejs.org/api/stream.html
  1324. * @constructor
  1325. * @param {StreamHelper} helper the helper wrapping the worker
  1326. * @param {Object} options the nodejs stream options
  1327. * @param {Function} updateCb the update callback.
  1328. */
  1329. function NodejsStreamOutputAdapter(helper, options, updateCb) {
  1330. Readable.call(this, options);
  1331. this._helper = helper;
  1332.  
  1333. var self = this;
  1334. helper.on("data", function (data, meta) {
  1335. if (!self.push(data)) {
  1336. self._helper.pause();
  1337. }
  1338. if(updateCb) {
  1339. updateCb(meta);
  1340. }
  1341. })
  1342. .on("error", function(e) {
  1343. self.emit('error', e);
  1344. })
  1345. .on("end", function () {
  1346. self.push(null);
  1347. });
  1348. }
  1349.  
  1350.  
  1351. NodejsStreamOutputAdapter.prototype._read = function() {
  1352. this._helper.resume();
  1353. };
  1354.  
  1355. module.exports = NodejsStreamOutputAdapter;
  1356.  
  1357. },{"../utils":32,"readable-stream":16}],14:[function(require,module,exports){
  1358. 'use strict';
  1359.  
  1360. module.exports = {
  1361. /**
  1362. * True if this is running in Nodejs, will be undefined in a browser.
  1363. * In a browser, browserify won't include this file and the whole module
  1364. * will be resolved an empty object.
  1365. */
  1366. isNode : typeof Buffer !== "undefined",
  1367. /**
  1368. * Create a new nodejs Buffer from an existing content.
  1369. * @param {Object} data the data to pass to the constructor.
  1370. * @param {String} encoding the encoding to use.
  1371. * @return {Buffer} a new Buffer.
  1372. */
  1373. newBufferFrom: function(data, encoding) {
  1374. // XXX We can't use `Buffer.from` which comes from `Uint8Array.from`
  1375. // in nodejs v4 (< v.4.5). It's not the expected implementation (and
  1376. // has a different signature).
  1377. // see https://github.com/nodejs/node/issues/8053
  1378. // A condition on nodejs' version won't solve the issue as we don't
  1379. // control the Buffer polyfills that may or may not be used.
  1380. return new Buffer(data, encoding);
  1381. },
  1382. /**
  1383. * Create a new nodejs Buffer with the specified size.
  1384. * @param {Integer} size the size of the buffer.
  1385. * @return {Buffer} a new Buffer.
  1386. */
  1387. allocBuffer: function (size) {
  1388. if (Buffer.alloc) {
  1389. return Buffer.alloc(size);
  1390. } else {
  1391. return new Buffer(size);
  1392. }
  1393. },
  1394. /**
  1395. * Find out if an object is a Buffer.
  1396. * @param {Object} b the object to test.
  1397. * @return {Boolean} true if the object is a Buffer, false otherwise.
  1398. */
  1399. isBuffer : function(b){
  1400. return Buffer.isBuffer(b);
  1401. },
  1402.  
  1403. isStream : function (obj) {
  1404. return obj &&
  1405. typeof obj.on === "function" &&
  1406. typeof obj.pause === "function" &&
  1407. typeof obj.resume === "function";
  1408. }
  1409. };
  1410.  
  1411. },{}],15:[function(require,module,exports){
  1412. 'use strict';
  1413. var utf8 = require('./utf8');
  1414. var utils = require('./utils');
  1415. var GenericWorker = require('./stream/GenericWorker');
  1416. var StreamHelper = require('./stream/StreamHelper');
  1417. var defaults = require('./defaults');
  1418. var CompressedObject = require('./compressedObject');
  1419. var ZipObject = require('./zipObject');
  1420. var generate = require("./generate");
  1421. var nodejsUtils = require("./nodejsUtils");
  1422. var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
  1423.  
  1424.  
  1425. /**
  1426. * Add a file in the current folder.
  1427. * @private
  1428. * @param {string} name the name of the file
  1429. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  1430. * @param {Object} originalOptions the options of the file
  1431. * @return {Object} the new file.
  1432. */
  1433. var fileAdd = function(name, data, originalOptions) {
  1434. // be sure sub folders exist
  1435. var dataType = utils.getTypeOf(data),
  1436. parent;
  1437.  
  1438.  
  1439. /*
  1440. * Correct options.
  1441. */
  1442.  
  1443. var o = utils.extend(originalOptions || {}, defaults);
  1444. o.date = o.date || new Date();
  1445. if (o.compression !== null) {
  1446. o.compression = o.compression.toUpperCase();
  1447. }
  1448.  
  1449. if (typeof o.unixPermissions === "string") {
  1450. o.unixPermissions = parseInt(o.unixPermissions, 8);
  1451. }
  1452.  
  1453. // UNX_IFDIR 0040000 see zipinfo.c
  1454. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  1455. o.dir = true;
  1456. }
  1457. // Bit 4 Directory
  1458. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  1459. o.dir = true;
  1460. }
  1461.  
  1462. if (o.dir) {
  1463. name = forceTrailingSlash(name);
  1464. }
  1465. if (o.createFolders && (parent = parentFolder(name))) {
  1466. folderAdd.call(this, parent, true);
  1467. }
  1468.  
  1469. var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
  1470. if (!originalOptions || typeof originalOptions.binary === "undefined") {
  1471. o.binary = !isUnicodeString;
  1472. }
  1473.  
  1474.  
  1475. var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
  1476.  
  1477. if (isCompressedEmpty || o.dir || !data || data.length === 0) {
  1478. o.base64 = false;
  1479. o.binary = true;
  1480. data = "";
  1481. o.compression = "STORE";
  1482. dataType = "string";
  1483. }
  1484.  
  1485. /*
  1486. * Convert content to fit.
  1487. */
  1488.  
  1489. var zipObjectContent = null;
  1490. if (data instanceof CompressedObject || data instanceof GenericWorker) {
  1491. zipObjectContent = data;
  1492. } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1493. zipObjectContent = new NodejsStreamInputAdapter(name, data);
  1494. } else {
  1495. zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
  1496. }
  1497.  
  1498. var object = new ZipObject(name, zipObjectContent, o);
  1499. this.files[name] = object;
  1500. /*
  1501. TODO: we can't throw an exception because we have async promises
  1502. (we can have a promise of a Date() for example) but returning a
  1503. promise is useless because file(name, data) returns the JSZip
  1504. object for chaining. Should we break that to allow the user
  1505. to catch the error ?
  1506.  
  1507. return external.Promise.resolve(zipObjectContent)
  1508. .then(function () {
  1509. return object;
  1510. });
  1511. */
  1512. };
  1513.  
  1514. /**
  1515. * Find the parent folder of the path.
  1516. * @private
  1517. * @param {string} path the path to use
  1518. * @return {string} the parent folder, or ""
  1519. */
  1520. var parentFolder = function (path) {
  1521. if (path.slice(-1) === '/') {
  1522. path = path.substring(0, path.length - 1);
  1523. }
  1524. var lastSlash = path.lastIndexOf('/');
  1525. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  1526. };
  1527.  
  1528. /**
  1529. * Returns the path with a slash at the end.
  1530. * @private
  1531. * @param {String} path the path to check.
  1532. * @return {String} the path with a trailing slash.
  1533. */
  1534. var forceTrailingSlash = function(path) {
  1535. // Check the name ends with a /
  1536. if (path.slice(-1) !== "/") {
  1537. path += "/"; // IE doesn't like substr(-1)
  1538. }
  1539. return path;
  1540. };
  1541.  
  1542. /**
  1543. * Add a (sub) folder in the current folder.
  1544. * @private
  1545. * @param {string} name the folder's name
  1546. * @param {boolean=} [createFolders] If true, automatically create sub
  1547. * folders. Defaults to false.
  1548. * @return {Object} the new folder.
  1549. */
  1550. var folderAdd = function(name, createFolders) {
  1551. createFolders = (typeof createFolders !== 'undefined') ? createFolders : defaults.createFolders;
  1552.  
  1553. name = forceTrailingSlash(name);
  1554.  
  1555. // Does this folder already exist?
  1556. if (!this.files[name]) {
  1557. fileAdd.call(this, name, null, {
  1558. dir: true,
  1559. createFolders: createFolders
  1560. });
  1561. }
  1562. return this.files[name];
  1563. };
  1564.  
  1565. /**
  1566. * Cross-window, cross-Node-context regular expression detection
  1567. * @param {Object} object Anything
  1568. * @return {Boolean} true if the object is a regular expression,
  1569. * false otherwise
  1570. */
  1571. function isRegExp(object) {
  1572. return Object.prototype.toString.call(object) === "[object RegExp]";
  1573. }
  1574.  
  1575. // return the actual prototype of JSZip
  1576. var out = {
  1577. /**
  1578. * @see loadAsync
  1579. */
  1580. load: function() {
  1581. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1582. },
  1583.  
  1584.  
  1585. /**
  1586. * Call a callback function for each entry at this folder level.
  1587. * @param {Function} cb the callback function:
  1588. * function (relativePath, file) {...}
  1589. * It takes 2 arguments : the relative path and the file.
  1590. */
  1591. forEach: function(cb) {
  1592. var filename, relativePath, file;
  1593. for (filename in this.files) {
  1594. if (!this.files.hasOwnProperty(filename)) {
  1595. continue;
  1596. }
  1597. file = this.files[filename];
  1598. relativePath = filename.slice(this.root.length, filename.length);
  1599. if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
  1600. cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
  1601. }
  1602. }
  1603. },
  1604.  
  1605. /**
  1606. * Filter nested files/folders with the specified function.
  1607. * @param {Function} search the predicate to use :
  1608. * function (relativePath, file) {...}
  1609. * It takes 2 arguments : the relative path and the file.
  1610. * @return {Array} An array of matching elements.
  1611. */
  1612. filter: function(search) {
  1613. var result = [];
  1614. this.forEach(function (relativePath, entry) {
  1615. if (search(relativePath, entry)) { // the file matches the function
  1616. result.push(entry);
  1617. }
  1618.  
  1619. });
  1620. return result;
  1621. },
  1622.  
  1623. /**
  1624. * Add a file to the zip file, or search a file.
  1625. * @param {string|RegExp} name The name of the file to add (if data is defined),
  1626. * the name of the file to find (if no data) or a regex to match files.
  1627. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  1628. * @param {Object} o File options
  1629. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  1630. * a file (when searching by string) or an array of files (when searching by regex).
  1631. */
  1632. file: function(name, data, o) {
  1633. if (arguments.length === 1) {
  1634. if (isRegExp(name)) {
  1635. var regexp = name;
  1636. return this.filter(function(relativePath, file) {
  1637. return !file.dir && regexp.test(relativePath);
  1638. });
  1639. }
  1640. else { // text
  1641. var obj = this.files[this.root + name];
  1642. if (obj && !obj.dir) {
  1643. return obj;
  1644. } else {
  1645. return null;
  1646. }
  1647. }
  1648. }
  1649. else { // more than one argument : we have data !
  1650. name = this.root + name;
  1651. fileAdd.call(this, name, data, o);
  1652. }
  1653. return this;
  1654. },
  1655.  
  1656. /**
  1657. * Add a directory to the zip file, or search.
  1658. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  1659. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  1660. */
  1661. folder: function(arg) {
  1662. if (!arg) {
  1663. return this;
  1664. }
  1665.  
  1666. if (isRegExp(arg)) {
  1667. return this.filter(function(relativePath, file) {
  1668. return file.dir && arg.test(relativePath);
  1669. });
  1670. }
  1671.  
  1672. // else, name is a new folder
  1673. var name = this.root + arg;
  1674. var newFolder = folderAdd.call(this, name);
  1675.  
  1676. // Allow chaining by returning a new object with this folder as the root
  1677. var ret = this.clone();
  1678. ret.root = newFolder.name;
  1679. return ret;
  1680. },
  1681.  
  1682. /**
  1683. * Delete a file, or a directory and all sub-files, from the zip
  1684. * @param {string} name the name of the file to delete
  1685. * @return {JSZip} this JSZip object
  1686. */
  1687. remove: function(name) {
  1688. name = this.root + name;
  1689. var file = this.files[name];
  1690. if (!file) {
  1691. // Look for any folders
  1692. if (name.slice(-1) !== "/") {
  1693. name += "/";
  1694. }
  1695. file = this.files[name];
  1696. }
  1697.  
  1698. if (file && !file.dir) {
  1699. // file
  1700. delete this.files[name];
  1701. } else {
  1702. // maybe a folder, delete recursively
  1703. var kids = this.filter(function(relativePath, file) {
  1704. return file.name.slice(0, name.length) === name;
  1705. });
  1706. for (var i = 0; i < kids.length; i++) {
  1707. delete this.files[kids[i].name];
  1708. }
  1709. }
  1710.  
  1711. return this;
  1712. },
  1713.  
  1714. /**
  1715. * Generate the complete zip file
  1716. * @param {Object} options the options to generate the zip file :
  1717. * - compression, "STORE" by default.
  1718. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1719. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  1720. */
  1721. generate: function(options) {
  1722. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1723. },
  1724.  
  1725. /**
  1726. * Generate the complete zip file as an internal stream.
  1727. * @param {Object} options the options to generate the zip file :
  1728. * - compression, "STORE" by default.
  1729. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1730. * @return {StreamHelper} the streamed zip file.
  1731. */
  1732. generateInternalStream: function(options) {
  1733. var worker, opts = {};
  1734. try {
  1735. opts = utils.extend(options || {}, {
  1736. streamFiles: false,
  1737. compression: "STORE",
  1738. compressionOptions : null,
  1739. type: "",
  1740. platform: "DOS",
  1741. comment: null,
  1742. mimeType: 'application/zip',
  1743. encodeFileName: utf8.utf8encode
  1744. });
  1745.  
  1746. opts.type = opts.type.toLowerCase();
  1747. opts.compression = opts.compression.toUpperCase();
  1748.  
  1749. // "binarystring" is prefered but the internals use "string".
  1750. if(opts.type === "binarystring") {
  1751. opts.type = "string";
  1752. }
  1753.  
  1754. if (!opts.type) {
  1755. throw new Error("No output type specified.");
  1756. }
  1757.  
  1758. utils.checkSupport(opts.type);
  1759.  
  1760. // accept nodejs `process.platform`
  1761. if(
  1762. opts.platform === 'darwin' ||
  1763. opts.platform === 'freebsd' ||
  1764. opts.platform === 'linux' ||
  1765. opts.platform === 'sunos'
  1766. ) {
  1767. opts.platform = "UNIX";
  1768. }
  1769. if (opts.platform === 'win32') {
  1770. opts.platform = "DOS";
  1771. }
  1772.  
  1773. var comment = opts.comment || this.comment || "";
  1774. worker = generate.generateWorker(this, opts, comment);
  1775. } catch (e) {
  1776. worker = new GenericWorker("error");
  1777. worker.error(e);
  1778. }
  1779. return new StreamHelper(worker, opts.type || "string", opts.mimeType);
  1780. },
  1781. /**
  1782. * Generate the complete zip file asynchronously.
  1783. * @see generateInternalStream
  1784. */
  1785. generateAsync: function(options, onUpdate) {
  1786. return this.generateInternalStream(options).accumulate(onUpdate);
  1787. },
  1788. /**
  1789. * Generate the complete zip file asynchronously.
  1790. * @see generateInternalStream
  1791. */
  1792. generateNodeStream: function(options, onUpdate) {
  1793. options = options || {};
  1794. if (!options.type) {
  1795. options.type = "nodebuffer";
  1796. }
  1797. return this.generateInternalStream(options).toNodejsStream(onUpdate);
  1798. }
  1799. };
  1800. module.exports = out;
  1801.  
  1802. },{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(require,module,exports){
  1803. /*
  1804. * This file is used by module bundlers (browserify/webpack/etc) when
  1805. * including a stream implementation. We use "readable-stream" to get a
  1806. * consistent behavior between nodejs versions but bundlers often have a shim
  1807. * for "stream". Using this shim greatly improve the compatibility and greatly
  1808. * reduce the final size of the bundle (only one stream implementation, not
  1809. * two).
  1810. */
  1811. module.exports = require("stream");
  1812.  
  1813. },{"stream":undefined}],17:[function(require,module,exports){
  1814. 'use strict';
  1815. var DataReader = require('./DataReader');
  1816. var utils = require('../utils');
  1817.  
  1818. function ArrayReader(data) {
  1819. DataReader.call(this, data);
  1820. for(var i = 0; i < this.data.length; i++) {
  1821. data[i] = data[i] & 0xFF;
  1822. }
  1823. }
  1824. utils.inherits(ArrayReader, DataReader);
  1825. /**
  1826. * @see DataReader.byteAt
  1827. */
  1828. ArrayReader.prototype.byteAt = function(i) {
  1829. return this.data[this.zero + i];
  1830. };
  1831. /**
  1832. * @see DataReader.lastIndexOfSignature
  1833. */
  1834. ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  1835. var sig0 = sig.charCodeAt(0),
  1836. sig1 = sig.charCodeAt(1),
  1837. sig2 = sig.charCodeAt(2),
  1838. sig3 = sig.charCodeAt(3);
  1839. for (var i = this.length - 4; i >= 0; --i) {
  1840. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  1841. return i - this.zero;
  1842. }
  1843. }
  1844.  
  1845. return -1;
  1846. };
  1847. /**
  1848. * @see DataReader.readAndCheckSignature
  1849. */
  1850. ArrayReader.prototype.readAndCheckSignature = function (sig) {
  1851. var sig0 = sig.charCodeAt(0),
  1852. sig1 = sig.charCodeAt(1),
  1853. sig2 = sig.charCodeAt(2),
  1854. sig3 = sig.charCodeAt(3),
  1855. data = this.readData(4);
  1856. return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
  1857. };
  1858. /**
  1859. * @see DataReader.readData
  1860. */
  1861. ArrayReader.prototype.readData = function(size) {
  1862. this.checkOffset(size);
  1863. if(size === 0) {
  1864. return [];
  1865. }
  1866. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1867. this.index += size;
  1868. return result;
  1869. };
  1870. module.exports = ArrayReader;
  1871.  
  1872. },{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){
  1873. 'use strict';
  1874. var utils = require('../utils');
  1875.  
  1876. function DataReader(data) {
  1877. this.data = data; // type : see implementation
  1878. this.length = data.length;
  1879. this.index = 0;
  1880. this.zero = 0;
  1881. }
  1882. DataReader.prototype = {
  1883. /**
  1884. * Check that the offset will not go too far.
  1885. * @param {string} offset the additional offset to check.
  1886. * @throws {Error} an Error if the offset is out of bounds.
  1887. */
  1888. checkOffset: function(offset) {
  1889. this.checkIndex(this.index + offset);
  1890. },
  1891. /**
  1892. * Check that the specified index will not be too far.
  1893. * @param {string} newIndex the index to check.
  1894. * @throws {Error} an Error if the index is out of bounds.
  1895. */
  1896. checkIndex: function(newIndex) {
  1897. if (this.length < this.zero + newIndex || newIndex < 0) {
  1898. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  1899. }
  1900. },
  1901. /**
  1902. * Change the index.
  1903. * @param {number} newIndex The new index.
  1904. * @throws {Error} if the new index is out of the data.
  1905. */
  1906. setIndex: function(newIndex) {
  1907. this.checkIndex(newIndex);
  1908. this.index = newIndex;
  1909. },
  1910. /**
  1911. * Skip the next n bytes.
  1912. * @param {number} n the number of bytes to skip.
  1913. * @throws {Error} if the new index is out of the data.
  1914. */
  1915. skip: function(n) {
  1916. this.setIndex(this.index + n);
  1917. },
  1918. /**
  1919. * Get the byte at the specified index.
  1920. * @param {number} i the index to use.
  1921. * @return {number} a byte.
  1922. */
  1923. byteAt: function(i) {
  1924. // see implementations
  1925. },
  1926. /**
  1927. * Get the next number with a given byte size.
  1928. * @param {number} size the number of bytes to read.
  1929. * @return {number} the corresponding number.
  1930. */
  1931. readInt: function(size) {
  1932. var result = 0,
  1933. i;
  1934. this.checkOffset(size);
  1935. for (i = this.index + size - 1; i >= this.index; i--) {
  1936. result = (result << 8) + this.byteAt(i);
  1937. }
  1938. this.index += size;
  1939. return result;
  1940. },
  1941. /**
  1942. * Get the next string with a given byte size.
  1943. * @param {number} size the number of bytes to read.
  1944. * @return {string} the corresponding string.
  1945. */
  1946. readString: function(size) {
  1947. return utils.transformTo("string", this.readData(size));
  1948. },
  1949. /**
  1950. * Get raw data without conversion, <size> bytes.
  1951. * @param {number} size the number of bytes to read.
  1952. * @return {Object} the raw data, implementation specific.
  1953. */
  1954. readData: function(size) {
  1955. // see implementations
  1956. },
  1957. /**
  1958. * Find the last occurence of a zip signature (4 bytes).
  1959. * @param {string} sig the signature to find.
  1960. * @return {number} the index of the last occurence, -1 if not found.
  1961. */
  1962. lastIndexOfSignature: function(sig) {
  1963. // see implementations
  1964. },
  1965. /**
  1966. * Read the signature (4 bytes) at the current position and compare it with sig.
  1967. * @param {string} sig the expected signature
  1968. * @return {boolean} true if the signature matches, false otherwise.
  1969. */
  1970. readAndCheckSignature: function(sig) {
  1971. // see implementations
  1972. },
  1973. /**
  1974. * Get the next date.
  1975. * @return {Date} the date.
  1976. */
  1977. readDate: function() {
  1978. var dostime = this.readInt(4);
  1979. return new Date(Date.UTC(
  1980. ((dostime >> 25) & 0x7f) + 1980, // year
  1981. ((dostime >> 21) & 0x0f) - 1, // month
  1982. (dostime >> 16) & 0x1f, // day
  1983. (dostime >> 11) & 0x1f, // hour
  1984. (dostime >> 5) & 0x3f, // minute
  1985. (dostime & 0x1f) << 1)); // second
  1986. }
  1987. };
  1988. module.exports = DataReader;
  1989.  
  1990. },{"../utils":32}],19:[function(require,module,exports){
  1991. 'use strict';
  1992. var Uint8ArrayReader = require('./Uint8ArrayReader');
  1993. var utils = require('../utils');
  1994.  
  1995. function NodeBufferReader(data) {
  1996. Uint8ArrayReader.call(this, data);
  1997. }
  1998. utils.inherits(NodeBufferReader, Uint8ArrayReader);
  1999.  
  2000. /**
  2001. * @see DataReader.readData
  2002. */
  2003. NodeBufferReader.prototype.readData = function(size) {
  2004. this.checkOffset(size);
  2005. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  2006. this.index += size;
  2007. return result;
  2008. };
  2009. module.exports = NodeBufferReader;
  2010.  
  2011. },{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){
  2012. 'use strict';
  2013. var DataReader = require('./DataReader');
  2014. var utils = require('../utils');
  2015.  
  2016. function StringReader(data) {
  2017. DataReader.call(this, data);
  2018. }
  2019. utils.inherits(StringReader, DataReader);
  2020. /**
  2021. * @see DataReader.byteAt
  2022. */
  2023. StringReader.prototype.byteAt = function(i) {
  2024. return this.data.charCodeAt(this.zero + i);
  2025. };
  2026. /**
  2027. * @see DataReader.lastIndexOfSignature
  2028. */
  2029. StringReader.prototype.lastIndexOfSignature = function(sig) {
  2030. return this.data.lastIndexOf(sig) - this.zero;
  2031. };
  2032. /**
  2033. * @see DataReader.readAndCheckSignature
  2034. */
  2035. StringReader.prototype.readAndCheckSignature = function (sig) {
  2036. var data = this.readData(4);
  2037. return sig === data;
  2038. };
  2039. /**
  2040. * @see DataReader.readData
  2041. */
  2042. StringReader.prototype.readData = function(size) {
  2043. this.checkOffset(size);
  2044. // this will work because the constructor applied the "& 0xff" mask.
  2045. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  2046. this.index += size;
  2047. return result;
  2048. };
  2049. module.exports = StringReader;
  2050.  
  2051. },{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){
  2052. 'use strict';
  2053. var ArrayReader = require('./ArrayReader');
  2054. var utils = require('../utils');
  2055.  
  2056. function Uint8ArrayReader(data) {
  2057. ArrayReader.call(this, data);
  2058. }
  2059. utils.inherits(Uint8ArrayReader, ArrayReader);
  2060. /**
  2061. * @see DataReader.readData
  2062. */
  2063. Uint8ArrayReader.prototype.readData = function(size) {
  2064. this.checkOffset(size);
  2065. if(size === 0) {
  2066. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  2067. return new Uint8Array(0);
  2068. }
  2069. var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
  2070. this.index += size;
  2071. return result;
  2072. };
  2073. module.exports = Uint8ArrayReader;
  2074.  
  2075. },{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){
  2076. 'use strict';
  2077.  
  2078. var utils = require('../utils');
  2079. var support = require('../support');
  2080. var ArrayReader = require('./ArrayReader');
  2081. var StringReader = require('./StringReader');
  2082. var NodeBufferReader = require('./NodeBufferReader');
  2083. var Uint8ArrayReader = require('./Uint8ArrayReader');
  2084.  
  2085. /**
  2086. * Create a reader adapted to the data.
  2087. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
  2088. * @return {DataReader} the data reader.
  2089. */
  2090. module.exports = function (data) {
  2091. var type = utils.getTypeOf(data);
  2092. utils.checkSupport(type);
  2093. if (type === "string" && !support.uint8array) {
  2094. return new StringReader(data);
  2095. }
  2096. if (type === "nodebuffer") {
  2097. return new NodeBufferReader(data);
  2098. }
  2099. if (support.uint8array) {
  2100. return new Uint8ArrayReader(utils.transformTo("uint8array", data));
  2101. }
  2102. return new ArrayReader(utils.transformTo("array", data));
  2103. };
  2104.  
  2105. },{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){
  2106. 'use strict';
  2107. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  2108. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  2109. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  2110. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  2111. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  2112. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  2113.  
  2114. },{}],24:[function(require,module,exports){
  2115. 'use strict';
  2116.  
  2117. var GenericWorker = require('./GenericWorker');
  2118. var utils = require('../utils');
  2119.  
  2120. /**
  2121. * A worker which convert chunks to a specified type.
  2122. * @constructor
  2123. * @param {String} destType the destination type.
  2124. */
  2125. function ConvertWorker(destType) {
  2126. GenericWorker.call(this, "ConvertWorker to " + destType);
  2127. this.destType = destType;
  2128. }
  2129. utils.inherits(ConvertWorker, GenericWorker);
  2130.  
  2131. /**
  2132. * @see GenericWorker.processChunk
  2133. */
  2134. ConvertWorker.prototype.processChunk = function (chunk) {
  2135. this.push({
  2136. data : utils.transformTo(this.destType, chunk.data),
  2137. meta : chunk.meta
  2138. });
  2139. };
  2140. module.exports = ConvertWorker;
  2141.  
  2142. },{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){
  2143. 'use strict';
  2144.  
  2145. var GenericWorker = require('./GenericWorker');
  2146. var crc32 = require('../crc32');
  2147. var utils = require('../utils');
  2148.  
  2149. /**
  2150. * A worker which calculate the crc32 of the data flowing through.
  2151. * @constructor
  2152. */
  2153. function Crc32Probe() {
  2154. GenericWorker.call(this, "Crc32Probe");
  2155. this.withStreamInfo("crc32", 0);
  2156. }
  2157. utils.inherits(Crc32Probe, GenericWorker);
  2158.  
  2159. /**
  2160. * @see GenericWorker.processChunk
  2161. */
  2162. Crc32Probe.prototype.processChunk = function (chunk) {
  2163. this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
  2164. this.push(chunk);
  2165. };
  2166. module.exports = Crc32Probe;
  2167.  
  2168. },{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){
  2169. 'use strict';
  2170.  
  2171. var utils = require('../utils');
  2172. var GenericWorker = require('./GenericWorker');
  2173.  
  2174. /**
  2175. * A worker which calculate the total length of the data flowing through.
  2176. * @constructor
  2177. * @param {String} propName the name used to expose the length
  2178. */
  2179. function DataLengthProbe(propName) {
  2180. GenericWorker.call(this, "DataLengthProbe for " + propName);
  2181. this.propName = propName;
  2182. this.withStreamInfo(propName, 0);
  2183. }
  2184. utils.inherits(DataLengthProbe, GenericWorker);
  2185.  
  2186. /**
  2187. * @see GenericWorker.processChunk
  2188. */
  2189. DataLengthProbe.prototype.processChunk = function (chunk) {
  2190. if(chunk) {
  2191. var length = this.streamInfo[this.propName] || 0;
  2192. this.streamInfo[this.propName] = length + chunk.data.length;
  2193. }
  2194. GenericWorker.prototype.processChunk.call(this, chunk);
  2195. };
  2196. module.exports = DataLengthProbe;
  2197.  
  2198.  
  2199. },{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){
  2200. 'use strict';
  2201.  
  2202. var utils = require('../utils');
  2203. var GenericWorker = require('./GenericWorker');
  2204.  
  2205. // the size of the generated chunks
  2206. // TODO expose this as a public variable
  2207. var DEFAULT_BLOCK_SIZE = 16 * 1024;
  2208.  
  2209. /**
  2210. * A worker that reads a content and emits chunks.
  2211. * @constructor
  2212. * @param {Promise} dataP the promise of the data to split
  2213. */
  2214. function DataWorker(dataP) {
  2215. GenericWorker.call(this, "DataWorker");
  2216. var self = this;
  2217. this.dataIsReady = false;
  2218. this.index = 0;
  2219. this.max = 0;
  2220. this.data = null;
  2221. this.type = "";
  2222.  
  2223. this._tickScheduled = false;
  2224.  
  2225. dataP.then(function (data) {
  2226. self.dataIsReady = true;
  2227. self.data = data;
  2228. self.max = data && data.length || 0;
  2229. self.type = utils.getTypeOf(data);
  2230. if(!self.isPaused) {
  2231. self._tickAndRepeat();
  2232. }
  2233. }, function (e) {
  2234. self.error(e);
  2235. });
  2236. }
  2237.  
  2238. utils.inherits(DataWorker, GenericWorker);
  2239.  
  2240. /**
  2241. * @see GenericWorker.cleanUp
  2242. */
  2243. DataWorker.prototype.cleanUp = function () {
  2244. GenericWorker.prototype.cleanUp.call(this);
  2245. this.data = null;
  2246. };
  2247.  
  2248. /**
  2249. * @see GenericWorker.resume
  2250. */
  2251. DataWorker.prototype.resume = function () {
  2252. if(!GenericWorker.prototype.resume.call(this)) {
  2253. return false;
  2254. }
  2255.  
  2256. if (!this._tickScheduled && this.dataIsReady) {
  2257. this._tickScheduled = true;
  2258. utils.delay(this._tickAndRepeat, [], this);
  2259. }
  2260. return true;
  2261. };
  2262.  
  2263. /**
  2264. * Trigger a tick a schedule an other call to this function.
  2265. */
  2266. DataWorker.prototype._tickAndRepeat = function() {
  2267. this._tickScheduled = false;
  2268. if(this.isPaused || this.isFinished) {
  2269. return;
  2270. }
  2271. this._tick();
  2272. if(!this.isFinished) {
  2273. utils.delay(this._tickAndRepeat, [], this);
  2274. this._tickScheduled = true;
  2275. }
  2276. };
  2277.  
  2278. /**
  2279. * Read and push a chunk.
  2280. */
  2281. DataWorker.prototype._tick = function() {
  2282.  
  2283. if(this.isPaused || this.isFinished) {
  2284. return false;
  2285. }
  2286.  
  2287. var size = DEFAULT_BLOCK_SIZE;
  2288. var data = null, nextIndex = Math.min(this.max, this.index + size);
  2289. if (this.index >= this.max) {
  2290. // EOF
  2291. return this.end();
  2292. } else {
  2293. switch(this.type) {
  2294. case "string":
  2295. data = this.data.substring(this.index, nextIndex);
  2296. break;
  2297. case "uint8array":
  2298. data = this.data.subarray(this.index, nextIndex);
  2299. break;
  2300. case "array":
  2301. case "nodebuffer":
  2302. data = this.data.slice(this.index, nextIndex);
  2303. break;
  2304. }
  2305. this.index = nextIndex;
  2306. return this.push({
  2307. data : data,
  2308. meta : {
  2309. percent : this.max ? this.index / this.max * 100 : 0
  2310. }
  2311. });
  2312. }
  2313. };
  2314.  
  2315. module.exports = DataWorker;
  2316.  
  2317. },{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){
  2318. 'use strict';
  2319.  
  2320. /**
  2321. * A worker that does nothing but passing chunks to the next one. This is like
  2322. * a nodejs stream but with some differences. On the good side :
  2323. * - it works on IE 6-9 without any issue / polyfill
  2324. * - it weights less than the full dependencies bundled with browserify
  2325. * - it forwards errors (no need to declare an error handler EVERYWHERE)
  2326. *
  2327. * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
  2328. * object containing anything (`percent` for example), see each worker for more
  2329. * details. The latter is the real data (String, Uint8Array, etc).
  2330. *
  2331. * @constructor
  2332. * @param {String} name the name of the stream (mainly used for debugging purposes)
  2333. */
  2334. function GenericWorker(name) {
  2335. // the name of the worker
  2336. this.name = name || "default";
  2337. // an object containing metadata about the workers chain
  2338. this.streamInfo = {};
  2339. // an error which happened when the worker was paused
  2340. this.generatedError = null;
  2341. // an object containing metadata to be merged by this worker into the general metadata
  2342. this.extraStreamInfo = {};
  2343. // true if the stream is paused (and should not do anything), false otherwise
  2344. this.isPaused = true;
  2345. // true if the stream is finished (and should not do anything), false otherwise
  2346. this.isFinished = false;
  2347. // true if the stream is locked to prevent further structure updates (pipe), false otherwise
  2348. this.isLocked = false;
  2349. // the event listeners
  2350. this._listeners = {
  2351. 'data':[],
  2352. 'end':[],
  2353. 'error':[]
  2354. };
  2355. // the previous worker, if any
  2356. this.previous = null;
  2357. }
  2358.  
  2359. GenericWorker.prototype = {
  2360. /**
  2361. * Push a chunk to the next workers.
  2362. * @param {Object} chunk the chunk to push
  2363. */
  2364. push : function (chunk) {
  2365. this.emit("data", chunk);
  2366. },
  2367. /**
  2368. * End the stream.
  2369. * @return {Boolean} true if this call ended the worker, false otherwise.
  2370. */
  2371. end : function () {
  2372. if (this.isFinished) {
  2373. return false;
  2374. }
  2375.  
  2376. this.flush();
  2377. try {
  2378. this.emit("end");
  2379. this.cleanUp();
  2380. this.isFinished = true;
  2381. } catch (e) {
  2382. this.emit("error", e);
  2383. }
  2384. return true;
  2385. },
  2386. /**
  2387. * End the stream with an error.
  2388. * @param {Error} e the error which caused the premature end.
  2389. * @return {Boolean} true if this call ended the worker with an error, false otherwise.
  2390. */
  2391. error : function (e) {
  2392. if (this.isFinished) {
  2393. return false;
  2394. }
  2395.  
  2396. if(this.isPaused) {
  2397. this.generatedError = e;
  2398. } else {
  2399. this.isFinished = true;
  2400.  
  2401. this.emit("error", e);
  2402.  
  2403. // in the workers chain exploded in the middle of the chain,
  2404. // the error event will go downward but we also need to notify
  2405. // workers upward that there has been an error.
  2406. if(this.previous) {
  2407. this.previous.error(e);
  2408. }
  2409.  
  2410. this.cleanUp();
  2411. }
  2412. return true;
  2413. },
  2414. /**
  2415. * Add a callback on an event.
  2416. * @param {String} name the name of the event (data, end, error)
  2417. * @param {Function} listener the function to call when the event is triggered
  2418. * @return {GenericWorker} the current object for chainability
  2419. */
  2420. on : function (name, listener) {
  2421. this._listeners[name].push(listener);
  2422. return this;
  2423. },
  2424. /**
  2425. * Clean any references when a worker is ending.
  2426. */
  2427. cleanUp : function () {
  2428. this.streamInfo = this.generatedError = this.extraStreamInfo = null;
  2429. this._listeners = [];
  2430. },
  2431. /**
  2432. * Trigger an event. This will call registered callback with the provided arg.
  2433. * @param {String} name the name of the event (data, end, error)
  2434. * @param {Object} arg the argument to call the callback with.
  2435. */
  2436. emit : function (name, arg) {
  2437. if (this._listeners[name]) {
  2438. for(var i = 0; i < this._listeners[name].length; i++) {
  2439. this._listeners[name][i].call(this, arg);
  2440. }
  2441. }
  2442. },
  2443. /**
  2444. * Chain a worker with an other.
  2445. * @param {Worker} next the worker receiving events from the current one.
  2446. * @return {worker} the next worker for chainability
  2447. */
  2448. pipe : function (next) {
  2449. return next.registerPrevious(this);
  2450. },
  2451. /**
  2452. * Same as `pipe` in the other direction.
  2453. * Using an API with `pipe(next)` is very easy.
  2454. * Implementing the API with the point of view of the next one registering
  2455. * a source is easier, see the ZipFileWorker.
  2456. * @param {Worker} previous the previous worker, sending events to this one
  2457. * @return {Worker} the current worker for chainability
  2458. */
  2459. registerPrevious : function (previous) {
  2460. if (this.isLocked) {
  2461. throw new Error("The stream '" + this + "' has already been used.");
  2462. }
  2463.  
  2464. // sharing the streamInfo...
  2465. this.streamInfo = previous.streamInfo;
  2466. // ... and adding our own bits
  2467. this.mergeStreamInfo();
  2468. this.previous = previous;
  2469. var self = this;
  2470. previous.on('data', function (chunk) {
  2471. self.processChunk(chunk);
  2472. });
  2473. previous.on('end', function () {
  2474. self.end();
  2475. });
  2476. previous.on('error', function (e) {
  2477. self.error(e);
  2478. });
  2479. return this;
  2480. },
  2481. /**
  2482. * Pause the stream so it doesn't send events anymore.
  2483. * @return {Boolean} true if this call paused the worker, false otherwise.
  2484. */
  2485. pause : function () {
  2486. if(this.isPaused || this.isFinished) {
  2487. return false;
  2488. }
  2489. this.isPaused = true;
  2490.  
  2491. if(this.previous) {
  2492. this.previous.pause();
  2493. }
  2494. return true;
  2495. },
  2496. /**
  2497. * Resume a paused stream.
  2498. * @return {Boolean} true if this call resumed the worker, false otherwise.
  2499. */
  2500. resume : function () {
  2501. if(!this.isPaused || this.isFinished) {
  2502. return false;
  2503. }
  2504. this.isPaused = false;
  2505.  
  2506. // if true, the worker tried to resume but failed
  2507. var withError = false;
  2508. if(this.generatedError) {
  2509. this.error(this.generatedError);
  2510. withError = true;
  2511. }
  2512. if(this.previous) {
  2513. this.previous.resume();
  2514. }
  2515.  
  2516. return !withError;
  2517. },
  2518. /**
  2519. * Flush any remaining bytes as the stream is ending.
  2520. */
  2521. flush : function () {},
  2522. /**
  2523. * Process a chunk. This is usually the method overridden.
  2524. * @param {Object} chunk the chunk to process.
  2525. */
  2526. processChunk : function(chunk) {
  2527. this.push(chunk);
  2528. },
  2529. /**
  2530. * Add a key/value to be added in the workers chain streamInfo once activated.
  2531. * @param {String} key the key to use
  2532. * @param {Object} value the associated value
  2533. * @return {Worker} the current worker for chainability
  2534. */
  2535. withStreamInfo : function (key, value) {
  2536. this.extraStreamInfo[key] = value;
  2537. this.mergeStreamInfo();
  2538. return this;
  2539. },
  2540. /**
  2541. * Merge this worker's streamInfo into the chain's streamInfo.
  2542. */
  2543. mergeStreamInfo : function () {
  2544. for(var key in this.extraStreamInfo) {
  2545. if (!this.extraStreamInfo.hasOwnProperty(key)) {
  2546. continue;
  2547. }
  2548. this.streamInfo[key] = this.extraStreamInfo[key];
  2549. }
  2550. },
  2551.  
  2552. /**
  2553. * Lock the stream to prevent further updates on the workers chain.
  2554. * After calling this method, all calls to pipe will fail.
  2555. */
  2556. lock: function () {
  2557. if (this.isLocked) {
  2558. throw new Error("The stream '" + this + "' has already been used.");
  2559. }
  2560. this.isLocked = true;
  2561. if (this.previous) {
  2562. this.previous.lock();
  2563. }
  2564. },
  2565.  
  2566. /**
  2567. *
  2568. * Pretty print the workers chain.
  2569. */
  2570. toString : function () {
  2571. var me = "Worker " + this.name;
  2572. if (this.previous) {
  2573. return this.previous + " -> " + me;
  2574. } else {
  2575. return me;
  2576. }
  2577. }
  2578. };
  2579.  
  2580. module.exports = GenericWorker;
  2581.  
  2582. },{}],29:[function(require,module,exports){
  2583. 'use strict';
  2584.  
  2585. var utils = require('../utils');
  2586. var ConvertWorker = require('./ConvertWorker');
  2587. var GenericWorker = require('./GenericWorker');
  2588. var base64 = require('../base64');
  2589. var support = require("../support");
  2590. var external = require("../external");
  2591.  
  2592. var NodejsStreamOutputAdapter = null;
  2593. if (support.nodestream) {
  2594. try {
  2595. NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter');
  2596. } catch(e) {}
  2597. }
  2598.  
  2599. /**
  2600. * Apply the final transformation of the data. If the user wants a Blob for
  2601. * example, it's easier to work with an U8intArray and finally do the
  2602. * ArrayBuffer/Blob conversion.
  2603. * @param {String} type the name of the final type
  2604. * @param {String|Uint8Array|Buffer} content the content to transform
  2605. * @param {String} mimeType the mime type of the content, if applicable.
  2606. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
  2607. */
  2608. function transformZipOutput(type, content, mimeType) {
  2609. switch(type) {
  2610. case "blob" :
  2611. return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType);
  2612. case "base64" :
  2613. return base64.encode(content);
  2614. default :
  2615. return utils.transformTo(type, content);
  2616. }
  2617. }
  2618.  
  2619. /**
  2620. * Concatenate an array of data of the given type.
  2621. * @param {String} type the type of the data in the given array.
  2622. * @param {Array} dataArray the array containing the data chunks to concatenate
  2623. * @return {String|Uint8Array|Buffer} the concatenated data
  2624. * @throws Error if the asked type is unsupported
  2625. */
  2626. function concat (type, dataArray) {
  2627. var i, index = 0, res = null, totalLength = 0;
  2628. for(i = 0; i < dataArray.length; i++) {
  2629. totalLength += dataArray[i].length;
  2630. }
  2631. switch(type) {
  2632. case "string":
  2633. return dataArray.join("");
  2634. case "array":
  2635. return Array.prototype.concat.apply([], dataArray);
  2636. case "uint8array":
  2637. res = new Uint8Array(totalLength);
  2638. for(i = 0; i < dataArray.length; i++) {
  2639. res.set(dataArray[i], index);
  2640. index += dataArray[i].length;
  2641. }
  2642. return res;
  2643. case "nodebuffer":
  2644. return Buffer.concat(dataArray);
  2645. default:
  2646. throw new Error("concat : unsupported type '" + type + "'");
  2647. }
  2648. }
  2649.  
  2650. /**
  2651. * Listen a StreamHelper, accumulate its content and concatenate it into a
  2652. * complete block.
  2653. * @param {StreamHelper} helper the helper to use.
  2654. * @param {Function} updateCallback a callback called on each update. Called
  2655. * with one arg :
  2656. * - the metadata linked to the update received.
  2657. * @return Promise the promise for the accumulation.
  2658. */
  2659. function accumulate(helper, updateCallback) {
  2660. return new external.Promise(function (resolve, reject){
  2661. var dataArray = [];
  2662. var chunkType = helper._internalType,
  2663. resultType = helper._outputType,
  2664. mimeType = helper._mimeType;
  2665. helper
  2666. .on('data', function (data, meta) {
  2667. dataArray.push(data);
  2668. if(updateCallback) {
  2669. updateCallback(meta);
  2670. }
  2671. })
  2672. .on('error', function(err) {
  2673. dataArray = [];
  2674. reject(err);
  2675. })
  2676. .on('end', function (){
  2677. try {
  2678. var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);
  2679. resolve(result);
  2680. } catch (e) {
  2681. reject(e);
  2682. }
  2683. dataArray = [];
  2684. })
  2685. .resume();
  2686. });
  2687. }
  2688.  
  2689. /**
  2690. * An helper to easily use workers outside of JSZip.
  2691. * @constructor
  2692. * @param {Worker} worker the worker to wrap
  2693. * @param {String} outputType the type of data expected by the use
  2694. * @param {String} mimeType the mime type of the content, if applicable.
  2695. */
  2696. function StreamHelper(worker, outputType, mimeType) {
  2697. var internalType = outputType;
  2698. switch(outputType) {
  2699. case "blob":
  2700. case "arraybuffer":
  2701. internalType = "uint8array";
  2702. break;
  2703. case "base64":
  2704. internalType = "string";
  2705. break;
  2706. }
  2707.  
  2708. try {
  2709. // the type used internally
  2710. this._internalType = internalType;
  2711. // the type used to output results
  2712. this._outputType = outputType;
  2713. // the mime type
  2714. this._mimeType = mimeType;
  2715. utils.checkSupport(internalType);
  2716. this._worker = worker.pipe(new ConvertWorker(internalType));
  2717. // the last workers can be rewired without issues but we need to
  2718. // prevent any updates on previous workers.
  2719. worker.lock();
  2720. } catch(e) {
  2721. this._worker = new GenericWorker("error");
  2722. this._worker.error(e);
  2723. }
  2724. }
  2725.  
  2726. StreamHelper.prototype = {
  2727. /**
  2728. * Listen a StreamHelper, accumulate its content and concatenate it into a
  2729. * complete block.
  2730. * @param {Function} updateCb the update callback.
  2731. * @return Promise the promise for the accumulation.
  2732. */
  2733. accumulate : function (updateCb) {
  2734. return accumulate(this, updateCb);
  2735. },
  2736. /**
  2737. * Add a listener on an event triggered on a stream.
  2738. * @param {String} evt the name of the event
  2739. * @param {Function} fn the listener
  2740. * @return {StreamHelper} the current helper.
  2741. */
  2742. on : function (evt, fn) {
  2743. var self = this;
  2744.  
  2745. if(evt === "data") {
  2746. this._worker.on(evt, function (chunk) {
  2747. fn.call(self, chunk.data, chunk.meta);
  2748. });
  2749. } else {
  2750. this._worker.on(evt, function () {
  2751. utils.delay(fn, arguments, self);
  2752. });
  2753. }
  2754. return this;
  2755. },
  2756. /**
  2757. * Resume the flow of chunks.
  2758. * @return {StreamHelper} the current helper.
  2759. */
  2760. resume : function () {
  2761. utils.delay(this._worker.resume, [], this._worker);
  2762. return this;
  2763. },
  2764. /**
  2765. * Pause the flow of chunks.
  2766. * @return {StreamHelper} the current helper.
  2767. */
  2768. pause : function () {
  2769. this._worker.pause();
  2770. return this;
  2771. },
  2772. /**
  2773. * Return a nodejs stream for this helper.
  2774. * @param {Function} updateCb the update callback.
  2775. * @return {NodejsStreamOutputAdapter} the nodejs stream.
  2776. */
  2777. toNodejsStream : function (updateCb) {
  2778. utils.checkSupport("nodestream");
  2779. if (this._outputType !== "nodebuffer") {
  2780. // an object stream containing blob/arraybuffer/uint8array/string
  2781. // is strange and I don't know if it would be useful.
  2782. // I you find this comment and have a good usecase, please open a
  2783. // bug report !
  2784. throw new Error(this._outputType + " is not supported by this method");
  2785. }
  2786.  
  2787. return new NodejsStreamOutputAdapter(this, {
  2788. objectMode : this._outputType !== "nodebuffer"
  2789. }, updateCb);
  2790. }
  2791. };
  2792.  
  2793.  
  2794. module.exports = StreamHelper;
  2795.  
  2796. },{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){
  2797. 'use strict';
  2798.  
  2799. exports.base64 = true;
  2800. exports.array = true;
  2801. exports.string = true;
  2802. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  2803. exports.nodebuffer = typeof Buffer !== "undefined";
  2804. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  2805. exports.uint8array = typeof Uint8Array !== "undefined";
  2806.  
  2807. if (typeof ArrayBuffer === "undefined") {
  2808. exports.blob = false;
  2809. }
  2810. else {
  2811. var buffer = new ArrayBuffer(0);
  2812. try {
  2813. exports.blob = new Blob([buffer], {
  2814. type: "application/zip"
  2815. }).size === 0;
  2816. }
  2817. catch (e) {
  2818. try {
  2819. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  2820. var builder = new Builder();
  2821. builder.append(buffer);
  2822. exports.blob = builder.getBlob('application/zip').size === 0;
  2823. }
  2824. catch (e) {
  2825. exports.blob = false;
  2826. }
  2827. }
  2828. }
  2829.  
  2830. try {
  2831. exports.nodestream = !!require('readable-stream').Readable;
  2832. } catch(e) {
  2833. exports.nodestream = false;
  2834. }
  2835.  
  2836. },{"readable-stream":16}],31:[function(require,module,exports){
  2837. 'use strict';
  2838.  
  2839. var utils = require('./utils');
  2840. var support = require('./support');
  2841. var nodejsUtils = require('./nodejsUtils');
  2842. var GenericWorker = require('./stream/GenericWorker');
  2843.  
  2844. /**
  2845. * The following functions come from pako, from pako/lib/utils/strings
  2846. * released under the MIT license, see pako https://github.com/nodeca/pako/
  2847. */
  2848.  
  2849. // Table with utf8 lengths (calculated by first byte of sequence)
  2850. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  2851. // because max possible codepoint is 0x10ffff
  2852. var _utf8len = new Array(256);
  2853. for (var i=0; i<256; i++) {
  2854. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  2855. }
  2856. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  2857.  
  2858. // convert string to array (typed, when possible)
  2859. var string2buf = function (str) {
  2860. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  2861.  
  2862. // count binary size
  2863. for (m_pos = 0; m_pos < str_len; m_pos++) {
  2864. c = str.charCodeAt(m_pos);
  2865. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2866. c2 = str.charCodeAt(m_pos+1);
  2867. if ((c2 & 0xfc00) === 0xdc00) {
  2868. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2869. m_pos++;
  2870. }
  2871. }
  2872. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  2873. }
  2874.  
  2875. // allocate buffer
  2876. if (support.uint8array) {
  2877. buf = new Uint8Array(buf_len);
  2878. } else {
  2879. buf = new Array(buf_len);
  2880. }
  2881.  
  2882. // convert
  2883. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  2884. c = str.charCodeAt(m_pos);
  2885. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2886. c2 = str.charCodeAt(m_pos+1);
  2887. if ((c2 & 0xfc00) === 0xdc00) {
  2888. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2889. m_pos++;
  2890. }
  2891. }
  2892. if (c < 0x80) {
  2893. /* one byte */
  2894. buf[i++] = c;
  2895. } else if (c < 0x800) {
  2896. /* two bytes */
  2897. buf[i++] = 0xC0 | (c >>> 6);
  2898. buf[i++] = 0x80 | (c & 0x3f);
  2899. } else if (c < 0x10000) {
  2900. /* three bytes */
  2901. buf[i++] = 0xE0 | (c >>> 12);
  2902. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2903. buf[i++] = 0x80 | (c & 0x3f);
  2904. } else {
  2905. /* four bytes */
  2906. buf[i++] = 0xf0 | (c >>> 18);
  2907. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  2908. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2909. buf[i++] = 0x80 | (c & 0x3f);
  2910. }
  2911. }
  2912.  
  2913. return buf;
  2914. };
  2915.  
  2916. // Calculate max possible position in utf8 buffer,
  2917. // that will not break sequence. If that's not possible
  2918. // - (very small limits) return max size as is.
  2919. //
  2920. // buf[] - utf8 bytes array
  2921. // max - length limit (mandatory);
  2922. var utf8border = function(buf, max) {
  2923. var pos;
  2924.  
  2925. max = max || buf.length;
  2926. if (max > buf.length) { max = buf.length; }
  2927.  
  2928. // go back from last position, until start of sequence found
  2929. pos = max-1;
  2930. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  2931.  
  2932. // Fuckup - very small and broken sequence,
  2933. // return max, because we should return something anyway.
  2934. if (pos < 0) { return max; }
  2935.  
  2936. // If we came to start of buffer - that means vuffer is too small,
  2937. // return max too.
  2938. if (pos === 0) { return max; }
  2939.  
  2940. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  2941. };
  2942.  
  2943. // convert array to string
  2944. var buf2string = function (buf) {
  2945. var str, i, out, c, c_len;
  2946. var len = buf.length;
  2947.  
  2948. // Reserve max possible length (2 words per char)
  2949. // NB: by unknown reasons, Array is significantly faster for
  2950. // String.fromCharCode.apply than Uint16Array.
  2951. var utf16buf = new Array(len*2);
  2952.  
  2953. for (out=0, i=0; i<len;) {
  2954. c = buf[i++];
  2955. // quick process ascii
  2956. if (c < 0x80) { utf16buf[out++] = c; continue; }
  2957.  
  2958. c_len = _utf8len[c];
  2959. // skip 5 & 6 byte codes
  2960. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  2961.  
  2962. // apply mask on first byte
  2963. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  2964. // join the rest
  2965. while (c_len > 1 && i < len) {
  2966. c = (c << 6) | (buf[i++] & 0x3f);
  2967. c_len--;
  2968. }
  2969.  
  2970. // terminated by end of string?
  2971. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  2972.  
  2973. if (c < 0x10000) {
  2974. utf16buf[out++] = c;
  2975. } else {
  2976. c -= 0x10000;
  2977. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  2978. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  2979. }
  2980. }
  2981.  
  2982. // shrinkBuf(utf16buf, out)
  2983. if (utf16buf.length !== out) {
  2984. if(utf16buf.subarray) {
  2985. utf16buf = utf16buf.subarray(0, out);
  2986. } else {
  2987. utf16buf.length = out;
  2988. }
  2989. }
  2990.  
  2991. // return String.fromCharCode.apply(null, utf16buf);
  2992. return utils.applyFromCharCode(utf16buf);
  2993. };
  2994.  
  2995.  
  2996. // That's all for the pako functions.
  2997.  
  2998.  
  2999. /**
  3000. * Transform a javascript string into an array (typed if possible) of bytes,
  3001. * UTF-8 encoded.
  3002. * @param {String} str the string to encode
  3003. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  3004. */
  3005. exports.utf8encode = function utf8encode(str) {
  3006. if (support.nodebuffer) {
  3007. return nodejsUtils.newBufferFrom(str, "utf-8");
  3008. }
  3009.  
  3010. return string2buf(str);
  3011. };
  3012.  
  3013.  
  3014. /**
  3015. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  3016. * string into a javascript string.
  3017. * @param {Array|Uint8Array|Buffer} buf the data de decode
  3018. * @return {String} the decoded string.
  3019. */
  3020. exports.utf8decode = function utf8decode(buf) {
  3021. if (support.nodebuffer) {
  3022. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  3023. }
  3024.  
  3025. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  3026.  
  3027. return buf2string(buf);
  3028. };
  3029.  
  3030. /**
  3031. * A worker to decode utf8 encoded binary chunks into string chunks.
  3032. * @constructor
  3033. */
  3034. function Utf8DecodeWorker() {
  3035. GenericWorker.call(this, "utf-8 decode");
  3036. // the last bytes if a chunk didn't end with a complete codepoint.
  3037. this.leftOver = null;
  3038. }
  3039. utils.inherits(Utf8DecodeWorker, GenericWorker);
  3040.  
  3041. /**
  3042. * @see GenericWorker.processChunk
  3043. */
  3044. Utf8DecodeWorker.prototype.processChunk = function (chunk) {
  3045.  
  3046. var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
  3047.  
  3048. // 1st step, re-use what's left of the previous chunk
  3049. if (this.leftOver && this.leftOver.length) {
  3050. if(support.uint8array) {
  3051. var previousData = data;
  3052. data = new Uint8Array(previousData.length + this.leftOver.length);
  3053. data.set(this.leftOver, 0);
  3054. data.set(previousData, this.leftOver.length);
  3055. } else {
  3056. data = this.leftOver.concat(data);
  3057. }
  3058. this.leftOver = null;
  3059. }
  3060.  
  3061. var nextBoundary = utf8border(data);
  3062. var usableData = data;
  3063. if (nextBoundary !== data.length) {
  3064. if (support.uint8array) {
  3065. usableData = data.subarray(0, nextBoundary);
  3066. this.leftOver = data.subarray(nextBoundary, data.length);
  3067. } else {
  3068. usableData = data.slice(0, nextBoundary);
  3069. this.leftOver = data.slice(nextBoundary, data.length);
  3070. }
  3071. }
  3072.  
  3073. this.push({
  3074. data : exports.utf8decode(usableData),
  3075. meta : chunk.meta
  3076. });
  3077. };
  3078.  
  3079. /**
  3080. * @see GenericWorker.flush
  3081. */
  3082. Utf8DecodeWorker.prototype.flush = function () {
  3083. if(this.leftOver && this.leftOver.length) {
  3084. this.push({
  3085. data : exports.utf8decode(this.leftOver),
  3086. meta : {}
  3087. });
  3088. this.leftOver = null;
  3089. }
  3090. };
  3091. exports.Utf8DecodeWorker = Utf8DecodeWorker;
  3092.  
  3093. /**
  3094. * A worker to endcode string chunks into utf8 encoded binary chunks.
  3095. * @constructor
  3096. */
  3097. function Utf8EncodeWorker() {
  3098. GenericWorker.call(this, "utf-8 encode");
  3099. }
  3100. utils.inherits(Utf8EncodeWorker, GenericWorker);
  3101.  
  3102. /**
  3103. * @see GenericWorker.processChunk
  3104. */
  3105. Utf8EncodeWorker.prototype.processChunk = function (chunk) {
  3106. this.push({
  3107. data : exports.utf8encode(chunk.data),
  3108. meta : chunk.meta
  3109. });
  3110. };
  3111. exports.Utf8EncodeWorker = Utf8EncodeWorker;
  3112.  
  3113. },{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){
  3114. 'use strict';
  3115.  
  3116. var support = require('./support');
  3117. var base64 = require('./base64');
  3118. var nodejsUtils = require('./nodejsUtils');
  3119. var setImmediate = require('core-js/library/fn/set-immediate');
  3120. var external = require("./external");
  3121.  
  3122.  
  3123. /**
  3124. * Convert a string that pass as a "binary string": it should represent a byte
  3125. * array but may have > 255 char codes. Be sure to take only the first byte
  3126. * and returns the byte array.
  3127. * @param {String} str the string to transform.
  3128. * @return {Array|Uint8Array} the string in a binary format.
  3129. */
  3130. function string2binary(str) {
  3131. var result = null;
  3132. if (support.uint8array) {
  3133. result = new Uint8Array(str.length);
  3134. } else {
  3135. result = new Array(str.length);
  3136. }
  3137. return stringToArrayLike(str, result);
  3138. }
  3139.  
  3140. /**
  3141. * Create a new blob with the given content and the given type.
  3142. * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use
  3143. * an Uint8Array because the stock browser of android 4 won't accept it (it
  3144. * will be silently converted to a string, "[object Uint8Array]").
  3145. *
  3146. * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:
  3147. * when a large amount of Array is used to create the Blob, the amount of
  3148. * memory consumed is nearly 100 times the original data amount.
  3149. *
  3150. * @param {String} type the mime type of the blob.
  3151. * @return {Blob} the created blob.
  3152. */
  3153. exports.newBlob = function(part, type) {
  3154. exports.checkSupport("blob");
  3155.  
  3156. try {
  3157. // Blob constructor
  3158. return new Blob([part], {
  3159. type: type
  3160. });
  3161. }
  3162. catch (e) {
  3163.  
  3164. try {
  3165. // deprecated, browser only, old way
  3166. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  3167. var builder = new Builder();
  3168. builder.append(part);
  3169. return builder.getBlob(type);
  3170. }
  3171. catch (e) {
  3172.  
  3173. // well, fuck ?!
  3174. throw new Error("Bug : can't construct the Blob.");
  3175. }
  3176. }
  3177.  
  3178.  
  3179. };
  3180. /**
  3181. * The identity function.
  3182. * @param {Object} input the input.
  3183. * @return {Object} the same input.
  3184. */
  3185. function identity(input) {
  3186. return input;
  3187. }
  3188.  
  3189. /**
  3190. * Fill in an array with a string.
  3191. * @param {String} str the string to use.
  3192. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  3193. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  3194. */
  3195. function stringToArrayLike(str, array) {
  3196. for (var i = 0; i < str.length; ++i) {
  3197. array[i] = str.charCodeAt(i) & 0xFF;
  3198. }
  3199. return array;
  3200. }
  3201.  
  3202. /**
  3203. * An helper for the function arrayLikeToString.
  3204. * This contains static informations and functions that
  3205. * can be optimized by the browser JIT compiler.
  3206. */
  3207. var arrayToStringHelper = {
  3208. /**
  3209. * Transform an array of int into a string, chunk by chunk.
  3210. * See the performances notes on arrayLikeToString.
  3211. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3212. * @param {String} type the type of the array.
  3213. * @param {Integer} chunk the chunk size.
  3214. * @return {String} the resulting string.
  3215. * @throws Error if the chunk is too big for the stack.
  3216. */
  3217. stringifyByChunk: function(array, type, chunk) {
  3218. var result = [], k = 0, len = array.length;
  3219. // shortcut
  3220. if (len <= chunk) {
  3221. return String.fromCharCode.apply(null, array);
  3222. }
  3223. while (k < len) {
  3224. if (type === "array" || type === "nodebuffer") {
  3225. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  3226. }
  3227. else {
  3228. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  3229. }
  3230. k += chunk;
  3231. }
  3232. return result.join("");
  3233. },
  3234. /**
  3235. * Call String.fromCharCode on every item in the array.
  3236. * This is the naive implementation, which generate A LOT of intermediate string.
  3237. * This should be used when everything else fail.
  3238. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3239. * @return {String} the result.
  3240. */
  3241. stringifyByChar: function(array){
  3242. var resultStr = "";
  3243. for(var i = 0; i < array.length; i++) {
  3244. resultStr += String.fromCharCode(array[i]);
  3245. }
  3246. return resultStr;
  3247. },
  3248. applyCanBeUsed : {
  3249. /**
  3250. * true if the browser accepts to use String.fromCharCode on Uint8Array
  3251. */
  3252. uint8array : (function () {
  3253. try {
  3254. return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
  3255. } catch (e) {
  3256. return false;
  3257. }
  3258. })(),
  3259. /**
  3260. * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
  3261. */
  3262. nodebuffer : (function () {
  3263. try {
  3264. return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;
  3265. } catch (e) {
  3266. return false;
  3267. }
  3268. })()
  3269. }
  3270. };
  3271.  
  3272. /**
  3273. * Transform an array-like object to a string.
  3274. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3275. * @return {String} the result.
  3276. */
  3277. function arrayLikeToString(array) {
  3278. // Performances notes :
  3279. // --------------------
  3280. // String.fromCharCode.apply(null, array) is the fastest, see
  3281. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  3282. // but the stack is limited (and we can get huge arrays !).
  3283. //
  3284. // result += String.fromCharCode(array[i]); generate too many strings !
  3285. //
  3286. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  3287. // TODO : we now have workers that split the work. Do we still need that ?
  3288. var chunk = 65536,
  3289. type = exports.getTypeOf(array),
  3290. canUseApply = true;
  3291. if (type === "uint8array") {
  3292. canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
  3293. } else if (type === "nodebuffer") {
  3294. canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
  3295. }
  3296.  
  3297. if (canUseApply) {
  3298. while (chunk > 1) {
  3299. try {
  3300. return arrayToStringHelper.stringifyByChunk(array, type, chunk);
  3301. } catch (e) {
  3302. chunk = Math.floor(chunk / 2);
  3303. }
  3304. }
  3305. }
  3306.  
  3307. // no apply or chunk error : slow and painful algorithm
  3308. // default browser on android 4.*
  3309. return arrayToStringHelper.stringifyByChar(array);
  3310. }
  3311.  
  3312. exports.applyFromCharCode = arrayLikeToString;
  3313.  
  3314.  
  3315. /**
  3316. * Copy the data from an array-like to an other array-like.
  3317. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  3318. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  3319. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  3320. */
  3321. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  3322. for (var i = 0; i < arrayFrom.length; i++) {
  3323. arrayTo[i] = arrayFrom[i];
  3324. }
  3325. return arrayTo;
  3326. }
  3327.  
  3328. // a matrix containing functions to transform everything into everything.
  3329. var transform = {};
  3330.  
  3331. // string to ?
  3332. transform["string"] = {
  3333. "string": identity,
  3334. "array": function(input) {
  3335. return stringToArrayLike(input, new Array(input.length));
  3336. },
  3337. "arraybuffer": function(input) {
  3338. return transform["string"]["uint8array"](input).buffer;
  3339. },
  3340. "uint8array": function(input) {
  3341. return stringToArrayLike(input, new Uint8Array(input.length));
  3342. },
  3343. "nodebuffer": function(input) {
  3344. return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));
  3345. }
  3346. };
  3347.  
  3348. // array to ?
  3349. transform["array"] = {
  3350. "string": arrayLikeToString,
  3351. "array": identity,
  3352. "arraybuffer": function(input) {
  3353. return (new Uint8Array(input)).buffer;
  3354. },
  3355. "uint8array": function(input) {
  3356. return new Uint8Array(input);
  3357. },
  3358. "nodebuffer": function(input) {
  3359. return nodejsUtils.newBufferFrom(input);
  3360. }
  3361. };
  3362.  
  3363. // arraybuffer to ?
  3364. transform["arraybuffer"] = {
  3365. "string": function(input) {
  3366. return arrayLikeToString(new Uint8Array(input));
  3367. },
  3368. "array": function(input) {
  3369. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  3370. },
  3371. "arraybuffer": identity,
  3372. "uint8array": function(input) {
  3373. return new Uint8Array(input);
  3374. },
  3375. "nodebuffer": function(input) {
  3376. return nodejsUtils.newBufferFrom(new Uint8Array(input));
  3377. }
  3378. };
  3379.  
  3380. // uint8array to ?
  3381. transform["uint8array"] = {
  3382. "string": arrayLikeToString,
  3383. "array": function(input) {
  3384. return arrayLikeToArrayLike(input, new Array(input.length));
  3385. },
  3386. "arraybuffer": function(input) {
  3387. return input.buffer;
  3388. },
  3389. "uint8array": identity,
  3390. "nodebuffer": function(input) {
  3391. return nodejsUtils.newBufferFrom(input);
  3392. }
  3393. };
  3394.  
  3395. // nodebuffer to ?
  3396. transform["nodebuffer"] = {
  3397. "string": arrayLikeToString,
  3398. "array": function(input) {
  3399. return arrayLikeToArrayLike(input, new Array(input.length));
  3400. },
  3401. "arraybuffer": function(input) {
  3402. return transform["nodebuffer"]["uint8array"](input).buffer;
  3403. },
  3404. "uint8array": function(input) {
  3405. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  3406. },
  3407. "nodebuffer": identity
  3408. };
  3409.  
  3410. /**
  3411. * Transform an input into any type.
  3412. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  3413. * If no output type is specified, the unmodified input will be returned.
  3414. * @param {String} outputType the output type.
  3415. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  3416. * @throws {Error} an Error if the browser doesn't support the requested output type.
  3417. */
  3418. exports.transformTo = function(outputType, input) {
  3419. if (!input) {
  3420. // undefined, null, etc
  3421. // an empty string won't harm.
  3422. input = "";
  3423. }
  3424. if (!outputType) {
  3425. return input;
  3426. }
  3427. exports.checkSupport(outputType);
  3428. var inputType = exports.getTypeOf(input);
  3429. var result = transform[inputType][outputType](input);
  3430. return result;
  3431. };
  3432.  
  3433. /**
  3434. * Return the type of the input.
  3435. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  3436. * @param {Object} input the input to identify.
  3437. * @return {String} the (lowercase) type of the input.
  3438. */
  3439. exports.getTypeOf = function(input) {
  3440. if (typeof input === "string") {
  3441. return "string";
  3442. }
  3443. if (Object.prototype.toString.call(input) === "[object Array]") {
  3444. return "array";
  3445. }
  3446. if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
  3447. return "nodebuffer";
  3448. }
  3449. if (support.uint8array && input instanceof Uint8Array) {
  3450. return "uint8array";
  3451. }
  3452. if (support.arraybuffer && input instanceof ArrayBuffer) {
  3453. return "arraybuffer";
  3454. }
  3455. };
  3456.  
  3457. /**
  3458. * Throw an exception if the type is not supported.
  3459. * @param {String} type the type to check.
  3460. * @throws {Error} an Error if the browser doesn't support the requested type.
  3461. */
  3462. exports.checkSupport = function(type) {
  3463. var supported = support[type.toLowerCase()];
  3464. if (!supported) {
  3465. throw new Error(type + " is not supported by this platform");
  3466. }
  3467. };
  3468.  
  3469. exports.MAX_VALUE_16BITS = 65535;
  3470. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  3471.  
  3472. /**
  3473. * Prettify a string read as binary.
  3474. * @param {string} str the string to prettify.
  3475. * @return {string} a pretty string.
  3476. */
  3477. exports.pretty = function(str) {
  3478. var res = '',
  3479. code, i;
  3480. for (i = 0; i < (str || "").length; i++) {
  3481. code = str.charCodeAt(i);
  3482. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  3483. }
  3484. return res;
  3485. };
  3486.  
  3487. /**
  3488. * Defer the call of a function.
  3489. * @param {Function} callback the function to call asynchronously.
  3490. * @param {Array} args the arguments to give to the callback.
  3491. */
  3492. exports.delay = function(callback, args, self) {
  3493. setImmediate(function () {
  3494. callback.apply(self || null, args || []);
  3495. });
  3496. };
  3497.  
  3498. /**
  3499. * Extends a prototype with an other, without calling a constructor with
  3500. * side effects. Inspired by nodejs' `utils.inherits`
  3501. * @param {Function} ctor the constructor to augment
  3502. * @param {Function} superCtor the parent constructor to use
  3503. */
  3504. exports.inherits = function (ctor, superCtor) {
  3505. var Obj = function() {};
  3506. Obj.prototype = superCtor.prototype;
  3507. ctor.prototype = new Obj();
  3508. };
  3509.  
  3510. /**
  3511. * Merge the objects passed as parameters into a new one.
  3512. * @private
  3513. * @param {...Object} var_args All objects to merge.
  3514. * @return {Object} a new object with the data of the others.
  3515. */
  3516. exports.extend = function() {
  3517. var result = {}, i, attr;
  3518. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  3519. for (attr in arguments[i]) {
  3520. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  3521. result[attr] = arguments[i][attr];
  3522. }
  3523. }
  3524. }
  3525. return result;
  3526. };
  3527.  
  3528. /**
  3529. * Transform arbitrary content into a Promise.
  3530. * @param {String} name a name for the content being processed.
  3531. * @param {Object} inputData the content to process.
  3532. * @param {Boolean} isBinary true if the content is not an unicode string
  3533. * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
  3534. * @param {Boolean} isBase64 true if the string content is encoded with base64.
  3535. * @return {Promise} a promise in a format usable by JSZip.
  3536. */
  3537. exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
  3538.  
  3539. // if inputData is already a promise, this flatten it.
  3540. var promise = external.Promise.resolve(inputData).then(function(data) {
  3541. var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);
  3542.  
  3543. if (isBlob && typeof FileReader !== "undefined") {
  3544. return new external.Promise(function (resolve, reject) {
  3545. var reader = new FileReader();
  3546.  
  3547. reader.onload = function(e) {
  3548. resolve(e.target.result);
  3549. };
  3550. reader.onerror = function(e) {
  3551. reject(e.target.error);
  3552. };
  3553. reader.readAsArrayBuffer(data);
  3554. });
  3555. } else {
  3556. return data;
  3557. }
  3558. });
  3559.  
  3560. return promise.then(function(data) {
  3561. var dataType = exports.getTypeOf(data);
  3562.  
  3563. if (!dataType) {
  3564. return external.Promise.reject(
  3565. new Error("Can't read the data of '" + name + "'. Is it " +
  3566. "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")
  3567. );
  3568. }
  3569. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  3570. if (dataType === "arraybuffer") {
  3571. data = exports.transformTo("uint8array", data);
  3572. } else if (dataType === "string") {
  3573. if (isBase64) {
  3574. data = base64.decode(data);
  3575. }
  3576. else if (isBinary) {
  3577. // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
  3578. if (isOptimizedBinaryString !== true) {
  3579. // this is a string, not in a base64 format.
  3580. // Be sure that this is a correct "binary string"
  3581. data = string2binary(data);
  3582. }
  3583. }
  3584. }
  3585. return data;
  3586. });
  3587. };
  3588.  
  3589. },{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"core-js/library/fn/set-immediate":36}],33:[function(require,module,exports){
  3590. 'use strict';
  3591. var readerFor = require('./reader/readerFor');
  3592. var utils = require('./utils');
  3593. var sig = require('./signature');
  3594. var ZipEntry = require('./zipEntry');
  3595. var utf8 = require('./utf8');
  3596. var support = require('./support');
  3597. // class ZipEntries {{{
  3598. /**
  3599. * All the entries in the zip file.
  3600. * @constructor
  3601. * @param {Object} loadOptions Options for loading the stream.
  3602. */
  3603. function ZipEntries(loadOptions) {
  3604. this.files = [];
  3605. this.loadOptions = loadOptions;
  3606. }
  3607. ZipEntries.prototype = {
  3608. /**
  3609. * Check that the reader is on the specified signature.
  3610. * @param {string} expectedSignature the expected signature.
  3611. * @throws {Error} if it is an other signature.
  3612. */
  3613. checkSignature: function(expectedSignature) {
  3614. if (!this.reader.readAndCheckSignature(expectedSignature)) {
  3615. this.reader.index -= 4;
  3616. var signature = this.reader.readString(4);
  3617. throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  3618. }
  3619. },
  3620. /**
  3621. * Check if the given signature is at the given index.
  3622. * @param {number} askedIndex the index to check.
  3623. * @param {string} expectedSignature the signature to expect.
  3624. * @return {boolean} true if the signature is here, false otherwise.
  3625. */
  3626. isSignature: function(askedIndex, expectedSignature) {
  3627. var currentIndex = this.reader.index;
  3628. this.reader.setIndex(askedIndex);
  3629. var signature = this.reader.readString(4);
  3630. var result = signature === expectedSignature;
  3631. this.reader.setIndex(currentIndex);
  3632. return result;
  3633. },
  3634. /**
  3635. * Read the end of the central directory.
  3636. */
  3637. readBlockEndOfCentral: function() {
  3638. this.diskNumber = this.reader.readInt(2);
  3639. this.diskWithCentralDirStart = this.reader.readInt(2);
  3640. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  3641. this.centralDirRecords = this.reader.readInt(2);
  3642. this.centralDirSize = this.reader.readInt(4);
  3643. this.centralDirOffset = this.reader.readInt(4);
  3644.  
  3645. this.zipCommentLength = this.reader.readInt(2);
  3646. // warning : the encoding depends of the system locale
  3647. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  3648. // On a windows machine, this field is encoded with the localized windows code page.
  3649. var zipComment = this.reader.readData(this.zipCommentLength);
  3650. var decodeParamType = support.uint8array ? "uint8array" : "array";
  3651. // To get consistent behavior with the generation part, we will assume that
  3652. // this is utf8 encoded unless specified otherwise.
  3653. var decodeContent = utils.transformTo(decodeParamType, zipComment);
  3654. this.zipComment = this.loadOptions.decodeFileName(decodeContent);
  3655. },
  3656. /**
  3657. * Read the end of the Zip 64 central directory.
  3658. * Not merged with the method readEndOfCentral :
  3659. * The end of central can coexist with its Zip64 brother,
  3660. * I don't want to read the wrong number of bytes !
  3661. */
  3662. readBlockZip64EndOfCentral: function() {
  3663. this.zip64EndOfCentralSize = this.reader.readInt(8);
  3664. this.reader.skip(4);
  3665. // this.versionMadeBy = this.reader.readString(2);
  3666. // this.versionNeeded = this.reader.readInt(2);
  3667. this.diskNumber = this.reader.readInt(4);
  3668. this.diskWithCentralDirStart = this.reader.readInt(4);
  3669. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  3670. this.centralDirRecords = this.reader.readInt(8);
  3671. this.centralDirSize = this.reader.readInt(8);
  3672. this.centralDirOffset = this.reader.readInt(8);
  3673.  
  3674. this.zip64ExtensibleData = {};
  3675. var extraDataSize = this.zip64EndOfCentralSize - 44,
  3676. index = 0,
  3677. extraFieldId,
  3678. extraFieldLength,
  3679. extraFieldValue;
  3680. while (index < extraDataSize) {
  3681. extraFieldId = this.reader.readInt(2);
  3682. extraFieldLength = this.reader.readInt(4);
  3683. extraFieldValue = this.reader.readData(extraFieldLength);
  3684. this.zip64ExtensibleData[extraFieldId] = {
  3685. id: extraFieldId,
  3686. length: extraFieldLength,
  3687. value: extraFieldValue
  3688. };
  3689. }
  3690. },
  3691. /**
  3692. * Read the end of the Zip 64 central directory locator.
  3693. */
  3694. readBlockZip64EndOfCentralLocator: function() {
  3695. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  3696. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  3697. this.disksCount = this.reader.readInt(4);
  3698. if (this.disksCount > 1) {
  3699. throw new Error("Multi-volumes zip are not supported");
  3700. }
  3701. },
  3702. /**
  3703. * Read the local files, based on the offset read in the central part.
  3704. */
  3705. readLocalFiles: function() {
  3706. var i, file;
  3707. for (i = 0; i < this.files.length; i++) {
  3708. file = this.files[i];
  3709. this.reader.setIndex(file.localHeaderOffset);
  3710. this.checkSignature(sig.LOCAL_FILE_HEADER);
  3711. file.readLocalPart(this.reader);
  3712. file.handleUTF8();
  3713. file.processAttributes();
  3714. }
  3715. },
  3716. /**
  3717. * Read the central directory.
  3718. */
  3719. readCentralDir: function() {
  3720. var file;
  3721.  
  3722. this.reader.setIndex(this.centralDirOffset);
  3723. while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
  3724. file = new ZipEntry({
  3725. zip64: this.zip64
  3726. }, this.loadOptions);
  3727. file.readCentralPart(this.reader);
  3728. this.files.push(file);
  3729. }
  3730.  
  3731. if (this.centralDirRecords !== this.files.length) {
  3732. if (this.centralDirRecords !== 0 && this.files.length === 0) {
  3733. // We expected some records but couldn't find ANY.
  3734. // This is really suspicious, as if something went wrong.
  3735. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  3736. } else {
  3737. // We found some records but not all.
  3738. // Something is wrong but we got something for the user: no error here.
  3739. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
  3740. }
  3741. }
  3742. },
  3743. /**
  3744. * Read the end of central directory.
  3745. */
  3746. readEndOfCentral: function() {
  3747. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  3748. if (offset < 0) {
  3749. // Check if the content is a truncated zip or complete garbage.
  3750. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  3751. // extractible zip for example) but it can give a good hint.
  3752. // If an ajax request was used without responseType, we will also
  3753. // get unreadable data.
  3754. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  3755.  
  3756. if (isGarbage) {
  3757. throw new Error("Can't find end of central directory : is this a zip file ? " +
  3758. "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");
  3759. } else {
  3760. throw new Error("Corrupted zip: can't find end of central directory");
  3761. }
  3762.  
  3763. }
  3764. this.reader.setIndex(offset);
  3765. var endOfCentralDirOffset = offset;
  3766. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  3767. this.readBlockEndOfCentral();
  3768.  
  3769.  
  3770. /* extract from the zip spec :
  3771. 4) If one of the fields in the end of central directory
  3772. record is too small to hold required data, the field
  3773. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  3774. ZIP64 format record should be created.
  3775. 5) The end of central directory record and the
  3776. Zip64 end of central directory locator record must
  3777. reside on the same disk when splitting or spanning
  3778. an archive.
  3779. */
  3780. 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) {
  3781. this.zip64 = true;
  3782.  
  3783. /*
  3784. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  3785. the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents
  3786. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  3787. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  3788. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  3789. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  3790. */
  3791.  
  3792. // should look for a zip64 EOCD locator
  3793. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3794. if (offset < 0) {
  3795. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
  3796. }
  3797. this.reader.setIndex(offset);
  3798. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3799. this.readBlockZip64EndOfCentralLocator();
  3800.  
  3801. // now the zip64 EOCD record
  3802. if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
  3803. // console.warn("ZIP64 end of central directory not where expected.");
  3804. this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3805. if (this.relativeOffsetEndOfZip64CentralDir < 0) {
  3806. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
  3807. }
  3808. }
  3809. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  3810. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3811. this.readBlockZip64EndOfCentral();
  3812. }
  3813.  
  3814. var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
  3815. if (this.zip64) {
  3816. expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
  3817. expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
  3818. }
  3819.  
  3820. var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  3821.  
  3822. if (extraBytes > 0) {
  3823. // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
  3824. if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
  3825. // The offsets seem wrong, but we have something at the specified offset.
  3826. // So… we keep it.
  3827. } else {
  3828. // the offset is wrong, update the "zero" of the reader
  3829. // this happens if data has been prepended (crx files for example)
  3830. this.reader.zero = extraBytes;
  3831. }
  3832. } else if (extraBytes < 0) {
  3833. throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
  3834. }
  3835. },
  3836. prepareReader: function(data) {
  3837. this.reader = readerFor(data);
  3838. },
  3839. /**
  3840. * Read a zip file and create ZipEntries.
  3841. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  3842. */
  3843. load: function(data) {
  3844. this.prepareReader(data);
  3845. this.readEndOfCentral();
  3846. this.readCentralDir();
  3847. this.readLocalFiles();
  3848. }
  3849. };
  3850. // }}} end of ZipEntries
  3851. module.exports = ZipEntries;
  3852.  
  3853. },{"./reader/readerFor":22,"./signature":23,"./support":30,"./utf8":31,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){
  3854. 'use strict';
  3855. var readerFor = require('./reader/readerFor');
  3856. var utils = require('./utils');
  3857. var CompressedObject = require('./compressedObject');
  3858. var crc32fn = require('./crc32');
  3859. var utf8 = require('./utf8');
  3860. var compressions = require('./compressions');
  3861. var support = require('./support');
  3862.  
  3863. var MADE_BY_DOS = 0x00;
  3864. var MADE_BY_UNIX = 0x03;
  3865.  
  3866. /**
  3867. * Find a compression registered in JSZip.
  3868. * @param {string} compressionMethod the method magic to find.
  3869. * @return {Object|null} the JSZip compression object, null if none found.
  3870. */
  3871. var findCompression = function(compressionMethod) {
  3872. for (var method in compressions) {
  3873. if (!compressions.hasOwnProperty(method)) {
  3874. continue;
  3875. }
  3876. if (compressions[method].magic === compressionMethod) {
  3877. return compressions[method];
  3878. }
  3879. }
  3880. return null;
  3881. };
  3882.  
  3883. // class ZipEntry {{{
  3884. /**
  3885. * An entry in the zip file.
  3886. * @constructor
  3887. * @param {Object} options Options of the current file.
  3888. * @param {Object} loadOptions Options for loading the stream.
  3889. */
  3890. function ZipEntry(options, loadOptions) {
  3891. this.options = options;
  3892. this.loadOptions = loadOptions;
  3893. }
  3894. ZipEntry.prototype = {
  3895. /**
  3896. * say if the file is encrypted.
  3897. * @return {boolean} true if the file is encrypted, false otherwise.
  3898. */
  3899. isEncrypted: function() {
  3900. // bit 1 is set
  3901. return (this.bitFlag & 0x0001) === 0x0001;
  3902. },
  3903. /**
  3904. * say if the file has utf-8 filename/comment.
  3905. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  3906. */
  3907. useUTF8: function() {
  3908. // bit 11 is set
  3909. return (this.bitFlag & 0x0800) === 0x0800;
  3910. },
  3911. /**
  3912. * Read the local part of a zip file and add the info in this object.
  3913. * @param {DataReader} reader the reader to use.
  3914. */
  3915. readLocalPart: function(reader) {
  3916. var compression, localExtraFieldsLength;
  3917.  
  3918. // we already know everything from the central dir !
  3919. // If the central dir data are false, we are doomed.
  3920. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  3921. // The less data we get here, the more reliable this should be.
  3922. // Let's skip the whole header and dash to the data !
  3923. reader.skip(22);
  3924. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  3925. // Strangely, the filename here is OK.
  3926. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  3927. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  3928. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  3929. // the internet.
  3930. //
  3931. // I think I see the logic here : the central directory is used to display
  3932. // content and the local directory is used to extract the files. Mixing / and \
  3933. // may be used to display \ to windows users and use / when extracting the files.
  3934. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  3935. this.fileNameLength = reader.readInt(2);
  3936. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  3937. // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
  3938. this.fileName = reader.readData(this.fileNameLength);
  3939. reader.skip(localExtraFieldsLength);
  3940.  
  3941. if (this.compressedSize === -1 || this.uncompressedSize === -1) {
  3942. throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
  3943. }
  3944.  
  3945. compression = findCompression(this.compressionMethod);
  3946. if (compression === null) { // no compression found
  3947. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
  3948. }
  3949. this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
  3950. },
  3951.  
  3952. /**
  3953. * Read the central part of a zip file and add the info in this object.
  3954. * @param {DataReader} reader the reader to use.
  3955. */
  3956. readCentralPart: function(reader) {
  3957. this.versionMadeBy = reader.readInt(2);
  3958. reader.skip(2);
  3959. // this.versionNeeded = reader.readInt(2);
  3960. this.bitFlag = reader.readInt(2);
  3961. this.compressionMethod = reader.readString(2);
  3962. this.date = reader.readDate();
  3963. this.crc32 = reader.readInt(4);
  3964. this.compressedSize = reader.readInt(4);
  3965. this.uncompressedSize = reader.readInt(4);
  3966. var fileNameLength = reader.readInt(2);
  3967. this.extraFieldsLength = reader.readInt(2);
  3968. this.fileCommentLength = reader.readInt(2);
  3969. this.diskNumberStart = reader.readInt(2);
  3970. this.internalFileAttributes = reader.readInt(2);
  3971. this.externalFileAttributes = reader.readInt(4);
  3972. this.localHeaderOffset = reader.readInt(4);
  3973.  
  3974. if (this.isEncrypted()) {
  3975. throw new Error("Encrypted zip are not supported");
  3976. }
  3977.  
  3978. // will be read in the local part, see the comments there
  3979. reader.skip(fileNameLength);
  3980. this.readExtraFields(reader);
  3981. this.parseZIP64ExtraField(reader);
  3982. this.fileComment = reader.readData(this.fileCommentLength);
  3983. },
  3984.  
  3985. /**
  3986. * Parse the external file attributes and get the unix/dos permissions.
  3987. */
  3988. processAttributes: function () {
  3989. this.unixPermissions = null;
  3990. this.dosPermissions = null;
  3991. var madeBy = this.versionMadeBy >> 8;
  3992.  
  3993. // Check if we have the DOS directory flag set.
  3994. // We look for it in the DOS and UNIX permissions
  3995. // but some unknown platform could set it as a compatibility flag.
  3996. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  3997.  
  3998. if(madeBy === MADE_BY_DOS) {
  3999. // first 6 bits (0 to 5)
  4000. this.dosPermissions = this.externalFileAttributes & 0x3F;
  4001. }
  4002.  
  4003. if(madeBy === MADE_BY_UNIX) {
  4004. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  4005. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  4006. }
  4007.  
  4008. // fail safe : if the name ends with a / it probably means a folder
  4009. if (!this.dir && this.fileNameStr.slice(-1) === '/') {
  4010. this.dir = true;
  4011. }
  4012. },
  4013.  
  4014. /**
  4015. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  4016. * @param {DataReader} reader the reader to use.
  4017. */
  4018. parseZIP64ExtraField: function(reader) {
  4019.  
  4020. if (!this.extraFields[0x0001]) {
  4021. return;
  4022. }
  4023.  
  4024. // should be something, preparing the extra reader
  4025. var extraReader = readerFor(this.extraFields[0x0001].value);
  4026.  
  4027. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  4028. // won't let us have more.
  4029. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  4030. this.uncompressedSize = extraReader.readInt(8);
  4031. }
  4032. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  4033. this.compressedSize = extraReader.readInt(8);
  4034. }
  4035. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  4036. this.localHeaderOffset = extraReader.readInt(8);
  4037. }
  4038. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  4039. this.diskNumberStart = extraReader.readInt(4);
  4040. }
  4041. },
  4042. /**
  4043. * Read the central part of a zip file and add the info in this object.
  4044. * @param {DataReader} reader the reader to use.
  4045. */
  4046. readExtraFields: function(reader) {
  4047. var end = reader.index + this.extraFieldsLength,
  4048. extraFieldId,
  4049. extraFieldLength,
  4050. extraFieldValue;
  4051.  
  4052. if (!this.extraFields) {
  4053. this.extraFields = {};
  4054. }
  4055.  
  4056. while (reader.index < end) {
  4057. extraFieldId = reader.readInt(2);
  4058. extraFieldLength = reader.readInt(2);
  4059. extraFieldValue = reader.readData(extraFieldLength);
  4060.  
  4061. this.extraFields[extraFieldId] = {
  4062. id: extraFieldId,
  4063. length: extraFieldLength,
  4064. value: extraFieldValue
  4065. };
  4066. }
  4067. },
  4068. /**
  4069. * Apply an UTF8 transformation if needed.
  4070. */
  4071. handleUTF8: function() {
  4072. var decodeParamType = support.uint8array ? "uint8array" : "array";
  4073. if (this.useUTF8()) {
  4074. this.fileNameStr = utf8.utf8decode(this.fileName);
  4075. this.fileCommentStr = utf8.utf8decode(this.fileComment);
  4076. } else {
  4077. var upath = this.findExtraFieldUnicodePath();
  4078. if (upath !== null) {
  4079. this.fileNameStr = upath;
  4080. } else {
  4081. // ASCII text or unsupported code page
  4082. var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);
  4083. this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
  4084. }
  4085.  
  4086. var ucomment = this.findExtraFieldUnicodeComment();
  4087. if (ucomment !== null) {
  4088. this.fileCommentStr = ucomment;
  4089. } else {
  4090. // ASCII text or unsupported code page
  4091. var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);
  4092. this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
  4093. }
  4094. }
  4095. },
  4096.  
  4097. /**
  4098. * Find the unicode path declared in the extra field, if any.
  4099. * @return {String} the unicode path, null otherwise.
  4100. */
  4101. findExtraFieldUnicodePath: function() {
  4102. var upathField = this.extraFields[0x7075];
  4103. if (upathField) {
  4104. var extraReader = readerFor(upathField.value);
  4105.  
  4106. // wrong version
  4107. if (extraReader.readInt(1) !== 1) {
  4108. return null;
  4109. }
  4110.  
  4111. // the crc of the filename changed, this field is out of date.
  4112. if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
  4113. return null;
  4114. }
  4115.  
  4116. return utf8.utf8decode(extraReader.readData(upathField.length - 5));
  4117. }
  4118. return null;
  4119. },
  4120.  
  4121. /**
  4122. * Find the unicode comment declared in the extra field, if any.
  4123. * @return {String} the unicode comment, null otherwise.
  4124. */
  4125. findExtraFieldUnicodeComment: function() {
  4126. var ucommentField = this.extraFields[0x6375];
  4127. if (ucommentField) {
  4128. var extraReader = readerFor(ucommentField.value);
  4129.  
  4130. // wrong version
  4131. if (extraReader.readInt(1) !== 1) {
  4132. return null;
  4133. }
  4134.  
  4135. // the crc of the comment changed, this field is out of date.
  4136. if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
  4137. return null;
  4138. }
  4139.  
  4140. return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
  4141. }
  4142. return null;
  4143. }
  4144. };
  4145. module.exports = ZipEntry;
  4146.  
  4147. },{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){
  4148. 'use strict';
  4149.  
  4150. var StreamHelper = require('./stream/StreamHelper');
  4151. var DataWorker = require('./stream/DataWorker');
  4152. var utf8 = require('./utf8');
  4153. var CompressedObject = require('./compressedObject');
  4154. var GenericWorker = require('./stream/GenericWorker');
  4155.  
  4156. /**
  4157. * A simple object representing a file in the zip file.
  4158. * @constructor
  4159. * @param {string} name the name of the file
  4160. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  4161. * @param {Object} options the options of the file
  4162. */
  4163. var ZipObject = function(name, data, options) {
  4164. this.name = name;
  4165. this.dir = options.dir;
  4166. this.date = options.date;
  4167. this.comment = options.comment;
  4168. this.unixPermissions = options.unixPermissions;
  4169. this.dosPermissions = options.dosPermissions;
  4170.  
  4171. this._data = data;
  4172. this._dataBinary = options.binary;
  4173. // keep only the compression
  4174. this.options = {
  4175. compression : options.compression,
  4176. compressionOptions : options.compressionOptions
  4177. };
  4178. };
  4179.  
  4180. ZipObject.prototype = {
  4181. /**
  4182. * Create an internal stream for the content of this object.
  4183. * @param {String} type the type of each chunk.
  4184. * @return StreamHelper the stream.
  4185. */
  4186. internalStream: function (type) {
  4187. var result = null, outputType = "string";
  4188. try {
  4189. if (!type) {
  4190. throw new Error("No output type specified.");
  4191. }
  4192. outputType = type.toLowerCase();
  4193. var askUnicodeString = outputType === "string" || outputType === "text";
  4194. if (outputType === "binarystring" || outputType === "text") {
  4195. outputType = "string";
  4196. }
  4197. result = this._decompressWorker();
  4198.  
  4199. var isUnicodeString = !this._dataBinary;
  4200.  
  4201. if (isUnicodeString && !askUnicodeString) {
  4202. result = result.pipe(new utf8.Utf8EncodeWorker());
  4203. }
  4204. if (!isUnicodeString && askUnicodeString) {
  4205. result = result.pipe(new utf8.Utf8DecodeWorker());
  4206. }
  4207. } catch (e) {
  4208. result = new GenericWorker("error");
  4209. result.error(e);
  4210. }
  4211.  
  4212. return new StreamHelper(result, outputType, "");
  4213. },
  4214.  
  4215. /**
  4216. * Prepare the content in the asked type.
  4217. * @param {String} type the type of the result.
  4218. * @param {Function} onUpdate a function to call on each internal update.
  4219. * @return Promise the promise of the result.
  4220. */
  4221. async: function (type, onUpdate) {
  4222. return this.internalStream(type).accumulate(onUpdate);
  4223. },
  4224.  
  4225. /**
  4226. * Prepare the content as a nodejs stream.
  4227. * @param {String} type the type of each chunk.
  4228. * @param {Function} onUpdate a function to call on each internal update.
  4229. * @return Stream the stream.
  4230. */
  4231. nodeStream: function (type, onUpdate) {
  4232. return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
  4233. },
  4234.  
  4235. /**
  4236. * Return a worker for the compressed content.
  4237. * @private
  4238. * @param {Object} compression the compression object to use.
  4239. * @param {Object} compressionOptions the options to use when compressing.
  4240. * @return Worker the worker.
  4241. */
  4242. _compressWorker: function (compression, compressionOptions) {
  4243. if (
  4244. this._data instanceof CompressedObject &&
  4245. this._data.compression.magic === compression.magic
  4246. ) {
  4247. return this._data.getCompressedWorker();
  4248. } else {
  4249. var result = this._decompressWorker();
  4250. if(!this._dataBinary) {
  4251. result = result.pipe(new utf8.Utf8EncodeWorker());
  4252. }
  4253. return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
  4254. }
  4255. },
  4256. /**
  4257. * Return a worker for the decompressed content.
  4258. * @private
  4259. * @return Worker the worker.
  4260. */
  4261. _decompressWorker : function () {
  4262. if (this._data instanceof CompressedObject) {
  4263. return this._data.getContentWorker();
  4264. } else if (this._data instanceof GenericWorker) {
  4265. return this._data;
  4266. } else {
  4267. return new DataWorker(this._data);
  4268. }
  4269. }
  4270. };
  4271.  
  4272. var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
  4273. var removedFn = function () {
  4274. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  4275. };
  4276.  
  4277. for(var i = 0; i < removedMethods.length; i++) {
  4278. ZipObject.prototype[removedMethods[i]] = removedFn;
  4279. }
  4280. module.exports = ZipObject;
  4281.  
  4282. },{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){
  4283. require('../modules/web.immediate');
  4284. module.exports = require('../modules/_core').setImmediate;
  4285. },{"../modules/_core":40,"../modules/web.immediate":56}],37:[function(require,module,exports){
  4286. module.exports = function(it){
  4287. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  4288. return it;
  4289. };
  4290. },{}],38:[function(require,module,exports){
  4291. var isObject = require('./_is-object');
  4292. module.exports = function(it){
  4293. if(!isObject(it))throw TypeError(it + ' is not an object!');
  4294. return it;
  4295. };
  4296. },{"./_is-object":51}],39:[function(require,module,exports){
  4297. var toString = {}.toString;
  4298.  
  4299. module.exports = function(it){
  4300. return toString.call(it).slice(8, -1);
  4301. };
  4302. },{}],40:[function(require,module,exports){
  4303. var core = module.exports = {version: '2.3.0'};
  4304. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  4305. },{}],41:[function(require,module,exports){
  4306. // optional / simple context binding
  4307. var aFunction = require('./_a-function');
  4308. module.exports = function(fn, that, length){
  4309. aFunction(fn);
  4310. if(that === undefined)return fn;
  4311. switch(length){
  4312. case 1: return function(a){
  4313. return fn.call(that, a);
  4314. };
  4315. case 2: return function(a, b){
  4316. return fn.call(that, a, b);
  4317. };
  4318. case 3: return function(a, b, c){
  4319. return fn.call(that, a, b, c);
  4320. };
  4321. }
  4322. return function(/* ...args */){
  4323. return fn.apply(that, arguments);
  4324. };
  4325. };
  4326. },{"./_a-function":37}],42:[function(require,module,exports){
  4327. // Thank's IE8 for his funny defineProperty
  4328. module.exports = !require('./_fails')(function(){
  4329. return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
  4330. });
  4331. },{"./_fails":45}],43:[function(require,module,exports){
  4332. var isObject = require('./_is-object')
  4333. , document = require('./_global').document
  4334. // in old IE typeof document.createElement is 'object'
  4335. , is = isObject(document) && isObject(document.createElement);
  4336. module.exports = function(it){
  4337. return is ? document.createElement(it) : {};
  4338. };
  4339. },{"./_global":46,"./_is-object":51}],44:[function(require,module,exports){
  4340. var global = require('./_global')
  4341. , core = require('./_core')
  4342. , ctx = require('./_ctx')
  4343. , hide = require('./_hide')
  4344. , PROTOTYPE = 'prototype';
  4345.  
  4346. var $export = function(type, name, source){
  4347. var IS_FORCED = type & $export.F
  4348. , IS_GLOBAL = type & $export.G
  4349. , IS_STATIC = type & $export.S
  4350. , IS_PROTO = type & $export.P
  4351. , IS_BIND = type & $export.B
  4352. , IS_WRAP = type & $export.W
  4353. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  4354. , expProto = exports[PROTOTYPE]
  4355. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  4356. , key, own, out;
  4357. if(IS_GLOBAL)source = name;
  4358. for(key in source){
  4359. // contains in native
  4360. own = !IS_FORCED && target && target[key] !== undefined;
  4361. if(own && key in exports)continue;
  4362. // export native or passed
  4363. out = own ? target[key] : source[key];
  4364. // prevent global pollution for namespaces
  4365. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  4366. // bind timers to global for call from export context
  4367. : IS_BIND && own ? ctx(out, global)
  4368. // wrap global constructors for prevent change them in library
  4369. : IS_WRAP && target[key] == out ? (function(C){
  4370. var F = function(a, b, c){
  4371. if(this instanceof C){
  4372. switch(arguments.length){
  4373. case 0: return new C;
  4374. case 1: return new C(a);
  4375. case 2: return new C(a, b);
  4376. } return new C(a, b, c);
  4377. } return C.apply(this, arguments);
  4378. };
  4379. F[PROTOTYPE] = C[PROTOTYPE];
  4380. return F;
  4381. // make static versions for prototype methods
  4382. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  4383. // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
  4384. if(IS_PROTO){
  4385. (exports.virtual || (exports.virtual = {}))[key] = out;
  4386. // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
  4387. if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
  4388. }
  4389. }
  4390. };
  4391. // type bitmap
  4392. $export.F = 1; // forced
  4393. $export.G = 2; // global
  4394. $export.S = 4; // static
  4395. $export.P = 8; // proto
  4396. $export.B = 16; // bind
  4397. $export.W = 32; // wrap
  4398. $export.U = 64; // safe
  4399. $export.R = 128; // real proto method for `library`
  4400. module.exports = $export;
  4401. },{"./_core":40,"./_ctx":41,"./_global":46,"./_hide":47}],45:[function(require,module,exports){
  4402. module.exports = function(exec){
  4403. try {
  4404. return !!exec();
  4405. } catch(e){
  4406. return true;
  4407. }
  4408. };
  4409. },{}],46:[function(require,module,exports){
  4410. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  4411. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  4412. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  4413. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  4414. },{}],47:[function(require,module,exports){
  4415. var dP = require('./_object-dp')
  4416. , createDesc = require('./_property-desc');
  4417. module.exports = require('./_descriptors') ? function(object, key, value){
  4418. return dP.f(object, key, createDesc(1, value));
  4419. } : function(object, key, value){
  4420. object[key] = value;
  4421. return object;
  4422. };
  4423. },{"./_descriptors":42,"./_object-dp":52,"./_property-desc":53}],48:[function(require,module,exports){
  4424. module.exports = require('./_global').document && document.documentElement;
  4425. },{"./_global":46}],49:[function(require,module,exports){
  4426. module.exports = !require('./_descriptors') && !require('./_fails')(function(){
  4427. return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7;
  4428. });
  4429. },{"./_descriptors":42,"./_dom-create":43,"./_fails":45}],50:[function(require,module,exports){
  4430. // fast apply, http://jsperf.lnkit.com/fast-apply/5
  4431. module.exports = function(fn, args, that){
  4432. var un = that === undefined;
  4433. switch(args.length){
  4434. case 0: return un ? fn()
  4435. : fn.call(that);
  4436. case 1: return un ? fn(args[0])
  4437. : fn.call(that, args[0]);
  4438. case 2: return un ? fn(args[0], args[1])
  4439. : fn.call(that, args[0], args[1]);
  4440. case 3: return un ? fn(args[0], args[1], args[2])
  4441. : fn.call(that, args[0], args[1], args[2]);
  4442. case 4: return un ? fn(args[0], args[1], args[2], args[3])
  4443. : fn.call(that, args[0], args[1], args[2], args[3]);
  4444. } return fn.apply(that, args);
  4445. };
  4446. },{}],51:[function(require,module,exports){
  4447. module.exports = function(it){
  4448. return typeof it === 'object' ? it !== null : typeof it === 'function';
  4449. };
  4450. },{}],52:[function(require,module,exports){
  4451. var anObject = require('./_an-object')
  4452. , IE8_DOM_DEFINE = require('./_ie8-dom-define')
  4453. , toPrimitive = require('./_to-primitive')
  4454. , dP = Object.defineProperty;
  4455.  
  4456. exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){
  4457. anObject(O);
  4458. P = toPrimitive(P, true);
  4459. anObject(Attributes);
  4460. if(IE8_DOM_DEFINE)try {
  4461. return dP(O, P, Attributes);
  4462. } catch(e){ /* empty */ }
  4463. if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
  4464. if('value' in Attributes)O[P] = Attributes.value;
  4465. return O;
  4466. };
  4467. },{"./_an-object":38,"./_descriptors":42,"./_ie8-dom-define":49,"./_to-primitive":55}],53:[function(require,module,exports){
  4468. module.exports = function(bitmap, value){
  4469. return {
  4470. enumerable : !(bitmap & 1),
  4471. configurable: !(bitmap & 2),
  4472. writable : !(bitmap & 4),
  4473. value : value
  4474. };
  4475. };
  4476. },{}],54:[function(require,module,exports){
  4477. var ctx = require('./_ctx')
  4478. , invoke = require('./_invoke')
  4479. , html = require('./_html')
  4480. , cel = require('./_dom-create')
  4481. , global = require('./_global')
  4482. , process = global.process
  4483. , setTask = global.setImmediate
  4484. , clearTask = global.clearImmediate
  4485. , MessageChannel = global.MessageChannel
  4486. , counter = 0
  4487. , queue = {}
  4488. , ONREADYSTATECHANGE = 'onreadystatechange'
  4489. , defer, channel, port;
  4490. var run = function(){
  4491. var id = +this;
  4492. if(queue.hasOwnProperty(id)){
  4493. var fn = queue[id];
  4494. delete queue[id];
  4495. fn();
  4496. }
  4497. };
  4498. var listener = function(event){
  4499. run.call(event.data);
  4500. };
  4501. // Node.js 0.9+ & IE10+ has setImmediate, otherwise:
  4502. if(!setTask || !clearTask){
  4503. setTask = function setImmediate(fn){
  4504. var args = [], i = 1;
  4505. while(arguments.length > i)args.push(arguments[i++]);
  4506. queue[++counter] = function(){
  4507. invoke(typeof fn == 'function' ? fn : Function(fn), args);
  4508. };
  4509. defer(counter);
  4510. return counter;
  4511. };
  4512. clearTask = function clearImmediate(id){
  4513. delete queue[id];
  4514. };
  4515. // Node.js 0.8-
  4516. if(require('./_cof')(process) == 'process'){
  4517. defer = function(id){
  4518. process.nextTick(ctx(run, id, 1));
  4519. };
  4520. // Browsers with MessageChannel, includes WebWorkers
  4521. } else if(MessageChannel){
  4522. channel = new MessageChannel;
  4523. port = channel.port2;
  4524. channel.port1.onmessage = listener;
  4525. defer = ctx(port.postMessage, port, 1);
  4526. // Browsers with postMessage, skip WebWorkers
  4527. // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
  4528. } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
  4529. defer = function(id){
  4530. global.postMessage(id + '', '*');
  4531. };
  4532. global.addEventListener('message', listener, false);
  4533. // IE8-
  4534. } else if(ONREADYSTATECHANGE in cel('script')){
  4535. defer = function(id){
  4536. html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
  4537. html.removeChild(this);
  4538. run.call(id);
  4539. };
  4540. };
  4541. // Rest old browsers
  4542. } else {
  4543. defer = function(id){
  4544. setTimeout(ctx(run, id, 1), 0);
  4545. };
  4546. }
  4547. }
  4548. module.exports = {
  4549. set: setTask,
  4550. clear: clearTask
  4551. };
  4552. },{"./_cof":39,"./_ctx":41,"./_dom-create":43,"./_global":46,"./_html":48,"./_invoke":50}],55:[function(require,module,exports){
  4553. // 7.1.1 ToPrimitive(input [, PreferredType])
  4554. var isObject = require('./_is-object');
  4555. // instead of the ES6 spec version, we didn't implement @@toPrimitive case
  4556. // and the second argument - flag - preferred type is a string
  4557. module.exports = function(it, S){
  4558. if(!isObject(it))return it;
  4559. var fn, val;
  4560. if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
  4561. if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
  4562. if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
  4563. throw TypeError("Can't convert object to primitive value");
  4564. };
  4565. },{"./_is-object":51}],56:[function(require,module,exports){
  4566. var $export = require('./_export')
  4567. , $task = require('./_task');
  4568. $export($export.G + $export.B, {
  4569. setImmediate: $task.set,
  4570. clearImmediate: $task.clear
  4571. });
  4572. },{"./_export":44,"./_task":54}],57:[function(require,module,exports){
  4573. (function (global){
  4574. 'use strict';
  4575. var Mutation = global.MutationObserver || global.WebKitMutationObserver;
  4576.  
  4577. var scheduleDrain;
  4578.  
  4579. {
  4580. if (Mutation) {
  4581. var called = 0;
  4582. var observer = new Mutation(nextTick);
  4583. var element = global.document.createTextNode('');
  4584. observer.observe(element, {
  4585. characterData: true
  4586. });
  4587. scheduleDrain = function () {
  4588. element.data = (called = ++called % 2);
  4589. };
  4590. } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
  4591. var channel = new global.MessageChannel();
  4592. channel.port1.onmessage = nextTick;
  4593. scheduleDrain = function () {
  4594. channel.port2.postMessage(0);
  4595. };
  4596. } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
  4597. scheduleDrain = function () {
  4598.  
  4599. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  4600. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  4601. var scriptEl = global.document.createElement('script');
  4602. scriptEl.onreadystatechange = function () {
  4603. nextTick();
  4604.  
  4605. scriptEl.onreadystatechange = null;
  4606. scriptEl.parentNode.removeChild(scriptEl);
  4607. scriptEl = null;
  4608. };
  4609. global.document.documentElement.appendChild(scriptEl);
  4610. };
  4611. } else {
  4612. scheduleDrain = function () {
  4613. setTimeout(nextTick, 0);
  4614. };
  4615. }
  4616. }
  4617.  
  4618. var draining;
  4619. var queue = [];
  4620. //named nextTick for less confusing stack traces
  4621. function nextTick() {
  4622. draining = true;
  4623. var i, oldQueue;
  4624. var len = queue.length;
  4625. while (len) {
  4626. oldQueue = queue;
  4627. queue = [];
  4628. i = -1;
  4629. while (++i < len) {
  4630. oldQueue[i]();
  4631. }
  4632. len = queue.length;
  4633. }
  4634. draining = false;
  4635. }
  4636.  
  4637. module.exports = immediate;
  4638. function immediate(task) {
  4639. if (queue.push(task) === 1 && !draining) {
  4640. scheduleDrain();
  4641. }
  4642. }
  4643.  
  4644. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4645. },{}],58:[function(require,module,exports){
  4646. 'use strict';
  4647. var immediate = require('immediate');
  4648.  
  4649. /* istanbul ignore next */
  4650. function INTERNAL() {}
  4651.  
  4652. var handlers = {};
  4653.  
  4654. var REJECTED = ['REJECTED'];
  4655. var FULFILLED = ['FULFILLED'];
  4656. var PENDING = ['PENDING'];
  4657.  
  4658. module.exports = Promise;
  4659.  
  4660. function Promise(resolver) {
  4661. if (typeof resolver !== 'function') {
  4662. throw new TypeError('resolver must be a function');
  4663. }
  4664. this.state = PENDING;
  4665. this.queue = [];
  4666. this.outcome = void 0;
  4667. if (resolver !== INTERNAL) {
  4668. safelyResolveThenable(this, resolver);
  4669. }
  4670. }
  4671.  
  4672. Promise.prototype["catch"] = function (onRejected) {
  4673. return this.then(null, onRejected);
  4674. };
  4675. Promise.prototype.then = function (onFulfilled, onRejected) {
  4676. if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
  4677. typeof onRejected !== 'function' && this.state === REJECTED) {
  4678. return this;
  4679. }
  4680. var promise = new this.constructor(INTERNAL);
  4681. if (this.state !== PENDING) {
  4682. var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
  4683. unwrap(promise, resolver, this.outcome);
  4684. } else {
  4685. this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  4686. }
  4687.  
  4688. return promise;
  4689. };
  4690. function QueueItem(promise, onFulfilled, onRejected) {
  4691. this.promise = promise;
  4692. if (typeof onFulfilled === 'function') {
  4693. this.onFulfilled = onFulfilled;
  4694. this.callFulfilled = this.otherCallFulfilled;
  4695. }
  4696. if (typeof onRejected === 'function') {
  4697. this.onRejected = onRejected;
  4698. this.callRejected = this.otherCallRejected;
  4699. }
  4700. }
  4701. QueueItem.prototype.callFulfilled = function (value) {
  4702. handlers.resolve(this.promise, value);
  4703. };
  4704. QueueItem.prototype.otherCallFulfilled = function (value) {
  4705. unwrap(this.promise, this.onFulfilled, value);
  4706. };
  4707. QueueItem.prototype.callRejected = function (value) {
  4708. handlers.reject(this.promise, value);
  4709. };
  4710. QueueItem.prototype.otherCallRejected = function (value) {
  4711. unwrap(this.promise, this.onRejected, value);
  4712. };
  4713.  
  4714. function unwrap(promise, func, value) {
  4715. immediate(function () {
  4716. var returnValue;
  4717. try {
  4718. returnValue = func(value);
  4719. } catch (e) {
  4720. return handlers.reject(promise, e);
  4721. }
  4722. if (returnValue === promise) {
  4723. handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
  4724. } else {
  4725. handlers.resolve(promise, returnValue);
  4726. }
  4727. });
  4728. }
  4729.  
  4730. handlers.resolve = function (self, value) {
  4731. var result = tryCatch(getThen, value);
  4732. if (result.status === 'error') {
  4733. return handlers.reject(self, result.value);
  4734. }
  4735. var thenable = result.value;
  4736.  
  4737. if (thenable) {
  4738. safelyResolveThenable(self, thenable);
  4739. } else {
  4740. self.state = FULFILLED;
  4741. self.outcome = value;
  4742. var i = -1;
  4743. var len = self.queue.length;
  4744. while (++i < len) {
  4745. self.queue[i].callFulfilled(value);
  4746. }
  4747. }
  4748. return self;
  4749. };
  4750. handlers.reject = function (self, error) {
  4751. self.state = REJECTED;
  4752. self.outcome = error;
  4753. var i = -1;
  4754. var len = self.queue.length;
  4755. while (++i < len) {
  4756. self.queue[i].callRejected(error);
  4757. }
  4758. return self;
  4759. };
  4760.  
  4761. function getThen(obj) {
  4762. // Make sure we only access the accessor once as required by the spec
  4763. var then = obj && obj.then;
  4764. if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
  4765. return function appyThen() {
  4766. then.apply(obj, arguments);
  4767. };
  4768. }
  4769. }
  4770.  
  4771. function safelyResolveThenable(self, thenable) {
  4772. // Either fulfill, reject or reject with error
  4773. var called = false;
  4774. function onError(value) {
  4775. if (called) {
  4776. return;
  4777. }
  4778. called = true;
  4779. handlers.reject(self, value);
  4780. }
  4781.  
  4782. function onSuccess(value) {
  4783. if (called) {
  4784. return;
  4785. }
  4786. called = true;
  4787. handlers.resolve(self, value);
  4788. }
  4789.  
  4790. function tryToUnwrap() {
  4791. thenable(onSuccess, onError);
  4792. }
  4793.  
  4794. var result = tryCatch(tryToUnwrap);
  4795. if (result.status === 'error') {
  4796. onError(result.value);
  4797. }
  4798. }
  4799.  
  4800. function tryCatch(func, value) {
  4801. var out = {};
  4802. try {
  4803. out.value = func(value);
  4804. out.status = 'success';
  4805. } catch (e) {
  4806. out.status = 'error';
  4807. out.value = e;
  4808. }
  4809. return out;
  4810. }
  4811.  
  4812. Promise.resolve = resolve;
  4813. function resolve(value) {
  4814. if (value instanceof this) {
  4815. return value;
  4816. }
  4817. return handlers.resolve(new this(INTERNAL), value);
  4818. }
  4819.  
  4820. Promise.reject = reject;
  4821. function reject(reason) {
  4822. var promise = new this(INTERNAL);
  4823. return handlers.reject(promise, reason);
  4824. }
  4825.  
  4826. Promise.all = all;
  4827. function all(iterable) {
  4828. var self = this;
  4829. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4830. return this.reject(new TypeError('must be an array'));
  4831. }
  4832.  
  4833. var len = iterable.length;
  4834. var called = false;
  4835. if (!len) {
  4836. return this.resolve([]);
  4837. }
  4838.  
  4839. var values = new Array(len);
  4840. var resolved = 0;
  4841. var i = -1;
  4842. var promise = new this(INTERNAL);
  4843.  
  4844. while (++i < len) {
  4845. allResolver(iterable[i], i);
  4846. }
  4847. return promise;
  4848. function allResolver(value, i) {
  4849. self.resolve(value).then(resolveFromAll, function (error) {
  4850. if (!called) {
  4851. called = true;
  4852. handlers.reject(promise, error);
  4853. }
  4854. });
  4855. function resolveFromAll(outValue) {
  4856. values[i] = outValue;
  4857. if (++resolved === len && !called) {
  4858. called = true;
  4859. handlers.resolve(promise, values);
  4860. }
  4861. }
  4862. }
  4863. }
  4864.  
  4865. Promise.race = race;
  4866. function race(iterable) {
  4867. var self = this;
  4868. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4869. return this.reject(new TypeError('must be an array'));
  4870. }
  4871.  
  4872. var len = iterable.length;
  4873. var called = false;
  4874. if (!len) {
  4875. return this.resolve([]);
  4876. }
  4877.  
  4878. var i = -1;
  4879. var promise = new this(INTERNAL);
  4880.  
  4881. while (++i < len) {
  4882. resolver(iterable[i]);
  4883. }
  4884. return promise;
  4885. function resolver(value) {
  4886. self.resolve(value).then(function (response) {
  4887. if (!called) {
  4888. called = true;
  4889. handlers.resolve(promise, response);
  4890. }
  4891. }, function (error) {
  4892. if (!called) {
  4893. called = true;
  4894. handlers.reject(promise, error);
  4895. }
  4896. });
  4897. }
  4898. }
  4899.  
  4900. },{"immediate":57}],59:[function(require,module,exports){
  4901. // Top level file is just a mixin of submodules & constants
  4902. 'use strict';
  4903.  
  4904. var assign = require('./lib/utils/common').assign;
  4905.  
  4906. var deflate = require('./lib/deflate');
  4907. var inflate = require('./lib/inflate');
  4908. var constants = require('./lib/zlib/constants');
  4909.  
  4910. var pako = {};
  4911.  
  4912. assign(pako, deflate, inflate, constants);
  4913.  
  4914. module.exports = pako;
  4915.  
  4916. },{"./lib/deflate":60,"./lib/inflate":61,"./lib/utils/common":62,"./lib/zlib/constants":65}],60:[function(require,module,exports){
  4917. 'use strict';
  4918.  
  4919.  
  4920. var zlib_deflate = require('./zlib/deflate');
  4921. var utils = require('./utils/common');
  4922. var strings = require('./utils/strings');
  4923. var msg = require('./zlib/messages');
  4924. var ZStream = require('./zlib/zstream');
  4925.  
  4926. var toString = Object.prototype.toString;
  4927.  
  4928. /* Public constants ==========================================================*/
  4929. /* ===========================================================================*/
  4930.  
  4931. var Z_NO_FLUSH = 0;
  4932. var Z_FINISH = 4;
  4933.  
  4934. var Z_OK = 0;
  4935. var Z_STREAM_END = 1;
  4936. var Z_SYNC_FLUSH = 2;
  4937.  
  4938. var Z_DEFAULT_COMPRESSION = -1;
  4939.  
  4940. var Z_DEFAULT_STRATEGY = 0;
  4941.  
  4942. var Z_DEFLATED = 8;
  4943.  
  4944. /* ===========================================================================*/
  4945.  
  4946.  
  4947. /**
  4948. * class Deflate
  4949. *
  4950. * Generic JS-style wrapper for zlib calls. If you don't need
  4951. * streaming behaviour - use more simple functions: [[deflate]],
  4952. * [[deflateRaw]] and [[gzip]].
  4953. **/
  4954.  
  4955. /* internal
  4956. * Deflate.chunks -> Array
  4957. *
  4958. * Chunks of output data, if [[Deflate#onData]] not overriden.
  4959. **/
  4960.  
  4961. /**
  4962. * Deflate.result -> Uint8Array|Array
  4963. *
  4964. * Compressed result, generated by default [[Deflate#onData]]
  4965. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  4966. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  4967. * push a chunk with explicit flush (call [[Deflate#push]] with
  4968. * `Z_SYNC_FLUSH` param).
  4969. **/
  4970.  
  4971. /**
  4972. * Deflate.err -> Number
  4973. *
  4974. * Error code after deflate finished. 0 (Z_OK) on success.
  4975. * You will not need it in real life, because deflate errors
  4976. * are possible only on wrong options or bad `onData` / `onEnd`
  4977. * custom handlers.
  4978. **/
  4979.  
  4980. /**
  4981. * Deflate.msg -> String
  4982. *
  4983. * Error message, if [[Deflate.err]] != 0
  4984. **/
  4985.  
  4986.  
  4987. /**
  4988. * new Deflate(options)
  4989. * - options (Object): zlib deflate options.
  4990. *
  4991. * Creates new deflator instance with specified params. Throws exception
  4992. * on bad params. Supported options:
  4993. *
  4994. * - `level`
  4995. * - `windowBits`
  4996. * - `memLevel`
  4997. * - `strategy`
  4998. * - `dictionary`
  4999. *
  5000. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5001. * for more information on these.
  5002. *
  5003. * Additional options, for internal needs:
  5004. *
  5005. * - `chunkSize` - size of generated data chunks (16K by default)
  5006. * - `raw` (Boolean) - do raw deflate
  5007. * - `gzip` (Boolean) - create gzip wrapper
  5008. * - `to` (String) - if equal to 'string', then result will be "binary string"
  5009. * (each char code [0..255])
  5010. * - `header` (Object) - custom header for gzip
  5011. * - `text` (Boolean) - true if compressed data believed to be text
  5012. * - `time` (Number) - modification time, unix timestamp
  5013. * - `os` (Number) - operation system code
  5014. * - `extra` (Array) - array of bytes with extra data (max 65536)
  5015. * - `name` (String) - file name (binary string)
  5016. * - `comment` (String) - comment (binary string)
  5017. * - `hcrc` (Boolean) - true if header crc should be added
  5018. *
  5019. * ##### Example:
  5020. *
  5021. * ```javascript
  5022. * var pako = require('pako')
  5023. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5024. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5025. *
  5026. * var deflate = new pako.Deflate({ level: 3});
  5027. *
  5028. * deflate.push(chunk1, false);
  5029. * deflate.push(chunk2, true); // true -> last chunk
  5030. *
  5031. * if (deflate.err) { throw new Error(deflate.err); }
  5032. *
  5033. * console.log(deflate.result);
  5034. * ```
  5035. **/
  5036. function Deflate(options) {
  5037. if (!(this instanceof Deflate)) return new Deflate(options);
  5038.  
  5039. this.options = utils.assign({
  5040. level: Z_DEFAULT_COMPRESSION,
  5041. method: Z_DEFLATED,
  5042. chunkSize: 16384,
  5043. windowBits: 15,
  5044. memLevel: 8,
  5045. strategy: Z_DEFAULT_STRATEGY,
  5046. to: ''
  5047. }, options || {});
  5048.  
  5049. var opt = this.options;
  5050.  
  5051. if (opt.raw && (opt.windowBits > 0)) {
  5052. opt.windowBits = -opt.windowBits;
  5053. }
  5054.  
  5055. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  5056. opt.windowBits += 16;
  5057. }
  5058.  
  5059. this.err = 0; // error code, if happens (0 = Z_OK)
  5060. this.msg = ''; // error message
  5061. this.ended = false; // used to avoid multiple onEnd() calls
  5062. this.chunks = []; // chunks of compressed data
  5063.  
  5064. this.strm = new ZStream();
  5065. this.strm.avail_out = 0;
  5066.  
  5067. var status = zlib_deflate.deflateInit2(
  5068. this.strm,
  5069. opt.level,
  5070. opt.method,
  5071. opt.windowBits,
  5072. opt.memLevel,
  5073. opt.strategy
  5074. );
  5075.  
  5076. if (status !== Z_OK) {
  5077. throw new Error(msg[status]);
  5078. }
  5079.  
  5080. if (opt.header) {
  5081. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  5082. }
  5083.  
  5084. if (opt.dictionary) {
  5085. var dict;
  5086. // Convert data if needed
  5087. if (typeof opt.dictionary === 'string') {
  5088. // If we need to compress text, change encoding to utf8.
  5089. dict = strings.string2buf(opt.dictionary);
  5090. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  5091. dict = new Uint8Array(opt.dictionary);
  5092. } else {
  5093. dict = opt.dictionary;
  5094. }
  5095.  
  5096. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  5097.  
  5098. if (status !== Z_OK) {
  5099. throw new Error(msg[status]);
  5100. }
  5101.  
  5102. this._dict_set = true;
  5103. }
  5104. }
  5105.  
  5106. /**
  5107. * Deflate#push(data[, mode]) -> Boolean
  5108. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  5109. * converted to utf8 byte sequence.
  5110. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5111. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5112. *
  5113. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  5114. * new compressed chunks. Returns `true` on success. The last data block must have
  5115. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5116. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5117. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  5118. *
  5119. * On fail call [[Deflate#onEnd]] with error code and return false.
  5120. *
  5121. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5122. * array format is detected automatically). Also, don't skip last param and always
  5123. * use the same type in your code (boolean or number). That will improve JS speed.
  5124. *
  5125. * For regular `Array`-s make sure all elements are [0..255].
  5126. *
  5127. * ##### Example
  5128. *
  5129. * ```javascript
  5130. * push(chunk, false); // push one of data chunks
  5131. * ...
  5132. * push(chunk, true); // push last chunk
  5133. * ```
  5134. **/
  5135. Deflate.prototype.push = function (data, mode) {
  5136. var strm = this.strm;
  5137. var chunkSize = this.options.chunkSize;
  5138. var status, _mode;
  5139.  
  5140. if (this.ended) { return false; }
  5141.  
  5142. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  5143.  
  5144. // Convert data if needed
  5145. if (typeof data === 'string') {
  5146. // If we need to compress text, change encoding to utf8.
  5147. strm.input = strings.string2buf(data);
  5148. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5149. strm.input = new Uint8Array(data);
  5150. } else {
  5151. strm.input = data;
  5152. }
  5153.  
  5154. strm.next_in = 0;
  5155. strm.avail_in = strm.input.length;
  5156.  
  5157. do {
  5158. if (strm.avail_out === 0) {
  5159. strm.output = new utils.Buf8(chunkSize);
  5160. strm.next_out = 0;
  5161. strm.avail_out = chunkSize;
  5162. }
  5163. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  5164.  
  5165. if (status !== Z_STREAM_END && status !== Z_OK) {
  5166. this.onEnd(status);
  5167. this.ended = true;
  5168. return false;
  5169. }
  5170. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  5171. if (this.options.to === 'string') {
  5172. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  5173. } else {
  5174. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5175. }
  5176. }
  5177. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  5178.  
  5179. // Finalize on the last chunk.
  5180. if (_mode === Z_FINISH) {
  5181. status = zlib_deflate.deflateEnd(this.strm);
  5182. this.onEnd(status);
  5183. this.ended = true;
  5184. return status === Z_OK;
  5185. }
  5186.  
  5187. // callback interim results if Z_SYNC_FLUSH.
  5188. if (_mode === Z_SYNC_FLUSH) {
  5189. this.onEnd(Z_OK);
  5190. strm.avail_out = 0;
  5191. return true;
  5192. }
  5193.  
  5194. return true;
  5195. };
  5196.  
  5197.  
  5198. /**
  5199. * Deflate#onData(chunk) -> Void
  5200. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5201. * on js engine support. When string output requested, each chunk
  5202. * will be string.
  5203. *
  5204. * By default, stores data blocks in `chunks[]` property and glue
  5205. * those in `onEnd`. Override this handler, if you need another behaviour.
  5206. **/
  5207. Deflate.prototype.onData = function (chunk) {
  5208. this.chunks.push(chunk);
  5209. };
  5210.  
  5211.  
  5212. /**
  5213. * Deflate#onEnd(status) -> Void
  5214. * - status (Number): deflate status. 0 (Z_OK) on success,
  5215. * other if not.
  5216. *
  5217. * Called once after you tell deflate that the input stream is
  5218. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5219. * or if an error happened. By default - join collected chunks,
  5220. * free memory and fill `results` / `err` properties.
  5221. **/
  5222. Deflate.prototype.onEnd = function (status) {
  5223. // On success - join
  5224. if (status === Z_OK) {
  5225. if (this.options.to === 'string') {
  5226. this.result = this.chunks.join('');
  5227. } else {
  5228. this.result = utils.flattenChunks(this.chunks);
  5229. }
  5230. }
  5231. this.chunks = [];
  5232. this.err = status;
  5233. this.msg = this.strm.msg;
  5234. };
  5235.  
  5236.  
  5237. /**
  5238. * deflate(data[, options]) -> Uint8Array|Array|String
  5239. * - data (Uint8Array|Array|String): input data to compress.
  5240. * - options (Object): zlib deflate options.
  5241. *
  5242. * Compress `data` with deflate algorithm and `options`.
  5243. *
  5244. * Supported options are:
  5245. *
  5246. * - level
  5247. * - windowBits
  5248. * - memLevel
  5249. * - strategy
  5250. * - dictionary
  5251. *
  5252. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5253. * for more information on these.
  5254. *
  5255. * Sugar (options):
  5256. *
  5257. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5258. * negative windowBits implicitly.
  5259. * - `to` (String) - if equal to 'string', then result will be "binary string"
  5260. * (each char code [0..255])
  5261. *
  5262. * ##### Example:
  5263. *
  5264. * ```javascript
  5265. * var pako = require('pako')
  5266. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  5267. *
  5268. * console.log(pako.deflate(data));
  5269. * ```
  5270. **/
  5271. function deflate(input, options) {
  5272. var deflator = new Deflate(options);
  5273.  
  5274. deflator.push(input, true);
  5275.  
  5276. // That will never happens, if you don't cheat with options :)
  5277. if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
  5278.  
  5279. return deflator.result;
  5280. }
  5281.  
  5282.  
  5283. /**
  5284. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  5285. * - data (Uint8Array|Array|String): input data to compress.
  5286. * - options (Object): zlib deflate options.
  5287. *
  5288. * The same as [[deflate]], but creates raw data, without wrapper
  5289. * (header and adler32 crc).
  5290. **/
  5291. function deflateRaw(input, options) {
  5292. options = options || {};
  5293. options.raw = true;
  5294. return deflate(input, options);
  5295. }
  5296.  
  5297.  
  5298. /**
  5299. * gzip(data[, options]) -> Uint8Array|Array|String
  5300. * - data (Uint8Array|Array|String): input data to compress.
  5301. * - options (Object): zlib deflate options.
  5302. *
  5303. * The same as [[deflate]], but create gzip wrapper instead of
  5304. * deflate one.
  5305. **/
  5306. function gzip(input, options) {
  5307. options = options || {};
  5308. options.gzip = true;
  5309. return deflate(input, options);
  5310. }
  5311.  
  5312.  
  5313. exports.Deflate = Deflate;
  5314. exports.deflate = deflate;
  5315. exports.deflateRaw = deflateRaw;
  5316. exports.gzip = gzip;
  5317.  
  5318. },{"./utils/common":62,"./utils/strings":63,"./zlib/deflate":67,"./zlib/messages":72,"./zlib/zstream":74}],61:[function(require,module,exports){
  5319. 'use strict';
  5320.  
  5321.  
  5322. var zlib_inflate = require('./zlib/inflate');
  5323. var utils = require('./utils/common');
  5324. var strings = require('./utils/strings');
  5325. var c = require('./zlib/constants');
  5326. var msg = require('./zlib/messages');
  5327. var ZStream = require('./zlib/zstream');
  5328. var GZheader = require('./zlib/gzheader');
  5329.  
  5330. var toString = Object.prototype.toString;
  5331.  
  5332. /**
  5333. * class Inflate
  5334. *
  5335. * Generic JS-style wrapper for zlib calls. If you don't need
  5336. * streaming behaviour - use more simple functions: [[inflate]]
  5337. * and [[inflateRaw]].
  5338. **/
  5339.  
  5340. /* internal
  5341. * inflate.chunks -> Array
  5342. *
  5343. * Chunks of output data, if [[Inflate#onData]] not overriden.
  5344. **/
  5345.  
  5346. /**
  5347. * Inflate.result -> Uint8Array|Array|String
  5348. *
  5349. * Uncompressed result, generated by default [[Inflate#onData]]
  5350. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  5351. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  5352. * push a chunk with explicit flush (call [[Inflate#push]] with
  5353. * `Z_SYNC_FLUSH` param).
  5354. **/
  5355.  
  5356. /**
  5357. * Inflate.err -> Number
  5358. *
  5359. * Error code after inflate finished. 0 (Z_OK) on success.
  5360. * Should be checked if broken data possible.
  5361. **/
  5362.  
  5363. /**
  5364. * Inflate.msg -> String
  5365. *
  5366. * Error message, if [[Inflate.err]] != 0
  5367. **/
  5368.  
  5369.  
  5370. /**
  5371. * new Inflate(options)
  5372. * - options (Object): zlib inflate options.
  5373. *
  5374. * Creates new inflator instance with specified params. Throws exception
  5375. * on bad params. Supported options:
  5376. *
  5377. * - `windowBits`
  5378. * - `dictionary`
  5379. *
  5380. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5381. * for more information on these.
  5382. *
  5383. * Additional options, for internal needs:
  5384. *
  5385. * - `chunkSize` - size of generated data chunks (16K by default)
  5386. * - `raw` (Boolean) - do raw inflate
  5387. * - `to` (String) - if equal to 'string', then result will be converted
  5388. * from utf8 to utf16 (javascript) string. When string output requested,
  5389. * chunk length can differ from `chunkSize`, depending on content.
  5390. *
  5391. * By default, when no options set, autodetect deflate/gzip data format via
  5392. * wrapper header.
  5393. *
  5394. * ##### Example:
  5395. *
  5396. * ```javascript
  5397. * var pako = require('pako')
  5398. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5399. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5400. *
  5401. * var inflate = new pako.Inflate({ level: 3});
  5402. *
  5403. * inflate.push(chunk1, false);
  5404. * inflate.push(chunk2, true); // true -> last chunk
  5405. *
  5406. * if (inflate.err) { throw new Error(inflate.err); }
  5407. *
  5408. * console.log(inflate.result);
  5409. * ```
  5410. **/
  5411. function Inflate(options) {
  5412. if (!(this instanceof Inflate)) return new Inflate(options);
  5413.  
  5414. this.options = utils.assign({
  5415. chunkSize: 16384,
  5416. windowBits: 0,
  5417. to: ''
  5418. }, options || {});
  5419.  
  5420. var opt = this.options;
  5421.  
  5422. // Force window size for `raw` data, if not set directly,
  5423. // because we have no header for autodetect.
  5424. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  5425. opt.windowBits = -opt.windowBits;
  5426. if (opt.windowBits === 0) { opt.windowBits = -15; }
  5427. }
  5428.  
  5429. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  5430. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  5431. !(options && options.windowBits)) {
  5432. opt.windowBits += 32;
  5433. }
  5434.  
  5435. // Gzip header has no info about windows size, we can do autodetect only
  5436. // for deflate. So, if window size not set, force it to max when gzip possible
  5437. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  5438. // bit 3 (16) -> gzipped data
  5439. // bit 4 (32) -> autodetect gzip/deflate
  5440. if ((opt.windowBits & 15) === 0) {
  5441. opt.windowBits |= 15;
  5442. }
  5443. }
  5444.  
  5445. this.err = 0; // error code, if happens (0 = Z_OK)
  5446. this.msg = ''; // error message
  5447. this.ended = false; // used to avoid multiple onEnd() calls
  5448. this.chunks = []; // chunks of compressed data
  5449.  
  5450. this.strm = new ZStream();
  5451. this.strm.avail_out = 0;
  5452.  
  5453. var status = zlib_inflate.inflateInit2(
  5454. this.strm,
  5455. opt.windowBits
  5456. );
  5457.  
  5458. if (status !== c.Z_OK) {
  5459. throw new Error(msg[status]);
  5460. }
  5461.  
  5462. this.header = new GZheader();
  5463.  
  5464. zlib_inflate.inflateGetHeader(this.strm, this.header);
  5465. }
  5466.  
  5467. /**
  5468. * Inflate#push(data[, mode]) -> Boolean
  5469. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  5470. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5471. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5472. *
  5473. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  5474. * new output chunks. Returns `true` on success. The last data block must have
  5475. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5476. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5477. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  5478. *
  5479. * On fail call [[Inflate#onEnd]] with error code and return false.
  5480. *
  5481. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5482. * format is detected automatically). Also, don't skip last param and always
  5483. * use the same type in your code (boolean or number). That will improve JS speed.
  5484. *
  5485. * For regular `Array`-s make sure all elements are [0..255].
  5486. *
  5487. * ##### Example
  5488. *
  5489. * ```javascript
  5490. * push(chunk, false); // push one of data chunks
  5491. * ...
  5492. * push(chunk, true); // push last chunk
  5493. * ```
  5494. **/
  5495. Inflate.prototype.push = function (data, mode) {
  5496. var strm = this.strm;
  5497. var chunkSize = this.options.chunkSize;
  5498. var dictionary = this.options.dictionary;
  5499. var status, _mode;
  5500. var next_out_utf8, tail, utf8str;
  5501. var dict;
  5502.  
  5503. // Flag to properly process Z_BUF_ERROR on testing inflate call
  5504. // when we check that all output data was flushed.
  5505. var allowBufError = false;
  5506.  
  5507. if (this.ended) { return false; }
  5508. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  5509.  
  5510. // Convert data if needed
  5511. if (typeof data === 'string') {
  5512. // Only binary strings can be decompressed on practice
  5513. strm.input = strings.binstring2buf(data);
  5514. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5515. strm.input = new Uint8Array(data);
  5516. } else {
  5517. strm.input = data;
  5518. }
  5519.  
  5520. strm.next_in = 0;
  5521. strm.avail_in = strm.input.length;
  5522.  
  5523. do {
  5524. if (strm.avail_out === 0) {
  5525. strm.output = new utils.Buf8(chunkSize);
  5526. strm.next_out = 0;
  5527. strm.avail_out = chunkSize;
  5528. }
  5529.  
  5530. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  5531.  
  5532. if (status === c.Z_NEED_DICT && dictionary) {
  5533. // Convert data if needed
  5534. if (typeof dictionary === 'string') {
  5535. dict = strings.string2buf(dictionary);
  5536. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  5537. dict = new Uint8Array(dictionary);
  5538. } else {
  5539. dict = dictionary;
  5540. }
  5541.  
  5542. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  5543.  
  5544. }
  5545.  
  5546. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  5547. status = c.Z_OK;
  5548. allowBufError = false;
  5549. }
  5550.  
  5551. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  5552. this.onEnd(status);
  5553. this.ended = true;
  5554. return false;
  5555. }
  5556.  
  5557. if (strm.next_out) {
  5558. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  5559.  
  5560. if (this.options.to === 'string') {
  5561.  
  5562. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  5563.  
  5564. tail = strm.next_out - next_out_utf8;
  5565. utf8str = strings.buf2string(strm.output, next_out_utf8);
  5566.  
  5567. // move tail
  5568. strm.next_out = tail;
  5569. strm.avail_out = chunkSize - tail;
  5570. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  5571.  
  5572. this.onData(utf8str);
  5573.  
  5574. } else {
  5575. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5576. }
  5577. }
  5578. }
  5579.  
  5580. // When no more input data, we should check that internal inflate buffers
  5581. // are flushed. The only way to do it when avail_out = 0 - run one more
  5582. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  5583. // Here we set flag to process this error properly.
  5584. //
  5585. // NOTE. Deflate does not return error in this case and does not needs such
  5586. // logic.
  5587. if (strm.avail_in === 0 && strm.avail_out === 0) {
  5588. allowBufError = true;
  5589. }
  5590.  
  5591. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  5592.  
  5593. if (status === c.Z_STREAM_END) {
  5594. _mode = c.Z_FINISH;
  5595. }
  5596.  
  5597. // Finalize on the last chunk.
  5598. if (_mode === c.Z_FINISH) {
  5599. status = zlib_inflate.inflateEnd(this.strm);
  5600. this.onEnd(status);
  5601. this.ended = true;
  5602. return status === c.Z_OK;
  5603. }
  5604.  
  5605. // callback interim results if Z_SYNC_FLUSH.
  5606. if (_mode === c.Z_SYNC_FLUSH) {
  5607. this.onEnd(c.Z_OK);
  5608. strm.avail_out = 0;
  5609. return true;
  5610. }
  5611.  
  5612. return true;
  5613. };
  5614.  
  5615.  
  5616. /**
  5617. * Inflate#onData(chunk) -> Void
  5618. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5619. * on js engine support. When string output requested, each chunk
  5620. * will be string.
  5621. *
  5622. * By default, stores data blocks in `chunks[]` property and glue
  5623. * those in `onEnd`. Override this handler, if you need another behaviour.
  5624. **/
  5625. Inflate.prototype.onData = function (chunk) {
  5626. this.chunks.push(chunk);
  5627. };
  5628.  
  5629.  
  5630. /**
  5631. * Inflate#onEnd(status) -> Void
  5632. * - status (Number): inflate status. 0 (Z_OK) on success,
  5633. * other if not.
  5634. *
  5635. * Called either after you tell inflate that the input stream is
  5636. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5637. * or if an error happened. By default - join collected chunks,
  5638. * free memory and fill `results` / `err` properties.
  5639. **/
  5640. Inflate.prototype.onEnd = function (status) {
  5641. // On success - join
  5642. if (status === c.Z_OK) {
  5643. if (this.options.to === 'string') {
  5644. // Glue & convert here, until we teach pako to send
  5645. // utf8 alligned strings to onData
  5646. this.result = this.chunks.join('');
  5647. } else {
  5648. this.result = utils.flattenChunks(this.chunks);
  5649. }
  5650. }
  5651. this.chunks = [];
  5652. this.err = status;
  5653. this.msg = this.strm.msg;
  5654. };
  5655.  
  5656.  
  5657. /**
  5658. * inflate(data[, options]) -> Uint8Array|Array|String
  5659. * - data (Uint8Array|Array|String): input data to decompress.
  5660. * - options (Object): zlib inflate options.
  5661. *
  5662. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  5663. * format via wrapper header by default. That's why we don't provide
  5664. * separate `ungzip` method.
  5665. *
  5666. * Supported options are:
  5667. *
  5668. * - windowBits
  5669. *
  5670. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5671. * for more information.
  5672. *
  5673. * Sugar (options):
  5674. *
  5675. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5676. * negative windowBits implicitly.
  5677. * - `to` (String) - if equal to 'string', then result will be converted
  5678. * from utf8 to utf16 (javascript) string. When string output requested,
  5679. * chunk length can differ from `chunkSize`, depending on content.
  5680. *
  5681. *
  5682. * ##### Example:
  5683. *
  5684. * ```javascript
  5685. * var pako = require('pako')
  5686. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  5687. * , output;
  5688. *
  5689. * try {
  5690. * output = pako.inflate(input);
  5691. * } catch (err)
  5692. * console.log(err);
  5693. * }
  5694. * ```
  5695. **/
  5696. function inflate(input, options) {
  5697. var inflator = new Inflate(options);
  5698.  
  5699. inflator.push(input, true);
  5700.  
  5701. // That will never happens, if you don't cheat with options :)
  5702. if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
  5703.  
  5704. return inflator.result;
  5705. }
  5706.  
  5707.  
  5708. /**
  5709. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  5710. * - data (Uint8Array|Array|String): input data to decompress.
  5711. * - options (Object): zlib inflate options.
  5712. *
  5713. * The same as [[inflate]], but creates raw data, without wrapper
  5714. * (header and adler32 crc).
  5715. **/
  5716. function inflateRaw(input, options) {
  5717. options = options || {};
  5718. options.raw = true;
  5719. return inflate(input, options);
  5720. }
  5721.  
  5722.  
  5723. /**
  5724. * ungzip(data[, options]) -> Uint8Array|Array|String
  5725. * - data (Uint8Array|Array|String): input data to decompress.
  5726. * - options (Object): zlib inflate options.
  5727. *
  5728. * Just shortcut to [[inflate]], because it autodetects format
  5729. * by header.content. Done for convenience.
  5730. **/
  5731.  
  5732.  
  5733. exports.Inflate = Inflate;
  5734. exports.inflate = inflate;
  5735. exports.inflateRaw = inflateRaw;
  5736. exports.ungzip = inflate;
  5737.  
  5738. },{"./utils/common":62,"./utils/strings":63,"./zlib/constants":65,"./zlib/gzheader":68,"./zlib/inflate":70,"./zlib/messages":72,"./zlib/zstream":74}],62:[function(require,module,exports){
  5739. 'use strict';
  5740.  
  5741.  
  5742. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  5743. (typeof Uint16Array !== 'undefined') &&
  5744. (typeof Int32Array !== 'undefined');
  5745.  
  5746.  
  5747. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  5748. var sources = Array.prototype.slice.call(arguments, 1);
  5749. while (sources.length) {
  5750. var source = sources.shift();
  5751. if (!source) { continue; }
  5752.  
  5753. if (typeof source !== 'object') {
  5754. throw new TypeError(source + 'must be non-object');
  5755. }
  5756.  
  5757. for (var p in source) {
  5758. if (source.hasOwnProperty(p)) {
  5759. obj[p] = source[p];
  5760. }
  5761. }
  5762. }
  5763.  
  5764. return obj;
  5765. };
  5766.  
  5767.  
  5768. // reduce buffer size, avoiding mem copy
  5769. exports.shrinkBuf = function (buf, size) {
  5770. if (buf.length === size) { return buf; }
  5771. if (buf.subarray) { return buf.subarray(0, size); }
  5772. buf.length = size;
  5773. return buf;
  5774. };
  5775.  
  5776.  
  5777. var fnTyped = {
  5778. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5779. if (src.subarray && dest.subarray) {
  5780. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  5781. return;
  5782. }
  5783. // Fallback to ordinary array
  5784. for (var i = 0; i < len; i++) {
  5785. dest[dest_offs + i] = src[src_offs + i];
  5786. }
  5787. },
  5788. // Join array of chunks to single array.
  5789. flattenChunks: function (chunks) {
  5790. var i, l, len, pos, chunk, result;
  5791.  
  5792. // calculate data length
  5793. len = 0;
  5794. for (i = 0, l = chunks.length; i < l; i++) {
  5795. len += chunks[i].length;
  5796. }
  5797.  
  5798. // join chunks
  5799. result = new Uint8Array(len);
  5800. pos = 0;
  5801. for (i = 0, l = chunks.length; i < l; i++) {
  5802. chunk = chunks[i];
  5803. result.set(chunk, pos);
  5804. pos += chunk.length;
  5805. }
  5806.  
  5807. return result;
  5808. }
  5809. };
  5810.  
  5811. var fnUntyped = {
  5812. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5813. for (var i = 0; i < len; i++) {
  5814. dest[dest_offs + i] = src[src_offs + i];
  5815. }
  5816. },
  5817. // Join array of chunks to single array.
  5818. flattenChunks: function (chunks) {
  5819. return [].concat.apply([], chunks);
  5820. }
  5821. };
  5822.  
  5823.  
  5824. // Enable/Disable typed arrays use, for testing
  5825. //
  5826. exports.setTyped = function (on) {
  5827. if (on) {
  5828. exports.Buf8 = Uint8Array;
  5829. exports.Buf16 = Uint16Array;
  5830. exports.Buf32 = Int32Array;
  5831. exports.assign(exports, fnTyped);
  5832. } else {
  5833. exports.Buf8 = Array;
  5834. exports.Buf16 = Array;
  5835. exports.Buf32 = Array;
  5836. exports.assign(exports, fnUntyped);
  5837. }
  5838. };
  5839.  
  5840. exports.setTyped(TYPED_OK);
  5841.  
  5842. },{}],63:[function(require,module,exports){
  5843. // String encode/decode helpers
  5844. 'use strict';
  5845.  
  5846.  
  5847. var utils = require('./common');
  5848.  
  5849.  
  5850. // Quick check if we can use fast array to bin string conversion
  5851. //
  5852. // - apply(Array) can fail on Android 2.2
  5853. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  5854. //
  5855. var STR_APPLY_OK = true;
  5856. var STR_APPLY_UIA_OK = true;
  5857.  
  5858. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  5859. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  5860.  
  5861.  
  5862. // Table with utf8 lengths (calculated by first byte of sequence)
  5863. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  5864. // because max possible codepoint is 0x10ffff
  5865. var _utf8len = new utils.Buf8(256);
  5866. for (var q = 0; q < 256; q++) {
  5867. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  5868. }
  5869. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  5870.  
  5871.  
  5872. // convert string to array (typed, when possible)
  5873. exports.string2buf = function (str) {
  5874. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  5875.  
  5876. // count binary size
  5877. for (m_pos = 0; m_pos < str_len; m_pos++) {
  5878. c = str.charCodeAt(m_pos);
  5879. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  5880. c2 = str.charCodeAt(m_pos + 1);
  5881. if ((c2 & 0xfc00) === 0xdc00) {
  5882. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5883. m_pos++;
  5884. }
  5885. }
  5886. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  5887. }
  5888.  
  5889. // allocate buffer
  5890. buf = new utils.Buf8(buf_len);
  5891.  
  5892. // convert
  5893. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  5894. c = str.charCodeAt(m_pos);
  5895. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  5896. c2 = str.charCodeAt(m_pos + 1);
  5897. if ((c2 & 0xfc00) === 0xdc00) {
  5898. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5899. m_pos++;
  5900. }
  5901. }
  5902. if (c < 0x80) {
  5903. /* one byte */
  5904. buf[i++] = c;
  5905. } else if (c < 0x800) {
  5906. /* two bytes */
  5907. buf[i++] = 0xC0 | (c >>> 6);
  5908. buf[i++] = 0x80 | (c & 0x3f);
  5909. } else if (c < 0x10000) {
  5910. /* three bytes */
  5911. buf[i++] = 0xE0 | (c >>> 12);
  5912. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5913. buf[i++] = 0x80 | (c & 0x3f);
  5914. } else {
  5915. /* four bytes */
  5916. buf[i++] = 0xf0 | (c >>> 18);
  5917. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  5918. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5919. buf[i++] = 0x80 | (c & 0x3f);
  5920. }
  5921. }
  5922.  
  5923. return buf;
  5924. };
  5925.  
  5926. // Helper (used in 2 places)
  5927. function buf2binstring(buf, len) {
  5928. // use fallback for big arrays to avoid stack overflow
  5929. if (len < 65537) {
  5930. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  5931. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  5932. }
  5933. }
  5934.  
  5935. var result = '';
  5936. for (var i = 0; i < len; i++) {
  5937. result += String.fromCharCode(buf[i]);
  5938. }
  5939. return result;
  5940. }
  5941.  
  5942.  
  5943. // Convert byte array to binary string
  5944. exports.buf2binstring = function (buf) {
  5945. return buf2binstring(buf, buf.length);
  5946. };
  5947.  
  5948.  
  5949. // Convert binary string (typed, when possible)
  5950. exports.binstring2buf = function (str) {
  5951. var buf = new utils.Buf8(str.length);
  5952. for (var i = 0, len = buf.length; i < len; i++) {
  5953. buf[i] = str.charCodeAt(i);
  5954. }
  5955. return buf;
  5956. };
  5957.  
  5958.  
  5959. // convert array to string
  5960. exports.buf2string = function (buf, max) {
  5961. var i, out, c, c_len;
  5962. var len = max || buf.length;
  5963.  
  5964. // Reserve max possible length (2 words per char)
  5965. // NB: by unknown reasons, Array is significantly faster for
  5966. // String.fromCharCode.apply than Uint16Array.
  5967. var utf16buf = new Array(len * 2);
  5968.  
  5969. for (out = 0, i = 0; i < len;) {
  5970. c = buf[i++];
  5971. // quick process ascii
  5972. if (c < 0x80) { utf16buf[out++] = c; continue; }
  5973.  
  5974. c_len = _utf8len[c];
  5975. // skip 5 & 6 byte codes
  5976. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  5977.  
  5978. // apply mask on first byte
  5979. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  5980. // join the rest
  5981. while (c_len > 1 && i < len) {
  5982. c = (c << 6) | (buf[i++] & 0x3f);
  5983. c_len--;
  5984. }
  5985.  
  5986. // terminated by end of string?
  5987. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  5988.  
  5989. if (c < 0x10000) {
  5990. utf16buf[out++] = c;
  5991. } else {
  5992. c -= 0x10000;
  5993. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  5994. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  5995. }
  5996. }
  5997.  
  5998. return buf2binstring(utf16buf, out);
  5999. };
  6000.  
  6001.  
  6002. // Calculate max possible position in utf8 buffer,
  6003. // that will not break sequence. If that's not possible
  6004. // - (very small limits) return max size as is.
  6005. //
  6006. // buf[] - utf8 bytes array
  6007. // max - length limit (mandatory);
  6008. exports.utf8border = function (buf, max) {
  6009. var pos;
  6010.  
  6011. max = max || buf.length;
  6012. if (max > buf.length) { max = buf.length; }
  6013.  
  6014. // go back from last position, until start of sequence found
  6015. pos = max - 1;
  6016. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  6017.  
  6018. // Fuckup - very small and broken sequence,
  6019. // return max, because we should return something anyway.
  6020. if (pos < 0) { return max; }
  6021.  
  6022. // If we came to start of buffer - that means vuffer is too small,
  6023. // return max too.
  6024. if (pos === 0) { return max; }
  6025.  
  6026. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  6027. };
  6028.  
  6029. },{"./common":62}],64:[function(require,module,exports){
  6030. 'use strict';
  6031.  
  6032. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  6033. // It doesn't worth to make additional optimizationa as in original.
  6034. // Small size is preferable.
  6035.  
  6036. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6037. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6038. //
  6039. // This software is provided 'as-is', without any express or implied
  6040. // warranty. In no event will the authors be held liable for any damages
  6041. // arising from the use of this software.
  6042. //
  6043. // Permission is granted to anyone to use this software for any purpose,
  6044. // including commercial applications, and to alter it and redistribute it
  6045. // freely, subject to the following restrictions:
  6046. //
  6047. // 1. The origin of this software must not be misrepresented; you must not
  6048. // claim that you wrote the original software. If you use this software
  6049. // in a product, an acknowledgment in the product documentation would be
  6050. // appreciated but is not required.
  6051. // 2. Altered source versions must be plainly marked as such, and must not be
  6052. // misrepresented as being the original software.
  6053. // 3. This notice may not be removed or altered from any source distribution.
  6054.  
  6055. function adler32(adler, buf, len, pos) {
  6056. var s1 = (adler & 0xffff) |0,
  6057. s2 = ((adler >>> 16) & 0xffff) |0,
  6058. n = 0;
  6059.  
  6060. while (len !== 0) {
  6061. // Set limit ~ twice less than 5552, to keep
  6062. // s2 in 31-bits, because we force signed ints.
  6063. // in other case %= will fail.
  6064. n = len > 2000 ? 2000 : len;
  6065. len -= n;
  6066.  
  6067. do {
  6068. s1 = (s1 + buf[pos++]) |0;
  6069. s2 = (s2 + s1) |0;
  6070. } while (--n);
  6071.  
  6072. s1 %= 65521;
  6073. s2 %= 65521;
  6074. }
  6075.  
  6076. return (s1 | (s2 << 16)) |0;
  6077. }
  6078.  
  6079.  
  6080. module.exports = adler32;
  6081.  
  6082. },{}],65:[function(require,module,exports){
  6083. 'use strict';
  6084.  
  6085. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6086. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6087. //
  6088. // This software is provided 'as-is', without any express or implied
  6089. // warranty. In no event will the authors be held liable for any damages
  6090. // arising from the use of this software.
  6091. //
  6092. // Permission is granted to anyone to use this software for any purpose,
  6093. // including commercial applications, and to alter it and redistribute it
  6094. // freely, subject to the following restrictions:
  6095. //
  6096. // 1. The origin of this software must not be misrepresented; you must not
  6097. // claim that you wrote the original software. If you use this software
  6098. // in a product, an acknowledgment in the product documentation would be
  6099. // appreciated but is not required.
  6100. // 2. Altered source versions must be plainly marked as such, and must not be
  6101. // misrepresented as being the original software.
  6102. // 3. This notice may not be removed or altered from any source distribution.
  6103.  
  6104. module.exports = {
  6105.  
  6106. /* Allowed flush values; see deflate() and inflate() below for details */
  6107. Z_NO_FLUSH: 0,
  6108. Z_PARTIAL_FLUSH: 1,
  6109. Z_SYNC_FLUSH: 2,
  6110. Z_FULL_FLUSH: 3,
  6111. Z_FINISH: 4,
  6112. Z_BLOCK: 5,
  6113. Z_TREES: 6,
  6114.  
  6115. /* Return codes for the compression/decompression functions. Negative values
  6116. * are errors, positive values are used for special but normal events.
  6117. */
  6118. Z_OK: 0,
  6119. Z_STREAM_END: 1,
  6120. Z_NEED_DICT: 2,
  6121. Z_ERRNO: -1,
  6122. Z_STREAM_ERROR: -2,
  6123. Z_DATA_ERROR: -3,
  6124. //Z_MEM_ERROR: -4,
  6125. Z_BUF_ERROR: -5,
  6126. //Z_VERSION_ERROR: -6,
  6127.  
  6128. /* compression levels */
  6129. Z_NO_COMPRESSION: 0,
  6130. Z_BEST_SPEED: 1,
  6131. Z_BEST_COMPRESSION: 9,
  6132. Z_DEFAULT_COMPRESSION: -1,
  6133.  
  6134.  
  6135. Z_FILTERED: 1,
  6136. Z_HUFFMAN_ONLY: 2,
  6137. Z_RLE: 3,
  6138. Z_FIXED: 4,
  6139. Z_DEFAULT_STRATEGY: 0,
  6140.  
  6141. /* Possible values of the data_type field (though see inflate()) */
  6142. Z_BINARY: 0,
  6143. Z_TEXT: 1,
  6144. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  6145. Z_UNKNOWN: 2,
  6146.  
  6147. /* The deflate compression method */
  6148. Z_DEFLATED: 8
  6149. //Z_NULL: null // Use -1 or null inline, depending on var type
  6150. };
  6151.  
  6152. },{}],66:[function(require,module,exports){
  6153. 'use strict';
  6154.  
  6155. // Note: we can't get significant speed boost here.
  6156. // So write code to minimize size - no pregenerated tables
  6157. // and array tools dependencies.
  6158.  
  6159. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6160. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6161. //
  6162. // This software is provided 'as-is', without any express or implied
  6163. // warranty. In no event will the authors be held liable for any damages
  6164. // arising from the use of this software.
  6165. //
  6166. // Permission is granted to anyone to use this software for any purpose,
  6167. // including commercial applications, and to alter it and redistribute it
  6168. // freely, subject to the following restrictions:
  6169. //
  6170. // 1. The origin of this software must not be misrepresented; you must not
  6171. // claim that you wrote the original software. If you use this software
  6172. // in a product, an acknowledgment in the product documentation would be
  6173. // appreciated but is not required.
  6174. // 2. Altered source versions must be plainly marked as such, and must not be
  6175. // misrepresented as being the original software.
  6176. // 3. This notice may not be removed or altered from any source distribution.
  6177.  
  6178. // Use ordinary array, since untyped makes no boost here
  6179. function makeTable() {
  6180. var c, table = [];
  6181.  
  6182. for (var n = 0; n < 256; n++) {
  6183. c = n;
  6184. for (var k = 0; k < 8; k++) {
  6185. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  6186. }
  6187. table[n] = c;
  6188. }
  6189.  
  6190. return table;
  6191. }
  6192.  
  6193. // Create table on load. Just 255 signed longs. Not a problem.
  6194. var crcTable = makeTable();
  6195.  
  6196.  
  6197. function crc32(crc, buf, len, pos) {
  6198. var t = crcTable,
  6199. end = pos + len;
  6200.  
  6201. crc ^= -1;
  6202.  
  6203. for (var i = pos; i < end; i++) {
  6204. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  6205. }
  6206.  
  6207. return (crc ^ (-1)); // >>> 0;
  6208. }
  6209.  
  6210.  
  6211. module.exports = crc32;
  6212.  
  6213. },{}],67:[function(require,module,exports){
  6214. 'use strict';
  6215.  
  6216. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6217. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6218. //
  6219. // This software is provided 'as-is', without any express or implied
  6220. // warranty. In no event will the authors be held liable for any damages
  6221. // arising from the use of this software.
  6222. //
  6223. // Permission is granted to anyone to use this software for any purpose,
  6224. // including commercial applications, and to alter it and redistribute it
  6225. // freely, subject to the following restrictions:
  6226. //
  6227. // 1. The origin of this software must not be misrepresented; you must not
  6228. // claim that you wrote the original software. If you use this software
  6229. // in a product, an acknowledgment in the product documentation would be
  6230. // appreciated but is not required.
  6231. // 2. Altered source versions must be plainly marked as such, and must not be
  6232. // misrepresented as being the original software.
  6233. // 3. This notice may not be removed or altered from any source distribution.
  6234.  
  6235. var utils = require('../utils/common');
  6236. var trees = require('./trees');
  6237. var adler32 = require('./adler32');
  6238. var crc32 = require('./crc32');
  6239. var msg = require('./messages');
  6240.  
  6241. /* Public constants ==========================================================*/
  6242. /* ===========================================================================*/
  6243.  
  6244.  
  6245. /* Allowed flush values; see deflate() and inflate() below for details */
  6246. var Z_NO_FLUSH = 0;
  6247. var Z_PARTIAL_FLUSH = 1;
  6248. //var Z_SYNC_FLUSH = 2;
  6249. var Z_FULL_FLUSH = 3;
  6250. var Z_FINISH = 4;
  6251. var Z_BLOCK = 5;
  6252. //var Z_TREES = 6;
  6253.  
  6254.  
  6255. /* Return codes for the compression/decompression functions. Negative values
  6256. * are errors, positive values are used for special but normal events.
  6257. */
  6258. var Z_OK = 0;
  6259. var Z_STREAM_END = 1;
  6260. //var Z_NEED_DICT = 2;
  6261. //var Z_ERRNO = -1;
  6262. var Z_STREAM_ERROR = -2;
  6263. var Z_DATA_ERROR = -3;
  6264. //var Z_MEM_ERROR = -4;
  6265. var Z_BUF_ERROR = -5;
  6266. //var Z_VERSION_ERROR = -6;
  6267.  
  6268.  
  6269. /* compression levels */
  6270. //var Z_NO_COMPRESSION = 0;
  6271. //var Z_BEST_SPEED = 1;
  6272. //var Z_BEST_COMPRESSION = 9;
  6273. var Z_DEFAULT_COMPRESSION = -1;
  6274.  
  6275.  
  6276. var Z_FILTERED = 1;
  6277. var Z_HUFFMAN_ONLY = 2;
  6278. var Z_RLE = 3;
  6279. var Z_FIXED = 4;
  6280. var Z_DEFAULT_STRATEGY = 0;
  6281.  
  6282. /* Possible values of the data_type field (though see inflate()) */
  6283. //var Z_BINARY = 0;
  6284. //var Z_TEXT = 1;
  6285. //var Z_ASCII = 1; // = Z_TEXT
  6286. var Z_UNKNOWN = 2;
  6287.  
  6288.  
  6289. /* The deflate compression method */
  6290. var Z_DEFLATED = 8;
  6291.  
  6292. /*============================================================================*/
  6293.  
  6294.  
  6295. var MAX_MEM_LEVEL = 9;
  6296. /* Maximum value for memLevel in deflateInit2 */
  6297. var MAX_WBITS = 15;
  6298. /* 32K LZ77 window */
  6299. var DEF_MEM_LEVEL = 8;
  6300.  
  6301.  
  6302. var LENGTH_CODES = 29;
  6303. /* number of length codes, not counting the special END_BLOCK code */
  6304. var LITERALS = 256;
  6305. /* number of literal bytes 0..255 */
  6306. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  6307. /* number of Literal or Length codes, including the END_BLOCK code */
  6308. var D_CODES = 30;
  6309. /* number of distance codes */
  6310. var BL_CODES = 19;
  6311. /* number of codes used to transfer the bit lengths */
  6312. var HEAP_SIZE = 2 * L_CODES + 1;
  6313. /* maximum heap size */
  6314. var MAX_BITS = 15;
  6315. /* All codes must not exceed MAX_BITS bits */
  6316.  
  6317. var MIN_MATCH = 3;
  6318. var MAX_MATCH = 258;
  6319. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  6320.  
  6321. var PRESET_DICT = 0x20;
  6322.  
  6323. var INIT_STATE = 42;
  6324. var EXTRA_STATE = 69;
  6325. var NAME_STATE = 73;
  6326. var COMMENT_STATE = 91;
  6327. var HCRC_STATE = 103;
  6328. var BUSY_STATE = 113;
  6329. var FINISH_STATE = 666;
  6330.  
  6331. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  6332. var BS_BLOCK_DONE = 2; /* block flush performed */
  6333. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  6334. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  6335.  
  6336. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  6337.  
  6338. function err(strm, errorCode) {
  6339. strm.msg = msg[errorCode];
  6340. return errorCode;
  6341. }
  6342.  
  6343. function rank(f) {
  6344. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  6345. }
  6346.  
  6347. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  6348.  
  6349.  
  6350. /* =========================================================================
  6351. * Flush as much pending output as possible. All deflate() output goes
  6352. * through this function so some applications may wish to modify it
  6353. * to avoid allocating a large strm->output buffer and copying into it.
  6354. * (See also read_buf()).
  6355. */
  6356. function flush_pending(strm) {
  6357. var s = strm.state;
  6358.  
  6359. //_tr_flush_bits(s);
  6360. var len = s.pending;
  6361. if (len > strm.avail_out) {
  6362. len = strm.avail_out;
  6363. }
  6364. if (len === 0) { return; }
  6365.  
  6366. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  6367. strm.next_out += len;
  6368. s.pending_out += len;
  6369. strm.total_out += len;
  6370. strm.avail_out -= len;
  6371. s.pending -= len;
  6372. if (s.pending === 0) {
  6373. s.pending_out = 0;
  6374. }
  6375. }
  6376.  
  6377.  
  6378. function flush_block_only(s, last) {
  6379. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  6380. s.block_start = s.strstart;
  6381. flush_pending(s.strm);
  6382. }
  6383.  
  6384.  
  6385. function put_byte(s, b) {
  6386. s.pending_buf[s.pending++] = b;
  6387. }
  6388.  
  6389.  
  6390. /* =========================================================================
  6391. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  6392. * IN assertion: the stream state is correct and there is enough room in
  6393. * pending_buf.
  6394. */
  6395. function putShortMSB(s, b) {
  6396. // put_byte(s, (Byte)(b >> 8));
  6397. // put_byte(s, (Byte)(b & 0xff));
  6398. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  6399. s.pending_buf[s.pending++] = b & 0xff;
  6400. }
  6401.  
  6402.  
  6403. /* ===========================================================================
  6404. * Read a new buffer from the current input stream, update the adler32
  6405. * and total number of bytes read. All deflate() input goes through
  6406. * this function so some applications may wish to modify it to avoid
  6407. * allocating a large strm->input buffer and copying from it.
  6408. * (See also flush_pending()).
  6409. */
  6410. function read_buf(strm, buf, start, size) {
  6411. var len = strm.avail_in;
  6412.  
  6413. if (len > size) { len = size; }
  6414. if (len === 0) { return 0; }
  6415.  
  6416. strm.avail_in -= len;
  6417.  
  6418. // zmemcpy(buf, strm->next_in, len);
  6419. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  6420. if (strm.state.wrap === 1) {
  6421. strm.adler = adler32(strm.adler, buf, len, start);
  6422. }
  6423.  
  6424. else if (strm.state.wrap === 2) {
  6425. strm.adler = crc32(strm.adler, buf, len, start);
  6426. }
  6427.  
  6428. strm.next_in += len;
  6429. strm.total_in += len;
  6430.  
  6431. return len;
  6432. }
  6433.  
  6434.  
  6435. /* ===========================================================================
  6436. * Set match_start to the longest match starting at the given string and
  6437. * return its length. Matches shorter or equal to prev_length are discarded,
  6438. * in which case the result is equal to prev_length and match_start is
  6439. * garbage.
  6440. * IN assertions: cur_match is the head of the hash chain for the current
  6441. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  6442. * OUT assertion: the match length is not greater than s->lookahead.
  6443. */
  6444. function longest_match(s, cur_match) {
  6445. var chain_length = s.max_chain_length; /* max hash chain length */
  6446. var scan = s.strstart; /* current string */
  6447. var match; /* matched string */
  6448. var len; /* length of current match */
  6449. var best_len = s.prev_length; /* best match length so far */
  6450. var nice_match = s.nice_match; /* stop if match long enough */
  6451. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  6452. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  6453.  
  6454. var _win = s.window; // shortcut
  6455.  
  6456. var wmask = s.w_mask;
  6457. var prev = s.prev;
  6458.  
  6459. /* Stop when cur_match becomes <= limit. To simplify the code,
  6460. * we prevent matches with the string of window index 0.
  6461. */
  6462.  
  6463. var strend = s.strstart + MAX_MATCH;
  6464. var scan_end1 = _win[scan + best_len - 1];
  6465. var scan_end = _win[scan + best_len];
  6466.  
  6467. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  6468. * It is easy to get rid of this optimization if necessary.
  6469. */
  6470. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  6471.  
  6472. /* Do not waste too much time if we already have a good match: */
  6473. if (s.prev_length >= s.good_match) {
  6474. chain_length >>= 2;
  6475. }
  6476. /* Do not look for matches beyond the end of the input. This is necessary
  6477. * to make deflate deterministic.
  6478. */
  6479. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  6480.  
  6481. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  6482.  
  6483. do {
  6484. // Assert(cur_match < s->strstart, "no future");
  6485. match = cur_match;
  6486.  
  6487. /* Skip to next match if the match length cannot increase
  6488. * or if the match length is less than 2. Note that the checks below
  6489. * for insufficient lookahead only occur occasionally for performance
  6490. * reasons. Therefore uninitialized memory will be accessed, and
  6491. * conditional jumps will be made that depend on those values.
  6492. * However the length of the match is limited to the lookahead, so
  6493. * the output of deflate is not affected by the uninitialized values.
  6494. */
  6495.  
  6496. if (_win[match + best_len] !== scan_end ||
  6497. _win[match + best_len - 1] !== scan_end1 ||
  6498. _win[match] !== _win[scan] ||
  6499. _win[++match] !== _win[scan + 1]) {
  6500. continue;
  6501. }
  6502.  
  6503. /* The check at best_len-1 can be removed because it will be made
  6504. * again later. (This heuristic is not always a win.)
  6505. * It is not necessary to compare scan[2] and match[2] since they
  6506. * are always equal when the other bytes match, given that
  6507. * the hash keys are equal and that HASH_BITS >= 8.
  6508. */
  6509. scan += 2;
  6510. match++;
  6511. // Assert(*scan == *match, "match[2]?");
  6512.  
  6513. /* We check for insufficient lookahead only every 8th comparison;
  6514. * the 256th check will be made at strstart+258.
  6515. */
  6516. do {
  6517. /*jshint noempty:false*/
  6518. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6519. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6520. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6521. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6522. scan < strend);
  6523.  
  6524. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  6525.  
  6526. len = MAX_MATCH - (strend - scan);
  6527. scan = strend - MAX_MATCH;
  6528.  
  6529. if (len > best_len) {
  6530. s.match_start = cur_match;
  6531. best_len = len;
  6532. if (len >= nice_match) {
  6533. break;
  6534. }
  6535. scan_end1 = _win[scan + best_len - 1];
  6536. scan_end = _win[scan + best_len];
  6537. }
  6538. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  6539.  
  6540. if (best_len <= s.lookahead) {
  6541. return best_len;
  6542. }
  6543. return s.lookahead;
  6544. }
  6545.  
  6546.  
  6547. /* ===========================================================================
  6548. * Fill the window when the lookahead becomes insufficient.
  6549. * Updates strstart and lookahead.
  6550. *
  6551. * IN assertion: lookahead < MIN_LOOKAHEAD
  6552. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  6553. * At least one byte has been read, or avail_in == 0; reads are
  6554. * performed for at least two bytes (required for the zip translate_eol
  6555. * option -- not supported here).
  6556. */
  6557. function fill_window(s) {
  6558. var _w_size = s.w_size;
  6559. var p, n, m, more, str;
  6560.  
  6561. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  6562.  
  6563. do {
  6564. more = s.window_size - s.lookahead - s.strstart;
  6565.  
  6566. // JS ints have 32 bit, block below not needed
  6567. /* Deal with !@#$% 64K limit: */
  6568. //if (sizeof(int) <= 2) {
  6569. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  6570. // more = wsize;
  6571. //
  6572. // } else if (more == (unsigned)(-1)) {
  6573. // /* Very unlikely, but possible on 16 bit machine if
  6574. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  6575. // */
  6576. // more--;
  6577. // }
  6578. //}
  6579.  
  6580.  
  6581. /* If the window is almost full and there is insufficient lookahead,
  6582. * move the upper half to the lower one to make room in the upper half.
  6583. */
  6584. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  6585.  
  6586. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  6587. s.match_start -= _w_size;
  6588. s.strstart -= _w_size;
  6589. /* we now have strstart >= MAX_DIST */
  6590. s.block_start -= _w_size;
  6591.  
  6592. /* Slide the hash table (could be avoided with 32 bit values
  6593. at the expense of memory usage). We slide even when level == 0
  6594. to keep the hash table consistent if we switch back to level > 0
  6595. later. (Using level 0 permanently is not an optimal usage of
  6596. zlib, so we don't care about this pathological case.)
  6597. */
  6598.  
  6599. n = s.hash_size;
  6600. p = n;
  6601. do {
  6602. m = s.head[--p];
  6603. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  6604. } while (--n);
  6605.  
  6606. n = _w_size;
  6607. p = n;
  6608. do {
  6609. m = s.prev[--p];
  6610. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  6611. /* If n is not on any hash chain, prev[n] is garbage but
  6612. * its value will never be used.
  6613. */
  6614. } while (--n);
  6615.  
  6616. more += _w_size;
  6617. }
  6618. if (s.strm.avail_in === 0) {
  6619. break;
  6620. }
  6621.  
  6622. /* If there was no sliding:
  6623. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  6624. * more == window_size - lookahead - strstart
  6625. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  6626. * => more >= window_size - 2*WSIZE + 2
  6627. * In the BIG_MEM or MMAP case (not yet supported),
  6628. * window_size == input_size + MIN_LOOKAHEAD &&
  6629. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  6630. * Otherwise, window_size == 2*WSIZE so more >= 2.
  6631. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  6632. */
  6633. //Assert(more >= 2, "more < 2");
  6634. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  6635. s.lookahead += n;
  6636.  
  6637. /* Initialize the hash value now that we have some input: */
  6638. if (s.lookahead + s.insert >= MIN_MATCH) {
  6639. str = s.strstart - s.insert;
  6640. s.ins_h = s.window[str];
  6641.  
  6642. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  6643. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  6644. //#if MIN_MATCH != 3
  6645. // Call update_hash() MIN_MATCH-3 more times
  6646. //#endif
  6647. while (s.insert) {
  6648. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6649. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  6650.  
  6651. s.prev[str & s.w_mask] = s.head[s.ins_h];
  6652. s.head[s.ins_h] = str;
  6653. str++;
  6654. s.insert--;
  6655. if (s.lookahead + s.insert < MIN_MATCH) {
  6656. break;
  6657. }
  6658. }
  6659. }
  6660. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  6661. * but this is not important since only literal bytes will be emitted.
  6662. */
  6663.  
  6664. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  6665.  
  6666. /* If the WIN_INIT bytes after the end of the current data have never been
  6667. * written, then zero those bytes in order to avoid memory check reports of
  6668. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  6669. * the longest match routines. Update the high water mark for the next
  6670. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  6671. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  6672. */
  6673. // if (s.high_water < s.window_size) {
  6674. // var curr = s.strstart + s.lookahead;
  6675. // var init = 0;
  6676. //
  6677. // if (s.high_water < curr) {
  6678. // /* Previous high water mark below current data -- zero WIN_INIT
  6679. // * bytes or up to end of window, whichever is less.
  6680. // */
  6681. // init = s.window_size - curr;
  6682. // if (init > WIN_INIT)
  6683. // init = WIN_INIT;
  6684. // zmemzero(s->window + curr, (unsigned)init);
  6685. // s->high_water = curr + init;
  6686. // }
  6687. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  6688. // /* High water mark at or above current data, but below current data
  6689. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  6690. // * to end of window, whichever is less.
  6691. // */
  6692. // init = (ulg)curr + WIN_INIT - s->high_water;
  6693. // if (init > s->window_size - s->high_water)
  6694. // init = s->window_size - s->high_water;
  6695. // zmemzero(s->window + s->high_water, (unsigned)init);
  6696. // s->high_water += init;
  6697. // }
  6698. // }
  6699. //
  6700. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  6701. // "not enough room for search");
  6702. }
  6703.  
  6704. /* ===========================================================================
  6705. * Copy without compression as much as possible from the input stream, return
  6706. * the current block state.
  6707. * This function does not insert new strings in the dictionary since
  6708. * uncompressible data is probably not useful. This function is used
  6709. * only for the level=0 compression option.
  6710. * NOTE: this function should be optimized to avoid extra copying from
  6711. * window to pending_buf.
  6712. */
  6713. function deflate_stored(s, flush) {
  6714. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  6715. * to pending_buf_size, and each stored block has a 5 byte header:
  6716. */
  6717. var max_block_size = 0xffff;
  6718.  
  6719. if (max_block_size > s.pending_buf_size - 5) {
  6720. max_block_size = s.pending_buf_size - 5;
  6721. }
  6722.  
  6723. /* Copy as much as possible from input to output: */
  6724. for (;;) {
  6725. /* Fill the window as much as possible: */
  6726. if (s.lookahead <= 1) {
  6727.  
  6728. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  6729. // s->block_start >= (long)s->w_size, "slide too late");
  6730. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  6731. // s.block_start >= s.w_size)) {
  6732. // throw new Error("slide too late");
  6733. // }
  6734.  
  6735. fill_window(s);
  6736. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  6737. return BS_NEED_MORE;
  6738. }
  6739.  
  6740. if (s.lookahead === 0) {
  6741. break;
  6742. }
  6743. /* flush the current block */
  6744. }
  6745. //Assert(s->block_start >= 0L, "block gone");
  6746. // if (s.block_start < 0) throw new Error("block gone");
  6747.  
  6748. s.strstart += s.lookahead;
  6749. s.lookahead = 0;
  6750.  
  6751. /* Emit a stored block if pending_buf will be full: */
  6752. var max_start = s.block_start + max_block_size;
  6753.  
  6754. if (s.strstart === 0 || s.strstart >= max_start) {
  6755. /* strstart == 0 is possible when wraparound on 16-bit machine */
  6756. s.lookahead = s.strstart - max_start;
  6757. s.strstart = max_start;
  6758. /*** FLUSH_BLOCK(s, 0); ***/
  6759. flush_block_only(s, false);
  6760. if (s.strm.avail_out === 0) {
  6761. return BS_NEED_MORE;
  6762. }
  6763. /***/
  6764.  
  6765.  
  6766. }
  6767. /* Flush if we may have to slide, otherwise block_start may become
  6768. * negative and the data will be gone:
  6769. */
  6770. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  6771. /*** FLUSH_BLOCK(s, 0); ***/
  6772. flush_block_only(s, false);
  6773. if (s.strm.avail_out === 0) {
  6774. return BS_NEED_MORE;
  6775. }
  6776. /***/
  6777. }
  6778. }
  6779.  
  6780. s.insert = 0;
  6781.  
  6782. if (flush === Z_FINISH) {
  6783. /*** FLUSH_BLOCK(s, 1); ***/
  6784. flush_block_only(s, true);
  6785. if (s.strm.avail_out === 0) {
  6786. return BS_FINISH_STARTED;
  6787. }
  6788. /***/
  6789. return BS_FINISH_DONE;
  6790. }
  6791.  
  6792. if (s.strstart > s.block_start) {
  6793. /*** FLUSH_BLOCK(s, 0); ***/
  6794. flush_block_only(s, false);
  6795. if (s.strm.avail_out === 0) {
  6796. return BS_NEED_MORE;
  6797. }
  6798. /***/
  6799. }
  6800.  
  6801. return BS_NEED_MORE;
  6802. }
  6803.  
  6804. /* ===========================================================================
  6805. * Compress as much as possible from the input stream, return the current
  6806. * block state.
  6807. * This function does not perform lazy evaluation of matches and inserts
  6808. * new strings in the dictionary only for unmatched strings or for short
  6809. * matches. It is used only for the fast compression options.
  6810. */
  6811. function deflate_fast(s, flush) {
  6812. var hash_head; /* head of the hash chain */
  6813. var bflush; /* set if current block must be flushed */
  6814.  
  6815. for (;;) {
  6816. /* Make sure that we always have enough lookahead, except
  6817. * at the end of the input file. We need MAX_MATCH bytes
  6818. * for the next match, plus MIN_MATCH bytes to insert the
  6819. * string following the next match.
  6820. */
  6821. if (s.lookahead < MIN_LOOKAHEAD) {
  6822. fill_window(s);
  6823. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6824. return BS_NEED_MORE;
  6825. }
  6826. if (s.lookahead === 0) {
  6827. break; /* flush the current block */
  6828. }
  6829. }
  6830.  
  6831. /* Insert the string window[strstart .. strstart+2] in the
  6832. * dictionary, and set hash_head to the head of the hash chain:
  6833. */
  6834. hash_head = 0/*NIL*/;
  6835. if (s.lookahead >= MIN_MATCH) {
  6836. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6837. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6838. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6839. s.head[s.ins_h] = s.strstart;
  6840. /***/
  6841. }
  6842.  
  6843. /* Find the longest match, discarding those <= prev_length.
  6844. * At this point we have always match_length < MIN_MATCH
  6845. */
  6846. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  6847. /* To simplify the code, we prevent matches with the string
  6848. * of window index 0 (in particular we have to avoid a match
  6849. * of the string with itself at the start of the input file).
  6850. */
  6851. s.match_length = longest_match(s, hash_head);
  6852. /* longest_match() sets match_start */
  6853. }
  6854. if (s.match_length >= MIN_MATCH) {
  6855. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  6856.  
  6857. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  6858. s.match_length - MIN_MATCH, bflush); ***/
  6859. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  6860.  
  6861. s.lookahead -= s.match_length;
  6862.  
  6863. /* Insert new strings in the hash table only if the match length
  6864. * is not too large. This saves time but degrades compression.
  6865. */
  6866. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  6867. s.match_length--; /* string at strstart already in table */
  6868. do {
  6869. s.strstart++;
  6870. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6871. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6872. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6873. s.head[s.ins_h] = s.strstart;
  6874. /***/
  6875. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  6876. * always MIN_MATCH bytes ahead.
  6877. */
  6878. } while (--s.match_length !== 0);
  6879. s.strstart++;
  6880. } else
  6881. {
  6882. s.strstart += s.match_length;
  6883. s.match_length = 0;
  6884. s.ins_h = s.window[s.strstart];
  6885. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  6886. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  6887.  
  6888. //#if MIN_MATCH != 3
  6889. // Call UPDATE_HASH() MIN_MATCH-3 more times
  6890. //#endif
  6891. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  6892. * matter since it will be recomputed at next deflate call.
  6893. */
  6894. }
  6895. } else {
  6896. /* No match, output a literal byte */
  6897. //Tracevv((stderr,"%c", s.window[s.strstart]));
  6898. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6899. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6900.  
  6901. s.lookahead--;
  6902. s.strstart++;
  6903. }
  6904. if (bflush) {
  6905. /*** FLUSH_BLOCK(s, 0); ***/
  6906. flush_block_only(s, false);
  6907. if (s.strm.avail_out === 0) {
  6908. return BS_NEED_MORE;
  6909. }
  6910. /***/
  6911. }
  6912. }
  6913. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  6914. if (flush === Z_FINISH) {
  6915. /*** FLUSH_BLOCK(s, 1); ***/
  6916. flush_block_only(s, true);
  6917. if (s.strm.avail_out === 0) {
  6918. return BS_FINISH_STARTED;
  6919. }
  6920. /***/
  6921. return BS_FINISH_DONE;
  6922. }
  6923. if (s.last_lit) {
  6924. /*** FLUSH_BLOCK(s, 0); ***/
  6925. flush_block_only(s, false);
  6926. if (s.strm.avail_out === 0) {
  6927. return BS_NEED_MORE;
  6928. }
  6929. /***/
  6930. }
  6931. return BS_BLOCK_DONE;
  6932. }
  6933.  
  6934. /* ===========================================================================
  6935. * Same as above, but achieves better compression. We use a lazy
  6936. * evaluation for matches: a match is finally adopted only if there is
  6937. * no better match at the next window position.
  6938. */
  6939. function deflate_slow(s, flush) {
  6940. var hash_head; /* head of hash chain */
  6941. var bflush; /* set if current block must be flushed */
  6942.  
  6943. var max_insert;
  6944.  
  6945. /* Process the input block. */
  6946. for (;;) {
  6947. /* Make sure that we always have enough lookahead, except
  6948. * at the end of the input file. We need MAX_MATCH bytes
  6949. * for the next match, plus MIN_MATCH bytes to insert the
  6950. * string following the next match.
  6951. */
  6952. if (s.lookahead < MIN_LOOKAHEAD) {
  6953. fill_window(s);
  6954. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6955. return BS_NEED_MORE;
  6956. }
  6957. if (s.lookahead === 0) { break; } /* flush the current block */
  6958. }
  6959.  
  6960. /* Insert the string window[strstart .. strstart+2] in the
  6961. * dictionary, and set hash_head to the head of the hash chain:
  6962. */
  6963. hash_head = 0/*NIL*/;
  6964. if (s.lookahead >= MIN_MATCH) {
  6965. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6966. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6967. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6968. s.head[s.ins_h] = s.strstart;
  6969. /***/
  6970. }
  6971.  
  6972. /* Find the longest match, discarding those <= prev_length.
  6973. */
  6974. s.prev_length = s.match_length;
  6975. s.prev_match = s.match_start;
  6976. s.match_length = MIN_MATCH - 1;
  6977.  
  6978. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  6979. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  6980. /* To simplify the code, we prevent matches with the string
  6981. * of window index 0 (in particular we have to avoid a match
  6982. * of the string with itself at the start of the input file).
  6983. */
  6984. s.match_length = longest_match(s, hash_head);
  6985. /* longest_match() sets match_start */
  6986.  
  6987. if (s.match_length <= 5 &&
  6988. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  6989.  
  6990. /* If prev_match is also MIN_MATCH, match_start is garbage
  6991. * but we will ignore the current match anyway.
  6992. */
  6993. s.match_length = MIN_MATCH - 1;
  6994. }
  6995. }
  6996. /* If there was a match at the previous step and the current
  6997. * match is not better, output the previous match:
  6998. */
  6999. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  7000. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  7001. /* Do not insert strings in hash table beyond this. */
  7002.  
  7003. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  7004.  
  7005. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  7006. s.prev_length - MIN_MATCH, bflush);***/
  7007. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  7008. /* Insert in hash table all strings up to the end of the match.
  7009. * strstart-1 and strstart are already inserted. If there is not
  7010. * enough lookahead, the last two strings are not inserted in
  7011. * the hash table.
  7012. */
  7013. s.lookahead -= s.prev_length - 1;
  7014. s.prev_length -= 2;
  7015. do {
  7016. if (++s.strstart <= max_insert) {
  7017. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7018. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7019. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7020. s.head[s.ins_h] = s.strstart;
  7021. /***/
  7022. }
  7023. } while (--s.prev_length !== 0);
  7024. s.match_available = 0;
  7025. s.match_length = MIN_MATCH - 1;
  7026. s.strstart++;
  7027.  
  7028. if (bflush) {
  7029. /*** FLUSH_BLOCK(s, 0); ***/
  7030. flush_block_only(s, false);
  7031. if (s.strm.avail_out === 0) {
  7032. return BS_NEED_MORE;
  7033. }
  7034. /***/
  7035. }
  7036.  
  7037. } else if (s.match_available) {
  7038. /* If there was no match at the previous position, output a
  7039. * single literal. If there was a match but the current match
  7040. * is longer, truncate the previous match to a single literal.
  7041. */
  7042. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  7043. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  7044. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  7045.  
  7046. if (bflush) {
  7047. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  7048. flush_block_only(s, false);
  7049. /***/
  7050. }
  7051. s.strstart++;
  7052. s.lookahead--;
  7053. if (s.strm.avail_out === 0) {
  7054. return BS_NEED_MORE;
  7055. }
  7056. } else {
  7057. /* There is no previous match to compare with, wait for
  7058. * the next step to decide.
  7059. */
  7060. s.match_available = 1;
  7061. s.strstart++;
  7062. s.lookahead--;
  7063. }
  7064. }
  7065. //Assert (flush != Z_NO_FLUSH, "no flush?");
  7066. if (s.match_available) {
  7067. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  7068. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  7069. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  7070.  
  7071. s.match_available = 0;
  7072. }
  7073. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  7074. if (flush === Z_FINISH) {
  7075. /*** FLUSH_BLOCK(s, 1); ***/
  7076. flush_block_only(s, true);
  7077. if (s.strm.avail_out === 0) {
  7078. return BS_FINISH_STARTED;
  7079. }
  7080. /***/
  7081. return BS_FINISH_DONE;
  7082. }
  7083. if (s.last_lit) {
  7084. /*** FLUSH_BLOCK(s, 0); ***/
  7085. flush_block_only(s, false);
  7086. if (s.strm.avail_out === 0) {
  7087. return BS_NEED_MORE;
  7088. }
  7089. /***/
  7090. }
  7091.  
  7092. return BS_BLOCK_DONE;
  7093. }
  7094.  
  7095.  
  7096. /* ===========================================================================
  7097. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  7098. * one. Do not maintain a hash table. (It will be regenerated if this run of
  7099. * deflate switches away from Z_RLE.)
  7100. */
  7101. function deflate_rle(s, flush) {
  7102. var bflush; /* set if current block must be flushed */
  7103. var prev; /* byte at distance one to match */
  7104. var scan, strend; /* scan goes up to strend for length of run */
  7105.  
  7106. var _win = s.window;
  7107.  
  7108. for (;;) {
  7109. /* Make sure that we always have enough lookahead, except
  7110. * at the end of the input file. We need MAX_MATCH bytes
  7111. * for the longest run, plus one for the unrolled loop.
  7112. */
  7113. if (s.lookahead <= MAX_MATCH) {
  7114. fill_window(s);
  7115. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  7116. return BS_NEED_MORE;
  7117. }
  7118. if (s.lookahead === 0) { break; } /* flush the current block */
  7119. }
  7120.  
  7121. /* See how many times the previous byte repeats */
  7122. s.match_length = 0;
  7123. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  7124. scan = s.strstart - 1;
  7125. prev = _win[scan];
  7126. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  7127. strend = s.strstart + MAX_MATCH;
  7128. do {
  7129. /*jshint noempty:false*/
  7130. } while (prev === _win[++scan] && prev === _win[++scan] &&
  7131. prev === _win[++scan] && prev === _win[++scan] &&
  7132. prev === _win[++scan] && prev === _win[++scan] &&
  7133. prev === _win[++scan] && prev === _win[++scan] &&
  7134. scan < strend);
  7135. s.match_length = MAX_MATCH - (strend - scan);
  7136. if (s.match_length > s.lookahead) {
  7137. s.match_length = s.lookahead;
  7138. }
  7139. }
  7140. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  7141. }
  7142.  
  7143. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  7144. if (s.match_length >= MIN_MATCH) {
  7145. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  7146.  
  7147. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  7148. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  7149.  
  7150. s.lookahead -= s.match_length;
  7151. s.strstart += s.match_length;
  7152. s.match_length = 0;
  7153. } else {
  7154. /* No match, output a literal byte */
  7155. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7156. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7157. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7158.  
  7159. s.lookahead--;
  7160. s.strstart++;
  7161. }
  7162. if (bflush) {
  7163. /*** FLUSH_BLOCK(s, 0); ***/
  7164. flush_block_only(s, false);
  7165. if (s.strm.avail_out === 0) {
  7166. return BS_NEED_MORE;
  7167. }
  7168. /***/
  7169. }
  7170. }
  7171. s.insert = 0;
  7172. if (flush === Z_FINISH) {
  7173. /*** FLUSH_BLOCK(s, 1); ***/
  7174. flush_block_only(s, true);
  7175. if (s.strm.avail_out === 0) {
  7176. return BS_FINISH_STARTED;
  7177. }
  7178. /***/
  7179. return BS_FINISH_DONE;
  7180. }
  7181. if (s.last_lit) {
  7182. /*** FLUSH_BLOCK(s, 0); ***/
  7183. flush_block_only(s, false);
  7184. if (s.strm.avail_out === 0) {
  7185. return BS_NEED_MORE;
  7186. }
  7187. /***/
  7188. }
  7189. return BS_BLOCK_DONE;
  7190. }
  7191.  
  7192. /* ===========================================================================
  7193. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  7194. * (It will be regenerated if this run of deflate switches away from Huffman.)
  7195. */
  7196. function deflate_huff(s, flush) {
  7197. var bflush; /* set if current block must be flushed */
  7198.  
  7199. for (;;) {
  7200. /* Make sure that we have a literal to write. */
  7201. if (s.lookahead === 0) {
  7202. fill_window(s);
  7203. if (s.lookahead === 0) {
  7204. if (flush === Z_NO_FLUSH) {
  7205. return BS_NEED_MORE;
  7206. }
  7207. break; /* flush the current block */
  7208. }
  7209. }
  7210.  
  7211. /* Output a literal byte */
  7212. s.match_length = 0;
  7213. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7214. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7215. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7216. s.lookahead--;
  7217. s.strstart++;
  7218. if (bflush) {
  7219. /*** FLUSH_BLOCK(s, 0); ***/
  7220. flush_block_only(s, false);
  7221. if (s.strm.avail_out === 0) {
  7222. return BS_NEED_MORE;
  7223. }
  7224. /***/
  7225. }
  7226. }
  7227. s.insert = 0;
  7228. if (flush === Z_FINISH) {
  7229. /*** FLUSH_BLOCK(s, 1); ***/
  7230. flush_block_only(s, true);
  7231. if (s.strm.avail_out === 0) {
  7232. return BS_FINISH_STARTED;
  7233. }
  7234. /***/
  7235. return BS_FINISH_DONE;
  7236. }
  7237. if (s.last_lit) {
  7238. /*** FLUSH_BLOCK(s, 0); ***/
  7239. flush_block_only(s, false);
  7240. if (s.strm.avail_out === 0) {
  7241. return BS_NEED_MORE;
  7242. }
  7243. /***/
  7244. }
  7245. return BS_BLOCK_DONE;
  7246. }
  7247.  
  7248. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  7249. * the desired pack level (0..9). The values given below have been tuned to
  7250. * exclude worst case performance for pathological files. Better values may be
  7251. * found for specific files.
  7252. */
  7253. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  7254. this.good_length = good_length;
  7255. this.max_lazy = max_lazy;
  7256. this.nice_length = nice_length;
  7257. this.max_chain = max_chain;
  7258. this.func = func;
  7259. }
  7260.  
  7261. var configuration_table;
  7262.  
  7263. configuration_table = [
  7264. /* good lazy nice chain */
  7265. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  7266. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  7267. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  7268. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  7269.  
  7270. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  7271. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  7272. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  7273. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  7274. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  7275. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  7276. ];
  7277.  
  7278.  
  7279. /* ===========================================================================
  7280. * Initialize the "longest match" routines for a new zlib stream
  7281. */
  7282. function lm_init(s) {
  7283. s.window_size = 2 * s.w_size;
  7284.  
  7285. /*** CLEAR_HASH(s); ***/
  7286. zero(s.head); // Fill with NIL (= 0);
  7287.  
  7288. /* Set the default configuration parameters:
  7289. */
  7290. s.max_lazy_match = configuration_table[s.level].max_lazy;
  7291. s.good_match = configuration_table[s.level].good_length;
  7292. s.nice_match = configuration_table[s.level].nice_length;
  7293. s.max_chain_length = configuration_table[s.level].max_chain;
  7294.  
  7295. s.strstart = 0;
  7296. s.block_start = 0;
  7297. s.lookahead = 0;
  7298. s.insert = 0;
  7299. s.match_length = s.prev_length = MIN_MATCH - 1;
  7300. s.match_available = 0;
  7301. s.ins_h = 0;
  7302. }
  7303.  
  7304.  
  7305. function DeflateState() {
  7306. this.strm = null; /* pointer back to this zlib stream */
  7307. this.status = 0; /* as the name implies */
  7308. this.pending_buf = null; /* output still pending */
  7309. this.pending_buf_size = 0; /* size of pending_buf */
  7310. this.pending_out = 0; /* next pending byte to output to the stream */
  7311. this.pending = 0; /* nb of bytes in the pending buffer */
  7312. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  7313. this.gzhead = null; /* gzip header information to write */
  7314. this.gzindex = 0; /* where in extra, name, or comment */
  7315. this.method = Z_DEFLATED; /* can only be DEFLATED */
  7316. this.last_flush = -1; /* value of flush param for previous deflate call */
  7317.  
  7318. this.w_size = 0; /* LZ77 window size (32K by default) */
  7319. this.w_bits = 0; /* log2(w_size) (8..16) */
  7320. this.w_mask = 0; /* w_size - 1 */
  7321.  
  7322. this.window = null;
  7323. /* Sliding window. Input bytes are read into the second half of the window,
  7324. * and move to the first half later to keep a dictionary of at least wSize
  7325. * bytes. With this organization, matches are limited to a distance of
  7326. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  7327. * performed with a length multiple of the block size.
  7328. */
  7329.  
  7330. this.window_size = 0;
  7331. /* Actual size of window: 2*wSize, except when the user input buffer
  7332. * is directly used as sliding window.
  7333. */
  7334.  
  7335. this.prev = null;
  7336. /* Link to older string with same hash index. To limit the size of this
  7337. * array to 64K, this link is maintained only for the last 32K strings.
  7338. * An index in this array is thus a window index modulo 32K.
  7339. */
  7340.  
  7341. this.head = null; /* Heads of the hash chains or NIL. */
  7342.  
  7343. this.ins_h = 0; /* hash index of string to be inserted */
  7344. this.hash_size = 0; /* number of elements in hash table */
  7345. this.hash_bits = 0; /* log2(hash_size) */
  7346. this.hash_mask = 0; /* hash_size-1 */
  7347.  
  7348. this.hash_shift = 0;
  7349. /* Number of bits by which ins_h must be shifted at each input
  7350. * step. It must be such that after MIN_MATCH steps, the oldest
  7351. * byte no longer takes part in the hash key, that is:
  7352. * hash_shift * MIN_MATCH >= hash_bits
  7353. */
  7354.  
  7355. this.block_start = 0;
  7356. /* Window position at the beginning of the current output block. Gets
  7357. * negative when the window is moved backwards.
  7358. */
  7359.  
  7360. this.match_length = 0; /* length of best match */
  7361. this.prev_match = 0; /* previous match */
  7362. this.match_available = 0; /* set if previous match exists */
  7363. this.strstart = 0; /* start of string to insert */
  7364. this.match_start = 0; /* start of matching string */
  7365. this.lookahead = 0; /* number of valid bytes ahead in window */
  7366.  
  7367. this.prev_length = 0;
  7368. /* Length of the best match at previous step. Matches not greater than this
  7369. * are discarded. This is used in the lazy match evaluation.
  7370. */
  7371.  
  7372. this.max_chain_length = 0;
  7373. /* To speed up deflation, hash chains are never searched beyond this
  7374. * length. A higher limit improves compression ratio but degrades the
  7375. * speed.
  7376. */
  7377.  
  7378. this.max_lazy_match = 0;
  7379. /* Attempt to find a better match only when the current match is strictly
  7380. * smaller than this value. This mechanism is used only for compression
  7381. * levels >= 4.
  7382. */
  7383. // That's alias to max_lazy_match, don't use directly
  7384. //this.max_insert_length = 0;
  7385. /* Insert new strings in the hash table only if the match length is not
  7386. * greater than this length. This saves time but degrades compression.
  7387. * max_insert_length is used only for compression levels <= 3.
  7388. */
  7389.  
  7390. this.level = 0; /* compression level (1..9) */
  7391. this.strategy = 0; /* favor or force Huffman coding*/
  7392.  
  7393. this.good_match = 0;
  7394. /* Use a faster search when the previous match is longer than this */
  7395.  
  7396. this.nice_match = 0; /* Stop searching when current match exceeds this */
  7397.  
  7398. /* used by trees.c: */
  7399.  
  7400. /* Didn't use ct_data typedef below to suppress compiler warning */
  7401.  
  7402. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  7403. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  7404. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  7405.  
  7406. // Use flat array of DOUBLE size, with interleaved fata,
  7407. // because JS does not support effective
  7408. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  7409. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  7410. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  7411. zero(this.dyn_ltree);
  7412. zero(this.dyn_dtree);
  7413. zero(this.bl_tree);
  7414.  
  7415. this.l_desc = null; /* desc. for literal tree */
  7416. this.d_desc = null; /* desc. for distance tree */
  7417. this.bl_desc = null; /* desc. for bit length tree */
  7418.  
  7419. //ush bl_count[MAX_BITS+1];
  7420. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  7421. /* number of codes at each bit length for an optimal tree */
  7422.  
  7423. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  7424. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  7425. zero(this.heap);
  7426.  
  7427. this.heap_len = 0; /* number of elements in the heap */
  7428. this.heap_max = 0; /* element of largest frequency */
  7429. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  7430. * The same heap array is used to build all trees.
  7431. */
  7432.  
  7433. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  7434. zero(this.depth);
  7435. /* Depth of each subtree used as tie breaker for trees of equal frequency
  7436. */
  7437.  
  7438. this.l_buf = 0; /* buffer index for literals or lengths */
  7439.  
  7440. this.lit_bufsize = 0;
  7441. /* Size of match buffer for literals/lengths. There are 4 reasons for
  7442. * limiting lit_bufsize to 64K:
  7443. * - frequencies can be kept in 16 bit counters
  7444. * - if compression is not successful for the first block, all input
  7445. * data is still in the window so we can still emit a stored block even
  7446. * when input comes from standard input. (This can also be done for
  7447. * all blocks if lit_bufsize is not greater than 32K.)
  7448. * - if compression is not successful for a file smaller than 64K, we can
  7449. * even emit a stored file instead of a stored block (saving 5 bytes).
  7450. * This is applicable only for zip (not gzip or zlib).
  7451. * - creating new Huffman trees less frequently may not provide fast
  7452. * adaptation to changes in the input data statistics. (Take for
  7453. * example a binary file with poorly compressible code followed by
  7454. * a highly compressible string table.) Smaller buffer sizes give
  7455. * fast adaptation but have of course the overhead of transmitting
  7456. * trees more frequently.
  7457. * - I can't count above 4
  7458. */
  7459.  
  7460. this.last_lit = 0; /* running index in l_buf */
  7461.  
  7462. this.d_buf = 0;
  7463. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  7464. * the same number of elements. To use different lengths, an extra flag
  7465. * array would be necessary.
  7466. */
  7467.  
  7468. this.opt_len = 0; /* bit length of current block with optimal trees */
  7469. this.static_len = 0; /* bit length of current block with static trees */
  7470. this.matches = 0; /* number of string matches in current block */
  7471. this.insert = 0; /* bytes at end of window left to insert */
  7472.  
  7473.  
  7474. this.bi_buf = 0;
  7475. /* Output buffer. bits are inserted starting at the bottom (least
  7476. * significant bits).
  7477. */
  7478. this.bi_valid = 0;
  7479. /* Number of valid bits in bi_buf. All bits above the last valid bit
  7480. * are always zero.
  7481. */
  7482.  
  7483. // Used for window memory init. We safely ignore it for JS. That makes
  7484. // sense only for pointers and memory check tools.
  7485. //this.high_water = 0;
  7486. /* High water mark offset in window for initialized bytes -- bytes above
  7487. * this are set to zero in order to avoid memory check warnings when
  7488. * longest match routines access bytes past the input. This is then
  7489. * updated to the new high water mark.
  7490. */
  7491. }
  7492.  
  7493.  
  7494. function deflateResetKeep(strm) {
  7495. var s;
  7496.  
  7497. if (!strm || !strm.state) {
  7498. return err(strm, Z_STREAM_ERROR);
  7499. }
  7500.  
  7501. strm.total_in = strm.total_out = 0;
  7502. strm.data_type = Z_UNKNOWN;
  7503.  
  7504. s = strm.state;
  7505. s.pending = 0;
  7506. s.pending_out = 0;
  7507.  
  7508. if (s.wrap < 0) {
  7509. s.wrap = -s.wrap;
  7510. /* was made negative by deflate(..., Z_FINISH); */
  7511. }
  7512. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  7513. strm.adler = (s.wrap === 2) ?
  7514. 0 // crc32(0, Z_NULL, 0)
  7515. :
  7516. 1; // adler32(0, Z_NULL, 0)
  7517. s.last_flush = Z_NO_FLUSH;
  7518. trees._tr_init(s);
  7519. return Z_OK;
  7520. }
  7521.  
  7522.  
  7523. function deflateReset(strm) {
  7524. var ret = deflateResetKeep(strm);
  7525. if (ret === Z_OK) {
  7526. lm_init(strm.state);
  7527. }
  7528. return ret;
  7529. }
  7530.  
  7531.  
  7532. function deflateSetHeader(strm, head) {
  7533. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7534. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  7535. strm.state.gzhead = head;
  7536. return Z_OK;
  7537. }
  7538.  
  7539.  
  7540. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  7541. if (!strm) { // === Z_NULL
  7542. return Z_STREAM_ERROR;
  7543. }
  7544. var wrap = 1;
  7545.  
  7546. if (level === Z_DEFAULT_COMPRESSION) {
  7547. level = 6;
  7548. }
  7549.  
  7550. if (windowBits < 0) { /* suppress zlib wrapper */
  7551. wrap = 0;
  7552. windowBits = -windowBits;
  7553. }
  7554.  
  7555. else if (windowBits > 15) {
  7556. wrap = 2; /* write gzip wrapper instead */
  7557. windowBits -= 16;
  7558. }
  7559.  
  7560.  
  7561. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  7562. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  7563. strategy < 0 || strategy > Z_FIXED) {
  7564. return err(strm, Z_STREAM_ERROR);
  7565. }
  7566.  
  7567.  
  7568. if (windowBits === 8) {
  7569. windowBits = 9;
  7570. }
  7571. /* until 256-byte window bug fixed */
  7572.  
  7573. var s = new DeflateState();
  7574.  
  7575. strm.state = s;
  7576. s.strm = strm;
  7577.  
  7578. s.wrap = wrap;
  7579. s.gzhead = null;
  7580. s.w_bits = windowBits;
  7581. s.w_size = 1 << s.w_bits;
  7582. s.w_mask = s.w_size - 1;
  7583.  
  7584. s.hash_bits = memLevel + 7;
  7585. s.hash_size = 1 << s.hash_bits;
  7586. s.hash_mask = s.hash_size - 1;
  7587. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  7588.  
  7589. s.window = new utils.Buf8(s.w_size * 2);
  7590. s.head = new utils.Buf16(s.hash_size);
  7591. s.prev = new utils.Buf16(s.w_size);
  7592.  
  7593. // Don't need mem init magic for JS.
  7594. //s.high_water = 0; /* nothing written to s->window yet */
  7595.  
  7596. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  7597.  
  7598. s.pending_buf_size = s.lit_bufsize * 4;
  7599.  
  7600. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  7601. //s->pending_buf = (uchf *) overlay;
  7602. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  7603.  
  7604. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  7605. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  7606. s.d_buf = 1 * s.lit_bufsize;
  7607.  
  7608. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  7609. s.l_buf = (1 + 2) * s.lit_bufsize;
  7610.  
  7611. s.level = level;
  7612. s.strategy = strategy;
  7613. s.method = method;
  7614.  
  7615. return deflateReset(strm);
  7616. }
  7617.  
  7618. function deflateInit(strm, level) {
  7619. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  7620. }
  7621.  
  7622.  
  7623. function deflate(strm, flush) {
  7624. var old_flush, s;
  7625. var beg, val; // for gzip header write only
  7626.  
  7627. if (!strm || !strm.state ||
  7628. flush > Z_BLOCK || flush < 0) {
  7629. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  7630. }
  7631.  
  7632. s = strm.state;
  7633.  
  7634. if (!strm.output ||
  7635. (!strm.input && strm.avail_in !== 0) ||
  7636. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  7637. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  7638. }
  7639.  
  7640. s.strm = strm; /* just in case */
  7641. old_flush = s.last_flush;
  7642. s.last_flush = flush;
  7643.  
  7644. /* Write the header */
  7645. if (s.status === INIT_STATE) {
  7646.  
  7647. if (s.wrap === 2) { // GZIP header
  7648. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7649. put_byte(s, 31);
  7650. put_byte(s, 139);
  7651. put_byte(s, 8);
  7652. if (!s.gzhead) { // s->gzhead == Z_NULL
  7653. put_byte(s, 0);
  7654. put_byte(s, 0);
  7655. put_byte(s, 0);
  7656. put_byte(s, 0);
  7657. put_byte(s, 0);
  7658. put_byte(s, s.level === 9 ? 2 :
  7659. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7660. 4 : 0));
  7661. put_byte(s, OS_CODE);
  7662. s.status = BUSY_STATE;
  7663. }
  7664. else {
  7665. put_byte(s, (s.gzhead.text ? 1 : 0) +
  7666. (s.gzhead.hcrc ? 2 : 0) +
  7667. (!s.gzhead.extra ? 0 : 4) +
  7668. (!s.gzhead.name ? 0 : 8) +
  7669. (!s.gzhead.comment ? 0 : 16)
  7670. );
  7671. put_byte(s, s.gzhead.time & 0xff);
  7672. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  7673. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  7674. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  7675. put_byte(s, s.level === 9 ? 2 :
  7676. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7677. 4 : 0));
  7678. put_byte(s, s.gzhead.os & 0xff);
  7679. if (s.gzhead.extra && s.gzhead.extra.length) {
  7680. put_byte(s, s.gzhead.extra.length & 0xff);
  7681. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  7682. }
  7683. if (s.gzhead.hcrc) {
  7684. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  7685. }
  7686. s.gzindex = 0;
  7687. s.status = EXTRA_STATE;
  7688. }
  7689. }
  7690. else // DEFLATE header
  7691. {
  7692. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  7693. var level_flags = -1;
  7694.  
  7695. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  7696. level_flags = 0;
  7697. } else if (s.level < 6) {
  7698. level_flags = 1;
  7699. } else if (s.level === 6) {
  7700. level_flags = 2;
  7701. } else {
  7702. level_flags = 3;
  7703. }
  7704. header |= (level_flags << 6);
  7705. if (s.strstart !== 0) { header |= PRESET_DICT; }
  7706. header += 31 - (header % 31);
  7707.  
  7708. s.status = BUSY_STATE;
  7709. putShortMSB(s, header);
  7710.  
  7711. /* Save the adler32 of the preset dictionary: */
  7712. if (s.strstart !== 0) {
  7713. putShortMSB(s, strm.adler >>> 16);
  7714. putShortMSB(s, strm.adler & 0xffff);
  7715. }
  7716. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  7717. }
  7718. }
  7719.  
  7720. //#ifdef GZIP
  7721. if (s.status === EXTRA_STATE) {
  7722. if (s.gzhead.extra/* != Z_NULL*/) {
  7723. beg = s.pending; /* start of bytes to update crc */
  7724.  
  7725. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  7726. if (s.pending === s.pending_buf_size) {
  7727. if (s.gzhead.hcrc && s.pending > beg) {
  7728. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7729. }
  7730. flush_pending(strm);
  7731. beg = s.pending;
  7732. if (s.pending === s.pending_buf_size) {
  7733. break;
  7734. }
  7735. }
  7736. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  7737. s.gzindex++;
  7738. }
  7739. if (s.gzhead.hcrc && s.pending > beg) {
  7740. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7741. }
  7742. if (s.gzindex === s.gzhead.extra.length) {
  7743. s.gzindex = 0;
  7744. s.status = NAME_STATE;
  7745. }
  7746. }
  7747. else {
  7748. s.status = NAME_STATE;
  7749. }
  7750. }
  7751. if (s.status === NAME_STATE) {
  7752. if (s.gzhead.name/* != Z_NULL*/) {
  7753. beg = s.pending; /* start of bytes to update crc */
  7754. //int val;
  7755.  
  7756. do {
  7757. if (s.pending === s.pending_buf_size) {
  7758. if (s.gzhead.hcrc && s.pending > beg) {
  7759. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7760. }
  7761. flush_pending(strm);
  7762. beg = s.pending;
  7763. if (s.pending === s.pending_buf_size) {
  7764. val = 1;
  7765. break;
  7766. }
  7767. }
  7768. // JS specific: little magic to add zero terminator to end of string
  7769. if (s.gzindex < s.gzhead.name.length) {
  7770. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  7771. } else {
  7772. val = 0;
  7773. }
  7774. put_byte(s, val);
  7775. } while (val !== 0);
  7776.  
  7777. if (s.gzhead.hcrc && s.pending > beg) {
  7778. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7779. }
  7780. if (val === 0) {
  7781. s.gzindex = 0;
  7782. s.status = COMMENT_STATE;
  7783. }
  7784. }
  7785. else {
  7786. s.status = COMMENT_STATE;
  7787. }
  7788. }
  7789. if (s.status === COMMENT_STATE) {
  7790. if (s.gzhead.comment/* != Z_NULL*/) {
  7791. beg = s.pending; /* start of bytes to update crc */
  7792. //int val;
  7793.  
  7794. do {
  7795. if (s.pending === s.pending_buf_size) {
  7796. if (s.gzhead.hcrc && s.pending > beg) {
  7797. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7798. }
  7799. flush_pending(strm);
  7800. beg = s.pending;
  7801. if (s.pending === s.pending_buf_size) {
  7802. val = 1;
  7803. break;
  7804. }
  7805. }
  7806. // JS specific: little magic to add zero terminator to end of string
  7807. if (s.gzindex < s.gzhead.comment.length) {
  7808. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  7809. } else {
  7810. val = 0;
  7811. }
  7812. put_byte(s, val);
  7813. } while (val !== 0);
  7814.  
  7815. if (s.gzhead.hcrc && s.pending > beg) {
  7816. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7817. }
  7818. if (val === 0) {
  7819. s.status = HCRC_STATE;
  7820. }
  7821. }
  7822. else {
  7823. s.status = HCRC_STATE;
  7824. }
  7825. }
  7826. if (s.status === HCRC_STATE) {
  7827. if (s.gzhead.hcrc) {
  7828. if (s.pending + 2 > s.pending_buf_size) {
  7829. flush_pending(strm);
  7830. }
  7831. if (s.pending + 2 <= s.pending_buf_size) {
  7832. put_byte(s, strm.adler & 0xff);
  7833. put_byte(s, (strm.adler >> 8) & 0xff);
  7834. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7835. s.status = BUSY_STATE;
  7836. }
  7837. }
  7838. else {
  7839. s.status = BUSY_STATE;
  7840. }
  7841. }
  7842. //#endif
  7843.  
  7844. /* Flush as much pending output as possible */
  7845. if (s.pending !== 0) {
  7846. flush_pending(strm);
  7847. if (strm.avail_out === 0) {
  7848. /* Since avail_out is 0, deflate will be called again with
  7849. * more output space, but possibly with both pending and
  7850. * avail_in equal to zero. There won't be anything to do,
  7851. * but this is not an error situation so make sure we
  7852. * return OK instead of BUF_ERROR at next call of deflate:
  7853. */
  7854. s.last_flush = -1;
  7855. return Z_OK;
  7856. }
  7857.  
  7858. /* Make sure there is something to do and avoid duplicate consecutive
  7859. * flushes. For repeated and useless calls with Z_FINISH, we keep
  7860. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  7861. */
  7862. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  7863. flush !== Z_FINISH) {
  7864. return err(strm, Z_BUF_ERROR);
  7865. }
  7866.  
  7867. /* User must not provide more input after the first FINISH: */
  7868. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  7869. return err(strm, Z_BUF_ERROR);
  7870. }
  7871.  
  7872. /* Start a new block or continue the current one.
  7873. */
  7874. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  7875. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  7876. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  7877. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  7878. configuration_table[s.level].func(s, flush));
  7879.  
  7880. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  7881. s.status = FINISH_STATE;
  7882. }
  7883. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  7884. if (strm.avail_out === 0) {
  7885. s.last_flush = -1;
  7886. /* avoid BUF_ERROR next call, see above */
  7887. }
  7888. return Z_OK;
  7889. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  7890. * of deflate should use the same flush parameter to make sure
  7891. * that the flush is complete. So we don't have to output an
  7892. * empty block here, this will be done at next call. This also
  7893. * ensures that for a very small output buffer, we emit at most
  7894. * one empty block.
  7895. */
  7896. }
  7897. if (bstate === BS_BLOCK_DONE) {
  7898. if (flush === Z_PARTIAL_FLUSH) {
  7899. trees._tr_align(s);
  7900. }
  7901. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  7902.  
  7903. trees._tr_stored_block(s, 0, 0, false);
  7904. /* For a full flush, this empty block will be recognized
  7905. * as a special marker by inflate_sync().
  7906. */
  7907. if (flush === Z_FULL_FLUSH) {
  7908. /*** CLEAR_HASH(s); ***/ /* forget history */
  7909. zero(s.head); // Fill with NIL (= 0);
  7910.  
  7911. if (s.lookahead === 0) {
  7912. s.strstart = 0;
  7913. s.block_start = 0;
  7914. s.insert = 0;
  7915. }
  7916. }
  7917. }
  7918. flush_pending(strm);
  7919. if (strm.avail_out === 0) {
  7920. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  7921. return Z_OK;
  7922. }
  7923. }
  7924. }
  7925. //Assert(strm->avail_out > 0, "bug2");
  7926. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  7927.  
  7928. if (flush !== Z_FINISH) { return Z_OK; }
  7929. if (s.wrap <= 0) { return Z_STREAM_END; }
  7930.  
  7931. /* Write the trailer */
  7932. if (s.wrap === 2) {
  7933. put_byte(s, strm.adler & 0xff);
  7934. put_byte(s, (strm.adler >> 8) & 0xff);
  7935. put_byte(s, (strm.adler >> 16) & 0xff);
  7936. put_byte(s, (strm.adler >> 24) & 0xff);
  7937. put_byte(s, strm.total_in & 0xff);
  7938. put_byte(s, (strm.total_in >> 8) & 0xff);
  7939. put_byte(s, (strm.total_in >> 16) & 0xff);
  7940. put_byte(s, (strm.total_in >> 24) & 0xff);
  7941. }
  7942. else
  7943. {
  7944. putShortMSB(s, strm.adler >>> 16);
  7945. putShortMSB(s, strm.adler & 0xffff);
  7946. }
  7947.  
  7948. flush_pending(strm);
  7949. /* If avail_out is zero, the application will call deflate again
  7950. * to flush the rest.
  7951. */
  7952. if (s.wrap > 0) { s.wrap = -s.wrap; }
  7953. /* write the trailer only once! */
  7954. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  7955. }
  7956.  
  7957. function deflateEnd(strm) {
  7958. var status;
  7959.  
  7960. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7961. return Z_STREAM_ERROR;
  7962. }
  7963.  
  7964. status = strm.state.status;
  7965. if (status !== INIT_STATE &&
  7966. status !== EXTRA_STATE &&
  7967. status !== NAME_STATE &&
  7968. status !== COMMENT_STATE &&
  7969. status !== HCRC_STATE &&
  7970. status !== BUSY_STATE &&
  7971. status !== FINISH_STATE
  7972. ) {
  7973. return err(strm, Z_STREAM_ERROR);
  7974. }
  7975.  
  7976. strm.state = null;
  7977.  
  7978. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  7979. }
  7980.  
  7981.  
  7982. /* =========================================================================
  7983. * Initializes the compression dictionary from the given byte
  7984. * sequence without producing any compressed output.
  7985. */
  7986. function deflateSetDictionary(strm, dictionary) {
  7987. var dictLength = dictionary.length;
  7988.  
  7989. var s;
  7990. var str, n;
  7991. var wrap;
  7992. var avail;
  7993. var next;
  7994. var input;
  7995. var tmpDict;
  7996.  
  7997. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7998. return Z_STREAM_ERROR;
  7999. }
  8000.  
  8001. s = strm.state;
  8002. wrap = s.wrap;
  8003.  
  8004. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  8005. return Z_STREAM_ERROR;
  8006. }
  8007.  
  8008. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  8009. if (wrap === 1) {
  8010. /* adler32(strm->adler, dictionary, dictLength); */
  8011. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  8012. }
  8013.  
  8014. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  8015.  
  8016. /* if dictionary would fill window, just replace the history */
  8017. if (dictLength >= s.w_size) {
  8018. if (wrap === 0) { /* already empty otherwise */
  8019. /*** CLEAR_HASH(s); ***/
  8020. zero(s.head); // Fill with NIL (= 0);
  8021. s.strstart = 0;
  8022. s.block_start = 0;
  8023. s.insert = 0;
  8024. }
  8025. /* use the tail */
  8026. // dictionary = dictionary.slice(dictLength - s.w_size);
  8027. tmpDict = new utils.Buf8(s.w_size);
  8028. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  8029. dictionary = tmpDict;
  8030. dictLength = s.w_size;
  8031. }
  8032. /* insert dictionary into window and hash */
  8033. avail = strm.avail_in;
  8034. next = strm.next_in;
  8035. input = strm.input;
  8036. strm.avail_in = dictLength;
  8037. strm.next_in = 0;
  8038. strm.input = dictionary;
  8039. fill_window(s);
  8040. while (s.lookahead >= MIN_MATCH) {
  8041. str = s.strstart;
  8042. n = s.lookahead - (MIN_MATCH - 1);
  8043. do {
  8044. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  8045. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  8046.  
  8047. s.prev[str & s.w_mask] = s.head[s.ins_h];
  8048.  
  8049. s.head[s.ins_h] = str;
  8050. str++;
  8051. } while (--n);
  8052. s.strstart = str;
  8053. s.lookahead = MIN_MATCH - 1;
  8054. fill_window(s);
  8055. }
  8056. s.strstart += s.lookahead;
  8057. s.block_start = s.strstart;
  8058. s.insert = s.lookahead;
  8059. s.lookahead = 0;
  8060. s.match_length = s.prev_length = MIN_MATCH - 1;
  8061. s.match_available = 0;
  8062. strm.next_in = next;
  8063. strm.input = input;
  8064. strm.avail_in = avail;
  8065. s.wrap = wrap;
  8066. return Z_OK;
  8067. }
  8068.  
  8069.  
  8070. exports.deflateInit = deflateInit;
  8071. exports.deflateInit2 = deflateInit2;
  8072. exports.deflateReset = deflateReset;
  8073. exports.deflateResetKeep = deflateResetKeep;
  8074. exports.deflateSetHeader = deflateSetHeader;
  8075. exports.deflate = deflate;
  8076. exports.deflateEnd = deflateEnd;
  8077. exports.deflateSetDictionary = deflateSetDictionary;
  8078. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  8079.  
  8080. /* Not implemented
  8081. exports.deflateBound = deflateBound;
  8082. exports.deflateCopy = deflateCopy;
  8083. exports.deflateParams = deflateParams;
  8084. exports.deflatePending = deflatePending;
  8085. exports.deflatePrime = deflatePrime;
  8086. exports.deflateTune = deflateTune;
  8087. */
  8088.  
  8089. },{"../utils/common":62,"./adler32":64,"./crc32":66,"./messages":72,"./trees":73}],68:[function(require,module,exports){
  8090. 'use strict';
  8091.  
  8092. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8093. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8094. //
  8095. // This software is provided 'as-is', without any express or implied
  8096. // warranty. In no event will the authors be held liable for any damages
  8097. // arising from the use of this software.
  8098. //
  8099. // Permission is granted to anyone to use this software for any purpose,
  8100. // including commercial applications, and to alter it and redistribute it
  8101. // freely, subject to the following restrictions:
  8102. //
  8103. // 1. The origin of this software must not be misrepresented; you must not
  8104. // claim that you wrote the original software. If you use this software
  8105. // in a product, an acknowledgment in the product documentation would be
  8106. // appreciated but is not required.
  8107. // 2. Altered source versions must be plainly marked as such, and must not be
  8108. // misrepresented as being the original software.
  8109. // 3. This notice may not be removed or altered from any source distribution.
  8110.  
  8111. function GZheader() {
  8112. /* true if compressed data believed to be text */
  8113. this.text = 0;
  8114. /* modification time */
  8115. this.time = 0;
  8116. /* extra flags (not used when writing a gzip file) */
  8117. this.xflags = 0;
  8118. /* operating system */
  8119. this.os = 0;
  8120. /* pointer to extra field or Z_NULL if none */
  8121. this.extra = null;
  8122. /* extra field length (valid if extra != Z_NULL) */
  8123. this.extra_len = 0; // Actually, we don't need it in JS,
  8124. // but leave for few code modifications
  8125.  
  8126. //
  8127. // Setup limits is not necessary because in js we should not preallocate memory
  8128. // for inflate use constant limit in 65536 bytes
  8129. //
  8130.  
  8131. /* space at extra (only when reading header) */
  8132. // this.extra_max = 0;
  8133. /* pointer to zero-terminated file name or Z_NULL */
  8134. this.name = '';
  8135. /* space at name (only when reading header) */
  8136. // this.name_max = 0;
  8137. /* pointer to zero-terminated comment or Z_NULL */
  8138. this.comment = '';
  8139. /* space at comment (only when reading header) */
  8140. // this.comm_max = 0;
  8141. /* true if there was or will be a header crc */
  8142. this.hcrc = 0;
  8143. /* true when done reading gzip header (not used when writing a gzip file) */
  8144. this.done = false;
  8145. }
  8146.  
  8147. module.exports = GZheader;
  8148.  
  8149. },{}],69:[function(require,module,exports){
  8150. 'use strict';
  8151.  
  8152. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8153. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8154. //
  8155. // This software is provided 'as-is', without any express or implied
  8156. // warranty. In no event will the authors be held liable for any damages
  8157. // arising from the use of this software.
  8158. //
  8159. // Permission is granted to anyone to use this software for any purpose,
  8160. // including commercial applications, and to alter it and redistribute it
  8161. // freely, subject to the following restrictions:
  8162. //
  8163. // 1. The origin of this software must not be misrepresented; you must not
  8164. // claim that you wrote the original software. If you use this software
  8165. // in a product, an acknowledgment in the product documentation would be
  8166. // appreciated but is not required.
  8167. // 2. Altered source versions must be plainly marked as such, and must not be
  8168. // misrepresented as being the original software.
  8169. // 3. This notice may not be removed or altered from any source distribution.
  8170.  
  8171. // See state defs from inflate.js
  8172. var BAD = 30; /* got a data error -- remain here until reset */
  8173. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  8174.  
  8175. /*
  8176. Decode literal, length, and distance codes and write out the resulting
  8177. literal and match bytes until either not enough input or output is
  8178. available, an end-of-block is encountered, or a data error is encountered.
  8179. When large enough input and output buffers are supplied to inflate(), for
  8180. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  8181. inflate execution time is spent in this routine.
  8182.  
  8183. Entry assumptions:
  8184.  
  8185. state.mode === LEN
  8186. strm.avail_in >= 6
  8187. strm.avail_out >= 258
  8188. start >= strm.avail_out
  8189. state.bits < 8
  8190.  
  8191. On return, state.mode is one of:
  8192.  
  8193. LEN -- ran out of enough output space or enough available input
  8194. TYPE -- reached end of block code, inflate() to interpret next block
  8195. BAD -- error in block data
  8196.  
  8197. Notes:
  8198.  
  8199. - The maximum input bits used by a length/distance pair is 15 bits for the
  8200. length code, 5 bits for the length extra, 15 bits for the distance code,
  8201. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  8202. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  8203. checking for available input while decoding.
  8204.  
  8205. - The maximum bytes that a single length/distance pair can output is 258
  8206. bytes, which is the maximum length that can be coded. inflate_fast()
  8207. requires strm.avail_out >= 258 for each loop to avoid checking for
  8208. output space.
  8209. */
  8210. module.exports = function inflate_fast(strm, start) {
  8211. var state;
  8212. var _in; /* local strm.input */
  8213. var last; /* have enough input while in < last */
  8214. var _out; /* local strm.output */
  8215. var beg; /* inflate()'s initial strm.output */
  8216. var end; /* while out < end, enough space available */
  8217. //#ifdef INFLATE_STRICT
  8218. var dmax; /* maximum distance from zlib header */
  8219. //#endif
  8220. var wsize; /* window size or zero if not using window */
  8221. var whave; /* valid bytes in the window */
  8222. var wnext; /* window write index */
  8223. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  8224. var s_window; /* allocated sliding window, if wsize != 0 */
  8225. var hold; /* local strm.hold */
  8226. var bits; /* local strm.bits */
  8227. var lcode; /* local strm.lencode */
  8228. var dcode; /* local strm.distcode */
  8229. var lmask; /* mask for first level of length codes */
  8230. var dmask; /* mask for first level of distance codes */
  8231. var here; /* retrieved table entry */
  8232. var op; /* code bits, operation, extra bits, or */
  8233. /* window position, window bytes to copy */
  8234. var len; /* match length, unused bytes */
  8235. var dist; /* match distance */
  8236. var from; /* where to copy match from */
  8237. var from_source;
  8238.  
  8239.  
  8240. var input, output; // JS specific, because we have no pointers
  8241.  
  8242. /* copy state to local variables */
  8243. state = strm.state;
  8244. //here = state.here;
  8245. _in = strm.next_in;
  8246. input = strm.input;
  8247. last = _in + (strm.avail_in - 5);
  8248. _out = strm.next_out;
  8249. output = strm.output;
  8250. beg = _out - (start - strm.avail_out);
  8251. end = _out + (strm.avail_out - 257);
  8252. //#ifdef INFLATE_STRICT
  8253. dmax = state.dmax;
  8254. //#endif
  8255. wsize = state.wsize;
  8256. whave = state.whave;
  8257. wnext = state.wnext;
  8258. s_window = state.window;
  8259. hold = state.hold;
  8260. bits = state.bits;
  8261. lcode = state.lencode;
  8262. dcode = state.distcode;
  8263. lmask = (1 << state.lenbits) - 1;
  8264. dmask = (1 << state.distbits) - 1;
  8265.  
  8266.  
  8267. /* decode literals and length/distances until end-of-block or not enough
  8268. input data or output space */
  8269.  
  8270. top:
  8271. do {
  8272. if (bits < 15) {
  8273. hold += input[_in++] << bits;
  8274. bits += 8;
  8275. hold += input[_in++] << bits;
  8276. bits += 8;
  8277. }
  8278.  
  8279. here = lcode[hold & lmask];
  8280.  
  8281. dolen:
  8282. for (;;) { // Goto emulation
  8283. op = here >>> 24/*here.bits*/;
  8284. hold >>>= op;
  8285. bits -= op;
  8286. op = (here >>> 16) & 0xff/*here.op*/;
  8287. if (op === 0) { /* literal */
  8288. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8289. // "inflate: literal '%c'\n" :
  8290. // "inflate: literal 0x%02x\n", here.val));
  8291. output[_out++] = here & 0xffff/*here.val*/;
  8292. }
  8293. else if (op & 16) { /* length base */
  8294. len = here & 0xffff/*here.val*/;
  8295. op &= 15; /* number of extra bits */
  8296. if (op) {
  8297. if (bits < op) {
  8298. hold += input[_in++] << bits;
  8299. bits += 8;
  8300. }
  8301. len += hold & ((1 << op) - 1);
  8302. hold >>>= op;
  8303. bits -= op;
  8304. }
  8305. //Tracevv((stderr, "inflate: length %u\n", len));
  8306. if (bits < 15) {
  8307. hold += input[_in++] << bits;
  8308. bits += 8;
  8309. hold += input[_in++] << bits;
  8310. bits += 8;
  8311. }
  8312. here = dcode[hold & dmask];
  8313.  
  8314. dodist:
  8315. for (;;) { // goto emulation
  8316. op = here >>> 24/*here.bits*/;
  8317. hold >>>= op;
  8318. bits -= op;
  8319. op = (here >>> 16) & 0xff/*here.op*/;
  8320.  
  8321. if (op & 16) { /* distance base */
  8322. dist = here & 0xffff/*here.val*/;
  8323. op &= 15; /* number of extra bits */
  8324. if (bits < op) {
  8325. hold += input[_in++] << bits;
  8326. bits += 8;
  8327. if (bits < op) {
  8328. hold += input[_in++] << bits;
  8329. bits += 8;
  8330. }
  8331. }
  8332. dist += hold & ((1 << op) - 1);
  8333. //#ifdef INFLATE_STRICT
  8334. if (dist > dmax) {
  8335. strm.msg = 'invalid distance too far back';
  8336. state.mode = BAD;
  8337. break top;
  8338. }
  8339. //#endif
  8340. hold >>>= op;
  8341. bits -= op;
  8342. //Tracevv((stderr, "inflate: distance %u\n", dist));
  8343. op = _out - beg; /* max distance in output */
  8344. if (dist > op) { /* see if copy from window */
  8345. op = dist - op; /* distance back in window */
  8346. if (op > whave) {
  8347. if (state.sane) {
  8348. strm.msg = 'invalid distance too far back';
  8349. state.mode = BAD;
  8350. break top;
  8351. }
  8352.  
  8353. // (!) This block is disabled in zlib defailts,
  8354. // don't enable it for binary compatibility
  8355. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  8356. // if (len <= op - whave) {
  8357. // do {
  8358. // output[_out++] = 0;
  8359. // } while (--len);
  8360. // continue top;
  8361. // }
  8362. // len -= op - whave;
  8363. // do {
  8364. // output[_out++] = 0;
  8365. // } while (--op > whave);
  8366. // if (op === 0) {
  8367. // from = _out - dist;
  8368. // do {
  8369. // output[_out++] = output[from++];
  8370. // } while (--len);
  8371. // continue top;
  8372. // }
  8373. //#endif
  8374. }
  8375. from = 0; // window index
  8376. from_source = s_window;
  8377. if (wnext === 0) { /* very common case */
  8378. from += wsize - op;
  8379. if (op < len) { /* some from window */
  8380. len -= op;
  8381. do {
  8382. output[_out++] = s_window[from++];
  8383. } while (--op);
  8384. from = _out - dist; /* rest from output */
  8385. from_source = output;
  8386. }
  8387. }
  8388. else if (wnext < op) { /* wrap around window */
  8389. from += wsize + wnext - op;
  8390. op -= wnext;
  8391. if (op < len) { /* some from end of window */
  8392. len -= op;
  8393. do {
  8394. output[_out++] = s_window[from++];
  8395. } while (--op);
  8396. from = 0;
  8397. if (wnext < len) { /* some from start of window */
  8398. op = wnext;
  8399. len -= op;
  8400. do {
  8401. output[_out++] = s_window[from++];
  8402. } while (--op);
  8403. from = _out - dist; /* rest from output */
  8404. from_source = output;
  8405. }
  8406. }
  8407. }
  8408. else { /* contiguous in window */
  8409. from += wnext - op;
  8410. if (op < len) { /* some from window */
  8411. len -= op;
  8412. do {
  8413. output[_out++] = s_window[from++];
  8414. } while (--op);
  8415. from = _out - dist; /* rest from output */
  8416. from_source = output;
  8417. }
  8418. }
  8419. while (len > 2) {
  8420. output[_out++] = from_source[from++];
  8421. output[_out++] = from_source[from++];
  8422. output[_out++] = from_source[from++];
  8423. len -= 3;
  8424. }
  8425. if (len) {
  8426. output[_out++] = from_source[from++];
  8427. if (len > 1) {
  8428. output[_out++] = from_source[from++];
  8429. }
  8430. }
  8431. }
  8432. else {
  8433. from = _out - dist; /* copy direct from output */
  8434. do { /* minimum length is three */
  8435. output[_out++] = output[from++];
  8436. output[_out++] = output[from++];
  8437. output[_out++] = output[from++];
  8438. len -= 3;
  8439. } while (len > 2);
  8440. if (len) {
  8441. output[_out++] = output[from++];
  8442. if (len > 1) {
  8443. output[_out++] = output[from++];
  8444. }
  8445. }
  8446. }
  8447. }
  8448. else if ((op & 64) === 0) { /* 2nd level distance code */
  8449. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8450. continue dodist;
  8451. }
  8452. else {
  8453. strm.msg = 'invalid distance code';
  8454. state.mode = BAD;
  8455. break top;
  8456. }
  8457.  
  8458. break; // need to emulate goto via "continue"
  8459. }
  8460. }
  8461. else if ((op & 64) === 0) { /* 2nd level length code */
  8462. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8463. continue dolen;
  8464. }
  8465. else if (op & 32) { /* end-of-block */
  8466. //Tracevv((stderr, "inflate: end of block\n"));
  8467. state.mode = TYPE;
  8468. break top;
  8469. }
  8470. else {
  8471. strm.msg = 'invalid literal/length code';
  8472. state.mode = BAD;
  8473. break top;
  8474. }
  8475.  
  8476. break; // need to emulate goto via "continue"
  8477. }
  8478. } while (_in < last && _out < end);
  8479.  
  8480. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  8481. len = bits >> 3;
  8482. _in -= len;
  8483. bits -= len << 3;
  8484. hold &= (1 << bits) - 1;
  8485.  
  8486. /* update state and return */
  8487. strm.next_in = _in;
  8488. strm.next_out = _out;
  8489. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  8490. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  8491. state.hold = hold;
  8492. state.bits = bits;
  8493. return;
  8494. };
  8495.  
  8496. },{}],70:[function(require,module,exports){
  8497. 'use strict';
  8498.  
  8499. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8500. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8501. //
  8502. // This software is provided 'as-is', without any express or implied
  8503. // warranty. In no event will the authors be held liable for any damages
  8504. // arising from the use of this software.
  8505. //
  8506. // Permission is granted to anyone to use this software for any purpose,
  8507. // including commercial applications, and to alter it and redistribute it
  8508. // freely, subject to the following restrictions:
  8509. //
  8510. // 1. The origin of this software must not be misrepresented; you must not
  8511. // claim that you wrote the original software. If you use this software
  8512. // in a product, an acknowledgment in the product documentation would be
  8513. // appreciated but is not required.
  8514. // 2. Altered source versions must be plainly marked as such, and must not be
  8515. // misrepresented as being the original software.
  8516. // 3. This notice may not be removed or altered from any source distribution.
  8517.  
  8518. var utils = require('../utils/common');
  8519. var adler32 = require('./adler32');
  8520. var crc32 = require('./crc32');
  8521. var inflate_fast = require('./inffast');
  8522. var inflate_table = require('./inftrees');
  8523.  
  8524. var CODES = 0;
  8525. var LENS = 1;
  8526. var DISTS = 2;
  8527.  
  8528. /* Public constants ==========================================================*/
  8529. /* ===========================================================================*/
  8530.  
  8531.  
  8532. /* Allowed flush values; see deflate() and inflate() below for details */
  8533. //var Z_NO_FLUSH = 0;
  8534. //var Z_PARTIAL_FLUSH = 1;
  8535. //var Z_SYNC_FLUSH = 2;
  8536. //var Z_FULL_FLUSH = 3;
  8537. var Z_FINISH = 4;
  8538. var Z_BLOCK = 5;
  8539. var Z_TREES = 6;
  8540.  
  8541.  
  8542. /* Return codes for the compression/decompression functions. Negative values
  8543. * are errors, positive values are used for special but normal events.
  8544. */
  8545. var Z_OK = 0;
  8546. var Z_STREAM_END = 1;
  8547. var Z_NEED_DICT = 2;
  8548. //var Z_ERRNO = -1;
  8549. var Z_STREAM_ERROR = -2;
  8550. var Z_DATA_ERROR = -3;
  8551. var Z_MEM_ERROR = -4;
  8552. var Z_BUF_ERROR = -5;
  8553. //var Z_VERSION_ERROR = -6;
  8554.  
  8555. /* The deflate compression method */
  8556. var Z_DEFLATED = 8;
  8557.  
  8558.  
  8559. /* STATES ====================================================================*/
  8560. /* ===========================================================================*/
  8561.  
  8562.  
  8563. var HEAD = 1; /* i: waiting for magic header */
  8564. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  8565. var TIME = 3; /* i: waiting for modification time (gzip) */
  8566. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  8567. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  8568. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  8569. var NAME = 7; /* i: waiting for end of file name (gzip) */
  8570. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  8571. var HCRC = 9; /* i: waiting for header crc (gzip) */
  8572. var DICTID = 10; /* i: waiting for dictionary check value */
  8573. var DICT = 11; /* waiting for inflateSetDictionary() call */
  8574. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  8575. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  8576. var STORED = 14; /* i: waiting for stored size (length and complement) */
  8577. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  8578. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  8579. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  8580. var LENLENS = 18; /* i: waiting for code length code lengths */
  8581. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  8582. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  8583. var LEN = 21; /* i: waiting for length/lit/eob code */
  8584. var LENEXT = 22; /* i: waiting for length extra bits */
  8585. var DIST = 23; /* i: waiting for distance code */
  8586. var DISTEXT = 24; /* i: waiting for distance extra bits */
  8587. var MATCH = 25; /* o: waiting for output space to copy string */
  8588. var LIT = 26; /* o: waiting for output space to write literal */
  8589. var CHECK = 27; /* i: waiting for 32-bit check value */
  8590. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  8591. var DONE = 29; /* finished check, done -- remain here until reset */
  8592. var BAD = 30; /* got a data error -- remain here until reset */
  8593. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  8594. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  8595.  
  8596. /* ===========================================================================*/
  8597.  
  8598.  
  8599.  
  8600. var ENOUGH_LENS = 852;
  8601. var ENOUGH_DISTS = 592;
  8602. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  8603.  
  8604. var MAX_WBITS = 15;
  8605. /* 32K LZ77 window */
  8606. var DEF_WBITS = MAX_WBITS;
  8607.  
  8608.  
  8609. function zswap32(q) {
  8610. return (((q >>> 24) & 0xff) +
  8611. ((q >>> 8) & 0xff00) +
  8612. ((q & 0xff00) << 8) +
  8613. ((q & 0xff) << 24));
  8614. }
  8615.  
  8616.  
  8617. function InflateState() {
  8618. this.mode = 0; /* current inflate mode */
  8619. this.last = false; /* true if processing last block */
  8620. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  8621. this.havedict = false; /* true if dictionary provided */
  8622. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  8623. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  8624. this.check = 0; /* protected copy of check value */
  8625. this.total = 0; /* protected copy of output count */
  8626. // TODO: may be {}
  8627. this.head = null; /* where to save gzip header information */
  8628.  
  8629. /* sliding window */
  8630. this.wbits = 0; /* log base 2 of requested window size */
  8631. this.wsize = 0; /* window size or zero if not using window */
  8632. this.whave = 0; /* valid bytes in the window */
  8633. this.wnext = 0; /* window write index */
  8634. this.window = null; /* allocated sliding window, if needed */
  8635.  
  8636. /* bit accumulator */
  8637. this.hold = 0; /* input bit accumulator */
  8638. this.bits = 0; /* number of bits in "in" */
  8639.  
  8640. /* for string and stored block copying */
  8641. this.length = 0; /* literal or length of data to copy */
  8642. this.offset = 0; /* distance back to copy string from */
  8643.  
  8644. /* for table and code decoding */
  8645. this.extra = 0; /* extra bits needed */
  8646.  
  8647. /* fixed and dynamic code tables */
  8648. this.lencode = null; /* starting table for length/literal codes */
  8649. this.distcode = null; /* starting table for distance codes */
  8650. this.lenbits = 0; /* index bits for lencode */
  8651. this.distbits = 0; /* index bits for distcode */
  8652.  
  8653. /* dynamic table building */
  8654. this.ncode = 0; /* number of code length code lengths */
  8655. this.nlen = 0; /* number of length code lengths */
  8656. this.ndist = 0; /* number of distance code lengths */
  8657. this.have = 0; /* number of code lengths in lens[] */
  8658. this.next = null; /* next available space in codes[] */
  8659.  
  8660. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  8661. this.work = new utils.Buf16(288); /* work area for code table building */
  8662.  
  8663. /*
  8664. because we don't have pointers in js, we use lencode and distcode directly
  8665. as buffers so we don't need codes
  8666. */
  8667. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  8668. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  8669. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  8670. this.sane = 0; /* if false, allow invalid distance too far */
  8671. this.back = 0; /* bits back of last unprocessed length/lit */
  8672. this.was = 0; /* initial length of match */
  8673. }
  8674.  
  8675. function inflateResetKeep(strm) {
  8676. var state;
  8677.  
  8678. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8679. state = strm.state;
  8680. strm.total_in = strm.total_out = state.total = 0;
  8681. strm.msg = ''; /*Z_NULL*/
  8682. if (state.wrap) { /* to support ill-conceived Java test suite */
  8683. strm.adler = state.wrap & 1;
  8684. }
  8685. state.mode = HEAD;
  8686. state.last = 0;
  8687. state.havedict = 0;
  8688. state.dmax = 32768;
  8689. state.head = null/*Z_NULL*/;
  8690. state.hold = 0;
  8691. state.bits = 0;
  8692. //state.lencode = state.distcode = state.next = state.codes;
  8693. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  8694. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  8695.  
  8696. state.sane = 1;
  8697. state.back = -1;
  8698. //Tracev((stderr, "inflate: reset\n"));
  8699. return Z_OK;
  8700. }
  8701.  
  8702. function inflateReset(strm) {
  8703. var state;
  8704.  
  8705. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8706. state = strm.state;
  8707. state.wsize = 0;
  8708. state.whave = 0;
  8709. state.wnext = 0;
  8710. return inflateResetKeep(strm);
  8711.  
  8712. }
  8713.  
  8714. function inflateReset2(strm, windowBits) {
  8715. var wrap;
  8716. var state;
  8717.  
  8718. /* get the state */
  8719. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8720. state = strm.state;
  8721.  
  8722. /* extract wrap request from windowBits parameter */
  8723. if (windowBits < 0) {
  8724. wrap = 0;
  8725. windowBits = -windowBits;
  8726. }
  8727. else {
  8728. wrap = (windowBits >> 4) + 1;
  8729. if (windowBits < 48) {
  8730. windowBits &= 15;
  8731. }
  8732. }
  8733.  
  8734. /* set number of window bits, free window if different */
  8735. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  8736. return Z_STREAM_ERROR;
  8737. }
  8738. if (state.window !== null && state.wbits !== windowBits) {
  8739. state.window = null;
  8740. }
  8741.  
  8742. /* update state and reset the rest of it */
  8743. state.wrap = wrap;
  8744. state.wbits = windowBits;
  8745. return inflateReset(strm);
  8746. }
  8747.  
  8748. function inflateInit2(strm, windowBits) {
  8749. var ret;
  8750. var state;
  8751.  
  8752. if (!strm) { return Z_STREAM_ERROR; }
  8753. //strm.msg = Z_NULL; /* in case we return an error */
  8754.  
  8755. state = new InflateState();
  8756.  
  8757. //if (state === Z_NULL) return Z_MEM_ERROR;
  8758. //Tracev((stderr, "inflate: allocated\n"));
  8759. strm.state = state;
  8760. state.window = null/*Z_NULL*/;
  8761. ret = inflateReset2(strm, windowBits);
  8762. if (ret !== Z_OK) {
  8763. strm.state = null/*Z_NULL*/;
  8764. }
  8765. return ret;
  8766. }
  8767.  
  8768. function inflateInit(strm) {
  8769. return inflateInit2(strm, DEF_WBITS);
  8770. }
  8771.  
  8772.  
  8773. /*
  8774. Return state with length and distance decoding tables and index sizes set to
  8775. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  8776. If BUILDFIXED is defined, then instead this routine builds the tables the
  8777. first time it's called, and returns those tables the first time and
  8778. thereafter. This reduces the size of the code by about 2K bytes, in
  8779. exchange for a little execution time. However, BUILDFIXED should not be
  8780. used for threaded applications, since the rewriting of the tables and virgin
  8781. may not be thread-safe.
  8782. */
  8783. var virgin = true;
  8784.  
  8785. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  8786.  
  8787. function fixedtables(state) {
  8788. /* build fixed huffman tables if first call (may not be thread safe) */
  8789. if (virgin) {
  8790. var sym;
  8791.  
  8792. lenfix = new utils.Buf32(512);
  8793. distfix = new utils.Buf32(32);
  8794.  
  8795. /* literal/length table */
  8796. sym = 0;
  8797. while (sym < 144) { state.lens[sym++] = 8; }
  8798. while (sym < 256) { state.lens[sym++] = 9; }
  8799. while (sym < 280) { state.lens[sym++] = 7; }
  8800. while (sym < 288) { state.lens[sym++] = 8; }
  8801.  
  8802. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  8803.  
  8804. /* distance table */
  8805. sym = 0;
  8806. while (sym < 32) { state.lens[sym++] = 5; }
  8807.  
  8808. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  8809.  
  8810. /* do this just once */
  8811. virgin = false;
  8812. }
  8813.  
  8814. state.lencode = lenfix;
  8815. state.lenbits = 9;
  8816. state.distcode = distfix;
  8817. state.distbits = 5;
  8818. }
  8819.  
  8820.  
  8821. /*
  8822. Update the window with the last wsize (normally 32K) bytes written before
  8823. returning. If window does not exist yet, create it. This is only called
  8824. when a window is already in use, or when output has been written during this
  8825. inflate call, but the end of the deflate stream has not been reached yet.
  8826. It is also called to create a window for dictionary data when a dictionary
  8827. is loaded.
  8828.  
  8829. Providing output buffers larger than 32K to inflate() should provide a speed
  8830. advantage, since only the last 32K of output is copied to the sliding window
  8831. upon return from inflate(), and since all distances after the first 32K of
  8832. output will fall in the output data, making match copies simpler and faster.
  8833. The advantage may be dependent on the size of the processor's data caches.
  8834. */
  8835. function updatewindow(strm, src, end, copy) {
  8836. var dist;
  8837. var state = strm.state;
  8838.  
  8839. /* if it hasn't been done already, allocate space for the window */
  8840. if (state.window === null) {
  8841. state.wsize = 1 << state.wbits;
  8842. state.wnext = 0;
  8843. state.whave = 0;
  8844.  
  8845. state.window = new utils.Buf8(state.wsize);
  8846. }
  8847.  
  8848. /* copy state->wsize or less output bytes into the circular window */
  8849. if (copy >= state.wsize) {
  8850. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  8851. state.wnext = 0;
  8852. state.whave = state.wsize;
  8853. }
  8854. else {
  8855. dist = state.wsize - state.wnext;
  8856. if (dist > copy) {
  8857. dist = copy;
  8858. }
  8859. //zmemcpy(state->window + state->wnext, end - copy, dist);
  8860. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  8861. copy -= dist;
  8862. if (copy) {
  8863. //zmemcpy(state->window, end - copy, copy);
  8864. utils.arraySet(state.window, src, end - copy, copy, 0);
  8865. state.wnext = copy;
  8866. state.whave = state.wsize;
  8867. }
  8868. else {
  8869. state.wnext += dist;
  8870. if (state.wnext === state.wsize) { state.wnext = 0; }
  8871. if (state.whave < state.wsize) { state.whave += dist; }
  8872. }
  8873. }
  8874. return 0;
  8875. }
  8876.  
  8877. function inflate(strm, flush) {
  8878. var state;
  8879. var input, output; // input/output buffers
  8880. var next; /* next input INDEX */
  8881. var put; /* next output INDEX */
  8882. var have, left; /* available input and output */
  8883. var hold; /* bit buffer */
  8884. var bits; /* bits in bit buffer */
  8885. var _in, _out; /* save starting available input and output */
  8886. var copy; /* number of stored or match bytes to copy */
  8887. var from; /* where to copy match bytes from */
  8888. var from_source;
  8889. var here = 0; /* current decoding table entry */
  8890. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  8891. //var last; /* parent table entry */
  8892. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  8893. var len; /* length to copy for repeats, bits to drop */
  8894. var ret; /* return code */
  8895. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  8896. var opts;
  8897.  
  8898. var n; // temporary var for NEED_BITS
  8899.  
  8900. var order = /* permutation of code lengths */
  8901. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  8902.  
  8903.  
  8904. if (!strm || !strm.state || !strm.output ||
  8905. (!strm.input && strm.avail_in !== 0)) {
  8906. return Z_STREAM_ERROR;
  8907. }
  8908.  
  8909. state = strm.state;
  8910. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  8911.  
  8912.  
  8913. //--- LOAD() ---
  8914. put = strm.next_out;
  8915. output = strm.output;
  8916. left = strm.avail_out;
  8917. next = strm.next_in;
  8918. input = strm.input;
  8919. have = strm.avail_in;
  8920. hold = state.hold;
  8921. bits = state.bits;
  8922. //---
  8923.  
  8924. _in = have;
  8925. _out = left;
  8926. ret = Z_OK;
  8927.  
  8928. inf_leave: // goto emulation
  8929. for (;;) {
  8930. switch (state.mode) {
  8931. case HEAD:
  8932. if (state.wrap === 0) {
  8933. state.mode = TYPEDO;
  8934. break;
  8935. }
  8936. //=== NEEDBITS(16);
  8937. while (bits < 16) {
  8938. if (have === 0) { break inf_leave; }
  8939. have--;
  8940. hold += input[next++] << bits;
  8941. bits += 8;
  8942. }
  8943. //===//
  8944. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  8945. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  8946. //=== CRC2(state.check, hold);
  8947. hbuf[0] = hold & 0xff;
  8948. hbuf[1] = (hold >>> 8) & 0xff;
  8949. state.check = crc32(state.check, hbuf, 2, 0);
  8950. //===//
  8951.  
  8952. //=== INITBITS();
  8953. hold = 0;
  8954. bits = 0;
  8955. //===//
  8956. state.mode = FLAGS;
  8957. break;
  8958. }
  8959. state.flags = 0; /* expect zlib header */
  8960. if (state.head) {
  8961. state.head.done = false;
  8962. }
  8963. if (!(state.wrap & 1) || /* check if zlib header allowed */
  8964. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  8965. strm.msg = 'incorrect header check';
  8966. state.mode = BAD;
  8967. break;
  8968. }
  8969. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  8970. strm.msg = 'unknown compression method';
  8971. state.mode = BAD;
  8972. break;
  8973. }
  8974. //--- DROPBITS(4) ---//
  8975. hold >>>= 4;
  8976. bits -= 4;
  8977. //---//
  8978. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  8979. if (state.wbits === 0) {
  8980. state.wbits = len;
  8981. }
  8982. else if (len > state.wbits) {
  8983. strm.msg = 'invalid window size';
  8984. state.mode = BAD;
  8985. break;
  8986. }
  8987. state.dmax = 1 << len;
  8988. //Tracev((stderr, "inflate: zlib header ok\n"));
  8989. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8990. state.mode = hold & 0x200 ? DICTID : TYPE;
  8991. //=== INITBITS();
  8992. hold = 0;
  8993. bits = 0;
  8994. //===//
  8995. break;
  8996. case FLAGS:
  8997. //=== NEEDBITS(16); */
  8998. while (bits < 16) {
  8999. if (have === 0) { break inf_leave; }
  9000. have--;
  9001. hold += input[next++] << bits;
  9002. bits += 8;
  9003. }
  9004. //===//
  9005. state.flags = hold;
  9006. if ((state.flags & 0xff) !== Z_DEFLATED) {
  9007. strm.msg = 'unknown compression method';
  9008. state.mode = BAD;
  9009. break;
  9010. }
  9011. if (state.flags & 0xe000) {
  9012. strm.msg = 'unknown header flags set';
  9013. state.mode = BAD;
  9014. break;
  9015. }
  9016. if (state.head) {
  9017. state.head.text = ((hold >> 8) & 1);
  9018. }
  9019. if (state.flags & 0x0200) {
  9020. //=== CRC2(state.check, hold);
  9021. hbuf[0] = hold & 0xff;
  9022. hbuf[1] = (hold >>> 8) & 0xff;
  9023. state.check = crc32(state.check, hbuf, 2, 0);
  9024. //===//
  9025. }
  9026. //=== INITBITS();
  9027. hold = 0;
  9028. bits = 0;
  9029. //===//
  9030. state.mode = TIME;
  9031. /* falls through */
  9032. case TIME:
  9033. //=== NEEDBITS(32); */
  9034. while (bits < 32) {
  9035. if (have === 0) { break inf_leave; }
  9036. have--;
  9037. hold += input[next++] << bits;
  9038. bits += 8;
  9039. }
  9040. //===//
  9041. if (state.head) {
  9042. state.head.time = hold;
  9043. }
  9044. if (state.flags & 0x0200) {
  9045. //=== CRC4(state.check, hold)
  9046. hbuf[0] = hold & 0xff;
  9047. hbuf[1] = (hold >>> 8) & 0xff;
  9048. hbuf[2] = (hold >>> 16) & 0xff;
  9049. hbuf[3] = (hold >>> 24) & 0xff;
  9050. state.check = crc32(state.check, hbuf, 4, 0);
  9051. //===
  9052. }
  9053. //=== INITBITS();
  9054. hold = 0;
  9055. bits = 0;
  9056. //===//
  9057. state.mode = OS;
  9058. /* falls through */
  9059. case OS:
  9060. //=== NEEDBITS(16); */
  9061. while (bits < 16) {
  9062. if (have === 0) { break inf_leave; }
  9063. have--;
  9064. hold += input[next++] << bits;
  9065. bits += 8;
  9066. }
  9067. //===//
  9068. if (state.head) {
  9069. state.head.xflags = (hold & 0xff);
  9070. state.head.os = (hold >> 8);
  9071. }
  9072. if (state.flags & 0x0200) {
  9073. //=== CRC2(state.check, hold);
  9074. hbuf[0] = hold & 0xff;
  9075. hbuf[1] = (hold >>> 8) & 0xff;
  9076. state.check = crc32(state.check, hbuf, 2, 0);
  9077. //===//
  9078. }
  9079. //=== INITBITS();
  9080. hold = 0;
  9081. bits = 0;
  9082. //===//
  9083. state.mode = EXLEN;
  9084. /* falls through */
  9085. case EXLEN:
  9086. if (state.flags & 0x0400) {
  9087. //=== NEEDBITS(16); */
  9088. while (bits < 16) {
  9089. if (have === 0) { break inf_leave; }
  9090. have--;
  9091. hold += input[next++] << bits;
  9092. bits += 8;
  9093. }
  9094. //===//
  9095. state.length = hold;
  9096. if (state.head) {
  9097. state.head.extra_len = hold;
  9098. }
  9099. if (state.flags & 0x0200) {
  9100. //=== CRC2(state.check, hold);
  9101. hbuf[0] = hold & 0xff;
  9102. hbuf[1] = (hold >>> 8) & 0xff;
  9103. state.check = crc32(state.check, hbuf, 2, 0);
  9104. //===//
  9105. }
  9106. //=== INITBITS();
  9107. hold = 0;
  9108. bits = 0;
  9109. //===//
  9110. }
  9111. else if (state.head) {
  9112. state.head.extra = null/*Z_NULL*/;
  9113. }
  9114. state.mode = EXTRA;
  9115. /* falls through */
  9116. case EXTRA:
  9117. if (state.flags & 0x0400) {
  9118. copy = state.length;
  9119. if (copy > have) { copy = have; }
  9120. if (copy) {
  9121. if (state.head) {
  9122. len = state.head.extra_len - state.length;
  9123. if (!state.head.extra) {
  9124. // Use untyped array for more conveniend processing later
  9125. state.head.extra = new Array(state.head.extra_len);
  9126. }
  9127. utils.arraySet(
  9128. state.head.extra,
  9129. input,
  9130. next,
  9131. // extra field is limited to 65536 bytes
  9132. // - no need for additional size check
  9133. copy,
  9134. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  9135. len
  9136. );
  9137. //zmemcpy(state.head.extra + len, next,
  9138. // len + copy > state.head.extra_max ?
  9139. // state.head.extra_max - len : copy);
  9140. }
  9141. if (state.flags & 0x0200) {
  9142. state.check = crc32(state.check, input, copy, next);
  9143. }
  9144. have -= copy;
  9145. next += copy;
  9146. state.length -= copy;
  9147. }
  9148. if (state.length) { break inf_leave; }
  9149. }
  9150. state.length = 0;
  9151. state.mode = NAME;
  9152. /* falls through */
  9153. case NAME:
  9154. if (state.flags & 0x0800) {
  9155. if (have === 0) { break inf_leave; }
  9156. copy = 0;
  9157. do {
  9158. // TODO: 2 or 1 bytes?
  9159. len = input[next + copy++];
  9160. /* use constant limit because in js we should not preallocate memory */
  9161. if (state.head && len &&
  9162. (state.length < 65536 /*state.head.name_max*/)) {
  9163. state.head.name += String.fromCharCode(len);
  9164. }
  9165. } while (len && copy < have);
  9166.  
  9167. if (state.flags & 0x0200) {
  9168. state.check = crc32(state.check, input, copy, next);
  9169. }
  9170. have -= copy;
  9171. next += copy;
  9172. if (len) { break inf_leave; }
  9173. }
  9174. else if (state.head) {
  9175. state.head.name = null;
  9176. }
  9177. state.length = 0;
  9178. state.mode = COMMENT;
  9179. /* falls through */
  9180. case COMMENT:
  9181. if (state.flags & 0x1000) {
  9182. if (have === 0) { break inf_leave; }
  9183. copy = 0;
  9184. do {
  9185. len = input[next + copy++];
  9186. /* use constant limit because in js we should not preallocate memory */
  9187. if (state.head && len &&
  9188. (state.length < 65536 /*state.head.comm_max*/)) {
  9189. state.head.comment += String.fromCharCode(len);
  9190. }
  9191. } while (len && copy < have);
  9192. if (state.flags & 0x0200) {
  9193. state.check = crc32(state.check, input, copy, next);
  9194. }
  9195. have -= copy;
  9196. next += copy;
  9197. if (len) { break inf_leave; }
  9198. }
  9199. else if (state.head) {
  9200. state.head.comment = null;
  9201. }
  9202. state.mode = HCRC;
  9203. /* falls through */
  9204. case HCRC:
  9205. if (state.flags & 0x0200) {
  9206. //=== NEEDBITS(16); */
  9207. while (bits < 16) {
  9208. if (have === 0) { break inf_leave; }
  9209. have--;
  9210. hold += input[next++] << bits;
  9211. bits += 8;
  9212. }
  9213. //===//
  9214. if (hold !== (state.check & 0xffff)) {
  9215. strm.msg = 'header crc mismatch';
  9216. state.mode = BAD;
  9217. break;
  9218. }
  9219. //=== INITBITS();
  9220. hold = 0;
  9221. bits = 0;
  9222. //===//
  9223. }
  9224. if (state.head) {
  9225. state.head.hcrc = ((state.flags >> 9) & 1);
  9226. state.head.done = true;
  9227. }
  9228. strm.adler = state.check = 0;
  9229. state.mode = TYPE;
  9230. break;
  9231. case DICTID:
  9232. //=== NEEDBITS(32); */
  9233. while (bits < 32) {
  9234. if (have === 0) { break inf_leave; }
  9235. have--;
  9236. hold += input[next++] << bits;
  9237. bits += 8;
  9238. }
  9239. //===//
  9240. strm.adler = state.check = zswap32(hold);
  9241. //=== INITBITS();
  9242. hold = 0;
  9243. bits = 0;
  9244. //===//
  9245. state.mode = DICT;
  9246. /* falls through */
  9247. case DICT:
  9248. if (state.havedict === 0) {
  9249. //--- RESTORE() ---
  9250. strm.next_out = put;
  9251. strm.avail_out = left;
  9252. strm.next_in = next;
  9253. strm.avail_in = have;
  9254. state.hold = hold;
  9255. state.bits = bits;
  9256. //---
  9257. return Z_NEED_DICT;
  9258. }
  9259. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  9260. state.mode = TYPE;
  9261. /* falls through */
  9262. case TYPE:
  9263. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  9264. /* falls through */
  9265. case TYPEDO:
  9266. if (state.last) {
  9267. //--- BYTEBITS() ---//
  9268. hold >>>= bits & 7;
  9269. bits -= bits & 7;
  9270. //---//
  9271. state.mode = CHECK;
  9272. break;
  9273. }
  9274. //=== NEEDBITS(3); */
  9275. while (bits < 3) {
  9276. if (have === 0) { break inf_leave; }
  9277. have--;
  9278. hold += input[next++] << bits;
  9279. bits += 8;
  9280. }
  9281. //===//
  9282. state.last = (hold & 0x01)/*BITS(1)*/;
  9283. //--- DROPBITS(1) ---//
  9284. hold >>>= 1;
  9285. bits -= 1;
  9286. //---//
  9287.  
  9288. switch ((hold & 0x03)/*BITS(2)*/) {
  9289. case 0: /* stored block */
  9290. //Tracev((stderr, "inflate: stored block%s\n",
  9291. // state.last ? " (last)" : ""));
  9292. state.mode = STORED;
  9293. break;
  9294. case 1: /* fixed block */
  9295. fixedtables(state);
  9296. //Tracev((stderr, "inflate: fixed codes block%s\n",
  9297. // state.last ? " (last)" : ""));
  9298. state.mode = LEN_; /* decode codes */
  9299. if (flush === Z_TREES) {
  9300. //--- DROPBITS(2) ---//
  9301. hold >>>= 2;
  9302. bits -= 2;
  9303. //---//
  9304. break inf_leave;
  9305. }
  9306. break;
  9307. case 2: /* dynamic block */
  9308. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  9309. // state.last ? " (last)" : ""));
  9310. state.mode = TABLE;
  9311. break;
  9312. case 3:
  9313. strm.msg = 'invalid block type';
  9314. state.mode = BAD;
  9315. }
  9316. //--- DROPBITS(2) ---//
  9317. hold >>>= 2;
  9318. bits -= 2;
  9319. //---//
  9320. break;
  9321. case STORED:
  9322. //--- BYTEBITS() ---// /* go to byte boundary */
  9323. hold >>>= bits & 7;
  9324. bits -= bits & 7;
  9325. //---//
  9326. //=== NEEDBITS(32); */
  9327. while (bits < 32) {
  9328. if (have === 0) { break inf_leave; }
  9329. have--;
  9330. hold += input[next++] << bits;
  9331. bits += 8;
  9332. }
  9333. //===//
  9334. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  9335. strm.msg = 'invalid stored block lengths';
  9336. state.mode = BAD;
  9337. break;
  9338. }
  9339. state.length = hold & 0xffff;
  9340. //Tracev((stderr, "inflate: stored length %u\n",
  9341. // state.length));
  9342. //=== INITBITS();
  9343. hold = 0;
  9344. bits = 0;
  9345. //===//
  9346. state.mode = COPY_;
  9347. if (flush === Z_TREES) { break inf_leave; }
  9348. /* falls through */
  9349. case COPY_:
  9350. state.mode = COPY;
  9351. /* falls through */
  9352. case COPY:
  9353. copy = state.length;
  9354. if (copy) {
  9355. if (copy > have) { copy = have; }
  9356. if (copy > left) { copy = left; }
  9357. if (copy === 0) { break inf_leave; }
  9358. //--- zmemcpy(put, next, copy); ---
  9359. utils.arraySet(output, input, next, copy, put);
  9360. //---//
  9361. have -= copy;
  9362. next += copy;
  9363. left -= copy;
  9364. put += copy;
  9365. state.length -= copy;
  9366. break;
  9367. }
  9368. //Tracev((stderr, "inflate: stored end\n"));
  9369. state.mode = TYPE;
  9370. break;
  9371. case TABLE:
  9372. //=== NEEDBITS(14); */
  9373. while (bits < 14) {
  9374. if (have === 0) { break inf_leave; }
  9375. have--;
  9376. hold += input[next++] << bits;
  9377. bits += 8;
  9378. }
  9379. //===//
  9380. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  9381. //--- DROPBITS(5) ---//
  9382. hold >>>= 5;
  9383. bits -= 5;
  9384. //---//
  9385. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  9386. //--- DROPBITS(5) ---//
  9387. hold >>>= 5;
  9388. bits -= 5;
  9389. //---//
  9390. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  9391. //--- DROPBITS(4) ---//
  9392. hold >>>= 4;
  9393. bits -= 4;
  9394. //---//
  9395. //#ifndef PKZIP_BUG_WORKAROUND
  9396. if (state.nlen > 286 || state.ndist > 30) {
  9397. strm.msg = 'too many length or distance symbols';
  9398. state.mode = BAD;
  9399. break;
  9400. }
  9401. //#endif
  9402. //Tracev((stderr, "inflate: table sizes ok\n"));
  9403. state.have = 0;
  9404. state.mode = LENLENS;
  9405. /* falls through */
  9406. case LENLENS:
  9407. while (state.have < state.ncode) {
  9408. //=== NEEDBITS(3);
  9409. while (bits < 3) {
  9410. if (have === 0) { break inf_leave; }
  9411. have--;
  9412. hold += input[next++] << bits;
  9413. bits += 8;
  9414. }
  9415. //===//
  9416. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  9417. //--- DROPBITS(3) ---//
  9418. hold >>>= 3;
  9419. bits -= 3;
  9420. //---//
  9421. }
  9422. while (state.have < 19) {
  9423. state.lens[order[state.have++]] = 0;
  9424. }
  9425. // We have separate tables & no pointers. 2 commented lines below not needed.
  9426. //state.next = state.codes;
  9427. //state.lencode = state.next;
  9428. // Switch to use dynamic table
  9429. state.lencode = state.lendyn;
  9430. state.lenbits = 7;
  9431.  
  9432. opts = { bits: state.lenbits };
  9433. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  9434. state.lenbits = opts.bits;
  9435.  
  9436. if (ret) {
  9437. strm.msg = 'invalid code lengths set';
  9438. state.mode = BAD;
  9439. break;
  9440. }
  9441. //Tracev((stderr, "inflate: code lengths ok\n"));
  9442. state.have = 0;
  9443. state.mode = CODELENS;
  9444. /* falls through */
  9445. case CODELENS:
  9446. while (state.have < state.nlen + state.ndist) {
  9447. for (;;) {
  9448. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  9449. here_bits = here >>> 24;
  9450. here_op = (here >>> 16) & 0xff;
  9451. here_val = here & 0xffff;
  9452.  
  9453. if ((here_bits) <= bits) { break; }
  9454. //--- PULLBYTE() ---//
  9455. if (have === 0) { break inf_leave; }
  9456. have--;
  9457. hold += input[next++] << bits;
  9458. bits += 8;
  9459. //---//
  9460. }
  9461. if (here_val < 16) {
  9462. //--- DROPBITS(here.bits) ---//
  9463. hold >>>= here_bits;
  9464. bits -= here_bits;
  9465. //---//
  9466. state.lens[state.have++] = here_val;
  9467. }
  9468. else {
  9469. if (here_val === 16) {
  9470. //=== NEEDBITS(here.bits + 2);
  9471. n = here_bits + 2;
  9472. while (bits < n) {
  9473. if (have === 0) { break inf_leave; }
  9474. have--;
  9475. hold += input[next++] << bits;
  9476. bits += 8;
  9477. }
  9478. //===//
  9479. //--- DROPBITS(here.bits) ---//
  9480. hold >>>= here_bits;
  9481. bits -= here_bits;
  9482. //---//
  9483. if (state.have === 0) {
  9484. strm.msg = 'invalid bit length repeat';
  9485. state.mode = BAD;
  9486. break;
  9487. }
  9488. len = state.lens[state.have - 1];
  9489. copy = 3 + (hold & 0x03);//BITS(2);
  9490. //--- DROPBITS(2) ---//
  9491. hold >>>= 2;
  9492. bits -= 2;
  9493. //---//
  9494. }
  9495. else if (here_val === 17) {
  9496. //=== NEEDBITS(here.bits + 3);
  9497. n = here_bits + 3;
  9498. while (bits < n) {
  9499. if (have === 0) { break inf_leave; }
  9500. have--;
  9501. hold += input[next++] << bits;
  9502. bits += 8;
  9503. }
  9504. //===//
  9505. //--- DROPBITS(here.bits) ---//
  9506. hold >>>= here_bits;
  9507. bits -= here_bits;
  9508. //---//
  9509. len = 0;
  9510. copy = 3 + (hold & 0x07);//BITS(3);
  9511. //--- DROPBITS(3) ---//
  9512. hold >>>= 3;
  9513. bits -= 3;
  9514. //---//
  9515. }
  9516. else {
  9517. //=== NEEDBITS(here.bits + 7);
  9518. n = here_bits + 7;
  9519. while (bits < n) {
  9520. if (have === 0) { break inf_leave; }
  9521. have--;
  9522. hold += input[next++] << bits;
  9523. bits += 8;
  9524. }
  9525. //===//
  9526. //--- DROPBITS(here.bits) ---//
  9527. hold >>>= here_bits;
  9528. bits -= here_bits;
  9529. //---//
  9530. len = 0;
  9531. copy = 11 + (hold & 0x7f);//BITS(7);
  9532. //--- DROPBITS(7) ---//
  9533. hold >>>= 7;
  9534. bits -= 7;
  9535. //---//
  9536. }
  9537. if (state.have + copy > state.nlen + state.ndist) {
  9538. strm.msg = 'invalid bit length repeat';
  9539. state.mode = BAD;
  9540. break;
  9541. }
  9542. while (copy--) {
  9543. state.lens[state.have++] = len;
  9544. }
  9545. }
  9546. }
  9547.  
  9548. /* handle error breaks in while */
  9549. if (state.mode === BAD) { break; }
  9550.  
  9551. /* check for end-of-block code (better have one) */
  9552. if (state.lens[256] === 0) {
  9553. strm.msg = 'invalid code -- missing end-of-block';
  9554. state.mode = BAD;
  9555. break;
  9556. }
  9557.  
  9558. /* build code tables -- note: do not change the lenbits or distbits
  9559. values here (9 and 6) without reading the comments in inftrees.h
  9560. concerning the ENOUGH constants, which depend on those values */
  9561. state.lenbits = 9;
  9562.  
  9563. opts = { bits: state.lenbits };
  9564. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  9565. // We have separate tables & no pointers. 2 commented lines below not needed.
  9566. // state.next_index = opts.table_index;
  9567. state.lenbits = opts.bits;
  9568. // state.lencode = state.next;
  9569.  
  9570. if (ret) {
  9571. strm.msg = 'invalid literal/lengths set';
  9572. state.mode = BAD;
  9573. break;
  9574. }
  9575.  
  9576. state.distbits = 6;
  9577. //state.distcode.copy(state.codes);
  9578. // Switch to use dynamic table
  9579. state.distcode = state.distdyn;
  9580. opts = { bits: state.distbits };
  9581. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  9582. // We have separate tables & no pointers. 2 commented lines below not needed.
  9583. // state.next_index = opts.table_index;
  9584. state.distbits = opts.bits;
  9585. // state.distcode = state.next;
  9586.  
  9587. if (ret) {
  9588. strm.msg = 'invalid distances set';
  9589. state.mode = BAD;
  9590. break;
  9591. }
  9592. //Tracev((stderr, 'inflate: codes ok\n'));
  9593. state.mode = LEN_;
  9594. if (flush === Z_TREES) { break inf_leave; }
  9595. /* falls through */
  9596. case LEN_:
  9597. state.mode = LEN;
  9598. /* falls through */
  9599. case LEN:
  9600. if (have >= 6 && left >= 258) {
  9601. //--- RESTORE() ---
  9602. strm.next_out = put;
  9603. strm.avail_out = left;
  9604. strm.next_in = next;
  9605. strm.avail_in = have;
  9606. state.hold = hold;
  9607. state.bits = bits;
  9608. //---
  9609. inflate_fast(strm, _out);
  9610. //--- LOAD() ---
  9611. put = strm.next_out;
  9612. output = strm.output;
  9613. left = strm.avail_out;
  9614. next = strm.next_in;
  9615. input = strm.input;
  9616. have = strm.avail_in;
  9617. hold = state.hold;
  9618. bits = state.bits;
  9619. //---
  9620.  
  9621. if (state.mode === TYPE) {
  9622. state.back = -1;
  9623. }
  9624. break;
  9625. }
  9626. state.back = 0;
  9627. for (;;) {
  9628. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  9629. here_bits = here >>> 24;
  9630. here_op = (here >>> 16) & 0xff;
  9631. here_val = here & 0xffff;
  9632.  
  9633. if (here_bits <= bits) { break; }
  9634. //--- PULLBYTE() ---//
  9635. if (have === 0) { break inf_leave; }
  9636. have--;
  9637. hold += input[next++] << bits;
  9638. bits += 8;
  9639. //---//
  9640. }
  9641. if (here_op && (here_op & 0xf0) === 0) {
  9642. last_bits = here_bits;
  9643. last_op = here_op;
  9644. last_val = here_val;
  9645. for (;;) {
  9646. here = state.lencode[last_val +
  9647. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9648. here_bits = here >>> 24;
  9649. here_op = (here >>> 16) & 0xff;
  9650. here_val = here & 0xffff;
  9651.  
  9652. if ((last_bits + here_bits) <= bits) { break; }
  9653. //--- PULLBYTE() ---//
  9654. if (have === 0) { break inf_leave; }
  9655. have--;
  9656. hold += input[next++] << bits;
  9657. bits += 8;
  9658. //---//
  9659. }
  9660. //--- DROPBITS(last.bits) ---//
  9661. hold >>>= last_bits;
  9662. bits -= last_bits;
  9663. //---//
  9664. state.back += last_bits;
  9665. }
  9666. //--- DROPBITS(here.bits) ---//
  9667. hold >>>= here_bits;
  9668. bits -= here_bits;
  9669. //---//
  9670. state.back += here_bits;
  9671. state.length = here_val;
  9672. if (here_op === 0) {
  9673. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  9674. // "inflate: literal '%c'\n" :
  9675. // "inflate: literal 0x%02x\n", here.val));
  9676. state.mode = LIT;
  9677. break;
  9678. }
  9679. if (here_op & 32) {
  9680. //Tracevv((stderr, "inflate: end of block\n"));
  9681. state.back = -1;
  9682. state.mode = TYPE;
  9683. break;
  9684. }
  9685. if (here_op & 64) {
  9686. strm.msg = 'invalid literal/length code';
  9687. state.mode = BAD;
  9688. break;
  9689. }
  9690. state.extra = here_op & 15;
  9691. state.mode = LENEXT;
  9692. /* falls through */
  9693. case LENEXT:
  9694. if (state.extra) {
  9695. //=== NEEDBITS(state.extra);
  9696. n = state.extra;
  9697. while (bits < n) {
  9698. if (have === 0) { break inf_leave; }
  9699. have--;
  9700. hold += input[next++] << bits;
  9701. bits += 8;
  9702. }
  9703. //===//
  9704. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9705. //--- DROPBITS(state.extra) ---//
  9706. hold >>>= state.extra;
  9707. bits -= state.extra;
  9708. //---//
  9709. state.back += state.extra;
  9710. }
  9711. //Tracevv((stderr, "inflate: length %u\n", state.length));
  9712. state.was = state.length;
  9713. state.mode = DIST;
  9714. /* falls through */
  9715. case DIST:
  9716. for (;;) {
  9717. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  9718. here_bits = here >>> 24;
  9719. here_op = (here >>> 16) & 0xff;
  9720. here_val = here & 0xffff;
  9721.  
  9722. if ((here_bits) <= bits) { break; }
  9723. //--- PULLBYTE() ---//
  9724. if (have === 0) { break inf_leave; }
  9725. have--;
  9726. hold += input[next++] << bits;
  9727. bits += 8;
  9728. //---//
  9729. }
  9730. if ((here_op & 0xf0) === 0) {
  9731. last_bits = here_bits;
  9732. last_op = here_op;
  9733. last_val = here_val;
  9734. for (;;) {
  9735. here = state.distcode[last_val +
  9736. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9737. here_bits = here >>> 24;
  9738. here_op = (here >>> 16) & 0xff;
  9739. here_val = here & 0xffff;
  9740.  
  9741. if ((last_bits + here_bits) <= bits) { break; }
  9742. //--- PULLBYTE() ---//
  9743. if (have === 0) { break inf_leave; }
  9744. have--;
  9745. hold += input[next++] << bits;
  9746. bits += 8;
  9747. //---//
  9748. }
  9749. //--- DROPBITS(last.bits) ---//
  9750. hold >>>= last_bits;
  9751. bits -= last_bits;
  9752. //---//
  9753. state.back += last_bits;
  9754. }
  9755. //--- DROPBITS(here.bits) ---//
  9756. hold >>>= here_bits;
  9757. bits -= here_bits;
  9758. //---//
  9759. state.back += here_bits;
  9760. if (here_op & 64) {
  9761. strm.msg = 'invalid distance code';
  9762. state.mode = BAD;
  9763. break;
  9764. }
  9765. state.offset = here_val;
  9766. state.extra = (here_op) & 15;
  9767. state.mode = DISTEXT;
  9768. /* falls through */
  9769. case DISTEXT:
  9770. if (state.extra) {
  9771. //=== NEEDBITS(state.extra);
  9772. n = state.extra;
  9773. while (bits < n) {
  9774. if (have === 0) { break inf_leave; }
  9775. have--;
  9776. hold += input[next++] << bits;
  9777. bits += 8;
  9778. }
  9779. //===//
  9780. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9781. //--- DROPBITS(state.extra) ---//
  9782. hold >>>= state.extra;
  9783. bits -= state.extra;
  9784. //---//
  9785. state.back += state.extra;
  9786. }
  9787. //#ifdef INFLATE_STRICT
  9788. if (state.offset > state.dmax) {
  9789. strm.msg = 'invalid distance too far back';
  9790. state.mode = BAD;
  9791. break;
  9792. }
  9793. //#endif
  9794. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  9795. state.mode = MATCH;
  9796. /* falls through */
  9797. case MATCH:
  9798. if (left === 0) { break inf_leave; }
  9799. copy = _out - left;
  9800. if (state.offset > copy) { /* copy from window */
  9801. copy = state.offset - copy;
  9802. if (copy > state.whave) {
  9803. if (state.sane) {
  9804. strm.msg = 'invalid distance too far back';
  9805. state.mode = BAD;
  9806. break;
  9807. }
  9808. // (!) This block is disabled in zlib defailts,
  9809. // don't enable it for binary compatibility
  9810. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9811. // Trace((stderr, "inflate.c too far\n"));
  9812. // copy -= state.whave;
  9813. // if (copy > state.length) { copy = state.length; }
  9814. // if (copy > left) { copy = left; }
  9815. // left -= copy;
  9816. // state.length -= copy;
  9817. // do {
  9818. // output[put++] = 0;
  9819. // } while (--copy);
  9820. // if (state.length === 0) { state.mode = LEN; }
  9821. // break;
  9822. //#endif
  9823. }
  9824. if (copy > state.wnext) {
  9825. copy -= state.wnext;
  9826. from = state.wsize - copy;
  9827. }
  9828. else {
  9829. from = state.wnext - copy;
  9830. }
  9831. if (copy > state.length) { copy = state.length; }
  9832. from_source = state.window;
  9833. }
  9834. else { /* copy from output */
  9835. from_source = output;
  9836. from = put - state.offset;
  9837. copy = state.length;
  9838. }
  9839. if (copy > left) { copy = left; }
  9840. left -= copy;
  9841. state.length -= copy;
  9842. do {
  9843. output[put++] = from_source[from++];
  9844. } while (--copy);
  9845. if (state.length === 0) { state.mode = LEN; }
  9846. break;
  9847. case LIT:
  9848. if (left === 0) { break inf_leave; }
  9849. output[put++] = state.length;
  9850. left--;
  9851. state.mode = LEN;
  9852. break;
  9853. case CHECK:
  9854. if (state.wrap) {
  9855. //=== NEEDBITS(32);
  9856. while (bits < 32) {
  9857. if (have === 0) { break inf_leave; }
  9858. have--;
  9859. // Use '|' insdead of '+' to make sure that result is signed
  9860. hold |= input[next++] << bits;
  9861. bits += 8;
  9862. }
  9863. //===//
  9864. _out -= left;
  9865. strm.total_out += _out;
  9866. state.total += _out;
  9867. if (_out) {
  9868. strm.adler = state.check =
  9869. /*UPDATE(state.check, put - _out, _out);*/
  9870. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  9871.  
  9872. }
  9873. _out = left;
  9874. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  9875. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  9876. strm.msg = 'incorrect data check';
  9877. state.mode = BAD;
  9878. break;
  9879. }
  9880. //=== INITBITS();
  9881. hold = 0;
  9882. bits = 0;
  9883. //===//
  9884. //Tracev((stderr, "inflate: check matches trailer\n"));
  9885. }
  9886. state.mode = LENGTH;
  9887. /* falls through */
  9888. case LENGTH:
  9889. if (state.wrap && state.flags) {
  9890. //=== NEEDBITS(32);
  9891. while (bits < 32) {
  9892. if (have === 0) { break inf_leave; }
  9893. have--;
  9894. hold += input[next++] << bits;
  9895. bits += 8;
  9896. }
  9897. //===//
  9898. if (hold !== (state.total & 0xffffffff)) {
  9899. strm.msg = 'incorrect length check';
  9900. state.mode = BAD;
  9901. break;
  9902. }
  9903. //=== INITBITS();
  9904. hold = 0;
  9905. bits = 0;
  9906. //===//
  9907. //Tracev((stderr, "inflate: length matches trailer\n"));
  9908. }
  9909. state.mode = DONE;
  9910. /* falls through */
  9911. case DONE:
  9912. ret = Z_STREAM_END;
  9913. break inf_leave;
  9914. case BAD:
  9915. ret = Z_DATA_ERROR;
  9916. break inf_leave;
  9917. case MEM:
  9918. return Z_MEM_ERROR;
  9919. case SYNC:
  9920. /* falls through */
  9921. default:
  9922. return Z_STREAM_ERROR;
  9923. }
  9924. }
  9925.  
  9926. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  9927.  
  9928. /*
  9929. Return from inflate(), updating the total counts and the check value.
  9930. If there was no progress during the inflate() call, return a buffer
  9931. error. Call updatewindow() to create and/or update the window state.
  9932. Note: a memory error from inflate() is non-recoverable.
  9933. */
  9934.  
  9935. //--- RESTORE() ---
  9936. strm.next_out = put;
  9937. strm.avail_out = left;
  9938. strm.next_in = next;
  9939. strm.avail_in = have;
  9940. state.hold = hold;
  9941. state.bits = bits;
  9942. //---
  9943.  
  9944. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  9945. (state.mode < CHECK || flush !== Z_FINISH))) {
  9946. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  9947. state.mode = MEM;
  9948. return Z_MEM_ERROR;
  9949. }
  9950. }
  9951. _in -= strm.avail_in;
  9952. _out -= strm.avail_out;
  9953. strm.total_in += _in;
  9954. strm.total_out += _out;
  9955. state.total += _out;
  9956. if (state.wrap && _out) {
  9957. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  9958. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  9959. }
  9960. strm.data_type = state.bits + (state.last ? 64 : 0) +
  9961. (state.mode === TYPE ? 128 : 0) +
  9962. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  9963. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  9964. ret = Z_BUF_ERROR;
  9965. }
  9966. return ret;
  9967. }
  9968.  
  9969. function inflateEnd(strm) {
  9970.  
  9971. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  9972. return Z_STREAM_ERROR;
  9973. }
  9974.  
  9975. var state = strm.state;
  9976. if (state.window) {
  9977. state.window = null;
  9978. }
  9979. strm.state = null;
  9980. return Z_OK;
  9981. }
  9982.  
  9983. function inflateGetHeader(strm, head) {
  9984. var state;
  9985.  
  9986. /* check state */
  9987. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9988. state = strm.state;
  9989. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  9990.  
  9991. /* save header structure */
  9992. state.head = head;
  9993. head.done = false;
  9994. return Z_OK;
  9995. }
  9996.  
  9997. function inflateSetDictionary(strm, dictionary) {
  9998. var dictLength = dictionary.length;
  9999.  
  10000. var state;
  10001. var dictid;
  10002. var ret;
  10003.  
  10004. /* check state */
  10005. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  10006. state = strm.state;
  10007.  
  10008. if (state.wrap !== 0 && state.mode !== DICT) {
  10009. return Z_STREAM_ERROR;
  10010. }
  10011.  
  10012. /* check for correct dictionary identifier */
  10013. if (state.mode === DICT) {
  10014. dictid = 1; /* adler32(0, null, 0)*/
  10015. /* dictid = adler32(dictid, dictionary, dictLength); */
  10016. dictid = adler32(dictid, dictionary, dictLength, 0);
  10017. if (dictid !== state.check) {
  10018. return Z_DATA_ERROR;
  10019. }
  10020. }
  10021. /* copy dictionary to window using updatewindow(), which will amend the
  10022. existing dictionary if appropriate */
  10023. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  10024. if (ret) {
  10025. state.mode = MEM;
  10026. return Z_MEM_ERROR;
  10027. }
  10028. state.havedict = 1;
  10029. // Tracev((stderr, "inflate: dictionary set\n"));
  10030. return Z_OK;
  10031. }
  10032.  
  10033. exports.inflateReset = inflateReset;
  10034. exports.inflateReset2 = inflateReset2;
  10035. exports.inflateResetKeep = inflateResetKeep;
  10036. exports.inflateInit = inflateInit;
  10037. exports.inflateInit2 = inflateInit2;
  10038. exports.inflate = inflate;
  10039. exports.inflateEnd = inflateEnd;
  10040. exports.inflateGetHeader = inflateGetHeader;
  10041. exports.inflateSetDictionary = inflateSetDictionary;
  10042. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  10043.  
  10044. /* Not implemented
  10045. exports.inflateCopy = inflateCopy;
  10046. exports.inflateGetDictionary = inflateGetDictionary;
  10047. exports.inflateMark = inflateMark;
  10048. exports.inflatePrime = inflatePrime;
  10049. exports.inflateSync = inflateSync;
  10050. exports.inflateSyncPoint = inflateSyncPoint;
  10051. exports.inflateUndermine = inflateUndermine;
  10052. */
  10053.  
  10054. },{"../utils/common":62,"./adler32":64,"./crc32":66,"./inffast":69,"./inftrees":71}],71:[function(require,module,exports){
  10055. 'use strict';
  10056.  
  10057. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10058. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10059. //
  10060. // This software is provided 'as-is', without any express or implied
  10061. // warranty. In no event will the authors be held liable for any damages
  10062. // arising from the use of this software.
  10063. //
  10064. // Permission is granted to anyone to use this software for any purpose,
  10065. // including commercial applications, and to alter it and redistribute it
  10066. // freely, subject to the following restrictions:
  10067. //
  10068. // 1. The origin of this software must not be misrepresented; you must not
  10069. // claim that you wrote the original software. If you use this software
  10070. // in a product, an acknowledgment in the product documentation would be
  10071. // appreciated but is not required.
  10072. // 2. Altered source versions must be plainly marked as such, and must not be
  10073. // misrepresented as being the original software.
  10074. // 3. This notice may not be removed or altered from any source distribution.
  10075.  
  10076. var utils = require('../utils/common');
  10077.  
  10078. var MAXBITS = 15;
  10079. var ENOUGH_LENS = 852;
  10080. var ENOUGH_DISTS = 592;
  10081. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  10082.  
  10083. var CODES = 0;
  10084. var LENS = 1;
  10085. var DISTS = 2;
  10086.  
  10087. var lbase = [ /* Length codes 257..285 base */
  10088. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  10089. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  10090. ];
  10091.  
  10092. var lext = [ /* Length codes 257..285 extra */
  10093. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  10094. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  10095. ];
  10096.  
  10097. var dbase = [ /* Distance codes 0..29 base */
  10098. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  10099. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  10100. 8193, 12289, 16385, 24577, 0, 0
  10101. ];
  10102.  
  10103. var dext = [ /* Distance codes 0..29 extra */
  10104. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  10105. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  10106. 28, 28, 29, 29, 64, 64
  10107. ];
  10108.  
  10109. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  10110. {
  10111. var bits = opts.bits;
  10112. //here = opts.here; /* table entry for duplication */
  10113.  
  10114. var len = 0; /* a code's length in bits */
  10115. var sym = 0; /* index of code symbols */
  10116. var min = 0, max = 0; /* minimum and maximum code lengths */
  10117. var root = 0; /* number of index bits for root table */
  10118. var curr = 0; /* number of index bits for current table */
  10119. var drop = 0; /* code bits to drop for sub-table */
  10120. var left = 0; /* number of prefix codes available */
  10121. var used = 0; /* code entries in table used */
  10122. var huff = 0; /* Huffman code */
  10123. var incr; /* for incrementing code, index */
  10124. var fill; /* index for replicating entries */
  10125. var low; /* low bits for current root entry */
  10126. var mask; /* mask for low root bits */
  10127. var next; /* next available space in table */
  10128. var base = null; /* base value table to use */
  10129. var base_index = 0;
  10130. // var shoextra; /* extra bits table to use */
  10131. var end; /* use base and extra for symbol > end */
  10132. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  10133. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  10134. var extra = null;
  10135. var extra_index = 0;
  10136.  
  10137. var here_bits, here_op, here_val;
  10138.  
  10139. /*
  10140. Process a set of code lengths to create a canonical Huffman code. The
  10141. code lengths are lens[0..codes-1]. Each length corresponds to the
  10142. symbols 0..codes-1. The Huffman code is generated by first sorting the
  10143. symbols by length from short to long, and retaining the symbol order
  10144. for codes with equal lengths. Then the code starts with all zero bits
  10145. for the first code of the shortest length, and the codes are integer
  10146. increments for the same length, and zeros are appended as the length
  10147. increases. For the deflate format, these bits are stored backwards
  10148. from their more natural integer increment ordering, and so when the
  10149. decoding tables are built in the large loop below, the integer codes
  10150. are incremented backwards.
  10151.  
  10152. This routine assumes, but does not check, that all of the entries in
  10153. lens[] are in the range 0..MAXBITS. The caller must assure this.
  10154. 1..MAXBITS is interpreted as that code length. zero means that that
  10155. symbol does not occur in this code.
  10156.  
  10157. The codes are sorted by computing a count of codes for each length,
  10158. creating from that a table of starting indices for each length in the
  10159. sorted table, and then entering the symbols in order in the sorted
  10160. table. The sorted table is work[], with that space being provided by
  10161. the caller.
  10162.  
  10163. The length counts are used for other purposes as well, i.e. finding
  10164. the minimum and maximum length codes, determining if there are any
  10165. codes at all, checking for a valid set of lengths, and looking ahead
  10166. at length counts to determine sub-table sizes when building the
  10167. decoding tables.
  10168. */
  10169.  
  10170. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  10171. for (len = 0; len <= MAXBITS; len++) {
  10172. count[len] = 0;
  10173. }
  10174. for (sym = 0; sym < codes; sym++) {
  10175. count[lens[lens_index + sym]]++;
  10176. }
  10177.  
  10178. /* bound code lengths, force root to be within code lengths */
  10179. root = bits;
  10180. for (max = MAXBITS; max >= 1; max--) {
  10181. if (count[max] !== 0) { break; }
  10182. }
  10183. if (root > max) {
  10184. root = max;
  10185. }
  10186. if (max === 0) { /* no symbols to code at all */
  10187. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  10188. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  10189. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  10190. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  10191.  
  10192.  
  10193. //table.op[opts.table_index] = 64;
  10194. //table.bits[opts.table_index] = 1;
  10195. //table.val[opts.table_index++] = 0;
  10196. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  10197.  
  10198. opts.bits = 1;
  10199. return 0; /* no symbols, but wait for decoding to report error */
  10200. }
  10201. for (min = 1; min < max; min++) {
  10202. if (count[min] !== 0) { break; }
  10203. }
  10204. if (root < min) {
  10205. root = min;
  10206. }
  10207.  
  10208. /* check for an over-subscribed or incomplete set of lengths */
  10209. left = 1;
  10210. for (len = 1; len <= MAXBITS; len++) {
  10211. left <<= 1;
  10212. left -= count[len];
  10213. if (left < 0) {
  10214. return -1;
  10215. } /* over-subscribed */
  10216. }
  10217. if (left > 0 && (type === CODES || max !== 1)) {
  10218. return -1; /* incomplete set */
  10219. }
  10220.  
  10221. /* generate offsets into symbol table for each length for sorting */
  10222. offs[1] = 0;
  10223. for (len = 1; len < MAXBITS; len++) {
  10224. offs[len + 1] = offs[len] + count[len];
  10225. }
  10226.  
  10227. /* sort symbols by length, by symbol order within each length */
  10228. for (sym = 0; sym < codes; sym++) {
  10229. if (lens[lens_index + sym] !== 0) {
  10230. work[offs[lens[lens_index + sym]]++] = sym;
  10231. }
  10232. }
  10233.  
  10234. /*
  10235. Create and fill in decoding tables. In this loop, the table being
  10236. filled is at next and has curr index bits. The code being used is huff
  10237. with length len. That code is converted to an index by dropping drop
  10238. bits off of the bottom. For codes where len is less than drop + curr,
  10239. those top drop + curr - len bits are incremented through all values to
  10240. fill the table with replicated entries.
  10241.  
  10242. root is the number of index bits for the root table. When len exceeds
  10243. root, sub-tables are created pointed to by the root entry with an index
  10244. of the low root bits of huff. This is saved in low to check for when a
  10245. new sub-table should be started. drop is zero when the root table is
  10246. being filled, and drop is root when sub-tables are being filled.
  10247.  
  10248. When a new sub-table is needed, it is necessary to look ahead in the
  10249. code lengths to determine what size sub-table is needed. The length
  10250. counts are used for this, and so count[] is decremented as codes are
  10251. entered in the tables.
  10252.  
  10253. used keeps track of how many table entries have been allocated from the
  10254. provided *table space. It is checked for LENS and DIST tables against
  10255. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  10256. the initial root table size constants. See the comments in inftrees.h
  10257. for more information.
  10258.  
  10259. sym increments through all symbols, and the loop terminates when
  10260. all codes of length max, i.e. all codes, have been processed. This
  10261. routine permits incomplete codes, so another loop after this one fills
  10262. in the rest of the decoding tables with invalid code markers.
  10263. */
  10264.  
  10265. /* set up for code type */
  10266. // poor man optimization - use if-else instead of switch,
  10267. // to avoid deopts in old v8
  10268. if (type === CODES) {
  10269. base = extra = work; /* dummy value--not used */
  10270. end = 19;
  10271.  
  10272. } else if (type === LENS) {
  10273. base = lbase;
  10274. base_index -= 257;
  10275. extra = lext;
  10276. extra_index -= 257;
  10277. end = 256;
  10278.  
  10279. } else { /* DISTS */
  10280. base = dbase;
  10281. extra = dext;
  10282. end = -1;
  10283. }
  10284.  
  10285. /* initialize opts for loop */
  10286. huff = 0; /* starting code */
  10287. sym = 0; /* starting code symbol */
  10288. len = min; /* starting code length */
  10289. next = table_index; /* current table to fill in */
  10290. curr = root; /* current table index bits */
  10291. drop = 0; /* current bits to drop from code for index */
  10292. low = -1; /* trigger new sub-table when len > root */
  10293. used = 1 << root; /* use root table entries */
  10294. mask = used - 1; /* mask for comparing low */
  10295.  
  10296. /* check available table space */
  10297. if ((type === LENS && used > ENOUGH_LENS) ||
  10298. (type === DISTS && used > ENOUGH_DISTS)) {
  10299. return 1;
  10300. }
  10301.  
  10302. /* process all codes and make table entries */
  10303. for (;;) {
  10304. /* create table entry */
  10305. here_bits = len - drop;
  10306. if (work[sym] < end) {
  10307. here_op = 0;
  10308. here_val = work[sym];
  10309. }
  10310. else if (work[sym] > end) {
  10311. here_op = extra[extra_index + work[sym]];
  10312. here_val = base[base_index + work[sym]];
  10313. }
  10314. else {
  10315. here_op = 32 + 64; /* end of block */
  10316. here_val = 0;
  10317. }
  10318.  
  10319. /* replicate for those indices with low len bits equal to huff */
  10320. incr = 1 << (len - drop);
  10321. fill = 1 << curr;
  10322. min = fill; /* save offset to next table */
  10323. do {
  10324. fill -= incr;
  10325. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  10326. } while (fill !== 0);
  10327.  
  10328. /* backwards increment the len-bit code huff */
  10329. incr = 1 << (len - 1);
  10330. while (huff & incr) {
  10331. incr >>= 1;
  10332. }
  10333. if (incr !== 0) {
  10334. huff &= incr - 1;
  10335. huff += incr;
  10336. } else {
  10337. huff = 0;
  10338. }
  10339.  
  10340. /* go to next symbol, update count, len */
  10341. sym++;
  10342. if (--count[len] === 0) {
  10343. if (len === max) { break; }
  10344. len = lens[lens_index + work[sym]];
  10345. }
  10346.  
  10347. /* create new sub-table if needed */
  10348. if (len > root && (huff & mask) !== low) {
  10349. /* if first time, transition to sub-tables */
  10350. if (drop === 0) {
  10351. drop = root;
  10352. }
  10353.  
  10354. /* increment past last table */
  10355. next += min; /* here min is 1 << curr */
  10356.  
  10357. /* determine length of next table */
  10358. curr = len - drop;
  10359. left = 1 << curr;
  10360. while (curr + drop < max) {
  10361. left -= count[curr + drop];
  10362. if (left <= 0) { break; }
  10363. curr++;
  10364. left <<= 1;
  10365. }
  10366.  
  10367. /* check for enough space */
  10368. used += 1 << curr;
  10369. if ((type === LENS && used > ENOUGH_LENS) ||
  10370. (type === DISTS && used > ENOUGH_DISTS)) {
  10371. return 1;
  10372. }
  10373.  
  10374. /* point entry in root table to sub-table */
  10375. low = huff & mask;
  10376. /*table.op[low] = curr;
  10377. table.bits[low] = root;
  10378. table.val[low] = next - opts.table_index;*/
  10379. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  10380. }
  10381. }
  10382.  
  10383. /* fill in remaining table entry if code is incomplete (guaranteed to have
  10384. at most one remaining entry, since if the code is incomplete, the
  10385. maximum code length that was allowed to get this far is one bit) */
  10386. if (huff !== 0) {
  10387. //table.op[next + huff] = 64; /* invalid code marker */
  10388. //table.bits[next + huff] = len - drop;
  10389. //table.val[next + huff] = 0;
  10390. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  10391. }
  10392.  
  10393. /* set return parameters */
  10394. //opts.table_index += used;
  10395. opts.bits = root;
  10396. return 0;
  10397. };
  10398.  
  10399. },{"../utils/common":62}],72:[function(require,module,exports){
  10400. 'use strict';
  10401.  
  10402. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10403. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10404. //
  10405. // This software is provided 'as-is', without any express or implied
  10406. // warranty. In no event will the authors be held liable for any damages
  10407. // arising from the use of this software.
  10408. //
  10409. // Permission is granted to anyone to use this software for any purpose,
  10410. // including commercial applications, and to alter it and redistribute it
  10411. // freely, subject to the following restrictions:
  10412. //
  10413. // 1. The origin of this software must not be misrepresented; you must not
  10414. // claim that you wrote the original software. If you use this software
  10415. // in a product, an acknowledgment in the product documentation would be
  10416. // appreciated but is not required.
  10417. // 2. Altered source versions must be plainly marked as such, and must not be
  10418. // misrepresented as being the original software.
  10419. // 3. This notice may not be removed or altered from any source distribution.
  10420.  
  10421. module.exports = {
  10422. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  10423. 1: 'stream end', /* Z_STREAM_END 1 */
  10424. 0: '', /* Z_OK 0 */
  10425. '-1': 'file error', /* Z_ERRNO (-1) */
  10426. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  10427. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  10428. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  10429. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  10430. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  10431. };
  10432.  
  10433. },{}],73:[function(require,module,exports){
  10434. 'use strict';
  10435.  
  10436. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10437. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10438. //
  10439. // This software is provided 'as-is', without any express or implied
  10440. // warranty. In no event will the authors be held liable for any damages
  10441. // arising from the use of this software.
  10442. //
  10443. // Permission is granted to anyone to use this software for any purpose,
  10444. // including commercial applications, and to alter it and redistribute it
  10445. // freely, subject to the following restrictions:
  10446. //
  10447. // 1. The origin of this software must not be misrepresented; you must not
  10448. // claim that you wrote the original software. If you use this software
  10449. // in a product, an acknowledgment in the product documentation would be
  10450. // appreciated but is not required.
  10451. // 2. Altered source versions must be plainly marked as such, and must not be
  10452. // misrepresented as being the original software.
  10453. // 3. This notice may not be removed or altered from any source distribution.
  10454.  
  10455. var utils = require('../utils/common');
  10456.  
  10457. /* Public constants ==========================================================*/
  10458. /* ===========================================================================*/
  10459.  
  10460.  
  10461. //var Z_FILTERED = 1;
  10462. //var Z_HUFFMAN_ONLY = 2;
  10463. //var Z_RLE = 3;
  10464. var Z_FIXED = 4;
  10465. //var Z_DEFAULT_STRATEGY = 0;
  10466.  
  10467. /* Possible values of the data_type field (though see inflate()) */
  10468. var Z_BINARY = 0;
  10469. var Z_TEXT = 1;
  10470. //var Z_ASCII = 1; // = Z_TEXT
  10471. var Z_UNKNOWN = 2;
  10472.  
  10473. /*============================================================================*/
  10474.  
  10475.  
  10476. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  10477.  
  10478. // From zutil.h
  10479.  
  10480. var STORED_BLOCK = 0;
  10481. var STATIC_TREES = 1;
  10482. var DYN_TREES = 2;
  10483. /* The three kinds of block type */
  10484.  
  10485. var MIN_MATCH = 3;
  10486. var MAX_MATCH = 258;
  10487. /* The minimum and maximum match lengths */
  10488.  
  10489. // From deflate.h
  10490. /* ===========================================================================
  10491. * Internal compression state.
  10492. */
  10493.  
  10494. var LENGTH_CODES = 29;
  10495. /* number of length codes, not counting the special END_BLOCK code */
  10496.  
  10497. var LITERALS = 256;
  10498. /* number of literal bytes 0..255 */
  10499.  
  10500. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  10501. /* number of Literal or Length codes, including the END_BLOCK code */
  10502.  
  10503. var D_CODES = 30;
  10504. /* number of distance codes */
  10505.  
  10506. var BL_CODES = 19;
  10507. /* number of codes used to transfer the bit lengths */
  10508.  
  10509. var HEAP_SIZE = 2 * L_CODES + 1;
  10510. /* maximum heap size */
  10511.  
  10512. var MAX_BITS = 15;
  10513. /* All codes must not exceed MAX_BITS bits */
  10514.  
  10515. var Buf_size = 16;
  10516. /* size of bit buffer in bi_buf */
  10517.  
  10518.  
  10519. /* ===========================================================================
  10520. * Constants
  10521. */
  10522.  
  10523. var MAX_BL_BITS = 7;
  10524. /* Bit length codes must not exceed MAX_BL_BITS bits */
  10525.  
  10526. var END_BLOCK = 256;
  10527. /* end of block literal code */
  10528.  
  10529. var REP_3_6 = 16;
  10530. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  10531.  
  10532. var REPZ_3_10 = 17;
  10533. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  10534.  
  10535. var REPZ_11_138 = 18;
  10536. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  10537.  
  10538. /* eslint-disable comma-spacing,array-bracket-spacing */
  10539. var extra_lbits = /* extra bits for each length code */
  10540. [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];
  10541.  
  10542. var extra_dbits = /* extra bits for each distance code */
  10543. [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];
  10544.  
  10545. var extra_blbits = /* extra bits for each bit length code */
  10546. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  10547.  
  10548. var bl_order =
  10549. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  10550. /* eslint-enable comma-spacing,array-bracket-spacing */
  10551.  
  10552. /* The lengths of the bit length codes are sent in order of decreasing
  10553. * probability, to avoid transmitting the lengths for unused bit length codes.
  10554. */
  10555.  
  10556. /* ===========================================================================
  10557. * Local data. These are initialized only once.
  10558. */
  10559.  
  10560. // We pre-fill arrays with 0 to avoid uninitialized gaps
  10561.  
  10562. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  10563.  
  10564. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  10565. var static_ltree = new Array((L_CODES + 2) * 2);
  10566. zero(static_ltree);
  10567. /* The static literal tree. Since the bit lengths are imposed, there is no
  10568. * need for the L_CODES extra codes used during heap construction. However
  10569. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  10570. * below).
  10571. */
  10572.  
  10573. var static_dtree = new Array(D_CODES * 2);
  10574. zero(static_dtree);
  10575. /* The static distance tree. (Actually a trivial tree since all codes use
  10576. * 5 bits.)
  10577. */
  10578.  
  10579. var _dist_code = new Array(DIST_CODE_LEN);
  10580. zero(_dist_code);
  10581. /* Distance codes. The first 256 values correspond to the distances
  10582. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  10583. * the 15 bit distances.
  10584. */
  10585.  
  10586. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  10587. zero(_length_code);
  10588. /* length code for each normalized match length (0 == MIN_MATCH) */
  10589.  
  10590. var base_length = new Array(LENGTH_CODES);
  10591. zero(base_length);
  10592. /* First normalized length for each code (0 = MIN_MATCH) */
  10593.  
  10594. var base_dist = new Array(D_CODES);
  10595. zero(base_dist);
  10596. /* First normalized distance for each code (0 = distance of 1) */
  10597.  
  10598.  
  10599. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  10600.  
  10601. this.static_tree = static_tree; /* static tree or NULL */
  10602. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  10603. this.extra_base = extra_base; /* base index for extra_bits */
  10604. this.elems = elems; /* max number of elements in the tree */
  10605. this.max_length = max_length; /* max bit length for the codes */
  10606.  
  10607. // show if `static_tree` has data or dummy - needed for monomorphic objects
  10608. this.has_stree = static_tree && static_tree.length;
  10609. }
  10610.  
  10611.  
  10612. var static_l_desc;
  10613. var static_d_desc;
  10614. var static_bl_desc;
  10615.  
  10616.  
  10617. function TreeDesc(dyn_tree, stat_desc) {
  10618. this.dyn_tree = dyn_tree; /* the dynamic tree */
  10619. this.max_code = 0; /* largest code with non zero frequency */
  10620. this.stat_desc = stat_desc; /* the corresponding static tree */
  10621. }
  10622.  
  10623.  
  10624.  
  10625. function d_code(dist) {
  10626. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  10627. }
  10628.  
  10629.  
  10630. /* ===========================================================================
  10631. * Output a short LSB first on the stream.
  10632. * IN assertion: there is enough room in pendingBuf.
  10633. */
  10634. function put_short(s, w) {
  10635. // put_byte(s, (uch)((w) & 0xff));
  10636. // put_byte(s, (uch)((ush)(w) >> 8));
  10637. s.pending_buf[s.pending++] = (w) & 0xff;
  10638. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  10639. }
  10640.  
  10641.  
  10642. /* ===========================================================================
  10643. * Send a value on a given number of bits.
  10644. * IN assertion: length <= 16 and value fits in length bits.
  10645. */
  10646. function send_bits(s, value, length) {
  10647. if (s.bi_valid > (Buf_size - length)) {
  10648. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10649. put_short(s, s.bi_buf);
  10650. s.bi_buf = value >> (Buf_size - s.bi_valid);
  10651. s.bi_valid += length - Buf_size;
  10652. } else {
  10653. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10654. s.bi_valid += length;
  10655. }
  10656. }
  10657.  
  10658.  
  10659. function send_code(s, c, tree) {
  10660. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  10661. }
  10662.  
  10663.  
  10664. /* ===========================================================================
  10665. * Reverse the first len bits of a code, using straightforward code (a faster
  10666. * method would use a table)
  10667. * IN assertion: 1 <= len <= 15
  10668. */
  10669. function bi_reverse(code, len) {
  10670. var res = 0;
  10671. do {
  10672. res |= code & 1;
  10673. code >>>= 1;
  10674. res <<= 1;
  10675. } while (--len > 0);
  10676. return res >>> 1;
  10677. }
  10678.  
  10679.  
  10680. /* ===========================================================================
  10681. * Flush the bit buffer, keeping at most 7 bits in it.
  10682. */
  10683. function bi_flush(s) {
  10684. if (s.bi_valid === 16) {
  10685. put_short(s, s.bi_buf);
  10686. s.bi_buf = 0;
  10687. s.bi_valid = 0;
  10688.  
  10689. } else if (s.bi_valid >= 8) {
  10690. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  10691. s.bi_buf >>= 8;
  10692. s.bi_valid -= 8;
  10693. }
  10694. }
  10695.  
  10696.  
  10697. /* ===========================================================================
  10698. * Compute the optimal bit lengths for a tree and update the total bit length
  10699. * for the current block.
  10700. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  10701. * above are the tree nodes sorted by increasing frequency.
  10702. * OUT assertions: the field len is set to the optimal bit length, the
  10703. * array bl_count contains the frequencies for each bit length.
  10704. * The length opt_len is updated; static_len is also updated if stree is
  10705. * not null.
  10706. */
  10707. function gen_bitlen(s, desc)
  10708. // deflate_state *s;
  10709. // tree_desc *desc; /* the tree descriptor */
  10710. {
  10711. var tree = desc.dyn_tree;
  10712. var max_code = desc.max_code;
  10713. var stree = desc.stat_desc.static_tree;
  10714. var has_stree = desc.stat_desc.has_stree;
  10715. var extra = desc.stat_desc.extra_bits;
  10716. var base = desc.stat_desc.extra_base;
  10717. var max_length = desc.stat_desc.max_length;
  10718. var h; /* heap index */
  10719. var n, m; /* iterate over the tree elements */
  10720. var bits; /* bit length */
  10721. var xbits; /* extra bits */
  10722. var f; /* frequency */
  10723. var overflow = 0; /* number of elements with bit length too large */
  10724.  
  10725. for (bits = 0; bits <= MAX_BITS; bits++) {
  10726. s.bl_count[bits] = 0;
  10727. }
  10728.  
  10729. /* In a first pass, compute the optimal bit lengths (which may
  10730. * overflow in the case of the bit length tree).
  10731. */
  10732. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  10733.  
  10734. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  10735. n = s.heap[h];
  10736. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  10737. if (bits > max_length) {
  10738. bits = max_length;
  10739. overflow++;
  10740. }
  10741. tree[n * 2 + 1]/*.Len*/ = bits;
  10742. /* We overwrite tree[n].Dad which is no longer needed */
  10743.  
  10744. if (n > max_code) { continue; } /* not a leaf node */
  10745.  
  10746. s.bl_count[bits]++;
  10747. xbits = 0;
  10748. if (n >= base) {
  10749. xbits = extra[n - base];
  10750. }
  10751. f = tree[n * 2]/*.Freq*/;
  10752. s.opt_len += f * (bits + xbits);
  10753. if (has_stree) {
  10754. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  10755. }
  10756. }
  10757. if (overflow === 0) { return; }
  10758.  
  10759. // Trace((stderr,"\nbit length overflow\n"));
  10760. /* This happens for example on obj2 and pic of the Calgary corpus */
  10761.  
  10762. /* Find the first bit length which could increase: */
  10763. do {
  10764. bits = max_length - 1;
  10765. while (s.bl_count[bits] === 0) { bits--; }
  10766. s.bl_count[bits]--; /* move one leaf down the tree */
  10767. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  10768. s.bl_count[max_length]--;
  10769. /* The brother of the overflow item also moves one step up,
  10770. * but this does not affect bl_count[max_length]
  10771. */
  10772. overflow -= 2;
  10773. } while (overflow > 0);
  10774.  
  10775. /* Now recompute all bit lengths, scanning in increasing frequency.
  10776. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  10777. * lengths instead of fixing only the wrong ones. This idea is taken
  10778. * from 'ar' written by Haruhiko Okumura.)
  10779. */
  10780. for (bits = max_length; bits !== 0; bits--) {
  10781. n = s.bl_count[bits];
  10782. while (n !== 0) {
  10783. m = s.heap[--h];
  10784. if (m > max_code) { continue; }
  10785. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  10786. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  10787. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  10788. tree[m * 2 + 1]/*.Len*/ = bits;
  10789. }
  10790. n--;
  10791. }
  10792. }
  10793. }
  10794.  
  10795.  
  10796. /* ===========================================================================
  10797. * Generate the codes for a given tree and bit counts (which need not be
  10798. * optimal).
  10799. * IN assertion: the array bl_count contains the bit length statistics for
  10800. * the given tree and the field len is set for all tree elements.
  10801. * OUT assertion: the field code is set for all tree elements of non
  10802. * zero code length.
  10803. */
  10804. function gen_codes(tree, max_code, bl_count)
  10805. // ct_data *tree; /* the tree to decorate */
  10806. // int max_code; /* largest code with non zero frequency */
  10807. // ushf *bl_count; /* number of codes at each bit length */
  10808. {
  10809. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  10810. var code = 0; /* running code value */
  10811. var bits; /* bit index */
  10812. var n; /* code index */
  10813.  
  10814. /* The distribution counts are first used to generate the code values
  10815. * without bit reversal.
  10816. */
  10817. for (bits = 1; bits <= MAX_BITS; bits++) {
  10818. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  10819. }
  10820. /* Check that the bit counts in bl_count are consistent. The last code
  10821. * must be all ones.
  10822. */
  10823. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  10824. // "inconsistent bit counts");
  10825. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  10826.  
  10827. for (n = 0; n <= max_code; n++) {
  10828. var len = tree[n * 2 + 1]/*.Len*/;
  10829. if (len === 0) { continue; }
  10830. /* Now reverse the bits */
  10831. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  10832.  
  10833. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  10834. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  10835. }
  10836. }
  10837.  
  10838.  
  10839. /* ===========================================================================
  10840. * Initialize the various 'constant' tables.
  10841. */
  10842. function tr_static_init() {
  10843. var n; /* iterates over tree elements */
  10844. var bits; /* bit counter */
  10845. var length; /* length value */
  10846. var code; /* code value */
  10847. var dist; /* distance index */
  10848. var bl_count = new Array(MAX_BITS + 1);
  10849. /* number of codes at each bit length for an optimal tree */
  10850.  
  10851. // do check in _tr_init()
  10852. //if (static_init_done) return;
  10853.  
  10854. /* For some embedded targets, global variables are not initialized: */
  10855. /*#ifdef NO_INIT_GLOBAL_POINTERS
  10856. static_l_desc.static_tree = static_ltree;
  10857. static_l_desc.extra_bits = extra_lbits;
  10858. static_d_desc.static_tree = static_dtree;
  10859. static_d_desc.extra_bits = extra_dbits;
  10860. static_bl_desc.extra_bits = extra_blbits;
  10861. #endif*/
  10862.  
  10863. /* Initialize the mapping length (0..255) -> length code (0..28) */
  10864. length = 0;
  10865. for (code = 0; code < LENGTH_CODES - 1; code++) {
  10866. base_length[code] = length;
  10867. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  10868. _length_code[length++] = code;
  10869. }
  10870. }
  10871. //Assert (length == 256, "tr_static_init: length != 256");
  10872. /* Note that the length 255 (match length 258) can be represented
  10873. * in two different ways: code 284 + 5 bits or code 285, so we
  10874. * overwrite length_code[255] to use the best encoding:
  10875. */
  10876. _length_code[length - 1] = code;
  10877.  
  10878. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  10879. dist = 0;
  10880. for (code = 0; code < 16; code++) {
  10881. base_dist[code] = dist;
  10882. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  10883. _dist_code[dist++] = code;
  10884. }
  10885. }
  10886. //Assert (dist == 256, "tr_static_init: dist != 256");
  10887. dist >>= 7; /* from now on, all distances are divided by 128 */
  10888. for (; code < D_CODES; code++) {
  10889. base_dist[code] = dist << 7;
  10890. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  10891. _dist_code[256 + dist++] = code;
  10892. }
  10893. }
  10894. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  10895.  
  10896. /* Construct the codes of the static literal tree */
  10897. for (bits = 0; bits <= MAX_BITS; bits++) {
  10898. bl_count[bits] = 0;
  10899. }
  10900.  
  10901. n = 0;
  10902. while (n <= 143) {
  10903. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10904. n++;
  10905. bl_count[8]++;
  10906. }
  10907. while (n <= 255) {
  10908. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  10909. n++;
  10910. bl_count[9]++;
  10911. }
  10912. while (n <= 279) {
  10913. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  10914. n++;
  10915. bl_count[7]++;
  10916. }
  10917. while (n <= 287) {
  10918. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10919. n++;
  10920. bl_count[8]++;
  10921. }
  10922. /* Codes 286 and 287 do not exist, but we must include them in the
  10923. * tree construction to get a canonical Huffman tree (longest code
  10924. * all ones)
  10925. */
  10926. gen_codes(static_ltree, L_CODES + 1, bl_count);
  10927.  
  10928. /* The static distance tree is trivial: */
  10929. for (n = 0; n < D_CODES; n++) {
  10930. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  10931. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  10932. }
  10933.  
  10934. // Now data ready and we can init static trees
  10935. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  10936. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  10937. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  10938.  
  10939. //static_init_done = true;
  10940. }
  10941.  
  10942.  
  10943. /* ===========================================================================
  10944. * Initialize a new block.
  10945. */
  10946. function init_block(s) {
  10947. var n; /* iterates over tree elements */
  10948.  
  10949. /* Initialize the trees. */
  10950. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  10951. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  10952. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  10953.  
  10954. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  10955. s.opt_len = s.static_len = 0;
  10956. s.last_lit = s.matches = 0;
  10957. }
  10958.  
  10959.  
  10960. /* ===========================================================================
  10961. * Flush the bit buffer and align the output on a byte boundary
  10962. */
  10963. function bi_windup(s)
  10964. {
  10965. if (s.bi_valid > 8) {
  10966. put_short(s, s.bi_buf);
  10967. } else if (s.bi_valid > 0) {
  10968. //put_byte(s, (Byte)s->bi_buf);
  10969. s.pending_buf[s.pending++] = s.bi_buf;
  10970. }
  10971. s.bi_buf = 0;
  10972. s.bi_valid = 0;
  10973. }
  10974.  
  10975. /* ===========================================================================
  10976. * Copy a stored block, storing first the length and its
  10977. * one's complement if requested.
  10978. */
  10979. function copy_block(s, buf, len, header)
  10980. //DeflateState *s;
  10981. //charf *buf; /* the input data */
  10982. //unsigned len; /* its length */
  10983. //int header; /* true if block header must be written */
  10984. {
  10985. bi_windup(s); /* align on byte boundary */
  10986.  
  10987. if (header) {
  10988. put_short(s, len);
  10989. put_short(s, ~len);
  10990. }
  10991. // while (len--) {
  10992. // put_byte(s, *buf++);
  10993. // }
  10994. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  10995. s.pending += len;
  10996. }
  10997.  
  10998. /* ===========================================================================
  10999. * Compares to subtrees, using the tree depth as tie breaker when
  11000. * the subtrees have equal frequency. This minimizes the worst case length.
  11001. */
  11002. function smaller(tree, n, m, depth) {
  11003. var _n2 = n * 2;
  11004. var _m2 = m * 2;
  11005. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  11006. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  11007. }
  11008.  
  11009. /* ===========================================================================
  11010. * Restore the heap property by moving down the tree starting at node k,
  11011. * exchanging a node with the smallest of its two sons if necessary, stopping
  11012. * when the heap property is re-established (each father smaller than its
  11013. * two sons).
  11014. */
  11015. function pqdownheap(s, tree, k)
  11016. // deflate_state *s;
  11017. // ct_data *tree; /* the tree to restore */
  11018. // int k; /* node to move down */
  11019. {
  11020. var v = s.heap[k];
  11021. var j = k << 1; /* left son of k */
  11022. while (j <= s.heap_len) {
  11023. /* Set j to the smallest of the two sons: */
  11024. if (j < s.heap_len &&
  11025. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  11026. j++;
  11027. }
  11028. /* Exit if v is smaller than both sons */
  11029. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  11030.  
  11031. /* Exchange v with the smallest son */
  11032. s.heap[k] = s.heap[j];
  11033. k = j;
  11034.  
  11035. /* And continue down the tree, setting j to the left son of k */
  11036. j <<= 1;
  11037. }
  11038. s.heap[k] = v;
  11039. }
  11040.  
  11041.  
  11042. // inlined manually
  11043. // var SMALLEST = 1;
  11044.  
  11045. /* ===========================================================================
  11046. * Send the block data compressed using the given Huffman trees
  11047. */
  11048. function compress_block(s, ltree, dtree)
  11049. // deflate_state *s;
  11050. // const ct_data *ltree; /* literal tree */
  11051. // const ct_data *dtree; /* distance tree */
  11052. {
  11053. var dist; /* distance of matched string */
  11054. var lc; /* match length or unmatched char (if dist == 0) */
  11055. var lx = 0; /* running index in l_buf */
  11056. var code; /* the code to send */
  11057. var extra; /* number of extra bits to send */
  11058.  
  11059. if (s.last_lit !== 0) {
  11060. do {
  11061. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  11062. lc = s.pending_buf[s.l_buf + lx];
  11063. lx++;
  11064.  
  11065. if (dist === 0) {
  11066. send_code(s, lc, ltree); /* send a literal byte */
  11067. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  11068. } else {
  11069. /* Here, lc is the match length - MIN_MATCH */
  11070. code = _length_code[lc];
  11071. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  11072. extra = extra_lbits[code];
  11073. if (extra !== 0) {
  11074. lc -= base_length[code];
  11075. send_bits(s, lc, extra); /* send the extra length bits */
  11076. }
  11077. dist--; /* dist is now the match distance - 1 */
  11078. code = d_code(dist);
  11079. //Assert (code < D_CODES, "bad d_code");
  11080.  
  11081. send_code(s, code, dtree); /* send the distance code */
  11082. extra = extra_dbits[code];
  11083. if (extra !== 0) {
  11084. dist -= base_dist[code];
  11085. send_bits(s, dist, extra); /* send the extra distance bits */
  11086. }
  11087. } /* literal or match pair ? */
  11088.  
  11089. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  11090. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  11091. // "pendingBuf overflow");
  11092.  
  11093. } while (lx < s.last_lit);
  11094. }
  11095.  
  11096. send_code(s, END_BLOCK, ltree);
  11097. }
  11098.  
  11099.  
  11100. /* ===========================================================================
  11101. * Construct one Huffman tree and assigns the code bit strings and lengths.
  11102. * Update the total bit length for the current block.
  11103. * IN assertion: the field freq is set for all tree elements.
  11104. * OUT assertions: the fields len and code are set to the optimal bit length
  11105. * and corresponding code. The length opt_len is updated; static_len is
  11106. * also updated if stree is not null. The field max_code is set.
  11107. */
  11108. function build_tree(s, desc)
  11109. // deflate_state *s;
  11110. // tree_desc *desc; /* the tree descriptor */
  11111. {
  11112. var tree = desc.dyn_tree;
  11113. var stree = desc.stat_desc.static_tree;
  11114. var has_stree = desc.stat_desc.has_stree;
  11115. var elems = desc.stat_desc.elems;
  11116. var n, m; /* iterate over heap elements */
  11117. var max_code = -1; /* largest code with non zero frequency */
  11118. var node; /* new node being created */
  11119.  
  11120. /* Construct the initial heap, with least frequent element in
  11121. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  11122. * heap[0] is not used.
  11123. */
  11124. s.heap_len = 0;
  11125. s.heap_max = HEAP_SIZE;
  11126.  
  11127. for (n = 0; n < elems; n++) {
  11128. if (tree[n * 2]/*.Freq*/ !== 0) {
  11129. s.heap[++s.heap_len] = max_code = n;
  11130. s.depth[n] = 0;
  11131.  
  11132. } else {
  11133. tree[n * 2 + 1]/*.Len*/ = 0;
  11134. }
  11135. }
  11136.  
  11137. /* The pkzip format requires that at least one distance code exists,
  11138. * and that at least one bit should be sent even if there is only one
  11139. * possible code. So to avoid special checks later on we force at least
  11140. * two codes of non zero frequency.
  11141. */
  11142. while (s.heap_len < 2) {
  11143. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  11144. tree[node * 2]/*.Freq*/ = 1;
  11145. s.depth[node] = 0;
  11146. s.opt_len--;
  11147.  
  11148. if (has_stree) {
  11149. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  11150. }
  11151. /* node is 0 or 1 so it does not have extra bits */
  11152. }
  11153. desc.max_code = max_code;
  11154.  
  11155. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  11156. * establish sub-heaps of increasing lengths:
  11157. */
  11158. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  11159.  
  11160. /* Construct the Huffman tree by repeatedly combining the least two
  11161. * frequent nodes.
  11162. */
  11163. node = elems; /* next internal node of the tree */
  11164. do {
  11165. //pqremove(s, tree, n); /* n = node of least frequency */
  11166. /*** pqremove ***/
  11167. n = s.heap[1/*SMALLEST*/];
  11168. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  11169. pqdownheap(s, tree, 1/*SMALLEST*/);
  11170. /***/
  11171.  
  11172. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  11173.  
  11174. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  11175. s.heap[--s.heap_max] = m;
  11176.  
  11177. /* Create a new node father of n and m */
  11178. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  11179. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  11180. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  11181.  
  11182. /* and insert the new node in the heap */
  11183. s.heap[1/*SMALLEST*/] = node++;
  11184. pqdownheap(s, tree, 1/*SMALLEST*/);
  11185.  
  11186. } while (s.heap_len >= 2);
  11187.  
  11188. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  11189.  
  11190. /* At this point, the fields freq and dad are set. We can now
  11191. * generate the bit lengths.
  11192. */
  11193. gen_bitlen(s, desc);
  11194.  
  11195. /* The field len is now set, we can generate the bit codes */
  11196. gen_codes(tree, max_code, s.bl_count);
  11197. }
  11198.  
  11199.  
  11200. /* ===========================================================================
  11201. * Scan a literal or distance tree to determine the frequencies of the codes
  11202. * in the bit length tree.
  11203. */
  11204. function scan_tree(s, tree, max_code)
  11205. // deflate_state *s;
  11206. // ct_data *tree; /* the tree to be scanned */
  11207. // int max_code; /* and its largest code of non zero frequency */
  11208. {
  11209. var n; /* iterates over all tree elements */
  11210. var prevlen = -1; /* last emitted length */
  11211. var curlen; /* length of current code */
  11212.  
  11213. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  11214.  
  11215. var count = 0; /* repeat count of the current code */
  11216. var max_count = 7; /* max repeat count */
  11217. var min_count = 4; /* min repeat count */
  11218.  
  11219. if (nextlen === 0) {
  11220. max_count = 138;
  11221. min_count = 3;
  11222. }
  11223. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  11224.  
  11225. for (n = 0; n <= max_code; n++) {
  11226. curlen = nextlen;
  11227. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  11228.  
  11229. if (++count < max_count && curlen === nextlen) {
  11230. continue;
  11231.  
  11232. } else if (count < min_count) {
  11233. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  11234.  
  11235. } else if (curlen !== 0) {
  11236.  
  11237. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  11238. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  11239.  
  11240. } else if (count <= 10) {
  11241. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  11242.  
  11243. } else {
  11244. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  11245. }
  11246.  
  11247. count = 0;
  11248. prevlen = curlen;
  11249.  
  11250. if (nextlen === 0) {
  11251. max_count = 138;
  11252. min_count = 3;
  11253.  
  11254. } else if (curlen === nextlen) {
  11255. max_count = 6;
  11256. min_count = 3;
  11257.  
  11258. } else {
  11259. max_count = 7;
  11260. min_count = 4;
  11261. }
  11262. }
  11263. }
  11264.  
  11265.  
  11266. /* ===========================================================================
  11267. * Send a literal or distance tree in compressed form, using the codes in
  11268. * bl_tree.
  11269. */
  11270. function send_tree(s, tree, max_code)
  11271. // deflate_state *s;
  11272. // ct_data *tree; /* the tree to be scanned */
  11273. // int max_code; /* and its largest code of non zero frequency */
  11274. {
  11275. var n; /* iterates over all tree elements */
  11276. var prevlen = -1; /* last emitted length */
  11277. var curlen; /* length of current code */
  11278.  
  11279. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  11280.  
  11281. var count = 0; /* repeat count of the current code */
  11282. var max_count = 7; /* max repeat count */
  11283. var min_count = 4; /* min repeat count */
  11284.  
  11285. /* tree[max_code+1].Len = -1; */ /* guard already set */
  11286. if (nextlen === 0) {
  11287. max_count = 138;
  11288. min_count = 3;
  11289. }
  11290.  
  11291. for (n = 0; n <= max_code; n++) {
  11292. curlen = nextlen;
  11293. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  11294.  
  11295. if (++count < max_count && curlen === nextlen) {
  11296. continue;
  11297.  
  11298. } else if (count < min_count) {
  11299. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  11300.  
  11301. } else if (curlen !== 0) {
  11302. if (curlen !== prevlen) {
  11303. send_code(s, curlen, s.bl_tree);
  11304. count--;
  11305. }
  11306. //Assert(count >= 3 && count <= 6, " 3_6?");
  11307. send_code(s, REP_3_6, s.bl_tree);
  11308. send_bits(s, count - 3, 2);
  11309.  
  11310. } else if (count <= 10) {
  11311. send_code(s, REPZ_3_10, s.bl_tree);
  11312. send_bits(s, count - 3, 3);
  11313.  
  11314. } else {
  11315. send_code(s, REPZ_11_138, s.bl_tree);
  11316. send_bits(s, count - 11, 7);
  11317. }
  11318.  
  11319. count = 0;
  11320. prevlen = curlen;
  11321. if (nextlen === 0) {
  11322. max_count = 138;
  11323. min_count = 3;
  11324.  
  11325. } else if (curlen === nextlen) {
  11326. max_count = 6;
  11327. min_count = 3;
  11328.  
  11329. } else {
  11330. max_count = 7;
  11331. min_count = 4;
  11332. }
  11333. }
  11334. }
  11335.  
  11336.  
  11337. /* ===========================================================================
  11338. * Construct the Huffman tree for the bit lengths and return the index in
  11339. * bl_order of the last bit length code to send.
  11340. */
  11341. function build_bl_tree(s) {
  11342. var max_blindex; /* index of last bit length code of non zero freq */
  11343.  
  11344. /* Determine the bit length frequencies for literal and distance trees */
  11345. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  11346. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  11347.  
  11348. /* Build the bit length tree: */
  11349. build_tree(s, s.bl_desc);
  11350. /* opt_len now includes the length of the tree representations, except
  11351. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  11352. */
  11353.  
  11354. /* Determine the number of bit length codes to send. The pkzip format
  11355. * requires that at least 4 bit length codes be sent. (appnote.txt says
  11356. * 3 but the actual value used is 4.)
  11357. */
  11358. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  11359. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  11360. break;
  11361. }
  11362. }
  11363. /* Update opt_len to include the bit length tree and counts */
  11364. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  11365. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  11366. // s->opt_len, s->static_len));
  11367.  
  11368. return max_blindex;
  11369. }
  11370.  
  11371.  
  11372. /* ===========================================================================
  11373. * Send the header for a block using dynamic Huffman trees: the counts, the
  11374. * lengths of the bit length codes, the literal tree and the distance tree.
  11375. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  11376. */
  11377. function send_all_trees(s, lcodes, dcodes, blcodes)
  11378. // deflate_state *s;
  11379. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  11380. {
  11381. var rank; /* index in bl_order */
  11382.  
  11383. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  11384. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  11385. // "too many codes");
  11386. //Tracev((stderr, "\nbl counts: "));
  11387. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  11388. send_bits(s, dcodes - 1, 5);
  11389. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  11390. for (rank = 0; rank < blcodes; rank++) {
  11391. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  11392. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  11393. }
  11394. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  11395.  
  11396. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  11397. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  11398.  
  11399. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  11400. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  11401. }
  11402.  
  11403.  
  11404. /* ===========================================================================
  11405. * Check if the data type is TEXT or BINARY, using the following algorithm:
  11406. * - TEXT if the two conditions below are satisfied:
  11407. * a) There are no non-portable control characters belonging to the
  11408. * "black list" (0..6, 14..25, 28..31).
  11409. * b) There is at least one printable character belonging to the
  11410. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  11411. * - BINARY otherwise.
  11412. * - The following partially-portable control characters form a
  11413. * "gray list" that is ignored in this detection algorithm:
  11414. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  11415. * IN assertion: the fields Freq of dyn_ltree are set.
  11416. */
  11417. function detect_data_type(s) {
  11418. /* black_mask is the bit mask of black-listed bytes
  11419. * set bits 0..6, 14..25, and 28..31
  11420. * 0xf3ffc07f = binary 11110011111111111100000001111111
  11421. */
  11422. var black_mask = 0xf3ffc07f;
  11423. var n;
  11424.  
  11425. /* Check for non-textual ("black-listed") bytes. */
  11426. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  11427. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  11428. return Z_BINARY;
  11429. }
  11430. }
  11431.  
  11432. /* Check for textual ("white-listed") bytes. */
  11433. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  11434. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  11435. return Z_TEXT;
  11436. }
  11437. for (n = 32; n < LITERALS; n++) {
  11438. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  11439. return Z_TEXT;
  11440. }
  11441. }
  11442.  
  11443. /* There are no "black-listed" or "white-listed" bytes:
  11444. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  11445. */
  11446. return Z_BINARY;
  11447. }
  11448.  
  11449.  
  11450. var static_init_done = false;
  11451.  
  11452. /* ===========================================================================
  11453. * Initialize the tree data structures for a new zlib stream.
  11454. */
  11455. function _tr_init(s)
  11456. {
  11457.  
  11458. if (!static_init_done) {
  11459. tr_static_init();
  11460. static_init_done = true;
  11461. }
  11462.  
  11463. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  11464. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  11465. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  11466.  
  11467. s.bi_buf = 0;
  11468. s.bi_valid = 0;
  11469.  
  11470. /* Initialize the first block of the first file: */
  11471. init_block(s);
  11472. }
  11473.  
  11474.  
  11475. /* ===========================================================================
  11476. * Send a stored block
  11477. */
  11478. function _tr_stored_block(s, buf, stored_len, last)
  11479. //DeflateState *s;
  11480. //charf *buf; /* input block */
  11481. //ulg stored_len; /* length of input block */
  11482. //int last; /* one if this is the last block for a file */
  11483. {
  11484. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  11485. copy_block(s, buf, stored_len, true); /* with header */
  11486. }
  11487.  
  11488.  
  11489. /* ===========================================================================
  11490. * Send one empty static block to give enough lookahead for inflate.
  11491. * This takes 10 bits, of which 7 may remain in the bit buffer.
  11492. */
  11493. function _tr_align(s) {
  11494. send_bits(s, STATIC_TREES << 1, 3);
  11495. send_code(s, END_BLOCK, static_ltree);
  11496. bi_flush(s);
  11497. }
  11498.  
  11499.  
  11500. /* ===========================================================================
  11501. * Determine the best encoding for the current block: dynamic trees, static
  11502. * trees or store, and output the encoded block to the zip file.
  11503. */
  11504. function _tr_flush_block(s, buf, stored_len, last)
  11505. //DeflateState *s;
  11506. //charf *buf; /* input block, or NULL if too old */
  11507. //ulg stored_len; /* length of input block */
  11508. //int last; /* one if this is the last block for a file */
  11509. {
  11510. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  11511. var max_blindex = 0; /* index of last bit length code of non zero freq */
  11512.  
  11513. /* Build the Huffman trees unless a stored block is forced */
  11514. if (s.level > 0) {
  11515.  
  11516. /* Check if the file is binary or text */
  11517. if (s.strm.data_type === Z_UNKNOWN) {
  11518. s.strm.data_type = detect_data_type(s);
  11519. }
  11520.  
  11521. /* Construct the literal and distance trees */
  11522. build_tree(s, s.l_desc);
  11523. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  11524. // s->static_len));
  11525.  
  11526. build_tree(s, s.d_desc);
  11527. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  11528. // s->static_len));
  11529. /* At this point, opt_len and static_len are the total bit lengths of
  11530. * the compressed block data, excluding the tree representations.
  11531. */
  11532.  
  11533. /* Build the bit length tree for the above two trees, and get the index
  11534. * in bl_order of the last bit length code to send.
  11535. */
  11536. max_blindex = build_bl_tree(s);
  11537.  
  11538. /* Determine the best encoding. Compute the block lengths in bytes. */
  11539. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  11540. static_lenb = (s.static_len + 3 + 7) >>> 3;
  11541.  
  11542. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  11543. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  11544. // s->last_lit));
  11545.  
  11546. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  11547.  
  11548. } else {
  11549. // Assert(buf != (char*)0, "lost buf");
  11550. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  11551. }
  11552.  
  11553. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  11554. /* 4: two words for the lengths */
  11555.  
  11556. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  11557. * Otherwise we can't have processed more than WSIZE input bytes since
  11558. * the last block flush, because compression would have been
  11559. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  11560. * transform a block into a stored block.
  11561. */
  11562. _tr_stored_block(s, buf, stored_len, last);
  11563.  
  11564. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  11565.  
  11566. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  11567. compress_block(s, static_ltree, static_dtree);
  11568.  
  11569. } else {
  11570. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  11571. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  11572. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  11573. }
  11574. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  11575. /* The above check is made mod 2^32, for files larger than 512 MB
  11576. * and uLong implemented on 32 bits.
  11577. */
  11578. init_block(s);
  11579.  
  11580. if (last) {
  11581. bi_windup(s);
  11582. }
  11583. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  11584. // s->compressed_len-7*last));
  11585. }
  11586.  
  11587. /* ===========================================================================
  11588. * Save the match info and tally the frequency counts. Return true if
  11589. * the current block must be flushed.
  11590. */
  11591. function _tr_tally(s, dist, lc)
  11592. // deflate_state *s;
  11593. // unsigned dist; /* distance of matched string */
  11594. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  11595. {
  11596. //var out_length, in_length, dcode;
  11597.  
  11598. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  11599. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  11600.  
  11601. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  11602. s.last_lit++;
  11603.  
  11604. if (dist === 0) {
  11605. /* lc is the unmatched char */
  11606. s.dyn_ltree[lc * 2]/*.Freq*/++;
  11607. } else {
  11608. s.matches++;
  11609. /* Here, lc is the match length - MIN_MATCH */
  11610. dist--; /* dist = match distance - 1 */
  11611. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  11612. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  11613. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  11614.  
  11615. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  11616. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  11617. }
  11618.  
  11619. // (!) This block is disabled in zlib defailts,
  11620. // don't enable it for binary compatibility
  11621.  
  11622. //#ifdef TRUNCATE_BLOCK
  11623. // /* Try to guess if it is profitable to stop the current block here */
  11624. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  11625. // /* Compute an upper bound for the compressed length */
  11626. // out_length = s.last_lit*8;
  11627. // in_length = s.strstart - s.block_start;
  11628. //
  11629. // for (dcode = 0; dcode < D_CODES; dcode++) {
  11630. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  11631. // }
  11632. // out_length >>>= 3;
  11633. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  11634. // // s->last_lit, in_length, out_length,
  11635. // // 100L - out_length*100L/in_length));
  11636. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  11637. // return true;
  11638. // }
  11639. // }
  11640. //#endif
  11641.  
  11642. return (s.last_lit === s.lit_bufsize - 1);
  11643. /* We avoid equality with lit_bufsize because of wraparound at 64K
  11644. * on 16 bit machines and because stored blocks are restricted to
  11645. * 64K-1 bytes.
  11646. */
  11647. }
  11648.  
  11649. exports._tr_init = _tr_init;
  11650. exports._tr_stored_block = _tr_stored_block;
  11651. exports._tr_flush_block = _tr_flush_block;
  11652. exports._tr_tally = _tr_tally;
  11653. exports._tr_align = _tr_align;
  11654.  
  11655. },{"../utils/common":62}],74:[function(require,module,exports){
  11656. 'use strict';
  11657.  
  11658. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  11659. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  11660. //
  11661. // This software is provided 'as-is', without any express or implied
  11662. // warranty. In no event will the authors be held liable for any damages
  11663. // arising from the use of this software.
  11664. //
  11665. // Permission is granted to anyone to use this software for any purpose,
  11666. // including commercial applications, and to alter it and redistribute it
  11667. // freely, subject to the following restrictions:
  11668. //
  11669. // 1. The origin of this software must not be misrepresented; you must not
  11670. // claim that you wrote the original software. If you use this software
  11671. // in a product, an acknowledgment in the product documentation would be
  11672. // appreciated but is not required.
  11673. // 2. Altered source versions must be plainly marked as such, and must not be
  11674. // misrepresented as being the original software.
  11675. // 3. This notice may not be removed or altered from any source distribution.
  11676.  
  11677. function ZStream() {
  11678. /* next input byte */
  11679. this.input = null; // JS specific, because we have no pointers
  11680. this.next_in = 0;
  11681. /* number of bytes available at input */
  11682. this.avail_in = 0;
  11683. /* total number of input bytes read so far */
  11684. this.total_in = 0;
  11685. /* next output byte should be put there */
  11686. this.output = null; // JS specific, because we have no pointers
  11687. this.next_out = 0;
  11688. /* remaining free space at output */
  11689. this.avail_out = 0;
  11690. /* total number of bytes output so far */
  11691. this.total_out = 0;
  11692. /* last error message, NULL if no error */
  11693. this.msg = ''/*Z_NULL*/;
  11694. /* not visible by applications */
  11695. this.state = null;
  11696. /* best guess about the data type: binary or text */
  11697. this.data_type = 2/*Z_UNKNOWN*/;
  11698. /* adler32 value of the uncompressed data */
  11699. this.adler = 0;
  11700. }
  11701.  
  11702. module.exports = ZStream;
  11703.  
  11704. },{}]},{},[10])(10)
  11705. });/* FileSaver.js
  11706. * A saveAs() FileSaver implementation.
  11707. * 1.1.20160328
  11708. *
  11709. * By Eli Grey, http://eligrey.com
  11710. * License: MIT
  11711. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  11712. */
  11713.  
  11714. /*global self */
  11715. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  11716.  
  11717. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  11718.  
  11719. var saveAs = saveAs || (function(view) {
  11720. "use strict";
  11721. // IE <10 is explicitly unsupported
  11722. if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  11723. return;
  11724. }
  11725. var
  11726. doc = view.document
  11727. // only get URL when necessary in case Blob.js hasn't overridden it yet
  11728. , get_URL = function() {
  11729. return view.URL || view.webkitURL || view;
  11730. }
  11731. , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  11732. , can_use_save_link = "download" in save_link
  11733. , click = function(node) {
  11734. var event = new MouseEvent("click");
  11735. node.dispatchEvent(event);
  11736. }
  11737. , is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent)
  11738. , webkit_req_fs = view.webkitRequestFileSystem
  11739. , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
  11740. , throw_outside = function(ex) {
  11741. (view.setImmediate || view.setTimeout)(function() {
  11742. throw ex;
  11743. }, 0);
  11744. }
  11745. , force_saveable_type = "application/octet-stream"
  11746. , fs_min_size = 0
  11747. // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
  11748. , arbitrary_revoke_timeout = 1000 * 40 // in ms
  11749. , revoke = function(file) {
  11750. var revoker = function() {
  11751. if (typeof file === "string") { // file is an object URL
  11752. get_URL().revokeObjectURL(file);
  11753. } else { // file is a File
  11754. file.remove();
  11755. }
  11756. };
  11757. /* // Take note W3C:
  11758. var
  11759. uri = typeof file === "string" ? file : file.toURL()
  11760. , revoker = function(evt) {
  11761. // idealy DownloadFinishedEvent.data would be the URL requested
  11762. if (evt.data === uri) {
  11763. if (typeof file === "string") { // file is an object URL
  11764. get_URL().revokeObjectURL(file);
  11765. } else { // file is a File
  11766. file.remove();
  11767. }
  11768. }
  11769. }
  11770. ;
  11771. view.addEventListener("downloadfinished", revoker);
  11772. */
  11773. setTimeout(revoker, arbitrary_revoke_timeout);
  11774. }
  11775. , dispatch = function(filesaver, event_types, event) {
  11776. event_types = [].concat(event_types);
  11777. var i = event_types.length;
  11778. while (i--) {
  11779. var listener = filesaver["on" + event_types[i]];
  11780. if (typeof listener === "function") {
  11781. try {
  11782. listener.call(filesaver, event || filesaver);
  11783. } catch (ex) {
  11784. throw_outside(ex);
  11785. }
  11786. }
  11787. }
  11788. }
  11789. , auto_bom = function(blob) {
  11790. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  11791. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  11792. return new Blob(["\ufeff", blob], {type: blob.type});
  11793. }
  11794. return blob;
  11795. }
  11796. , FileSaver = function(blob, name, no_auto_bom) {
  11797. if (!no_auto_bom) {
  11798. blob = auto_bom(blob);
  11799. }
  11800. // First try a.download, then web filesystem, then object URLs
  11801. var
  11802. filesaver = this
  11803. , type = blob.type
  11804. , blob_changed = false
  11805. , object_url
  11806. , target_view
  11807. , dispatch_all = function() {
  11808. dispatch(filesaver, "writestart progress write writeend".split(" "));
  11809. }
  11810. // on any filesys errors revert to saving with object URLs
  11811. , fs_error = function() {
  11812. if (target_view && is_safari && typeof FileReader !== "undefined") {
  11813. // Safari doesn't allow downloading of blob urls
  11814. var reader = new FileReader();
  11815. reader.onloadend = function() {
  11816. var base64Data = reader.result;
  11817. target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
  11818. filesaver.readyState = filesaver.DONE;
  11819. dispatch_all();
  11820. };
  11821. reader.readAsDataURL(blob);
  11822. filesaver.readyState = filesaver.INIT;
  11823. return;
  11824. }
  11825. // don't create more object URLs than needed
  11826. if (blob_changed || !object_url) {
  11827. object_url = get_URL().createObjectURL(blob);
  11828. }
  11829. if (target_view) {
  11830. target_view.location.href = object_url;
  11831. } else {
  11832. var new_tab = view.open(object_url, "_blank");
  11833. if (new_tab === undefined && is_safari) {
  11834. //Apple do not allow window.open, see http://bit.ly/1kZffRI
  11835. view.location.href = object_url
  11836. }
  11837. }
  11838. filesaver.readyState = filesaver.DONE;
  11839. dispatch_all();
  11840. revoke(object_url);
  11841. }
  11842. , abortable = function(func) {
  11843. return function() {
  11844. if (filesaver.readyState !== filesaver.DONE) {
  11845. return func.apply(this, arguments);
  11846. }
  11847. };
  11848. }
  11849. , create_if_not_found = {create: true, exclusive: false}
  11850. , slice
  11851. ;
  11852. filesaver.readyState = filesaver.INIT;
  11853. if (!name) {
  11854. name = "download";
  11855. }
  11856. if (can_use_save_link) {
  11857. object_url = get_URL().createObjectURL(blob);
  11858. setTimeout(function() {
  11859. save_link.href = object_url;
  11860. save_link.download = name;
  11861. click(save_link);
  11862. dispatch_all();
  11863. revoke(object_url);
  11864. filesaver.readyState = filesaver.DONE;
  11865. });
  11866. return;
  11867. }
  11868. // Object and web filesystem URLs have a problem saving in Google Chrome when
  11869. // viewed in a tab, so I force save with application/octet-stream
  11870. // http://code.google.com/p/chromium/issues/detail?id=91158
  11871. // Update: Google errantly closed 91158, I submitted it again:
  11872. // https://code.google.com/p/chromium/issues/detail?id=389642
  11873. if (view.chrome && type && type !== force_saveable_type) {
  11874. slice = blob.slice || blob.webkitSlice;
  11875. blob = slice.call(blob, 0, blob.size, force_saveable_type);
  11876. blob_changed = true;
  11877. }
  11878. // Since I can't be sure that the guessed media type will trigger a download
  11879. // in WebKit, I append .download to the filename.
  11880. // https://bugs.webkit.org/show_bug.cgi?id=65440
  11881. if (webkit_req_fs && name !== "download") {
  11882. name += ".download";
  11883. }
  11884. if (type === force_saveable_type || webkit_req_fs) {
  11885. target_view = view;
  11886. }
  11887. if (!req_fs) {
  11888. fs_error();
  11889. return;
  11890. }
  11891. fs_min_size += blob.size;
  11892. req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
  11893. fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
  11894. var save = function() {
  11895. dir.getFile(name, create_if_not_found, abortable(function(file) {
  11896. file.createWriter(abortable(function(writer) {
  11897. writer.onwriteend = function(event) {
  11898. target_view.location.href = file.toURL();
  11899. filesaver.readyState = filesaver.DONE;
  11900. dispatch(filesaver, "writeend", event);
  11901. revoke(file);
  11902. };
  11903. writer.onerror = function() {
  11904. var error = writer.error;
  11905. if (error.code !== error.ABORT_ERR) {
  11906. fs_error();
  11907. }
  11908. };
  11909. "writestart progress write abort".split(" ").forEach(function(event) {
  11910. writer["on" + event] = filesaver["on" + event];
  11911. });
  11912. writer.write(blob);
  11913. filesaver.abort = function() {
  11914. writer.abort();
  11915. filesaver.readyState = filesaver.DONE;
  11916. };
  11917. filesaver.readyState = filesaver.WRITING;
  11918. }), fs_error);
  11919. }), fs_error);
  11920. };
  11921. dir.getFile(name, {create: false}, abortable(function(file) {
  11922. // delete file if it already exists
  11923. file.remove();
  11924. save();
  11925. }), abortable(function(ex) {
  11926. if (ex.code === ex.NOT_FOUND_ERR) {
  11927. save();
  11928. } else {
  11929. fs_error();
  11930. }
  11931. }));
  11932. }), fs_error);
  11933. }), fs_error);
  11934. }
  11935. , FS_proto = FileSaver.prototype
  11936. , saveAs = function(blob, name, no_auto_bom) {
  11937. return new FileSaver(blob, name, no_auto_bom);
  11938. }
  11939. ;
  11940. // IE 10+ (native saveAs)
  11941. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  11942. return function(blob, name, no_auto_bom) {
  11943. if (!no_auto_bom) {
  11944. blob = auto_bom(blob);
  11945. }
  11946. return navigator.msSaveOrOpenBlob(blob, name || "download");
  11947. };
  11948. }
  11949.  
  11950. FS_proto.abort = function() {
  11951. var filesaver = this;
  11952. filesaver.readyState = filesaver.DONE;
  11953. dispatch(filesaver, "abort");
  11954. };
  11955. FS_proto.readyState = FS_proto.INIT = 0;
  11956. FS_proto.WRITING = 1;
  11957. FS_proto.DONE = 2;
  11958.  
  11959. FS_proto.error =
  11960. FS_proto.onwritestart =
  11961. FS_proto.onprogress =
  11962. FS_proto.onwrite =
  11963. FS_proto.onabort =
  11964. FS_proto.onerror =
  11965. FS_proto.onwriteend =
  11966. null;
  11967.  
  11968. return saveAs;
  11969. }(
  11970. typeof self !== "undefined" && self
  11971. || typeof window !== "undefined" && window
  11972. || this.content
  11973. ));
  11974. // `self` is undefined in Firefox for Android content script context
  11975. // while `this` is nsIContentFrameMessageManager
  11976. // with an attribute `content` that corresponds to the window
  11977.  
  11978. if (typeof module !== "undefined" && module.exports) {
  11979. module.exports.saveAs = saveAs;
  11980. } else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
  11981. define([], function() {
  11982. return saveAs;
  11983. });
  11984. }
  11985.  
  11986. var zip;
  11987. var imageList = [];
  11988. var imageData = [];
  11989. var infoStr;
  11990. var origin = window.location.origin;
  11991. var setting = null;
  11992. var fetchCount = 0;
  11993. var downloadedCount = 0;
  11994. var totalCount = 0;
  11995. var retryCount = 0;
  11996. var failedCount = 0;
  11997. var fetchThread = [];
  11998. var dirName;
  11999. var fileName;
  12000. var progressTable = null;
  12001. var needNumberImages = false;
  12002. var pagesRange = [];
  12003. var isDownloading = false;
  12004. var isPausing = false;
  12005. var isSaving = false;
  12006. var pageURLsList = [];
  12007. var getAllPagesURLFin = false;
  12008. var pretitle = document.title;
  12009. var needTitleStatus = false;
  12010. var delayTime = 0;
  12011. var fetchPagesXHR = new XMLHttpRequest();
  12012. var emptyAudio;
  12013. var emptyAudioFile = 'data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU3LjcxLjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAAEAAABVgANTU1NTU1Q0NDQ0NDUFBQUFBQXl5eXl5ea2tra2tra3l5eXl5eYaGhoaGhpSUlJSUlKGhoaGhoaGvr6+vr6+8vLy8vLzKysrKysrX19fX19fX5eXl5eXl8vLy8vLy////////AAAAAExhdmM1Ny44OQAAAAAAAAAAAAAAACQCgAAAAAAAAAVY82AhbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAALACwAAP/AADwQKVE9YWDGPkQWpT66yk4+zIiYPoTUaT3tnU487uNhOvEmQDaCm1Yz1c6DPjbs6zdZVBk0pdGpMzxF/+MYxA8L0DU0AP+0ANkwmYaAMkOKDDjmYoMtwNMyDxMzDHE/MEsLow9AtDnBlQgDhTx+Eye0GgMHoCyDC8gUswJcMVMABBGj/+MYxBoK4DVpQP8iAtVmDk7LPgi8wvDzI4/MWAwK1T7rxOQwtsItMMQBazAowc4wZMC5MF4AeQAGDpruNuMEzyfjLBJhACU+/+MYxCkJ4DVcAP8MAO9J9THVg6oxRMGNMIqCCTAEwzwwBkINOPAs/iwjgBnMepYyId0PhWo+80PXMVsBFzD/AiwwfcKGMEJB/+MYxDwKKDVkAP8eAF8wMwIxMlpU/OaDPLpNKkEw4dRoBh6qP2FC8jCJQFcweQIPMHOBtTBoAVcwOoCNMYDI0u0Dd8ANTIsy/+MYxE4KUDVsAP8eAFBVpgVVPjdGeTEWQr0wdcDtMCeBgDBkgRgwFYB7Pv/zqx0yQQMCCgKNgonHKj6RRVkxM0GwML0AhDAN/+MYxF8KCDVwAP8MAIHZMDDA3DArAQo3K+TF5WOBDQw0lgcKQUJxhT5sxRcwQQI+EIPWMA7AVBoTABgTgzfBN+ajn3c0lZMe/+MYxHEJyDV0AP7MAA4eEwsqP/PDmzC/gNcwXUGaMBVBIwMEsmB6gaxhVuGkpoqMZMQjooTBwM0+S8FTMC0BcjBTgPwwOQDm/+MYxIQKKDV4AP8WADAzAKQwI4CGPhWOEwCFAiBAYQnQMT+uwXUeGzjBWQVkwTcENMBzA2zAGgFEJfSPkPSZzPXgqFy2h0xB/+MYxJYJCDV8AP7WAE0+7kK7MQrATDAvQRIwOADKMBuA9TAYQNM3AiOSPjGxowgHMKFGcBNMQU1FMy45OS41VVU/31eYM4sK/+MYxKwJaDV8AP7SAI4y1Yq0MmOIADGwBZwwlgIJMztCM0qU5TQPG/MSkn8yEROzCdAxECVMQU1FMy45OS41VTe7Ohk+Pqcx/+MYxMEJMDWAAP6MADVLDFUx+4J6Mq7NsjN2zXo8V5fjVJCXNOhwM0vTCDAxFpMYYQU+RlVMQU1FMy45OS41VVVVVVVVVVVV/+MYxNcJADWAAP7EAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV/+MYxOsJwDWEAP7SAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV/+MYxPMLoDV8AP+eAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV/+MYxPQL0DVcAP+0AFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV';
  12014.  
  12015. var ehDownloadRegex = {
  12016. imageURL: [
  12017. /<a href="(\S+?\/fullimg\.php\?\S+?)"/,
  12018. /<img id="img" src="(\S+?)"/,
  12019. /<\/(?:script|iframe)><a[\s\S]+?><img src="(\S+?)"/ // Sometimes preview image may not have id="img"
  12020. ],
  12021. nextFetchURL: [
  12022. /<a id="next"[\s\S]+?href="(\S+?\/s\/\S+?)"/,
  12023. /<a href="(\S+?\/s\/\S+?)"><img src="https?:\/\/ehgt.org\/g\/n.png"/
  12024. ],
  12025. preFetchURL: /<div class="sn"><a[\s\S]+?href="(\S+?\/s\/\S+?)"/,
  12026. nl: /return nl\('([\d-]+)'\)/,
  12027. fileName: /g\/l.png"\s?\/><\/a><\/div><div>([\s\S]+?) :: /,
  12028. resFileName: /filename=['"]?([\s\S]+?)['"]?$/m,
  12029. dangerChars: /[:"*?|<>\/\\\n]/g,
  12030. pagesRange: /^(\d*(-\d*(\/\d+)?)?\s*,\s*)*\d*(-\d*(\/\d+)?)?$/,
  12031. pagesURL: /(?:<a href=").+?(?=")/gi,
  12032. mpvKey: /var imagelist\s*=\s*(\[.+?\]);/,
  12033. imageLimits: /You are currently at <strong>(\d+)<\/strong> towards a limit of <strong>(\d+)<\/strong>/,
  12034. pagesLength: /<table class="ptt".+>(\d+)<\/a>.+?<\/table>/,
  12035. IPBanExpires: /The ban expires in \d+ hours?( and \d+ minutes?)?/,
  12036. categoryTag: /g\/c\/(\w+)\./,
  12037. slashOnly: /^[\\/]*$/
  12038. };
  12039.  
  12040. var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
  12041. var ehDownloadFS = {
  12042. fs: undefined,
  12043. needFileSystem: false,
  12044. initHandler: function(fs) {
  12045. ehDownloadFS.fs = fs;
  12046. console.log('[EHD] File System is opened! Name >', fs.name);
  12047. ehDownloadFS.removeAllFiles(fs); // It's sure that user have downloaded or ignored temp archive
  12048. },
  12049. errorHandler: function(e) {
  12050. var errorMsg = 'File System Request Error > ';
  12051. errorMsg += e.name || 'Unknown Error';
  12052. console.error('[EHD] ' + errorMsg, e.message);
  12053. console.error(e);
  12054. },
  12055. saveAs: function(fs, forced){
  12056. var fs = fs || ehDownloadFS.fs;
  12057. if (fs === undefined) return;
  12058. fs.root.getFile(unsafeWindow.gid + '.zip', {}, function (fileEntry) {
  12059. var url = fileEntry.toURL();
  12060. console.log('[EHD] File URL >', url);
  12061. var a = document.createElement('a');
  12062. a.setAttribute('href', url);
  12063. a.setAttribute('download', fileName + (setting['save-as-cbz'] ? '.cbz' : '.zip'));
  12064. a.click();
  12065. pushDialog('\n\nNot download or file is broken? <a href="' + url + '" download="' + fileName + (setting['save-as-cbz'] ? '.cbz' : '.zip') + '" style="color: #ffffff; font-weight: bold;">Click here to download</a>\n\n');
  12066. if (!forced) {
  12067. insertCloseButton();
  12068. if (emptyAudio) {
  12069. emptyAudio.pause();
  12070. }
  12071. }
  12072. });
  12073. },
  12074. removeFile: function(fileName, fs, isEntry){
  12075. var fs = fs || ehDownloadFS.fs;
  12076. if (fs === undefined) return;
  12077. var removeFunction = function(fileEntry){
  12078. if (fileEntry.isFile) fileEntry.remove(function(){
  12079. console.log('[EHD] File', fileName, 'is removed.');
  12080. });
  12081. else if (fileEntry.isDirectory) fileEntry.removeRecursively(function() {
  12082. console.log('[EHD] Directory', fileName, 'is removed.');
  12083. });
  12084. };
  12085. if (isEntry) removeFunction(fileName);
  12086. else fs.root.getFile(fileName, {create: false}, removeFunction);
  12087. },
  12088. removeAllFiles: function(fs){
  12089. var fs = fs || ehDownloadFS.fs;
  12090. if (fs === undefined) return;
  12091. console.log('[EHD] Request removing all files in File System.');
  12092. fs.root.createReader().readEntries(function(entries){
  12093. if (entries.length === 0) return;
  12094. for (var i = 0; i < entries.length; i++) {
  12095. ehDownloadFS.removeFile(entries[i], fs, true);
  12096. }
  12097. }, ehDownloadFS.errorHandler);
  12098. },
  12099. initCheckerHandler: function(fs) {
  12100. //ehDownloadFS.fs = fs;
  12101. console.log('[EHD] File System is opened! Name >', fs.name);
  12102. ehDownloadFS.removeFile(unsafeWindow.gid + '.zip', fs);
  12103. fs.root.getFile('config.txt', {create: false}, function(fileEntry){
  12104. fileEntry.file(function(file){
  12105. var fileReader = new FileReader();
  12106. fileReader.onloadend = function() {
  12107. var value = this.result;
  12108. if (value === '' || value == null) return;
  12109. var data = JSON.parse(value);
  12110. if (data && confirm('You have an archive that is not downloaded, save it?\n\nFile Name: ' + data.fileName + '\n\n* If you have already downloaded it, click cancel to remove the cached archive file.')) {
  12111. fileName = data.fileName;
  12112. dirName = data.dirName;
  12113. ehDownloadFS.storeTempArchive(data, fs);
  12114. }
  12115. else {
  12116. ehDownloadFS.removeAllFiles(fs);
  12117. }
  12118. };
  12119. fileReader.readAsText(file);
  12120. });
  12121. });
  12122. },
  12123. storeTempArchive: function(data, fs){
  12124. var fs = fs || ehDownloadFS.fs;
  12125. if (fs === undefined) return;
  12126. fs.root.getDirectory('raw', {}, function(fileEntry){
  12127. fileEntry.createReader().readEntries(function(entries){
  12128. if (entries.length === 0) return;
  12129. var index = 0;
  12130. var fileReader = new FileReader();
  12131. zip = new JSZip();
  12132. ehDownloadDialog.style.display = 'block';
  12133. ehDownloadDialog.innerHTML = '';
  12134. pushDialog('Preparing......');
  12135. fileReader.onloadend = function() {
  12136. (data.dirName && !ehDownloadRegex.slashOnly.test(data.dirName) ? zip.folder(data.dirName) : zip).file(entries[index].name, this.result);
  12137. index++;
  12138. if (index < entries.length) addFile();
  12139. else {
  12140. ehDownloadFS.removeAllFiles();
  12141. setTimeout(generateZip, 3000, true, fs); // wait for removing all files
  12142. }
  12143. };
  12144. var addFile = function(){
  12145. console.log('[EHD] TempArchiveFileIndex >', index, '| TempArchiveFileName >', entries[index].name, '| TempArchiveFilePath >', entries[index].fullPath, '| TempArchiveFileLength >', entries.length);
  12146. pushDialog('\n' + (index + 1) + '/' + entries.length);
  12147. fs.root.getFile(entries[index].fullPath, {create: false}, function(fileEntry){
  12148. fileEntry.file(function(file){
  12149. fileReader.readAsArrayBuffer(file);
  12150. });
  12151. });
  12152. };
  12153. addFile();
  12154. }, ehDownloadFS.errorHandler);
  12155. }, ehDownloadFS.errorHandler);
  12156. }
  12157. };
  12158.  
  12159. var ehDownloadStyle = '\
  12160. @-webkit-keyframes progress { \
  12161. from { -webkit-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \
  12162. 60% { -webkit-transform: translateX(15%) scaleX(0.7); transform: translateX(15%) scaleX(0.7); } \
  12163. to { -webkit-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \
  12164. } \
  12165. @-moz-keyframes progress { \
  12166. from { -moz-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \
  12167. 60% { -moz-transform: translateX(15%) scaleX(0.7); transform: translateX(15%) scaleX(0.7); } \
  12168. to { -moz-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \
  12169. } \
  12170. @-ms-keyframes progress { \
  12171. from { -ms-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \
  12172. 60% { -ms-transform: translateX(15%) scaleX(0.7); transform: translateX(15%) scaleX(0.7); } \
  12173. to { -ms-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \
  12174. } \
  12175. @keyframes progress { \
  12176. from { -webkit-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \
  12177. 60% { -webkit-transform: translateX(15%) scaleX(0.7); transform: translateX(15%) scaleX(0.7); } \
  12178. to { -webkit-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \
  12179. } \
  12180. .ehD-box { margin: 20px auto; width: 732px; box-sizing: border-box; font-size: 12px; border: 1px groove #000000; }\
  12181. .ehD-box a { cursor: pointer; }\
  12182. .ehD-box .g2 { display: inline-block; margin: 10px; padding: 0; line-height: 14px; }\
  12183. .ehD-box legend { font-weight: 700; padding: 0 10px; } \
  12184. .ehD-box legend a { color: inherit; text-decoration: none; }\
  12185. .ehD-box input[type="text"] { width: 250px; }\
  12186. .ehD-box-extend input[type="text"] { width: 255px; }\
  12187. .ehD-box input::placeholder { color: #999999; -webkit-text-fill-color: #999999; }\
  12188. .ehD-setting { position: fixed; left: 0; right: 0; top: 0; bottom: 0; padding: 5px; border: 1px solid #000000; background: #34353b; color: #dddddd; width: 600px; height: 380px; max-width: 100%; max-height: 100%; overflow-x: hidden; overflow-y: auto; box-sizing: border-box; margin: auto; z-index: 999; text-align: left; font-size: 12px; outline: 5px rgba(0, 0, 0, 0.25) solid; }\
  12189. .ehD-setting-tab { list-style: none; margin: 5px 0; padding: 0 10px; border-bottom: 1px solid #cccccc; overflow: auto; }\
  12190. .ehD-setting-tab li { float: left; padding: 5px 10px; border-bottom: 0; cursor: pointer; }\
  12191. .ehD-setting[data-active-setting="basic"] li[data-target-setting="basic"], .ehD-setting[data-active-setting="advanced"] li[data-target-setting="advanced"] { font-weight: bold; background: #cccccc; color: #000000; }\
  12192. .ehD-setting-main { overflow: hidden }\
  12193. .ehD-setting-wrapper { width: 200%; overflow: hidden; -webkit-transform: translateX(0%); -moz-transform: translateX(0%); -o-transform: translateX(0%); -ms-transform: translateX(0%); transform: translateX(0%); -webkit-transition: all 0.5s cubic-bezier(0.86, 0, 0.07, 1); -moz-transition: all 0.5s cubic-bezier(0.86, 0, 0.07, 1); -o-transition: all 0.5s cubic-bezier(0.86, 0, 0.07, 1); -ms-transition: all 0.5s cubic-bezier(0.86, 0, 0.07, 1); transition: all 0.5s cubic-bezier(0.86, 0, 0.07, 1); }\
  12194. .ehD-setting[data-active-setting="advanced"] .ehD-setting-wrapper { -webkit-transform: translateX(-50%); -moz-transform: translateX(-50%); -o-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%); }\
  12195. .ehD-setting-content { width: 50%; float: left; box-sizing: border-box; padding: 5px 10px; height: 295px; max-height: calc(100vh - 85px); overflow: auto; }\
  12196. .ehD-setting .g2 { padding-bottom: 10px; }\
  12197. .ehD-setting input, .ehD-box input, .ehD-setting select, .ehD-box select { vertical-align: middle; top: 0; margin: 0; }\
  12198. .ehD-setting input[type="text"], .ehD-box input[type="text"], .ehD-setting input[type="number"] { height: 18px; padding: 0 0 0 3px; line-height: 18px; border-radius: 3px; }\
  12199. .ehD-setting input[type="text"], .ehD-setting input[type="number"] { border: 1px solid #8d8d8d; } \
  12200. .ehD-setting input[type="checkbox"] { margin: 3px 3px 4px 0 } \
  12201. .ehD-setting select { padding: 0 3px 1px; } \
  12202. .ehD-setting-note { border: 1px dashed #999999; padding: 10px 10px 0 10px; }\
  12203. .ehD-setting-footer { text-align: center; margin-top: 5px; border-top: 1px solid #cccccc; padding-top: 5px; }\
  12204. .ehD-setting sup { vertical-align: top; }\
  12205. .ehD-setting a { color: #ffffff; }\
  12206. .ehD-box input[type="number"] { height: 17px; }\
  12207. .ehD-dialog progress { height: 12px; -webkit-appearance: none; border: 1px solid #4f535b; color: #4f535b; background: #34353b; position: relative; } \
  12208. .ehD-dialog progress::-webkit-progress-bar { background: #34353b; } \
  12209. .ehD-dialog progress::-webkit-progress-value { background: #4f535b; -webkit-transition: all 0.2s ease; transition: all 0.2s ease; } \
  12210. .ehD-dialog progress::-moz-progress-bar { background: #4f535b; -moz-transition: all 0.2s ease; transition: all 0.2s ease; } \
  12211. .ehD-dialog progress::-ms-fill { background: #4f535b; -ms-transition: all 0.2s ease; transition: all 0.2s ease; } \
  12212. .ehD-dialog progress:not([value])::after { content: ""; will-change: transform; width: 100%; height: 100%; left: 0; top: 0; display: block; background: #4f535b; position: absolute; -webkit-animation: progress 1s linear infinite; -moz-animation: progress 1s linear infinite; -ms-animation: progress 1s linear infinite; animation: progress 1s linear infinite; } \
  12213. .ehD-dialog progress:not([value])::-moz-progress-bar { width: 0px !important; } \
  12214. .ehD-pt { table-layout: fixed; width: 100%; }\
  12215. .ehD-pt-name { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\
  12216. .ehD-pt-progress-outer { width: 160px; position: relative; }\
  12217. .ehD-pt-progress { width: 150px; }\
  12218. .ehD-pt-progress-text { position: absolute; width: 100%; text-align: center; color: #b8b8b8; left: 0; right: 0; }\
  12219. .ehD-pt-status { width: 130px; }\
  12220. .ehD-pt-succeed .ehD-pt-status { color: #00ff00; }\
  12221. .ehD-pt-warning .ehD-pt-status { color: #ffff00; }\
  12222. .ehD-pt-failed .ehD-pt-status { color: #ff0000; }\
  12223. .ehD-pt-abort { color: #ffff00; display: none; cursor: pointer; }\
  12224. .ehD-pt-status[data-inited-abort]:hover .ehD-pt-abort, .ehD-pt-failed .ehD-pt-status[data-inited-abort]:hover .ehD-pt-status-text, .ehD-pt-succeed .ehD-pt-status[data-inited-abort]:hover .ehD-pt-status-text { display: inline; }\
  12225. .ehD-pt-status[data-inited-abort]:hover .ehD-pt-status-text, .ehD-pt-failed .ehD-pt-status[data-inited-abort]:hover .ehD-pt-abort, .ehD-pt-succeed .ehD-pt-status[data-inited-abort]:hover .ehD-pt-abort { display: none; }\
  12226. .ehD-pt-gen-progress { width: 50%; }\
  12227. .ehD-pt-gen-filename { margin-bottom: 1em; }\
  12228. .ehD-dialog { position: fixed; right: 0; bottom: 0; display: none; padding: 5px; border: 1px solid #000000; background: #34353b; color: #dddddd; width: 550px; height: 300px; overflow: auto; z-index: 999; word-break: break-all; }\
  12229. .ehD-status { position: fixed; right: 0; bottom: 311px; width: 550px; padding: 5px; border: 1px solid #000000; background: #34353b; color: #dddddd; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -o-user-select: none; -ms-user-select: none; user-select: none; }\
  12230. .ehD-dialog, .ehD-status { -webkit-transition: margin 0.5s ease; -moz-transition: margin 0.5s ease; -o-transition: margin 0.5s ease; -ms-transition: margin 0.5s ease; transition: margin 0.5s ease; }\
  12231. .ehD-dialog.hidden, .ehD-dialog.hidden .ehD-status { margin-bottom: -311px; }\
  12232. .ehD-dialog .ehD-force-download-tips { position: fixed; right: 0; bottom: 288px; border: 1px solid #000000; width: 550px; padding: 5px; background: rgba(0, 0, 0, 0.75); color: #ffffff; cursor: pointer; opacity: 0; pointer-events: none; -webkit-transition: opacity 0.5s ease, bottom 0.5s ease; -moz-transition: opacity 0.5s ease, bottom 0.5s ease; -o-transition: opacity 0.5s ease, bottom 0.5s ease; -ms-transition: opacity 0.5s ease, bottom 0.5s ease; transition: opacity 0.5s ease, bottom 0.5s ease; }\
  12233. .ehD-dialog:hover .ehD-force-download-tips { opacity: 1; }\
  12234. .ehD-dialog.hidden .ehD-force-download-tips { bottom: -24px; }\
  12235. .ehD-close-tips { position: fixed; left: 0; right: 0; bottom: 0; padding: 10px; border: 1px solid #000000; background: #34353b; color: #dddddd; width: 732px; max-width: 100%; max-height: 100%; overflow-x: hidden; overflow-y: auto; box-sizing: border-box; margin: auto; z-index: 1000; text-align: left; font-size: 14px; outline: 5px rgba(0, 0, 0, 0.25) solid; }\
  12236. .ehD-feedback { position: absolute; right: 5px; top: 14px; }\
  12237. ';
  12238.  
  12239. function initSetting() {
  12240. loadSetting().then(function (res) {
  12241. setting = res ? JSON.parse(res) : {};
  12242. needNumberImages = setting['number-images'];
  12243. needTitleStatus = setting['status-in-title'] === 'always' ? true : false;
  12244.  
  12245. // overwrite settings or set default settings
  12246. if (setting['status-in-title'] === true) setting['status-in-title'] = 'blur';
  12247. if (!setting['save-info-list']) {
  12248. setting['save-info-list'] = ['title', 'metas', 'uploader-comment', 'page-links'];
  12249. }
  12250. if (localStorage.getItem('ehd-image-limits-g.e-hentai.org')) {
  12251. localStorage.removeItem('ehd-image-limits-g.e-hentai.org');
  12252. }
  12253. // remove config of get image limits from r.e-hentai.org
  12254. if (setting['image-limits-both']) {
  12255. delete setting['image-limits-both'];
  12256. GM_setValue('ehD-setting', JSON.stringify(setting));
  12257. }
  12258. if (localStorage.getItem('ehd-image-limits-r.e-hentai.org')) {
  12259. localStorage.removeItem('ehd-image-limits-r.e-hentai.org');
  12260. }
  12261. if (typeof setting['auto-download-cancel'] === 'undefined') {
  12262. setting['auto-download-cancel'] = true;
  12263. }
  12264.  
  12265. console.log('[EHD] E-Hentai Downloader Setting >', JSON.stringify(setting));
  12266.  
  12267. // disable single-thread download
  12268. if (setting['enable-multi-threading'] === false) {
  12269. delete setting['enable-multi-threading'];
  12270. alert('Single-thread download is unavailable now, because its code is too old and it\'s hard to add new features on it.\n\nIf you still need it, please roll back to the last-supported version (1.17.4).\n\nYou can get it at:\n- GitHub: https://github.com/ccloli/E-Hentai-Downloader/releases\n- GreasyFork: https://greasyfork.org/scripts/10379-e-hentai-downloader/versions (requires log in and enable Adult content)\n- SleazyFork: https://sleazyfork.org/scripts/10379-e-hentai-downloader/versions');
  12271. GM_setValue('ehD-setting', JSON.stringify(setting));
  12272. }
  12273.  
  12274. if (setting['recheck-file-name']) toggleFilenameConfirmInput();
  12275. ehDownloadNumberInput.querySelector('input').checked = needNumberImages;
  12276. ehDownloadPauseBtn.textContent = setting['force-pause'] ? 'Pause (Downloading images will be aborted)' : 'Pause (Downloading images will keep downloading)';
  12277.  
  12278. if (!setting['hide-image-limits']) {
  12279. getResolutionSetting(true);
  12280. getImageLimits(true);
  12281. setInterval(getImageLimits, 60000);
  12282. }
  12283.  
  12284. if (!setting['hide-estimated-cost']) {
  12285. try {
  12286. showPreCalcCost();
  12287. }
  12288. catch (e) { }
  12289. }
  12290.  
  12291. // Forced request File System to check if have temp archive
  12292. if (setting['store-in-fs'] && requestFileSystem) {
  12293. requestFileSystem(window.TEMPORARY, 1024 * 1024 * 1024, ehDownloadFS.initCheckerHandler, ehDownloadFS.errorHandler);
  12294. }
  12295. });
  12296. }
  12297.  
  12298. // log information
  12299. console.log('[EHD] UserAgent >', navigator.userAgent);
  12300. console.log('[EHD] Script Handler >', GM_info.scriptHandler || (navigator.userAgent.indexOf('Firefox') >= 0 ? 'GreaseMonkey' : (navigator.userAgent.indexOf('Opera') >= 0 || navigator.userAgent.indexOf('Maxthon') >= 0) ? 'Violentmonkey' : undefined)); // (Only Tampermonkey supports GM_info.scriptHandler)
  12301. console.log('[EHD] Script Handler Version >', GM_info.version);
  12302. console.log('[EHD] E-Hentai Downloader Version >', GM_info.script.version);
  12303. console.log('[EHD] Current URL >', window.location.href);
  12304. console.log('[EHD] Is Logged In >', unsafeWindow.apiuid !== -1);
  12305.  
  12306.  
  12307. String.prototype.replaceHTMLEntites = function() {
  12308. var matchEntity = function(entity) {
  12309. var entitesList = {"euro":"€","nbsp":" ","quot":"\"","amp":"&","lt":"<","gt":">","iexcl":"¡","cent":"¢","pound":"£","curren":"¤","yen":"¥","brvbar":"¦","sect":"§","uml":"¨","copy":"©","ordf":"ª","not":"¬","shy":"","reg":"®","macr":"¯","deg":"°","plusmn":"±","sup2":"²","sup3":"³","acute":"´","micro":"µ","para":"¶","middot":"·","cedil":"¸","sup1":"¹","ordm":"º","raquo":"»","frac14":"¼","frac12":"½","frac34":"¾","iquest":"¿","agrave":"à","aacute":"á","acirc":"â","atilde":"ã","auml":"ä","aring":"å","aelig":"æ","ccedil":"ç","egrave":"è","eacute":"é","ecirc":"ê","euml":"ë","igrave":"ì","iacute":"í","icirc":"î","iuml":"ï","eth":"ð","ntilde":"ñ","ograve":"ò","oacute":"ó","ocirc":"ô","otilde":"õ","ouml":"ö","times":"×","oslash":"ø","ugrave":"ù","uacute":"ú","ucirc":"û","uuml":"ü","yacute":"ý","thorn":"þ","szlig":"ß","divide":"÷"};
  12310. if (entitesList[entity]) return entitesList[entity];
  12311. else if (/#\d+/.test(entity)) {
  12312. var charCode = entity.match(/#(\d+)/)[1] - 0;
  12313. return String.fromCharCode(charCode);
  12314. }
  12315. else if (/#[xX][0-9a-f]+/.test(entity)) {
  12316. var charCode = parseInt(entity.match(/#[xX]([0-9a-f]+)/)[1] - 0, 16);
  12317. return String.fromCharCode(charCode);
  12318. }
  12319. else return '&' + entity + ';';
  12320. };
  12321. var result = this.replace(/&(#[xX]?\d+|[a-zA-Z]+);/g, function(match, entity) {
  12322. return matchEntity(entity.toLowerCase());
  12323. });
  12324. return result;
  12325. };
  12326.  
  12327. function createBlob(abdata, config) {
  12328. try { // to detect if blob generates successfully
  12329. return new Blob(abdata, config);
  12330. }
  12331. catch (error) {
  12332. pushDialog('An error occurred when generating Blob object.');
  12333. console.error('[EHD] An error occurred when generating Blob object. Error Name >', error.name, '| Error Message >', error.message);
  12334. if (confirm('An error occurred when generating Blob object.\n\nError Name: ' + error.name + '\nError Message: ' + error.message + '\n\nTry again?')) return createBlob(abdata, config);
  12335.  
  12336. abdata = undefined;
  12337. throw new Error('[EHD] An error occurred when generating Blob object, and user refused to retry.');
  12338. }
  12339. }
  12340.  
  12341. // show info in dialog box
  12342. function pushDialog(str) {
  12343. var needScrollIntoView = ehDownloadDialog.clientHeight + ehDownloadDialog.scrollTop >= ehDownloadDialog.scrollHeight;
  12344.  
  12345. if (typeof str === 'string') {
  12346. var tn = document.createElement('span');
  12347. tn.innerHTML += str.replace(/\n/gi, '<br>');
  12348. ehDownloadDialog.appendChild(tn);
  12349. }
  12350. else ehDownloadDialog.appendChild(str);
  12351.  
  12352. if (getAllPagesURLFin && isDownloading && ehDownloadDialog.contains(ehDownloadPauseBtn)) {
  12353. ehDownloadDialog.appendChild(ehDownloadPauseBtn);
  12354. }
  12355.  
  12356. if (needScrollIntoView) {
  12357. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  12358. }
  12359. }
  12360.  
  12361. function getSafeName(str, ignoreSlash) {
  12362. var replaceList = {
  12363. ':': ':',
  12364. '"': '"',
  12365. '*': '*',
  12366. '?': '?',
  12367. '|': '|',
  12368. '<': '<',
  12369. '>': '>',
  12370. '/': '/',
  12371. '\\': '\',
  12372. '\n': '-'
  12373. };
  12374. var replaceFn = function(match) {
  12375. if (ignoreSlash && (match === '/' || match === '\\')) {
  12376. return match;
  12377. }
  12378. else if (setting['replace-with-full-width']) {
  12379. return replaceList[match];
  12380. }
  12381. else {
  12382. return '-';
  12383. }
  12384. };
  12385.  
  12386. return str.trim().replace(ehDownloadRegex.dangerChars, replaceFn);
  12387. }
  12388.  
  12389. // replace dir name and zip filename
  12390. function getReplacedName(str) {
  12391. return str.replace(/\{gid\}/gi, unsafeWindow.gid)
  12392. .replace(/\{token\}/gi, unsafeWindow.token)
  12393. .replace(/\{title\}/gi, getSafeName(document.getElementById('gn').textContent))
  12394. .replace(/\{subtitle\}/gi, document.getElementById('gj').textContent ? getSafeName(document.getElementById('gj').textContent) : getSafeName(document.getElementById('gn').textContent))
  12395. .replace(/\{tag\}|\{category\}/gi, document.querySelector('#gdc .cs').textContent.trim().toUpperCase())
  12396. .replace(/\{uploader\}/gi, getSafeName(document.querySelector('#gdn a').textContent))
  12397. .replaceHTMLEntites();
  12398. }
  12399.  
  12400. function PageData(pageURL, imageURL, imageName, nextNL, realIndex, imageNumber) {
  12401. this.pageURL = pageURL.split('?')[0];
  12402. this.imageURL = imageURL;
  12403. this.imageName = getSafeName(imageName);
  12404. this._imageName = this.imageName;
  12405. this.equalCount = 1;
  12406. this.nextNL = nextNL;
  12407. this.realIndex = realIndex;
  12408. this.imageNumber = imageNumber;
  12409. }
  12410.  
  12411. // rename images that have the same name
  12412. function renameImages() {
  12413. imageList.forEach(function(elem, index) {
  12414. // if Number Images are enabled, filename won't be changed, just numbering
  12415. if (!needNumberImages) {
  12416. for (var i = 0; i < index; i++) {
  12417. if (elem !== undefined && imageList[i] !== undefined && elem.imageName.toLowerCase() === imageList[i]['imageName'].toLowerCase()) {
  12418. var nameParts = elem.imageName.split('.');
  12419. nameParts[nameParts.length - 2] += ' (' + (++imageList[i].equalCount) + ')';
  12420. elem.imageName = nameParts.join('.');
  12421. break;
  12422. }
  12423. }
  12424. }
  12425. else elem['imageName'] = elem['imageNumber'] + (setting['number-separator'] ? setting['number-separator'] : ':') + elem['imageName'];
  12426. });
  12427. }
  12428.  
  12429. // store responsed content from GM_xhr
  12430. // Updated on 1.19: Now the index argument is the page's number - 1 (original is page's number)
  12431. function storeRes(res, index) {
  12432. imageData[index] = res;
  12433. downloadedCount++;
  12434. console.log('[EHD] Index >', index + 1, ' | RealIndex >', imageList[index]['realIndex'], ' | Name >', imageList[index]['imageName'], ' | RetryCount >', retryCount[index], ' | DownloadedCount >', downloadedCount, ' | FetchCount >', fetchCount, ' | FailedCount >', failedCount);
  12435. fetchCount--;
  12436.  
  12437. updateTotalStatus();
  12438. if (!isPausing) checkFailed();
  12439. for (var i in res) {
  12440. delete res[i];
  12441. }
  12442. }
  12443.  
  12444. function generateZip(isFromFS, fs, isRetry, forced){
  12445. isSaving = true;
  12446.  
  12447. // remove pause button
  12448. if (!forced && ehDownloadDialog.contains(ehDownloadPauseBtn)) {
  12449. ehDownloadDialog.removeChild(ehDownloadPauseBtn);
  12450. }
  12451.  
  12452. if (!isFromFS && !isRetry) {
  12453. if (setting['save-info-list'].toString().indexOf('page-links') >= 0) {
  12454. imageList.forEach(function(elem, index){
  12455. // Image URL may useless, see https://github.com/ccloli/E-Hentai-Downloader/issues/6
  12456. infoStr += '\n\nPage ' + elem['realIndex'] + ': ' + elem['pageURL'] + '\nImage ' + elem['realIndex'] + ': ' + elem['imageName'] /*+ '\nImage URL: ' + elem['imageURL']*/;
  12457. });
  12458. }
  12459. pushDialog('\nFinish downloading at ' + new Date() + '\n');
  12460. infoStr += '\n\nDownloaded at ' + new Date() + '\n\nGenerated by E-Hentai Downloader. https://github.com/ccloli/E-Hentai-Downloader';
  12461.  
  12462. if (setting['save-info'] === 'file' || !setting['save-info']) {
  12463. (dirName && !ehDownloadRegex.slashOnly.test(dirName) ? zip.folder(dirName) : zip).file('info.txt', infoStr.replace(/\n/gi, '\r\n'));
  12464. }
  12465. }
  12466.  
  12467. pushDialog('\n\nGenerating Zip file...\n');
  12468.  
  12469. var fs = fs || ehDownloadFS.fs;
  12470.  
  12471. var progress = document.createElement('progress');
  12472. var curFile = document.createElement('div');
  12473. progress.className = 'ehD-pt-gen-progress';
  12474. curFile.className = 'ehD-pt-gen-filename';
  12475. curFile.textContent = ' ';
  12476. ehDownloadDialog.appendChild(progress);
  12477. ehDownloadDialog.appendChild(curFile);
  12478. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  12479.  
  12480. var saveToFileSystem = function(abData) {
  12481. curFile.textContent = ' ';
  12482.  
  12483. var fsErrorHandler = function(error) {
  12484. ehDownloadFS.errorHandler(error);
  12485. ehDownloadFS.removeAllFiles();
  12486.  
  12487. if (confirm('An error occured when storing files to FileSystem.\n' +
  12488. 'Error Name: ' + (error.name || 'Unknown Error') + '\n' +
  12489. 'Error Message: ' + error.message + '\n\n' +
  12490. 'Should I try FileSystem again (Yes) or redirect to try using Blob (No)? \n' +
  12491. '* If the error message shows there\'s no more free disk space, try removing some files from the drive where Chrome installed (mostly C: on Windows)')) {
  12492. saveToFileSystem(abData);
  12493. }
  12494. else {
  12495. ehDownloadFS.needFileSystem = false;
  12496. saveToBlob(abData);
  12497. }
  12498. };
  12499.  
  12500. var fs = fs || ehDownloadFS.fs;
  12501. pushDialog('\n\nSlicing and storing Zip file to FileSystem...');
  12502. var data = abData;
  12503. var dataIndex = 0;
  12504. var dataLength = data.byteLength;
  12505. var loopWrite = function(fileEntry){
  12506. fileEntry.createWriter(function(fileWriter){
  12507. //fileWriter.seek(fileWriter.length);
  12508. dataIndex = fileWriter.length;
  12509. if (dataIndex >= dataLength) {
  12510. data = undefined;
  12511. abData = undefined;
  12512. return setTimeout(function(){
  12513. ehDownloadFS.saveAs(isFromFS ? fs : undefined, forced);
  12514. isSaving = false;
  12515. }, 1500);
  12516. }
  12517. fileWriter.seek(dataIndex);
  12518. var dataLastIndex = dataIndex + 1024 * 1024 * 10;
  12519. // I tried setting it as 100MB but some parts were still gone, so I have to make it smaller.
  12520. console.log('[EHD] DataIndex >', dataIndex, '| DataLastIndex >', dataLastIndex, '| FileWriterLength >', fileWriter.length, '| DataLength >', dataLength);
  12521. pushDialog('\n' + dataIndex + '-' + dataLastIndex + '/' + dataLength);
  12522. var blob = createBlob([data.slice(dataIndex, dataLastIndex)], {type: 'application/zip'});
  12523. fileWriter.write(blob);
  12524. if ('close' in blob) blob.close(); // File Blob.close() API, not supported by all the browser now
  12525. blob = null;
  12526. setTimeout(loopWrite, 100, fileEntry);
  12527. }, fsErrorHandler);
  12528. };
  12529. fs.root.getFile(unsafeWindow.gid + '.zip', {create: true}, function(fileEntry){
  12530. if (fileEntry.isFile) fileEntry.remove(function(){
  12531. console.log('[EHD] File', fileName, 'is removed.');
  12532. }, fsErrorHandler);
  12533. else if (fileEntry.isDirectory) fileEntry.removeRecursively(function() {
  12534. console.log('[EHD] Directory', fileName, 'is removed.');
  12535. }, fsErrorHandler);
  12536. fs.root.getFile(unsafeWindow.gid + '.zip', {create: true}, loopWrite, fsErrorHandler);
  12537. }, fsErrorHandler);
  12538. //fs.root.getFile(unsafeWindow.gid + '.zip', {create: true}, loopWrite, fsErrorHandler);
  12539. };
  12540.  
  12541. var saveToBlob = function(abData){
  12542. curFile.textContent = 'Generating Blob object...';
  12543. var blob = createBlob([abData], {type: setting['save-as-cbz'] ? 'application/vnd.comicbook+zip' : 'application/zip'});
  12544. saveAs(blob, fileName + (setting['save-as-cbz'] ? '.cbz' : '.zip'));
  12545.  
  12546. var redownloadBtn = document.createElement('button');
  12547. redownloadBtn.textContent = 'Not download? Click here to download';
  12548. redownloadBtn.addEventListener('click', function(){
  12549. // rebuild blob object if "File is not exist" occured
  12550. blob = createBlob([abData], {type: setting['save-as-cbz'] ? 'application/vnd.comicbook+zip' : 'application/zip'});
  12551. saveAs(blob, fileName + (setting['save-as-cbz'] ? '.cbz' : '.zip'));
  12552.  
  12553. setTimeout(function(){
  12554. if ('close' in blob) blob.close();
  12555. blob = null;
  12556. }, 10e3); // 10s to fixed Chrome delay downloads
  12557. });
  12558. ehDownloadDialog.appendChild(redownloadBtn);
  12559.  
  12560. if (!forced) insertCloseButton();
  12561. isSaving = false;
  12562.  
  12563. setTimeout(function(){
  12564. if ('close' in blob) blob.close();
  12565. blob = null;
  12566. }, 10e3); // 10s to fixed Chrome delay downloads
  12567. };
  12568.  
  12569. try {
  12570. var lastMetaTime = 0;
  12571. // build arraybuffer object to detect if it generates successfully
  12572. zip.generateAsync({
  12573. type: 'arraybuffer',
  12574. compression: setting['compression-level'] ? 'DEFLATE' : 'STORE',
  12575. compressionOptions: {
  12576. level: setting['compression-level'] > 0 ? (setting['compression-level'] < 10 ? setting['compression-level'] : 9) : 1
  12577. },
  12578. streamFiles: setting['file-descriptor'] ? true : false,
  12579. comment: setting['save-info'] === 'comment' ? infoStr.replace(/\n/gi, '\r\n') : undefined
  12580. }, function(meta){
  12581. // meta update function will be called nearly every 1ms, for performance, update every 300ms
  12582. // anyway it's still too fast so that you may still cannot see the update
  12583. var thisMetaTime = Date.now();
  12584. if (thisMetaTime - lastMetaTime < 300) {
  12585. return;
  12586. }
  12587. lastMetaTime = thisMetaTime;
  12588. progress.value = meta.percent / 100;
  12589. curFile.textContent = meta.currentFile || 'Calculating extra data...';
  12590. }).then(function(abData){
  12591. progress.value = 1;
  12592.  
  12593. if (!forced) {
  12594. if (emptyAudio) {
  12595. emptyAudio.pause();
  12596. }
  12597. }
  12598.  
  12599. if (isFromFS || ehDownloadFS.needFileSystem) { // using filesystem to save file is needed
  12600. saveToFileSystem(abData);
  12601. }
  12602. else { // or just using blob
  12603. saveToBlob(abData);
  12604. }
  12605.  
  12606. if (!forced) {
  12607. zip.file(/.*/).forEach(function(elem){
  12608. zip.remove(elem);
  12609. });
  12610. }
  12611. });
  12612. }
  12613. catch (error) {
  12614. abData = undefined;
  12615.  
  12616. pushDialog('An error occurred when generating Zip file as ArrayBuffer.');
  12617. console.error('[EHD] An error occurred when generating Zip file as ArrayBuffer.');
  12618. console.error(error);
  12619. if (confirm('An error occurred when generating Zip file as ArrayBuffer. Try again?')) return generateZip(isFromFS, fs, 1);
  12620.  
  12621. var fsErrorHandler = function(error) {
  12622. ehDownloadFS.errorHandler(error);
  12623. ehDownloadFS.removeAllFiles();
  12624.  
  12625. if (confirm('An error occured when storing files to FileSystem.\n' +
  12626. 'Error Name: ' + (error.name || 'Unknown Error') + '\n' +
  12627. 'Error Message: ' + error.message + '\n\n' +
  12628. 'Should I try again (Yes) or stop it (No, and the downloaded file will be removed)? \n' +
  12629. '* If the error message shows there\'s no more free disk space, try removing some files from the drive where Chrome installed (mostly C: on Windows)')) {
  12630. generateZip(isFromFS, fs, isRetry, forced);
  12631. }
  12632. };
  12633.  
  12634. if (isFromFS || ehDownloadFS.needFileSystem) {
  12635. // if enabled file system, then store all files into file system
  12636. pushDialog('Storing files into File System...');
  12637. var files = zip.file(/.*/);
  12638. var fileIndex = 0;
  12639. var filesLength = files.length;
  12640. var initFS = function(r){
  12641. fs = r;
  12642. fs.root.getDirectory('raw', {create: true}, loopWrite, fsErrorHandler);
  12643. };
  12644. var loopWrite = function(){
  12645. fs.root.getFile('raw/' + files[fileIndex]['name'], {create: true}, function(fileEntry){
  12646. fileEntry.createWriter(function(fileWriter){
  12647. console.log('[EHD] FileIndex >', fileIndex, '| FilesLength >', filesLength);
  12648. var blob = createBlob([files[fileIndex].asArrayBuffer()], {type: 'application/octet-stream'});
  12649. fileWriter.write(blob);
  12650. if ('close' in blob) blob.close(); // File Blob.close() API, not supported by all the browser now
  12651. blob = null;
  12652. fileIndex++; // some files may still gone in this way, I have no good way to solve it
  12653. if (fileIndex < filesLength) setTimeout(loopWrite, 100);
  12654. else {
  12655. fs.root.getFile('config.txt', {create: true}, function(fileEntry){
  12656. fileEntry.createWriter(function(fileWriter){
  12657. var t = JSON.stringify({fileName: fileName, dirName: dirName});
  12658. var blob = createBlob([t], {type: 'text/plain'});
  12659. fileWriter.write(blob);
  12660. if ('close' in blob) blob.close(); // File Blob.close() API, not supported by all the browser now
  12661. blob = null;
  12662. pushDialog('Success!\nPlease close this tab and open a new tab to download.\nIf you still can\'t download it, try using <a href="https://chrome.google.com/webstore/detail/nhnjmpbdkieehidddbaeajffijockaea" target="_blank">HTML5 FileSystem Explorer</a> to save them.');
  12663.  
  12664. files.forEach(function(elem){
  12665. zip.remove(elem);
  12666. });
  12667. zip = undefined;
  12668. isSaving = false;
  12669. });
  12670. });
  12671. }
  12672. }, fsErrorHandler);
  12673. }, fsErrorHandler);
  12674. };
  12675. requestFileSystem(window.TEMPORARY, 1024 * 1024 * 1024 * 1024, initFS, fsErrorHandler);
  12676. }
  12677. }
  12678. }
  12679.  
  12680. // update progress table info
  12681. function updateProgress(nodeList, data) {
  12682. if (data.name !== undefined) nodeList.fileName.textContent = data.name;
  12683. if (data.progress !== undefined) nodeList.progress.value = data.progress;
  12684. if (data.progressText !== undefined) nodeList.progressText.textContent = data.progressText;
  12685. if (data.status !== undefined) nodeList.statusText.textContent = data.status;
  12686. if (data.class !== undefined) nodeList.current.className = ['ehD-pt-item', data.class].join(' ').trim();
  12687. }
  12688.  
  12689. // update ehDownloadStatus
  12690. function updateTotalStatus(){
  12691. ehDownloadStatus.textContent = 'Total: ' + totalCount + ' | Downloading: ' + fetchCount + ' | Succeed: ' + downloadedCount + ' | Failed: ' + failedCount;
  12692. if (needTitleStatus) document.title = '[' + (isPausing ? '❙❙' : downloadedCount < totalCount ? '↓ ' + downloadedCount + '/' + totalCount : totalCount === 0 ? '↓' : '√' ) + '] ' + pretitle;
  12693. }
  12694.  
  12695. // Updated on 1.19: Now the index argument is the page's number - 1 (original is page's number)
  12696. function failedFetching(index, nodeList, forced){
  12697. if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31
  12698. if (typeof fetchThread[index] !== 'undefined' && 'abort' in fetchThread[index]) fetchThread[index].abort();
  12699. console.error('[EHD] Index >', index + 1, ' | RealIndex >', imageList[index]['realIndex'], ' | Name >', imageList[index]['imageName'], ' | RetryCount >', retryCount[index], ' | DownloadedCount >', downloadedCount, ' | FetchCount >', fetchCount, ' | FailedCount >', failedCount);
  12700.  
  12701. if (!forced && retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  12702. retryCount[index]++;
  12703. fetchOriginalImage(index, nodeList);
  12704. }
  12705. else {
  12706. updateProgress(nodeList, {
  12707. class: 'ehD-pt-failed'
  12708. });
  12709.  
  12710. imageList[index]['imageFinalURL'] = null;
  12711. failedCount++;
  12712. if (!isPausing || !setting['force-pause']) fetchCount--;
  12713.  
  12714. updateTotalStatus();
  12715. checkFailed();
  12716. }
  12717. }
  12718.  
  12719. function saveDownloaded(forced){
  12720. renameImages();
  12721.  
  12722. for (var j = 0; j < imageData.length; j++) {
  12723. if (imageData[j] != null && imageData[j] !== 'Fetching') {
  12724. (dirName && !ehDownloadRegex.slashOnly.test(dirName) ? zip.folder(dirName) : zip).file(imageList[j]['imageName'], imageData[j]);
  12725. if (!forced) imageData[j] = null;
  12726. }
  12727. }
  12728. generateZip(false, undefined, false, forced);
  12729. if (forced) {
  12730. // if force download zip file, image data should be recoverd to original content
  12731. imageList.forEach(function(elem, index) {
  12732. elem.equalCount = 1;
  12733. elem.imageName = elem._imageName;
  12734. });
  12735. }
  12736. }
  12737.  
  12738. function checkFailed() {
  12739. if (downloadedCount + failedCount < totalCount) { // download not finished, some files are not being called to download
  12740. requestDownload();
  12741. }
  12742. else if (failedCount > 0) { // all files are called to download and some files can't be downloaded
  12743. if (fetchCount === 0) { // all files are finished downloading
  12744. for (var i = 0; i < fetchThread.length; i++) {
  12745. if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort();
  12746. }
  12747. if (setting['number-auto-retry'] || confirm('Some images failed to download. Would you like to try them again?')) {
  12748. retryAllFailed();
  12749. }
  12750. else {
  12751. pushDialog('\nFetch images failed.\n');
  12752. if (setting['auto-download-cancel'] || confirm('Fetch images failed, Please try again later.\n\nWould you like to download downloaded images?')) {
  12753. saveDownloaded();
  12754. }
  12755. else {
  12756. insertCloseButton();
  12757. }
  12758. zip.file(/.*/).forEach(function (elem) {
  12759. zip.remove(elem);
  12760. });
  12761. isDownloading = false;
  12762. }
  12763. }
  12764. }
  12765. else { // all files are downloaded successfully
  12766. renameImages();
  12767. for (var j = 0; j < totalCount; j++) {
  12768. (dirName && !ehDownloadRegex.slashOnly.test(dirName) ? zip.folder(dirName) : zip).file(imageList[j]['imageName'], imageData.shift());
  12769. }
  12770. generateZip();
  12771. zip.file(/.*/).forEach(function (elem) {
  12772. zip.remove(elem);
  12773. });
  12774. isDownloading = false;
  12775. }
  12776. }
  12777.  
  12778. // Updated on 1.19: Now the index argument is the page's number - 1 (original is page's number)
  12779. function fetchOriginalImage(index, nodeList) {
  12780. // GM_xhr 于 GreaseMonkey 2.3 / 2.4 中开始支持 responseType 以获取返回类型为 ArrayBuffer 的请求
  12781. // GM_xhr support responseType to fetch ArrayBuffer request on 2.3 / 2.4
  12782. // https://github.com/greasemonkey/greasemonkey/issues/1834
  12783. //console.log(imageList[index]);
  12784. if (retryCount[index] === undefined) retryCount[index] = 0;
  12785. if (isPausing) return;
  12786.  
  12787. var requestURL = imageList[index]['imageFinalURL'] || imageList[index]['imageURL'];
  12788. var needScrollIntoView = ehDownloadDialog.clientHeight + ehDownloadDialog.scrollTop >= ehDownloadDialog.scrollHeight;
  12789.  
  12790. if (nodeList === undefined) {
  12791. var node = progressTable.querySelector('tr[data-index="' + index + '"]');
  12792. if (!node) {
  12793. node = document.createElement('tr');
  12794. node.className = 'ehD-pt-item';
  12795. node.setAttribute('data-index', index);
  12796. node.innerHTML = '\
  12797. <td class="ehD-pt-name">#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'] + '</td>\
  12798. <td class="ehD-pt-progress-outer">\
  12799. <progress class="ehD-pt-progress"></progress>\
  12800. <span class="ehD-pt-progress-text"></span>\
  12801. </td>\
  12802. <td class="ehD-pt-status">\
  12803. <span class="ehD-pt-status-text">Pending...</span>\
  12804. <span class="ehD-pt-abort">Force Abort</span>\
  12805. </td>';
  12806. progressTable.appendChild(node);
  12807. }
  12808.  
  12809. nodeList = {
  12810. current: node,
  12811. fileName: node.getElementsByTagName('td')[0],
  12812. status: node.getElementsByTagName('td')[2],
  12813. statusText: node.getElementsByClassName('ehD-pt-status-text')[0],
  12814. progress: node.getElementsByTagName('progress')[0],
  12815. progressText: node.getElementsByTagName('span')[0],
  12816. abort: node.getElementsByClassName('ehD-pt-abort')[0]
  12817. };
  12818. }
  12819. var speedInfo = {
  12820. lastProgress: 0,
  12821. lastTimestamp: new Date().getTime(),
  12822. zeroDetect: null,
  12823. expiredDetect: null
  12824. };
  12825.  
  12826. if (needScrollIntoView) {
  12827. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  12828. }
  12829.  
  12830. var zeroSpeedHandler = function(res){
  12831. if (imageData[index] instanceof ArrayBuffer) { // Has already downloaded
  12832. updateProgress(nodeList, {
  12833. name: '#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'],
  12834. status: 'Succeed!',
  12835. progress: '1',
  12836. progressText: '100%',
  12837. class: 'ehD-pt-succeed'
  12838. });
  12839.  
  12840. return;
  12841. }
  12842. if (!isDownloading) return; // Temporarily fixes #31
  12843. if (isPausing && setting['force-pause']) return;
  12844.  
  12845. updateProgress(nodeList, { progressText: '0 KB/s' });
  12846.  
  12847. if (setting['speed-detect'] && speedInfo.expiredDetect === null) {
  12848. speedInfo.expiredDetect = setTimeout(expiredSpeedHandler, (setting['speed-expired'] ? setting['speed-expired'] : 30) * 1000, res);
  12849. }
  12850. };
  12851.  
  12852. var expiredSpeedHandler = function(res){
  12853. if (imageData[index] instanceof ArrayBuffer) { // Has already downloaded
  12854. updateProgress(nodeList, {
  12855. name: '#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'],
  12856. status: 'Succeed!',
  12857. progress: '1',
  12858. progressText: '100%',
  12859. class: 'ehD-pt-succeed'
  12860. });
  12861.  
  12862. return;
  12863. }
  12864. if (!isDownloading) return; // Temporarily fixes #31
  12865. if (isPausing && setting['force-pause']) return;
  12866.  
  12867. if (typeof fetchThread[index] !== 'undefined' && 'abort' in fetchThread[index]) fetchThread[index].abort();
  12868.  
  12869. console.log('[EHD] #' + (index + 1) + ': Speed Too Low');
  12870. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  12871.  
  12872. updateProgress(nodeList, {
  12873. status: 'Failed! (Low Speed)',
  12874. progress: '0',
  12875. progressText: '',
  12876. class: 'ehD-pt-warning'
  12877. });
  12878.  
  12879. if (imageList[index]['imageURL'].indexOf('fullimg.php') >= 0) imageList[index]['imageFinalURL'] = res.finalUrl;
  12880.  
  12881. for (var i in res) {
  12882. delete res[i];
  12883. }
  12884.  
  12885. failedFetching(index, nodeList);
  12886. };
  12887.  
  12888. var removeTimerHandler = function(){
  12889. if (speedInfo.expiredDetect !== null) {
  12890. clearTimeout(speedInfo.expiredDetect);
  12891. speedInfo.expiredDetect = null;
  12892. }
  12893.  
  12894. if (speedInfo.zeroDetect !== null) {
  12895. clearTimeout(speedInfo.zeroDetect);
  12896. speedInfo.zeroDetect = null;
  12897. }
  12898. };
  12899.  
  12900. fetchThread[index] = GM_xmlhttpRequest({
  12901. method: 'GET',
  12902. url: requestURL,
  12903. responseType: 'arraybuffer',
  12904. timeout: (setting['timeout'] !== undefined) ? Number(setting['timeout']) * 1000 : 300000,
  12905. headers: {
  12906. 'Referer': imageList[index]['pageURL'],
  12907. 'X-Alt-Referer': imageList[index]['pageURL']
  12908. },
  12909. onprogress: function(res) {
  12910. var t = new Date().getTime();
  12911. var speedText;
  12912. var speedKBs = res.lengthComputable ? Number((res.loaded - speedInfo.lastProgress) / (t - speedInfo.lastTimestamp) / 1.024) : -1;
  12913.  
  12914. if (t - speedInfo.lastTimestamp >= 1000 || speedInfo.lastProgress === 0) {
  12915. speedText = res.lengthComputable ? speedKBs.toFixed(2) + ' KB/s' : '';
  12916. speedInfo.lastProgress = res.loaded;
  12917. speedInfo.lastTimestamp = t;
  12918. }
  12919.  
  12920. updateProgress(nodeList, {
  12921. name: '#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'],
  12922. progress: res.lengthComputable ? res.loaded / res.total : '',
  12923. progressText: speedText,
  12924. class: '',
  12925. status: retryCount[index] === 0 ? 'Downloading...' : 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ') ...'
  12926. });
  12927.  
  12928. // set showing speed to 0
  12929. if (speedInfo.zeroDetect !== null) {
  12930. clearTimeout(speedInfo.zeroDetect);
  12931. speedInfo.zeroDetect = null;
  12932. }
  12933. speedInfo.zeroDetect = setTimeout(zeroSpeedHandler, 3000, res);
  12934.  
  12935. if (setting['speed-detect']) {
  12936. if (speedKBs >= setting['speed-min'] ? setting['speed-min'] : 5) {
  12937.  
  12938. if (speedInfo.expiredDetect !== null) {
  12939. clearTimeout(speedInfo.expiredDetect);
  12940. speedInfo.expiredDetect = null;
  12941. }
  12942.  
  12943. for (var i in res) {
  12944. delete res[i];
  12945. }
  12946. }
  12947. else if (speedInfo.expiredDetect === null) {
  12948. speedInfo.expiredDetect = setTimeout(expiredSpeedHandler, (setting['speed-expired'] ? setting['speed-expired'] : 30) * 1000, res);
  12949. console.log('[EHD] Speed detect handler is inited for', index + 1, '!');
  12950. }
  12951. }
  12952. },
  12953. onload: function(res) {
  12954. try {
  12955. removeTimerHandler();
  12956. if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31
  12957.  
  12958. // cache them to reduce waiting time and CPU usage on Chrome with Tampermonkey
  12959. // (Tampermonkey uses a dirty way to give res.response, transfer string to arraybuffer every time)
  12960. // now store progress just spent ~1s instead of ~8s
  12961. var response = res.response;
  12962. var byteLength = response.byteLength;
  12963. var responseHeaders = res.responseHeaders;
  12964. // use regex to fixed compatibility with http/2, as its headers are lower case (at least fixed with Yandex Turbo)
  12965. var mime = responseHeaders.match(/Content-Type:/i) ? responseHeaders.split(/Content-Type:/i)[1].split('\n')[0].trim().split('/') : ['', ''];
  12966.  
  12967. if (!response) {
  12968. console.log('[EHD] #' + (index + 1) + ': Empty Response (See: https://github.com/ccloli/E-Hentai-Downloader/issues/16 )');
  12969. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  12970.  
  12971. updateProgress(nodeList, {
  12972. status: 'Failed! (Empty Response)',
  12973. progress: '0',
  12974. progressText: '',
  12975. class: 'ehD-pt-warning'
  12976. });
  12977.  
  12978. for (var i in res) {
  12979. delete res[i];
  12980. }
  12981. return failedFetching(index, nodeList);
  12982.  
  12983. // res.response polyfill is useless, so it has been removed
  12984. }
  12985. else if (byteLength === 925) { // '403 Access Denied' Image Byte Size
  12986. // GM_xhr only support abort()
  12987. console.log('[EHD] #' + (index + 1) + ': 403 Access Denied');
  12988. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  12989.  
  12990. updateProgress(nodeList, {
  12991. status: 'Failed! (Error 403)',
  12992. progress: '0',
  12993. progressText: '',
  12994. class: 'ehD-pt-warning'
  12995. });
  12996.  
  12997. for (var i in res) {
  12998. delete res[i];
  12999. }
  13000. return failedFetching(index, nodeList, true);
  13001. }
  13002. else if (byteLength === 28) { // 'An error has occurred. (403)' Length
  13003. console.log('[EHD] #' + (index + 1) + ': An error has occurred. (403)');
  13004. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  13005. updateProgress(nodeList, {
  13006. status: 'Failed! (Error 403)',
  13007. progress: '0',
  13008. progressText: '',
  13009. class: 'ehD-pt-warning'
  13010. });
  13011.  
  13012. for (var i in res) {
  13013. delete res[i];
  13014. }
  13015. return failedFetching(index, nodeList, true);
  13016. }
  13017. else if (
  13018. byteLength === 142 || // Image Viewing Limits String Byte Size (exhentai)
  13019. byteLength === 144 || // Image Viewing Limits String Byte Size (g.e-hentai)
  13020. byteLength === 28658 || // '509 Bandwidth Exceeded' Image Byte Size
  13021. (mime[0] === 'text' && (res.responseText || new TextDecoder().decode(new DataView(response))).indexOf('You have exceeded your image viewing limits') >= 0) // directly detect response content in case byteLength will be modified
  13022. ) {
  13023. // thought exceed the limits, downloading image is still accessable
  13024. /*for (var i = 0; i < fetchThread.length; i++) {
  13025. if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort();
  13026. }*/
  13027. console.log('[EHD] #' + (index + 1) + ': Exceed Image Viewing Limits / 509 Bandwidth Exceeded');
  13028. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  13029.  
  13030. updateProgress(nodeList, {
  13031. status: 'Failed! (Exceed Limits)',
  13032. progress: '0',
  13033. progressText: '',
  13034. class: 'ehD-pt-failed'
  13035. });
  13036.  
  13037. for (var i in res) {
  13038. delete res[i];
  13039. }
  13040.  
  13041. failedCount++;
  13042. fetchCount--;
  13043. updateTotalStatus();
  13044.  
  13045. if (isPausing) return;
  13046.  
  13047. pushDialog('You have exceeded your image viewing limits.\n');
  13048. isPausing = true;
  13049. updateTotalStatus();
  13050. if (emptyAudio) {
  13051. emptyAudio.pause();
  13052. }
  13053.  
  13054. if (ehDownloadDialog.contains(ehDownloadPauseBtn)) {
  13055. ehDownloadDialog.removeChild(ehDownloadPauseBtn);
  13056. }
  13057.  
  13058. if (confirm('You have temporarily reached the limit for how many images you can browse.\n\n\
  13059. - If you are not signed in, sign up/in with an E-Hentai account at E-Hentai Forums to get double daily quota.\n\
  13060. - You can run Hentai@Home to support E-Hentai and get some points which you can pay to increase your limit.\n\
  13061. - Check back in a few hours, and you will be able to download more (3 points are reduced per minute by default).\n\
  13062. - You can reset your image viewing limits to continue by paying your GPs or credits.\n\n\
  13063. If you want to reset your limits by paying your GPs or credits right now, choose YES, and you can reset it in the opened window. Or if you want to wait a few minutes until you have enough free limit, then continue, choose NO.')) {
  13064. window.open('https://e-hentai.org/home.php');
  13065. }
  13066.  
  13067. var resetButton = document.createElement('a');
  13068. resetButton.innerHTML = '<button>Reset Limits</button>';
  13069. resetButton.setAttribute('href', 'https://e-hentai.org/home.php');
  13070. resetButton.setAttribute('target', '_blank');
  13071. ehDownloadDialog.appendChild(resetButton);
  13072.  
  13073. var continueButton = document.createElement('button');
  13074. continueButton.innerHTML = 'Continue Download';
  13075. continueButton.addEventListener('click', function(){
  13076. //fetchCount = 0;
  13077. ehDownloadDialog.removeChild(resetButton);
  13078. ehDownloadDialog.removeChild(continueButton);
  13079. ehDownloadDialog.removeChild(cancelButton);
  13080. ehDownloadDialog.appendChild(ehDownloadPauseBtn);
  13081.  
  13082. isPausing = false;
  13083. initProgressTable();
  13084. checkFailed();
  13085. });
  13086. ehDownloadDialog.appendChild(continueButton);
  13087.  
  13088. var cancelButton = document.createElement('button');
  13089. cancelButton.innerHTML = 'Cancel Download';
  13090. cancelButton.addEventListener('click', function(){
  13091. ehDownloadDialog.removeChild(resetButton);
  13092. ehDownloadDialog.removeChild(continueButton);
  13093. ehDownloadDialog.removeChild(cancelButton);
  13094.  
  13095. if (setting['auto-download-cancel'] || confirm('You have exceeded your image viewing limits. Would you like to save downloaded images?')) {
  13096. saveDownloaded();
  13097. }
  13098. else {
  13099. insertCloseButton();
  13100. }
  13101. isPausing = false;
  13102. isDownloading = false;
  13103. zip.file(/.*/).forEach(function (elem) {
  13104. zip.remove(elem);
  13105. });
  13106. });
  13107. ehDownloadDialog.appendChild(cancelButton);
  13108.  
  13109. return;
  13110. }
  13111. // ip banned
  13112. else if (
  13113. (mime[0] === 'text' && (res.responseText || new TextDecoder().decode(new DataView(response))).indexOf('Your IP address has been temporarily banned') >= 0)
  13114. ) {
  13115. console.log('[EHD] #' + (index + 1) + ': IP address banned');
  13116. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  13117.  
  13118. updateProgress(nodeList, {
  13119. status: 'Failed! (IP banned)',
  13120. progress: '0',
  13121. progressText: '',
  13122. class: 'ehD-pt-failed'
  13123. });
  13124.  
  13125. for (var i in res) {
  13126. delete res[i];
  13127. }
  13128.  
  13129. failedCount++;
  13130. fetchCount--;
  13131. updateTotalStatus();
  13132.  
  13133. if (isPausing) return;
  13134.  
  13135. pushDialog('Your IP address has been temporarily banned.\n');
  13136. isPausing = true;
  13137. updateTotalStatus();
  13138. if (emptyAudio) {
  13139. emptyAudio.pause();
  13140. }
  13141.  
  13142. if (ehDownloadDialog.contains(ehDownloadPauseBtn)) {
  13143. ehDownloadDialog.removeChild(ehDownloadPauseBtn);
  13144. }
  13145.  
  13146. var expiredTime = (res.responseText || new TextDecoder().decode(new DataView(response))).match(ehDownloadRegex.IPBanExpires);
  13147.  
  13148. alert('Your IP address has been temporarily banned. \n\n\
  13149. Make sure your download settings are not configured to download too fast. If you are using conservative rules, check if your computer is infected with malware, or if you are using a shared IP with others.\n\
  13150. If you can change your IP (like using a proxy) or wait until you\'re unblocked, you can then continue your download; or cancel your download and get downloaded images.\n\n' +
  13151. (expiredTime ? '\n' + expiredTime[0] : '')
  13152. );
  13153.  
  13154. var continueButton = document.createElement('button');
  13155. continueButton.innerHTML = 'Continue Download';
  13156. continueButton.addEventListener('click', function () {
  13157. //fetchCount = 0;
  13158. ehDownloadDialog.removeChild(continueButton);
  13159. ehDownloadDialog.removeChild(cancelButton);
  13160. ehDownloadDialog.appendChild(ehDownloadPauseBtn);
  13161.  
  13162. isPausing = false;
  13163. initProgressTable();
  13164. checkFailed();
  13165. });
  13166. ehDownloadDialog.appendChild(continueButton);
  13167.  
  13168. var cancelButton = document.createElement('button');
  13169. cancelButton.innerHTML = 'Cancel Download';
  13170. cancelButton.addEventListener('click', function () {
  13171. ehDownloadDialog.removeChild(continueButton);
  13172. ehDownloadDialog.removeChild(cancelButton);
  13173.  
  13174. if (setting['auto-download-cancel'] || confirm('Would you like to save downloaded images?')) {
  13175. saveDownloaded();
  13176. }
  13177. else {
  13178. insertCloseButton();
  13179. }
  13180. isPausing = false;
  13181. isDownloading = false;
  13182. zip.file(/.*/).forEach(function (elem) {
  13183. zip.remove(elem);
  13184. });
  13185. });
  13186. ehDownloadDialog.appendChild(cancelButton);
  13187.  
  13188. return;
  13189. }
  13190. // res.status should be detected at here, because we should know are we reached image limits at first
  13191. else if (res.status !== 200) {
  13192. console.log('[EHD] #' + (index + 1) + ': Wrong Response Status');
  13193. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  13194.  
  13195. updateProgress(nodeList, {
  13196. status: 'Failed! (Wrong Status)',
  13197. progress: '0',
  13198. progressText: '',
  13199. class: 'ehD-pt-warning'
  13200. });
  13201.  
  13202. for (var i in res) {
  13203. delete res[i];
  13204. }
  13205. return failedFetching(index, nodeList);
  13206. }
  13207. // GM_xhr doesn't support xhr.getResponseHeader() function
  13208. //if (res.getResponseHeader('Content-Type').split('/')[0] != 'image') {
  13209. else if (mime[0] !== 'image') {
  13210. console.log('[EHD] #' + (index + 1) + ': Wrong Content-Type');
  13211. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  13212.  
  13213. updateProgress(nodeList, {
  13214. status: 'Failed! (Wrong MIME)',
  13215. progress: '0',
  13216. progressText: '',
  13217. class: 'ehD-pt-warning'
  13218. });
  13219.  
  13220. for (var i in res) {
  13221. delete res[i];
  13222. }
  13223. return failedFetching(index, nodeList);
  13224. }
  13225.  
  13226. // logs in #80 shows sometimes it didn't match the regex, but cannot reproduce right now
  13227. try {
  13228. imageList[index]['_imageName'] = imageList[index]['imageName'] = res.responseHeaders.match(ehDownloadRegex.resFileName) ? getSafeName(res.responseHeaders.match(ehDownloadRegex.resFileName)[1].trim()) : imageList[index]['imageName'];
  13229. }
  13230. catch (error) {
  13231. console.log('[EHD] #' + (index + 1) + ': Parse file name failed');
  13232. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  13233.  
  13234. imageList[index]['_imageName'] = imageList[index]['imageName'];
  13235. }
  13236.  
  13237. updateProgress(nodeList, {
  13238. name: '#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'],
  13239. status: 'Succeed!',
  13240. progress: '1',
  13241. progressText: '100%',
  13242. class: 'ehD-pt-succeed'
  13243. });
  13244.  
  13245. storeRes(response, index);
  13246.  
  13247. for (var i in res) {
  13248. delete res[i];
  13249. }
  13250. response = null;
  13251. }
  13252. catch (error) {
  13253. console.log('[EHD] #' + (index + 1) + ': Unknown Error (Please send feedback)');
  13254. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  13255. console.log(error);
  13256.  
  13257. updateProgress(nodeList, {
  13258. status: 'Failed! (Unknown)',
  13259. progress: '0',
  13260. progressText: '',
  13261. class: 'ehD-pt-failed'
  13262. });
  13263.  
  13264. for (var i in res) {
  13265. delete res[i];
  13266. }
  13267. return failedFetching(index, nodeList);
  13268. }
  13269. },
  13270. onerror: function(res){
  13271. removeTimerHandler();
  13272. if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31
  13273.  
  13274. console.log('[EHD] #' + (index + 1) + ': Network Error');
  13275. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  13276.  
  13277. updateProgress(nodeList, {
  13278. status: 'Failed! (Network Error)',
  13279. progress: '0',
  13280. progressText: '',
  13281. class: 'ehD-pt-warning'
  13282. });
  13283.  
  13284. if (imageList[index]['imageURL'].indexOf('fullimg.php') >= 0) imageList[index]['imageFinalURL'] = res.finalUrl;
  13285.  
  13286. for (var i in res) {
  13287. delete res[i];
  13288. }
  13289.  
  13290. failedFetching(index, nodeList);
  13291. },
  13292. ontimeout: function(res){
  13293. removeTimerHandler();
  13294. if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31
  13295.  
  13296. console.log('[EHD] #' + (index + 1) + ': Timed Out');
  13297. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders);
  13298.  
  13299. updateProgress(nodeList, {
  13300. status: 'Failed! (Timed Out)',
  13301. progress: '0',
  13302. progressText: '',
  13303. class: 'ehD-pt-warning'
  13304. });
  13305.  
  13306. if (imageList[index]['imageURL'].indexOf('fullimg.php') >= 0) imageList[index]['imageFinalURL'] = res.finalUrl;
  13307.  
  13308. for (var i in res) {
  13309. delete res[i];
  13310. }
  13311.  
  13312. failedFetching(index, nodeList);
  13313. }
  13314. });
  13315.  
  13316. if (nodeList.status.dataset.initedAbort !== '2') {
  13317. nodeList.abort.addEventListener('click', function(){
  13318. if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31
  13319.  
  13320. removeTimerHandler();
  13321. });
  13322.  
  13323. nodeList.status.setAttribute('data-inited-abort', '2');
  13324. }
  13325.  
  13326. updateTotalStatus();
  13327. }
  13328.  
  13329. function retryAllFailed(){
  13330. var index, refetch = 0;
  13331. initProgressTable();
  13332.  
  13333. for (index = 0; index < imageData.length; index++) {
  13334. if (imageData[index] === 'Fetching') {
  13335. imageData[index] = null;
  13336. retryCount[index] = 0;
  13337. }
  13338. }
  13339.  
  13340. failedCount = 0;
  13341. fetchCount = 0;
  13342. requestDownload();
  13343. }
  13344.  
  13345. function insertCloseButton() {
  13346. var exitButton = document.createElement('button');
  13347. exitButton.style.display = 'block';
  13348. exitButton.style.margin = '0 auto';
  13349. exitButton.textContent = 'Close';
  13350. exitButton.onclick = function(){
  13351. ehDownloadDialog.removeChild(exitButton);
  13352. ehDownloadDialog.style.display = 'none';
  13353. if (ehDownloadFS.needFileSystem) ehDownloadFS.removeFile(unsafeWindow.gid + '.zip');
  13354. };
  13355. ehDownloadDialog.appendChild(exitButton);
  13356. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  13357.  
  13358. if (ehDownloadDialog.contains(forceDownloadTips)) ehDownloadDialog.removeChild(forceDownloadTips);
  13359. }
  13360.  
  13361. function getPagesURLFromMPV() {
  13362. var mpvURL = location.origin + '/mpv/' + unsafeWindow.gid + '/' +
  13363. unsafeWindow.token + '/';
  13364.  
  13365. var xhr = new XMLHttpRequest();
  13366. xhr.open('GET', mpvURL);
  13367. xhr.onload = function () {
  13368. if (xhr.status !== 200 || !xhr.responseText) {
  13369. if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13370. pushDialog('Failed! Retrying... ');
  13371. retryCount++;
  13372. xhr.open('GET', mpvURL);
  13373. xhr.timeout = 30000;
  13374. xhr.send();
  13375. }
  13376. else {
  13377. pushDialog('Failed!\nFetch Pages\' URL failed, Please try again later.');
  13378. isDownloading = false;
  13379. alert('Fetch Pages\' URL failed, Please try again later.');
  13380. }
  13381. return;
  13382. }
  13383.  
  13384. var listMatch = xhr.responseText.match(ehDownloadRegex.mpvKey);
  13385. if (!listMatch) {
  13386. console.error('[EHD] Response content is incorrect!');
  13387. if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13388. pushDialog('Failed! Retrying... ');
  13389. retryCount++;
  13390. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13391. xhr.timeout = 30000;
  13392. xhr.send();
  13393. }
  13394. else {
  13395. pushDialog('Failed!\nCan\'t get pages URL from response content.');
  13396. isDownloading = false;
  13397. }
  13398. return;
  13399. }
  13400.  
  13401. var list = new Function('return ' + listMatch[1])();
  13402.  
  13403. list.forEach(function (elem, index) {
  13404. var curURL = location.origin + '/s/' + elem.k + '/' + unsafeWindow.gid + '-' + (index + 1);
  13405. pageURLsList.push(curURL);
  13406. });
  13407. pushDialog('Succeed!');
  13408.  
  13409.  
  13410. // copied from getAllPagesURL(), THAT's UGLY!!!
  13411. // so when will 2.0 comes out /_\
  13412. getAllPagesURLFin = true;
  13413. var wrongPages = pagesRange.filter(function (elem) { return elem > pageURLsList.length; });
  13414. if (wrongPages.length !== 0) {
  13415. pagesRange = pagesRange.filter(function (elem) { return elem <= pageURLsList.length; });
  13416. pushDialog('\nPage ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.\n');
  13417. if (pagesRange.length === 0) {
  13418. pushDialog('Nothing matches provided pages range, stop downloading.');
  13419. alert('Nothing matches provided pages range, stop downloading.');
  13420. insertCloseButton();
  13421. return;
  13422. }
  13423. }
  13424. totalCount = pagesRange.length || pageURLsList.length;
  13425. pushDialog('\n\n');
  13426. initProgressTable();
  13427. requestDownload();
  13428. };
  13429. xhr.send();
  13430. pushDialog('Fetching Gallery Pages URL From MPV...');
  13431. }
  13432.  
  13433. // /*if pages range is set, then*/ get all pages URL to select needed pages
  13434. function getAllPagesURL() {
  13435. pagesRange = [];
  13436. var pagesRangeText = ehDownloadRange.querySelector('input').value.replace(/,/g, ',').trim();
  13437. var retryCount = 0;
  13438.  
  13439. if (pagesRangeText) { // if pages range is defined
  13440. console.log('[EHD] Pages Range >', pagesRangeText);
  13441. if (!ehDownloadRegex.pagesRange.test(pagesRangeText)) return alert('The format of Pages Range is incorrect.');
  13442.  
  13443. var rangeRegex = /(?:(\d*)-(\d*))(?:\/(\d+))?|(\d+)/g;
  13444. var matches;
  13445. while (matches = rangeRegex.exec(pagesRangeText)) {
  13446. var single = Number(matches[4]);
  13447. if (!isNaN(single)) {
  13448. pagesRange.push(single);
  13449. continue;
  13450. }
  13451.  
  13452. var begin = Number(matches[1]) || 1;
  13453. var end = Number(matches[2]) || getFileSizeAndLength().page;
  13454. if (begin > end) {
  13455. var tmp = begin;
  13456. begin = end;
  13457. end = tmp;
  13458. }
  13459. var mod = Number(matches[3]) || 1;
  13460.  
  13461. for (var i = begin; i <= end; i += mod) {
  13462. pagesRange.push(i);
  13463. }
  13464. }
  13465.  
  13466. pagesRange.sort(function(a, b){ return a - b; });
  13467. pagesRange = pagesRange.filter(function(e, i, arr) { return i == 0 || e != arr[i - 1] });
  13468. }
  13469.  
  13470. ehDownloadDialog.style.display = 'block';
  13471. if (!getAllPagesURLFin) {
  13472. pageURLsList = [];
  13473. var pagesLength;
  13474. try { // in case pages has been modified like #56
  13475. pagesLength = [].reduce.call(document.querySelectorAll('.ptt td'), function(x, y){
  13476. var i = Number(y.textContent);
  13477. if (!isNaN(i)) return x > i ? x : i;
  13478. else return x;
  13479. });
  13480. }
  13481. catch (error) {}
  13482. var curPage = 0;
  13483. retryCount = 0;
  13484.  
  13485. var xhr = fetchPagesXHR;
  13486. xhr.onload = function(){
  13487. if (xhr.status !== 200 || !xhr.responseText) {
  13488. if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13489. pushDialog('Failed! Retrying... ');
  13490. retryCount++;
  13491. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13492. xhr.timeout = 30000;
  13493. xhr.send();
  13494. }
  13495. else {
  13496. pushDialog('Failed!\nFetch Pages\' URL failed, Please try again later.');
  13497. isDownloading = false;
  13498. alert('Fetch Pages\' URL failed, Please try again later.');
  13499. }
  13500. return;
  13501. }
  13502.  
  13503. var pagesURL = xhr.responseText.split('<div id="gdt">')[1].split('<div class="c">')[0].match(ehDownloadRegex.pagesURL);
  13504. if (!pagesURL) {
  13505. console.error('[EHD] Response content is incorrect!');
  13506. if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13507. pushDialog('Failed! Retrying... ');
  13508. retryCount++;
  13509. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13510. xhr.timeout = 30000;
  13511. xhr.send();
  13512. }
  13513. else {
  13514. pushDialog('Failed!\nCan\'t get pages URL from response content.');
  13515. isDownloading = false;
  13516. //alert('We can\'t get request content from response content. It\'s possible that E-Hentai changes source code format so that we can\'t find them, or your ISP modifies (or say hijacks) the page content. If it\'s sure that you can access to any pages of E-Hentai, including current page: ' + location.origin + location.pathname + '?p=' + curPage + ' , please report a bug.');
  13517. }
  13518. return;
  13519. }
  13520.  
  13521. if (pagesURL[0].indexOf('/mpv/') >= 0) {
  13522. console.log('[EHD] Page 1 URL > ' + pagesURL[0] + ' , use MPV fetch');
  13523. pushDialog('Pages URL is MPV link\n');
  13524.  
  13525. getPagesURLFromMPV();
  13526. return;
  13527. }
  13528.  
  13529. for (var i = 0; i < pagesURL.length; i++) {
  13530. pageURLsList.push(pagesURL[i].split('"')[1].replaceHTMLEntites());
  13531. }
  13532. pushDialog('Succeed!');
  13533.  
  13534. curPage++;
  13535. if (!pagesLength) { // can't get pagesLength correctly before
  13536. pagesLength = xhr.responseText.match(ehDownloadRegex.pagesLength)[1] - 0;
  13537. }
  13538. if (curPage === pagesLength) {
  13539. getAllPagesURLFin = true;
  13540. var wrongPages = pagesRange.filter(function(elem){ return elem > pageURLsList.length; });
  13541. if (wrongPages.length !== 0) {
  13542. pagesRange = pagesRange.filter(function(elem){ return elem <= pageURLsList.length; });
  13543. pushDialog('\nPage ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.\n');
  13544. if (pagesRange.length === 0) {
  13545. pushDialog('Nothing matches provided pages range, stop downloading.');
  13546. alert('Nothing matches provided pages range, stop downloading.');
  13547. insertCloseButton();
  13548. return;
  13549. }
  13550. }
  13551. totalCount = pagesRange.length || pageURLsList.length;
  13552. pushDialog('\n\n');
  13553. initProgressTable();
  13554. requestDownload();
  13555. }
  13556. else {
  13557. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13558. xhr.send();
  13559. pushDialog('\nFetching Gallery Pages URL (' + (curPage + 1) + '/' + pagesLength + ') ... ');
  13560. }
  13561. };
  13562. xhr.ontimeout = xhr.onerror = function(){
  13563. if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13564. pushDialog('Failed! Retrying... ');
  13565. retryCount++;
  13566. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13567. xhr.timeout = 30000;
  13568. xhr.send();
  13569. }
  13570. else {
  13571. pushDialog('Failed!\nFetch Pages\' URL failed, Please try again later.');
  13572. isDownloading = false;
  13573. alert('Fetch Pages\' URL failed, Please try again later.');
  13574. }
  13575. };
  13576. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13577. xhr.timeout = 30000;
  13578. xhr.send();
  13579. pushDialog('\nFetching Gallery Pages URL (' + (curPage + 1) + '/' + (pagesLength || '?') + ') ... ');
  13580. }
  13581. else {
  13582. var wrongPages = pagesRange.filter(function(elem){ return elem > pageURLsList.length; });
  13583. if (wrongPages.length !== 0) {
  13584. pagesRange = pagesRange.filter(function(elem){ return elem <= pageURLsList.length; });
  13585. pushDialog('\nPage ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.\n');
  13586. if (pagesRange.length === 0) {
  13587. pushDialog('Nothing matches provided pages range, stop downloading.');
  13588. alert('Nothing matches provided pages range, stop downloading.');
  13589. insertCloseButton();
  13590. return;
  13591. }
  13592. }
  13593.  
  13594. totalCount = pagesRange.length || pageURLsList.length;
  13595. pushDialog('\n\n');
  13596. initProgressTable();
  13597. requestDownload();
  13598. }
  13599. }
  13600.  
  13601. function initEHDownload() {
  13602. for (var i = 0; i < fetchThread.length; i++) {
  13603. if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort();
  13604. }
  13605. imageList = [];
  13606. imageData = [];
  13607. fetchThread = [];
  13608. retryCount = [];
  13609. downloadedCount = fetchCount = failedCount = 0;
  13610. isPausing = false;
  13611. zip = new JSZip();
  13612. infoStr = '';
  13613. fetchPagesXHR.abort();
  13614.  
  13615. if (setting['recheck-file-name']) {
  13616. var dirNameNode = document.querySelector('.ehD-box-extend-dirname');
  13617. var fileNameNode = document.querySelector('.ehD-box-extend-filename');
  13618.  
  13619. if (dirNameNode && dirNameNode.value) {
  13620. dirName = getSafeName(dirNameNode.value, true);
  13621. }
  13622. else {
  13623. dirName = getReplacedName(!setting['dir-name'] ? '{gid}_{token}' : setting['dir-name']);
  13624. }
  13625.  
  13626. if (fileNameNode && fileNameNode.value) {
  13627. fileName = getSafeName(fileNameNode.value);
  13628. }
  13629. else {
  13630. fileName = getReplacedName(!setting['file-name'] ? '{title}' : setting['file-name']);
  13631. }
  13632. }
  13633. else {
  13634. dirName = getReplacedName(!setting['dir-name'] ? '{gid}_{token}' : setting['dir-name']);
  13635. fileName = getReplacedName(!setting['file-name'] ? '{title}' : setting['file-name']);
  13636. }
  13637.  
  13638. if (dirName.trim() === '/') dirName = '';
  13639. needNumberImages = ehDownloadNumberInput.querySelector('input').checked;
  13640.  
  13641. var requiredBytes = Math.ceil(getFileSizeAndLength().size + 100 * 1024);
  13642. var requiredMBs = getFileSizeAndLength().sizeMB + 0.1;
  13643.  
  13644. var fsErrorHandler = function (error) {
  13645. ehDownloadFS.errorHandler(error);
  13646.  
  13647. // roll back and use Blob to handle file
  13648. ehDownloadFS.needFileSystem = false;
  13649. alert('An error occured when requesting FileSystem.\n' +
  13650. 'Error Name: ' + (e.name || 'Unknown Error') + '\n' +
  13651. 'Error Message: ' + e.message + '\n\n' +
  13652. 'Roll back and use Blob to handle file.');
  13653. };
  13654.  
  13655. if ((!setting['store-in-fs'] && requiredMBs >= 300) && !confirm('This archive is too large (original size), please consider downloading this archive in a different way.\n\nMaximum allowed file size: Chrome / Opera 15+ 500MB | IE 10+ 600 MB | Firefox 20+ 800 MB\n(From FileSaver.js introduction)\n\nPlease also consider your operating system\'s free memory (RAM), it may take about DOUBLE the size of archive file size when generating ZIP file.\n\n* If you continue, you would probably get an error like "Failed - No File" or "Out Of Memory" if you don\'t have enough RAM and can\'t save the file successfully.\n\n* If you are using Chrome, you can try enabling "Request File System to handle large Zip file" on the settings page.\n\n* You can set Pages Range to download this archive in parts. If you have already enabled it, please ignore this message.\n\nAre you sure to continue downloading?')) return;
  13656. else if (setting['store-in-fs'] && requestFileSystem && requiredMBs >= (setting['fs-size'] !== undefined ? setting['fs-size'] : 200)) {
  13657. ehDownloadFS.needFileSystem = true;
  13658. console.log('[EHD] Required File System Space >', requiredBytes);
  13659.  
  13660. // Chrome can use about 10% of free space of disk where Chrome User Data stored in as TEMPORARY File System Storage.
  13661. if (navigator.webkitTemporaryStorage) { // if support navigator.webkitTemporaryStorage to check usable space
  13662. // use `queryUsageAndQuota` instead of `requestQuota` to check storage space,
  13663. // because `requestQuota` is incorrect when harddisk is full, says have about 5GB storage
  13664. navigator.webkitTemporaryStorage.queryUsageAndQuota(function (usage, quota) {
  13665. console.log('[EHD] Free TEMPORARY File System Space >', quota - usage);
  13666. if (quota - usage < requiredBytes) {
  13667. console.log('[EHD] Free TEMPORARY File System Space is not enough.');
  13668.  
  13669. // free space is not enough, then use persistent space
  13670. // in fact, free space of persisent file storage is always 10GiB, even free disk space is not enough
  13671. navigator.webkitPersistentStorage.queryUsageAndQuota(function (usage, quota) {
  13672. console.log('[EHD] Free PERSISTENT File System Space >', quota - usage);
  13673. if (quota - usage < requiredBytes) {
  13674. // roll back and use Blob to handle file
  13675. ehDownloadFS.needFileSystem = false;
  13676. alert('You don\'t have enough free space on the drive where Chrome stores user data (Default is system drive, normally it\'s C: ), please delete some files.\n\nNeeds more than ' + (requiredBytes - (quota - usage)) + ' Bytes.\n\nRoll back and use Blob to handle file.');
  13677. }
  13678. else {
  13679. pushDialog('\n<strong>Please allow storing large content if the browser asked for it.</strong>\n');
  13680. requestFileSystem(window.PERSISTENT, requiredBytes, ehDownloadFS.initHandler, fsErrorHandler);
  13681. }
  13682. }, fsErrorHandler);
  13683. }
  13684. else requestFileSystem(window.TEMPORARY, requiredBytes, ehDownloadFS.initHandler, fsErrorHandler);
  13685. }, fsErrorHandler);
  13686. }
  13687. else requestFileSystem(window.TEMPORARY, requiredBytes, ehDownloadFS.initHandler, fsErrorHandler);
  13688. }
  13689.  
  13690. // Array.prototype.some() is a bit ugly, so we use toString().indexOf() lol
  13691. var infoNeeds = setting['save-info-list'].toString();
  13692. if (infoNeeds.indexOf('title') >= 0) {
  13693. infoStr += document.getElementById('gn').textContent.replaceHTMLEntites() + '\n' +
  13694. document.getElementById('gj').textContent.replaceHTMLEntites() + '\n' +
  13695. window.location.href.replaceHTMLEntites() + '\n\n';
  13696. }
  13697.  
  13698. if (infoNeeds.indexOf('metas') >= 0) {
  13699. infoStr += 'Category: ' + document.querySelector('#gdc .cs').textContent.trim() + '\n' +
  13700. 'Uploader: ' + document.querySelector('#gdn a').textContent.replaceHTMLEntites() + '\n';
  13701. }
  13702. var metaNodes = document.querySelectorAll('#gdd tr');
  13703. for (var i = 0; i < metaNodes.length; i++) {
  13704. var c1 = metaNodes[i].getElementsByClassName('gdt1')[0].textContent.replaceHTMLEntites();
  13705. var c2 = metaNodes[i].getElementsByClassName('gdt2')[0].textContent.replaceHTMLEntites();
  13706. if (infoNeeds.indexOf('metas') >= 0) infoStr += c1 + ' ' + c2 + '\n';
  13707. }
  13708. if (infoNeeds.indexOf('metas') >= 0) infoStr += 'Rating: ' + unsafeWindow.average_rating + '\n\n';
  13709.  
  13710. if (infoNeeds.indexOf('tags') >= 0) {
  13711. infoStr += 'Tags:\n';
  13712.  
  13713. var tagsList = document.querySelectorAll('#taglist tr');
  13714. Array.prototype.forEach.call(tagsList, function(elem){
  13715. var tds = elem.getElementsByTagName('td');
  13716. infoStr += '> ' + tds[0].textContent + ' ';
  13717.  
  13718. var tags = tds[1].querySelectorAll('a');
  13719. infoStr += Array.prototype.map.call(tags, function(e){
  13720. return e.textContent;
  13721. }).join(', ') + '\n';
  13722. });
  13723.  
  13724. infoStr += '\n';
  13725. }
  13726.  
  13727. if (infoNeeds.indexOf('uploader-comment') >= 0 && document.getElementById('comment_0')) {
  13728. infoStr += 'Uploader Comment:\n' + document.getElementById('comment_0').innerHTML.replace(/<br>|<br \/>/gi, '\n') + '\n\n';
  13729. }
  13730. isDownloading = true;
  13731. pushDialog(infoStr);
  13732.  
  13733. pushDialog('Start downloading at ' + new Date() + '\n');
  13734. ehDownloadDialog.appendChild(ehDownloadStatus);
  13735.  
  13736. // get all pages url to fix 403 forbidden (download request was timed out)
  13737. getAllPagesURL();
  13738.  
  13739. // init playing music
  13740. if (setting['play-silent-music']) {
  13741. emptyAudio = new Audio(emptyAudioFile);
  13742. emptyAudio.loop = true;
  13743.  
  13744. var hidden, visibilityChange;
  13745. if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support
  13746. hidden = 'hidden';
  13747. visibilityChange = 'visibilitychange';
  13748. }
  13749. else if (typeof document.mozHidden !== 'undefined') {
  13750. hidden = 'mozHidden';
  13751. visibilityChange = 'mozvisibilitychange';
  13752. }
  13753. else if (typeof document.webkitHidden !== 'undefined') {
  13754. hidden = 'webkitHidden';
  13755. visibilityChange = 'webkitvisibilitychange';
  13756. }
  13757.  
  13758. var visibilityChangeHandler = function(isHidden) {
  13759. if (typeof isHidden !== 'boolean') {
  13760. isHidden = document[hidden];
  13761. }
  13762. if (isHidden && ((isDownloading && !isPausing) || isSaving)) {
  13763. emptyAudio.play();
  13764. }
  13765. else {
  13766. emptyAudio.pause();
  13767. }
  13768. };
  13769.  
  13770. if (visibilityChange) {
  13771. window.addEventListener(visibilityChange, visibilityChangeHandler);
  13772. }
  13773. else {
  13774. window.addEventListener('focus', function() {
  13775. visibilityChangeHandler(false);
  13776. });
  13777. window.addEventListener('blur', function() {
  13778. visibilityChangeHandler(true);
  13779. });
  13780. }
  13781.  
  13782. visibilityChangeHandler();
  13783. }
  13784. }
  13785.  
  13786. function initProgressTable(){
  13787. progressTable = document.createElement('table');
  13788. progressTable.className = 'ehD-pt';
  13789. ehDownloadDialog.style.display = 'block';
  13790. ehDownloadDialog.appendChild(progressTable);
  13791. ehDownloadDialog.appendChild(forceDownloadTips);
  13792. ehDownloadDialog.appendChild(ehDownloadPauseBtn);
  13793. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  13794. }
  13795.  
  13796. function requestDownload(ignoreFailed){
  13797. if (isPausing) return;
  13798. if (setting['delay-request']) {
  13799. var curTime = Date.now();
  13800. if (delayTime < curTime) {
  13801. delayTime = curTime;
  13802. }
  13803. }
  13804.  
  13805. var j = 0;
  13806. for (var i = fetchCount; i < (setting['thread-count'] !== undefined ? setting['thread-count'] : 5); i++) {
  13807. for (/*var j = 0*/; j < totalCount; j++) {
  13808. if (imageData[j] == null && (ignoreFailed || (retryCount[j] || 0) <= (setting['retry-count'] !== undefined ? setting['retry-count'] : 3))) {
  13809. imageData[j] = 'Fetching';
  13810. if (imageList[j] && setting['never-new-url']) fetchOriginalImage(j);
  13811. else if (setting['delay-request']) {
  13812. setTimeout(function(j) {
  13813. if (isPausing || fetchCount >= (setting['thread-count'] !== undefined ? setting['thread-count'] : 5)) {
  13814. imageData[j] = null;
  13815. return;
  13816. }
  13817. getPageData(j);
  13818. fetchCount++;
  13819. }, delayTime - curTime + setting['delay-request'] * 1000, j);
  13820. delayTime += setting['delay-request'] * 1000;
  13821. }
  13822. else {
  13823. getPageData(j);
  13824. fetchCount++;
  13825. }
  13826. break;
  13827. }
  13828. }
  13829. }
  13830.  
  13831. }
  13832.  
  13833. function getPageData(index) {
  13834. if (isPausing) return;
  13835.  
  13836. if (pagesRange.length) var realIndex = pagesRange[index];
  13837. else var realIndex = index + 1;
  13838.  
  13839. var needScrollIntoView = ehDownloadDialog.clientHeight + ehDownloadDialog.scrollTop >= ehDownloadDialog.scrollHeight;
  13840.  
  13841. var node = progressTable.querySelector('tr[data-index="' + index + '"]');
  13842. if (!node) {
  13843. node = document.createElement('tr');
  13844. node.className = 'ehD-pt-item';
  13845. node.setAttribute('data-index', index);
  13846. node.innerHTML = '\
  13847. <td class="ehD-pt-name">#' + realIndex + '</td>\
  13848. <td class="ehD-pt-progress-outer">\
  13849. <progress class="ehD-pt-progress"></progress>\
  13850. <span class="ehD-pt-progress-text"></span>\
  13851. </td>\
  13852. <td class="ehD-pt-status">\
  13853. <span class="ehD-pt-status-text">Pending...</span>\
  13854. <span class="ehD-pt-abort">Force Abort</span>\
  13855. </td>';
  13856. progressTable.appendChild(node);
  13857. }
  13858. if (needScrollIntoView) {
  13859. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  13860. }
  13861.  
  13862. var nodeList = {
  13863. current: node,
  13864. fileName: node.getElementsByTagName('td')[0],
  13865. status: node.getElementsByTagName('td')[2],
  13866. statusText: node.getElementsByClassName('ehD-pt-status-text')[0],
  13867. progress: node.getElementsByTagName('progress')[0],
  13868. progressText: node.getElementsByTagName('span')[0],
  13869. abort: node.getElementsByClassName('ehD-pt-abort')[0]
  13870. };
  13871.  
  13872. retryCount[index] = 0;
  13873. var fetchURL = (imageList[index] ? (imageList[index]['pageURL'] + ((!setting['never-send-nl'] && imageList[index]['nextNL']) ? (imageList[index]['pageURL'].indexOf('?') >= 0 ? '&' : '?') + 'nl=' + imageList[index]['nextNL'] : '')).replaceHTMLEntites() : pageURLsList[realIndex - 1])/*.replace(/^https?:/, '')*/;
  13874.  
  13875. // assign to fetchThread, so that we can abort them and all GM_xhr by one command fetchThread[i].abort()
  13876. var xhr = fetchThread[index] = new XMLHttpRequest();
  13877. xhr.onload = function() {
  13878. if (xhr.status !== 200 || !xhr.responseText) {
  13879. if (retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13880. retryCount[index]++;
  13881.  
  13882. updateProgress(nodeList, {
  13883. status: 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ')...',
  13884. progress: '',
  13885. progressText: '',
  13886. class: 'ehD-pt-warning'
  13887. });
  13888.  
  13889. xhr.open('GET', fetchURL);
  13890. xhr.timeout = 30000;
  13891. xhr.send();
  13892. }
  13893. else {
  13894. failedCount++;
  13895. fetchCount--;
  13896.  
  13897. console.error('[EHD] #' + realIndex + ': Failed getting image URL');
  13898. updateProgress(nodeList, {
  13899. status: 'Failed getting URL',
  13900. progress: '0',
  13901. progressText: '',
  13902. class: 'ehD-pt-failed'
  13903. });
  13904. updateTotalStatus();
  13905.  
  13906. checkFailed();
  13907. }
  13908.  
  13909. return;
  13910. }
  13911.  
  13912. try {
  13913. var imageURL = (unsafeWindow.apiuid !== -1 && xhr.responseText.indexOf('fullimg.php') >= 0 && !setting['force-resized']) ? xhr.responseText.match(ehDownloadRegex.imageURL[0])[1].replaceHTMLEntites() : xhr.responseText.indexOf('id="img"') > -1 ? xhr.responseText.match(ehDownloadRegex.imageURL[1])[1].replaceHTMLEntites() : xhr.responseText.match(ehDownloadRegex.imageURL[2])[1].replaceHTMLEntites();
  13914. var fileName = xhr.responseText.match(ehDownloadRegex.fileName)[1].replaceHTMLEntites();
  13915. var nextNL = ehDownloadRegex.nl.test(xhr.responseText) ? xhr.responseText.match(ehDownloadRegex.nl)[1] : null;
  13916. }
  13917. catch (error) {
  13918. console.error('[EHD] Response content is not correct!', error);
  13919. if (retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13920. retryCount[index]++;
  13921.  
  13922. updateProgress(nodeList, {
  13923. status: 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ')...',
  13924. progress: '',
  13925. progressText: '',
  13926. class: 'ehD-pt-warning'
  13927. });
  13928.  
  13929. xhr.open('GET', fetchURL);
  13930. xhr.timeout = 30000;
  13931. xhr.send();
  13932. }
  13933. else {
  13934. failedCount++;
  13935. fetchCount--;
  13936.  
  13937. console.error('[EHD] #' + realIndex + ': Can\'t get request content from response content');
  13938. updateProgress(nodeList, {
  13939. status: 'Response Error',
  13940. progress: '0',
  13941. progressText: '',
  13942. class: 'ehD-pt-failed'
  13943. });
  13944. updateTotalStatus();
  13945. //alert('We can\'t get request content from response content. It\'s possible that E-Hentai changes source code format so that we can\'t find them, or your ISP modifies (or say hijacks) the page content. If it\'s sure that you can access to any pages of E-Hentai, including current page: ' + fetchURL + ' , please report a bug.');
  13946.  
  13947. checkFailed();
  13948. }
  13949. return;
  13950. }
  13951.  
  13952. var imageNumber = '';
  13953. if (needNumberImages) {
  13954. // Number images, thanks to JingJang@GitHub, source: https://github.com/JingJang/E-Hentai-Downloader
  13955. if (!setting['number-real-index'] && pagesRange.length) { // if pages range was set and number original index is not required
  13956. var len = pagesRange.length.toString().length,
  13957. padding = new Array(len < 3 ? len + 1 : len).join('0');
  13958. imageNumber = (padding + (index + 1)).slice(0 - len);
  13959. }
  13960. else { // pages range was not set (download all pages, so index + 1 === realIndex) or number original index is required
  13961. var len = pageURLsList.length.toString().length,
  13962. padding = new Array(len < 3 ? len + 1 : len).join('0');
  13963. imageNumber = (padding + realIndex).slice(0 - len);
  13964. }
  13965. }
  13966.  
  13967. //imageList.push(new PageData(fetchURL, imageURL, fileName, nextNL, realIndex));
  13968. imageList[index] = new PageData(fetchURL, imageURL, fileName, nextNL, realIndex, imageNumber);
  13969.  
  13970. if (isPausing) {
  13971. updateProgress(nodeList, {
  13972. name: '#' + realIndex + ': ' + fileName,
  13973. status: 'Auto Paused',
  13974. progress: '',
  13975. progressText: '',
  13976. class: 'ehD-pt-failed'
  13977. });
  13978. fetchCount--;
  13979. imageData[index] = null;
  13980. updateTotalStatus();
  13981. }
  13982. else {
  13983. fetchOriginalImage(index, nodeList);
  13984. }
  13985.  
  13986. };
  13987. xhr.onerror = xhr.ontimeout = function() {
  13988. if (retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13989. retryCount[index]++;
  13990.  
  13991. updateProgress(nodeList, {
  13992. status: 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ')...',
  13993. progress: '',
  13994. progressText: '',
  13995. class: 'ehD-pt-warning'
  13996. });
  13997.  
  13998. xhr.open('GET', fetchURL);
  13999. xhr.timeout = 30000;
  14000. xhr.send();
  14001. }
  14002. else {
  14003. failedCount++;
  14004. fetchCount--;
  14005.  
  14006. console.error('[EHD] #' + realIndex + ': Failed getting image URL');
  14007. updateProgress(nodeList, {
  14008. status: 'Failed getting URL',
  14009. progress: '0',
  14010. progressText: '',
  14011. class: 'ehD-pt-failed'
  14012. });
  14013. updateTotalStatus();
  14014.  
  14015. checkFailed();
  14016. }
  14017. };
  14018. xhr.open('GET', fetchURL);
  14019. xhr.timeout = 30000;
  14020. xhr.send();
  14021.  
  14022. nodeList.abort.addEventListener('click', function () {
  14023. if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31
  14024.  
  14025. if (typeof fetchThread[index] !== 'undefined' && 'abort' in fetchThread[index]) fetchThread[index].abort();
  14026.  
  14027. console.log('[EHD] #' + (index + 1) + ': Force Aborted By User');
  14028. updateProgress(nodeList, {
  14029. status: 'Failed! (User Aborted)',
  14030. progress: '0',
  14031. progressText: '',
  14032. class: 'ehD-pt-warning'
  14033. });
  14034.  
  14035. failedFetching(index, nodeList);
  14036. });
  14037.  
  14038. nodeList.status.setAttribute('data-inited-abort', '1');
  14039. }
  14040.  
  14041. function showSettings() {
  14042. var ehDownloadSettingPanel = document.createElement('div');
  14043. ehDownloadSettingPanel.className = 'ehD-setting';
  14044. ehDownloadSettingPanel.setAttribute('data-active-setting', 'basic');
  14045. ehDownloadSettingPanel.innerHTML = '\
  14046. <ul class="ehD-setting-tab">\
  14047. <li data-target-setting="basic">Basic</li>\
  14048. <li data-target-setting="advanced">Advanced</li>\
  14049. </ul>\
  14050. <div class="ehD-feedback">\
  14051. ' + ehDownloadArrow + ' <strong>Feedback</strong>\
  14052. <a href="https://github.com/ccloli/E-Hentai-Downloader/issues" target="_blank">GitHub</a>\
  14053. <a href="https://sleazyfork.org/scripts/10379-e-hentai-downloader/feedback" target="_blank">GreasyFork</a>\
  14054. </div>\
  14055. <div class="ehD-setting-main">\
  14056. <div class="ehD-setting-wrapper">\
  14057. <div data-setting-page="basic" class="ehD-setting-content">\
  14058. <div class="g2"><label>Download <input type="number" data-ehd-setting="thread-count" min="1" placeholder="5" style="width: 46px;"> images at the same time (≤ 5 is recommended)</label></div>\
  14059. <div class="g2"' + ((GM_info.scriptHandler && GM_info.scriptHandler === 'Violentmonkey') ? ' style="opacity: 0.5;" title="Violentmonkey may not support this feature"' : '') + '><label>Abort downloading current image after <input type="number" data-ehd-setting="timeout" min="0" placeholder="300" style="width: 46px;"> second(s) (0 is never abort)</label></div>\
  14060. <div class="g2"><label><input type="checkbox" data-ehd-setting="speed-detect"> Abort downloading current image if speed is less than <input type="number" data-ehd-setting="speed-min" min="0" placeholder="5" style="width: 46px;"> KB/s in <input type="number" data-ehd-setting="speed-expired" min="1" placeholder="30" style="width: 46px;"> second(s)</label></div>\
  14061. <div class="g2"><label>Skip current image after retried <input type="number" data-ehd-setting="retry-count" min="1" placeholder="3" style="width: 46px;"> time(s)</label></div>\
  14062. <div class="g2"><label>Delay <input type="number" data-ehd-setting="delay-request" min="0" placeholder="0" step="0.1" style="width: 46px;"> second(s) before requesting next image</label></div>\
  14063. <div class="g2"><label><input type="checkbox" data-ehd-setting="number-images"> Number images (00101.jpg, 00201_theme.jpg, 00302.jpg...) (Separator <input type="text" data-ehd-setting="number-separator" style="width: 46px;" placeholder=":">)</label></div>\
  14064. <div class="g2"><label><input type="checkbox" data-ehd-setting="number-real-index"> Number images with original page number if pages range is set</label></div>\
  14065. <div class="g2"><label><input type="checkbox" data-ehd-setting="number-auto-retry"> Retry automatically when images download failed</label></div>\
  14066. <div class="g2"><label><input type="checkbox" data-ehd-setting="auto-download-cancel"> Get downloaded images automatically when canceled downloading</label></div>\
  14067. <div class="g2"><label>Set folder name as <input type="text" data-ehd-setting="dir-name" placeholder="{gid}_{token}" style="width: 110px;"> (if you don\'t want to create folder, use "<code>/</code>") *</label></div>\
  14068. <div class="g2"><label>Set Zip file name as <input type="text" data-ehd-setting="file-name" placeholder="{title}" style="width: 110px;"> *</label></div>\
  14069. <div class="g2"><label><input type="checkbox" data-ehd-setting="recheck-file-name"> Show inputs to recheck file name and folder name before downloading</label></div>\
  14070. <div class="g2"><label><input type="checkbox" data-ehd-setting="ignore-torrent"> Never show notification if torrents are available</label></div>\
  14071. <div class="g2"><label><select data-ehd-setting="status-in-title"><option value="never">Never</option><option value="blur">When current tab is not focused</option><option value="always">Always</option></select> show download progress in title</label></div>\
  14072. <div class="g2"><label><input type="checkbox" data-ehd-setting="hide-image-limits"> Disable requesting and showing image limits</label></div>\
  14073. <div class="g2"><label><input type="checkbox" data-ehd-setting="hide-estimated-cost"> Disable pre-calculating image limits cost</label></div>\
  14074. <div class="ehD-setting-note">\
  14075. <div class="g2">\
  14076. * Available templates: \
  14077. <span title="You can find GID and token at the address bar like this: exhentai.org/g/[GID]/[Token]/"><code>{gid}</code> Gallery GID</sapn> | \
  14078. <span title="You can find GID and token at the address bar like this: exhentai.org/g/[GID]/[Token]/"><code>{token}</code> Gallery token</sapn> | \
  14079. <span title="This title is the English title or Latin transliteration, you can find it as the first line of the title."><code>{title}</code> Gallery title</span> | \
  14080. <span title="This title is the original language title, you can find it as the second line of the title."><code>{subtitle}</code> Gallery sub-title</span> | \
  14081. <span title="This tag means the sort name of the gallery, and its output string is upper."><code>{tag}</code>, <code>{category}</code> Gallery category</span> | \
  14082. <span title="You can find it at the left of the gallery page."><code>{uploader}</code> Gallery uploader</span>\
  14083. </div>\
  14084. </div>\
  14085. </div>\
  14086. <div data-setting-page="advanced" class="ehD-setting-content">\
  14087. <div class="g2"><label>Set compression level as <input type="number" data-ehd-setting="compression-level" min="0" max="9" placeholder="0" style="width: 46px;"> (0 ~ 9, 0 is only store, not recommended to enable)</label></div>\
  14088. <div class="g2"><label><input type="checkbox" data-ehd-setting="file-descriptor"> Stream files and create Zip with file descriptors </label><sup>(1)</sup></div>\
  14089. <div class="g2"><label><input type="checkbox" data-ehd-setting="force-resized"> Force download resized image (never download original image) </label><sup>(2)</sup></div>\
  14090. <div class="g2"><label><input type="checkbox" data-ehd-setting="never-new-url"> Never get new image URL when failed to download image </label><sup>(2)</sup></div>\
  14091. <div class="g2"><label><input type="checkbox" data-ehd-setting="never-send-nl"> Never send "nl" GET parameter when getting new image URL </label><sup>(2)</sup></div>\
  14092. <div class="g2"' + (requestFileSystem ? '' : ' style="opacity: 0.5;" title="Only Chrome supports this feature"') + '><label><input type="checkbox" data-ehd-setting="store-in-fs"> Request File System to handle large Zip file </label><sup>(3)</sup></div>\
  14093. <div class="g2"' + (requestFileSystem ? '' : ' style="opacity: 0.5;" title="Only Chrome supports this feature"') + '><label>Use File System if archive is larger than <input type="number" data-ehd-setting="fs-size" min="0" placeholder="200" style="width: 46px;"> MB (0 is always) </label><sup>(3)</sup></div>\
  14094. <div class="g2"><label><input type="checkbox" data-ehd-setting="play-silent-music"> Play silent music during the process to avoid downloading freeze </label><sup>(4)</sup></div>\
  14095. <div class="g2"><label>Record and save gallery info as <select data-ehd-setting="save-info"><option value="file">File info.txt</option><option value="comment">Zip comment</option><option value="none">None</option></select></label></div>\
  14096. <div class="g2">...which includes <label><input type="checkbox" data-ehd-setting="save-info-list[]" value="title">Title & Gallery Link</label> <label><input type="checkbox" data-ehd-setting="save-info-list[]" value="metas">Metadatas</label> <label><input type="checkbox" data-ehd-setting="save-info-list[]" value="tags">Tags</label> <label><input type="checkbox" data-ehd-setting="save-info-list[]" value="uploader-comment">Uploader Comment</label> <label><input type="checkbox" data-ehd-setting="save-info-list[]" value="page-links">Page Links</label></div>\
  14097. <div class="g2"><label><input type="checkbox" data-ehd-setting="replace-with-full-width"> Replace forbidden characters with full-width characters instead of dash (-)</label></div>\
  14098. <div class="g2"><label><input type="checkbox" data-ehd-setting="force-pause"> Force drop downloaded images data when pausing download</label></div>\
  14099. <div class="g2"><label><input type="checkbox" data-ehd-setting="save-as-cbz"> Save as CBZ (Comic book archive) file<sup>(5)</sup></label></div>\
  14100. <div class="ehD-setting-note">\
  14101. <div class="g2">\
  14102. (1) This may reduce memory usage but some decompress softwares may not support the Zip file. See <a href="https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html" target="_blank" style="color: #ffffff;">JSZip Docs</a> for more info.\
  14103. </div>\
  14104. <div class="g2">\
  14105. (2) Enable these options may save your image viewing limits <a href="https://github.com/ccloli/E-Hentai-Downloader/wiki/E%E2%88%92Hentai-Image-Viewing-Limits" target="_blank" style="color: #ffffff;">(See wiki)</a>, but may also cause some download problems.\
  14106. </div>\
  14107. <div class="g2">\
  14108. (3) If enabled you can save larger Zip files (probably ~1GB).\
  14109. </div>\
  14110. <div class="g2">\
  14111. (4) If enabled will play slient music to avoid downloading freeze when page is in background <a href="https://github.com/ccloli/E-Hentai-Downloader/issues/65" target="_blank">(See issue)</a>. Only needed if you have the problem, because the audio-playing icon maybe annoying.\
  14112. </div>\
  14113. <div class="g2">\
  14114. (5) <a href="https://en.wikipedia.org/wiki/Comic_book_archive">Comic book archive</a> is a file type to archive comic images, you can open it with some comic viewer like CDisplay/CDisplayEX, or just extract it as a Zip file. To keep the order of images, you can also enable numbering images.\
  14115. </div>\
  14116. </div>\
  14117. </div>\
  14118. </div>\
  14119. </div>\
  14120. <div class="ehD-setting-footer" style="text-align: center">\
  14121. <button data-action="save">Save</button> <button data-action="cancel">Cancel</button>\
  14122. </div>';
  14123. document.body.appendChild(ehDownloadSettingPanel);
  14124. for (var i in setting) {
  14125. if (setting[i] instanceof Array) {
  14126. setting[i].forEach(function(elem){
  14127. var element = ehDownloadSettingPanel.querySelector('input[data-ehd-setting="' + i + '[]"][value="' + elem + '"], select[data-ehd-setting="' + i + '[]"] option[value="' + elem + '"]');
  14128. if (!element) return;
  14129.  
  14130. if (element.getAttribute('type') === 'checkbox') {
  14131. element.setAttribute('checked', 'checked');
  14132. }
  14133. else if (element.tagName.toLowerCase() === 'option') {
  14134. element.setAttribute('selected', 'selected');
  14135. }
  14136. else element.value = elem;
  14137. });
  14138. }
  14139. else {
  14140. var element = ehDownloadSettingPanel.querySelector('input[data-ehd-setting="' + i + '"], select[data-ehd-setting="' + i + '"]');
  14141. if (!element) continue;
  14142. if (element.getAttribute('type') === 'checkbox') {
  14143. if (setting[i]) element.setAttribute('checked', 'checked');
  14144. }
  14145. else if (element.tagName.toLowerCase() === 'select') {
  14146. element = element.querySelector('option[value="' + setting[i] + '"]');
  14147. if (!element) continue;
  14148. element.setAttribute('selected', 'selected');
  14149. }
  14150. else element.setAttribute('value', setting[i]);
  14151. }
  14152. }
  14153.  
  14154. ehDownloadSettingPanel.getElementsByClassName('ehD-setting-tab')[0].addEventListener('click', function(event){
  14155. var target = event.target;
  14156. if (target.tagName.toLowerCase() === 'li') {
  14157. ehDownloadSettingPanel.setAttribute('data-active-setting', target.dataset.targetSetting);
  14158. }
  14159. });
  14160.  
  14161. ehDownloadSettingPanel.getElementsByClassName('ehD-setting-footer')[0].addEventListener('click', function(event){
  14162. var target = event.target;
  14163. if (target.tagName.toLowerCase() === 'button') {
  14164. if (target.dataset.action === 'save') {
  14165. var inputs = ehDownloadSettingPanel.querySelectorAll('input[data-ehd-setting], select[data-ehd-setting]');
  14166. setting = {};
  14167. for (var i = 0; i < inputs.length; i++) {
  14168. if (inputs[i].getAttribute('type') !== 'checkbox' && inputs[i].value === '') continue;
  14169.  
  14170. var curSettingName = inputs[i].dataset.ehdSetting;
  14171.  
  14172. if (inputs[i].getAttribute('type') === 'checkbox') {
  14173. if (inputs[i].checked) {
  14174. if (inputs[i].hasAttribute('value')) {
  14175. if (curSettingName.indexOf('[]') >= 0) {
  14176. curSettingName = curSettingName.split('[]')[0];
  14177. if (!setting[curSettingName]) setting[curSettingName] = [];
  14178. setting[curSettingName].push(inputs[i].getAttribute('value'));
  14179. }
  14180. else {
  14181. setting[curSettingName] = inputs[i].getAttribute('value');
  14182. }
  14183. }
  14184. else {
  14185. setting[curSettingName] = inputs[i].checked;
  14186. }
  14187. }
  14188. else {
  14189. setting[curSettingName] = inputs[i].checked;
  14190. }
  14191. }
  14192. else if (inputs[i].getAttribute('type') === 'number') {
  14193. setting[curSettingName] = Number(inputs[i].value);
  14194. if (isNaN(setting[curSettingName])) {
  14195. setting[curSettingName] = Number(inputs[i].getAttribute('placeholder'));
  14196. }
  14197. }
  14198. else {
  14199. setting[curSettingName] = inputs[i].value;
  14200. }
  14201. }
  14202. GM_setValue('ehD-setting', JSON.stringify(setting));
  14203. }
  14204. document.body.removeChild(ehDownloadSettingPanel);
  14205.  
  14206. if (document.querySelector('.ehD-box-extend')) {
  14207. toggleFilenameConfirmInput('reset');
  14208. }
  14209. else {
  14210. toggleFilenameConfirmInput(!setting['recheck-file-name']);
  14211. }
  14212. showPreCalcCost();
  14213. }
  14214. });
  14215.  
  14216. Array.prototype.forEach.call(ehDownloadSettingPanel.getElementsByClassName('ehD-setting-content'), function(elem) {
  14217. elem.addEventListener('focusin', function(event){
  14218. ehDownloadSettingPanel.setAttribute('data-active-setting', this.dataset.settingPage);
  14219. // prevent auto-scroll from browser
  14220. ehDownloadSettingPanel.scrollLeft = 0;
  14221. }, true);
  14222. });
  14223. }
  14224.  
  14225. function getImageLimits(forced, host){
  14226. var host = host || location.hostname;
  14227. if (host === 'exhentai.org') {
  14228. host = 'e-hentai.org';
  14229. }
  14230. var url = 'https://' + host + '/home.php';
  14231.  
  14232. var preData = JSON.parse(localStorage.getItem('ehd-image-limits-' + host) || '{"timestamp":0}');
  14233. if (!forced && new Date() - preData.timestamp < 30000) {
  14234. return showImageLimits();
  14235. }
  14236.  
  14237. console.log('[EHD] Request Image Limits From ' + host);
  14238.  
  14239. GM_xmlhttpRequest({
  14240. method: 'GET',
  14241. url: url,
  14242. timeout: 300000,
  14243. onload: function(res) {
  14244. if (!res.responseText) return;
  14245. var data = res.responseText.match(ehDownloadRegex.imageLimits);
  14246. if (data && data.length === 3) {
  14247. preData.cur = data[1];
  14248. preData.total = data[2];
  14249. preData.timestamp = new Date().getTime();
  14250. localStorage.setItem('ehd-image-limits-' + host, JSON.stringify(preData));
  14251. showImageLimits();
  14252. }
  14253. }
  14254. });
  14255. }
  14256.  
  14257. function showImageLimits(){
  14258. var list = Object.keys(localStorage).filter(function(elem){
  14259. return elem.indexOf('ehd-image-limits-') === 0;
  14260. }).sort().map(function(elem){
  14261. var curData = JSON.parse(localStorage.getItem(elem));
  14262. return curData.cur + '/' + curData.total;
  14263. });
  14264.  
  14265. ehDownloadBox.getElementsByClassName('ehD-box-limit')[0].innerHTML = ' | <a href="https://e-hentai.org/home.php">Image Limits: ' + list.join('; ') + '</a>';
  14266. }
  14267.  
  14268. var getFileSizeAndLength = function() {
  14269. var context = document.getElementById('gdd').textContent;
  14270. var sizeText = context.split('File Size:')[1].split('Length:')[0].trim();
  14271. var pageText = context.split('Length:')[1].split('page')[0].trim();
  14272.  
  14273. var sizeMB, sizeKB;
  14274. var page = pageText - 0;
  14275.  
  14276. if (sizeText.indexOf('MB') >= 0) {
  14277. sizeMB = parseFloat(sizeText) + 0.01;
  14278. sizeKB = sizeMB * 1024;
  14279. }
  14280. else if (sizeText.indexOf('GB') >= 0) {
  14281. sizeMB = (parseFloat(sizeText) + 0.01) * 1024;
  14282. sizeKB = sizeMB * 1024;
  14283. }
  14284. else {
  14285. sizeMB = 1;
  14286. sizeKB = parseFloat(sizeText);
  14287. }
  14288.  
  14289. var result = {
  14290. sizeMB: sizeMB,
  14291. sizeKB: sizeKB,
  14292. size: sizeKB * 1024,
  14293. page: page
  14294. };
  14295.  
  14296. getFileSizeAndLength = function(){
  14297. return result;
  14298. };
  14299.  
  14300. return result;
  14301. };
  14302.  
  14303. function toggleFilenameConfirmInput(hide){
  14304. var extendNodes = document.querySelector('.ehD-box-extend');
  14305. if (extendNodes) {
  14306. if (hide === 'reset') {
  14307. ehDownloadBox.removeChild(extendNodes);
  14308. if (setting['recheck-file-name']) toggleFilenameConfirmInput();
  14309. }
  14310. else if (hide) {
  14311. extendNodes.style.display = 'none';
  14312. }
  14313. else {
  14314. extendNodes.style.display = 'block';
  14315. }
  14316. }
  14317. else if (!hide) {
  14318. extendNodes = document.createElement('div');
  14319. extendNodes.className = 'ehD-box-extend';
  14320. extendNodes.innerHTML = '<div class="g2">' + ehDownloadArrow + ' <a><label>File Name <input type="text" class="ehD-box-extend-filename"></label></a></div>' +
  14321. '<div class="g2">' + ehDownloadArrow + ' <a><label>Path Name <input type="text" class="ehD-box-extend-dirname"</label></a></div>';
  14322. ehDownloadBox.appendChild(extendNodes);
  14323.  
  14324. dirName = getReplacedName(!setting['dir-name'] ? '{gid}_{token}' : setting['dir-name']);
  14325. fileName = getReplacedName(!setting['file-name'] ? '{title}' : setting['file-name']);
  14326. extendNodes.getElementsByClassName('ehD-box-extend-filename')[0].value = fileName;
  14327. extendNodes.getElementsByClassName('ehD-box-extend-dirname')[0].value = dirName;
  14328. }
  14329. }
  14330.  
  14331. function getResolutionSetting(forced){
  14332. var url = '/uconfig.php';
  14333.  
  14334. var preData = JSON.parse(localStorage.getItem('ehd-resolution') || '{"timestamp":0}');
  14335. if (!forced && new Date() - preData.timestamp < 3600e3) {
  14336. return;
  14337. }
  14338.  
  14339. console.log('[EHD] Request Resolution Setting');
  14340.  
  14341. var xhr = new XMLHttpRequest();
  14342. xhr.onload = function() {
  14343. if (!xhr.responseText) return;
  14344. var preData = {
  14345. withoutHentaiAtHome: +((xhr.responseText.match(/id="uh_(\d)" checked/) || [])[1] || 0),
  14346. resolution: +((xhr.responseText.match(/id="xr_(\d)" checked/) || [])[1] || 0),
  14347. timestamp: Date.now()
  14348. };
  14349. console.log('[EHD] Resolution Setting >', JSON.stringify(preData));
  14350. localStorage.setItem('ehd-resolution', JSON.stringify(preData));
  14351. showPreCalcCost();
  14352. };
  14353. xhr.open('GET', url);
  14354. xhr.send();
  14355. }
  14356.  
  14357. function showPreCalcCost(){
  14358. var resolutionSetting = JSON.parse(localStorage.getItem('ehd-resolution') || '{"timestamp":0}');
  14359. var resolutionCost = {
  14360. 0: 1,
  14361. 1: 1,
  14362. 2: 1,
  14363. 3: 1,
  14364. 4: 3,
  14365. 5: 5
  14366. };
  14367. var size = 0;
  14368. var page = getFileSizeAndLength().page;
  14369. var perCost = resolutionCost[resolutionSetting.resolution || 0];
  14370. if (resolutionSetting.withoutHentaiAtHome) {
  14371. perCost += 5;
  14372. }
  14373. var cost = page * perCost;
  14374.  
  14375. if (!setting['force-resized']) {
  14376. size = getFileSizeAndLength().sizeMB;
  14377. // 1 point per 0.1 MB since August 2019, less than 0.1 MB will also be counted, so asumme each image size has the extra < 100 KB
  14378. cost = Math.ceil((size * 10) + page * (1 + perCost));
  14379. }
  14380.  
  14381. ehDownloadBox.getElementsByClassName('ehD-box-cost')[0].innerHTML = ' | <a href="https://github.com/ccloli/E-Hentai-Downloader/wiki/E%E2%88%92Hentai-Image-Viewing-Limits" target="_blank" title="1 point per 0.1 MB since August 2019, less than 0.1 MB will also be counted">Estimated Limits Cost: ' + cost + '</a>';
  14382. }
  14383.  
  14384. // EHD Box, thanks to JingJang@GitHub, source: https://github.com/JingJang/E-Hentai-Downloader
  14385. var ehDownloadBox = document.createElement('fieldset');
  14386. ehDownloadBox.className = 'ehD-box';
  14387. var ehDownloadBoxTitle = document.createElement('legend');
  14388. ehDownloadBoxTitle.innerHTML = 'E-Hentai Downloader <span class="ehD-box-limit"></span> <span class="ehD-box-cost"></span>';
  14389. if (origin.indexOf('exhentai.org') >= 0) ehDownloadBoxTitle.style.color = '#ffff66';
  14390. ehDownloadBox.appendChild(ehDownloadBoxTitle);
  14391. var ehDownloadStylesheet = document.createElement('style');
  14392. ehDownloadStylesheet.textContent = ehDownloadStyle;
  14393. ehDownloadBox.appendChild(ehDownloadStylesheet);
  14394.  
  14395. var ehDownloadArrow = '<img src="data:image/gif;base64,R0lGODlhBQAHALMAAK6vr7OztK+urra2tkJCQsDAwEZGRrKyskdHR0FBQUhISP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAFAAcAAAQUUI1FlREVpbOUSkTgbZ0CUEhBLREAOw==">';
  14396.  
  14397. var ehDownloadAction = document.createElement('div');
  14398. ehDownloadAction.className = 'g2';
  14399. ehDownloadAction.innerHTML = ehDownloadArrow + ' <a>Download Archive</a>';
  14400. ehDownloadAction.addEventListener('click', function(event){
  14401. event.preventDefault();
  14402.  
  14403. var torrentsNode = document.querySelector('#gd5 a[onclick*="gallerytorrents.php"]');
  14404. var torrentsCount = torrentsNode ? torrentsNode.textContent.match(/\d+/)[0] - 0 : 0;
  14405. if (isDownloading && !confirm('E-Hentai Downloader is working now, are you sure to stop downloading and start a new download?')) return;
  14406. else if (!setting['ignore-torrent'] && torrentsCount > 0 && !confirm('There are ' + torrentsCount + ' torrent(s) available for this gallery. You can download the torrent(s) to get a stable and controllable download experience without spending your image limits, or even get bonus content.\n\nContinue downloading with E-Hentai Downloader (Yes) or use torrent(s) directly (No)?\n(You can disable this notification in the Settings)')) {
  14407. return torrentsNode.dispatchEvent(new MouseEvent('click'));
  14408. }
  14409. if (unsafeWindow.apiuid === -1 && !confirm('You are not logged in to E-Hentai Forums, so you can\'t download original image. Continue?')) return;
  14410. ehDownloadDialog.innerHTML = '';
  14411.  
  14412. initEHDownload();
  14413. });
  14414. ehDownloadBox.appendChild(ehDownloadAction);
  14415.  
  14416. var ehDownloadNumberInput = document.createElement('div');
  14417. ehDownloadNumberInput.className = 'g2';
  14418. ehDownloadNumberInput.innerHTML = ehDownloadArrow + ' <a><label><input type="checkbox" style="vertical-align: middle; margin: 0;"> Number Images</label></a>';
  14419. ehDownloadBox.appendChild(ehDownloadNumberInput);
  14420.  
  14421. var ehDownloadRange = document.createElement('div');
  14422. ehDownloadRange.className = 'g2';
  14423. ehDownloadRange.innerHTML = ehDownloadArrow + ' <a><label>Pages Range <input type="text" placeholder="eg. -10,12,14-20,27,30-40/2,50-60/3,70-"></label></a>';
  14424. ehDownloadBox.appendChild(ehDownloadRange);
  14425.  
  14426. var ehDownloadSetting = document.createElement('div');
  14427. ehDownloadSetting.className = 'g2';
  14428. ehDownloadSetting.innerHTML = ehDownloadArrow + ' <a>Settings</a>';
  14429. ehDownloadSetting.addEventListener('click', function(event){
  14430. event.preventDefault();
  14431. showSettings();
  14432. });
  14433. ehDownloadBox.appendChild(ehDownloadSetting);
  14434.  
  14435. document.body.insertBefore(ehDownloadBox, document.getElementById('asm') || document.querySelector('.gm').nextElementSibling);
  14436.  
  14437. var ehDownloadDialog = document.createElement('div');
  14438. ehDownloadDialog.className = 'ehD-dialog';
  14439. document.body.appendChild(ehDownloadDialog);
  14440.  
  14441. var ehDownloadStatus = document.createElement('div');
  14442. ehDownloadStatus.className = 'ehD-status';
  14443. ehDownloadStatus.addEventListener('click', function(event){
  14444. event.preventDefault();
  14445. ehDownloadDialog.classList.toggle('hidden');
  14446. });
  14447.  
  14448. var ehDownloadPauseBtn = document.createElement('button');
  14449. ehDownloadPauseBtn.className = 'ehD-pause';
  14450. ehDownloadPauseBtn.textContent ='Pause';
  14451. ehDownloadPauseBtn.addEventListener('click', function(event){
  14452. if (!isPausing) {
  14453. isPausing = true;
  14454. ehDownloadPauseBtn.textContent = 'Resume';
  14455. if (setting['force-pause']) {
  14456. // waiting Tampermonkey for transfering string to ArrayBuffer, it may stuck for a second
  14457. setTimeout(function(){
  14458. for (var i = 0; i < fetchThread.length; i++) {
  14459. if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort();
  14460.  
  14461. if (imageData[i] === 'Fetching' && retryCount[i] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  14462. var elem = progressTable.querySelector('tr[data-index="' + i + '"] .ehD-pt-status-text');
  14463. if (elem) elem.textContent = 'Force Paused';
  14464.  
  14465. elem = progressTable.querySelector('tr[data-index="' + i + '"] .ehD-pt-progress-text');
  14466. if (elem) elem.textContent = '';
  14467.  
  14468. imageData[i] = null;
  14469. //fetchCount = 0; // fixed for async
  14470. fetchCount--;
  14471.  
  14472. updateTotalStatus();
  14473. }
  14474. }
  14475. }, 0);
  14476. }
  14477.  
  14478. if (emptyAudio) {
  14479. emptyAudio.pause();
  14480. }
  14481. }
  14482. else {
  14483. isPausing = false;
  14484. ehDownloadPauseBtn.textContent = setting['force-pause'] ? 'Pause (Downloading images will be aborted)' : 'Pause (Downloading images will keep downloading)';
  14485.  
  14486. checkFailed();
  14487. }
  14488. });
  14489.  
  14490. window.addEventListener('focus', function(){
  14491. if (setting['status-in-title'] === 'blur') {
  14492. if (!needTitleStatus) return;
  14493. document.title = pretitle;
  14494. needTitleStatus = false;
  14495. }
  14496. });
  14497.  
  14498. window.addEventListener('blur', function(){
  14499. if (isDownloading && setting['status-in-title'] === 'blur') {
  14500. needTitleStatus = true;
  14501. document.title = '[' + (isPausing ? '❙❙' : downloadedCount < totalCount ? '↓ ' + downloadedCount + '/' + totalCount : totalCount === 0 ? '↓' : '√' ) + '] ' + pretitle;
  14502. }
  14503. });
  14504.  
  14505. var forceDownloadTips = document.createElement('div');
  14506. forceDownloadTips.className = 'ehD-force-download-tips';
  14507. forceDownloadTips.innerHTML = 'If an error occured and script doesn\'t work, click <a href="javascript: getzip();" style="font-weight: bold; pointer-events: auto;" title="Force download won\'t stop current downloading task.">here</a> to force get your downloaded images.';
  14508. forceDownloadTips.getElementsByTagName('a')[0].addEventListener('click', function(event){
  14509. // fixed permission denied on GreaseMonkey
  14510. event.preventDefault();
  14511. saveDownloaded(true);
  14512. });
  14513.  
  14514. var closeTips = document.createElement('div');
  14515. closeTips.className = 'ehD-close-tips';
  14516. closeTips.innerHTML = 'E-Hentai Downloader is still running, please don\'t close this tab until it finished downloading.<br><br>If any bug occured and the script doesn\'t work correctly, you can move your mouse pointer onto the progress box, and force to save downloaded images before you leave.';
  14517.  
  14518. unsafeWindow.getzip = window.getzip = function(){
  14519. saveDownloaded(true);
  14520. };
  14521.  
  14522. initSetting();
  14523.  
  14524. window.addEventListener('storage', showImageLimits);
  14525.  
  14526. window.onbeforeunload = unsafeWindow.onbeforeunload = function(){
  14527. function clearRubbish(){
  14528. for (var i = 0; i < fetchThread.length; i++) {
  14529. if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort();
  14530. }
  14531. ehDownloadFS.removeFile(unsafeWindow.gid + '.zip');
  14532. }
  14533. if (isDownloading || isPausing || isSaving) {
  14534. document.body.appendChild(closeTips);
  14535.  
  14536. setTimeout(function(){
  14537. document.body.removeChild(closeTips);
  14538. }, 100);
  14539.  
  14540. return 'E-Hentai Downloader is still running, please don\'t close this tab until it finished downloading.';
  14541. }
  14542. clearRubbish();
  14543. };