E-Hentai Downloader

Download E-Hentai archive as zip file

Version vom 21.01.2018. Aktuellste Version

  1. // ==UserScript==
  2. // @name E-Hentai Downloader
  3. // @version 1.29.1
  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.3 - 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. // vim: set shiftwidth=4 softtabstop=4:
  377.  
  378. },{"./utils":32}],5:[function(require,module,exports){
  379. 'use strict';
  380. exports.base64 = false;
  381. exports.binary = false;
  382. exports.dir = false;
  383. exports.createFolders = true;
  384. exports.date = null;
  385. exports.compression = null;
  386. exports.compressionOptions = null;
  387. exports.comment = null;
  388. exports.unixPermissions = null;
  389. exports.dosPermissions = null;
  390.  
  391. },{}],6:[function(require,module,exports){
  392. /* global Promise */
  393. 'use strict';
  394.  
  395. // load the global object first:
  396. // - it should be better integrated in the system (unhandledRejection in node)
  397. // - the environment may have a custom Promise implementation (see zone.js)
  398. var ES6Promise = null;
  399. if (typeof Promise !== "undefined") {
  400. ES6Promise = Promise;
  401. } else {
  402. ES6Promise = require("lie");
  403. }
  404.  
  405. /**
  406. * Let the user use/change some implementations.
  407. */
  408. module.exports = {
  409. Promise: ES6Promise
  410. };
  411.  
  412. },{"lie":58}],7:[function(require,module,exports){
  413. 'use strict';
  414. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  415.  
  416. var pako = require("pako");
  417. var utils = require("./utils");
  418. var GenericWorker = require("./stream/GenericWorker");
  419.  
  420. var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
  421.  
  422. exports.magic = "\x08\x00";
  423.  
  424. /**
  425. * Create a worker that uses pako to inflate/deflate.
  426. * @constructor
  427. * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
  428. * @param {Object} options the options to use when (de)compressing.
  429. */
  430. function FlateWorker(action, options) {
  431. GenericWorker.call(this, "FlateWorker/" + action);
  432.  
  433. this._pako = new pako[action]({
  434. raw:true,
  435. level : options.level || -1 // default compression
  436. });
  437. // the `meta` object from the last chunk received
  438. // this allow this worker to pass around metadata
  439. this.meta = {};
  440.  
  441. var self = this;
  442. this._pako.onData = function(data) {
  443. self.push({
  444. data : data,
  445. meta : self.meta
  446. });
  447. };
  448. }
  449.  
  450. utils.inherits(FlateWorker, GenericWorker);
  451.  
  452. /**
  453. * @see GenericWorker.processChunk
  454. */
  455. FlateWorker.prototype.processChunk = function (chunk) {
  456. this.meta = chunk.meta;
  457. this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
  458. };
  459.  
  460. /**
  461. * @see GenericWorker.flush
  462. */
  463. FlateWorker.prototype.flush = function () {
  464. GenericWorker.prototype.flush.call(this);
  465. this._pako.push([], true);
  466. };
  467. /**
  468. * @see GenericWorker.cleanUp
  469. */
  470. FlateWorker.prototype.cleanUp = function () {
  471. GenericWorker.prototype.cleanUp.call(this);
  472. this._pako = null;
  473. };
  474.  
  475. exports.compressWorker = function (compressionOptions) {
  476. return new FlateWorker("Deflate", compressionOptions);
  477. };
  478. exports.uncompressWorker = function () {
  479. return new FlateWorker("Inflate", {});
  480. };
  481.  
  482. },{"./stream/GenericWorker":28,"./utils":32,"pako":59}],8:[function(require,module,exports){
  483. 'use strict';
  484.  
  485. var utils = require('../utils');
  486. var GenericWorker = require('../stream/GenericWorker');
  487. var utf8 = require('../utf8');
  488. var crc32 = require('../crc32');
  489. var signature = require('../signature');
  490.  
  491. /**
  492. * Transform an integer into a string in hexadecimal.
  493. * @private
  494. * @param {number} dec the number to convert.
  495. * @param {number} bytes the number of bytes to generate.
  496. * @returns {string} the result.
  497. */
  498. var decToHex = function(dec, bytes) {
  499. var hex = "", i;
  500. for (i = 0; i < bytes; i++) {
  501. hex += String.fromCharCode(dec & 0xff);
  502. dec = dec >>> 8;
  503. }
  504. return hex;
  505. };
  506.  
  507. /**
  508. * Generate the UNIX part of the external file attributes.
  509. * @param {Object} unixPermissions the unix permissions or null.
  510. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  511. * @return {Number} a 32 bit integer.
  512. *
  513. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  514. *
  515. * TTTTsstrwxrwxrwx0000000000ADVSHR
  516. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  517. * ^^^_________________________ setuid, setgid, sticky
  518. * ^^^^^^^^^________________ permissions
  519. * ^^^^^^^^^^______ not used ?
  520. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  521. */
  522. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  523.  
  524. var result = unixPermissions;
  525. if (!unixPermissions) {
  526. // I can't use octal values in strict mode, hence the hexa.
  527. // 040775 => 0x41fd
  528. // 0100664 => 0x81b4
  529. result = isDir ? 0x41fd : 0x81b4;
  530. }
  531. return (result & 0xFFFF) << 16;
  532. };
  533.  
  534. /**
  535. * Generate the DOS part of the external file attributes.
  536. * @param {Object} dosPermissions the dos permissions or null.
  537. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  538. * @return {Number} a 32 bit integer.
  539. *
  540. * Bit 0 Read-Only
  541. * Bit 1 Hidden
  542. * Bit 2 System
  543. * Bit 3 Volume Label
  544. * Bit 4 Directory
  545. * Bit 5 Archive
  546. */
  547. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  548.  
  549. // the dir flag is already set for compatibility
  550. return (dosPermissions || 0) & 0x3F;
  551. };
  552.  
  553. /**
  554. * Generate the various parts used in the construction of the final zip file.
  555. * @param {Object} streamInfo the hash with informations about the compressed file.
  556. * @param {Boolean} streamedContent is the content streamed ?
  557. * @param {Boolean} streamingEnded is the stream finished ?
  558. * @param {number} offset the current offset from the start of the zip file.
  559. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  560. * @param {Function} encodeFileName the function to encode the file name / comment.
  561. * @return {Object} the zip parts.
  562. */
  563. var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
  564. var file = streamInfo['file'],
  565. compression = streamInfo['compression'],
  566. useCustomEncoding = encodeFileName !== utf8.utf8encode,
  567. encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
  568. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  569. comment = file.comment,
  570. encodedComment = utils.transformTo("string", encodeFileName(comment)),
  571. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  572. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  573. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  574. dosTime,
  575. dosDate,
  576. extraFields = "",
  577. unicodePathExtraField = "",
  578. unicodeCommentExtraField = "",
  579. dir = file.dir,
  580. date = file.date;
  581.  
  582.  
  583. var dataInfo = {
  584. crc32 : 0,
  585. compressedSize : 0,
  586. uncompressedSize : 0
  587. };
  588.  
  589. // if the content is streamed, the sizes/crc32 are only available AFTER
  590. // the end of the stream.
  591. if (!streamedContent || streamingEnded) {
  592. dataInfo.crc32 = streamInfo['crc32'];
  593. dataInfo.compressedSize = streamInfo['compressedSize'];
  594. dataInfo.uncompressedSize = streamInfo['uncompressedSize'];
  595. }
  596.  
  597. var bitflag = 0;
  598. if (streamedContent) {
  599. // Bit 3: the sizes/crc32 are set to zero in the local header.
  600. // The correct values are put in the data descriptor immediately
  601. // following the compressed data.
  602. bitflag |= 0x0008;
  603. }
  604. if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
  605. // Bit 11: Language encoding flag (EFS).
  606. bitflag |= 0x0800;
  607. }
  608.  
  609.  
  610. var extFileAttr = 0;
  611. var versionMadeBy = 0;
  612. if (dir) {
  613. // dos or unix, we set the dos dir flag
  614. extFileAttr |= 0x00010;
  615. }
  616. if(platform === "UNIX") {
  617. versionMadeBy = 0x031E; // UNIX, version 3.0
  618. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  619. } else { // DOS or other, fallback to DOS
  620. versionMadeBy = 0x0014; // DOS, version 2.0
  621. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  622. }
  623.  
  624. // date
  625. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  626. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  627. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  628.  
  629. dosTime = date.getUTCHours();
  630. dosTime = dosTime << 6;
  631. dosTime = dosTime | date.getUTCMinutes();
  632. dosTime = dosTime << 5;
  633. dosTime = dosTime | date.getUTCSeconds() / 2;
  634.  
  635. dosDate = date.getUTCFullYear() - 1980;
  636. dosDate = dosDate << 4;
  637. dosDate = dosDate | (date.getUTCMonth() + 1);
  638. dosDate = dosDate << 5;
  639. dosDate = dosDate | date.getUTCDate();
  640.  
  641. if (useUTF8ForFileName) {
  642. // set the unicode path extra field. unzip needs at least one extra
  643. // field to correctly handle unicode path, so using the path is as good
  644. // as any other information. This could improve the situation with
  645. // other archive managers too.
  646. // This field is usually used without the utf8 flag, with a non
  647. // unicode path in the header (winrar, winzip). This helps (a bit)
  648. // with the messy Windows' default compressed folders feature but
  649. // breaks on p7zip which doesn't seek the unicode path extra field.
  650. // So for now, UTF-8 everywhere !
  651. unicodePathExtraField =
  652. // Version
  653. decToHex(1, 1) +
  654. // NameCRC32
  655. decToHex(crc32(encodedFileName), 4) +
  656. // UnicodeName
  657. utfEncodedFileName;
  658.  
  659. extraFields +=
  660. // Info-ZIP Unicode Path Extra Field
  661. "\x75\x70" +
  662. // size
  663. decToHex(unicodePathExtraField.length, 2) +
  664. // content
  665. unicodePathExtraField;
  666. }
  667.  
  668. if(useUTF8ForComment) {
  669.  
  670. unicodeCommentExtraField =
  671. // Version
  672. decToHex(1, 1) +
  673. // CommentCRC32
  674. decToHex(crc32(encodedComment), 4) +
  675. // UnicodeName
  676. utfEncodedComment;
  677.  
  678. extraFields +=
  679. // Info-ZIP Unicode Path Extra Field
  680. "\x75\x63" +
  681. // size
  682. decToHex(unicodeCommentExtraField.length, 2) +
  683. // content
  684. unicodeCommentExtraField;
  685. }
  686.  
  687. var header = "";
  688.  
  689. // version needed to extract
  690. header += "\x0A\x00";
  691. // general purpose bit flag
  692. header += decToHex(bitflag, 2);
  693. // compression method
  694. header += compression.magic;
  695. // last mod file time
  696. header += decToHex(dosTime, 2);
  697. // last mod file date
  698. header += decToHex(dosDate, 2);
  699. // crc-32
  700. header += decToHex(dataInfo.crc32, 4);
  701. // compressed size
  702. header += decToHex(dataInfo.compressedSize, 4);
  703. // uncompressed size
  704. header += decToHex(dataInfo.uncompressedSize, 4);
  705. // file name length
  706. header += decToHex(encodedFileName.length, 2);
  707. // extra field length
  708. header += decToHex(extraFields.length, 2);
  709.  
  710.  
  711. var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  712.  
  713. var dirRecord = signature.CENTRAL_FILE_HEADER +
  714. // version made by (00: DOS)
  715. decToHex(versionMadeBy, 2) +
  716. // file header (common to file and central directory)
  717. header +
  718. // file comment length
  719. decToHex(encodedComment.length, 2) +
  720. // disk number start
  721. "\x00\x00" +
  722. // internal file attributes TODO
  723. "\x00\x00" +
  724. // external file attributes
  725. decToHex(extFileAttr, 4) +
  726. // relative offset of local header
  727. decToHex(offset, 4) +
  728. // file name
  729. encodedFileName +
  730. // extra field
  731. extraFields +
  732. // file comment
  733. encodedComment;
  734.  
  735. return {
  736. fileRecord: fileRecord,
  737. dirRecord: dirRecord
  738. };
  739. };
  740.  
  741. /**
  742. * Generate the EOCD record.
  743. * @param {Number} entriesCount the number of entries in the zip file.
  744. * @param {Number} centralDirLength the length (in bytes) of the central dir.
  745. * @param {Number} localDirLength the length (in bytes) of the local dir.
  746. * @param {String} comment the zip file comment as a binary string.
  747. * @param {Function} encodeFileName the function to encode the comment.
  748. * @return {String} the EOCD record.
  749. */
  750. var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
  751. var dirEnd = "";
  752. var encodedComment = utils.transformTo("string", encodeFileName(comment));
  753.  
  754. // end of central dir signature
  755. dirEnd = signature.CENTRAL_DIRECTORY_END +
  756. // number of this disk
  757. "\x00\x00" +
  758. // number of the disk with the start of the central directory
  759. "\x00\x00" +
  760. // total number of entries in the central directory on this disk
  761. decToHex(entriesCount, 2) +
  762. // total number of entries in the central directory
  763. decToHex(entriesCount, 2) +
  764. // size of the central directory 4 bytes
  765. decToHex(centralDirLength, 4) +
  766. // offset of start of central directory with respect to the starting disk number
  767. decToHex(localDirLength, 4) +
  768. // .ZIP file comment length
  769. decToHex(encodedComment.length, 2) +
  770. // .ZIP file comment
  771. encodedComment;
  772.  
  773. return dirEnd;
  774. };
  775.  
  776. /**
  777. * Generate data descriptors for a file entry.
  778. * @param {Object} streamInfo the hash generated by a worker, containing informations
  779. * on the file entry.
  780. * @return {String} the data descriptors.
  781. */
  782. var generateDataDescriptors = function (streamInfo) {
  783. var descriptor = "";
  784. descriptor = signature.DATA_DESCRIPTOR +
  785. // crc-32 4 bytes
  786. decToHex(streamInfo['crc32'], 4) +
  787. // compressed size 4 bytes
  788. decToHex(streamInfo['compressedSize'], 4) +
  789. // uncompressed size 4 bytes
  790. decToHex(streamInfo['uncompressedSize'], 4);
  791.  
  792. return descriptor;
  793. };
  794.  
  795.  
  796. /**
  797. * A worker to concatenate other workers to create a zip file.
  798. * @param {Boolean} streamFiles `true` to stream the content of the files,
  799. * `false` to accumulate it.
  800. * @param {String} comment the comment to use.
  801. * @param {String} platform the platform to use, "UNIX" or "DOS".
  802. * @param {Function} encodeFileName the function to encode file names and comments.
  803. */
  804. function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
  805. GenericWorker.call(this, "ZipFileWorker");
  806. // The number of bytes written so far. This doesn't count accumulated chunks.
  807. this.bytesWritten = 0;
  808. // The comment of the zip file
  809. this.zipComment = comment;
  810. // The platform "generating" the zip file.
  811. this.zipPlatform = platform;
  812. // the function to encode file names and comments.
  813. this.encodeFileName = encodeFileName;
  814. // Should we stream the content of the files ?
  815. this.streamFiles = streamFiles;
  816. // If `streamFiles` is false, we will need to accumulate the content of the
  817. // files to calculate sizes / crc32 (and write them *before* the content).
  818. // This boolean indicates if we are accumulating chunks (it will change a lot
  819. // during the lifetime of this worker).
  820. this.accumulate = false;
  821. // The buffer receiving chunks when accumulating content.
  822. this.contentBuffer = [];
  823. // The list of generated directory records.
  824. this.dirRecords = [];
  825. // The offset (in bytes) from the beginning of the zip file for the current source.
  826. this.currentSourceOffset = 0;
  827. // The total number of entries in this zip file.
  828. this.entriesCount = 0;
  829. // the name of the file currently being added, null when handling the end of the zip file.
  830. // Used for the emited metadata.
  831. this.currentFile = null;
  832.  
  833.  
  834.  
  835. this._sources = [];
  836. }
  837. utils.inherits(ZipFileWorker, GenericWorker);
  838.  
  839. /**
  840. * @see GenericWorker.push
  841. */
  842. ZipFileWorker.prototype.push = function (chunk) {
  843.  
  844. var currentFilePercent = chunk.meta.percent || 0;
  845. var entriesCount = this.entriesCount;
  846. var remainingFiles = this._sources.length;
  847.  
  848. if(this.accumulate) {
  849. this.contentBuffer.push(chunk);
  850. } else {
  851. this.bytesWritten += chunk.data.length;
  852.  
  853. GenericWorker.prototype.push.call(this, {
  854. data : chunk.data,
  855. meta : {
  856. currentFile : this.currentFile,
  857. percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
  858. }
  859. });
  860. }
  861. };
  862.  
  863. /**
  864. * The worker started a new source (an other worker).
  865. * @param {Object} streamInfo the streamInfo object from the new source.
  866. */
  867. ZipFileWorker.prototype.openedSource = function (streamInfo) {
  868. this.currentSourceOffset = this.bytesWritten;
  869. this.currentFile = streamInfo['file'].name;
  870.  
  871. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  872.  
  873. // don't stream folders (because they don't have any content)
  874. if(streamedContent) {
  875. var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  876. this.push({
  877. data : record.fileRecord,
  878. meta : {percent:0}
  879. });
  880. } else {
  881. // we need to wait for the whole file before pushing anything
  882. this.accumulate = true;
  883. }
  884. };
  885.  
  886. /**
  887. * The worker finished a source (an other worker).
  888. * @param {Object} streamInfo the streamInfo object from the finished source.
  889. */
  890. ZipFileWorker.prototype.closedSource = function (streamInfo) {
  891. this.accumulate = false;
  892. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  893. var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  894.  
  895. this.dirRecords.push(record.dirRecord);
  896. if(streamedContent) {
  897. // after the streamed file, we put data descriptors
  898. this.push({
  899. data : generateDataDescriptors(streamInfo),
  900. meta : {percent:100}
  901. });
  902. } else {
  903. // the content wasn't streamed, we need to push everything now
  904. // first the file record, then the content
  905. this.push({
  906. data : record.fileRecord,
  907. meta : {percent:0}
  908. });
  909. while(this.contentBuffer.length) {
  910. this.push(this.contentBuffer.shift());
  911. }
  912. }
  913. this.currentFile = null;
  914. };
  915.  
  916. /**
  917. * @see GenericWorker.flush
  918. */
  919. ZipFileWorker.prototype.flush = function () {
  920.  
  921. var localDirLength = this.bytesWritten;
  922. for(var i = 0; i < this.dirRecords.length; i++) {
  923. this.push({
  924. data : this.dirRecords[i],
  925. meta : {percent:100}
  926. });
  927. }
  928. var centralDirLength = this.bytesWritten - localDirLength;
  929.  
  930. var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
  931.  
  932. this.push({
  933. data : dirEnd,
  934. meta : {percent:100}
  935. });
  936. };
  937.  
  938. /**
  939. * Prepare the next source to be read.
  940. */
  941. ZipFileWorker.prototype.prepareNextSource = function () {
  942. this.previous = this._sources.shift();
  943. this.openedSource(this.previous.streamInfo);
  944. if (this.isPaused) {
  945. this.previous.pause();
  946. } else {
  947. this.previous.resume();
  948. }
  949. };
  950.  
  951. /**
  952. * @see GenericWorker.registerPrevious
  953. */
  954. ZipFileWorker.prototype.registerPrevious = function (previous) {
  955. this._sources.push(previous);
  956. var self = this;
  957.  
  958. previous.on('data', function (chunk) {
  959. self.processChunk(chunk);
  960. });
  961. previous.on('end', function () {
  962. self.closedSource(self.previous.streamInfo);
  963. if(self._sources.length) {
  964. self.prepareNextSource();
  965. } else {
  966. self.end();
  967. }
  968. });
  969. previous.on('error', function (e) {
  970. self.error(e);
  971. });
  972. return this;
  973. };
  974.  
  975. /**
  976. * @see GenericWorker.resume
  977. */
  978. ZipFileWorker.prototype.resume = function () {
  979. if(!GenericWorker.prototype.resume.call(this)) {
  980. return false;
  981. }
  982.  
  983. if (!this.previous && this._sources.length) {
  984. this.prepareNextSource();
  985. return true;
  986. }
  987. if (!this.previous && !this._sources.length && !this.generatedError) {
  988. this.end();
  989. return true;
  990. }
  991. };
  992.  
  993. /**
  994. * @see GenericWorker.error
  995. */
  996. ZipFileWorker.prototype.error = function (e) {
  997. var sources = this._sources;
  998. if(!GenericWorker.prototype.error.call(this, e)) {
  999. return false;
  1000. }
  1001. for(var i = 0; i < sources.length; i++) {
  1002. try {
  1003. sources[i].error(e);
  1004. } catch(e) {
  1005. // the `error` exploded, nothing to do
  1006. }
  1007. }
  1008. return true;
  1009. };
  1010.  
  1011. /**
  1012. * @see GenericWorker.lock
  1013. */
  1014. ZipFileWorker.prototype.lock = function () {
  1015. GenericWorker.prototype.lock.call(this);
  1016. var sources = this._sources;
  1017. for(var i = 0; i < sources.length; i++) {
  1018. sources[i].lock();
  1019. }
  1020. };
  1021.  
  1022. module.exports = ZipFileWorker;
  1023.  
  1024. },{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){
  1025. 'use strict';
  1026.  
  1027. var compressions = require('../compressions');
  1028. var ZipFileWorker = require('./ZipFileWorker');
  1029.  
  1030. /**
  1031. * Find the compression to use.
  1032. * @param {String} fileCompression the compression defined at the file level, if any.
  1033. * @param {String} zipCompression the compression defined at the load() level.
  1034. * @return {Object} the compression object to use.
  1035. */
  1036. var getCompression = function (fileCompression, zipCompression) {
  1037.  
  1038. var compressionName = fileCompression || zipCompression;
  1039. var compression = compressions[compressionName];
  1040. if (!compression) {
  1041. throw new Error(compressionName + " is not a valid compression method !");
  1042. }
  1043. return compression;
  1044. };
  1045.  
  1046. /**
  1047. * Create a worker to generate a zip file.
  1048. * @param {JSZip} zip the JSZip instance at the right root level.
  1049. * @param {Object} options to generate the zip file.
  1050. * @param {String} comment the comment to use.
  1051. */
  1052. exports.generateWorker = function (zip, options, comment) {
  1053.  
  1054. var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
  1055. var entriesCount = 0;
  1056. try {
  1057.  
  1058. zip.forEach(function (relativePath, file) {
  1059. entriesCount++;
  1060. var compression = getCompression(file.options.compression, options.compression);
  1061. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  1062. var dir = file.dir, date = file.date;
  1063.  
  1064. file._compressWorker(compression, compressionOptions)
  1065. .withStreamInfo("file", {
  1066. name : relativePath,
  1067. dir : dir,
  1068. date : date,
  1069. comment : file.comment || "",
  1070. unixPermissions : file.unixPermissions,
  1071. dosPermissions : file.dosPermissions
  1072. })
  1073. .pipe(zipFileWorker);
  1074. });
  1075. zipFileWorker.entriesCount = entriesCount;
  1076. } catch (e) {
  1077. zipFileWorker.error(e);
  1078. }
  1079.  
  1080. return zipFileWorker;
  1081. };
  1082.  
  1083. },{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){
  1084. 'use strict';
  1085.  
  1086. /**
  1087. * Representation a of zip file in js
  1088. * @constructor
  1089. */
  1090. function JSZip() {
  1091. // if this constructor is used without `new`, it adds `new` before itself:
  1092. if(!(this instanceof JSZip)) {
  1093. return new JSZip();
  1094. }
  1095.  
  1096. if(arguments.length) {
  1097. throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
  1098. }
  1099.  
  1100. // object containing the files :
  1101. // {
  1102. // "folder/" : {...},
  1103. // "folder/data.txt" : {...}
  1104. // }
  1105. this.files = {};
  1106.  
  1107. this.comment = null;
  1108.  
  1109. // Where we are in the hierarchy
  1110. this.root = "";
  1111. this.clone = function() {
  1112. var newObj = new JSZip();
  1113. for (var i in this) {
  1114. if (typeof this[i] !== "function") {
  1115. newObj[i] = this[i];
  1116. }
  1117. }
  1118. return newObj;
  1119. };
  1120. }
  1121. JSZip.prototype = require('./object');
  1122. JSZip.prototype.loadAsync = require('./load');
  1123. JSZip.support = require('./support');
  1124. JSZip.defaults = require('./defaults');
  1125.  
  1126. // TODO find a better way to handle this version,
  1127. // a require('package.json').version doesn't work with webpack, see #327
  1128. JSZip.version = "3.1.3";
  1129.  
  1130. JSZip.loadAsync = function (content, options) {
  1131. return new JSZip().loadAsync(content, options);
  1132. };
  1133.  
  1134. JSZip.external = require("./external");
  1135. module.exports = JSZip;
  1136.  
  1137. },{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){
  1138. 'use strict';
  1139. var utils = require('./utils');
  1140. var external = require("./external");
  1141. var utf8 = require('./utf8');
  1142. var utils = require('./utils');
  1143. var ZipEntries = require('./zipEntries');
  1144. var Crc32Probe = require('./stream/Crc32Probe');
  1145. var nodejsUtils = require("./nodejsUtils");
  1146.  
  1147. /**
  1148. * Check the CRC32 of an entry.
  1149. * @param {ZipEntry} zipEntry the zip entry to check.
  1150. * @return {Promise} the result.
  1151. */
  1152. function checkEntryCRC32(zipEntry) {
  1153. return new external.Promise(function (resolve, reject) {
  1154. var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
  1155. worker.on("error", function (e) {
  1156. reject(e);
  1157. })
  1158. .on("end", function () {
  1159. if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
  1160. reject(new Error("Corrupted zip : CRC32 mismatch"));
  1161. } else {
  1162. resolve();
  1163. }
  1164. })
  1165. .resume();
  1166. });
  1167. }
  1168.  
  1169. module.exports = function(data, options) {
  1170. var zip = this;
  1171. options = utils.extend(options || {}, {
  1172. base64: false,
  1173. checkCRC32: false,
  1174. optimizedBinaryString: false,
  1175. createFolders: false,
  1176. decodeFileName: utf8.utf8decode
  1177. });
  1178.  
  1179. if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1180. return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
  1181. }
  1182.  
  1183. return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
  1184. .then(function(data) {
  1185. var zipEntries = new ZipEntries(options);
  1186. zipEntries.load(data);
  1187. return zipEntries;
  1188. }).then(function checkCRC32(zipEntries) {
  1189. var promises = [external.Promise.resolve(zipEntries)];
  1190. var files = zipEntries.files;
  1191. if (options.checkCRC32) {
  1192. for (var i = 0; i < files.length; i++) {
  1193. promises.push(checkEntryCRC32(files[i]));
  1194. }
  1195. }
  1196. return external.Promise.all(promises);
  1197. }).then(function addFiles(results) {
  1198. var zipEntries = results.shift();
  1199. var files = zipEntries.files;
  1200. for (var i = 0; i < files.length; i++) {
  1201. var input = files[i];
  1202. zip.file(input.fileNameStr, input.decompressed, {
  1203. binary: true,
  1204. optimizedBinaryString: true,
  1205. date: input.date,
  1206. dir: input.dir,
  1207. comment : input.fileCommentStr.length ? input.fileCommentStr : null,
  1208. unixPermissions : input.unixPermissions,
  1209. dosPermissions : input.dosPermissions,
  1210. createFolders: options.createFolders
  1211. });
  1212. }
  1213. if (zipEntries.zipComment.length) {
  1214. zip.comment = zipEntries.zipComment;
  1215. }
  1216.  
  1217. return zip;
  1218. });
  1219. };
  1220.  
  1221. },{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){
  1222. "use strict";
  1223.  
  1224. var utils = require('../utils');
  1225. var GenericWorker = require('../stream/GenericWorker');
  1226.  
  1227. /**
  1228. * A worker that use a nodejs stream as source.
  1229. * @constructor
  1230. * @param {String} filename the name of the file entry for this stream.
  1231. * @param {Readable} stream the nodejs stream.
  1232. */
  1233. function NodejsStreamInputAdapter(filename, stream) {
  1234. GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
  1235. this._upstreamEnded = false;
  1236. this._bindStream(stream);
  1237. }
  1238.  
  1239. utils.inherits(NodejsStreamInputAdapter, GenericWorker);
  1240.  
  1241. /**
  1242. * Prepare the stream and bind the callbacks on it.
  1243. * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
  1244. * @param {Stream} stream the nodejs stream to use.
  1245. */
  1246. NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
  1247. var self = this;
  1248. this._stream = stream;
  1249. stream.pause();
  1250. stream
  1251. .on("data", function (chunk) {
  1252. self.push({
  1253. data: chunk,
  1254. meta : {
  1255. percent : 0
  1256. }
  1257. });
  1258. })
  1259. .on("error", function (e) {
  1260. if(self.isPaused) {
  1261. this.generatedError = e;
  1262. } else {
  1263. self.error(e);
  1264. }
  1265. })
  1266. .on("end", function () {
  1267. if(self.isPaused) {
  1268. self._upstreamEnded = true;
  1269. } else {
  1270. self.end();
  1271. }
  1272. });
  1273. };
  1274. NodejsStreamInputAdapter.prototype.pause = function () {
  1275. if(!GenericWorker.prototype.pause.call(this)) {
  1276. return false;
  1277. }
  1278. this._stream.pause();
  1279. return true;
  1280. };
  1281. NodejsStreamInputAdapter.prototype.resume = function () {
  1282. if(!GenericWorker.prototype.resume.call(this)) {
  1283. return false;
  1284. }
  1285.  
  1286. if(this._upstreamEnded) {
  1287. this.end();
  1288. } else {
  1289. this._stream.resume();
  1290. }
  1291.  
  1292. return true;
  1293. };
  1294.  
  1295. module.exports = NodejsStreamInputAdapter;
  1296.  
  1297. },{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){
  1298. 'use strict';
  1299.  
  1300. var Readable = require('readable-stream').Readable;
  1301.  
  1302. var util = require('util');
  1303. util.inherits(NodejsStreamOutputAdapter, Readable);
  1304.  
  1305. /**
  1306. * A nodejs stream using a worker as source.
  1307. * @see the SourceWrapper in http://nodejs.org/api/stream.html
  1308. * @constructor
  1309. * @param {StreamHelper} helper the helper wrapping the worker
  1310. * @param {Object} options the nodejs stream options
  1311. * @param {Function} updateCb the update callback.
  1312. */
  1313. function NodejsStreamOutputAdapter(helper, options, updateCb) {
  1314. Readable.call(this, options);
  1315. this._helper = helper;
  1316.  
  1317. var self = this;
  1318. helper.on("data", function (data, meta) {
  1319. if (!self.push(data)) {
  1320. self._helper.pause();
  1321. }
  1322. if(updateCb) {
  1323. updateCb(meta);
  1324. }
  1325. })
  1326. .on("error", function(e) {
  1327. self.emit('error', e);
  1328. })
  1329. .on("end", function () {
  1330. self.push(null);
  1331. });
  1332. }
  1333.  
  1334.  
  1335. NodejsStreamOutputAdapter.prototype._read = function() {
  1336. this._helper.resume();
  1337. };
  1338.  
  1339. module.exports = NodejsStreamOutputAdapter;
  1340.  
  1341. },{"readable-stream":16,"util":undefined}],14:[function(require,module,exports){
  1342. 'use strict';
  1343.  
  1344. module.exports = {
  1345. /**
  1346. * True if this is running in Nodejs, will be undefined in a browser.
  1347. * In a browser, browserify won't include this file and the whole module
  1348. * will be resolved an empty object.
  1349. */
  1350. isNode : typeof Buffer !== "undefined",
  1351. /**
  1352. * Create a new nodejs Buffer.
  1353. * @param {Object} data the data to pass to the constructor.
  1354. * @param {String} encoding the encoding to use.
  1355. * @return {Buffer} a new Buffer.
  1356. */
  1357. newBuffer : function(data, encoding){
  1358. return new Buffer(data, encoding);
  1359. },
  1360. /**
  1361. * Find out if an object is a Buffer.
  1362. * @param {Object} b the object to test.
  1363. * @return {Boolean} true if the object is a Buffer, false otherwise.
  1364. */
  1365. isBuffer : function(b){
  1366. return Buffer.isBuffer(b);
  1367. },
  1368.  
  1369. isStream : function (obj) {
  1370. return obj &&
  1371. typeof obj.on === "function" &&
  1372. typeof obj.pause === "function" &&
  1373. typeof obj.resume === "function";
  1374. }
  1375. };
  1376.  
  1377. },{}],15:[function(require,module,exports){
  1378. 'use strict';
  1379. var utf8 = require('./utf8');
  1380. var utils = require('./utils');
  1381. var GenericWorker = require('./stream/GenericWorker');
  1382. var StreamHelper = require('./stream/StreamHelper');
  1383. var defaults = require('./defaults');
  1384. var CompressedObject = require('./compressedObject');
  1385. var ZipObject = require('./zipObject');
  1386. var generate = require("./generate");
  1387. var nodejsUtils = require("./nodejsUtils");
  1388. var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
  1389.  
  1390.  
  1391. /**
  1392. * Add a file in the current folder.
  1393. * @private
  1394. * @param {string} name the name of the file
  1395. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  1396. * @param {Object} originalOptions the options of the file
  1397. * @return {Object} the new file.
  1398. */
  1399. var fileAdd = function(name, data, originalOptions) {
  1400. // be sure sub folders exist
  1401. var dataType = utils.getTypeOf(data),
  1402. parent;
  1403.  
  1404.  
  1405. /*
  1406. * Correct options.
  1407. */
  1408.  
  1409. var o = utils.extend(originalOptions || {}, defaults);
  1410. o.date = o.date || new Date();
  1411. if (o.compression !== null) {
  1412. o.compression = o.compression.toUpperCase();
  1413. }
  1414.  
  1415. if (typeof o.unixPermissions === "string") {
  1416. o.unixPermissions = parseInt(o.unixPermissions, 8);
  1417. }
  1418.  
  1419. // UNX_IFDIR 0040000 see zipinfo.c
  1420. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  1421. o.dir = true;
  1422. }
  1423. // Bit 4 Directory
  1424. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  1425. o.dir = true;
  1426. }
  1427.  
  1428. if (o.dir) {
  1429. name = forceTrailingSlash(name);
  1430. }
  1431. if (o.createFolders && (parent = parentFolder(name))) {
  1432. folderAdd.call(this, parent, true);
  1433. }
  1434.  
  1435. var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
  1436. if (!originalOptions || typeof originalOptions.binary === "undefined") {
  1437. o.binary = !isUnicodeString;
  1438. }
  1439.  
  1440.  
  1441. var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
  1442.  
  1443. if (isCompressedEmpty || o.dir || !data || data.length === 0) {
  1444. o.base64 = false;
  1445. o.binary = true;
  1446. data = "";
  1447. o.compression = "STORE";
  1448. dataType = "string";
  1449. }
  1450.  
  1451. /*
  1452. * Convert content to fit.
  1453. */
  1454.  
  1455. var zipObjectContent = null;
  1456. if (data instanceof CompressedObject || data instanceof GenericWorker) {
  1457. zipObjectContent = data;
  1458. } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1459. zipObjectContent = new NodejsStreamInputAdapter(name, data);
  1460. } else {
  1461. zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
  1462. }
  1463.  
  1464. var object = new ZipObject(name, zipObjectContent, o);
  1465. this.files[name] = object;
  1466. /*
  1467. TODO: we can't throw an exception because we have async promises
  1468. (we can have a promise of a Date() for example) but returning a
  1469. promise is useless because file(name, data) returns the JSZip
  1470. object for chaining. Should we break that to allow the user
  1471. to catch the error ?
  1472.  
  1473. return external.Promise.resolve(zipObjectContent)
  1474. .then(function () {
  1475. return object;
  1476. });
  1477. */
  1478. };
  1479.  
  1480. /**
  1481. * Find the parent folder of the path.
  1482. * @private
  1483. * @param {string} path the path to use
  1484. * @return {string} the parent folder, or ""
  1485. */
  1486. var parentFolder = function (path) {
  1487. if (path.slice(-1) === '/') {
  1488. path = path.substring(0, path.length - 1);
  1489. }
  1490. var lastSlash = path.lastIndexOf('/');
  1491. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  1492. };
  1493.  
  1494. /**
  1495. * Returns the path with a slash at the end.
  1496. * @private
  1497. * @param {String} path the path to check.
  1498. * @return {String} the path with a trailing slash.
  1499. */
  1500. var forceTrailingSlash = function(path) {
  1501. // Check the name ends with a /
  1502. if (path.slice(-1) !== "/") {
  1503. path += "/"; // IE doesn't like substr(-1)
  1504. }
  1505. return path;
  1506. };
  1507.  
  1508. /**
  1509. * Add a (sub) folder in the current folder.
  1510. * @private
  1511. * @param {string} name the folder's name
  1512. * @param {boolean=} [createFolders] If true, automatically create sub
  1513. * folders. Defaults to false.
  1514. * @return {Object} the new folder.
  1515. */
  1516. var folderAdd = function(name, createFolders) {
  1517. createFolders = (typeof createFolders !== 'undefined') ? createFolders : defaults.createFolders;
  1518.  
  1519. name = forceTrailingSlash(name);
  1520.  
  1521. // Does this folder already exist?
  1522. if (!this.files[name]) {
  1523. fileAdd.call(this, name, null, {
  1524. dir: true,
  1525. createFolders: createFolders
  1526. });
  1527. }
  1528. return this.files[name];
  1529. };
  1530.  
  1531. /**
  1532. * Cross-window, cross-Node-context regular expression detection
  1533. * @param {Object} object Anything
  1534. * @return {Boolean} true if the object is a regular expression,
  1535. * false otherwise
  1536. */
  1537. function isRegExp(object) {
  1538. return Object.prototype.toString.call(object) === "[object RegExp]";
  1539. }
  1540.  
  1541. // return the actual prototype of JSZip
  1542. var out = {
  1543. /**
  1544. * @see loadAsync
  1545. */
  1546. load: function() {
  1547. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1548. },
  1549.  
  1550.  
  1551. /**
  1552. * Call a callback function for each entry at this folder level.
  1553. * @param {Function} cb the callback function:
  1554. * function (relativePath, file) {...}
  1555. * It takes 2 arguments : the relative path and the file.
  1556. */
  1557. forEach: function(cb) {
  1558. var filename, relativePath, file;
  1559. for (filename in this.files) {
  1560. if (!this.files.hasOwnProperty(filename)) {
  1561. continue;
  1562. }
  1563. file = this.files[filename];
  1564. relativePath = filename.slice(this.root.length, filename.length);
  1565. if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
  1566. cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
  1567. }
  1568. }
  1569. },
  1570.  
  1571. /**
  1572. * Filter nested files/folders with the specified function.
  1573. * @param {Function} search the predicate to use :
  1574. * function (relativePath, file) {...}
  1575. * It takes 2 arguments : the relative path and the file.
  1576. * @return {Array} An array of matching elements.
  1577. */
  1578. filter: function(search) {
  1579. var result = [];
  1580. this.forEach(function (relativePath, entry) {
  1581. if (search(relativePath, entry)) { // the file matches the function
  1582. result.push(entry);
  1583. }
  1584.  
  1585. });
  1586. return result;
  1587. },
  1588.  
  1589. /**
  1590. * Add a file to the zip file, or search a file.
  1591. * @param {string|RegExp} name The name of the file to add (if data is defined),
  1592. * the name of the file to find (if no data) or a regex to match files.
  1593. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  1594. * @param {Object} o File options
  1595. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  1596. * a file (when searching by string) or an array of files (when searching by regex).
  1597. */
  1598. file: function(name, data, o) {
  1599. if (arguments.length === 1) {
  1600. if (isRegExp(name)) {
  1601. var regexp = name;
  1602. return this.filter(function(relativePath, file) {
  1603. return !file.dir && regexp.test(relativePath);
  1604. });
  1605. }
  1606. else { // text
  1607. var obj = this.files[this.root + name];
  1608. if (obj && !obj.dir) {
  1609. return obj;
  1610. } else {
  1611. return null;
  1612. }
  1613. }
  1614. }
  1615. else { // more than one argument : we have data !
  1616. name = this.root + name;
  1617. fileAdd.call(this, name, data, o);
  1618. }
  1619. return this;
  1620. },
  1621.  
  1622. /**
  1623. * Add a directory to the zip file, or search.
  1624. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  1625. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  1626. */
  1627. folder: function(arg) {
  1628. if (!arg) {
  1629. return this;
  1630. }
  1631.  
  1632. if (isRegExp(arg)) {
  1633. return this.filter(function(relativePath, file) {
  1634. return file.dir && arg.test(relativePath);
  1635. });
  1636. }
  1637.  
  1638. // else, name is a new folder
  1639. var name = this.root + arg;
  1640. var newFolder = folderAdd.call(this, name);
  1641.  
  1642. // Allow chaining by returning a new object with this folder as the root
  1643. var ret = this.clone();
  1644. ret.root = newFolder.name;
  1645. return ret;
  1646. },
  1647.  
  1648. /**
  1649. * Delete a file, or a directory and all sub-files, from the zip
  1650. * @param {string} name the name of the file to delete
  1651. * @return {JSZip} this JSZip object
  1652. */
  1653. remove: function(name) {
  1654. name = this.root + name;
  1655. var file = this.files[name];
  1656. if (!file) {
  1657. // Look for any folders
  1658. if (name.slice(-1) !== "/") {
  1659. name += "/";
  1660. }
  1661. file = this.files[name];
  1662. }
  1663.  
  1664. if (file && !file.dir) {
  1665. // file
  1666. delete this.files[name];
  1667. } else {
  1668. // maybe a folder, delete recursively
  1669. var kids = this.filter(function(relativePath, file) {
  1670. return file.name.slice(0, name.length) === name;
  1671. });
  1672. for (var i = 0; i < kids.length; i++) {
  1673. delete this.files[kids[i].name];
  1674. }
  1675. }
  1676.  
  1677. return this;
  1678. },
  1679.  
  1680. /**
  1681. * Generate the complete zip file
  1682. * @param {Object} options the options to generate the zip file :
  1683. * - compression, "STORE" by default.
  1684. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1685. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  1686. */
  1687. generate: function(options) {
  1688. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1689. },
  1690.  
  1691. /**
  1692. * Generate the complete zip file as an internal stream.
  1693. * @param {Object} options the options to generate the zip file :
  1694. * - compression, "STORE" by default.
  1695. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1696. * @return {StreamHelper} the streamed zip file.
  1697. */
  1698. generateInternalStream: function(options) {
  1699. var worker, opts = {};
  1700. try {
  1701. opts = utils.extend(options || {}, {
  1702. streamFiles: false,
  1703. compression: "STORE",
  1704. compressionOptions : null,
  1705. type: "",
  1706. platform: "DOS",
  1707. comment: null,
  1708. mimeType: 'application/zip',
  1709. encodeFileName: utf8.utf8encode
  1710. });
  1711.  
  1712. opts.type = opts.type.toLowerCase();
  1713. opts.compression = opts.compression.toUpperCase();
  1714.  
  1715. // "binarystring" is prefered but the internals use "string".
  1716. if(opts.type === "binarystring") {
  1717. opts.type = "string";
  1718. }
  1719.  
  1720. if (!opts.type) {
  1721. throw new Error("No output type specified.");
  1722. }
  1723.  
  1724. utils.checkSupport(opts.type);
  1725.  
  1726. // accept nodejs `process.platform`
  1727. if(
  1728. opts.platform === 'darwin' ||
  1729. opts.platform === 'freebsd' ||
  1730. opts.platform === 'linux' ||
  1731. opts.platform === 'sunos'
  1732. ) {
  1733. opts.platform = "UNIX";
  1734. }
  1735. if (opts.platform === 'win32') {
  1736. opts.platform = "DOS";
  1737. }
  1738.  
  1739. var comment = opts.comment || this.comment || "";
  1740. worker = generate.generateWorker(this, opts, comment);
  1741. } catch (e) {
  1742. worker = new GenericWorker("error");
  1743. worker.error(e);
  1744. }
  1745. return new StreamHelper(worker, opts.type || "string", opts.mimeType);
  1746. },
  1747. /**
  1748. * Generate the complete zip file asynchronously.
  1749. * @see generateInternalStream
  1750. */
  1751. generateAsync: function(options, onUpdate) {
  1752. return this.generateInternalStream(options).accumulate(onUpdate);
  1753. },
  1754. /**
  1755. * Generate the complete zip file asynchronously.
  1756. * @see generateInternalStream
  1757. */
  1758. generateNodeStream: function(options, onUpdate) {
  1759. options = options || {};
  1760. if (!options.type) {
  1761. options.type = "nodebuffer";
  1762. }
  1763. return this.generateInternalStream(options).toNodejsStream(onUpdate);
  1764. }
  1765. };
  1766. module.exports = out;
  1767.  
  1768. },{"./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){
  1769. /*
  1770. * This file is used by module bundlers (browserify/webpack/etc) when
  1771. * including a stream implementation. We use "readable-stream" to get a
  1772. * consistent behavior between nodejs versions but bundlers often have a shim
  1773. * for "stream". Using this shim greatly improve the compatibility and greatly
  1774. * reduce the final size of the bundle (only one stream implementation, not
  1775. * two).
  1776. */
  1777. module.exports = require("stream");
  1778.  
  1779. },{"stream":undefined}],17:[function(require,module,exports){
  1780. 'use strict';
  1781. var DataReader = require('./DataReader');
  1782. var utils = require('../utils');
  1783.  
  1784. function ArrayReader(data) {
  1785. DataReader.call(this, data);
  1786. for(var i = 0; i < this.data.length; i++) {
  1787. data[i] = data[i] & 0xFF;
  1788. }
  1789. }
  1790. utils.inherits(ArrayReader, DataReader);
  1791. /**
  1792. * @see DataReader.byteAt
  1793. */
  1794. ArrayReader.prototype.byteAt = function(i) {
  1795. return this.data[this.zero + i];
  1796. };
  1797. /**
  1798. * @see DataReader.lastIndexOfSignature
  1799. */
  1800. ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  1801. var sig0 = sig.charCodeAt(0),
  1802. sig1 = sig.charCodeAt(1),
  1803. sig2 = sig.charCodeAt(2),
  1804. sig3 = sig.charCodeAt(3);
  1805. for (var i = this.length - 4; i >= 0; --i) {
  1806. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  1807. return i - this.zero;
  1808. }
  1809. }
  1810.  
  1811. return -1;
  1812. };
  1813. /**
  1814. * @see DataReader.readAndCheckSignature
  1815. */
  1816. ArrayReader.prototype.readAndCheckSignature = function (sig) {
  1817. var sig0 = sig.charCodeAt(0),
  1818. sig1 = sig.charCodeAt(1),
  1819. sig2 = sig.charCodeAt(2),
  1820. sig3 = sig.charCodeAt(3),
  1821. data = this.readData(4);
  1822. return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
  1823. };
  1824. /**
  1825. * @see DataReader.readData
  1826. */
  1827. ArrayReader.prototype.readData = function(size) {
  1828. this.checkOffset(size);
  1829. if(size === 0) {
  1830. return [];
  1831. }
  1832. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1833. this.index += size;
  1834. return result;
  1835. };
  1836. module.exports = ArrayReader;
  1837.  
  1838. },{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){
  1839. 'use strict';
  1840. var utils = require('../utils');
  1841.  
  1842. function DataReader(data) {
  1843. this.data = data; // type : see implementation
  1844. this.length = data.length;
  1845. this.index = 0;
  1846. this.zero = 0;
  1847. }
  1848. DataReader.prototype = {
  1849. /**
  1850. * Check that the offset will not go too far.
  1851. * @param {string} offset the additional offset to check.
  1852. * @throws {Error} an Error if the offset is out of bounds.
  1853. */
  1854. checkOffset: function(offset) {
  1855. this.checkIndex(this.index + offset);
  1856. },
  1857. /**
  1858. * Check that the specifed index will not be too far.
  1859. * @param {string} newIndex the index to check.
  1860. * @throws {Error} an Error if the index is out of bounds.
  1861. */
  1862. checkIndex: function(newIndex) {
  1863. if (this.length < this.zero + newIndex || newIndex < 0) {
  1864. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  1865. }
  1866. },
  1867. /**
  1868. * Change the index.
  1869. * @param {number} newIndex The new index.
  1870. * @throws {Error} if the new index is out of the data.
  1871. */
  1872. setIndex: function(newIndex) {
  1873. this.checkIndex(newIndex);
  1874. this.index = newIndex;
  1875. },
  1876. /**
  1877. * Skip the next n bytes.
  1878. * @param {number} n the number of bytes to skip.
  1879. * @throws {Error} if the new index is out of the data.
  1880. */
  1881. skip: function(n) {
  1882. this.setIndex(this.index + n);
  1883. },
  1884. /**
  1885. * Get the byte at the specified index.
  1886. * @param {number} i the index to use.
  1887. * @return {number} a byte.
  1888. */
  1889. byteAt: function(i) {
  1890. // see implementations
  1891. },
  1892. /**
  1893. * Get the next number with a given byte size.
  1894. * @param {number} size the number of bytes to read.
  1895. * @return {number} the corresponding number.
  1896. */
  1897. readInt: function(size) {
  1898. var result = 0,
  1899. i;
  1900. this.checkOffset(size);
  1901. for (i = this.index + size - 1; i >= this.index; i--) {
  1902. result = (result << 8) + this.byteAt(i);
  1903. }
  1904. this.index += size;
  1905. return result;
  1906. },
  1907. /**
  1908. * Get the next string with a given byte size.
  1909. * @param {number} size the number of bytes to read.
  1910. * @return {string} the corresponding string.
  1911. */
  1912. readString: function(size) {
  1913. return utils.transformTo("string", this.readData(size));
  1914. },
  1915. /**
  1916. * Get raw data without conversion, <size> bytes.
  1917. * @param {number} size the number of bytes to read.
  1918. * @return {Object} the raw data, implementation specific.
  1919. */
  1920. readData: function(size) {
  1921. // see implementations
  1922. },
  1923. /**
  1924. * Find the last occurence of a zip signature (4 bytes).
  1925. * @param {string} sig the signature to find.
  1926. * @return {number} the index of the last occurence, -1 if not found.
  1927. */
  1928. lastIndexOfSignature: function(sig) {
  1929. // see implementations
  1930. },
  1931. /**
  1932. * Read the signature (4 bytes) at the current position and compare it with sig.
  1933. * @param {string} sig the expected signature
  1934. * @return {boolean} true if the signature matches, false otherwise.
  1935. */
  1936. readAndCheckSignature: function(sig) {
  1937. // see implementations
  1938. },
  1939. /**
  1940. * Get the next date.
  1941. * @return {Date} the date.
  1942. */
  1943. readDate: function() {
  1944. var dostime = this.readInt(4);
  1945. return new Date(Date.UTC(
  1946. ((dostime >> 25) & 0x7f) + 1980, // year
  1947. ((dostime >> 21) & 0x0f) - 1, // month
  1948. (dostime >> 16) & 0x1f, // day
  1949. (dostime >> 11) & 0x1f, // hour
  1950. (dostime >> 5) & 0x3f, // minute
  1951. (dostime & 0x1f) << 1)); // second
  1952. }
  1953. };
  1954. module.exports = DataReader;
  1955.  
  1956. },{"../utils":32}],19:[function(require,module,exports){
  1957. 'use strict';
  1958. var Uint8ArrayReader = require('./Uint8ArrayReader');
  1959. var utils = require('../utils');
  1960.  
  1961. function NodeBufferReader(data) {
  1962. Uint8ArrayReader.call(this, data);
  1963. }
  1964. utils.inherits(NodeBufferReader, Uint8ArrayReader);
  1965.  
  1966. /**
  1967. * @see DataReader.readData
  1968. */
  1969. NodeBufferReader.prototype.readData = function(size) {
  1970. this.checkOffset(size);
  1971. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1972. this.index += size;
  1973. return result;
  1974. };
  1975. module.exports = NodeBufferReader;
  1976.  
  1977. },{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){
  1978. 'use strict';
  1979. var DataReader = require('./DataReader');
  1980. var utils = require('../utils');
  1981.  
  1982. function StringReader(data) {
  1983. DataReader.call(this, data);
  1984. }
  1985. utils.inherits(StringReader, DataReader);
  1986. /**
  1987. * @see DataReader.byteAt
  1988. */
  1989. StringReader.prototype.byteAt = function(i) {
  1990. return this.data.charCodeAt(this.zero + i);
  1991. };
  1992. /**
  1993. * @see DataReader.lastIndexOfSignature
  1994. */
  1995. StringReader.prototype.lastIndexOfSignature = function(sig) {
  1996. return this.data.lastIndexOf(sig) - this.zero;
  1997. };
  1998. /**
  1999. * @see DataReader.readAndCheckSignature
  2000. */
  2001. StringReader.prototype.readAndCheckSignature = function (sig) {
  2002. var data = this.readData(4);
  2003. return sig === data;
  2004. };
  2005. /**
  2006. * @see DataReader.readData
  2007. */
  2008. StringReader.prototype.readData = function(size) {
  2009. this.checkOffset(size);
  2010. // this will work because the constructor applied the "& 0xff" mask.
  2011. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  2012. this.index += size;
  2013. return result;
  2014. };
  2015. module.exports = StringReader;
  2016.  
  2017. },{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){
  2018. 'use strict';
  2019. var ArrayReader = require('./ArrayReader');
  2020. var utils = require('../utils');
  2021.  
  2022. function Uint8ArrayReader(data) {
  2023. ArrayReader.call(this, data);
  2024. }
  2025. utils.inherits(Uint8ArrayReader, ArrayReader);
  2026. /**
  2027. * @see DataReader.readData
  2028. */
  2029. Uint8ArrayReader.prototype.readData = function(size) {
  2030. this.checkOffset(size);
  2031. if(size === 0) {
  2032. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  2033. return new Uint8Array(0);
  2034. }
  2035. var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
  2036. this.index += size;
  2037. return result;
  2038. };
  2039. module.exports = Uint8ArrayReader;
  2040.  
  2041. },{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){
  2042. 'use strict';
  2043.  
  2044. var utils = require('../utils');
  2045. var support = require('../support');
  2046. var ArrayReader = require('./ArrayReader');
  2047. var StringReader = require('./StringReader');
  2048. var NodeBufferReader = require('./NodeBufferReader');
  2049. var Uint8ArrayReader = require('./Uint8ArrayReader');
  2050.  
  2051. /**
  2052. * Create a reader adapted to the data.
  2053. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
  2054. * @return {DataReader} the data reader.
  2055. */
  2056. module.exports = function (data) {
  2057. var type = utils.getTypeOf(data);
  2058. utils.checkSupport(type);
  2059. if (type === "string" && !support.uint8array) {
  2060. return new StringReader(data);
  2061. }
  2062. if (type === "nodebuffer") {
  2063. return new NodeBufferReader(data);
  2064. }
  2065. if (support.uint8array) {
  2066. return new Uint8ArrayReader(utils.transformTo("uint8array", data));
  2067. }
  2068. return new ArrayReader(utils.transformTo("array", data));
  2069. };
  2070.  
  2071. // vim: set shiftwidth=4 softtabstop=4:
  2072.  
  2073. },{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){
  2074. 'use strict';
  2075. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  2076. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  2077. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  2078. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  2079. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  2080. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  2081.  
  2082. },{}],24:[function(require,module,exports){
  2083. 'use strict';
  2084.  
  2085. var GenericWorker = require('./GenericWorker');
  2086. var utils = require('../utils');
  2087.  
  2088. /**
  2089. * A worker which convert chunks to a specified type.
  2090. * @constructor
  2091. * @param {String} destType the destination type.
  2092. */
  2093. function ConvertWorker(destType) {
  2094. GenericWorker.call(this, "ConvertWorker to " + destType);
  2095. this.destType = destType;
  2096. }
  2097. utils.inherits(ConvertWorker, GenericWorker);
  2098.  
  2099. /**
  2100. * @see GenericWorker.processChunk
  2101. */
  2102. ConvertWorker.prototype.processChunk = function (chunk) {
  2103. this.push({
  2104. data : utils.transformTo(this.destType, chunk.data),
  2105. meta : chunk.meta
  2106. });
  2107. };
  2108. module.exports = ConvertWorker;
  2109.  
  2110. },{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){
  2111. 'use strict';
  2112.  
  2113. var GenericWorker = require('./GenericWorker');
  2114. var crc32 = require('../crc32');
  2115. var utils = require('../utils');
  2116.  
  2117. /**
  2118. * A worker which calculate the crc32 of the data flowing through.
  2119. * @constructor
  2120. */
  2121. function Crc32Probe() {
  2122. GenericWorker.call(this, "Crc32Probe");
  2123. this.withStreamInfo("crc32", 0);
  2124. }
  2125. utils.inherits(Crc32Probe, GenericWorker);
  2126.  
  2127. /**
  2128. * @see GenericWorker.processChunk
  2129. */
  2130. Crc32Probe.prototype.processChunk = function (chunk) {
  2131. this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
  2132. this.push(chunk);
  2133. };
  2134. module.exports = Crc32Probe;
  2135.  
  2136. },{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){
  2137. 'use strict';
  2138.  
  2139. var utils = require('../utils');
  2140. var GenericWorker = require('./GenericWorker');
  2141.  
  2142. /**
  2143. * A worker which calculate the total length of the data flowing through.
  2144. * @constructor
  2145. * @param {String} propName the name used to expose the length
  2146. */
  2147. function DataLengthProbe(propName) {
  2148. GenericWorker.call(this, "DataLengthProbe for " + propName);
  2149. this.propName = propName;
  2150. this.withStreamInfo(propName, 0);
  2151. }
  2152. utils.inherits(DataLengthProbe, GenericWorker);
  2153.  
  2154. /**
  2155. * @see GenericWorker.processChunk
  2156. */
  2157. DataLengthProbe.prototype.processChunk = function (chunk) {
  2158. if(chunk) {
  2159. var length = this.streamInfo[this.propName] || 0;
  2160. this.streamInfo[this.propName] = length + chunk.data.length;
  2161. }
  2162. GenericWorker.prototype.processChunk.call(this, chunk);
  2163. };
  2164. module.exports = DataLengthProbe;
  2165.  
  2166.  
  2167. },{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){
  2168. 'use strict';
  2169.  
  2170. var utils = require('../utils');
  2171. var GenericWorker = require('./GenericWorker');
  2172.  
  2173. // the size of the generated chunks
  2174. // TODO expose this as a public variable
  2175. var DEFAULT_BLOCK_SIZE = 16 * 1024;
  2176.  
  2177. /**
  2178. * A worker that reads a content and emits chunks.
  2179. * @constructor
  2180. * @param {Promise} dataP the promise of the data to split
  2181. */
  2182. function DataWorker(dataP) {
  2183. GenericWorker.call(this, "DataWorker");
  2184. var self = this;
  2185. this.dataIsReady = false;
  2186. this.index = 0;
  2187. this.max = 0;
  2188. this.data = null;
  2189. this.type = "";
  2190.  
  2191. this._tickScheduled = false;
  2192.  
  2193. dataP.then(function (data) {
  2194. self.dataIsReady = true;
  2195. self.data = data;
  2196. self.max = data && data.length || 0;
  2197. self.type = utils.getTypeOf(data);
  2198. if(!self.isPaused) {
  2199. self._tickAndRepeat();
  2200. }
  2201. }, function (e) {
  2202. self.error(e);
  2203. });
  2204. }
  2205.  
  2206. utils.inherits(DataWorker, GenericWorker);
  2207.  
  2208. /**
  2209. * @see GenericWorker.cleanUp
  2210. */
  2211. DataWorker.prototype.cleanUp = function () {
  2212. GenericWorker.prototype.cleanUp.call(this);
  2213. this.data = null;
  2214. };
  2215.  
  2216. /**
  2217. * @see GenericWorker.resume
  2218. */
  2219. DataWorker.prototype.resume = function () {
  2220. if(!GenericWorker.prototype.resume.call(this)) {
  2221. return false;
  2222. }
  2223.  
  2224. if (!this._tickScheduled && this.dataIsReady) {
  2225. this._tickScheduled = true;
  2226. utils.delay(this._tickAndRepeat, [], this);
  2227. }
  2228. return true;
  2229. };
  2230.  
  2231. /**
  2232. * Trigger a tick a schedule an other call to this function.
  2233. */
  2234. DataWorker.prototype._tickAndRepeat = function() {
  2235. this._tickScheduled = false;
  2236. if(this.isPaused || this.isFinished) {
  2237. return;
  2238. }
  2239. this._tick();
  2240. if(!this.isFinished) {
  2241. utils.delay(this._tickAndRepeat, [], this);
  2242. this._tickScheduled = true;
  2243. }
  2244. };
  2245.  
  2246. /**
  2247. * Read and push a chunk.
  2248. */
  2249. DataWorker.prototype._tick = function() {
  2250.  
  2251. if(this.isPaused || this.isFinished) {
  2252. return false;
  2253. }
  2254.  
  2255. var size = DEFAULT_BLOCK_SIZE;
  2256. var data = null, nextIndex = Math.min(this.max, this.index + size);
  2257. if (this.index >= this.max) {
  2258. // EOF
  2259. return this.end();
  2260. } else {
  2261. switch(this.type) {
  2262. case "string":
  2263. data = this.data.substring(this.index, nextIndex);
  2264. break;
  2265. case "uint8array":
  2266. data = this.data.subarray(this.index, nextIndex);
  2267. break;
  2268. case "array":
  2269. case "nodebuffer":
  2270. data = this.data.slice(this.index, nextIndex);
  2271. break;
  2272. }
  2273. this.index = nextIndex;
  2274. return this.push({
  2275. data : data,
  2276. meta : {
  2277. percent : this.max ? this.index / this.max * 100 : 0
  2278. }
  2279. });
  2280. }
  2281. };
  2282.  
  2283. module.exports = DataWorker;
  2284.  
  2285. },{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){
  2286. 'use strict';
  2287.  
  2288. /**
  2289. * A worker that does nothing but passing chunks to the next one. This is like
  2290. * a nodejs stream but with some differences. On the good side :
  2291. * - it works on IE 6-9 without any issue / polyfill
  2292. * - it weights less than the full dependencies bundled with browserify
  2293. * - it forwards errors (no need to declare an error handler EVERYWHERE)
  2294. *
  2295. * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
  2296. * object containing anything (`percent` for example), see each worker for more
  2297. * details. The latter is the real data (String, Uint8Array, etc).
  2298. *
  2299. * @constructor
  2300. * @param {String} name the name of the stream (mainly used for debugging purposes)
  2301. */
  2302. function GenericWorker(name) {
  2303. // the name of the worker
  2304. this.name = name || "default";
  2305. // an object containing metadata about the workers chain
  2306. this.streamInfo = {};
  2307. // an error which happened when the worker was paused
  2308. this.generatedError = null;
  2309. // an object containing metadata to be merged by this worker into the general metadata
  2310. this.extraStreamInfo = {};
  2311. // true if the stream is paused (and should not do anything), false otherwise
  2312. this.isPaused = true;
  2313. // true if the stream is finished (and should not do anything), false otherwise
  2314. this.isFinished = false;
  2315. // true if the stream is locked to prevent further structure updates (pipe), false otherwise
  2316. this.isLocked = false;
  2317. // the event listeners
  2318. this._listeners = {
  2319. 'data':[],
  2320. 'end':[],
  2321. 'error':[]
  2322. };
  2323. // the previous worker, if any
  2324. this.previous = null;
  2325. }
  2326.  
  2327. GenericWorker.prototype = {
  2328. /**
  2329. * Push a chunk to the next workers.
  2330. * @param {Object} chunk the chunk to push
  2331. */
  2332. push : function (chunk) {
  2333. this.emit("data", chunk);
  2334. },
  2335. /**
  2336. * End the stream.
  2337. * @return {Boolean} true if this call ended the worker, false otherwise.
  2338. */
  2339. end : function () {
  2340. if (this.isFinished) {
  2341. return false;
  2342. }
  2343.  
  2344. this.flush();
  2345. try {
  2346. this.emit("end");
  2347. this.cleanUp();
  2348. this.isFinished = true;
  2349. } catch (e) {
  2350. this.emit("error", e);
  2351. }
  2352. return true;
  2353. },
  2354. /**
  2355. * End the stream with an error.
  2356. * @param {Error} e the error which caused the premature end.
  2357. * @return {Boolean} true if this call ended the worker with an error, false otherwise.
  2358. */
  2359. error : function (e) {
  2360. if (this.isFinished) {
  2361. return false;
  2362. }
  2363.  
  2364. if(this.isPaused) {
  2365. this.generatedError = e;
  2366. } else {
  2367. this.isFinished = true;
  2368.  
  2369. this.emit("error", e);
  2370.  
  2371. // in the workers chain exploded in the middle of the chain,
  2372. // the error event will go downward but we also need to notify
  2373. // workers upward that there has been an error.
  2374. if(this.previous) {
  2375. this.previous.error(e);
  2376. }
  2377.  
  2378. this.cleanUp();
  2379. }
  2380. return true;
  2381. },
  2382. /**
  2383. * Add a callback on an event.
  2384. * @param {String} name the name of the event (data, end, error)
  2385. * @param {Function} listener the function to call when the event is triggered
  2386. * @return {GenericWorker} the current object for chainability
  2387. */
  2388. on : function (name, listener) {
  2389. this._listeners[name].push(listener);
  2390. return this;
  2391. },
  2392. /**
  2393. * Clean any references when a worker is ending.
  2394. */
  2395. cleanUp : function () {
  2396. this.streamInfo = this.generatedError = this.extraStreamInfo = null;
  2397. this._listeners = [];
  2398. },
  2399. /**
  2400. * Trigger an event. This will call registered callback with the provided arg.
  2401. * @param {String} name the name of the event (data, end, error)
  2402. * @param {Object} arg the argument to call the callback with.
  2403. */
  2404. emit : function (name, arg) {
  2405. if (this._listeners[name]) {
  2406. for(var i = 0; i < this._listeners[name].length; i++) {
  2407. this._listeners[name][i].call(this, arg);
  2408. }
  2409. }
  2410. },
  2411. /**
  2412. * Chain a worker with an other.
  2413. * @param {Worker} next the worker receiving events from the current one.
  2414. * @return {worker} the next worker for chainability
  2415. */
  2416. pipe : function (next) {
  2417. return next.registerPrevious(this);
  2418. },
  2419. /**
  2420. * Same as `pipe` in the other direction.
  2421. * Using an API with `pipe(next)` is very easy.
  2422. * Implementing the API with the point of view of the next one registering
  2423. * a source is easier, see the ZipFileWorker.
  2424. * @param {Worker} previous the previous worker, sending events to this one
  2425. * @return {Worker} the current worker for chainability
  2426. */
  2427. registerPrevious : function (previous) {
  2428. if (this.isLocked) {
  2429. throw new Error("The stream '" + this + "' has already been used.");
  2430. }
  2431.  
  2432. // sharing the streamInfo...
  2433. this.streamInfo = previous.streamInfo;
  2434. // ... and adding our own bits
  2435. this.mergeStreamInfo();
  2436. this.previous = previous;
  2437. var self = this;
  2438. previous.on('data', function (chunk) {
  2439. self.processChunk(chunk);
  2440. });
  2441. previous.on('end', function () {
  2442. self.end();
  2443. });
  2444. previous.on('error', function (e) {
  2445. self.error(e);
  2446. });
  2447. return this;
  2448. },
  2449. /**
  2450. * Pause the stream so it doesn't send events anymore.
  2451. * @return {Boolean} true if this call paused the worker, false otherwise.
  2452. */
  2453. pause : function () {
  2454. if(this.isPaused || this.isFinished) {
  2455. return false;
  2456. }
  2457. this.isPaused = true;
  2458.  
  2459. if(this.previous) {
  2460. this.previous.pause();
  2461. }
  2462. return true;
  2463. },
  2464. /**
  2465. * Resume a paused stream.
  2466. * @return {Boolean} true if this call resumed the worker, false otherwise.
  2467. */
  2468. resume : function () {
  2469. if(!this.isPaused || this.isFinished) {
  2470. return false;
  2471. }
  2472. this.isPaused = false;
  2473.  
  2474. // if true, the worker tried to resume but failed
  2475. var withError = false;
  2476. if(this.generatedError) {
  2477. this.error(this.generatedError);
  2478. withError = true;
  2479. }
  2480. if(this.previous) {
  2481. this.previous.resume();
  2482. }
  2483.  
  2484. return !withError;
  2485. },
  2486. /**
  2487. * Flush any remaining bytes as the stream is ending.
  2488. */
  2489. flush : function () {},
  2490. /**
  2491. * Process a chunk. This is usually the method overridden.
  2492. * @param {Object} chunk the chunk to process.
  2493. */
  2494. processChunk : function(chunk) {
  2495. this.push(chunk);
  2496. },
  2497. /**
  2498. * Add a key/value to be added in the workers chain streamInfo once activated.
  2499. * @param {String} key the key to use
  2500. * @param {Object} value the associated value
  2501. * @return {Worker} the current worker for chainability
  2502. */
  2503. withStreamInfo : function (key, value) {
  2504. this.extraStreamInfo[key] = value;
  2505. this.mergeStreamInfo();
  2506. return this;
  2507. },
  2508. /**
  2509. * Merge this worker's streamInfo into the chain's streamInfo.
  2510. */
  2511. mergeStreamInfo : function () {
  2512. for(var key in this.extraStreamInfo) {
  2513. if (!this.extraStreamInfo.hasOwnProperty(key)) {
  2514. continue;
  2515. }
  2516. this.streamInfo[key] = this.extraStreamInfo[key];
  2517. }
  2518. },
  2519.  
  2520. /**
  2521. * Lock the stream to prevent further updates on the workers chain.
  2522. * After calling this method, all calls to pipe will fail.
  2523. */
  2524. lock: function () {
  2525. if (this.isLocked) {
  2526. throw new Error("The stream '" + this + "' has already been used.");
  2527. }
  2528. this.isLocked = true;
  2529. if (this.previous) {
  2530. this.previous.lock();
  2531. }
  2532. },
  2533.  
  2534. /**
  2535. *
  2536. * Pretty print the workers chain.
  2537. */
  2538. toString : function () {
  2539. var me = "Worker " + this.name;
  2540. if (this.previous) {
  2541. return this.previous + " -> " + me;
  2542. } else {
  2543. return me;
  2544. }
  2545. }
  2546. };
  2547.  
  2548. module.exports = GenericWorker;
  2549.  
  2550. },{}],29:[function(require,module,exports){
  2551. 'use strict';
  2552.  
  2553. var utils = require('../utils');
  2554. var ConvertWorker = require('./ConvertWorker');
  2555. var GenericWorker = require('./GenericWorker');
  2556. var base64 = require('../base64');
  2557. var support = require("../support");
  2558. var external = require("../external");
  2559.  
  2560. var NodejsStreamOutputAdapter = null;
  2561. if (support.nodestream) {
  2562. try {
  2563. NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter');
  2564. } catch(e) {}
  2565. }
  2566.  
  2567. /**
  2568. * Apply the final transformation of the data. If the user wants a Blob for
  2569. * example, it's easier to work with an U8intArray and finally do the
  2570. * ArrayBuffer/Blob conversion.
  2571. * @param {String} resultType the name of the final type
  2572. * @param {String} chunkType the type of the data in the given array.
  2573. * @param {Array} dataArray the array containing the data chunks to concatenate
  2574. * @param {String|Uint8Array|Buffer} content the content to transform
  2575. * @param {String} mimeType the mime type of the content, if applicable.
  2576. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
  2577. */
  2578. function transformZipOutput(resultType, chunkType, dataArray, mimeType) {
  2579. var content = null;
  2580. switch(resultType) {
  2581. case "blob" :
  2582. return utils.newBlob(dataArray, mimeType);
  2583. case "base64" :
  2584. content = concat(chunkType, dataArray);
  2585. return base64.encode(content);
  2586. default :
  2587. content = concat(chunkType, dataArray);
  2588. return utils.transformTo(resultType, content);
  2589. }
  2590. }
  2591.  
  2592. /**
  2593. * Concatenate an array of data of the given type.
  2594. * @param {String} type the type of the data in the given array.
  2595. * @param {Array} dataArray the array containing the data chunks to concatenate
  2596. * @return {String|Uint8Array|Buffer} the concatenated data
  2597. * @throws Error if the asked type is unsupported
  2598. */
  2599. function concat (type, dataArray) {
  2600. var i, index = 0, res = null, totalLength = 0;
  2601. for(i = 0; i < dataArray.length; i++) {
  2602. totalLength += dataArray[i].length;
  2603. }
  2604. switch(type) {
  2605. case "string":
  2606. return dataArray.join("");
  2607. case "array":
  2608. return Array.prototype.concat.apply([], dataArray);
  2609. case "uint8array":
  2610. res = new Uint8Array(totalLength);
  2611. for(i = 0; i < dataArray.length; i++) {
  2612. res.set(dataArray[i], index);
  2613. index += dataArray[i].length;
  2614. }
  2615. return res;
  2616. case "nodebuffer":
  2617. return Buffer.concat(dataArray);
  2618. default:
  2619. throw new Error("concat : unsupported type '" + type + "'");
  2620. }
  2621. }
  2622.  
  2623. /**
  2624. * Listen a StreamHelper, accumulate its content and concatenate it into a
  2625. * complete block.
  2626. * @param {StreamHelper} helper the helper to use.
  2627. * @param {Function} updateCallback a callback called on each update. Called
  2628. * with one arg :
  2629. * - the metadata linked to the update received.
  2630. * @return Promise the promise for the accumulation.
  2631. */
  2632. function accumulate(helper, updateCallback) {
  2633. return new external.Promise(function (resolve, reject){
  2634. var dataArray = [];
  2635. var chunkType = helper._internalType,
  2636. resultType = helper._outputType,
  2637. mimeType = helper._mimeType;
  2638. helper
  2639. .on('data', function (data, meta) {
  2640. dataArray.push(data);
  2641. if(updateCallback) {
  2642. updateCallback(meta);
  2643. }
  2644. })
  2645. .on('error', function(err) {
  2646. dataArray = [];
  2647. reject(err);
  2648. })
  2649. .on('end', function (){
  2650. try {
  2651. var result = transformZipOutput(resultType, chunkType, dataArray, mimeType);
  2652. resolve(result);
  2653. } catch (e) {
  2654. reject(e);
  2655. }
  2656. dataArray = [];
  2657. })
  2658. .resume();
  2659. });
  2660. }
  2661.  
  2662. /**
  2663. * An helper to easily use workers outside of JSZip.
  2664. * @constructor
  2665. * @param {Worker} worker the worker to wrap
  2666. * @param {String} outputType the type of data expected by the use
  2667. * @param {String} mimeType the mime type of the content, if applicable.
  2668. */
  2669. function StreamHelper(worker, outputType, mimeType) {
  2670. var internalType = outputType;
  2671. switch(outputType) {
  2672. case "blob":
  2673. internalType = "arraybuffer";
  2674. break;
  2675. case "arraybuffer":
  2676. internalType = "uint8array";
  2677. break;
  2678. case "base64":
  2679. internalType = "string";
  2680. break;
  2681. }
  2682.  
  2683. try {
  2684. // the type used internally
  2685. this._internalType = internalType;
  2686. // the type used to output results
  2687. this._outputType = outputType;
  2688. // the mime type
  2689. this._mimeType = mimeType;
  2690. utils.checkSupport(internalType);
  2691. this._worker = worker.pipe(new ConvertWorker(internalType));
  2692. // the last workers can be rewired without issues but we need to
  2693. // prevent any updates on previous workers.
  2694. worker.lock();
  2695. } catch(e) {
  2696. this._worker = new GenericWorker("error");
  2697. this._worker.error(e);
  2698. }
  2699. }
  2700.  
  2701. StreamHelper.prototype = {
  2702. /**
  2703. * Listen a StreamHelper, accumulate its content and concatenate it into a
  2704. * complete block.
  2705. * @param {Function} updateCb the update callback.
  2706. * @return Promise the promise for the accumulation.
  2707. */
  2708. accumulate : function (updateCb) {
  2709. return accumulate(this, updateCb);
  2710. },
  2711. /**
  2712. * Add a listener on an event triggered on a stream.
  2713. * @param {String} evt the name of the event
  2714. * @param {Function} fn the listener
  2715. * @return {StreamHelper} the current helper.
  2716. */
  2717. on : function (evt, fn) {
  2718. var self = this;
  2719.  
  2720. if(evt === "data") {
  2721. this._worker.on(evt, function (chunk) {
  2722. fn.call(self, chunk.data, chunk.meta);
  2723. });
  2724. } else {
  2725. this._worker.on(evt, function () {
  2726. utils.delay(fn, arguments, self);
  2727. });
  2728. }
  2729. return this;
  2730. },
  2731. /**
  2732. * Resume the flow of chunks.
  2733. * @return {StreamHelper} the current helper.
  2734. */
  2735. resume : function () {
  2736. utils.delay(this._worker.resume, [], this._worker);
  2737. return this;
  2738. },
  2739. /**
  2740. * Pause the flow of chunks.
  2741. * @return {StreamHelper} the current helper.
  2742. */
  2743. pause : function () {
  2744. this._worker.pause();
  2745. return this;
  2746. },
  2747. /**
  2748. * Return a nodejs stream for this helper.
  2749. * @param {Function} updateCb the update callback.
  2750. * @return {NodejsStreamOutputAdapter} the nodejs stream.
  2751. */
  2752. toNodejsStream : function (updateCb) {
  2753. utils.checkSupport("nodestream");
  2754. if (this._outputType !== "nodebuffer") {
  2755. // an object stream containing blob/arraybuffer/uint8array/string
  2756. // is strange and I don't know if it would be useful.
  2757. // I you find this comment and have a good usecase, please open a
  2758. // bug report !
  2759. throw new Error(this._outputType + " is not supported by this method");
  2760. }
  2761.  
  2762. return new NodejsStreamOutputAdapter(this, {
  2763. objectMode : this._outputType !== "nodebuffer"
  2764. }, updateCb);
  2765. }
  2766. };
  2767.  
  2768.  
  2769. module.exports = StreamHelper;
  2770.  
  2771. },{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){
  2772. 'use strict';
  2773.  
  2774. exports.base64 = true;
  2775. exports.array = true;
  2776. exports.string = true;
  2777. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  2778. exports.nodebuffer = typeof Buffer !== "undefined";
  2779. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  2780. exports.uint8array = typeof Uint8Array !== "undefined";
  2781.  
  2782. if (typeof ArrayBuffer === "undefined") {
  2783. exports.blob = false;
  2784. }
  2785. else {
  2786. var buffer = new ArrayBuffer(0);
  2787. try {
  2788. exports.blob = new Blob([buffer], {
  2789. type: "application/zip"
  2790. }).size === 0;
  2791. }
  2792. catch (e) {
  2793. try {
  2794. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  2795. var builder = new Builder();
  2796. builder.append(buffer);
  2797. exports.blob = builder.getBlob('application/zip').size === 0;
  2798. }
  2799. catch (e) {
  2800. exports.blob = false;
  2801. }
  2802. }
  2803. }
  2804.  
  2805. try {
  2806. exports.nodestream = !!require('readable-stream').Readable;
  2807. } catch(e) {
  2808. exports.nodestream = false;
  2809. }
  2810.  
  2811. },{"readable-stream":16}],31:[function(require,module,exports){
  2812. 'use strict';
  2813.  
  2814. var utils = require('./utils');
  2815. var support = require('./support');
  2816. var nodejsUtils = require('./nodejsUtils');
  2817. var GenericWorker = require('./stream/GenericWorker');
  2818.  
  2819. /**
  2820. * The following functions come from pako, from pako/lib/utils/strings
  2821. * released under the MIT license, see pako https://github.com/nodeca/pako/
  2822. */
  2823.  
  2824. // Table with utf8 lengths (calculated by first byte of sequence)
  2825. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  2826. // because max possible codepoint is 0x10ffff
  2827. var _utf8len = new Array(256);
  2828. for (var i=0; i<256; i++) {
  2829. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  2830. }
  2831. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  2832.  
  2833. // convert string to array (typed, when possible)
  2834. var string2buf = function (str) {
  2835. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  2836.  
  2837. // count binary size
  2838. for (m_pos = 0; m_pos < str_len; m_pos++) {
  2839. c = str.charCodeAt(m_pos);
  2840. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2841. c2 = str.charCodeAt(m_pos+1);
  2842. if ((c2 & 0xfc00) === 0xdc00) {
  2843. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2844. m_pos++;
  2845. }
  2846. }
  2847. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  2848. }
  2849.  
  2850. // allocate buffer
  2851. if (support.uint8array) {
  2852. buf = new Uint8Array(buf_len);
  2853. } else {
  2854. buf = new Array(buf_len);
  2855. }
  2856.  
  2857. // convert
  2858. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  2859. c = str.charCodeAt(m_pos);
  2860. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2861. c2 = str.charCodeAt(m_pos+1);
  2862. if ((c2 & 0xfc00) === 0xdc00) {
  2863. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2864. m_pos++;
  2865. }
  2866. }
  2867. if (c < 0x80) {
  2868. /* one byte */
  2869. buf[i++] = c;
  2870. } else if (c < 0x800) {
  2871. /* two bytes */
  2872. buf[i++] = 0xC0 | (c >>> 6);
  2873. buf[i++] = 0x80 | (c & 0x3f);
  2874. } else if (c < 0x10000) {
  2875. /* three bytes */
  2876. buf[i++] = 0xE0 | (c >>> 12);
  2877. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2878. buf[i++] = 0x80 | (c & 0x3f);
  2879. } else {
  2880. /* four bytes */
  2881. buf[i++] = 0xf0 | (c >>> 18);
  2882. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  2883. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2884. buf[i++] = 0x80 | (c & 0x3f);
  2885. }
  2886. }
  2887.  
  2888. return buf;
  2889. };
  2890.  
  2891. // Calculate max possible position in utf8 buffer,
  2892. // that will not break sequence. If that's not possible
  2893. // - (very small limits) return max size as is.
  2894. //
  2895. // buf[] - utf8 bytes array
  2896. // max - length limit (mandatory);
  2897. var utf8border = function(buf, max) {
  2898. var pos;
  2899.  
  2900. max = max || buf.length;
  2901. if (max > buf.length) { max = buf.length; }
  2902.  
  2903. // go back from last position, until start of sequence found
  2904. pos = max-1;
  2905. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  2906.  
  2907. // Fuckup - very small and broken sequence,
  2908. // return max, because we should return something anyway.
  2909. if (pos < 0) { return max; }
  2910.  
  2911. // If we came to start of buffer - that means vuffer is too small,
  2912. // return max too.
  2913. if (pos === 0) { return max; }
  2914.  
  2915. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  2916. };
  2917.  
  2918. // convert array to string
  2919. var buf2string = function (buf) {
  2920. var str, i, out, c, c_len;
  2921. var len = buf.length;
  2922.  
  2923. // Reserve max possible length (2 words per char)
  2924. // NB: by unknown reasons, Array is significantly faster for
  2925. // String.fromCharCode.apply than Uint16Array.
  2926. var utf16buf = new Array(len*2);
  2927.  
  2928. for (out=0, i=0; i<len;) {
  2929. c = buf[i++];
  2930. // quick process ascii
  2931. if (c < 0x80) { utf16buf[out++] = c; continue; }
  2932.  
  2933. c_len = _utf8len[c];
  2934. // skip 5 & 6 byte codes
  2935. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  2936.  
  2937. // apply mask on first byte
  2938. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  2939. // join the rest
  2940. while (c_len > 1 && i < len) {
  2941. c = (c << 6) | (buf[i++] & 0x3f);
  2942. c_len--;
  2943. }
  2944.  
  2945. // terminated by end of string?
  2946. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  2947.  
  2948. if (c < 0x10000) {
  2949. utf16buf[out++] = c;
  2950. } else {
  2951. c -= 0x10000;
  2952. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  2953. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  2954. }
  2955. }
  2956.  
  2957. // shrinkBuf(utf16buf, out)
  2958. if (utf16buf.length !== out) {
  2959. if(utf16buf.subarray) {
  2960. utf16buf = utf16buf.subarray(0, out);
  2961. } else {
  2962. utf16buf.length = out;
  2963. }
  2964. }
  2965.  
  2966. // return String.fromCharCode.apply(null, utf16buf);
  2967. return utils.applyFromCharCode(utf16buf);
  2968. };
  2969.  
  2970.  
  2971. // That's all for the pako functions.
  2972.  
  2973.  
  2974. /**
  2975. * Transform a javascript string into an array (typed if possible) of bytes,
  2976. * UTF-8 encoded.
  2977. * @param {String} str the string to encode
  2978. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  2979. */
  2980. exports.utf8encode = function utf8encode(str) {
  2981. if (support.nodebuffer) {
  2982. return nodejsUtils.newBuffer(str, "utf-8");
  2983. }
  2984.  
  2985. return string2buf(str);
  2986. };
  2987.  
  2988.  
  2989. /**
  2990. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  2991. * string into a javascript string.
  2992. * @param {Array|Uint8Array|Buffer} buf the data de decode
  2993. * @return {String} the decoded string.
  2994. */
  2995. exports.utf8decode = function utf8decode(buf) {
  2996. if (support.nodebuffer) {
  2997. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  2998. }
  2999.  
  3000. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  3001.  
  3002. return buf2string(buf);
  3003. };
  3004.  
  3005. /**
  3006. * A worker to decode utf8 encoded binary chunks into string chunks.
  3007. * @constructor
  3008. */
  3009. function Utf8DecodeWorker() {
  3010. GenericWorker.call(this, "utf-8 decode");
  3011. // the last bytes if a chunk didn't end with a complete codepoint.
  3012. this.leftOver = null;
  3013. }
  3014. utils.inherits(Utf8DecodeWorker, GenericWorker);
  3015.  
  3016. /**
  3017. * @see GenericWorker.processChunk
  3018. */
  3019. Utf8DecodeWorker.prototype.processChunk = function (chunk) {
  3020.  
  3021. var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
  3022.  
  3023. // 1st step, re-use what's left of the previous chunk
  3024. if (this.leftOver && this.leftOver.length) {
  3025. if(support.uint8array) {
  3026. var previousData = data;
  3027. data = new Uint8Array(previousData.length + this.leftOver.length);
  3028. data.set(this.leftOver, 0);
  3029. data.set(previousData, this.leftOver.length);
  3030. } else {
  3031. data = this.leftOver.concat(data);
  3032. }
  3033. this.leftOver = null;
  3034. }
  3035.  
  3036. var nextBoundary = utf8border(data);
  3037. var usableData = data;
  3038. if (nextBoundary !== data.length) {
  3039. if (support.uint8array) {
  3040. usableData = data.subarray(0, nextBoundary);
  3041. this.leftOver = data.subarray(nextBoundary, data.length);
  3042. } else {
  3043. usableData = data.slice(0, nextBoundary);
  3044. this.leftOver = data.slice(nextBoundary, data.length);
  3045. }
  3046. }
  3047.  
  3048. this.push({
  3049. data : exports.utf8decode(usableData),
  3050. meta : chunk.meta
  3051. });
  3052. };
  3053.  
  3054. /**
  3055. * @see GenericWorker.flush
  3056. */
  3057. Utf8DecodeWorker.prototype.flush = function () {
  3058. if(this.leftOver && this.leftOver.length) {
  3059. this.push({
  3060. data : exports.utf8decode(this.leftOver),
  3061. meta : {}
  3062. });
  3063. this.leftOver = null;
  3064. }
  3065. };
  3066. exports.Utf8DecodeWorker = Utf8DecodeWorker;
  3067.  
  3068. /**
  3069. * A worker to endcode string chunks into utf8 encoded binary chunks.
  3070. * @constructor
  3071. */
  3072. function Utf8EncodeWorker() {
  3073. GenericWorker.call(this, "utf-8 encode");
  3074. }
  3075. utils.inherits(Utf8EncodeWorker, GenericWorker);
  3076.  
  3077. /**
  3078. * @see GenericWorker.processChunk
  3079. */
  3080. Utf8EncodeWorker.prototype.processChunk = function (chunk) {
  3081. this.push({
  3082. data : exports.utf8encode(chunk.data),
  3083. meta : chunk.meta
  3084. });
  3085. };
  3086. exports.Utf8EncodeWorker = Utf8EncodeWorker;
  3087.  
  3088. },{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){
  3089. 'use strict';
  3090.  
  3091. var support = require('./support');
  3092. var base64 = require('./base64');
  3093. var nodejsUtils = require('./nodejsUtils');
  3094. var setImmediate = require('core-js/library/fn/set-immediate');
  3095. var external = require("./external");
  3096.  
  3097.  
  3098. /**
  3099. * Convert a string that pass as a "binary string": it should represent a byte
  3100. * array but may have > 255 char codes. Be sure to take only the first byte
  3101. * and returns the byte array.
  3102. * @param {String} str the string to transform.
  3103. * @return {Array|Uint8Array} the string in a binary format.
  3104. */
  3105. function string2binary(str) {
  3106. var result = null;
  3107. if (support.uint8array) {
  3108. result = new Uint8Array(str.length);
  3109. } else {
  3110. result = new Array(str.length);
  3111. }
  3112. return stringToArrayLike(str, result);
  3113. }
  3114.  
  3115. /**
  3116. * Create a new blob with the given content and the given type.
  3117. * @param {Array[String|ArrayBuffer]} parts the content to put in the blob. DO NOT use
  3118. * an Uint8Array because the stock browser of android 4 won't accept it (it
  3119. * will be silently converted to a string, "[object Uint8Array]").
  3120. * @param {String} type the mime type of the blob.
  3121. * @return {Blob} the created blob.
  3122. */
  3123. exports.newBlob = function(parts, type) {
  3124. exports.checkSupport("blob");
  3125.  
  3126. try {
  3127. // Blob constructor
  3128. return new Blob(parts, {
  3129. type: type
  3130. });
  3131. }
  3132. catch (e) {
  3133.  
  3134. try {
  3135. // deprecated, browser only, old way
  3136. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  3137. var builder = new Builder();
  3138. for (var i = 0; i < parts.length; i++) {
  3139. builder.append(parts[i]);
  3140. }
  3141. return builder.getBlob(type);
  3142. }
  3143. catch (e) {
  3144.  
  3145. // well, fuck ?!
  3146. throw new Error("Bug : can't construct the Blob.");
  3147. }
  3148. }
  3149.  
  3150.  
  3151. };
  3152. /**
  3153. * The identity function.
  3154. * @param {Object} input the input.
  3155. * @return {Object} the same input.
  3156. */
  3157. function identity(input) {
  3158. return input;
  3159. }
  3160.  
  3161. /**
  3162. * Fill in an array with a string.
  3163. * @param {String} str the string to use.
  3164. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  3165. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  3166. */
  3167. function stringToArrayLike(str, array) {
  3168. for (var i = 0; i < str.length; ++i) {
  3169. array[i] = str.charCodeAt(i) & 0xFF;
  3170. }
  3171. return array;
  3172. }
  3173.  
  3174. /**
  3175. * An helper for the function arrayLikeToString.
  3176. * This contains static informations and functions that
  3177. * can be optimized by the browser JIT compiler.
  3178. */
  3179. var arrayToStringHelper = {
  3180. /**
  3181. * Transform an array of int into a string, chunk by chunk.
  3182. * See the performances notes on arrayLikeToString.
  3183. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3184. * @param {String} type the type of the array.
  3185. * @param {Integer} chunk the chunk size.
  3186. * @return {String} the resulting string.
  3187. * @throws Error if the chunk is too big for the stack.
  3188. */
  3189. stringifyByChunk: function(array, type, chunk) {
  3190. var result = [], k = 0, len = array.length;
  3191. // shortcut
  3192. if (len <= chunk) {
  3193. return String.fromCharCode.apply(null, array);
  3194. }
  3195. while (k < len) {
  3196. if (type === "array" || type === "nodebuffer") {
  3197. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  3198. }
  3199. else {
  3200. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  3201. }
  3202. k += chunk;
  3203. }
  3204. return result.join("");
  3205. },
  3206. /**
  3207. * Call String.fromCharCode on every item in the array.
  3208. * This is the naive implementation, which generate A LOT of intermediate string.
  3209. * This should be used when everything else fail.
  3210. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3211. * @return {String} the result.
  3212. */
  3213. stringifyByChar: function(array){
  3214. var resultStr = "";
  3215. for(var i = 0; i < array.length; i++) {
  3216. resultStr += String.fromCharCode(array[i]);
  3217. }
  3218. return resultStr;
  3219. },
  3220. applyCanBeUsed : {
  3221. /**
  3222. * true if the browser accepts to use String.fromCharCode on Uint8Array
  3223. */
  3224. uint8array : (function () {
  3225. try {
  3226. return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
  3227. } catch (e) {
  3228. return false;
  3229. }
  3230. })(),
  3231. /**
  3232. * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
  3233. */
  3234. nodebuffer : (function () {
  3235. try {
  3236. return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.newBuffer(1)).length === 1;
  3237. } catch (e) {
  3238. return false;
  3239. }
  3240. })()
  3241. }
  3242. };
  3243.  
  3244. /**
  3245. * Transform an array-like object to a string.
  3246. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3247. * @return {String} the result.
  3248. */
  3249. function arrayLikeToString(array) {
  3250. // Performances notes :
  3251. // --------------------
  3252. // String.fromCharCode.apply(null, array) is the fastest, see
  3253. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  3254. // but the stack is limited (and we can get huge arrays !).
  3255. //
  3256. // result += String.fromCharCode(array[i]); generate too many strings !
  3257. //
  3258. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  3259. // TODO : we now have workers that split the work. Do we still need that ?
  3260. var chunk = 65536,
  3261. type = exports.getTypeOf(array),
  3262. canUseApply = true;
  3263. if (type === "uint8array") {
  3264. canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
  3265. } else if (type === "nodebuffer") {
  3266. canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
  3267. }
  3268.  
  3269. if (canUseApply) {
  3270. while (chunk > 1) {
  3271. try {
  3272. return arrayToStringHelper.stringifyByChunk(array, type, chunk);
  3273. } catch (e) {
  3274. chunk = Math.floor(chunk / 2);
  3275. }
  3276. }
  3277. }
  3278.  
  3279. // no apply or chunk error : slow and painful algorithm
  3280. // default browser on android 4.*
  3281. return arrayToStringHelper.stringifyByChar(array);
  3282. }
  3283.  
  3284. exports.applyFromCharCode = arrayLikeToString;
  3285.  
  3286.  
  3287. /**
  3288. * Copy the data from an array-like to an other array-like.
  3289. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  3290. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  3291. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  3292. */
  3293. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  3294. for (var i = 0; i < arrayFrom.length; i++) {
  3295. arrayTo[i] = arrayFrom[i];
  3296. }
  3297. return arrayTo;
  3298. }
  3299.  
  3300. // a matrix containing functions to transform everything into everything.
  3301. var transform = {};
  3302.  
  3303. // string to ?
  3304. transform["string"] = {
  3305. "string": identity,
  3306. "array": function(input) {
  3307. return stringToArrayLike(input, new Array(input.length));
  3308. },
  3309. "arraybuffer": function(input) {
  3310. return transform["string"]["uint8array"](input).buffer;
  3311. },
  3312. "uint8array": function(input) {
  3313. return stringToArrayLike(input, new Uint8Array(input.length));
  3314. },
  3315. "nodebuffer": function(input) {
  3316. return stringToArrayLike(input, nodejsUtils.newBuffer(input.length));
  3317. }
  3318. };
  3319.  
  3320. // array to ?
  3321. transform["array"] = {
  3322. "string": arrayLikeToString,
  3323. "array": identity,
  3324. "arraybuffer": function(input) {
  3325. return (new Uint8Array(input)).buffer;
  3326. },
  3327. "uint8array": function(input) {
  3328. return new Uint8Array(input);
  3329. },
  3330. "nodebuffer": function(input) {
  3331. return nodejsUtils.newBuffer(input);
  3332. }
  3333. };
  3334.  
  3335. // arraybuffer to ?
  3336. transform["arraybuffer"] = {
  3337. "string": function(input) {
  3338. return arrayLikeToString(new Uint8Array(input));
  3339. },
  3340. "array": function(input) {
  3341. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  3342. },
  3343. "arraybuffer": identity,
  3344. "uint8array": function(input) {
  3345. return new Uint8Array(input);
  3346. },
  3347. "nodebuffer": function(input) {
  3348. return nodejsUtils.newBuffer(new Uint8Array(input));
  3349. }
  3350. };
  3351.  
  3352. // uint8array to ?
  3353. transform["uint8array"] = {
  3354. "string": arrayLikeToString,
  3355. "array": function(input) {
  3356. return arrayLikeToArrayLike(input, new Array(input.length));
  3357. },
  3358. "arraybuffer": function(input) {
  3359. // copy the uint8array: DO NOT propagate the original ArrayBuffer, it
  3360. // can be way larger (the whole zip file for example).
  3361. var copy = new Uint8Array(input.length);
  3362. if (input.length) {
  3363. copy.set(input, 0);
  3364. }
  3365. return copy.buffer;
  3366. },
  3367. "uint8array": identity,
  3368. "nodebuffer": function(input) {
  3369. return nodejsUtils.newBuffer(input);
  3370. }
  3371. };
  3372.  
  3373. // nodebuffer to ?
  3374. transform["nodebuffer"] = {
  3375. "string": arrayLikeToString,
  3376. "array": function(input) {
  3377. return arrayLikeToArrayLike(input, new Array(input.length));
  3378. },
  3379. "arraybuffer": function(input) {
  3380. return transform["nodebuffer"]["uint8array"](input).buffer;
  3381. },
  3382. "uint8array": function(input) {
  3383. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  3384. },
  3385. "nodebuffer": identity
  3386. };
  3387.  
  3388. /**
  3389. * Transform an input into any type.
  3390. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  3391. * If no output type is specified, the unmodified input will be returned.
  3392. * @param {String} outputType the output type.
  3393. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  3394. * @throws {Error} an Error if the browser doesn't support the requested output type.
  3395. */
  3396. exports.transformTo = function(outputType, input) {
  3397. if (!input) {
  3398. // undefined, null, etc
  3399. // an empty string won't harm.
  3400. input = "";
  3401. }
  3402. if (!outputType) {
  3403. return input;
  3404. }
  3405. exports.checkSupport(outputType);
  3406. var inputType = exports.getTypeOf(input);
  3407. var result = transform[inputType][outputType](input);
  3408. return result;
  3409. };
  3410.  
  3411. /**
  3412. * Return the type of the input.
  3413. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  3414. * @param {Object} input the input to identify.
  3415. * @return {String} the (lowercase) type of the input.
  3416. */
  3417. exports.getTypeOf = function(input) {
  3418. if (typeof input === "string") {
  3419. return "string";
  3420. }
  3421. if (Object.prototype.toString.call(input) === "[object Array]") {
  3422. return "array";
  3423. }
  3424. if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
  3425. return "nodebuffer";
  3426. }
  3427. if (support.uint8array && input instanceof Uint8Array) {
  3428. return "uint8array";
  3429. }
  3430. if (support.arraybuffer && input instanceof ArrayBuffer) {
  3431. return "arraybuffer";
  3432. }
  3433. };
  3434.  
  3435. /**
  3436. * Throw an exception if the type is not supported.
  3437. * @param {String} type the type to check.
  3438. * @throws {Error} an Error if the browser doesn't support the requested type.
  3439. */
  3440. exports.checkSupport = function(type) {
  3441. var supported = support[type.toLowerCase()];
  3442. if (!supported) {
  3443. throw new Error(type + " is not supported by this platform");
  3444. }
  3445. };
  3446.  
  3447. exports.MAX_VALUE_16BITS = 65535;
  3448. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  3449.  
  3450. /**
  3451. * Prettify a string read as binary.
  3452. * @param {string} str the string to prettify.
  3453. * @return {string} a pretty string.
  3454. */
  3455. exports.pretty = function(str) {
  3456. var res = '',
  3457. code, i;
  3458. for (i = 0; i < (str || "").length; i++) {
  3459. code = str.charCodeAt(i);
  3460. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  3461. }
  3462. return res;
  3463. };
  3464.  
  3465. /**
  3466. * Defer the call of a function.
  3467. * @param {Function} callback the function to call asynchronously.
  3468. * @param {Array} args the arguments to give to the callback.
  3469. */
  3470. exports.delay = function(callback, args, self) {
  3471. setImmediate(function () {
  3472. callback.apply(self || null, args || []);
  3473. });
  3474. };
  3475.  
  3476. /**
  3477. * Extends a prototype with an other, without calling a constructor with
  3478. * side effects. Inspired by nodejs' `utils.inherits`
  3479. * @param {Function} ctor the constructor to augment
  3480. * @param {Function} superCtor the parent constructor to use
  3481. */
  3482. exports.inherits = function (ctor, superCtor) {
  3483. var Obj = function() {};
  3484. Obj.prototype = superCtor.prototype;
  3485. ctor.prototype = new Obj();
  3486. };
  3487.  
  3488. /**
  3489. * Merge the objects passed as parameters into a new one.
  3490. * @private
  3491. * @param {...Object} var_args All objects to merge.
  3492. * @return {Object} a new object with the data of the others.
  3493. */
  3494. exports.extend = function() {
  3495. var result = {}, i, attr;
  3496. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  3497. for (attr in arguments[i]) {
  3498. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  3499. result[attr] = arguments[i][attr];
  3500. }
  3501. }
  3502. }
  3503. return result;
  3504. };
  3505.  
  3506. /**
  3507. * Transform arbitrary content into a Promise.
  3508. * @param {String} name a name for the content being processed.
  3509. * @param {Object} inputData the content to process.
  3510. * @param {Boolean} isBinary true if the content is not an unicode string
  3511. * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
  3512. * @param {Boolean} isBase64 true if the string content is encoded with base64.
  3513. * @return {Promise} a promise in a format usable by JSZip.
  3514. */
  3515. exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
  3516.  
  3517. // if inputData is already a promise, this flatten it.
  3518. var promise = external.Promise.resolve(inputData).then(function(data) {
  3519. var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);
  3520.  
  3521. if (isBlob && typeof FileReader !== "undefined") {
  3522. return new external.Promise(function (resolve, reject) {
  3523. var reader = new FileReader();
  3524.  
  3525. reader.onload = function(e) {
  3526. resolve(e.target.result);
  3527. };
  3528. reader.onerror = function(e) {
  3529. reject(e.target.error);
  3530. };
  3531. reader.readAsArrayBuffer(data);
  3532. });
  3533. } else {
  3534. return data;
  3535. }
  3536. });
  3537.  
  3538. return promise.then(function(data) {
  3539. var dataType = exports.getTypeOf(data);
  3540.  
  3541. if (!dataType) {
  3542. return external.Promise.reject(
  3543. new Error("The data of '" + name + "' is in an unsupported format !")
  3544. );
  3545. }
  3546. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  3547. if (dataType === "arraybuffer") {
  3548. data = exports.transformTo("uint8array", data);
  3549. } else if (dataType === "string") {
  3550. if (isBase64) {
  3551. data = base64.decode(data);
  3552. }
  3553. else if (isBinary) {
  3554. // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
  3555. if (isOptimizedBinaryString !== true) {
  3556. // this is a string, not in a base64 format.
  3557. // Be sure that this is a correct "binary string"
  3558. data = string2binary(data);
  3559. }
  3560. }
  3561. }
  3562. return data;
  3563. });
  3564. };
  3565.  
  3566. },{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"core-js/library/fn/set-immediate":36}],33:[function(require,module,exports){
  3567. 'use strict';
  3568. var readerFor = require('./reader/readerFor');
  3569. var utils = require('./utils');
  3570. var sig = require('./signature');
  3571. var ZipEntry = require('./zipEntry');
  3572. var utf8 = require('./utf8');
  3573. var support = require('./support');
  3574. // class ZipEntries {{{
  3575. /**
  3576. * All the entries in the zip file.
  3577. * @constructor
  3578. * @param {Object} loadOptions Options for loading the stream.
  3579. */
  3580. function ZipEntries(loadOptions) {
  3581. this.files = [];
  3582. this.loadOptions = loadOptions;
  3583. }
  3584. ZipEntries.prototype = {
  3585. /**
  3586. * Check that the reader is on the speficied signature.
  3587. * @param {string} expectedSignature the expected signature.
  3588. * @throws {Error} if it is an other signature.
  3589. */
  3590. checkSignature: function(expectedSignature) {
  3591. if (!this.reader.readAndCheckSignature(expectedSignature)) {
  3592. this.reader.index -= 4;
  3593. var signature = this.reader.readString(4);
  3594. throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  3595. }
  3596. },
  3597. /**
  3598. * Check if the given signature is at the given index.
  3599. * @param {number} askedIndex the index to check.
  3600. * @param {string} expectedSignature the signature to expect.
  3601. * @return {boolean} true if the signature is here, false otherwise.
  3602. */
  3603. isSignature: function(askedIndex, expectedSignature) {
  3604. var currentIndex = this.reader.index;
  3605. this.reader.setIndex(askedIndex);
  3606. var signature = this.reader.readString(4);
  3607. var result = signature === expectedSignature;
  3608. this.reader.setIndex(currentIndex);
  3609. return result;
  3610. },
  3611. /**
  3612. * Read the end of the central directory.
  3613. */
  3614. readBlockEndOfCentral: function() {
  3615. this.diskNumber = this.reader.readInt(2);
  3616. this.diskWithCentralDirStart = this.reader.readInt(2);
  3617. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  3618. this.centralDirRecords = this.reader.readInt(2);
  3619. this.centralDirSize = this.reader.readInt(4);
  3620. this.centralDirOffset = this.reader.readInt(4);
  3621.  
  3622. this.zipCommentLength = this.reader.readInt(2);
  3623. // warning : the encoding depends of the system locale
  3624. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  3625. // On a windows machine, this field is encoded with the localized windows code page.
  3626. var zipComment = this.reader.readData(this.zipCommentLength);
  3627. var decodeParamType = support.uint8array ? "uint8array" : "array";
  3628. // To get consistent behavior with the generation part, we will assume that
  3629. // this is utf8 encoded unless specified otherwise.
  3630. var decodeContent = utils.transformTo(decodeParamType, zipComment);
  3631. this.zipComment = this.loadOptions.decodeFileName(decodeContent);
  3632. },
  3633. /**
  3634. * Read the end of the Zip 64 central directory.
  3635. * Not merged with the method readEndOfCentral :
  3636. * The end of central can coexist with its Zip64 brother,
  3637. * I don't want to read the wrong number of bytes !
  3638. */
  3639. readBlockZip64EndOfCentral: function() {
  3640. this.zip64EndOfCentralSize = this.reader.readInt(8);
  3641. this.reader.skip(4);
  3642. // this.versionMadeBy = this.reader.readString(2);
  3643. // this.versionNeeded = this.reader.readInt(2);
  3644. this.diskNumber = this.reader.readInt(4);
  3645. this.diskWithCentralDirStart = this.reader.readInt(4);
  3646. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  3647. this.centralDirRecords = this.reader.readInt(8);
  3648. this.centralDirSize = this.reader.readInt(8);
  3649. this.centralDirOffset = this.reader.readInt(8);
  3650.  
  3651. this.zip64ExtensibleData = {};
  3652. var extraDataSize = this.zip64EndOfCentralSize - 44,
  3653. index = 0,
  3654. extraFieldId,
  3655. extraFieldLength,
  3656. extraFieldValue;
  3657. while (index < extraDataSize) {
  3658. extraFieldId = this.reader.readInt(2);
  3659. extraFieldLength = this.reader.readInt(4);
  3660. extraFieldValue = this.reader.readData(extraFieldLength);
  3661. this.zip64ExtensibleData[extraFieldId] = {
  3662. id: extraFieldId,
  3663. length: extraFieldLength,
  3664. value: extraFieldValue
  3665. };
  3666. }
  3667. },
  3668. /**
  3669. * Read the end of the Zip 64 central directory locator.
  3670. */
  3671. readBlockZip64EndOfCentralLocator: function() {
  3672. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  3673. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  3674. this.disksCount = this.reader.readInt(4);
  3675. if (this.disksCount > 1) {
  3676. throw new Error("Multi-volumes zip are not supported");
  3677. }
  3678. },
  3679. /**
  3680. * Read the local files, based on the offset read in the central part.
  3681. */
  3682. readLocalFiles: function() {
  3683. var i, file;
  3684. for (i = 0; i < this.files.length; i++) {
  3685. file = this.files[i];
  3686. this.reader.setIndex(file.localHeaderOffset);
  3687. this.checkSignature(sig.LOCAL_FILE_HEADER);
  3688. file.readLocalPart(this.reader);
  3689. file.handleUTF8();
  3690. file.processAttributes();
  3691. }
  3692. },
  3693. /**
  3694. * Read the central directory.
  3695. */
  3696. readCentralDir: function() {
  3697. var file;
  3698.  
  3699. this.reader.setIndex(this.centralDirOffset);
  3700. while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
  3701. file = new ZipEntry({
  3702. zip64: this.zip64
  3703. }, this.loadOptions);
  3704. file.readCentralPart(this.reader);
  3705. this.files.push(file);
  3706. }
  3707.  
  3708. if (this.centralDirRecords !== this.files.length) {
  3709. if (this.centralDirRecords !== 0 && this.files.length === 0) {
  3710. // We expected some records but couldn't find ANY.
  3711. // This is really suspicious, as if something went wrong.
  3712. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  3713. } else {
  3714. // We found some records but not all.
  3715. // Something is wrong but we got something for the user: no error here.
  3716. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
  3717. }
  3718. }
  3719. },
  3720. /**
  3721. * Read the end of central directory.
  3722. */
  3723. readEndOfCentral: function() {
  3724. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  3725. if (offset < 0) {
  3726. // Check if the content is a truncated zip or complete garbage.
  3727. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  3728. // extractible zip for example) but it can give a good hint.
  3729. // If an ajax request was used without responseType, we will also
  3730. // get unreadable data.
  3731. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  3732.  
  3733. if (isGarbage) {
  3734. throw new Error("Can't find end of central directory : is this a zip file ? " +
  3735. "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
  3736. } else {
  3737. throw new Error("Corrupted zip : can't find end of central directory");
  3738. }
  3739.  
  3740. }
  3741. this.reader.setIndex(offset);
  3742. var endOfCentralDirOffset = offset;
  3743. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  3744. this.readBlockEndOfCentral();
  3745.  
  3746.  
  3747. /* extract from the zip spec :
  3748. 4) If one of the fields in the end of central directory
  3749. record is too small to hold required data, the field
  3750. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  3751. ZIP64 format record should be created.
  3752. 5) The end of central directory record and the
  3753. Zip64 end of central directory locator record must
  3754. reside on the same disk when splitting or spanning
  3755. an archive.
  3756. */
  3757. 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) {
  3758. this.zip64 = true;
  3759.  
  3760. /*
  3761. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  3762. the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
  3763. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  3764. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  3765. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  3766. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  3767. */
  3768.  
  3769. // should look for a zip64 EOCD locator
  3770. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3771. if (offset < 0) {
  3772. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
  3773. }
  3774. this.reader.setIndex(offset);
  3775. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3776. this.readBlockZip64EndOfCentralLocator();
  3777.  
  3778. // now the zip64 EOCD record
  3779. if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
  3780. // console.warn("ZIP64 end of central directory not where expected.");
  3781. this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3782. if (this.relativeOffsetEndOfZip64CentralDir < 0) {
  3783. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory");
  3784. }
  3785. }
  3786. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  3787. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3788. this.readBlockZip64EndOfCentral();
  3789. }
  3790.  
  3791. var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
  3792. if (this.zip64) {
  3793. expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
  3794. expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
  3795. }
  3796.  
  3797. var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  3798.  
  3799. if (extraBytes > 0) {
  3800. // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
  3801. if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
  3802. // The offsets seem wrong, but we have something at the specified offset.
  3803. // So… we keep it.
  3804. } else {
  3805. // the offset is wrong, update the "zero" of the reader
  3806. // this happens if data has been prepended (crx files for example)
  3807. this.reader.zero = extraBytes;
  3808. }
  3809. } else if (extraBytes < 0) {
  3810. throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
  3811. }
  3812. },
  3813. prepareReader: function(data) {
  3814. this.reader = readerFor(data);
  3815. },
  3816. /**
  3817. * Read a zip file and create ZipEntries.
  3818. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  3819. */
  3820. load: function(data) {
  3821. this.prepareReader(data);
  3822. this.readEndOfCentral();
  3823. this.readCentralDir();
  3824. this.readLocalFiles();
  3825. }
  3826. };
  3827. // }}} end of ZipEntries
  3828. module.exports = ZipEntries;
  3829.  
  3830. },{"./reader/readerFor":22,"./signature":23,"./support":30,"./utf8":31,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){
  3831. 'use strict';
  3832. var readerFor = require('./reader/readerFor');
  3833. var utils = require('./utils');
  3834. var CompressedObject = require('./compressedObject');
  3835. var crc32fn = require('./crc32');
  3836. var utf8 = require('./utf8');
  3837. var compressions = require('./compressions');
  3838. var support = require('./support');
  3839.  
  3840. var MADE_BY_DOS = 0x00;
  3841. var MADE_BY_UNIX = 0x03;
  3842.  
  3843. /**
  3844. * Find a compression registered in JSZip.
  3845. * @param {string} compressionMethod the method magic to find.
  3846. * @return {Object|null} the JSZip compression object, null if none found.
  3847. */
  3848. var findCompression = function(compressionMethod) {
  3849. for (var method in compressions) {
  3850. if (!compressions.hasOwnProperty(method)) {
  3851. continue;
  3852. }
  3853. if (compressions[method].magic === compressionMethod) {
  3854. return compressions[method];
  3855. }
  3856. }
  3857. return null;
  3858. };
  3859.  
  3860. // class ZipEntry {{{
  3861. /**
  3862. * An entry in the zip file.
  3863. * @constructor
  3864. * @param {Object} options Options of the current file.
  3865. * @param {Object} loadOptions Options for loading the stream.
  3866. */
  3867. function ZipEntry(options, loadOptions) {
  3868. this.options = options;
  3869. this.loadOptions = loadOptions;
  3870. }
  3871. ZipEntry.prototype = {
  3872. /**
  3873. * say if the file is encrypted.
  3874. * @return {boolean} true if the file is encrypted, false otherwise.
  3875. */
  3876. isEncrypted: function() {
  3877. // bit 1 is set
  3878. return (this.bitFlag & 0x0001) === 0x0001;
  3879. },
  3880. /**
  3881. * say if the file has utf-8 filename/comment.
  3882. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  3883. */
  3884. useUTF8: function() {
  3885. // bit 11 is set
  3886. return (this.bitFlag & 0x0800) === 0x0800;
  3887. },
  3888. /**
  3889. * Read the local part of a zip file and add the info in this object.
  3890. * @param {DataReader} reader the reader to use.
  3891. */
  3892. readLocalPart: function(reader) {
  3893. var compression, localExtraFieldsLength;
  3894.  
  3895. // we already know everything from the central dir !
  3896. // If the central dir data are false, we are doomed.
  3897. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  3898. // The less data we get here, the more reliable this should be.
  3899. // Let's skip the whole header and dash to the data !
  3900. reader.skip(22);
  3901. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  3902. // Strangely, the filename here is OK.
  3903. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  3904. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  3905. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  3906. // the internet.
  3907. //
  3908. // I think I see the logic here : the central directory is used to display
  3909. // content and the local directory is used to extract the files. Mixing / and \
  3910. // may be used to display \ to windows users and use / when extracting the files.
  3911. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  3912. this.fileNameLength = reader.readInt(2);
  3913. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  3914. // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
  3915. this.fileName = reader.readData(this.fileNameLength);
  3916. reader.skip(localExtraFieldsLength);
  3917.  
  3918. if (this.compressedSize === -1 || this.uncompressedSize === -1) {
  3919. throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
  3920. }
  3921.  
  3922. compression = findCompression(this.compressionMethod);
  3923. if (compression === null) { // no compression found
  3924. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
  3925. }
  3926. this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
  3927. },
  3928.  
  3929. /**
  3930. * Read the central part of a zip file and add the info in this object.
  3931. * @param {DataReader} reader the reader to use.
  3932. */
  3933. readCentralPart: function(reader) {
  3934. this.versionMadeBy = reader.readInt(2);
  3935. reader.skip(2);
  3936. // this.versionNeeded = reader.readInt(2);
  3937. this.bitFlag = reader.readInt(2);
  3938. this.compressionMethod = reader.readString(2);
  3939. this.date = reader.readDate();
  3940. this.crc32 = reader.readInt(4);
  3941. this.compressedSize = reader.readInt(4);
  3942. this.uncompressedSize = reader.readInt(4);
  3943. var fileNameLength = reader.readInt(2);
  3944. this.extraFieldsLength = reader.readInt(2);
  3945. this.fileCommentLength = reader.readInt(2);
  3946. this.diskNumberStart = reader.readInt(2);
  3947. this.internalFileAttributes = reader.readInt(2);
  3948. this.externalFileAttributes = reader.readInt(4);
  3949. this.localHeaderOffset = reader.readInt(4);
  3950.  
  3951. if (this.isEncrypted()) {
  3952. throw new Error("Encrypted zip are not supported");
  3953. }
  3954.  
  3955. // will be read in the local part, see the comments there
  3956. reader.skip(fileNameLength);
  3957. this.readExtraFields(reader);
  3958. this.parseZIP64ExtraField(reader);
  3959. this.fileComment = reader.readData(this.fileCommentLength);
  3960. },
  3961.  
  3962. /**
  3963. * Parse the external file attributes and get the unix/dos permissions.
  3964. */
  3965. processAttributes: function () {
  3966. this.unixPermissions = null;
  3967. this.dosPermissions = null;
  3968. var madeBy = this.versionMadeBy >> 8;
  3969.  
  3970. // Check if we have the DOS directory flag set.
  3971. // We look for it in the DOS and UNIX permissions
  3972. // but some unknown platform could set it as a compatibility flag.
  3973. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  3974.  
  3975. if(madeBy === MADE_BY_DOS) {
  3976. // first 6 bits (0 to 5)
  3977. this.dosPermissions = this.externalFileAttributes & 0x3F;
  3978. }
  3979.  
  3980. if(madeBy === MADE_BY_UNIX) {
  3981. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  3982. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  3983. }
  3984.  
  3985. // fail safe : if the name ends with a / it probably means a folder
  3986. if (!this.dir && this.fileNameStr.slice(-1) === '/') {
  3987. this.dir = true;
  3988. }
  3989. },
  3990.  
  3991. /**
  3992. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  3993. * @param {DataReader} reader the reader to use.
  3994. */
  3995. parseZIP64ExtraField: function(reader) {
  3996.  
  3997. if (!this.extraFields[0x0001]) {
  3998. return;
  3999. }
  4000.  
  4001. // should be something, preparing the extra reader
  4002. var extraReader = readerFor(this.extraFields[0x0001].value);
  4003.  
  4004. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  4005. // won't let us have more.
  4006. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  4007. this.uncompressedSize = extraReader.readInt(8);
  4008. }
  4009. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  4010. this.compressedSize = extraReader.readInt(8);
  4011. }
  4012. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  4013. this.localHeaderOffset = extraReader.readInt(8);
  4014. }
  4015. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  4016. this.diskNumberStart = extraReader.readInt(4);
  4017. }
  4018. },
  4019. /**
  4020. * Read the central part of a zip file and add the info in this object.
  4021. * @param {DataReader} reader the reader to use.
  4022. */
  4023. readExtraFields: function(reader) {
  4024. var end = reader.index + this.extraFieldsLength,
  4025. extraFieldId,
  4026. extraFieldLength,
  4027. extraFieldValue;
  4028.  
  4029. if (!this.extraFields) {
  4030. this.extraFields = {};
  4031. }
  4032.  
  4033. while (reader.index < end) {
  4034. extraFieldId = reader.readInt(2);
  4035. extraFieldLength = reader.readInt(2);
  4036. extraFieldValue = reader.readData(extraFieldLength);
  4037.  
  4038. this.extraFields[extraFieldId] = {
  4039. id: extraFieldId,
  4040. length: extraFieldLength,
  4041. value: extraFieldValue
  4042. };
  4043. }
  4044. },
  4045. /**
  4046. * Apply an UTF8 transformation if needed.
  4047. */
  4048. handleUTF8: function() {
  4049. var decodeParamType = support.uint8array ? "uint8array" : "array";
  4050. if (this.useUTF8()) {
  4051. this.fileNameStr = utf8.utf8decode(this.fileName);
  4052. this.fileCommentStr = utf8.utf8decode(this.fileComment);
  4053. } else {
  4054. var upath = this.findExtraFieldUnicodePath();
  4055. if (upath !== null) {
  4056. this.fileNameStr = upath;
  4057. } else {
  4058. // ASCII text or unsupported code page
  4059. var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);
  4060. this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
  4061. }
  4062.  
  4063. var ucomment = this.findExtraFieldUnicodeComment();
  4064. if (ucomment !== null) {
  4065. this.fileCommentStr = ucomment;
  4066. } else {
  4067. // ASCII text or unsupported code page
  4068. var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);
  4069. this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
  4070. }
  4071. }
  4072. },
  4073.  
  4074. /**
  4075. * Find the unicode path declared in the extra field, if any.
  4076. * @return {String} the unicode path, null otherwise.
  4077. */
  4078. findExtraFieldUnicodePath: function() {
  4079. var upathField = this.extraFields[0x7075];
  4080. if (upathField) {
  4081. var extraReader = readerFor(upathField.value);
  4082.  
  4083. // wrong version
  4084. if (extraReader.readInt(1) !== 1) {
  4085. return null;
  4086. }
  4087.  
  4088. // the crc of the filename changed, this field is out of date.
  4089. if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
  4090. return null;
  4091. }
  4092.  
  4093. return utf8.utf8decode(extraReader.readData(upathField.length - 5));
  4094. }
  4095. return null;
  4096. },
  4097.  
  4098. /**
  4099. * Find the unicode comment declared in the extra field, if any.
  4100. * @return {String} the unicode comment, null otherwise.
  4101. */
  4102. findExtraFieldUnicodeComment: function() {
  4103. var ucommentField = this.extraFields[0x6375];
  4104. if (ucommentField) {
  4105. var extraReader = readerFor(ucommentField.value);
  4106.  
  4107. // wrong version
  4108. if (extraReader.readInt(1) !== 1) {
  4109. return null;
  4110. }
  4111.  
  4112. // the crc of the comment changed, this field is out of date.
  4113. if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
  4114. return null;
  4115. }
  4116.  
  4117. return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
  4118. }
  4119. return null;
  4120. }
  4121. };
  4122. module.exports = ZipEntry;
  4123.  
  4124. },{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){
  4125. 'use strict';
  4126.  
  4127. var StreamHelper = require('./stream/StreamHelper');
  4128. var DataWorker = require('./stream/DataWorker');
  4129. var utf8 = require('./utf8');
  4130. var CompressedObject = require('./compressedObject');
  4131. var GenericWorker = require('./stream/GenericWorker');
  4132.  
  4133. /**
  4134. * A simple object representing a file in the zip file.
  4135. * @constructor
  4136. * @param {string} name the name of the file
  4137. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  4138. * @param {Object} options the options of the file
  4139. */
  4140. var ZipObject = function(name, data, options) {
  4141. this.name = name;
  4142. this.dir = options.dir;
  4143. this.date = options.date;
  4144. this.comment = options.comment;
  4145. this.unixPermissions = options.unixPermissions;
  4146. this.dosPermissions = options.dosPermissions;
  4147.  
  4148. this._data = data;
  4149. this._dataBinary = options.binary;
  4150. // keep only the compression
  4151. this.options = {
  4152. compression : options.compression,
  4153. compressionOptions : options.compressionOptions
  4154. };
  4155. };
  4156.  
  4157. ZipObject.prototype = {
  4158. /**
  4159. * Create an internal stream for the content of this object.
  4160. * @param {String} type the type of each chunk.
  4161. * @return StreamHelper the stream.
  4162. */
  4163. internalStream: function (type) {
  4164. var outputType = type.toLowerCase();
  4165. var askUnicodeString = outputType === "string" || outputType === "text";
  4166. if (outputType === "binarystring" || outputType === "text") {
  4167. outputType = "string";
  4168. }
  4169. var result = this._decompressWorker();
  4170.  
  4171. var isUnicodeString = !this._dataBinary;
  4172.  
  4173. if (isUnicodeString && !askUnicodeString) {
  4174. result = result.pipe(new utf8.Utf8EncodeWorker());
  4175. }
  4176. if (!isUnicodeString && askUnicodeString) {
  4177. result = result.pipe(new utf8.Utf8DecodeWorker());
  4178. }
  4179.  
  4180. return new StreamHelper(result, outputType, "");
  4181. },
  4182.  
  4183. /**
  4184. * Prepare the content in the asked type.
  4185. * @param {String} type the type of the result.
  4186. * @param {Function} onUpdate a function to call on each internal update.
  4187. * @return Promise the promise of the result.
  4188. */
  4189. async: function (type, onUpdate) {
  4190. return this.internalStream(type).accumulate(onUpdate);
  4191. },
  4192.  
  4193. /**
  4194. * Prepare the content as a nodejs stream.
  4195. * @param {String} type the type of each chunk.
  4196. * @param {Function} onUpdate a function to call on each internal update.
  4197. * @return Stream the stream.
  4198. */
  4199. nodeStream: function (type, onUpdate) {
  4200. return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
  4201. },
  4202.  
  4203. /**
  4204. * Return a worker for the compressed content.
  4205. * @private
  4206. * @param {Object} compression the compression object to use.
  4207. * @param {Object} compressionOptions the options to use when compressing.
  4208. * @return Worker the worker.
  4209. */
  4210. _compressWorker: function (compression, compressionOptions) {
  4211. if (
  4212. this._data instanceof CompressedObject &&
  4213. this._data.compression.magic === compression.magic
  4214. ) {
  4215. return this._data.getCompressedWorker();
  4216. } else {
  4217. var result = this._decompressWorker();
  4218. if(!this._dataBinary) {
  4219. result = result.pipe(new utf8.Utf8EncodeWorker());
  4220. }
  4221. return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
  4222. }
  4223. },
  4224. /**
  4225. * Return a worker for the decompressed content.
  4226. * @private
  4227. * @return Worker the worker.
  4228. */
  4229. _decompressWorker : function () {
  4230. if (this._data instanceof CompressedObject) {
  4231. return this._data.getContentWorker();
  4232. } else if (this._data instanceof GenericWorker) {
  4233. return this._data;
  4234. } else {
  4235. return new DataWorker(this._data);
  4236. }
  4237. }
  4238. };
  4239.  
  4240. var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
  4241. var removedFn = function () {
  4242. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  4243. };
  4244.  
  4245. for(var i = 0; i < removedMethods.length; i++) {
  4246. ZipObject.prototype[removedMethods[i]] = removedFn;
  4247. }
  4248. module.exports = ZipObject;
  4249.  
  4250. },{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){
  4251. require('../modules/web.immediate');
  4252. module.exports = require('../modules/_core').setImmediate;
  4253. },{"../modules/_core":40,"../modules/web.immediate":56}],37:[function(require,module,exports){
  4254. module.exports = function(it){
  4255. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  4256. return it;
  4257. };
  4258. },{}],38:[function(require,module,exports){
  4259. var isObject = require('./_is-object');
  4260. module.exports = function(it){
  4261. if(!isObject(it))throw TypeError(it + ' is not an object!');
  4262. return it;
  4263. };
  4264. },{"./_is-object":51}],39:[function(require,module,exports){
  4265. var toString = {}.toString;
  4266.  
  4267. module.exports = function(it){
  4268. return toString.call(it).slice(8, -1);
  4269. };
  4270. },{}],40:[function(require,module,exports){
  4271. var core = module.exports = {version: '2.3.0'};
  4272. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  4273. },{}],41:[function(require,module,exports){
  4274. // optional / simple context binding
  4275. var aFunction = require('./_a-function');
  4276. module.exports = function(fn, that, length){
  4277. aFunction(fn);
  4278. if(that === undefined)return fn;
  4279. switch(length){
  4280. case 1: return function(a){
  4281. return fn.call(that, a);
  4282. };
  4283. case 2: return function(a, b){
  4284. return fn.call(that, a, b);
  4285. };
  4286. case 3: return function(a, b, c){
  4287. return fn.call(that, a, b, c);
  4288. };
  4289. }
  4290. return function(/* ...args */){
  4291. return fn.apply(that, arguments);
  4292. };
  4293. };
  4294. },{"./_a-function":37}],42:[function(require,module,exports){
  4295. // Thank's IE8 for his funny defineProperty
  4296. module.exports = !require('./_fails')(function(){
  4297. return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
  4298. });
  4299. },{"./_fails":45}],43:[function(require,module,exports){
  4300. var isObject = require('./_is-object')
  4301. , document = require('./_global').document
  4302. // in old IE typeof document.createElement is 'object'
  4303. , is = isObject(document) && isObject(document.createElement);
  4304. module.exports = function(it){
  4305. return is ? document.createElement(it) : {};
  4306. };
  4307. },{"./_global":46,"./_is-object":51}],44:[function(require,module,exports){
  4308. var global = require('./_global')
  4309. , core = require('./_core')
  4310. , ctx = require('./_ctx')
  4311. , hide = require('./_hide')
  4312. , PROTOTYPE = 'prototype';
  4313.  
  4314. var $export = function(type, name, source){
  4315. var IS_FORCED = type & $export.F
  4316. , IS_GLOBAL = type & $export.G
  4317. , IS_STATIC = type & $export.S
  4318. , IS_PROTO = type & $export.P
  4319. , IS_BIND = type & $export.B
  4320. , IS_WRAP = type & $export.W
  4321. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  4322. , expProto = exports[PROTOTYPE]
  4323. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  4324. , key, own, out;
  4325. if(IS_GLOBAL)source = name;
  4326. for(key in source){
  4327. // contains in native
  4328. own = !IS_FORCED && target && target[key] !== undefined;
  4329. if(own && key in exports)continue;
  4330. // export native or passed
  4331. out = own ? target[key] : source[key];
  4332. // prevent global pollution for namespaces
  4333. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  4334. // bind timers to global for call from export context
  4335. : IS_BIND && own ? ctx(out, global)
  4336. // wrap global constructors for prevent change them in library
  4337. : IS_WRAP && target[key] == out ? (function(C){
  4338. var F = function(a, b, c){
  4339. if(this instanceof C){
  4340. switch(arguments.length){
  4341. case 0: return new C;
  4342. case 1: return new C(a);
  4343. case 2: return new C(a, b);
  4344. } return new C(a, b, c);
  4345. } return C.apply(this, arguments);
  4346. };
  4347. F[PROTOTYPE] = C[PROTOTYPE];
  4348. return F;
  4349. // make static versions for prototype methods
  4350. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  4351. // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
  4352. if(IS_PROTO){
  4353. (exports.virtual || (exports.virtual = {}))[key] = out;
  4354. // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
  4355. if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
  4356. }
  4357. }
  4358. };
  4359. // type bitmap
  4360. $export.F = 1; // forced
  4361. $export.G = 2; // global
  4362. $export.S = 4; // static
  4363. $export.P = 8; // proto
  4364. $export.B = 16; // bind
  4365. $export.W = 32; // wrap
  4366. $export.U = 64; // safe
  4367. $export.R = 128; // real proto method for `library`
  4368. module.exports = $export;
  4369. },{"./_core":40,"./_ctx":41,"./_global":46,"./_hide":47}],45:[function(require,module,exports){
  4370. module.exports = function(exec){
  4371. try {
  4372. return !!exec();
  4373. } catch(e){
  4374. return true;
  4375. }
  4376. };
  4377. },{}],46:[function(require,module,exports){
  4378. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  4379. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  4380. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  4381. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  4382. },{}],47:[function(require,module,exports){
  4383. var dP = require('./_object-dp')
  4384. , createDesc = require('./_property-desc');
  4385. module.exports = require('./_descriptors') ? function(object, key, value){
  4386. return dP.f(object, key, createDesc(1, value));
  4387. } : function(object, key, value){
  4388. object[key] = value;
  4389. return object;
  4390. };
  4391. },{"./_descriptors":42,"./_object-dp":52,"./_property-desc":53}],48:[function(require,module,exports){
  4392. module.exports = require('./_global').document && document.documentElement;
  4393. },{"./_global":46}],49:[function(require,module,exports){
  4394. module.exports = !require('./_descriptors') && !require('./_fails')(function(){
  4395. return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7;
  4396. });
  4397. },{"./_descriptors":42,"./_dom-create":43,"./_fails":45}],50:[function(require,module,exports){
  4398. // fast apply, http://jsperf.lnkit.com/fast-apply/5
  4399. module.exports = function(fn, args, that){
  4400. var un = that === undefined;
  4401. switch(args.length){
  4402. case 0: return un ? fn()
  4403. : fn.call(that);
  4404. case 1: return un ? fn(args[0])
  4405. : fn.call(that, args[0]);
  4406. case 2: return un ? fn(args[0], args[1])
  4407. : fn.call(that, args[0], args[1]);
  4408. case 3: return un ? fn(args[0], args[1], args[2])
  4409. : fn.call(that, args[0], args[1], args[2]);
  4410. case 4: return un ? fn(args[0], args[1], args[2], args[3])
  4411. : fn.call(that, args[0], args[1], args[2], args[3]);
  4412. } return fn.apply(that, args);
  4413. };
  4414. },{}],51:[function(require,module,exports){
  4415. module.exports = function(it){
  4416. return typeof it === 'object' ? it !== null : typeof it === 'function';
  4417. };
  4418. },{}],52:[function(require,module,exports){
  4419. var anObject = require('./_an-object')
  4420. , IE8_DOM_DEFINE = require('./_ie8-dom-define')
  4421. , toPrimitive = require('./_to-primitive')
  4422. , dP = Object.defineProperty;
  4423.  
  4424. exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){
  4425. anObject(O);
  4426. P = toPrimitive(P, true);
  4427. anObject(Attributes);
  4428. if(IE8_DOM_DEFINE)try {
  4429. return dP(O, P, Attributes);
  4430. } catch(e){ /* empty */ }
  4431. if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
  4432. if('value' in Attributes)O[P] = Attributes.value;
  4433. return O;
  4434. };
  4435. },{"./_an-object":38,"./_descriptors":42,"./_ie8-dom-define":49,"./_to-primitive":55}],53:[function(require,module,exports){
  4436. module.exports = function(bitmap, value){
  4437. return {
  4438. enumerable : !(bitmap & 1),
  4439. configurable: !(bitmap & 2),
  4440. writable : !(bitmap & 4),
  4441. value : value
  4442. };
  4443. };
  4444. },{}],54:[function(require,module,exports){
  4445. var ctx = require('./_ctx')
  4446. , invoke = require('./_invoke')
  4447. , html = require('./_html')
  4448. , cel = require('./_dom-create')
  4449. , global = require('./_global')
  4450. , process = global.process
  4451. , setTask = global.setImmediate
  4452. , clearTask = global.clearImmediate
  4453. , MessageChannel = global.MessageChannel
  4454. , counter = 0
  4455. , queue = {}
  4456. , ONREADYSTATECHANGE = 'onreadystatechange'
  4457. , defer, channel, port;
  4458. var run = function(){
  4459. var id = +this;
  4460. if(queue.hasOwnProperty(id)){
  4461. var fn = queue[id];
  4462. delete queue[id];
  4463. fn();
  4464. }
  4465. };
  4466. var listener = function(event){
  4467. run.call(event.data);
  4468. };
  4469. // Node.js 0.9+ & IE10+ has setImmediate, otherwise:
  4470. if(!setTask || !clearTask){
  4471. setTask = function setImmediate(fn){
  4472. var args = [], i = 1;
  4473. while(arguments.length > i)args.push(arguments[i++]);
  4474. queue[++counter] = function(){
  4475. invoke(typeof fn == 'function' ? fn : Function(fn), args);
  4476. };
  4477. defer(counter);
  4478. return counter;
  4479. };
  4480. clearTask = function clearImmediate(id){
  4481. delete queue[id];
  4482. };
  4483. // Node.js 0.8-
  4484. if(require('./_cof')(process) == 'process'){
  4485. defer = function(id){
  4486. process.nextTick(ctx(run, id, 1));
  4487. };
  4488. // Browsers with MessageChannel, includes WebWorkers
  4489. } else if(MessageChannel){
  4490. channel = new MessageChannel;
  4491. port = channel.port2;
  4492. channel.port1.onmessage = listener;
  4493. defer = ctx(port.postMessage, port, 1);
  4494. // Browsers with postMessage, skip WebWorkers
  4495. // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
  4496. } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
  4497. defer = function(id){
  4498. global.postMessage(id + '', '*');
  4499. };
  4500. global.addEventListener('message', listener, false);
  4501. // IE8-
  4502. } else if(ONREADYSTATECHANGE in cel('script')){
  4503. defer = function(id){
  4504. html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
  4505. html.removeChild(this);
  4506. run.call(id);
  4507. };
  4508. };
  4509. // Rest old browsers
  4510. } else {
  4511. defer = function(id){
  4512. setTimeout(ctx(run, id, 1), 0);
  4513. };
  4514. }
  4515. }
  4516. module.exports = {
  4517. set: setTask,
  4518. clear: clearTask
  4519. };
  4520. },{"./_cof":39,"./_ctx":41,"./_dom-create":43,"./_global":46,"./_html":48,"./_invoke":50}],55:[function(require,module,exports){
  4521. // 7.1.1 ToPrimitive(input [, PreferredType])
  4522. var isObject = require('./_is-object');
  4523. // instead of the ES6 spec version, we didn't implement @@toPrimitive case
  4524. // and the second argument - flag - preferred type is a string
  4525. module.exports = function(it, S){
  4526. if(!isObject(it))return it;
  4527. var fn, val;
  4528. if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
  4529. if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
  4530. if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
  4531. throw TypeError("Can't convert object to primitive value");
  4532. };
  4533. },{"./_is-object":51}],56:[function(require,module,exports){
  4534. var $export = require('./_export')
  4535. , $task = require('./_task');
  4536. $export($export.G + $export.B, {
  4537. setImmediate: $task.set,
  4538. clearImmediate: $task.clear
  4539. });
  4540. },{"./_export":44,"./_task":54}],57:[function(require,module,exports){
  4541. (function (global){
  4542. 'use strict';
  4543. var Mutation = global.MutationObserver || global.WebKitMutationObserver;
  4544.  
  4545. var scheduleDrain;
  4546.  
  4547. {
  4548. if (Mutation) {
  4549. var called = 0;
  4550. var observer = new Mutation(nextTick);
  4551. var element = global.document.createTextNode('');
  4552. observer.observe(element, {
  4553. characterData: true
  4554. });
  4555. scheduleDrain = function () {
  4556. element.data = (called = ++called % 2);
  4557. };
  4558. } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
  4559. var channel = new global.MessageChannel();
  4560. channel.port1.onmessage = nextTick;
  4561. scheduleDrain = function () {
  4562. channel.port2.postMessage(0);
  4563. };
  4564. } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
  4565. scheduleDrain = function () {
  4566.  
  4567. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  4568. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  4569. var scriptEl = global.document.createElement('script');
  4570. scriptEl.onreadystatechange = function () {
  4571. nextTick();
  4572.  
  4573. scriptEl.onreadystatechange = null;
  4574. scriptEl.parentNode.removeChild(scriptEl);
  4575. scriptEl = null;
  4576. };
  4577. global.document.documentElement.appendChild(scriptEl);
  4578. };
  4579. } else {
  4580. scheduleDrain = function () {
  4581. setTimeout(nextTick, 0);
  4582. };
  4583. }
  4584. }
  4585.  
  4586. var draining;
  4587. var queue = [];
  4588. //named nextTick for less confusing stack traces
  4589. function nextTick() {
  4590. draining = true;
  4591. var i, oldQueue;
  4592. var len = queue.length;
  4593. while (len) {
  4594. oldQueue = queue;
  4595. queue = [];
  4596. i = -1;
  4597. while (++i < len) {
  4598. oldQueue[i]();
  4599. }
  4600. len = queue.length;
  4601. }
  4602. draining = false;
  4603. }
  4604.  
  4605. module.exports = immediate;
  4606. function immediate(task) {
  4607. if (queue.push(task) === 1 && !draining) {
  4608. scheduleDrain();
  4609. }
  4610. }
  4611.  
  4612. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4613. },{}],58:[function(require,module,exports){
  4614. 'use strict';
  4615. var immediate = require('immediate');
  4616.  
  4617. /* istanbul ignore next */
  4618. function INTERNAL() {}
  4619.  
  4620. var handlers = {};
  4621.  
  4622. var REJECTED = ['REJECTED'];
  4623. var FULFILLED = ['FULFILLED'];
  4624. var PENDING = ['PENDING'];
  4625.  
  4626. module.exports = Promise;
  4627.  
  4628. function Promise(resolver) {
  4629. if (typeof resolver !== 'function') {
  4630. throw new TypeError('resolver must be a function');
  4631. }
  4632. this.state = PENDING;
  4633. this.queue = [];
  4634. this.outcome = void 0;
  4635. if (resolver !== INTERNAL) {
  4636. safelyResolveThenable(this, resolver);
  4637. }
  4638. }
  4639.  
  4640. Promise.prototype["catch"] = function (onRejected) {
  4641. return this.then(null, onRejected);
  4642. };
  4643. Promise.prototype.then = function (onFulfilled, onRejected) {
  4644. if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
  4645. typeof onRejected !== 'function' && this.state === REJECTED) {
  4646. return this;
  4647. }
  4648. var promise = new this.constructor(INTERNAL);
  4649. if (this.state !== PENDING) {
  4650. var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
  4651. unwrap(promise, resolver, this.outcome);
  4652. } else {
  4653. this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  4654. }
  4655.  
  4656. return promise;
  4657. };
  4658. function QueueItem(promise, onFulfilled, onRejected) {
  4659. this.promise = promise;
  4660. if (typeof onFulfilled === 'function') {
  4661. this.onFulfilled = onFulfilled;
  4662. this.callFulfilled = this.otherCallFulfilled;
  4663. }
  4664. if (typeof onRejected === 'function') {
  4665. this.onRejected = onRejected;
  4666. this.callRejected = this.otherCallRejected;
  4667. }
  4668. }
  4669. QueueItem.prototype.callFulfilled = function (value) {
  4670. handlers.resolve(this.promise, value);
  4671. };
  4672. QueueItem.prototype.otherCallFulfilled = function (value) {
  4673. unwrap(this.promise, this.onFulfilled, value);
  4674. };
  4675. QueueItem.prototype.callRejected = function (value) {
  4676. handlers.reject(this.promise, value);
  4677. };
  4678. QueueItem.prototype.otherCallRejected = function (value) {
  4679. unwrap(this.promise, this.onRejected, value);
  4680. };
  4681.  
  4682. function unwrap(promise, func, value) {
  4683. immediate(function () {
  4684. var returnValue;
  4685. try {
  4686. returnValue = func(value);
  4687. } catch (e) {
  4688. return handlers.reject(promise, e);
  4689. }
  4690. if (returnValue === promise) {
  4691. handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
  4692. } else {
  4693. handlers.resolve(promise, returnValue);
  4694. }
  4695. });
  4696. }
  4697.  
  4698. handlers.resolve = function (self, value) {
  4699. var result = tryCatch(getThen, value);
  4700. if (result.status === 'error') {
  4701. return handlers.reject(self, result.value);
  4702. }
  4703. var thenable = result.value;
  4704.  
  4705. if (thenable) {
  4706. safelyResolveThenable(self, thenable);
  4707. } else {
  4708. self.state = FULFILLED;
  4709. self.outcome = value;
  4710. var i = -1;
  4711. var len = self.queue.length;
  4712. while (++i < len) {
  4713. self.queue[i].callFulfilled(value);
  4714. }
  4715. }
  4716. return self;
  4717. };
  4718. handlers.reject = function (self, error) {
  4719. self.state = REJECTED;
  4720. self.outcome = error;
  4721. var i = -1;
  4722. var len = self.queue.length;
  4723. while (++i < len) {
  4724. self.queue[i].callRejected(error);
  4725. }
  4726. return self;
  4727. };
  4728.  
  4729. function getThen(obj) {
  4730. // Make sure we only access the accessor once as required by the spec
  4731. var then = obj && obj.then;
  4732. if (obj && typeof obj === 'object' && typeof then === 'function') {
  4733. return function appyThen() {
  4734. then.apply(obj, arguments);
  4735. };
  4736. }
  4737. }
  4738.  
  4739. function safelyResolveThenable(self, thenable) {
  4740. // Either fulfill, reject or reject with error
  4741. var called = false;
  4742. function onError(value) {
  4743. if (called) {
  4744. return;
  4745. }
  4746. called = true;
  4747. handlers.reject(self, value);
  4748. }
  4749.  
  4750. function onSuccess(value) {
  4751. if (called) {
  4752. return;
  4753. }
  4754. called = true;
  4755. handlers.resolve(self, value);
  4756. }
  4757.  
  4758. function tryToUnwrap() {
  4759. thenable(onSuccess, onError);
  4760. }
  4761.  
  4762. var result = tryCatch(tryToUnwrap);
  4763. if (result.status === 'error') {
  4764. onError(result.value);
  4765. }
  4766. }
  4767.  
  4768. function tryCatch(func, value) {
  4769. var out = {};
  4770. try {
  4771. out.value = func(value);
  4772. out.status = 'success';
  4773. } catch (e) {
  4774. out.status = 'error';
  4775. out.value = e;
  4776. }
  4777. return out;
  4778. }
  4779.  
  4780. Promise.resolve = resolve;
  4781. function resolve(value) {
  4782. if (value instanceof this) {
  4783. return value;
  4784. }
  4785. return handlers.resolve(new this(INTERNAL), value);
  4786. }
  4787.  
  4788. Promise.reject = reject;
  4789. function reject(reason) {
  4790. var promise = new this(INTERNAL);
  4791. return handlers.reject(promise, reason);
  4792. }
  4793.  
  4794. Promise.all = all;
  4795. function all(iterable) {
  4796. var self = this;
  4797. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4798. return this.reject(new TypeError('must be an array'));
  4799. }
  4800.  
  4801. var len = iterable.length;
  4802. var called = false;
  4803. if (!len) {
  4804. return this.resolve([]);
  4805. }
  4806.  
  4807. var values = new Array(len);
  4808. var resolved = 0;
  4809. var i = -1;
  4810. var promise = new this(INTERNAL);
  4811.  
  4812. while (++i < len) {
  4813. allResolver(iterable[i], i);
  4814. }
  4815. return promise;
  4816. function allResolver(value, i) {
  4817. self.resolve(value).then(resolveFromAll, function (error) {
  4818. if (!called) {
  4819. called = true;
  4820. handlers.reject(promise, error);
  4821. }
  4822. });
  4823. function resolveFromAll(outValue) {
  4824. values[i] = outValue;
  4825. if (++resolved === len && !called) {
  4826. called = true;
  4827. handlers.resolve(promise, values);
  4828. }
  4829. }
  4830. }
  4831. }
  4832.  
  4833. Promise.race = race;
  4834. function race(iterable) {
  4835. var self = this;
  4836. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4837. return this.reject(new TypeError('must be an array'));
  4838. }
  4839.  
  4840. var len = iterable.length;
  4841. var called = false;
  4842. if (!len) {
  4843. return this.resolve([]);
  4844. }
  4845.  
  4846. var i = -1;
  4847. var promise = new this(INTERNAL);
  4848.  
  4849. while (++i < len) {
  4850. resolver(iterable[i]);
  4851. }
  4852. return promise;
  4853. function resolver(value) {
  4854. self.resolve(value).then(function (response) {
  4855. if (!called) {
  4856. called = true;
  4857. handlers.resolve(promise, response);
  4858. }
  4859. }, function (error) {
  4860. if (!called) {
  4861. called = true;
  4862. handlers.reject(promise, error);
  4863. }
  4864. });
  4865. }
  4866. }
  4867.  
  4868. },{"immediate":57}],59:[function(require,module,exports){
  4869. // Top level file is just a mixin of submodules & constants
  4870. 'use strict';
  4871.  
  4872. var assign = require('./lib/utils/common').assign;
  4873.  
  4874. var deflate = require('./lib/deflate');
  4875. var inflate = require('./lib/inflate');
  4876. var constants = require('./lib/zlib/constants');
  4877.  
  4878. var pako = {};
  4879.  
  4880. assign(pako, deflate, inflate, constants);
  4881.  
  4882. module.exports = pako;
  4883.  
  4884. },{"./lib/deflate":60,"./lib/inflate":61,"./lib/utils/common":62,"./lib/zlib/constants":65}],60:[function(require,module,exports){
  4885. 'use strict';
  4886.  
  4887.  
  4888. var zlib_deflate = require('./zlib/deflate');
  4889. var utils = require('./utils/common');
  4890. var strings = require('./utils/strings');
  4891. var msg = require('./zlib/messages');
  4892. var ZStream = require('./zlib/zstream');
  4893.  
  4894. var toString = Object.prototype.toString;
  4895.  
  4896. /* Public constants ==========================================================*/
  4897. /* ===========================================================================*/
  4898.  
  4899. var Z_NO_FLUSH = 0;
  4900. var Z_FINISH = 4;
  4901.  
  4902. var Z_OK = 0;
  4903. var Z_STREAM_END = 1;
  4904. var Z_SYNC_FLUSH = 2;
  4905.  
  4906. var Z_DEFAULT_COMPRESSION = -1;
  4907.  
  4908. var Z_DEFAULT_STRATEGY = 0;
  4909.  
  4910. var Z_DEFLATED = 8;
  4911.  
  4912. /* ===========================================================================*/
  4913.  
  4914.  
  4915. /**
  4916. * class Deflate
  4917. *
  4918. * Generic JS-style wrapper for zlib calls. If you don't need
  4919. * streaming behaviour - use more simple functions: [[deflate]],
  4920. * [[deflateRaw]] and [[gzip]].
  4921. **/
  4922.  
  4923. /* internal
  4924. * Deflate.chunks -> Array
  4925. *
  4926. * Chunks of output data, if [[Deflate#onData]] not overriden.
  4927. **/
  4928.  
  4929. /**
  4930. * Deflate.result -> Uint8Array|Array
  4931. *
  4932. * Compressed result, generated by default [[Deflate#onData]]
  4933. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  4934. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  4935. * push a chunk with explicit flush (call [[Deflate#push]] with
  4936. * `Z_SYNC_FLUSH` param).
  4937. **/
  4938.  
  4939. /**
  4940. * Deflate.err -> Number
  4941. *
  4942. * Error code after deflate finished. 0 (Z_OK) on success.
  4943. * You will not need it in real life, because deflate errors
  4944. * are possible only on wrong options or bad `onData` / `onEnd`
  4945. * custom handlers.
  4946. **/
  4947.  
  4948. /**
  4949. * Deflate.msg -> String
  4950. *
  4951. * Error message, if [[Deflate.err]] != 0
  4952. **/
  4953.  
  4954.  
  4955. /**
  4956. * new Deflate(options)
  4957. * - options (Object): zlib deflate options.
  4958. *
  4959. * Creates new deflator instance with specified params. Throws exception
  4960. * on bad params. Supported options:
  4961. *
  4962. * - `level`
  4963. * - `windowBits`
  4964. * - `memLevel`
  4965. * - `strategy`
  4966. * - `dictionary`
  4967. *
  4968. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4969. * for more information on these.
  4970. *
  4971. * Additional options, for internal needs:
  4972. *
  4973. * - `chunkSize` - size of generated data chunks (16K by default)
  4974. * - `raw` (Boolean) - do raw deflate
  4975. * - `gzip` (Boolean) - create gzip wrapper
  4976. * - `to` (String) - if equal to 'string', then result will be "binary string"
  4977. * (each char code [0..255])
  4978. * - `header` (Object) - custom header for gzip
  4979. * - `text` (Boolean) - true if compressed data believed to be text
  4980. * - `time` (Number) - modification time, unix timestamp
  4981. * - `os` (Number) - operation system code
  4982. * - `extra` (Array) - array of bytes with extra data (max 65536)
  4983. * - `name` (String) - file name (binary string)
  4984. * - `comment` (String) - comment (binary string)
  4985. * - `hcrc` (Boolean) - true if header crc should be added
  4986. *
  4987. * ##### Example:
  4988. *
  4989. * ```javascript
  4990. * var pako = require('pako')
  4991. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  4992. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  4993. *
  4994. * var deflate = new pako.Deflate({ level: 3});
  4995. *
  4996. * deflate.push(chunk1, false);
  4997. * deflate.push(chunk2, true); // true -> last chunk
  4998. *
  4999. * if (deflate.err) { throw new Error(deflate.err); }
  5000. *
  5001. * console.log(deflate.result);
  5002. * ```
  5003. **/
  5004. function Deflate(options) {
  5005. if (!(this instanceof Deflate)) return new Deflate(options);
  5006.  
  5007. this.options = utils.assign({
  5008. level: Z_DEFAULT_COMPRESSION,
  5009. method: Z_DEFLATED,
  5010. chunkSize: 16384,
  5011. windowBits: 15,
  5012. memLevel: 8,
  5013. strategy: Z_DEFAULT_STRATEGY,
  5014. to: ''
  5015. }, options || {});
  5016.  
  5017. var opt = this.options;
  5018.  
  5019. if (opt.raw && (opt.windowBits > 0)) {
  5020. opt.windowBits = -opt.windowBits;
  5021. }
  5022.  
  5023. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  5024. opt.windowBits += 16;
  5025. }
  5026.  
  5027. this.err = 0; // error code, if happens (0 = Z_OK)
  5028. this.msg = ''; // error message
  5029. this.ended = false; // used to avoid multiple onEnd() calls
  5030. this.chunks = []; // chunks of compressed data
  5031.  
  5032. this.strm = new ZStream();
  5033. this.strm.avail_out = 0;
  5034.  
  5035. var status = zlib_deflate.deflateInit2(
  5036. this.strm,
  5037. opt.level,
  5038. opt.method,
  5039. opt.windowBits,
  5040. opt.memLevel,
  5041. opt.strategy
  5042. );
  5043.  
  5044. if (status !== Z_OK) {
  5045. throw new Error(msg[status]);
  5046. }
  5047.  
  5048. if (opt.header) {
  5049. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  5050. }
  5051.  
  5052. if (opt.dictionary) {
  5053. var dict;
  5054. // Convert data if needed
  5055. if (typeof opt.dictionary === 'string') {
  5056. // If we need to compress text, change encoding to utf8.
  5057. dict = strings.string2buf(opt.dictionary);
  5058. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  5059. dict = new Uint8Array(opt.dictionary);
  5060. } else {
  5061. dict = opt.dictionary;
  5062. }
  5063.  
  5064. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  5065.  
  5066. if (status !== Z_OK) {
  5067. throw new Error(msg[status]);
  5068. }
  5069.  
  5070. this._dict_set = true;
  5071. }
  5072. }
  5073.  
  5074. /**
  5075. * Deflate#push(data[, mode]) -> Boolean
  5076. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  5077. * converted to utf8 byte sequence.
  5078. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5079. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5080. *
  5081. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  5082. * new compressed chunks. Returns `true` on success. The last data block must have
  5083. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5084. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5085. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  5086. *
  5087. * On fail call [[Deflate#onEnd]] with error code and return false.
  5088. *
  5089. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5090. * array format is detected automatically). Also, don't skip last param and always
  5091. * use the same type in your code (boolean or number). That will improve JS speed.
  5092. *
  5093. * For regular `Array`-s make sure all elements are [0..255].
  5094. *
  5095. * ##### Example
  5096. *
  5097. * ```javascript
  5098. * push(chunk, false); // push one of data chunks
  5099. * ...
  5100. * push(chunk, true); // push last chunk
  5101. * ```
  5102. **/
  5103. Deflate.prototype.push = function (data, mode) {
  5104. var strm = this.strm;
  5105. var chunkSize = this.options.chunkSize;
  5106. var status, _mode;
  5107.  
  5108. if (this.ended) { return false; }
  5109.  
  5110. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  5111.  
  5112. // Convert data if needed
  5113. if (typeof data === 'string') {
  5114. // If we need to compress text, change encoding to utf8.
  5115. strm.input = strings.string2buf(data);
  5116. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5117. strm.input = new Uint8Array(data);
  5118. } else {
  5119. strm.input = data;
  5120. }
  5121.  
  5122. strm.next_in = 0;
  5123. strm.avail_in = strm.input.length;
  5124.  
  5125. do {
  5126. if (strm.avail_out === 0) {
  5127. strm.output = new utils.Buf8(chunkSize);
  5128. strm.next_out = 0;
  5129. strm.avail_out = chunkSize;
  5130. }
  5131. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  5132.  
  5133. if (status !== Z_STREAM_END && status !== Z_OK) {
  5134. this.onEnd(status);
  5135. this.ended = true;
  5136. return false;
  5137. }
  5138. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  5139. if (this.options.to === 'string') {
  5140. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  5141. } else {
  5142. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5143. }
  5144. }
  5145. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  5146.  
  5147. // Finalize on the last chunk.
  5148. if (_mode === Z_FINISH) {
  5149. status = zlib_deflate.deflateEnd(this.strm);
  5150. this.onEnd(status);
  5151. this.ended = true;
  5152. return status === Z_OK;
  5153. }
  5154.  
  5155. // callback interim results if Z_SYNC_FLUSH.
  5156. if (_mode === Z_SYNC_FLUSH) {
  5157. this.onEnd(Z_OK);
  5158. strm.avail_out = 0;
  5159. return true;
  5160. }
  5161.  
  5162. return true;
  5163. };
  5164.  
  5165.  
  5166. /**
  5167. * Deflate#onData(chunk) -> Void
  5168. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5169. * on js engine support. When string output requested, each chunk
  5170. * will be string.
  5171. *
  5172. * By default, stores data blocks in `chunks[]` property and glue
  5173. * those in `onEnd`. Override this handler, if you need another behaviour.
  5174. **/
  5175. Deflate.prototype.onData = function (chunk) {
  5176. this.chunks.push(chunk);
  5177. };
  5178.  
  5179.  
  5180. /**
  5181. * Deflate#onEnd(status) -> Void
  5182. * - status (Number): deflate status. 0 (Z_OK) on success,
  5183. * other if not.
  5184. *
  5185. * Called once after you tell deflate that the input stream is
  5186. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5187. * or if an error happened. By default - join collected chunks,
  5188. * free memory and fill `results` / `err` properties.
  5189. **/
  5190. Deflate.prototype.onEnd = function (status) {
  5191. // On success - join
  5192. if (status === Z_OK) {
  5193. if (this.options.to === 'string') {
  5194. this.result = this.chunks.join('');
  5195. } else {
  5196. this.result = utils.flattenChunks(this.chunks);
  5197. }
  5198. }
  5199. this.chunks = [];
  5200. this.err = status;
  5201. this.msg = this.strm.msg;
  5202. };
  5203.  
  5204.  
  5205. /**
  5206. * deflate(data[, options]) -> Uint8Array|Array|String
  5207. * - data (Uint8Array|Array|String): input data to compress.
  5208. * - options (Object): zlib deflate options.
  5209. *
  5210. * Compress `data` with deflate algorithm and `options`.
  5211. *
  5212. * Supported options are:
  5213. *
  5214. * - level
  5215. * - windowBits
  5216. * - memLevel
  5217. * - strategy
  5218. * - dictionary
  5219. *
  5220. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5221. * for more information on these.
  5222. *
  5223. * Sugar (options):
  5224. *
  5225. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5226. * negative windowBits implicitly.
  5227. * - `to` (String) - if equal to 'string', then result will be "binary string"
  5228. * (each char code [0..255])
  5229. *
  5230. * ##### Example:
  5231. *
  5232. * ```javascript
  5233. * var pako = require('pako')
  5234. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  5235. *
  5236. * console.log(pako.deflate(data));
  5237. * ```
  5238. **/
  5239. function deflate(input, options) {
  5240. var deflator = new Deflate(options);
  5241.  
  5242. deflator.push(input, true);
  5243.  
  5244. // That will never happens, if you don't cheat with options :)
  5245. if (deflator.err) { throw deflator.msg; }
  5246.  
  5247. return deflator.result;
  5248. }
  5249.  
  5250.  
  5251. /**
  5252. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  5253. * - data (Uint8Array|Array|String): input data to compress.
  5254. * - options (Object): zlib deflate options.
  5255. *
  5256. * The same as [[deflate]], but creates raw data, without wrapper
  5257. * (header and adler32 crc).
  5258. **/
  5259. function deflateRaw(input, options) {
  5260. options = options || {};
  5261. options.raw = true;
  5262. return deflate(input, options);
  5263. }
  5264.  
  5265.  
  5266. /**
  5267. * gzip(data[, options]) -> Uint8Array|Array|String
  5268. * - data (Uint8Array|Array|String): input data to compress.
  5269. * - options (Object): zlib deflate options.
  5270. *
  5271. * The same as [[deflate]], but create gzip wrapper instead of
  5272. * deflate one.
  5273. **/
  5274. function gzip(input, options) {
  5275. options = options || {};
  5276. options.gzip = true;
  5277. return deflate(input, options);
  5278. }
  5279.  
  5280.  
  5281. exports.Deflate = Deflate;
  5282. exports.deflate = deflate;
  5283. exports.deflateRaw = deflateRaw;
  5284. exports.gzip = gzip;
  5285.  
  5286. },{"./utils/common":62,"./utils/strings":63,"./zlib/deflate":67,"./zlib/messages":72,"./zlib/zstream":74}],61:[function(require,module,exports){
  5287. 'use strict';
  5288.  
  5289.  
  5290. var zlib_inflate = require('./zlib/inflate');
  5291. var utils = require('./utils/common');
  5292. var strings = require('./utils/strings');
  5293. var c = require('./zlib/constants');
  5294. var msg = require('./zlib/messages');
  5295. var ZStream = require('./zlib/zstream');
  5296. var GZheader = require('./zlib/gzheader');
  5297.  
  5298. var toString = Object.prototype.toString;
  5299.  
  5300. /**
  5301. * class Inflate
  5302. *
  5303. * Generic JS-style wrapper for zlib calls. If you don't need
  5304. * streaming behaviour - use more simple functions: [[inflate]]
  5305. * and [[inflateRaw]].
  5306. **/
  5307.  
  5308. /* internal
  5309. * inflate.chunks -> Array
  5310. *
  5311. * Chunks of output data, if [[Inflate#onData]] not overriden.
  5312. **/
  5313.  
  5314. /**
  5315. * Inflate.result -> Uint8Array|Array|String
  5316. *
  5317. * Uncompressed result, generated by default [[Inflate#onData]]
  5318. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  5319. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  5320. * push a chunk with explicit flush (call [[Inflate#push]] with
  5321. * `Z_SYNC_FLUSH` param).
  5322. **/
  5323.  
  5324. /**
  5325. * Inflate.err -> Number
  5326. *
  5327. * Error code after inflate finished. 0 (Z_OK) on success.
  5328. * Should be checked if broken data possible.
  5329. **/
  5330.  
  5331. /**
  5332. * Inflate.msg -> String
  5333. *
  5334. * Error message, if [[Inflate.err]] != 0
  5335. **/
  5336.  
  5337.  
  5338. /**
  5339. * new Inflate(options)
  5340. * - options (Object): zlib inflate options.
  5341. *
  5342. * Creates new inflator instance with specified params. Throws exception
  5343. * on bad params. Supported options:
  5344. *
  5345. * - `windowBits`
  5346. * - `dictionary`
  5347. *
  5348. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5349. * for more information on these.
  5350. *
  5351. * Additional options, for internal needs:
  5352. *
  5353. * - `chunkSize` - size of generated data chunks (16K by default)
  5354. * - `raw` (Boolean) - do raw inflate
  5355. * - `to` (String) - if equal to 'string', then result will be converted
  5356. * from utf8 to utf16 (javascript) string. When string output requested,
  5357. * chunk length can differ from `chunkSize`, depending on content.
  5358. *
  5359. * By default, when no options set, autodetect deflate/gzip data format via
  5360. * wrapper header.
  5361. *
  5362. * ##### Example:
  5363. *
  5364. * ```javascript
  5365. * var pako = require('pako')
  5366. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5367. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5368. *
  5369. * var inflate = new pako.Inflate({ level: 3});
  5370. *
  5371. * inflate.push(chunk1, false);
  5372. * inflate.push(chunk2, true); // true -> last chunk
  5373. *
  5374. * if (inflate.err) { throw new Error(inflate.err); }
  5375. *
  5376. * console.log(inflate.result);
  5377. * ```
  5378. **/
  5379. function Inflate(options) {
  5380. if (!(this instanceof Inflate)) return new Inflate(options);
  5381.  
  5382. this.options = utils.assign({
  5383. chunkSize: 16384,
  5384. windowBits: 0,
  5385. to: ''
  5386. }, options || {});
  5387.  
  5388. var opt = this.options;
  5389.  
  5390. // Force window size for `raw` data, if not set directly,
  5391. // because we have no header for autodetect.
  5392. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  5393. opt.windowBits = -opt.windowBits;
  5394. if (opt.windowBits === 0) { opt.windowBits = -15; }
  5395. }
  5396.  
  5397. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  5398. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  5399. !(options && options.windowBits)) {
  5400. opt.windowBits += 32;
  5401. }
  5402.  
  5403. // Gzip header has no info about windows size, we can do autodetect only
  5404. // for deflate. So, if window size not set, force it to max when gzip possible
  5405. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  5406. // bit 3 (16) -> gzipped data
  5407. // bit 4 (32) -> autodetect gzip/deflate
  5408. if ((opt.windowBits & 15) === 0) {
  5409. opt.windowBits |= 15;
  5410. }
  5411. }
  5412.  
  5413. this.err = 0; // error code, if happens (0 = Z_OK)
  5414. this.msg = ''; // error message
  5415. this.ended = false; // used to avoid multiple onEnd() calls
  5416. this.chunks = []; // chunks of compressed data
  5417.  
  5418. this.strm = new ZStream();
  5419. this.strm.avail_out = 0;
  5420.  
  5421. var status = zlib_inflate.inflateInit2(
  5422. this.strm,
  5423. opt.windowBits
  5424. );
  5425.  
  5426. if (status !== c.Z_OK) {
  5427. throw new Error(msg[status]);
  5428. }
  5429.  
  5430. this.header = new GZheader();
  5431.  
  5432. zlib_inflate.inflateGetHeader(this.strm, this.header);
  5433. }
  5434.  
  5435. /**
  5436. * Inflate#push(data[, mode]) -> Boolean
  5437. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  5438. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5439. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5440. *
  5441. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  5442. * new output chunks. Returns `true` on success. The last data block must have
  5443. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5444. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5445. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  5446. *
  5447. * On fail call [[Inflate#onEnd]] with error code and return false.
  5448. *
  5449. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5450. * format is detected automatically). Also, don't skip last param and always
  5451. * use the same type in your code (boolean or number). That will improve JS speed.
  5452. *
  5453. * For regular `Array`-s make sure all elements are [0..255].
  5454. *
  5455. * ##### Example
  5456. *
  5457. * ```javascript
  5458. * push(chunk, false); // push one of data chunks
  5459. * ...
  5460. * push(chunk, true); // push last chunk
  5461. * ```
  5462. **/
  5463. Inflate.prototype.push = function (data, mode) {
  5464. var strm = this.strm;
  5465. var chunkSize = this.options.chunkSize;
  5466. var dictionary = this.options.dictionary;
  5467. var status, _mode;
  5468. var next_out_utf8, tail, utf8str;
  5469. var dict;
  5470.  
  5471. // Flag to properly process Z_BUF_ERROR on testing inflate call
  5472. // when we check that all output data was flushed.
  5473. var allowBufError = false;
  5474.  
  5475. if (this.ended) { return false; }
  5476. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  5477.  
  5478. // Convert data if needed
  5479. if (typeof data === 'string') {
  5480. // Only binary strings can be decompressed on practice
  5481. strm.input = strings.binstring2buf(data);
  5482. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5483. strm.input = new Uint8Array(data);
  5484. } else {
  5485. strm.input = data;
  5486. }
  5487.  
  5488. strm.next_in = 0;
  5489. strm.avail_in = strm.input.length;
  5490.  
  5491. do {
  5492. if (strm.avail_out === 0) {
  5493. strm.output = new utils.Buf8(chunkSize);
  5494. strm.next_out = 0;
  5495. strm.avail_out = chunkSize;
  5496. }
  5497.  
  5498. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  5499.  
  5500. if (status === c.Z_NEED_DICT && dictionary) {
  5501. // Convert data if needed
  5502. if (typeof dictionary === 'string') {
  5503. dict = strings.string2buf(dictionary);
  5504. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  5505. dict = new Uint8Array(dictionary);
  5506. } else {
  5507. dict = dictionary;
  5508. }
  5509.  
  5510. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  5511.  
  5512. }
  5513.  
  5514. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  5515. status = c.Z_OK;
  5516. allowBufError = false;
  5517. }
  5518.  
  5519. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  5520. this.onEnd(status);
  5521. this.ended = true;
  5522. return false;
  5523. }
  5524.  
  5525. if (strm.next_out) {
  5526. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  5527.  
  5528. if (this.options.to === 'string') {
  5529.  
  5530. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  5531.  
  5532. tail = strm.next_out - next_out_utf8;
  5533. utf8str = strings.buf2string(strm.output, next_out_utf8);
  5534.  
  5535. // move tail
  5536. strm.next_out = tail;
  5537. strm.avail_out = chunkSize - tail;
  5538. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  5539.  
  5540. this.onData(utf8str);
  5541.  
  5542. } else {
  5543. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5544. }
  5545. }
  5546. }
  5547.  
  5548. // When no more input data, we should check that internal inflate buffers
  5549. // are flushed. The only way to do it when avail_out = 0 - run one more
  5550. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  5551. // Here we set flag to process this error properly.
  5552. //
  5553. // NOTE. Deflate does not return error in this case and does not needs such
  5554. // logic.
  5555. if (strm.avail_in === 0 && strm.avail_out === 0) {
  5556. allowBufError = true;
  5557. }
  5558.  
  5559. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  5560.  
  5561. if (status === c.Z_STREAM_END) {
  5562. _mode = c.Z_FINISH;
  5563. }
  5564.  
  5565. // Finalize on the last chunk.
  5566. if (_mode === c.Z_FINISH) {
  5567. status = zlib_inflate.inflateEnd(this.strm);
  5568. this.onEnd(status);
  5569. this.ended = true;
  5570. return status === c.Z_OK;
  5571. }
  5572.  
  5573. // callback interim results if Z_SYNC_FLUSH.
  5574. if (_mode === c.Z_SYNC_FLUSH) {
  5575. this.onEnd(c.Z_OK);
  5576. strm.avail_out = 0;
  5577. return true;
  5578. }
  5579.  
  5580. return true;
  5581. };
  5582.  
  5583.  
  5584. /**
  5585. * Inflate#onData(chunk) -> Void
  5586. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5587. * on js engine support. When string output requested, each chunk
  5588. * will be string.
  5589. *
  5590. * By default, stores data blocks in `chunks[]` property and glue
  5591. * those in `onEnd`. Override this handler, if you need another behaviour.
  5592. **/
  5593. Inflate.prototype.onData = function (chunk) {
  5594. this.chunks.push(chunk);
  5595. };
  5596.  
  5597.  
  5598. /**
  5599. * Inflate#onEnd(status) -> Void
  5600. * - status (Number): inflate status. 0 (Z_OK) on success,
  5601. * other if not.
  5602. *
  5603. * Called either after you tell inflate that the input stream is
  5604. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5605. * or if an error happened. By default - join collected chunks,
  5606. * free memory and fill `results` / `err` properties.
  5607. **/
  5608. Inflate.prototype.onEnd = function (status) {
  5609. // On success - join
  5610. if (status === c.Z_OK) {
  5611. if (this.options.to === 'string') {
  5612. // Glue & convert here, until we teach pako to send
  5613. // utf8 alligned strings to onData
  5614. this.result = this.chunks.join('');
  5615. } else {
  5616. this.result = utils.flattenChunks(this.chunks);
  5617. }
  5618. }
  5619. this.chunks = [];
  5620. this.err = status;
  5621. this.msg = this.strm.msg;
  5622. };
  5623.  
  5624.  
  5625. /**
  5626. * inflate(data[, options]) -> Uint8Array|Array|String
  5627. * - data (Uint8Array|Array|String): input data to decompress.
  5628. * - options (Object): zlib inflate options.
  5629. *
  5630. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  5631. * format via wrapper header by default. That's why we don't provide
  5632. * separate `ungzip` method.
  5633. *
  5634. * Supported options are:
  5635. *
  5636. * - windowBits
  5637. *
  5638. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5639. * for more information.
  5640. *
  5641. * Sugar (options):
  5642. *
  5643. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5644. * negative windowBits implicitly.
  5645. * - `to` (String) - if equal to 'string', then result will be converted
  5646. * from utf8 to utf16 (javascript) string. When string output requested,
  5647. * chunk length can differ from `chunkSize`, depending on content.
  5648. *
  5649. *
  5650. * ##### Example:
  5651. *
  5652. * ```javascript
  5653. * var pako = require('pako')
  5654. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  5655. * , output;
  5656. *
  5657. * try {
  5658. * output = pako.inflate(input);
  5659. * } catch (err)
  5660. * console.log(err);
  5661. * }
  5662. * ```
  5663. **/
  5664. function inflate(input, options) {
  5665. var inflator = new Inflate(options);
  5666.  
  5667. inflator.push(input, true);
  5668.  
  5669. // That will never happens, if you don't cheat with options :)
  5670. if (inflator.err) { throw inflator.msg; }
  5671.  
  5672. return inflator.result;
  5673. }
  5674.  
  5675.  
  5676. /**
  5677. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  5678. * - data (Uint8Array|Array|String): input data to decompress.
  5679. * - options (Object): zlib inflate options.
  5680. *
  5681. * The same as [[inflate]], but creates raw data, without wrapper
  5682. * (header and adler32 crc).
  5683. **/
  5684. function inflateRaw(input, options) {
  5685. options = options || {};
  5686. options.raw = true;
  5687. return inflate(input, options);
  5688. }
  5689.  
  5690.  
  5691. /**
  5692. * ungzip(data[, options]) -> Uint8Array|Array|String
  5693. * - data (Uint8Array|Array|String): input data to decompress.
  5694. * - options (Object): zlib inflate options.
  5695. *
  5696. * Just shortcut to [[inflate]], because it autodetects format
  5697. * by header.content. Done for convenience.
  5698. **/
  5699.  
  5700.  
  5701. exports.Inflate = Inflate;
  5702. exports.inflate = inflate;
  5703. exports.inflateRaw = inflateRaw;
  5704. exports.ungzip = inflate;
  5705.  
  5706. },{"./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){
  5707. 'use strict';
  5708.  
  5709.  
  5710. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  5711. (typeof Uint16Array !== 'undefined') &&
  5712. (typeof Int32Array !== 'undefined');
  5713.  
  5714.  
  5715. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  5716. var sources = Array.prototype.slice.call(arguments, 1);
  5717. while (sources.length) {
  5718. var source = sources.shift();
  5719. if (!source) { continue; }
  5720.  
  5721. if (typeof source !== 'object') {
  5722. throw new TypeError(source + 'must be non-object');
  5723. }
  5724.  
  5725. for (var p in source) {
  5726. if (source.hasOwnProperty(p)) {
  5727. obj[p] = source[p];
  5728. }
  5729. }
  5730. }
  5731.  
  5732. return obj;
  5733. };
  5734.  
  5735.  
  5736. // reduce buffer size, avoiding mem copy
  5737. exports.shrinkBuf = function (buf, size) {
  5738. if (buf.length === size) { return buf; }
  5739. if (buf.subarray) { return buf.subarray(0, size); }
  5740. buf.length = size;
  5741. return buf;
  5742. };
  5743.  
  5744.  
  5745. var fnTyped = {
  5746. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5747. if (src.subarray && dest.subarray) {
  5748. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  5749. return;
  5750. }
  5751. // Fallback to ordinary array
  5752. for (var i = 0; i < len; i++) {
  5753. dest[dest_offs + i] = src[src_offs + i];
  5754. }
  5755. },
  5756. // Join array of chunks to single array.
  5757. flattenChunks: function (chunks) {
  5758. var i, l, len, pos, chunk, result;
  5759.  
  5760. // calculate data length
  5761. len = 0;
  5762. for (i = 0, l = chunks.length; i < l; i++) {
  5763. len += chunks[i].length;
  5764. }
  5765.  
  5766. // join chunks
  5767. result = new Uint8Array(len);
  5768. pos = 0;
  5769. for (i = 0, l = chunks.length; i < l; i++) {
  5770. chunk = chunks[i];
  5771. result.set(chunk, pos);
  5772. pos += chunk.length;
  5773. }
  5774.  
  5775. return result;
  5776. }
  5777. };
  5778.  
  5779. var fnUntyped = {
  5780. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5781. for (var i = 0; i < len; i++) {
  5782. dest[dest_offs + i] = src[src_offs + i];
  5783. }
  5784. },
  5785. // Join array of chunks to single array.
  5786. flattenChunks: function (chunks) {
  5787. return [].concat.apply([], chunks);
  5788. }
  5789. };
  5790.  
  5791.  
  5792. // Enable/Disable typed arrays use, for testing
  5793. //
  5794. exports.setTyped = function (on) {
  5795. if (on) {
  5796. exports.Buf8 = Uint8Array;
  5797. exports.Buf16 = Uint16Array;
  5798. exports.Buf32 = Int32Array;
  5799. exports.assign(exports, fnTyped);
  5800. } else {
  5801. exports.Buf8 = Array;
  5802. exports.Buf16 = Array;
  5803. exports.Buf32 = Array;
  5804. exports.assign(exports, fnUntyped);
  5805. }
  5806. };
  5807.  
  5808. exports.setTyped(TYPED_OK);
  5809.  
  5810. },{}],63:[function(require,module,exports){
  5811. // String encode/decode helpers
  5812. 'use strict';
  5813.  
  5814.  
  5815. var utils = require('./common');
  5816.  
  5817.  
  5818. // Quick check if we can use fast array to bin string conversion
  5819. //
  5820. // - apply(Array) can fail on Android 2.2
  5821. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  5822. //
  5823. var STR_APPLY_OK = true;
  5824. var STR_APPLY_UIA_OK = true;
  5825.  
  5826. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  5827. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  5828.  
  5829.  
  5830. // Table with utf8 lengths (calculated by first byte of sequence)
  5831. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  5832. // because max possible codepoint is 0x10ffff
  5833. var _utf8len = new utils.Buf8(256);
  5834. for (var q = 0; q < 256; q++) {
  5835. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  5836. }
  5837. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  5838.  
  5839.  
  5840. // convert string to array (typed, when possible)
  5841. exports.string2buf = function (str) {
  5842. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  5843.  
  5844. // count binary size
  5845. for (m_pos = 0; m_pos < str_len; m_pos++) {
  5846. c = str.charCodeAt(m_pos);
  5847. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  5848. c2 = str.charCodeAt(m_pos + 1);
  5849. if ((c2 & 0xfc00) === 0xdc00) {
  5850. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5851. m_pos++;
  5852. }
  5853. }
  5854. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  5855. }
  5856.  
  5857. // allocate buffer
  5858. buf = new utils.Buf8(buf_len);
  5859.  
  5860. // convert
  5861. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  5862. c = str.charCodeAt(m_pos);
  5863. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  5864. c2 = str.charCodeAt(m_pos + 1);
  5865. if ((c2 & 0xfc00) === 0xdc00) {
  5866. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5867. m_pos++;
  5868. }
  5869. }
  5870. if (c < 0x80) {
  5871. /* one byte */
  5872. buf[i++] = c;
  5873. } else if (c < 0x800) {
  5874. /* two bytes */
  5875. buf[i++] = 0xC0 | (c >>> 6);
  5876. buf[i++] = 0x80 | (c & 0x3f);
  5877. } else if (c < 0x10000) {
  5878. /* three bytes */
  5879. buf[i++] = 0xE0 | (c >>> 12);
  5880. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5881. buf[i++] = 0x80 | (c & 0x3f);
  5882. } else {
  5883. /* four bytes */
  5884. buf[i++] = 0xf0 | (c >>> 18);
  5885. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  5886. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5887. buf[i++] = 0x80 | (c & 0x3f);
  5888. }
  5889. }
  5890.  
  5891. return buf;
  5892. };
  5893.  
  5894. // Helper (used in 2 places)
  5895. function buf2binstring(buf, len) {
  5896. // use fallback for big arrays to avoid stack overflow
  5897. if (len < 65537) {
  5898. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  5899. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  5900. }
  5901. }
  5902.  
  5903. var result = '';
  5904. for (var i = 0; i < len; i++) {
  5905. result += String.fromCharCode(buf[i]);
  5906. }
  5907. return result;
  5908. }
  5909.  
  5910.  
  5911. // Convert byte array to binary string
  5912. exports.buf2binstring = function (buf) {
  5913. return buf2binstring(buf, buf.length);
  5914. };
  5915.  
  5916.  
  5917. // Convert binary string (typed, when possible)
  5918. exports.binstring2buf = function (str) {
  5919. var buf = new utils.Buf8(str.length);
  5920. for (var i = 0, len = buf.length; i < len; i++) {
  5921. buf[i] = str.charCodeAt(i);
  5922. }
  5923. return buf;
  5924. };
  5925.  
  5926.  
  5927. // convert array to string
  5928. exports.buf2string = function (buf, max) {
  5929. var i, out, c, c_len;
  5930. var len = max || buf.length;
  5931.  
  5932. // Reserve max possible length (2 words per char)
  5933. // NB: by unknown reasons, Array is significantly faster for
  5934. // String.fromCharCode.apply than Uint16Array.
  5935. var utf16buf = new Array(len * 2);
  5936.  
  5937. for (out = 0, i = 0; i < len;) {
  5938. c = buf[i++];
  5939. // quick process ascii
  5940. if (c < 0x80) { utf16buf[out++] = c; continue; }
  5941.  
  5942. c_len = _utf8len[c];
  5943. // skip 5 & 6 byte codes
  5944. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  5945.  
  5946. // apply mask on first byte
  5947. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  5948. // join the rest
  5949. while (c_len > 1 && i < len) {
  5950. c = (c << 6) | (buf[i++] & 0x3f);
  5951. c_len--;
  5952. }
  5953.  
  5954. // terminated by end of string?
  5955. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  5956.  
  5957. if (c < 0x10000) {
  5958. utf16buf[out++] = c;
  5959. } else {
  5960. c -= 0x10000;
  5961. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  5962. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  5963. }
  5964. }
  5965.  
  5966. return buf2binstring(utf16buf, out);
  5967. };
  5968.  
  5969.  
  5970. // Calculate max possible position in utf8 buffer,
  5971. // that will not break sequence. If that's not possible
  5972. // - (very small limits) return max size as is.
  5973. //
  5974. // buf[] - utf8 bytes array
  5975. // max - length limit (mandatory);
  5976. exports.utf8border = function (buf, max) {
  5977. var pos;
  5978.  
  5979. max = max || buf.length;
  5980. if (max > buf.length) { max = buf.length; }
  5981.  
  5982. // go back from last position, until start of sequence found
  5983. pos = max - 1;
  5984. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  5985.  
  5986. // Fuckup - very small and broken sequence,
  5987. // return max, because we should return something anyway.
  5988. if (pos < 0) { return max; }
  5989.  
  5990. // If we came to start of buffer - that means vuffer is too small,
  5991. // return max too.
  5992. if (pos === 0) { return max; }
  5993.  
  5994. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  5995. };
  5996.  
  5997. },{"./common":62}],64:[function(require,module,exports){
  5998. 'use strict';
  5999.  
  6000. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  6001. // It doesn't worth to make additional optimizationa as in original.
  6002. // Small size is preferable.
  6003.  
  6004. function adler32(adler, buf, len, pos) {
  6005. var s1 = (adler & 0xffff) |0,
  6006. s2 = ((adler >>> 16) & 0xffff) |0,
  6007. n = 0;
  6008.  
  6009. while (len !== 0) {
  6010. // Set limit ~ twice less than 5552, to keep
  6011. // s2 in 31-bits, because we force signed ints.
  6012. // in other case %= will fail.
  6013. n = len > 2000 ? 2000 : len;
  6014. len -= n;
  6015.  
  6016. do {
  6017. s1 = (s1 + buf[pos++]) |0;
  6018. s2 = (s2 + s1) |0;
  6019. } while (--n);
  6020.  
  6021. s1 %= 65521;
  6022. s2 %= 65521;
  6023. }
  6024.  
  6025. return (s1 | (s2 << 16)) |0;
  6026. }
  6027.  
  6028.  
  6029. module.exports = adler32;
  6030.  
  6031. },{}],65:[function(require,module,exports){
  6032. 'use strict';
  6033.  
  6034.  
  6035. module.exports = {
  6036.  
  6037. /* Allowed flush values; see deflate() and inflate() below for details */
  6038. Z_NO_FLUSH: 0,
  6039. Z_PARTIAL_FLUSH: 1,
  6040. Z_SYNC_FLUSH: 2,
  6041. Z_FULL_FLUSH: 3,
  6042. Z_FINISH: 4,
  6043. Z_BLOCK: 5,
  6044. Z_TREES: 6,
  6045.  
  6046. /* Return codes for the compression/decompression functions. Negative values
  6047. * are errors, positive values are used for special but normal events.
  6048. */
  6049. Z_OK: 0,
  6050. Z_STREAM_END: 1,
  6051. Z_NEED_DICT: 2,
  6052. Z_ERRNO: -1,
  6053. Z_STREAM_ERROR: -2,
  6054. Z_DATA_ERROR: -3,
  6055. //Z_MEM_ERROR: -4,
  6056. Z_BUF_ERROR: -5,
  6057. //Z_VERSION_ERROR: -6,
  6058.  
  6059. /* compression levels */
  6060. Z_NO_COMPRESSION: 0,
  6061. Z_BEST_SPEED: 1,
  6062. Z_BEST_COMPRESSION: 9,
  6063. Z_DEFAULT_COMPRESSION: -1,
  6064.  
  6065.  
  6066. Z_FILTERED: 1,
  6067. Z_HUFFMAN_ONLY: 2,
  6068. Z_RLE: 3,
  6069. Z_FIXED: 4,
  6070. Z_DEFAULT_STRATEGY: 0,
  6071.  
  6072. /* Possible values of the data_type field (though see inflate()) */
  6073. Z_BINARY: 0,
  6074. Z_TEXT: 1,
  6075. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  6076. Z_UNKNOWN: 2,
  6077.  
  6078. /* The deflate compression method */
  6079. Z_DEFLATED: 8
  6080. //Z_NULL: null // Use -1 or null inline, depending on var type
  6081. };
  6082.  
  6083. },{}],66:[function(require,module,exports){
  6084. 'use strict';
  6085.  
  6086. // Note: we can't get significant speed boost here.
  6087. // So write code to minimize size - no pregenerated tables
  6088. // and array tools dependencies.
  6089.  
  6090.  
  6091. // Use ordinary array, since untyped makes no boost here
  6092. function makeTable() {
  6093. var c, table = [];
  6094.  
  6095. for (var n = 0; n < 256; n++) {
  6096. c = n;
  6097. for (var k = 0; k < 8; k++) {
  6098. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  6099. }
  6100. table[n] = c;
  6101. }
  6102.  
  6103. return table;
  6104. }
  6105.  
  6106. // Create table on load. Just 255 signed longs. Not a problem.
  6107. var crcTable = makeTable();
  6108.  
  6109.  
  6110. function crc32(crc, buf, len, pos) {
  6111. var t = crcTable,
  6112. end = pos + len;
  6113.  
  6114. crc ^= -1;
  6115.  
  6116. for (var i = pos; i < end; i++) {
  6117. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  6118. }
  6119.  
  6120. return (crc ^ (-1)); // >>> 0;
  6121. }
  6122.  
  6123.  
  6124. module.exports = crc32;
  6125.  
  6126. },{}],67:[function(require,module,exports){
  6127. 'use strict';
  6128.  
  6129. var utils = require('../utils/common');
  6130. var trees = require('./trees');
  6131. var adler32 = require('./adler32');
  6132. var crc32 = require('./crc32');
  6133. var msg = require('./messages');
  6134.  
  6135. /* Public constants ==========================================================*/
  6136. /* ===========================================================================*/
  6137.  
  6138.  
  6139. /* Allowed flush values; see deflate() and inflate() below for details */
  6140. var Z_NO_FLUSH = 0;
  6141. var Z_PARTIAL_FLUSH = 1;
  6142. //var Z_SYNC_FLUSH = 2;
  6143. var Z_FULL_FLUSH = 3;
  6144. var Z_FINISH = 4;
  6145. var Z_BLOCK = 5;
  6146. //var Z_TREES = 6;
  6147.  
  6148.  
  6149. /* Return codes for the compression/decompression functions. Negative values
  6150. * are errors, positive values are used for special but normal events.
  6151. */
  6152. var Z_OK = 0;
  6153. var Z_STREAM_END = 1;
  6154. //var Z_NEED_DICT = 2;
  6155. //var Z_ERRNO = -1;
  6156. var Z_STREAM_ERROR = -2;
  6157. var Z_DATA_ERROR = -3;
  6158. //var Z_MEM_ERROR = -4;
  6159. var Z_BUF_ERROR = -5;
  6160. //var Z_VERSION_ERROR = -6;
  6161.  
  6162.  
  6163. /* compression levels */
  6164. //var Z_NO_COMPRESSION = 0;
  6165. //var Z_BEST_SPEED = 1;
  6166. //var Z_BEST_COMPRESSION = 9;
  6167. var Z_DEFAULT_COMPRESSION = -1;
  6168.  
  6169.  
  6170. var Z_FILTERED = 1;
  6171. var Z_HUFFMAN_ONLY = 2;
  6172. var Z_RLE = 3;
  6173. var Z_FIXED = 4;
  6174. var Z_DEFAULT_STRATEGY = 0;
  6175.  
  6176. /* Possible values of the data_type field (though see inflate()) */
  6177. //var Z_BINARY = 0;
  6178. //var Z_TEXT = 1;
  6179. //var Z_ASCII = 1; // = Z_TEXT
  6180. var Z_UNKNOWN = 2;
  6181.  
  6182.  
  6183. /* The deflate compression method */
  6184. var Z_DEFLATED = 8;
  6185.  
  6186. /*============================================================================*/
  6187.  
  6188.  
  6189. var MAX_MEM_LEVEL = 9;
  6190. /* Maximum value for memLevel in deflateInit2 */
  6191. var MAX_WBITS = 15;
  6192. /* 32K LZ77 window */
  6193. var DEF_MEM_LEVEL = 8;
  6194.  
  6195.  
  6196. var LENGTH_CODES = 29;
  6197. /* number of length codes, not counting the special END_BLOCK code */
  6198. var LITERALS = 256;
  6199. /* number of literal bytes 0..255 */
  6200. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  6201. /* number of Literal or Length codes, including the END_BLOCK code */
  6202. var D_CODES = 30;
  6203. /* number of distance codes */
  6204. var BL_CODES = 19;
  6205. /* number of codes used to transfer the bit lengths */
  6206. var HEAP_SIZE = 2 * L_CODES + 1;
  6207. /* maximum heap size */
  6208. var MAX_BITS = 15;
  6209. /* All codes must not exceed MAX_BITS bits */
  6210.  
  6211. var MIN_MATCH = 3;
  6212. var MAX_MATCH = 258;
  6213. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  6214.  
  6215. var PRESET_DICT = 0x20;
  6216.  
  6217. var INIT_STATE = 42;
  6218. var EXTRA_STATE = 69;
  6219. var NAME_STATE = 73;
  6220. var COMMENT_STATE = 91;
  6221. var HCRC_STATE = 103;
  6222. var BUSY_STATE = 113;
  6223. var FINISH_STATE = 666;
  6224.  
  6225. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  6226. var BS_BLOCK_DONE = 2; /* block flush performed */
  6227. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  6228. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  6229.  
  6230. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  6231.  
  6232. function err(strm, errorCode) {
  6233. strm.msg = msg[errorCode];
  6234. return errorCode;
  6235. }
  6236.  
  6237. function rank(f) {
  6238. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  6239. }
  6240.  
  6241. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  6242.  
  6243.  
  6244. /* =========================================================================
  6245. * Flush as much pending output as possible. All deflate() output goes
  6246. * through this function so some applications may wish to modify it
  6247. * to avoid allocating a large strm->output buffer and copying into it.
  6248. * (See also read_buf()).
  6249. */
  6250. function flush_pending(strm) {
  6251. var s = strm.state;
  6252.  
  6253. //_tr_flush_bits(s);
  6254. var len = s.pending;
  6255. if (len > strm.avail_out) {
  6256. len = strm.avail_out;
  6257. }
  6258. if (len === 0) { return; }
  6259.  
  6260. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  6261. strm.next_out += len;
  6262. s.pending_out += len;
  6263. strm.total_out += len;
  6264. strm.avail_out -= len;
  6265. s.pending -= len;
  6266. if (s.pending === 0) {
  6267. s.pending_out = 0;
  6268. }
  6269. }
  6270.  
  6271.  
  6272. function flush_block_only(s, last) {
  6273. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  6274. s.block_start = s.strstart;
  6275. flush_pending(s.strm);
  6276. }
  6277.  
  6278.  
  6279. function put_byte(s, b) {
  6280. s.pending_buf[s.pending++] = b;
  6281. }
  6282.  
  6283.  
  6284. /* =========================================================================
  6285. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  6286. * IN assertion: the stream state is correct and there is enough room in
  6287. * pending_buf.
  6288. */
  6289. function putShortMSB(s, b) {
  6290. // put_byte(s, (Byte)(b >> 8));
  6291. // put_byte(s, (Byte)(b & 0xff));
  6292. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  6293. s.pending_buf[s.pending++] = b & 0xff;
  6294. }
  6295.  
  6296.  
  6297. /* ===========================================================================
  6298. * Read a new buffer from the current input stream, update the adler32
  6299. * and total number of bytes read. All deflate() input goes through
  6300. * this function so some applications may wish to modify it to avoid
  6301. * allocating a large strm->input buffer and copying from it.
  6302. * (See also flush_pending()).
  6303. */
  6304. function read_buf(strm, buf, start, size) {
  6305. var len = strm.avail_in;
  6306.  
  6307. if (len > size) { len = size; }
  6308. if (len === 0) { return 0; }
  6309.  
  6310. strm.avail_in -= len;
  6311.  
  6312. // zmemcpy(buf, strm->next_in, len);
  6313. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  6314. if (strm.state.wrap === 1) {
  6315. strm.adler = adler32(strm.adler, buf, len, start);
  6316. }
  6317.  
  6318. else if (strm.state.wrap === 2) {
  6319. strm.adler = crc32(strm.adler, buf, len, start);
  6320. }
  6321.  
  6322. strm.next_in += len;
  6323. strm.total_in += len;
  6324.  
  6325. return len;
  6326. }
  6327.  
  6328.  
  6329. /* ===========================================================================
  6330. * Set match_start to the longest match starting at the given string and
  6331. * return its length. Matches shorter or equal to prev_length are discarded,
  6332. * in which case the result is equal to prev_length and match_start is
  6333. * garbage.
  6334. * IN assertions: cur_match is the head of the hash chain for the current
  6335. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  6336. * OUT assertion: the match length is not greater than s->lookahead.
  6337. */
  6338. function longest_match(s, cur_match) {
  6339. var chain_length = s.max_chain_length; /* max hash chain length */
  6340. var scan = s.strstart; /* current string */
  6341. var match; /* matched string */
  6342. var len; /* length of current match */
  6343. var best_len = s.prev_length; /* best match length so far */
  6344. var nice_match = s.nice_match; /* stop if match long enough */
  6345. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  6346. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  6347.  
  6348. var _win = s.window; // shortcut
  6349.  
  6350. var wmask = s.w_mask;
  6351. var prev = s.prev;
  6352.  
  6353. /* Stop when cur_match becomes <= limit. To simplify the code,
  6354. * we prevent matches with the string of window index 0.
  6355. */
  6356.  
  6357. var strend = s.strstart + MAX_MATCH;
  6358. var scan_end1 = _win[scan + best_len - 1];
  6359. var scan_end = _win[scan + best_len];
  6360.  
  6361. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  6362. * It is easy to get rid of this optimization if necessary.
  6363. */
  6364. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  6365.  
  6366. /* Do not waste too much time if we already have a good match: */
  6367. if (s.prev_length >= s.good_match) {
  6368. chain_length >>= 2;
  6369. }
  6370. /* Do not look for matches beyond the end of the input. This is necessary
  6371. * to make deflate deterministic.
  6372. */
  6373. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  6374.  
  6375. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  6376.  
  6377. do {
  6378. // Assert(cur_match < s->strstart, "no future");
  6379. match = cur_match;
  6380.  
  6381. /* Skip to next match if the match length cannot increase
  6382. * or if the match length is less than 2. Note that the checks below
  6383. * for insufficient lookahead only occur occasionally for performance
  6384. * reasons. Therefore uninitialized memory will be accessed, and
  6385. * conditional jumps will be made that depend on those values.
  6386. * However the length of the match is limited to the lookahead, so
  6387. * the output of deflate is not affected by the uninitialized values.
  6388. */
  6389.  
  6390. if (_win[match + best_len] !== scan_end ||
  6391. _win[match + best_len - 1] !== scan_end1 ||
  6392. _win[match] !== _win[scan] ||
  6393. _win[++match] !== _win[scan + 1]) {
  6394. continue;
  6395. }
  6396.  
  6397. /* The check at best_len-1 can be removed because it will be made
  6398. * again later. (This heuristic is not always a win.)
  6399. * It is not necessary to compare scan[2] and match[2] since they
  6400. * are always equal when the other bytes match, given that
  6401. * the hash keys are equal and that HASH_BITS >= 8.
  6402. */
  6403. scan += 2;
  6404. match++;
  6405. // Assert(*scan == *match, "match[2]?");
  6406.  
  6407. /* We check for insufficient lookahead only every 8th comparison;
  6408. * the 256th check will be made at strstart+258.
  6409. */
  6410. do {
  6411. /*jshint noempty:false*/
  6412. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6413. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6414. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6415. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6416. scan < strend);
  6417.  
  6418. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  6419.  
  6420. len = MAX_MATCH - (strend - scan);
  6421. scan = strend - MAX_MATCH;
  6422.  
  6423. if (len > best_len) {
  6424. s.match_start = cur_match;
  6425. best_len = len;
  6426. if (len >= nice_match) {
  6427. break;
  6428. }
  6429. scan_end1 = _win[scan + best_len - 1];
  6430. scan_end = _win[scan + best_len];
  6431. }
  6432. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  6433.  
  6434. if (best_len <= s.lookahead) {
  6435. return best_len;
  6436. }
  6437. return s.lookahead;
  6438. }
  6439.  
  6440.  
  6441. /* ===========================================================================
  6442. * Fill the window when the lookahead becomes insufficient.
  6443. * Updates strstart and lookahead.
  6444. *
  6445. * IN assertion: lookahead < MIN_LOOKAHEAD
  6446. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  6447. * At least one byte has been read, or avail_in == 0; reads are
  6448. * performed for at least two bytes (required for the zip translate_eol
  6449. * option -- not supported here).
  6450. */
  6451. function fill_window(s) {
  6452. var _w_size = s.w_size;
  6453. var p, n, m, more, str;
  6454.  
  6455. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  6456.  
  6457. do {
  6458. more = s.window_size - s.lookahead - s.strstart;
  6459.  
  6460. // JS ints have 32 bit, block below not needed
  6461. /* Deal with !@#$% 64K limit: */
  6462. //if (sizeof(int) <= 2) {
  6463. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  6464. // more = wsize;
  6465. //
  6466. // } else if (more == (unsigned)(-1)) {
  6467. // /* Very unlikely, but possible on 16 bit machine if
  6468. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  6469. // */
  6470. // more--;
  6471. // }
  6472. //}
  6473.  
  6474.  
  6475. /* If the window is almost full and there is insufficient lookahead,
  6476. * move the upper half to the lower one to make room in the upper half.
  6477. */
  6478. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  6479.  
  6480. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  6481. s.match_start -= _w_size;
  6482. s.strstart -= _w_size;
  6483. /* we now have strstart >= MAX_DIST */
  6484. s.block_start -= _w_size;
  6485.  
  6486. /* Slide the hash table (could be avoided with 32 bit values
  6487. at the expense of memory usage). We slide even when level == 0
  6488. to keep the hash table consistent if we switch back to level > 0
  6489. later. (Using level 0 permanently is not an optimal usage of
  6490. zlib, so we don't care about this pathological case.)
  6491. */
  6492.  
  6493. n = s.hash_size;
  6494. p = n;
  6495. do {
  6496. m = s.head[--p];
  6497. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  6498. } while (--n);
  6499.  
  6500. n = _w_size;
  6501. p = n;
  6502. do {
  6503. m = s.prev[--p];
  6504. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  6505. /* If n is not on any hash chain, prev[n] is garbage but
  6506. * its value will never be used.
  6507. */
  6508. } while (--n);
  6509.  
  6510. more += _w_size;
  6511. }
  6512. if (s.strm.avail_in === 0) {
  6513. break;
  6514. }
  6515.  
  6516. /* If there was no sliding:
  6517. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  6518. * more == window_size - lookahead - strstart
  6519. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  6520. * => more >= window_size - 2*WSIZE + 2
  6521. * In the BIG_MEM or MMAP case (not yet supported),
  6522. * window_size == input_size + MIN_LOOKAHEAD &&
  6523. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  6524. * Otherwise, window_size == 2*WSIZE so more >= 2.
  6525. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  6526. */
  6527. //Assert(more >= 2, "more < 2");
  6528. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  6529. s.lookahead += n;
  6530.  
  6531. /* Initialize the hash value now that we have some input: */
  6532. if (s.lookahead + s.insert >= MIN_MATCH) {
  6533. str = s.strstart - s.insert;
  6534. s.ins_h = s.window[str];
  6535.  
  6536. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  6537. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  6538. //#if MIN_MATCH != 3
  6539. // Call update_hash() MIN_MATCH-3 more times
  6540. //#endif
  6541. while (s.insert) {
  6542. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6543. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  6544.  
  6545. s.prev[str & s.w_mask] = s.head[s.ins_h];
  6546. s.head[s.ins_h] = str;
  6547. str++;
  6548. s.insert--;
  6549. if (s.lookahead + s.insert < MIN_MATCH) {
  6550. break;
  6551. }
  6552. }
  6553. }
  6554. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  6555. * but this is not important since only literal bytes will be emitted.
  6556. */
  6557.  
  6558. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  6559.  
  6560. /* If the WIN_INIT bytes after the end of the current data have never been
  6561. * written, then zero those bytes in order to avoid memory check reports of
  6562. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  6563. * the longest match routines. Update the high water mark for the next
  6564. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  6565. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  6566. */
  6567. // if (s.high_water < s.window_size) {
  6568. // var curr = s.strstart + s.lookahead;
  6569. // var init = 0;
  6570. //
  6571. // if (s.high_water < curr) {
  6572. // /* Previous high water mark below current data -- zero WIN_INIT
  6573. // * bytes or up to end of window, whichever is less.
  6574. // */
  6575. // init = s.window_size - curr;
  6576. // if (init > WIN_INIT)
  6577. // init = WIN_INIT;
  6578. // zmemzero(s->window + curr, (unsigned)init);
  6579. // s->high_water = curr + init;
  6580. // }
  6581. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  6582. // /* High water mark at or above current data, but below current data
  6583. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  6584. // * to end of window, whichever is less.
  6585. // */
  6586. // init = (ulg)curr + WIN_INIT - s->high_water;
  6587. // if (init > s->window_size - s->high_water)
  6588. // init = s->window_size - s->high_water;
  6589. // zmemzero(s->window + s->high_water, (unsigned)init);
  6590. // s->high_water += init;
  6591. // }
  6592. // }
  6593. //
  6594. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  6595. // "not enough room for search");
  6596. }
  6597.  
  6598. /* ===========================================================================
  6599. * Copy without compression as much as possible from the input stream, return
  6600. * the current block state.
  6601. * This function does not insert new strings in the dictionary since
  6602. * uncompressible data is probably not useful. This function is used
  6603. * only for the level=0 compression option.
  6604. * NOTE: this function should be optimized to avoid extra copying from
  6605. * window to pending_buf.
  6606. */
  6607. function deflate_stored(s, flush) {
  6608. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  6609. * to pending_buf_size, and each stored block has a 5 byte header:
  6610. */
  6611. var max_block_size = 0xffff;
  6612.  
  6613. if (max_block_size > s.pending_buf_size - 5) {
  6614. max_block_size = s.pending_buf_size - 5;
  6615. }
  6616.  
  6617. /* Copy as much as possible from input to output: */
  6618. for (;;) {
  6619. /* Fill the window as much as possible: */
  6620. if (s.lookahead <= 1) {
  6621.  
  6622. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  6623. // s->block_start >= (long)s->w_size, "slide too late");
  6624. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  6625. // s.block_start >= s.w_size)) {
  6626. // throw new Error("slide too late");
  6627. // }
  6628.  
  6629. fill_window(s);
  6630. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  6631. return BS_NEED_MORE;
  6632. }
  6633.  
  6634. if (s.lookahead === 0) {
  6635. break;
  6636. }
  6637. /* flush the current block */
  6638. }
  6639. //Assert(s->block_start >= 0L, "block gone");
  6640. // if (s.block_start < 0) throw new Error("block gone");
  6641.  
  6642. s.strstart += s.lookahead;
  6643. s.lookahead = 0;
  6644.  
  6645. /* Emit a stored block if pending_buf will be full: */
  6646. var max_start = s.block_start + max_block_size;
  6647.  
  6648. if (s.strstart === 0 || s.strstart >= max_start) {
  6649. /* strstart == 0 is possible when wraparound on 16-bit machine */
  6650. s.lookahead = s.strstart - max_start;
  6651. s.strstart = max_start;
  6652. /*** FLUSH_BLOCK(s, 0); ***/
  6653. flush_block_only(s, false);
  6654. if (s.strm.avail_out === 0) {
  6655. return BS_NEED_MORE;
  6656. }
  6657. /***/
  6658.  
  6659.  
  6660. }
  6661. /* Flush if we may have to slide, otherwise block_start may become
  6662. * negative and the data will be gone:
  6663. */
  6664. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  6665. /*** FLUSH_BLOCK(s, 0); ***/
  6666. flush_block_only(s, false);
  6667. if (s.strm.avail_out === 0) {
  6668. return BS_NEED_MORE;
  6669. }
  6670. /***/
  6671. }
  6672. }
  6673.  
  6674. s.insert = 0;
  6675.  
  6676. if (flush === Z_FINISH) {
  6677. /*** FLUSH_BLOCK(s, 1); ***/
  6678. flush_block_only(s, true);
  6679. if (s.strm.avail_out === 0) {
  6680. return BS_FINISH_STARTED;
  6681. }
  6682. /***/
  6683. return BS_FINISH_DONE;
  6684. }
  6685.  
  6686. if (s.strstart > s.block_start) {
  6687. /*** FLUSH_BLOCK(s, 0); ***/
  6688. flush_block_only(s, false);
  6689. if (s.strm.avail_out === 0) {
  6690. return BS_NEED_MORE;
  6691. }
  6692. /***/
  6693. }
  6694.  
  6695. return BS_NEED_MORE;
  6696. }
  6697.  
  6698. /* ===========================================================================
  6699. * Compress as much as possible from the input stream, return the current
  6700. * block state.
  6701. * This function does not perform lazy evaluation of matches and inserts
  6702. * new strings in the dictionary only for unmatched strings or for short
  6703. * matches. It is used only for the fast compression options.
  6704. */
  6705. function deflate_fast(s, flush) {
  6706. var hash_head; /* head of the hash chain */
  6707. var bflush; /* set if current block must be flushed */
  6708.  
  6709. for (;;) {
  6710. /* Make sure that we always have enough lookahead, except
  6711. * at the end of the input file. We need MAX_MATCH bytes
  6712. * for the next match, plus MIN_MATCH bytes to insert the
  6713. * string following the next match.
  6714. */
  6715. if (s.lookahead < MIN_LOOKAHEAD) {
  6716. fill_window(s);
  6717. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6718. return BS_NEED_MORE;
  6719. }
  6720. if (s.lookahead === 0) {
  6721. break; /* flush the current block */
  6722. }
  6723. }
  6724.  
  6725. /* Insert the string window[strstart .. strstart+2] in the
  6726. * dictionary, and set hash_head to the head of the hash chain:
  6727. */
  6728. hash_head = 0/*NIL*/;
  6729. if (s.lookahead >= MIN_MATCH) {
  6730. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6731. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6732. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6733. s.head[s.ins_h] = s.strstart;
  6734. /***/
  6735. }
  6736.  
  6737. /* Find the longest match, discarding those <= prev_length.
  6738. * At this point we have always match_length < MIN_MATCH
  6739. */
  6740. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  6741. /* To simplify the code, we prevent matches with the string
  6742. * of window index 0 (in particular we have to avoid a match
  6743. * of the string with itself at the start of the input file).
  6744. */
  6745. s.match_length = longest_match(s, hash_head);
  6746. /* longest_match() sets match_start */
  6747. }
  6748. if (s.match_length >= MIN_MATCH) {
  6749. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  6750.  
  6751. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  6752. s.match_length - MIN_MATCH, bflush); ***/
  6753. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  6754.  
  6755. s.lookahead -= s.match_length;
  6756.  
  6757. /* Insert new strings in the hash table only if the match length
  6758. * is not too large. This saves time but degrades compression.
  6759. */
  6760. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  6761. s.match_length--; /* string at strstart already in table */
  6762. do {
  6763. s.strstart++;
  6764. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6765. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6766. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6767. s.head[s.ins_h] = s.strstart;
  6768. /***/
  6769. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  6770. * always MIN_MATCH bytes ahead.
  6771. */
  6772. } while (--s.match_length !== 0);
  6773. s.strstart++;
  6774. } else
  6775. {
  6776. s.strstart += s.match_length;
  6777. s.match_length = 0;
  6778. s.ins_h = s.window[s.strstart];
  6779. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  6780. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  6781.  
  6782. //#if MIN_MATCH != 3
  6783. // Call UPDATE_HASH() MIN_MATCH-3 more times
  6784. //#endif
  6785. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  6786. * matter since it will be recomputed at next deflate call.
  6787. */
  6788. }
  6789. } else {
  6790. /* No match, output a literal byte */
  6791. //Tracevv((stderr,"%c", s.window[s.strstart]));
  6792. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6793. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6794.  
  6795. s.lookahead--;
  6796. s.strstart++;
  6797. }
  6798. if (bflush) {
  6799. /*** FLUSH_BLOCK(s, 0); ***/
  6800. flush_block_only(s, false);
  6801. if (s.strm.avail_out === 0) {
  6802. return BS_NEED_MORE;
  6803. }
  6804. /***/
  6805. }
  6806. }
  6807. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  6808. if (flush === Z_FINISH) {
  6809. /*** FLUSH_BLOCK(s, 1); ***/
  6810. flush_block_only(s, true);
  6811. if (s.strm.avail_out === 0) {
  6812. return BS_FINISH_STARTED;
  6813. }
  6814. /***/
  6815. return BS_FINISH_DONE;
  6816. }
  6817. if (s.last_lit) {
  6818. /*** FLUSH_BLOCK(s, 0); ***/
  6819. flush_block_only(s, false);
  6820. if (s.strm.avail_out === 0) {
  6821. return BS_NEED_MORE;
  6822. }
  6823. /***/
  6824. }
  6825. return BS_BLOCK_DONE;
  6826. }
  6827.  
  6828. /* ===========================================================================
  6829. * Same as above, but achieves better compression. We use a lazy
  6830. * evaluation for matches: a match is finally adopted only if there is
  6831. * no better match at the next window position.
  6832. */
  6833. function deflate_slow(s, flush) {
  6834. var hash_head; /* head of hash chain */
  6835. var bflush; /* set if current block must be flushed */
  6836.  
  6837. var max_insert;
  6838.  
  6839. /* Process the input block. */
  6840. for (;;) {
  6841. /* Make sure that we always have enough lookahead, except
  6842. * at the end of the input file. We need MAX_MATCH bytes
  6843. * for the next match, plus MIN_MATCH bytes to insert the
  6844. * string following the next match.
  6845. */
  6846. if (s.lookahead < MIN_LOOKAHEAD) {
  6847. fill_window(s);
  6848. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6849. return BS_NEED_MORE;
  6850. }
  6851. if (s.lookahead === 0) { break; } /* flush the current block */
  6852. }
  6853.  
  6854. /* Insert the string window[strstart .. strstart+2] in the
  6855. * dictionary, and set hash_head to the head of the hash chain:
  6856. */
  6857. hash_head = 0/*NIL*/;
  6858. if (s.lookahead >= MIN_MATCH) {
  6859. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6860. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6861. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6862. s.head[s.ins_h] = s.strstart;
  6863. /***/
  6864. }
  6865.  
  6866. /* Find the longest match, discarding those <= prev_length.
  6867. */
  6868. s.prev_length = s.match_length;
  6869. s.prev_match = s.match_start;
  6870. s.match_length = MIN_MATCH - 1;
  6871.  
  6872. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  6873. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  6874. /* To simplify the code, we prevent matches with the string
  6875. * of window index 0 (in particular we have to avoid a match
  6876. * of the string with itself at the start of the input file).
  6877. */
  6878. s.match_length = longest_match(s, hash_head);
  6879. /* longest_match() sets match_start */
  6880.  
  6881. if (s.match_length <= 5 &&
  6882. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  6883.  
  6884. /* If prev_match is also MIN_MATCH, match_start is garbage
  6885. * but we will ignore the current match anyway.
  6886. */
  6887. s.match_length = MIN_MATCH - 1;
  6888. }
  6889. }
  6890. /* If there was a match at the previous step and the current
  6891. * match is not better, output the previous match:
  6892. */
  6893. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  6894. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  6895. /* Do not insert strings in hash table beyond this. */
  6896.  
  6897. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  6898.  
  6899. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  6900. s.prev_length - MIN_MATCH, bflush);***/
  6901. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  6902. /* Insert in hash table all strings up to the end of the match.
  6903. * strstart-1 and strstart are already inserted. If there is not
  6904. * enough lookahead, the last two strings are not inserted in
  6905. * the hash table.
  6906. */
  6907. s.lookahead -= s.prev_length - 1;
  6908. s.prev_length -= 2;
  6909. do {
  6910. if (++s.strstart <= max_insert) {
  6911. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6912. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6913. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6914. s.head[s.ins_h] = s.strstart;
  6915. /***/
  6916. }
  6917. } while (--s.prev_length !== 0);
  6918. s.match_available = 0;
  6919. s.match_length = MIN_MATCH - 1;
  6920. s.strstart++;
  6921.  
  6922. if (bflush) {
  6923. /*** FLUSH_BLOCK(s, 0); ***/
  6924. flush_block_only(s, false);
  6925. if (s.strm.avail_out === 0) {
  6926. return BS_NEED_MORE;
  6927. }
  6928. /***/
  6929. }
  6930.  
  6931. } else if (s.match_available) {
  6932. /* If there was no match at the previous position, output a
  6933. * single literal. If there was a match but the current match
  6934. * is longer, truncate the previous match to a single literal.
  6935. */
  6936. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6937. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6938. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6939.  
  6940. if (bflush) {
  6941. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  6942. flush_block_only(s, false);
  6943. /***/
  6944. }
  6945. s.strstart++;
  6946. s.lookahead--;
  6947. if (s.strm.avail_out === 0) {
  6948. return BS_NEED_MORE;
  6949. }
  6950. } else {
  6951. /* There is no previous match to compare with, wait for
  6952. * the next step to decide.
  6953. */
  6954. s.match_available = 1;
  6955. s.strstart++;
  6956. s.lookahead--;
  6957. }
  6958. }
  6959. //Assert (flush != Z_NO_FLUSH, "no flush?");
  6960. if (s.match_available) {
  6961. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6962. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6963. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6964.  
  6965. s.match_available = 0;
  6966. }
  6967. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  6968. if (flush === Z_FINISH) {
  6969. /*** FLUSH_BLOCK(s, 1); ***/
  6970. flush_block_only(s, true);
  6971. if (s.strm.avail_out === 0) {
  6972. return BS_FINISH_STARTED;
  6973. }
  6974. /***/
  6975. return BS_FINISH_DONE;
  6976. }
  6977. if (s.last_lit) {
  6978. /*** FLUSH_BLOCK(s, 0); ***/
  6979. flush_block_only(s, false);
  6980. if (s.strm.avail_out === 0) {
  6981. return BS_NEED_MORE;
  6982. }
  6983. /***/
  6984. }
  6985.  
  6986. return BS_BLOCK_DONE;
  6987. }
  6988.  
  6989.  
  6990. /* ===========================================================================
  6991. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  6992. * one. Do not maintain a hash table. (It will be regenerated if this run of
  6993. * deflate switches away from Z_RLE.)
  6994. */
  6995. function deflate_rle(s, flush) {
  6996. var bflush; /* set if current block must be flushed */
  6997. var prev; /* byte at distance one to match */
  6998. var scan, strend; /* scan goes up to strend for length of run */
  6999.  
  7000. var _win = s.window;
  7001.  
  7002. for (;;) {
  7003. /* Make sure that we always have enough lookahead, except
  7004. * at the end of the input file. We need MAX_MATCH bytes
  7005. * for the longest run, plus one for the unrolled loop.
  7006. */
  7007. if (s.lookahead <= MAX_MATCH) {
  7008. fill_window(s);
  7009. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  7010. return BS_NEED_MORE;
  7011. }
  7012. if (s.lookahead === 0) { break; } /* flush the current block */
  7013. }
  7014.  
  7015. /* See how many times the previous byte repeats */
  7016. s.match_length = 0;
  7017. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  7018. scan = s.strstart - 1;
  7019. prev = _win[scan];
  7020. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  7021. strend = s.strstart + MAX_MATCH;
  7022. do {
  7023. /*jshint noempty:false*/
  7024. } while (prev === _win[++scan] && prev === _win[++scan] &&
  7025. prev === _win[++scan] && prev === _win[++scan] &&
  7026. prev === _win[++scan] && prev === _win[++scan] &&
  7027. prev === _win[++scan] && prev === _win[++scan] &&
  7028. scan < strend);
  7029. s.match_length = MAX_MATCH - (strend - scan);
  7030. if (s.match_length > s.lookahead) {
  7031. s.match_length = s.lookahead;
  7032. }
  7033. }
  7034. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  7035. }
  7036.  
  7037. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  7038. if (s.match_length >= MIN_MATCH) {
  7039. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  7040.  
  7041. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  7042. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  7043.  
  7044. s.lookahead -= s.match_length;
  7045. s.strstart += s.match_length;
  7046. s.match_length = 0;
  7047. } else {
  7048. /* No match, output a literal byte */
  7049. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7050. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7051. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7052.  
  7053. s.lookahead--;
  7054. s.strstart++;
  7055. }
  7056. if (bflush) {
  7057. /*** FLUSH_BLOCK(s, 0); ***/
  7058. flush_block_only(s, false);
  7059. if (s.strm.avail_out === 0) {
  7060. return BS_NEED_MORE;
  7061. }
  7062. /***/
  7063. }
  7064. }
  7065. s.insert = 0;
  7066. if (flush === Z_FINISH) {
  7067. /*** FLUSH_BLOCK(s, 1); ***/
  7068. flush_block_only(s, true);
  7069. if (s.strm.avail_out === 0) {
  7070. return BS_FINISH_STARTED;
  7071. }
  7072. /***/
  7073. return BS_FINISH_DONE;
  7074. }
  7075. if (s.last_lit) {
  7076. /*** FLUSH_BLOCK(s, 0); ***/
  7077. flush_block_only(s, false);
  7078. if (s.strm.avail_out === 0) {
  7079. return BS_NEED_MORE;
  7080. }
  7081. /***/
  7082. }
  7083. return BS_BLOCK_DONE;
  7084. }
  7085.  
  7086. /* ===========================================================================
  7087. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  7088. * (It will be regenerated if this run of deflate switches away from Huffman.)
  7089. */
  7090. function deflate_huff(s, flush) {
  7091. var bflush; /* set if current block must be flushed */
  7092.  
  7093. for (;;) {
  7094. /* Make sure that we have a literal to write. */
  7095. if (s.lookahead === 0) {
  7096. fill_window(s);
  7097. if (s.lookahead === 0) {
  7098. if (flush === Z_NO_FLUSH) {
  7099. return BS_NEED_MORE;
  7100. }
  7101. break; /* flush the current block */
  7102. }
  7103. }
  7104.  
  7105. /* Output a literal byte */
  7106. s.match_length = 0;
  7107. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7108. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7109. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7110. s.lookahead--;
  7111. s.strstart++;
  7112. if (bflush) {
  7113. /*** FLUSH_BLOCK(s, 0); ***/
  7114. flush_block_only(s, false);
  7115. if (s.strm.avail_out === 0) {
  7116. return BS_NEED_MORE;
  7117. }
  7118. /***/
  7119. }
  7120. }
  7121. s.insert = 0;
  7122. if (flush === Z_FINISH) {
  7123. /*** FLUSH_BLOCK(s, 1); ***/
  7124. flush_block_only(s, true);
  7125. if (s.strm.avail_out === 0) {
  7126. return BS_FINISH_STARTED;
  7127. }
  7128. /***/
  7129. return BS_FINISH_DONE;
  7130. }
  7131. if (s.last_lit) {
  7132. /*** FLUSH_BLOCK(s, 0); ***/
  7133. flush_block_only(s, false);
  7134. if (s.strm.avail_out === 0) {
  7135. return BS_NEED_MORE;
  7136. }
  7137. /***/
  7138. }
  7139. return BS_BLOCK_DONE;
  7140. }
  7141.  
  7142. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  7143. * the desired pack level (0..9). The values given below have been tuned to
  7144. * exclude worst case performance for pathological files. Better values may be
  7145. * found for specific files.
  7146. */
  7147. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  7148. this.good_length = good_length;
  7149. this.max_lazy = max_lazy;
  7150. this.nice_length = nice_length;
  7151. this.max_chain = max_chain;
  7152. this.func = func;
  7153. }
  7154.  
  7155. var configuration_table;
  7156.  
  7157. configuration_table = [
  7158. /* good lazy nice chain */
  7159. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  7160. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  7161. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  7162. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  7163.  
  7164. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  7165. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  7166. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  7167. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  7168. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  7169. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  7170. ];
  7171.  
  7172.  
  7173. /* ===========================================================================
  7174. * Initialize the "longest match" routines for a new zlib stream
  7175. */
  7176. function lm_init(s) {
  7177. s.window_size = 2 * s.w_size;
  7178.  
  7179. /*** CLEAR_HASH(s); ***/
  7180. zero(s.head); // Fill with NIL (= 0);
  7181.  
  7182. /* Set the default configuration parameters:
  7183. */
  7184. s.max_lazy_match = configuration_table[s.level].max_lazy;
  7185. s.good_match = configuration_table[s.level].good_length;
  7186. s.nice_match = configuration_table[s.level].nice_length;
  7187. s.max_chain_length = configuration_table[s.level].max_chain;
  7188.  
  7189. s.strstart = 0;
  7190. s.block_start = 0;
  7191. s.lookahead = 0;
  7192. s.insert = 0;
  7193. s.match_length = s.prev_length = MIN_MATCH - 1;
  7194. s.match_available = 0;
  7195. s.ins_h = 0;
  7196. }
  7197.  
  7198.  
  7199. function DeflateState() {
  7200. this.strm = null; /* pointer back to this zlib stream */
  7201. this.status = 0; /* as the name implies */
  7202. this.pending_buf = null; /* output still pending */
  7203. this.pending_buf_size = 0; /* size of pending_buf */
  7204. this.pending_out = 0; /* next pending byte to output to the stream */
  7205. this.pending = 0; /* nb of bytes in the pending buffer */
  7206. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  7207. this.gzhead = null; /* gzip header information to write */
  7208. this.gzindex = 0; /* where in extra, name, or comment */
  7209. this.method = Z_DEFLATED; /* can only be DEFLATED */
  7210. this.last_flush = -1; /* value of flush param for previous deflate call */
  7211.  
  7212. this.w_size = 0; /* LZ77 window size (32K by default) */
  7213. this.w_bits = 0; /* log2(w_size) (8..16) */
  7214. this.w_mask = 0; /* w_size - 1 */
  7215.  
  7216. this.window = null;
  7217. /* Sliding window. Input bytes are read into the second half of the window,
  7218. * and move to the first half later to keep a dictionary of at least wSize
  7219. * bytes. With this organization, matches are limited to a distance of
  7220. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  7221. * performed with a length multiple of the block size.
  7222. */
  7223.  
  7224. this.window_size = 0;
  7225. /* Actual size of window: 2*wSize, except when the user input buffer
  7226. * is directly used as sliding window.
  7227. */
  7228.  
  7229. this.prev = null;
  7230. /* Link to older string with same hash index. To limit the size of this
  7231. * array to 64K, this link is maintained only for the last 32K strings.
  7232. * An index in this array is thus a window index modulo 32K.
  7233. */
  7234.  
  7235. this.head = null; /* Heads of the hash chains or NIL. */
  7236.  
  7237. this.ins_h = 0; /* hash index of string to be inserted */
  7238. this.hash_size = 0; /* number of elements in hash table */
  7239. this.hash_bits = 0; /* log2(hash_size) */
  7240. this.hash_mask = 0; /* hash_size-1 */
  7241.  
  7242. this.hash_shift = 0;
  7243. /* Number of bits by which ins_h must be shifted at each input
  7244. * step. It must be such that after MIN_MATCH steps, the oldest
  7245. * byte no longer takes part in the hash key, that is:
  7246. * hash_shift * MIN_MATCH >= hash_bits
  7247. */
  7248.  
  7249. this.block_start = 0;
  7250. /* Window position at the beginning of the current output block. Gets
  7251. * negative when the window is moved backwards.
  7252. */
  7253.  
  7254. this.match_length = 0; /* length of best match */
  7255. this.prev_match = 0; /* previous match */
  7256. this.match_available = 0; /* set if previous match exists */
  7257. this.strstart = 0; /* start of string to insert */
  7258. this.match_start = 0; /* start of matching string */
  7259. this.lookahead = 0; /* number of valid bytes ahead in window */
  7260.  
  7261. this.prev_length = 0;
  7262. /* Length of the best match at previous step. Matches not greater than this
  7263. * are discarded. This is used in the lazy match evaluation.
  7264. */
  7265.  
  7266. this.max_chain_length = 0;
  7267. /* To speed up deflation, hash chains are never searched beyond this
  7268. * length. A higher limit improves compression ratio but degrades the
  7269. * speed.
  7270. */
  7271.  
  7272. this.max_lazy_match = 0;
  7273. /* Attempt to find a better match only when the current match is strictly
  7274. * smaller than this value. This mechanism is used only for compression
  7275. * levels >= 4.
  7276. */
  7277. // That's alias to max_lazy_match, don't use directly
  7278. //this.max_insert_length = 0;
  7279. /* Insert new strings in the hash table only if the match length is not
  7280. * greater than this length. This saves time but degrades compression.
  7281. * max_insert_length is used only for compression levels <= 3.
  7282. */
  7283.  
  7284. this.level = 0; /* compression level (1..9) */
  7285. this.strategy = 0; /* favor or force Huffman coding*/
  7286.  
  7287. this.good_match = 0;
  7288. /* Use a faster search when the previous match is longer than this */
  7289.  
  7290. this.nice_match = 0; /* Stop searching when current match exceeds this */
  7291.  
  7292. /* used by trees.c: */
  7293.  
  7294. /* Didn't use ct_data typedef below to suppress compiler warning */
  7295.  
  7296. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  7297. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  7298. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  7299.  
  7300. // Use flat array of DOUBLE size, with interleaved fata,
  7301. // because JS does not support effective
  7302. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  7303. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  7304. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  7305. zero(this.dyn_ltree);
  7306. zero(this.dyn_dtree);
  7307. zero(this.bl_tree);
  7308.  
  7309. this.l_desc = null; /* desc. for literal tree */
  7310. this.d_desc = null; /* desc. for distance tree */
  7311. this.bl_desc = null; /* desc. for bit length tree */
  7312.  
  7313. //ush bl_count[MAX_BITS+1];
  7314. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  7315. /* number of codes at each bit length for an optimal tree */
  7316.  
  7317. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  7318. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  7319. zero(this.heap);
  7320.  
  7321. this.heap_len = 0; /* number of elements in the heap */
  7322. this.heap_max = 0; /* element of largest frequency */
  7323. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  7324. * The same heap array is used to build all trees.
  7325. */
  7326.  
  7327. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  7328. zero(this.depth);
  7329. /* Depth of each subtree used as tie breaker for trees of equal frequency
  7330. */
  7331.  
  7332. this.l_buf = 0; /* buffer index for literals or lengths */
  7333.  
  7334. this.lit_bufsize = 0;
  7335. /* Size of match buffer for literals/lengths. There are 4 reasons for
  7336. * limiting lit_bufsize to 64K:
  7337. * - frequencies can be kept in 16 bit counters
  7338. * - if compression is not successful for the first block, all input
  7339. * data is still in the window so we can still emit a stored block even
  7340. * when input comes from standard input. (This can also be done for
  7341. * all blocks if lit_bufsize is not greater than 32K.)
  7342. * - if compression is not successful for a file smaller than 64K, we can
  7343. * even emit a stored file instead of a stored block (saving 5 bytes).
  7344. * This is applicable only for zip (not gzip or zlib).
  7345. * - creating new Huffman trees less frequently may not provide fast
  7346. * adaptation to changes in the input data statistics. (Take for
  7347. * example a binary file with poorly compressible code followed by
  7348. * a highly compressible string table.) Smaller buffer sizes give
  7349. * fast adaptation but have of course the overhead of transmitting
  7350. * trees more frequently.
  7351. * - I can't count above 4
  7352. */
  7353.  
  7354. this.last_lit = 0; /* running index in l_buf */
  7355.  
  7356. this.d_buf = 0;
  7357. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  7358. * the same number of elements. To use different lengths, an extra flag
  7359. * array would be necessary.
  7360. */
  7361.  
  7362. this.opt_len = 0; /* bit length of current block with optimal trees */
  7363. this.static_len = 0; /* bit length of current block with static trees */
  7364. this.matches = 0; /* number of string matches in current block */
  7365. this.insert = 0; /* bytes at end of window left to insert */
  7366.  
  7367.  
  7368. this.bi_buf = 0;
  7369. /* Output buffer. bits are inserted starting at the bottom (least
  7370. * significant bits).
  7371. */
  7372. this.bi_valid = 0;
  7373. /* Number of valid bits in bi_buf. All bits above the last valid bit
  7374. * are always zero.
  7375. */
  7376.  
  7377. // Used for window memory init. We safely ignore it for JS. That makes
  7378. // sense only for pointers and memory check tools.
  7379. //this.high_water = 0;
  7380. /* High water mark offset in window for initialized bytes -- bytes above
  7381. * this are set to zero in order to avoid memory check warnings when
  7382. * longest match routines access bytes past the input. This is then
  7383. * updated to the new high water mark.
  7384. */
  7385. }
  7386.  
  7387.  
  7388. function deflateResetKeep(strm) {
  7389. var s;
  7390.  
  7391. if (!strm || !strm.state) {
  7392. return err(strm, Z_STREAM_ERROR);
  7393. }
  7394.  
  7395. strm.total_in = strm.total_out = 0;
  7396. strm.data_type = Z_UNKNOWN;
  7397.  
  7398. s = strm.state;
  7399. s.pending = 0;
  7400. s.pending_out = 0;
  7401.  
  7402. if (s.wrap < 0) {
  7403. s.wrap = -s.wrap;
  7404. /* was made negative by deflate(..., Z_FINISH); */
  7405. }
  7406. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  7407. strm.adler = (s.wrap === 2) ?
  7408. 0 // crc32(0, Z_NULL, 0)
  7409. :
  7410. 1; // adler32(0, Z_NULL, 0)
  7411. s.last_flush = Z_NO_FLUSH;
  7412. trees._tr_init(s);
  7413. return Z_OK;
  7414. }
  7415.  
  7416.  
  7417. function deflateReset(strm) {
  7418. var ret = deflateResetKeep(strm);
  7419. if (ret === Z_OK) {
  7420. lm_init(strm.state);
  7421. }
  7422. return ret;
  7423. }
  7424.  
  7425.  
  7426. function deflateSetHeader(strm, head) {
  7427. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7428. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  7429. strm.state.gzhead = head;
  7430. return Z_OK;
  7431. }
  7432.  
  7433.  
  7434. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  7435. if (!strm) { // === Z_NULL
  7436. return Z_STREAM_ERROR;
  7437. }
  7438. var wrap = 1;
  7439.  
  7440. if (level === Z_DEFAULT_COMPRESSION) {
  7441. level = 6;
  7442. }
  7443.  
  7444. if (windowBits < 0) { /* suppress zlib wrapper */
  7445. wrap = 0;
  7446. windowBits = -windowBits;
  7447. }
  7448.  
  7449. else if (windowBits > 15) {
  7450. wrap = 2; /* write gzip wrapper instead */
  7451. windowBits -= 16;
  7452. }
  7453.  
  7454.  
  7455. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  7456. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  7457. strategy < 0 || strategy > Z_FIXED) {
  7458. return err(strm, Z_STREAM_ERROR);
  7459. }
  7460.  
  7461.  
  7462. if (windowBits === 8) {
  7463. windowBits = 9;
  7464. }
  7465. /* until 256-byte window bug fixed */
  7466.  
  7467. var s = new DeflateState();
  7468.  
  7469. strm.state = s;
  7470. s.strm = strm;
  7471.  
  7472. s.wrap = wrap;
  7473. s.gzhead = null;
  7474. s.w_bits = windowBits;
  7475. s.w_size = 1 << s.w_bits;
  7476. s.w_mask = s.w_size - 1;
  7477.  
  7478. s.hash_bits = memLevel + 7;
  7479. s.hash_size = 1 << s.hash_bits;
  7480. s.hash_mask = s.hash_size - 1;
  7481. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  7482.  
  7483. s.window = new utils.Buf8(s.w_size * 2);
  7484. s.head = new utils.Buf16(s.hash_size);
  7485. s.prev = new utils.Buf16(s.w_size);
  7486.  
  7487. // Don't need mem init magic for JS.
  7488. //s.high_water = 0; /* nothing written to s->window yet */
  7489.  
  7490. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  7491.  
  7492. s.pending_buf_size = s.lit_bufsize * 4;
  7493.  
  7494. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  7495. //s->pending_buf = (uchf *) overlay;
  7496. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  7497.  
  7498. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  7499. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  7500. s.d_buf = 1 * s.lit_bufsize;
  7501.  
  7502. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  7503. s.l_buf = (1 + 2) * s.lit_bufsize;
  7504.  
  7505. s.level = level;
  7506. s.strategy = strategy;
  7507. s.method = method;
  7508.  
  7509. return deflateReset(strm);
  7510. }
  7511.  
  7512. function deflateInit(strm, level) {
  7513. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  7514. }
  7515.  
  7516.  
  7517. function deflate(strm, flush) {
  7518. var old_flush, s;
  7519. var beg, val; // for gzip header write only
  7520.  
  7521. if (!strm || !strm.state ||
  7522. flush > Z_BLOCK || flush < 0) {
  7523. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  7524. }
  7525.  
  7526. s = strm.state;
  7527.  
  7528. if (!strm.output ||
  7529. (!strm.input && strm.avail_in !== 0) ||
  7530. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  7531. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  7532. }
  7533.  
  7534. s.strm = strm; /* just in case */
  7535. old_flush = s.last_flush;
  7536. s.last_flush = flush;
  7537.  
  7538. /* Write the header */
  7539. if (s.status === INIT_STATE) {
  7540.  
  7541. if (s.wrap === 2) { // GZIP header
  7542. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7543. put_byte(s, 31);
  7544. put_byte(s, 139);
  7545. put_byte(s, 8);
  7546. if (!s.gzhead) { // s->gzhead == Z_NULL
  7547. put_byte(s, 0);
  7548. put_byte(s, 0);
  7549. put_byte(s, 0);
  7550. put_byte(s, 0);
  7551. put_byte(s, 0);
  7552. put_byte(s, s.level === 9 ? 2 :
  7553. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7554. 4 : 0));
  7555. put_byte(s, OS_CODE);
  7556. s.status = BUSY_STATE;
  7557. }
  7558. else {
  7559. put_byte(s, (s.gzhead.text ? 1 : 0) +
  7560. (s.gzhead.hcrc ? 2 : 0) +
  7561. (!s.gzhead.extra ? 0 : 4) +
  7562. (!s.gzhead.name ? 0 : 8) +
  7563. (!s.gzhead.comment ? 0 : 16)
  7564. );
  7565. put_byte(s, s.gzhead.time & 0xff);
  7566. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  7567. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  7568. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  7569. put_byte(s, s.level === 9 ? 2 :
  7570. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7571. 4 : 0));
  7572. put_byte(s, s.gzhead.os & 0xff);
  7573. if (s.gzhead.extra && s.gzhead.extra.length) {
  7574. put_byte(s, s.gzhead.extra.length & 0xff);
  7575. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  7576. }
  7577. if (s.gzhead.hcrc) {
  7578. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  7579. }
  7580. s.gzindex = 0;
  7581. s.status = EXTRA_STATE;
  7582. }
  7583. }
  7584. else // DEFLATE header
  7585. {
  7586. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  7587. var level_flags = -1;
  7588.  
  7589. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  7590. level_flags = 0;
  7591. } else if (s.level < 6) {
  7592. level_flags = 1;
  7593. } else if (s.level === 6) {
  7594. level_flags = 2;
  7595. } else {
  7596. level_flags = 3;
  7597. }
  7598. header |= (level_flags << 6);
  7599. if (s.strstart !== 0) { header |= PRESET_DICT; }
  7600. header += 31 - (header % 31);
  7601.  
  7602. s.status = BUSY_STATE;
  7603. putShortMSB(s, header);
  7604.  
  7605. /* Save the adler32 of the preset dictionary: */
  7606. if (s.strstart !== 0) {
  7607. putShortMSB(s, strm.adler >>> 16);
  7608. putShortMSB(s, strm.adler & 0xffff);
  7609. }
  7610. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  7611. }
  7612. }
  7613.  
  7614. //#ifdef GZIP
  7615. if (s.status === EXTRA_STATE) {
  7616. if (s.gzhead.extra/* != Z_NULL*/) {
  7617. beg = s.pending; /* start of bytes to update crc */
  7618.  
  7619. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  7620. if (s.pending === s.pending_buf_size) {
  7621. if (s.gzhead.hcrc && s.pending > beg) {
  7622. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7623. }
  7624. flush_pending(strm);
  7625. beg = s.pending;
  7626. if (s.pending === s.pending_buf_size) {
  7627. break;
  7628. }
  7629. }
  7630. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  7631. s.gzindex++;
  7632. }
  7633. if (s.gzhead.hcrc && s.pending > beg) {
  7634. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7635. }
  7636. if (s.gzindex === s.gzhead.extra.length) {
  7637. s.gzindex = 0;
  7638. s.status = NAME_STATE;
  7639. }
  7640. }
  7641. else {
  7642. s.status = NAME_STATE;
  7643. }
  7644. }
  7645. if (s.status === NAME_STATE) {
  7646. if (s.gzhead.name/* != Z_NULL*/) {
  7647. beg = s.pending; /* start of bytes to update crc */
  7648. //int val;
  7649.  
  7650. do {
  7651. if (s.pending === s.pending_buf_size) {
  7652. if (s.gzhead.hcrc && s.pending > beg) {
  7653. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7654. }
  7655. flush_pending(strm);
  7656. beg = s.pending;
  7657. if (s.pending === s.pending_buf_size) {
  7658. val = 1;
  7659. break;
  7660. }
  7661. }
  7662. // JS specific: little magic to add zero terminator to end of string
  7663. if (s.gzindex < s.gzhead.name.length) {
  7664. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  7665. } else {
  7666. val = 0;
  7667. }
  7668. put_byte(s, val);
  7669. } while (val !== 0);
  7670.  
  7671. if (s.gzhead.hcrc && s.pending > beg) {
  7672. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7673. }
  7674. if (val === 0) {
  7675. s.gzindex = 0;
  7676. s.status = COMMENT_STATE;
  7677. }
  7678. }
  7679. else {
  7680. s.status = COMMENT_STATE;
  7681. }
  7682. }
  7683. if (s.status === COMMENT_STATE) {
  7684. if (s.gzhead.comment/* != Z_NULL*/) {
  7685. beg = s.pending; /* start of bytes to update crc */
  7686. //int val;
  7687.  
  7688. do {
  7689. if (s.pending === s.pending_buf_size) {
  7690. if (s.gzhead.hcrc && s.pending > beg) {
  7691. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7692. }
  7693. flush_pending(strm);
  7694. beg = s.pending;
  7695. if (s.pending === s.pending_buf_size) {
  7696. val = 1;
  7697. break;
  7698. }
  7699. }
  7700. // JS specific: little magic to add zero terminator to end of string
  7701. if (s.gzindex < s.gzhead.comment.length) {
  7702. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  7703. } else {
  7704. val = 0;
  7705. }
  7706. put_byte(s, val);
  7707. } while (val !== 0);
  7708.  
  7709. if (s.gzhead.hcrc && s.pending > beg) {
  7710. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7711. }
  7712. if (val === 0) {
  7713. s.status = HCRC_STATE;
  7714. }
  7715. }
  7716. else {
  7717. s.status = HCRC_STATE;
  7718. }
  7719. }
  7720. if (s.status === HCRC_STATE) {
  7721. if (s.gzhead.hcrc) {
  7722. if (s.pending + 2 > s.pending_buf_size) {
  7723. flush_pending(strm);
  7724. }
  7725. if (s.pending + 2 <= s.pending_buf_size) {
  7726. put_byte(s, strm.adler & 0xff);
  7727. put_byte(s, (strm.adler >> 8) & 0xff);
  7728. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7729. s.status = BUSY_STATE;
  7730. }
  7731. }
  7732. else {
  7733. s.status = BUSY_STATE;
  7734. }
  7735. }
  7736. //#endif
  7737.  
  7738. /* Flush as much pending output as possible */
  7739. if (s.pending !== 0) {
  7740. flush_pending(strm);
  7741. if (strm.avail_out === 0) {
  7742. /* Since avail_out is 0, deflate will be called again with
  7743. * more output space, but possibly with both pending and
  7744. * avail_in equal to zero. There won't be anything to do,
  7745. * but this is not an error situation so make sure we
  7746. * return OK instead of BUF_ERROR at next call of deflate:
  7747. */
  7748. s.last_flush = -1;
  7749. return Z_OK;
  7750. }
  7751.  
  7752. /* Make sure there is something to do and avoid duplicate consecutive
  7753. * flushes. For repeated and useless calls with Z_FINISH, we keep
  7754. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  7755. */
  7756. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  7757. flush !== Z_FINISH) {
  7758. return err(strm, Z_BUF_ERROR);
  7759. }
  7760.  
  7761. /* User must not provide more input after the first FINISH: */
  7762. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  7763. return err(strm, Z_BUF_ERROR);
  7764. }
  7765.  
  7766. /* Start a new block or continue the current one.
  7767. */
  7768. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  7769. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  7770. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  7771. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  7772. configuration_table[s.level].func(s, flush));
  7773.  
  7774. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  7775. s.status = FINISH_STATE;
  7776. }
  7777. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  7778. if (strm.avail_out === 0) {
  7779. s.last_flush = -1;
  7780. /* avoid BUF_ERROR next call, see above */
  7781. }
  7782. return Z_OK;
  7783. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  7784. * of deflate should use the same flush parameter to make sure
  7785. * that the flush is complete. So we don't have to output an
  7786. * empty block here, this will be done at next call. This also
  7787. * ensures that for a very small output buffer, we emit at most
  7788. * one empty block.
  7789. */
  7790. }
  7791. if (bstate === BS_BLOCK_DONE) {
  7792. if (flush === Z_PARTIAL_FLUSH) {
  7793. trees._tr_align(s);
  7794. }
  7795. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  7796.  
  7797. trees._tr_stored_block(s, 0, 0, false);
  7798. /* For a full flush, this empty block will be recognized
  7799. * as a special marker by inflate_sync().
  7800. */
  7801. if (flush === Z_FULL_FLUSH) {
  7802. /*** CLEAR_HASH(s); ***/ /* forget history */
  7803. zero(s.head); // Fill with NIL (= 0);
  7804.  
  7805. if (s.lookahead === 0) {
  7806. s.strstart = 0;
  7807. s.block_start = 0;
  7808. s.insert = 0;
  7809. }
  7810. }
  7811. }
  7812. flush_pending(strm);
  7813. if (strm.avail_out === 0) {
  7814. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  7815. return Z_OK;
  7816. }
  7817. }
  7818. }
  7819. //Assert(strm->avail_out > 0, "bug2");
  7820. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  7821.  
  7822. if (flush !== Z_FINISH) { return Z_OK; }
  7823. if (s.wrap <= 0) { return Z_STREAM_END; }
  7824.  
  7825. /* Write the trailer */
  7826. if (s.wrap === 2) {
  7827. put_byte(s, strm.adler & 0xff);
  7828. put_byte(s, (strm.adler >> 8) & 0xff);
  7829. put_byte(s, (strm.adler >> 16) & 0xff);
  7830. put_byte(s, (strm.adler >> 24) & 0xff);
  7831. put_byte(s, strm.total_in & 0xff);
  7832. put_byte(s, (strm.total_in >> 8) & 0xff);
  7833. put_byte(s, (strm.total_in >> 16) & 0xff);
  7834. put_byte(s, (strm.total_in >> 24) & 0xff);
  7835. }
  7836. else
  7837. {
  7838. putShortMSB(s, strm.adler >>> 16);
  7839. putShortMSB(s, strm.adler & 0xffff);
  7840. }
  7841.  
  7842. flush_pending(strm);
  7843. /* If avail_out is zero, the application will call deflate again
  7844. * to flush the rest.
  7845. */
  7846. if (s.wrap > 0) { s.wrap = -s.wrap; }
  7847. /* write the trailer only once! */
  7848. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  7849. }
  7850.  
  7851. function deflateEnd(strm) {
  7852. var status;
  7853.  
  7854. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7855. return Z_STREAM_ERROR;
  7856. }
  7857.  
  7858. status = strm.state.status;
  7859. if (status !== INIT_STATE &&
  7860. status !== EXTRA_STATE &&
  7861. status !== NAME_STATE &&
  7862. status !== COMMENT_STATE &&
  7863. status !== HCRC_STATE &&
  7864. status !== BUSY_STATE &&
  7865. status !== FINISH_STATE
  7866. ) {
  7867. return err(strm, Z_STREAM_ERROR);
  7868. }
  7869.  
  7870. strm.state = null;
  7871.  
  7872. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  7873. }
  7874.  
  7875.  
  7876. /* =========================================================================
  7877. * Initializes the compression dictionary from the given byte
  7878. * sequence without producing any compressed output.
  7879. */
  7880. function deflateSetDictionary(strm, dictionary) {
  7881. var dictLength = dictionary.length;
  7882.  
  7883. var s;
  7884. var str, n;
  7885. var wrap;
  7886. var avail;
  7887. var next;
  7888. var input;
  7889. var tmpDict;
  7890.  
  7891. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7892. return Z_STREAM_ERROR;
  7893. }
  7894.  
  7895. s = strm.state;
  7896. wrap = s.wrap;
  7897.  
  7898. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  7899. return Z_STREAM_ERROR;
  7900. }
  7901.  
  7902. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  7903. if (wrap === 1) {
  7904. /* adler32(strm->adler, dictionary, dictLength); */
  7905. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  7906. }
  7907.  
  7908. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  7909.  
  7910. /* if dictionary would fill window, just replace the history */
  7911. if (dictLength >= s.w_size) {
  7912. if (wrap === 0) { /* already empty otherwise */
  7913. /*** CLEAR_HASH(s); ***/
  7914. zero(s.head); // Fill with NIL (= 0);
  7915. s.strstart = 0;
  7916. s.block_start = 0;
  7917. s.insert = 0;
  7918. }
  7919. /* use the tail */
  7920. // dictionary = dictionary.slice(dictLength - s.w_size);
  7921. tmpDict = new utils.Buf8(s.w_size);
  7922. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  7923. dictionary = tmpDict;
  7924. dictLength = s.w_size;
  7925. }
  7926. /* insert dictionary into window and hash */
  7927. avail = strm.avail_in;
  7928. next = strm.next_in;
  7929. input = strm.input;
  7930. strm.avail_in = dictLength;
  7931. strm.next_in = 0;
  7932. strm.input = dictionary;
  7933. fill_window(s);
  7934. while (s.lookahead >= MIN_MATCH) {
  7935. str = s.strstart;
  7936. n = s.lookahead - (MIN_MATCH - 1);
  7937. do {
  7938. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  7939. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  7940.  
  7941. s.prev[str & s.w_mask] = s.head[s.ins_h];
  7942.  
  7943. s.head[s.ins_h] = str;
  7944. str++;
  7945. } while (--n);
  7946. s.strstart = str;
  7947. s.lookahead = MIN_MATCH - 1;
  7948. fill_window(s);
  7949. }
  7950. s.strstart += s.lookahead;
  7951. s.block_start = s.strstart;
  7952. s.insert = s.lookahead;
  7953. s.lookahead = 0;
  7954. s.match_length = s.prev_length = MIN_MATCH - 1;
  7955. s.match_available = 0;
  7956. strm.next_in = next;
  7957. strm.input = input;
  7958. strm.avail_in = avail;
  7959. s.wrap = wrap;
  7960. return Z_OK;
  7961. }
  7962.  
  7963.  
  7964. exports.deflateInit = deflateInit;
  7965. exports.deflateInit2 = deflateInit2;
  7966. exports.deflateReset = deflateReset;
  7967. exports.deflateResetKeep = deflateResetKeep;
  7968. exports.deflateSetHeader = deflateSetHeader;
  7969. exports.deflate = deflate;
  7970. exports.deflateEnd = deflateEnd;
  7971. exports.deflateSetDictionary = deflateSetDictionary;
  7972. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  7973.  
  7974. /* Not implemented
  7975. exports.deflateBound = deflateBound;
  7976. exports.deflateCopy = deflateCopy;
  7977. exports.deflateParams = deflateParams;
  7978. exports.deflatePending = deflatePending;
  7979. exports.deflatePrime = deflatePrime;
  7980. exports.deflateTune = deflateTune;
  7981. */
  7982.  
  7983. },{"../utils/common":62,"./adler32":64,"./crc32":66,"./messages":72,"./trees":73}],68:[function(require,module,exports){
  7984. 'use strict';
  7985.  
  7986.  
  7987. function GZheader() {
  7988. /* true if compressed data believed to be text */
  7989. this.text = 0;
  7990. /* modification time */
  7991. this.time = 0;
  7992. /* extra flags (not used when writing a gzip file) */
  7993. this.xflags = 0;
  7994. /* operating system */
  7995. this.os = 0;
  7996. /* pointer to extra field or Z_NULL if none */
  7997. this.extra = null;
  7998. /* extra field length (valid if extra != Z_NULL) */
  7999. this.extra_len = 0; // Actually, we don't need it in JS,
  8000. // but leave for few code modifications
  8001.  
  8002. //
  8003. // Setup limits is not necessary because in js we should not preallocate memory
  8004. // for inflate use constant limit in 65536 bytes
  8005. //
  8006.  
  8007. /* space at extra (only when reading header) */
  8008. // this.extra_max = 0;
  8009. /* pointer to zero-terminated file name or Z_NULL */
  8010. this.name = '';
  8011. /* space at name (only when reading header) */
  8012. // this.name_max = 0;
  8013. /* pointer to zero-terminated comment or Z_NULL */
  8014. this.comment = '';
  8015. /* space at comment (only when reading header) */
  8016. // this.comm_max = 0;
  8017. /* true if there was or will be a header crc */
  8018. this.hcrc = 0;
  8019. /* true when done reading gzip header (not used when writing a gzip file) */
  8020. this.done = false;
  8021. }
  8022.  
  8023. module.exports = GZheader;
  8024.  
  8025. },{}],69:[function(require,module,exports){
  8026. 'use strict';
  8027.  
  8028. // See state defs from inflate.js
  8029. var BAD = 30; /* got a data error -- remain here until reset */
  8030. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  8031.  
  8032. /*
  8033. Decode literal, length, and distance codes and write out the resulting
  8034. literal and match bytes until either not enough input or output is
  8035. available, an end-of-block is encountered, or a data error is encountered.
  8036. When large enough input and output buffers are supplied to inflate(), for
  8037. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  8038. inflate execution time is spent in this routine.
  8039.  
  8040. Entry assumptions:
  8041.  
  8042. state.mode === LEN
  8043. strm.avail_in >= 6
  8044. strm.avail_out >= 258
  8045. start >= strm.avail_out
  8046. state.bits < 8
  8047.  
  8048. On return, state.mode is one of:
  8049.  
  8050. LEN -- ran out of enough output space or enough available input
  8051. TYPE -- reached end of block code, inflate() to interpret next block
  8052. BAD -- error in block data
  8053.  
  8054. Notes:
  8055.  
  8056. - The maximum input bits used by a length/distance pair is 15 bits for the
  8057. length code, 5 bits for the length extra, 15 bits for the distance code,
  8058. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  8059. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  8060. checking for available input while decoding.
  8061.  
  8062. - The maximum bytes that a single length/distance pair can output is 258
  8063. bytes, which is the maximum length that can be coded. inflate_fast()
  8064. requires strm.avail_out >= 258 for each loop to avoid checking for
  8065. output space.
  8066. */
  8067. module.exports = function inflate_fast(strm, start) {
  8068. var state;
  8069. var _in; /* local strm.input */
  8070. var last; /* have enough input while in < last */
  8071. var _out; /* local strm.output */
  8072. var beg; /* inflate()'s initial strm.output */
  8073. var end; /* while out < end, enough space available */
  8074. //#ifdef INFLATE_STRICT
  8075. var dmax; /* maximum distance from zlib header */
  8076. //#endif
  8077. var wsize; /* window size or zero if not using window */
  8078. var whave; /* valid bytes in the window */
  8079. var wnext; /* window write index */
  8080. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  8081. var s_window; /* allocated sliding window, if wsize != 0 */
  8082. var hold; /* local strm.hold */
  8083. var bits; /* local strm.bits */
  8084. var lcode; /* local strm.lencode */
  8085. var dcode; /* local strm.distcode */
  8086. var lmask; /* mask for first level of length codes */
  8087. var dmask; /* mask for first level of distance codes */
  8088. var here; /* retrieved table entry */
  8089. var op; /* code bits, operation, extra bits, or */
  8090. /* window position, window bytes to copy */
  8091. var len; /* match length, unused bytes */
  8092. var dist; /* match distance */
  8093. var from; /* where to copy match from */
  8094. var from_source;
  8095.  
  8096.  
  8097. var input, output; // JS specific, because we have no pointers
  8098.  
  8099. /* copy state to local variables */
  8100. state = strm.state;
  8101. //here = state.here;
  8102. _in = strm.next_in;
  8103. input = strm.input;
  8104. last = _in + (strm.avail_in - 5);
  8105. _out = strm.next_out;
  8106. output = strm.output;
  8107. beg = _out - (start - strm.avail_out);
  8108. end = _out + (strm.avail_out - 257);
  8109. //#ifdef INFLATE_STRICT
  8110. dmax = state.dmax;
  8111. //#endif
  8112. wsize = state.wsize;
  8113. whave = state.whave;
  8114. wnext = state.wnext;
  8115. s_window = state.window;
  8116. hold = state.hold;
  8117. bits = state.bits;
  8118. lcode = state.lencode;
  8119. dcode = state.distcode;
  8120. lmask = (1 << state.lenbits) - 1;
  8121. dmask = (1 << state.distbits) - 1;
  8122.  
  8123.  
  8124. /* decode literals and length/distances until end-of-block or not enough
  8125. input data or output space */
  8126.  
  8127. top:
  8128. do {
  8129. if (bits < 15) {
  8130. hold += input[_in++] << bits;
  8131. bits += 8;
  8132. hold += input[_in++] << bits;
  8133. bits += 8;
  8134. }
  8135.  
  8136. here = lcode[hold & lmask];
  8137.  
  8138. dolen:
  8139. for (;;) { // Goto emulation
  8140. op = here >>> 24/*here.bits*/;
  8141. hold >>>= op;
  8142. bits -= op;
  8143. op = (here >>> 16) & 0xff/*here.op*/;
  8144. if (op === 0) { /* literal */
  8145. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8146. // "inflate: literal '%c'\n" :
  8147. // "inflate: literal 0x%02x\n", here.val));
  8148. output[_out++] = here & 0xffff/*here.val*/;
  8149. }
  8150. else if (op & 16) { /* length base */
  8151. len = here & 0xffff/*here.val*/;
  8152. op &= 15; /* number of extra bits */
  8153. if (op) {
  8154. if (bits < op) {
  8155. hold += input[_in++] << bits;
  8156. bits += 8;
  8157. }
  8158. len += hold & ((1 << op) - 1);
  8159. hold >>>= op;
  8160. bits -= op;
  8161. }
  8162. //Tracevv((stderr, "inflate: length %u\n", len));
  8163. if (bits < 15) {
  8164. hold += input[_in++] << bits;
  8165. bits += 8;
  8166. hold += input[_in++] << bits;
  8167. bits += 8;
  8168. }
  8169. here = dcode[hold & dmask];
  8170.  
  8171. dodist:
  8172. for (;;) { // goto emulation
  8173. op = here >>> 24/*here.bits*/;
  8174. hold >>>= op;
  8175. bits -= op;
  8176. op = (here >>> 16) & 0xff/*here.op*/;
  8177.  
  8178. if (op & 16) { /* distance base */
  8179. dist = here & 0xffff/*here.val*/;
  8180. op &= 15; /* number of extra bits */
  8181. if (bits < op) {
  8182. hold += input[_in++] << bits;
  8183. bits += 8;
  8184. if (bits < op) {
  8185. hold += input[_in++] << bits;
  8186. bits += 8;
  8187. }
  8188. }
  8189. dist += hold & ((1 << op) - 1);
  8190. //#ifdef INFLATE_STRICT
  8191. if (dist > dmax) {
  8192. strm.msg = 'invalid distance too far back';
  8193. state.mode = BAD;
  8194. break top;
  8195. }
  8196. //#endif
  8197. hold >>>= op;
  8198. bits -= op;
  8199. //Tracevv((stderr, "inflate: distance %u\n", dist));
  8200. op = _out - beg; /* max distance in output */
  8201. if (dist > op) { /* see if copy from window */
  8202. op = dist - op; /* distance back in window */
  8203. if (op > whave) {
  8204. if (state.sane) {
  8205. strm.msg = 'invalid distance too far back';
  8206. state.mode = BAD;
  8207. break top;
  8208. }
  8209.  
  8210. // (!) This block is disabled in zlib defailts,
  8211. // don't enable it for binary compatibility
  8212. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  8213. // if (len <= op - whave) {
  8214. // do {
  8215. // output[_out++] = 0;
  8216. // } while (--len);
  8217. // continue top;
  8218. // }
  8219. // len -= op - whave;
  8220. // do {
  8221. // output[_out++] = 0;
  8222. // } while (--op > whave);
  8223. // if (op === 0) {
  8224. // from = _out - dist;
  8225. // do {
  8226. // output[_out++] = output[from++];
  8227. // } while (--len);
  8228. // continue top;
  8229. // }
  8230. //#endif
  8231. }
  8232. from = 0; // window index
  8233. from_source = s_window;
  8234. if (wnext === 0) { /* very common case */
  8235. from += wsize - op;
  8236. if (op < len) { /* some from window */
  8237. len -= op;
  8238. do {
  8239. output[_out++] = s_window[from++];
  8240. } while (--op);
  8241. from = _out - dist; /* rest from output */
  8242. from_source = output;
  8243. }
  8244. }
  8245. else if (wnext < op) { /* wrap around window */
  8246. from += wsize + wnext - op;
  8247. op -= wnext;
  8248. if (op < len) { /* some from end of window */
  8249. len -= op;
  8250. do {
  8251. output[_out++] = s_window[from++];
  8252. } while (--op);
  8253. from = 0;
  8254. if (wnext < len) { /* some from start of window */
  8255. op = wnext;
  8256. len -= op;
  8257. do {
  8258. output[_out++] = s_window[from++];
  8259. } while (--op);
  8260. from = _out - dist; /* rest from output */
  8261. from_source = output;
  8262. }
  8263. }
  8264. }
  8265. else { /* contiguous in window */
  8266. from += wnext - op;
  8267. if (op < len) { /* some from window */
  8268. len -= op;
  8269. do {
  8270. output[_out++] = s_window[from++];
  8271. } while (--op);
  8272. from = _out - dist; /* rest from output */
  8273. from_source = output;
  8274. }
  8275. }
  8276. while (len > 2) {
  8277. output[_out++] = from_source[from++];
  8278. output[_out++] = from_source[from++];
  8279. output[_out++] = from_source[from++];
  8280. len -= 3;
  8281. }
  8282. if (len) {
  8283. output[_out++] = from_source[from++];
  8284. if (len > 1) {
  8285. output[_out++] = from_source[from++];
  8286. }
  8287. }
  8288. }
  8289. else {
  8290. from = _out - dist; /* copy direct from output */
  8291. do { /* minimum length is three */
  8292. output[_out++] = output[from++];
  8293. output[_out++] = output[from++];
  8294. output[_out++] = output[from++];
  8295. len -= 3;
  8296. } while (len > 2);
  8297. if (len) {
  8298. output[_out++] = output[from++];
  8299. if (len > 1) {
  8300. output[_out++] = output[from++];
  8301. }
  8302. }
  8303. }
  8304. }
  8305. else if ((op & 64) === 0) { /* 2nd level distance code */
  8306. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8307. continue dodist;
  8308. }
  8309. else {
  8310. strm.msg = 'invalid distance code';
  8311. state.mode = BAD;
  8312. break top;
  8313. }
  8314.  
  8315. break; // need to emulate goto via "continue"
  8316. }
  8317. }
  8318. else if ((op & 64) === 0) { /* 2nd level length code */
  8319. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8320. continue dolen;
  8321. }
  8322. else if (op & 32) { /* end-of-block */
  8323. //Tracevv((stderr, "inflate: end of block\n"));
  8324. state.mode = TYPE;
  8325. break top;
  8326. }
  8327. else {
  8328. strm.msg = 'invalid literal/length code';
  8329. state.mode = BAD;
  8330. break top;
  8331. }
  8332.  
  8333. break; // need to emulate goto via "continue"
  8334. }
  8335. } while (_in < last && _out < end);
  8336.  
  8337. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  8338. len = bits >> 3;
  8339. _in -= len;
  8340. bits -= len << 3;
  8341. hold &= (1 << bits) - 1;
  8342.  
  8343. /* update state and return */
  8344. strm.next_in = _in;
  8345. strm.next_out = _out;
  8346. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  8347. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  8348. state.hold = hold;
  8349. state.bits = bits;
  8350. return;
  8351. };
  8352.  
  8353. },{}],70:[function(require,module,exports){
  8354. 'use strict';
  8355.  
  8356.  
  8357. var utils = require('../utils/common');
  8358. var adler32 = require('./adler32');
  8359. var crc32 = require('./crc32');
  8360. var inflate_fast = require('./inffast');
  8361. var inflate_table = require('./inftrees');
  8362.  
  8363. var CODES = 0;
  8364. var LENS = 1;
  8365. var DISTS = 2;
  8366.  
  8367. /* Public constants ==========================================================*/
  8368. /* ===========================================================================*/
  8369.  
  8370.  
  8371. /* Allowed flush values; see deflate() and inflate() below for details */
  8372. //var Z_NO_FLUSH = 0;
  8373. //var Z_PARTIAL_FLUSH = 1;
  8374. //var Z_SYNC_FLUSH = 2;
  8375. //var Z_FULL_FLUSH = 3;
  8376. var Z_FINISH = 4;
  8377. var Z_BLOCK = 5;
  8378. var Z_TREES = 6;
  8379.  
  8380.  
  8381. /* Return codes for the compression/decompression functions. Negative values
  8382. * are errors, positive values are used for special but normal events.
  8383. */
  8384. var Z_OK = 0;
  8385. var Z_STREAM_END = 1;
  8386. var Z_NEED_DICT = 2;
  8387. //var Z_ERRNO = -1;
  8388. var Z_STREAM_ERROR = -2;
  8389. var Z_DATA_ERROR = -3;
  8390. var Z_MEM_ERROR = -4;
  8391. var Z_BUF_ERROR = -5;
  8392. //var Z_VERSION_ERROR = -6;
  8393.  
  8394. /* The deflate compression method */
  8395. var Z_DEFLATED = 8;
  8396.  
  8397.  
  8398. /* STATES ====================================================================*/
  8399. /* ===========================================================================*/
  8400.  
  8401.  
  8402. var HEAD = 1; /* i: waiting for magic header */
  8403. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  8404. var TIME = 3; /* i: waiting for modification time (gzip) */
  8405. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  8406. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  8407. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  8408. var NAME = 7; /* i: waiting for end of file name (gzip) */
  8409. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  8410. var HCRC = 9; /* i: waiting for header crc (gzip) */
  8411. var DICTID = 10; /* i: waiting for dictionary check value */
  8412. var DICT = 11; /* waiting for inflateSetDictionary() call */
  8413. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  8414. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  8415. var STORED = 14; /* i: waiting for stored size (length and complement) */
  8416. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  8417. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  8418. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  8419. var LENLENS = 18; /* i: waiting for code length code lengths */
  8420. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  8421. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  8422. var LEN = 21; /* i: waiting for length/lit/eob code */
  8423. var LENEXT = 22; /* i: waiting for length extra bits */
  8424. var DIST = 23; /* i: waiting for distance code */
  8425. var DISTEXT = 24; /* i: waiting for distance extra bits */
  8426. var MATCH = 25; /* o: waiting for output space to copy string */
  8427. var LIT = 26; /* o: waiting for output space to write literal */
  8428. var CHECK = 27; /* i: waiting for 32-bit check value */
  8429. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  8430. var DONE = 29; /* finished check, done -- remain here until reset */
  8431. var BAD = 30; /* got a data error -- remain here until reset */
  8432. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  8433. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  8434.  
  8435. /* ===========================================================================*/
  8436.  
  8437.  
  8438.  
  8439. var ENOUGH_LENS = 852;
  8440. var ENOUGH_DISTS = 592;
  8441. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  8442.  
  8443. var MAX_WBITS = 15;
  8444. /* 32K LZ77 window */
  8445. var DEF_WBITS = MAX_WBITS;
  8446.  
  8447.  
  8448. function zswap32(q) {
  8449. return (((q >>> 24) & 0xff) +
  8450. ((q >>> 8) & 0xff00) +
  8451. ((q & 0xff00) << 8) +
  8452. ((q & 0xff) << 24));
  8453. }
  8454.  
  8455.  
  8456. function InflateState() {
  8457. this.mode = 0; /* current inflate mode */
  8458. this.last = false; /* true if processing last block */
  8459. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  8460. this.havedict = false; /* true if dictionary provided */
  8461. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  8462. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  8463. this.check = 0; /* protected copy of check value */
  8464. this.total = 0; /* protected copy of output count */
  8465. // TODO: may be {}
  8466. this.head = null; /* where to save gzip header information */
  8467.  
  8468. /* sliding window */
  8469. this.wbits = 0; /* log base 2 of requested window size */
  8470. this.wsize = 0; /* window size or zero if not using window */
  8471. this.whave = 0; /* valid bytes in the window */
  8472. this.wnext = 0; /* window write index */
  8473. this.window = null; /* allocated sliding window, if needed */
  8474.  
  8475. /* bit accumulator */
  8476. this.hold = 0; /* input bit accumulator */
  8477. this.bits = 0; /* number of bits in "in" */
  8478.  
  8479. /* for string and stored block copying */
  8480. this.length = 0; /* literal or length of data to copy */
  8481. this.offset = 0; /* distance back to copy string from */
  8482.  
  8483. /* for table and code decoding */
  8484. this.extra = 0; /* extra bits needed */
  8485.  
  8486. /* fixed and dynamic code tables */
  8487. this.lencode = null; /* starting table for length/literal codes */
  8488. this.distcode = null; /* starting table for distance codes */
  8489. this.lenbits = 0; /* index bits for lencode */
  8490. this.distbits = 0; /* index bits for distcode */
  8491.  
  8492. /* dynamic table building */
  8493. this.ncode = 0; /* number of code length code lengths */
  8494. this.nlen = 0; /* number of length code lengths */
  8495. this.ndist = 0; /* number of distance code lengths */
  8496. this.have = 0; /* number of code lengths in lens[] */
  8497. this.next = null; /* next available space in codes[] */
  8498.  
  8499. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  8500. this.work = new utils.Buf16(288); /* work area for code table building */
  8501.  
  8502. /*
  8503. because we don't have pointers in js, we use lencode and distcode directly
  8504. as buffers so we don't need codes
  8505. */
  8506. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  8507. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  8508. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  8509. this.sane = 0; /* if false, allow invalid distance too far */
  8510. this.back = 0; /* bits back of last unprocessed length/lit */
  8511. this.was = 0; /* initial length of match */
  8512. }
  8513.  
  8514. function inflateResetKeep(strm) {
  8515. var state;
  8516.  
  8517. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8518. state = strm.state;
  8519. strm.total_in = strm.total_out = state.total = 0;
  8520. strm.msg = ''; /*Z_NULL*/
  8521. if (state.wrap) { /* to support ill-conceived Java test suite */
  8522. strm.adler = state.wrap & 1;
  8523. }
  8524. state.mode = HEAD;
  8525. state.last = 0;
  8526. state.havedict = 0;
  8527. state.dmax = 32768;
  8528. state.head = null/*Z_NULL*/;
  8529. state.hold = 0;
  8530. state.bits = 0;
  8531. //state.lencode = state.distcode = state.next = state.codes;
  8532. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  8533. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  8534.  
  8535. state.sane = 1;
  8536. state.back = -1;
  8537. //Tracev((stderr, "inflate: reset\n"));
  8538. return Z_OK;
  8539. }
  8540.  
  8541. function inflateReset(strm) {
  8542. var state;
  8543.  
  8544. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8545. state = strm.state;
  8546. state.wsize = 0;
  8547. state.whave = 0;
  8548. state.wnext = 0;
  8549. return inflateResetKeep(strm);
  8550.  
  8551. }
  8552.  
  8553. function inflateReset2(strm, windowBits) {
  8554. var wrap;
  8555. var state;
  8556.  
  8557. /* get the state */
  8558. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8559. state = strm.state;
  8560.  
  8561. /* extract wrap request from windowBits parameter */
  8562. if (windowBits < 0) {
  8563. wrap = 0;
  8564. windowBits = -windowBits;
  8565. }
  8566. else {
  8567. wrap = (windowBits >> 4) + 1;
  8568. if (windowBits < 48) {
  8569. windowBits &= 15;
  8570. }
  8571. }
  8572.  
  8573. /* set number of window bits, free window if different */
  8574. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  8575. return Z_STREAM_ERROR;
  8576. }
  8577. if (state.window !== null && state.wbits !== windowBits) {
  8578. state.window = null;
  8579. }
  8580.  
  8581. /* update state and reset the rest of it */
  8582. state.wrap = wrap;
  8583. state.wbits = windowBits;
  8584. return inflateReset(strm);
  8585. }
  8586.  
  8587. function inflateInit2(strm, windowBits) {
  8588. var ret;
  8589. var state;
  8590.  
  8591. if (!strm) { return Z_STREAM_ERROR; }
  8592. //strm.msg = Z_NULL; /* in case we return an error */
  8593.  
  8594. state = new InflateState();
  8595.  
  8596. //if (state === Z_NULL) return Z_MEM_ERROR;
  8597. //Tracev((stderr, "inflate: allocated\n"));
  8598. strm.state = state;
  8599. state.window = null/*Z_NULL*/;
  8600. ret = inflateReset2(strm, windowBits);
  8601. if (ret !== Z_OK) {
  8602. strm.state = null/*Z_NULL*/;
  8603. }
  8604. return ret;
  8605. }
  8606.  
  8607. function inflateInit(strm) {
  8608. return inflateInit2(strm, DEF_WBITS);
  8609. }
  8610.  
  8611.  
  8612. /*
  8613. Return state with length and distance decoding tables and index sizes set to
  8614. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  8615. If BUILDFIXED is defined, then instead this routine builds the tables the
  8616. first time it's called, and returns those tables the first time and
  8617. thereafter. This reduces the size of the code by about 2K bytes, in
  8618. exchange for a little execution time. However, BUILDFIXED should not be
  8619. used for threaded applications, since the rewriting of the tables and virgin
  8620. may not be thread-safe.
  8621. */
  8622. var virgin = true;
  8623.  
  8624. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  8625.  
  8626. function fixedtables(state) {
  8627. /* build fixed huffman tables if first call (may not be thread safe) */
  8628. if (virgin) {
  8629. var sym;
  8630.  
  8631. lenfix = new utils.Buf32(512);
  8632. distfix = new utils.Buf32(32);
  8633.  
  8634. /* literal/length table */
  8635. sym = 0;
  8636. while (sym < 144) { state.lens[sym++] = 8; }
  8637. while (sym < 256) { state.lens[sym++] = 9; }
  8638. while (sym < 280) { state.lens[sym++] = 7; }
  8639. while (sym < 288) { state.lens[sym++] = 8; }
  8640.  
  8641. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  8642.  
  8643. /* distance table */
  8644. sym = 0;
  8645. while (sym < 32) { state.lens[sym++] = 5; }
  8646.  
  8647. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  8648.  
  8649. /* do this just once */
  8650. virgin = false;
  8651. }
  8652.  
  8653. state.lencode = lenfix;
  8654. state.lenbits = 9;
  8655. state.distcode = distfix;
  8656. state.distbits = 5;
  8657. }
  8658.  
  8659.  
  8660. /*
  8661. Update the window with the last wsize (normally 32K) bytes written before
  8662. returning. If window does not exist yet, create it. This is only called
  8663. when a window is already in use, or when output has been written during this
  8664. inflate call, but the end of the deflate stream has not been reached yet.
  8665. It is also called to create a window for dictionary data when a dictionary
  8666. is loaded.
  8667.  
  8668. Providing output buffers larger than 32K to inflate() should provide a speed
  8669. advantage, since only the last 32K of output is copied to the sliding window
  8670. upon return from inflate(), and since all distances after the first 32K of
  8671. output will fall in the output data, making match copies simpler and faster.
  8672. The advantage may be dependent on the size of the processor's data caches.
  8673. */
  8674. function updatewindow(strm, src, end, copy) {
  8675. var dist;
  8676. var state = strm.state;
  8677.  
  8678. /* if it hasn't been done already, allocate space for the window */
  8679. if (state.window === null) {
  8680. state.wsize = 1 << state.wbits;
  8681. state.wnext = 0;
  8682. state.whave = 0;
  8683.  
  8684. state.window = new utils.Buf8(state.wsize);
  8685. }
  8686.  
  8687. /* copy state->wsize or less output bytes into the circular window */
  8688. if (copy >= state.wsize) {
  8689. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  8690. state.wnext = 0;
  8691. state.whave = state.wsize;
  8692. }
  8693. else {
  8694. dist = state.wsize - state.wnext;
  8695. if (dist > copy) {
  8696. dist = copy;
  8697. }
  8698. //zmemcpy(state->window + state->wnext, end - copy, dist);
  8699. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  8700. copy -= dist;
  8701. if (copy) {
  8702. //zmemcpy(state->window, end - copy, copy);
  8703. utils.arraySet(state.window, src, end - copy, copy, 0);
  8704. state.wnext = copy;
  8705. state.whave = state.wsize;
  8706. }
  8707. else {
  8708. state.wnext += dist;
  8709. if (state.wnext === state.wsize) { state.wnext = 0; }
  8710. if (state.whave < state.wsize) { state.whave += dist; }
  8711. }
  8712. }
  8713. return 0;
  8714. }
  8715.  
  8716. function inflate(strm, flush) {
  8717. var state;
  8718. var input, output; // input/output buffers
  8719. var next; /* next input INDEX */
  8720. var put; /* next output INDEX */
  8721. var have, left; /* available input and output */
  8722. var hold; /* bit buffer */
  8723. var bits; /* bits in bit buffer */
  8724. var _in, _out; /* save starting available input and output */
  8725. var copy; /* number of stored or match bytes to copy */
  8726. var from; /* where to copy match bytes from */
  8727. var from_source;
  8728. var here = 0; /* current decoding table entry */
  8729. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  8730. //var last; /* parent table entry */
  8731. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  8732. var len; /* length to copy for repeats, bits to drop */
  8733. var ret; /* return code */
  8734. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  8735. var opts;
  8736.  
  8737. var n; // temporary var for NEED_BITS
  8738.  
  8739. var order = /* permutation of code lengths */
  8740. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  8741.  
  8742.  
  8743. if (!strm || !strm.state || !strm.output ||
  8744. (!strm.input && strm.avail_in !== 0)) {
  8745. return Z_STREAM_ERROR;
  8746. }
  8747.  
  8748. state = strm.state;
  8749. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  8750.  
  8751.  
  8752. //--- LOAD() ---
  8753. put = strm.next_out;
  8754. output = strm.output;
  8755. left = strm.avail_out;
  8756. next = strm.next_in;
  8757. input = strm.input;
  8758. have = strm.avail_in;
  8759. hold = state.hold;
  8760. bits = state.bits;
  8761. //---
  8762.  
  8763. _in = have;
  8764. _out = left;
  8765. ret = Z_OK;
  8766.  
  8767. inf_leave: // goto emulation
  8768. for (;;) {
  8769. switch (state.mode) {
  8770. case HEAD:
  8771. if (state.wrap === 0) {
  8772. state.mode = TYPEDO;
  8773. break;
  8774. }
  8775. //=== NEEDBITS(16);
  8776. while (bits < 16) {
  8777. if (have === 0) { break inf_leave; }
  8778. have--;
  8779. hold += input[next++] << bits;
  8780. bits += 8;
  8781. }
  8782. //===//
  8783. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  8784. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  8785. //=== CRC2(state.check, hold);
  8786. hbuf[0] = hold & 0xff;
  8787. hbuf[1] = (hold >>> 8) & 0xff;
  8788. state.check = crc32(state.check, hbuf, 2, 0);
  8789. //===//
  8790.  
  8791. //=== INITBITS();
  8792. hold = 0;
  8793. bits = 0;
  8794. //===//
  8795. state.mode = FLAGS;
  8796. break;
  8797. }
  8798. state.flags = 0; /* expect zlib header */
  8799. if (state.head) {
  8800. state.head.done = false;
  8801. }
  8802. if (!(state.wrap & 1) || /* check if zlib header allowed */
  8803. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  8804. strm.msg = 'incorrect header check';
  8805. state.mode = BAD;
  8806. break;
  8807. }
  8808. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  8809. strm.msg = 'unknown compression method';
  8810. state.mode = BAD;
  8811. break;
  8812. }
  8813. //--- DROPBITS(4) ---//
  8814. hold >>>= 4;
  8815. bits -= 4;
  8816. //---//
  8817. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  8818. if (state.wbits === 0) {
  8819. state.wbits = len;
  8820. }
  8821. else if (len > state.wbits) {
  8822. strm.msg = 'invalid window size';
  8823. state.mode = BAD;
  8824. break;
  8825. }
  8826. state.dmax = 1 << len;
  8827. //Tracev((stderr, "inflate: zlib header ok\n"));
  8828. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8829. state.mode = hold & 0x200 ? DICTID : TYPE;
  8830. //=== INITBITS();
  8831. hold = 0;
  8832. bits = 0;
  8833. //===//
  8834. break;
  8835. case FLAGS:
  8836. //=== NEEDBITS(16); */
  8837. while (bits < 16) {
  8838. if (have === 0) { break inf_leave; }
  8839. have--;
  8840. hold += input[next++] << bits;
  8841. bits += 8;
  8842. }
  8843. //===//
  8844. state.flags = hold;
  8845. if ((state.flags & 0xff) !== Z_DEFLATED) {
  8846. strm.msg = 'unknown compression method';
  8847. state.mode = BAD;
  8848. break;
  8849. }
  8850. if (state.flags & 0xe000) {
  8851. strm.msg = 'unknown header flags set';
  8852. state.mode = BAD;
  8853. break;
  8854. }
  8855. if (state.head) {
  8856. state.head.text = ((hold >> 8) & 1);
  8857. }
  8858. if (state.flags & 0x0200) {
  8859. //=== CRC2(state.check, hold);
  8860. hbuf[0] = hold & 0xff;
  8861. hbuf[1] = (hold >>> 8) & 0xff;
  8862. state.check = crc32(state.check, hbuf, 2, 0);
  8863. //===//
  8864. }
  8865. //=== INITBITS();
  8866. hold = 0;
  8867. bits = 0;
  8868. //===//
  8869. state.mode = TIME;
  8870. /* falls through */
  8871. case TIME:
  8872. //=== NEEDBITS(32); */
  8873. while (bits < 32) {
  8874. if (have === 0) { break inf_leave; }
  8875. have--;
  8876. hold += input[next++] << bits;
  8877. bits += 8;
  8878. }
  8879. //===//
  8880. if (state.head) {
  8881. state.head.time = hold;
  8882. }
  8883. if (state.flags & 0x0200) {
  8884. //=== CRC4(state.check, hold)
  8885. hbuf[0] = hold & 0xff;
  8886. hbuf[1] = (hold >>> 8) & 0xff;
  8887. hbuf[2] = (hold >>> 16) & 0xff;
  8888. hbuf[3] = (hold >>> 24) & 0xff;
  8889. state.check = crc32(state.check, hbuf, 4, 0);
  8890. //===
  8891. }
  8892. //=== INITBITS();
  8893. hold = 0;
  8894. bits = 0;
  8895. //===//
  8896. state.mode = OS;
  8897. /* falls through */
  8898. case OS:
  8899. //=== NEEDBITS(16); */
  8900. while (bits < 16) {
  8901. if (have === 0) { break inf_leave; }
  8902. have--;
  8903. hold += input[next++] << bits;
  8904. bits += 8;
  8905. }
  8906. //===//
  8907. if (state.head) {
  8908. state.head.xflags = (hold & 0xff);
  8909. state.head.os = (hold >> 8);
  8910. }
  8911. if (state.flags & 0x0200) {
  8912. //=== CRC2(state.check, hold);
  8913. hbuf[0] = hold & 0xff;
  8914. hbuf[1] = (hold >>> 8) & 0xff;
  8915. state.check = crc32(state.check, hbuf, 2, 0);
  8916. //===//
  8917. }
  8918. //=== INITBITS();
  8919. hold = 0;
  8920. bits = 0;
  8921. //===//
  8922. state.mode = EXLEN;
  8923. /* falls through */
  8924. case EXLEN:
  8925. if (state.flags & 0x0400) {
  8926. //=== NEEDBITS(16); */
  8927. while (bits < 16) {
  8928. if (have === 0) { break inf_leave; }
  8929. have--;
  8930. hold += input[next++] << bits;
  8931. bits += 8;
  8932. }
  8933. //===//
  8934. state.length = hold;
  8935. if (state.head) {
  8936. state.head.extra_len = hold;
  8937. }
  8938. if (state.flags & 0x0200) {
  8939. //=== CRC2(state.check, hold);
  8940. hbuf[0] = hold & 0xff;
  8941. hbuf[1] = (hold >>> 8) & 0xff;
  8942. state.check = crc32(state.check, hbuf, 2, 0);
  8943. //===//
  8944. }
  8945. //=== INITBITS();
  8946. hold = 0;
  8947. bits = 0;
  8948. //===//
  8949. }
  8950. else if (state.head) {
  8951. state.head.extra = null/*Z_NULL*/;
  8952. }
  8953. state.mode = EXTRA;
  8954. /* falls through */
  8955. case EXTRA:
  8956. if (state.flags & 0x0400) {
  8957. copy = state.length;
  8958. if (copy > have) { copy = have; }
  8959. if (copy) {
  8960. if (state.head) {
  8961. len = state.head.extra_len - state.length;
  8962. if (!state.head.extra) {
  8963. // Use untyped array for more conveniend processing later
  8964. state.head.extra = new Array(state.head.extra_len);
  8965. }
  8966. utils.arraySet(
  8967. state.head.extra,
  8968. input,
  8969. next,
  8970. // extra field is limited to 65536 bytes
  8971. // - no need for additional size check
  8972. copy,
  8973. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  8974. len
  8975. );
  8976. //zmemcpy(state.head.extra + len, next,
  8977. // len + copy > state.head.extra_max ?
  8978. // state.head.extra_max - len : copy);
  8979. }
  8980. if (state.flags & 0x0200) {
  8981. state.check = crc32(state.check, input, copy, next);
  8982. }
  8983. have -= copy;
  8984. next += copy;
  8985. state.length -= copy;
  8986. }
  8987. if (state.length) { break inf_leave; }
  8988. }
  8989. state.length = 0;
  8990. state.mode = NAME;
  8991. /* falls through */
  8992. case NAME:
  8993. if (state.flags & 0x0800) {
  8994. if (have === 0) { break inf_leave; }
  8995. copy = 0;
  8996. do {
  8997. // TODO: 2 or 1 bytes?
  8998. len = input[next + copy++];
  8999. /* use constant limit because in js we should not preallocate memory */
  9000. if (state.head && len &&
  9001. (state.length < 65536 /*state.head.name_max*/)) {
  9002. state.head.name += String.fromCharCode(len);
  9003. }
  9004. } while (len && copy < have);
  9005.  
  9006. if (state.flags & 0x0200) {
  9007. state.check = crc32(state.check, input, copy, next);
  9008. }
  9009. have -= copy;
  9010. next += copy;
  9011. if (len) { break inf_leave; }
  9012. }
  9013. else if (state.head) {
  9014. state.head.name = null;
  9015. }
  9016. state.length = 0;
  9017. state.mode = COMMENT;
  9018. /* falls through */
  9019. case COMMENT:
  9020. if (state.flags & 0x1000) {
  9021. if (have === 0) { break inf_leave; }
  9022. copy = 0;
  9023. do {
  9024. len = input[next + copy++];
  9025. /* use constant limit because in js we should not preallocate memory */
  9026. if (state.head && len &&
  9027. (state.length < 65536 /*state.head.comm_max*/)) {
  9028. state.head.comment += String.fromCharCode(len);
  9029. }
  9030. } while (len && copy < have);
  9031. if (state.flags & 0x0200) {
  9032. state.check = crc32(state.check, input, copy, next);
  9033. }
  9034. have -= copy;
  9035. next += copy;
  9036. if (len) { break inf_leave; }
  9037. }
  9038. else if (state.head) {
  9039. state.head.comment = null;
  9040. }
  9041. state.mode = HCRC;
  9042. /* falls through */
  9043. case HCRC:
  9044. if (state.flags & 0x0200) {
  9045. //=== NEEDBITS(16); */
  9046. while (bits < 16) {
  9047. if (have === 0) { break inf_leave; }
  9048. have--;
  9049. hold += input[next++] << bits;
  9050. bits += 8;
  9051. }
  9052. //===//
  9053. if (hold !== (state.check & 0xffff)) {
  9054. strm.msg = 'header crc mismatch';
  9055. state.mode = BAD;
  9056. break;
  9057. }
  9058. //=== INITBITS();
  9059. hold = 0;
  9060. bits = 0;
  9061. //===//
  9062. }
  9063. if (state.head) {
  9064. state.head.hcrc = ((state.flags >> 9) & 1);
  9065. state.head.done = true;
  9066. }
  9067. strm.adler = state.check = 0;
  9068. state.mode = TYPE;
  9069. break;
  9070. case DICTID:
  9071. //=== NEEDBITS(32); */
  9072. while (bits < 32) {
  9073. if (have === 0) { break inf_leave; }
  9074. have--;
  9075. hold += input[next++] << bits;
  9076. bits += 8;
  9077. }
  9078. //===//
  9079. strm.adler = state.check = zswap32(hold);
  9080. //=== INITBITS();
  9081. hold = 0;
  9082. bits = 0;
  9083. //===//
  9084. state.mode = DICT;
  9085. /* falls through */
  9086. case DICT:
  9087. if (state.havedict === 0) {
  9088. //--- RESTORE() ---
  9089. strm.next_out = put;
  9090. strm.avail_out = left;
  9091. strm.next_in = next;
  9092. strm.avail_in = have;
  9093. state.hold = hold;
  9094. state.bits = bits;
  9095. //---
  9096. return Z_NEED_DICT;
  9097. }
  9098. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  9099. state.mode = TYPE;
  9100. /* falls through */
  9101. case TYPE:
  9102. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  9103. /* falls through */
  9104. case TYPEDO:
  9105. if (state.last) {
  9106. //--- BYTEBITS() ---//
  9107. hold >>>= bits & 7;
  9108. bits -= bits & 7;
  9109. //---//
  9110. state.mode = CHECK;
  9111. break;
  9112. }
  9113. //=== NEEDBITS(3); */
  9114. while (bits < 3) {
  9115. if (have === 0) { break inf_leave; }
  9116. have--;
  9117. hold += input[next++] << bits;
  9118. bits += 8;
  9119. }
  9120. //===//
  9121. state.last = (hold & 0x01)/*BITS(1)*/;
  9122. //--- DROPBITS(1) ---//
  9123. hold >>>= 1;
  9124. bits -= 1;
  9125. //---//
  9126.  
  9127. switch ((hold & 0x03)/*BITS(2)*/) {
  9128. case 0: /* stored block */
  9129. //Tracev((stderr, "inflate: stored block%s\n",
  9130. // state.last ? " (last)" : ""));
  9131. state.mode = STORED;
  9132. break;
  9133. case 1: /* fixed block */
  9134. fixedtables(state);
  9135. //Tracev((stderr, "inflate: fixed codes block%s\n",
  9136. // state.last ? " (last)" : ""));
  9137. state.mode = LEN_; /* decode codes */
  9138. if (flush === Z_TREES) {
  9139. //--- DROPBITS(2) ---//
  9140. hold >>>= 2;
  9141. bits -= 2;
  9142. //---//
  9143. break inf_leave;
  9144. }
  9145. break;
  9146. case 2: /* dynamic block */
  9147. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  9148. // state.last ? " (last)" : ""));
  9149. state.mode = TABLE;
  9150. break;
  9151. case 3:
  9152. strm.msg = 'invalid block type';
  9153. state.mode = BAD;
  9154. }
  9155. //--- DROPBITS(2) ---//
  9156. hold >>>= 2;
  9157. bits -= 2;
  9158. //---//
  9159. break;
  9160. case STORED:
  9161. //--- BYTEBITS() ---// /* go to byte boundary */
  9162. hold >>>= bits & 7;
  9163. bits -= bits & 7;
  9164. //---//
  9165. //=== NEEDBITS(32); */
  9166. while (bits < 32) {
  9167. if (have === 0) { break inf_leave; }
  9168. have--;
  9169. hold += input[next++] << bits;
  9170. bits += 8;
  9171. }
  9172. //===//
  9173. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  9174. strm.msg = 'invalid stored block lengths';
  9175. state.mode = BAD;
  9176. break;
  9177. }
  9178. state.length = hold & 0xffff;
  9179. //Tracev((stderr, "inflate: stored length %u\n",
  9180. // state.length));
  9181. //=== INITBITS();
  9182. hold = 0;
  9183. bits = 0;
  9184. //===//
  9185. state.mode = COPY_;
  9186. if (flush === Z_TREES) { break inf_leave; }
  9187. /* falls through */
  9188. case COPY_:
  9189. state.mode = COPY;
  9190. /* falls through */
  9191. case COPY:
  9192. copy = state.length;
  9193. if (copy) {
  9194. if (copy > have) { copy = have; }
  9195. if (copy > left) { copy = left; }
  9196. if (copy === 0) { break inf_leave; }
  9197. //--- zmemcpy(put, next, copy); ---
  9198. utils.arraySet(output, input, next, copy, put);
  9199. //---//
  9200. have -= copy;
  9201. next += copy;
  9202. left -= copy;
  9203. put += copy;
  9204. state.length -= copy;
  9205. break;
  9206. }
  9207. //Tracev((stderr, "inflate: stored end\n"));
  9208. state.mode = TYPE;
  9209. break;
  9210. case TABLE:
  9211. //=== NEEDBITS(14); */
  9212. while (bits < 14) {
  9213. if (have === 0) { break inf_leave; }
  9214. have--;
  9215. hold += input[next++] << bits;
  9216. bits += 8;
  9217. }
  9218. //===//
  9219. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  9220. //--- DROPBITS(5) ---//
  9221. hold >>>= 5;
  9222. bits -= 5;
  9223. //---//
  9224. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  9225. //--- DROPBITS(5) ---//
  9226. hold >>>= 5;
  9227. bits -= 5;
  9228. //---//
  9229. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  9230. //--- DROPBITS(4) ---//
  9231. hold >>>= 4;
  9232. bits -= 4;
  9233. //---//
  9234. //#ifndef PKZIP_BUG_WORKAROUND
  9235. if (state.nlen > 286 || state.ndist > 30) {
  9236. strm.msg = 'too many length or distance symbols';
  9237. state.mode = BAD;
  9238. break;
  9239. }
  9240. //#endif
  9241. //Tracev((stderr, "inflate: table sizes ok\n"));
  9242. state.have = 0;
  9243. state.mode = LENLENS;
  9244. /* falls through */
  9245. case LENLENS:
  9246. while (state.have < state.ncode) {
  9247. //=== NEEDBITS(3);
  9248. while (bits < 3) {
  9249. if (have === 0) { break inf_leave; }
  9250. have--;
  9251. hold += input[next++] << bits;
  9252. bits += 8;
  9253. }
  9254. //===//
  9255. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  9256. //--- DROPBITS(3) ---//
  9257. hold >>>= 3;
  9258. bits -= 3;
  9259. //---//
  9260. }
  9261. while (state.have < 19) {
  9262. state.lens[order[state.have++]] = 0;
  9263. }
  9264. // We have separate tables & no pointers. 2 commented lines below not needed.
  9265. //state.next = state.codes;
  9266. //state.lencode = state.next;
  9267. // Switch to use dynamic table
  9268. state.lencode = state.lendyn;
  9269. state.lenbits = 7;
  9270.  
  9271. opts = { bits: state.lenbits };
  9272. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  9273. state.lenbits = opts.bits;
  9274.  
  9275. if (ret) {
  9276. strm.msg = 'invalid code lengths set';
  9277. state.mode = BAD;
  9278. break;
  9279. }
  9280. //Tracev((stderr, "inflate: code lengths ok\n"));
  9281. state.have = 0;
  9282. state.mode = CODELENS;
  9283. /* falls through */
  9284. case CODELENS:
  9285. while (state.have < state.nlen + state.ndist) {
  9286. for (;;) {
  9287. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  9288. here_bits = here >>> 24;
  9289. here_op = (here >>> 16) & 0xff;
  9290. here_val = here & 0xffff;
  9291.  
  9292. if ((here_bits) <= bits) { break; }
  9293. //--- PULLBYTE() ---//
  9294. if (have === 0) { break inf_leave; }
  9295. have--;
  9296. hold += input[next++] << bits;
  9297. bits += 8;
  9298. //---//
  9299. }
  9300. if (here_val < 16) {
  9301. //--- DROPBITS(here.bits) ---//
  9302. hold >>>= here_bits;
  9303. bits -= here_bits;
  9304. //---//
  9305. state.lens[state.have++] = here_val;
  9306. }
  9307. else {
  9308. if (here_val === 16) {
  9309. //=== NEEDBITS(here.bits + 2);
  9310. n = here_bits + 2;
  9311. while (bits < n) {
  9312. if (have === 0) { break inf_leave; }
  9313. have--;
  9314. hold += input[next++] << bits;
  9315. bits += 8;
  9316. }
  9317. //===//
  9318. //--- DROPBITS(here.bits) ---//
  9319. hold >>>= here_bits;
  9320. bits -= here_bits;
  9321. //---//
  9322. if (state.have === 0) {
  9323. strm.msg = 'invalid bit length repeat';
  9324. state.mode = BAD;
  9325. break;
  9326. }
  9327. len = state.lens[state.have - 1];
  9328. copy = 3 + (hold & 0x03);//BITS(2);
  9329. //--- DROPBITS(2) ---//
  9330. hold >>>= 2;
  9331. bits -= 2;
  9332. //---//
  9333. }
  9334. else if (here_val === 17) {
  9335. //=== NEEDBITS(here.bits + 3);
  9336. n = here_bits + 3;
  9337. while (bits < n) {
  9338. if (have === 0) { break inf_leave; }
  9339. have--;
  9340. hold += input[next++] << bits;
  9341. bits += 8;
  9342. }
  9343. //===//
  9344. //--- DROPBITS(here.bits) ---//
  9345. hold >>>= here_bits;
  9346. bits -= here_bits;
  9347. //---//
  9348. len = 0;
  9349. copy = 3 + (hold & 0x07);//BITS(3);
  9350. //--- DROPBITS(3) ---//
  9351. hold >>>= 3;
  9352. bits -= 3;
  9353. //---//
  9354. }
  9355. else {
  9356. //=== NEEDBITS(here.bits + 7);
  9357. n = here_bits + 7;
  9358. while (bits < n) {
  9359. if (have === 0) { break inf_leave; }
  9360. have--;
  9361. hold += input[next++] << bits;
  9362. bits += 8;
  9363. }
  9364. //===//
  9365. //--- DROPBITS(here.bits) ---//
  9366. hold >>>= here_bits;
  9367. bits -= here_bits;
  9368. //---//
  9369. len = 0;
  9370. copy = 11 + (hold & 0x7f);//BITS(7);
  9371. //--- DROPBITS(7) ---//
  9372. hold >>>= 7;
  9373. bits -= 7;
  9374. //---//
  9375. }
  9376. if (state.have + copy > state.nlen + state.ndist) {
  9377. strm.msg = 'invalid bit length repeat';
  9378. state.mode = BAD;
  9379. break;
  9380. }
  9381. while (copy--) {
  9382. state.lens[state.have++] = len;
  9383. }
  9384. }
  9385. }
  9386.  
  9387. /* handle error breaks in while */
  9388. if (state.mode === BAD) { break; }
  9389.  
  9390. /* check for end-of-block code (better have one) */
  9391. if (state.lens[256] === 0) {
  9392. strm.msg = 'invalid code -- missing end-of-block';
  9393. state.mode = BAD;
  9394. break;
  9395. }
  9396.  
  9397. /* build code tables -- note: do not change the lenbits or distbits
  9398. values here (9 and 6) without reading the comments in inftrees.h
  9399. concerning the ENOUGH constants, which depend on those values */
  9400. state.lenbits = 9;
  9401.  
  9402. opts = { bits: state.lenbits };
  9403. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  9404. // We have separate tables & no pointers. 2 commented lines below not needed.
  9405. // state.next_index = opts.table_index;
  9406. state.lenbits = opts.bits;
  9407. // state.lencode = state.next;
  9408.  
  9409. if (ret) {
  9410. strm.msg = 'invalid literal/lengths set';
  9411. state.mode = BAD;
  9412. break;
  9413. }
  9414.  
  9415. state.distbits = 6;
  9416. //state.distcode.copy(state.codes);
  9417. // Switch to use dynamic table
  9418. state.distcode = state.distdyn;
  9419. opts = { bits: state.distbits };
  9420. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  9421. // We have separate tables & no pointers. 2 commented lines below not needed.
  9422. // state.next_index = opts.table_index;
  9423. state.distbits = opts.bits;
  9424. // state.distcode = state.next;
  9425.  
  9426. if (ret) {
  9427. strm.msg = 'invalid distances set';
  9428. state.mode = BAD;
  9429. break;
  9430. }
  9431. //Tracev((stderr, 'inflate: codes ok\n'));
  9432. state.mode = LEN_;
  9433. if (flush === Z_TREES) { break inf_leave; }
  9434. /* falls through */
  9435. case LEN_:
  9436. state.mode = LEN;
  9437. /* falls through */
  9438. case LEN:
  9439. if (have >= 6 && left >= 258) {
  9440. //--- RESTORE() ---
  9441. strm.next_out = put;
  9442. strm.avail_out = left;
  9443. strm.next_in = next;
  9444. strm.avail_in = have;
  9445. state.hold = hold;
  9446. state.bits = bits;
  9447. //---
  9448. inflate_fast(strm, _out);
  9449. //--- LOAD() ---
  9450. put = strm.next_out;
  9451. output = strm.output;
  9452. left = strm.avail_out;
  9453. next = strm.next_in;
  9454. input = strm.input;
  9455. have = strm.avail_in;
  9456. hold = state.hold;
  9457. bits = state.bits;
  9458. //---
  9459.  
  9460. if (state.mode === TYPE) {
  9461. state.back = -1;
  9462. }
  9463. break;
  9464. }
  9465. state.back = 0;
  9466. for (;;) {
  9467. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  9468. here_bits = here >>> 24;
  9469. here_op = (here >>> 16) & 0xff;
  9470. here_val = here & 0xffff;
  9471.  
  9472. if (here_bits <= bits) { break; }
  9473. //--- PULLBYTE() ---//
  9474. if (have === 0) { break inf_leave; }
  9475. have--;
  9476. hold += input[next++] << bits;
  9477. bits += 8;
  9478. //---//
  9479. }
  9480. if (here_op && (here_op & 0xf0) === 0) {
  9481. last_bits = here_bits;
  9482. last_op = here_op;
  9483. last_val = here_val;
  9484. for (;;) {
  9485. here = state.lencode[last_val +
  9486. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9487. here_bits = here >>> 24;
  9488. here_op = (here >>> 16) & 0xff;
  9489. here_val = here & 0xffff;
  9490.  
  9491. if ((last_bits + here_bits) <= bits) { break; }
  9492. //--- PULLBYTE() ---//
  9493. if (have === 0) { break inf_leave; }
  9494. have--;
  9495. hold += input[next++] << bits;
  9496. bits += 8;
  9497. //---//
  9498. }
  9499. //--- DROPBITS(last.bits) ---//
  9500. hold >>>= last_bits;
  9501. bits -= last_bits;
  9502. //---//
  9503. state.back += last_bits;
  9504. }
  9505. //--- DROPBITS(here.bits) ---//
  9506. hold >>>= here_bits;
  9507. bits -= here_bits;
  9508. //---//
  9509. state.back += here_bits;
  9510. state.length = here_val;
  9511. if (here_op === 0) {
  9512. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  9513. // "inflate: literal '%c'\n" :
  9514. // "inflate: literal 0x%02x\n", here.val));
  9515. state.mode = LIT;
  9516. break;
  9517. }
  9518. if (here_op & 32) {
  9519. //Tracevv((stderr, "inflate: end of block\n"));
  9520. state.back = -1;
  9521. state.mode = TYPE;
  9522. break;
  9523. }
  9524. if (here_op & 64) {
  9525. strm.msg = 'invalid literal/length code';
  9526. state.mode = BAD;
  9527. break;
  9528. }
  9529. state.extra = here_op & 15;
  9530. state.mode = LENEXT;
  9531. /* falls through */
  9532. case LENEXT:
  9533. if (state.extra) {
  9534. //=== NEEDBITS(state.extra);
  9535. n = state.extra;
  9536. while (bits < n) {
  9537. if (have === 0) { break inf_leave; }
  9538. have--;
  9539. hold += input[next++] << bits;
  9540. bits += 8;
  9541. }
  9542. //===//
  9543. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9544. //--- DROPBITS(state.extra) ---//
  9545. hold >>>= state.extra;
  9546. bits -= state.extra;
  9547. //---//
  9548. state.back += state.extra;
  9549. }
  9550. //Tracevv((stderr, "inflate: length %u\n", state.length));
  9551. state.was = state.length;
  9552. state.mode = DIST;
  9553. /* falls through */
  9554. case DIST:
  9555. for (;;) {
  9556. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  9557. here_bits = here >>> 24;
  9558. here_op = (here >>> 16) & 0xff;
  9559. here_val = here & 0xffff;
  9560.  
  9561. if ((here_bits) <= bits) { break; }
  9562. //--- PULLBYTE() ---//
  9563. if (have === 0) { break inf_leave; }
  9564. have--;
  9565. hold += input[next++] << bits;
  9566. bits += 8;
  9567. //---//
  9568. }
  9569. if ((here_op & 0xf0) === 0) {
  9570. last_bits = here_bits;
  9571. last_op = here_op;
  9572. last_val = here_val;
  9573. for (;;) {
  9574. here = state.distcode[last_val +
  9575. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9576. here_bits = here >>> 24;
  9577. here_op = (here >>> 16) & 0xff;
  9578. here_val = here & 0xffff;
  9579.  
  9580. if ((last_bits + here_bits) <= bits) { break; }
  9581. //--- PULLBYTE() ---//
  9582. if (have === 0) { break inf_leave; }
  9583. have--;
  9584. hold += input[next++] << bits;
  9585. bits += 8;
  9586. //---//
  9587. }
  9588. //--- DROPBITS(last.bits) ---//
  9589. hold >>>= last_bits;
  9590. bits -= last_bits;
  9591. //---//
  9592. state.back += last_bits;
  9593. }
  9594. //--- DROPBITS(here.bits) ---//
  9595. hold >>>= here_bits;
  9596. bits -= here_bits;
  9597. //---//
  9598. state.back += here_bits;
  9599. if (here_op & 64) {
  9600. strm.msg = 'invalid distance code';
  9601. state.mode = BAD;
  9602. break;
  9603. }
  9604. state.offset = here_val;
  9605. state.extra = (here_op) & 15;
  9606. state.mode = DISTEXT;
  9607. /* falls through */
  9608. case DISTEXT:
  9609. if (state.extra) {
  9610. //=== NEEDBITS(state.extra);
  9611. n = state.extra;
  9612. while (bits < n) {
  9613. if (have === 0) { break inf_leave; }
  9614. have--;
  9615. hold += input[next++] << bits;
  9616. bits += 8;
  9617. }
  9618. //===//
  9619. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9620. //--- DROPBITS(state.extra) ---//
  9621. hold >>>= state.extra;
  9622. bits -= state.extra;
  9623. //---//
  9624. state.back += state.extra;
  9625. }
  9626. //#ifdef INFLATE_STRICT
  9627. if (state.offset > state.dmax) {
  9628. strm.msg = 'invalid distance too far back';
  9629. state.mode = BAD;
  9630. break;
  9631. }
  9632. //#endif
  9633. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  9634. state.mode = MATCH;
  9635. /* falls through */
  9636. case MATCH:
  9637. if (left === 0) { break inf_leave; }
  9638. copy = _out - left;
  9639. if (state.offset > copy) { /* copy from window */
  9640. copy = state.offset - copy;
  9641. if (copy > state.whave) {
  9642. if (state.sane) {
  9643. strm.msg = 'invalid distance too far back';
  9644. state.mode = BAD;
  9645. break;
  9646. }
  9647. // (!) This block is disabled in zlib defailts,
  9648. // don't enable it for binary compatibility
  9649. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9650. // Trace((stderr, "inflate.c too far\n"));
  9651. // copy -= state.whave;
  9652. // if (copy > state.length) { copy = state.length; }
  9653. // if (copy > left) { copy = left; }
  9654. // left -= copy;
  9655. // state.length -= copy;
  9656. // do {
  9657. // output[put++] = 0;
  9658. // } while (--copy);
  9659. // if (state.length === 0) { state.mode = LEN; }
  9660. // break;
  9661. //#endif
  9662. }
  9663. if (copy > state.wnext) {
  9664. copy -= state.wnext;
  9665. from = state.wsize - copy;
  9666. }
  9667. else {
  9668. from = state.wnext - copy;
  9669. }
  9670. if (copy > state.length) { copy = state.length; }
  9671. from_source = state.window;
  9672. }
  9673. else { /* copy from output */
  9674. from_source = output;
  9675. from = put - state.offset;
  9676. copy = state.length;
  9677. }
  9678. if (copy > left) { copy = left; }
  9679. left -= copy;
  9680. state.length -= copy;
  9681. do {
  9682. output[put++] = from_source[from++];
  9683. } while (--copy);
  9684. if (state.length === 0) { state.mode = LEN; }
  9685. break;
  9686. case LIT:
  9687. if (left === 0) { break inf_leave; }
  9688. output[put++] = state.length;
  9689. left--;
  9690. state.mode = LEN;
  9691. break;
  9692. case CHECK:
  9693. if (state.wrap) {
  9694. //=== NEEDBITS(32);
  9695. while (bits < 32) {
  9696. if (have === 0) { break inf_leave; }
  9697. have--;
  9698. // Use '|' insdead of '+' to make sure that result is signed
  9699. hold |= input[next++] << bits;
  9700. bits += 8;
  9701. }
  9702. //===//
  9703. _out -= left;
  9704. strm.total_out += _out;
  9705. state.total += _out;
  9706. if (_out) {
  9707. strm.adler = state.check =
  9708. /*UPDATE(state.check, put - _out, _out);*/
  9709. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  9710.  
  9711. }
  9712. _out = left;
  9713. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  9714. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  9715. strm.msg = 'incorrect data check';
  9716. state.mode = BAD;
  9717. break;
  9718. }
  9719. //=== INITBITS();
  9720. hold = 0;
  9721. bits = 0;
  9722. //===//
  9723. //Tracev((stderr, "inflate: check matches trailer\n"));
  9724. }
  9725. state.mode = LENGTH;
  9726. /* falls through */
  9727. case LENGTH:
  9728. if (state.wrap && state.flags) {
  9729. //=== NEEDBITS(32);
  9730. while (bits < 32) {
  9731. if (have === 0) { break inf_leave; }
  9732. have--;
  9733. hold += input[next++] << bits;
  9734. bits += 8;
  9735. }
  9736. //===//
  9737. if (hold !== (state.total & 0xffffffff)) {
  9738. strm.msg = 'incorrect length check';
  9739. state.mode = BAD;
  9740. break;
  9741. }
  9742. //=== INITBITS();
  9743. hold = 0;
  9744. bits = 0;
  9745. //===//
  9746. //Tracev((stderr, "inflate: length matches trailer\n"));
  9747. }
  9748. state.mode = DONE;
  9749. /* falls through */
  9750. case DONE:
  9751. ret = Z_STREAM_END;
  9752. break inf_leave;
  9753. case BAD:
  9754. ret = Z_DATA_ERROR;
  9755. break inf_leave;
  9756. case MEM:
  9757. return Z_MEM_ERROR;
  9758. case SYNC:
  9759. /* falls through */
  9760. default:
  9761. return Z_STREAM_ERROR;
  9762. }
  9763. }
  9764.  
  9765. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  9766.  
  9767. /*
  9768. Return from inflate(), updating the total counts and the check value.
  9769. If there was no progress during the inflate() call, return a buffer
  9770. error. Call updatewindow() to create and/or update the window state.
  9771. Note: a memory error from inflate() is non-recoverable.
  9772. */
  9773.  
  9774. //--- RESTORE() ---
  9775. strm.next_out = put;
  9776. strm.avail_out = left;
  9777. strm.next_in = next;
  9778. strm.avail_in = have;
  9779. state.hold = hold;
  9780. state.bits = bits;
  9781. //---
  9782.  
  9783. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  9784. (state.mode < CHECK || flush !== Z_FINISH))) {
  9785. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  9786. state.mode = MEM;
  9787. return Z_MEM_ERROR;
  9788. }
  9789. }
  9790. _in -= strm.avail_in;
  9791. _out -= strm.avail_out;
  9792. strm.total_in += _in;
  9793. strm.total_out += _out;
  9794. state.total += _out;
  9795. if (state.wrap && _out) {
  9796. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  9797. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  9798. }
  9799. strm.data_type = state.bits + (state.last ? 64 : 0) +
  9800. (state.mode === TYPE ? 128 : 0) +
  9801. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  9802. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  9803. ret = Z_BUF_ERROR;
  9804. }
  9805. return ret;
  9806. }
  9807.  
  9808. function inflateEnd(strm) {
  9809.  
  9810. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  9811. return Z_STREAM_ERROR;
  9812. }
  9813.  
  9814. var state = strm.state;
  9815. if (state.window) {
  9816. state.window = null;
  9817. }
  9818. strm.state = null;
  9819. return Z_OK;
  9820. }
  9821.  
  9822. function inflateGetHeader(strm, head) {
  9823. var state;
  9824.  
  9825. /* check state */
  9826. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9827. state = strm.state;
  9828. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  9829.  
  9830. /* save header structure */
  9831. state.head = head;
  9832. head.done = false;
  9833. return Z_OK;
  9834. }
  9835.  
  9836. function inflateSetDictionary(strm, dictionary) {
  9837. var dictLength = dictionary.length;
  9838.  
  9839. var state;
  9840. var dictid;
  9841. var ret;
  9842.  
  9843. /* check state */
  9844. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  9845. state = strm.state;
  9846.  
  9847. if (state.wrap !== 0 && state.mode !== DICT) {
  9848. return Z_STREAM_ERROR;
  9849. }
  9850.  
  9851. /* check for correct dictionary identifier */
  9852. if (state.mode === DICT) {
  9853. dictid = 1; /* adler32(0, null, 0)*/
  9854. /* dictid = adler32(dictid, dictionary, dictLength); */
  9855. dictid = adler32(dictid, dictionary, dictLength, 0);
  9856. if (dictid !== state.check) {
  9857. return Z_DATA_ERROR;
  9858. }
  9859. }
  9860. /* copy dictionary to window using updatewindow(), which will amend the
  9861. existing dictionary if appropriate */
  9862. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  9863. if (ret) {
  9864. state.mode = MEM;
  9865. return Z_MEM_ERROR;
  9866. }
  9867. state.havedict = 1;
  9868. // Tracev((stderr, "inflate: dictionary set\n"));
  9869. return Z_OK;
  9870. }
  9871.  
  9872. exports.inflateReset = inflateReset;
  9873. exports.inflateReset2 = inflateReset2;
  9874. exports.inflateResetKeep = inflateResetKeep;
  9875. exports.inflateInit = inflateInit;
  9876. exports.inflateInit2 = inflateInit2;
  9877. exports.inflate = inflate;
  9878. exports.inflateEnd = inflateEnd;
  9879. exports.inflateGetHeader = inflateGetHeader;
  9880. exports.inflateSetDictionary = inflateSetDictionary;
  9881. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  9882.  
  9883. /* Not implemented
  9884. exports.inflateCopy = inflateCopy;
  9885. exports.inflateGetDictionary = inflateGetDictionary;
  9886. exports.inflateMark = inflateMark;
  9887. exports.inflatePrime = inflatePrime;
  9888. exports.inflateSync = inflateSync;
  9889. exports.inflateSyncPoint = inflateSyncPoint;
  9890. exports.inflateUndermine = inflateUndermine;
  9891. */
  9892.  
  9893. },{"../utils/common":62,"./adler32":64,"./crc32":66,"./inffast":69,"./inftrees":71}],71:[function(require,module,exports){
  9894. 'use strict';
  9895.  
  9896.  
  9897. var utils = require('../utils/common');
  9898.  
  9899. var MAXBITS = 15;
  9900. var ENOUGH_LENS = 852;
  9901. var ENOUGH_DISTS = 592;
  9902. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  9903.  
  9904. var CODES = 0;
  9905. var LENS = 1;
  9906. var DISTS = 2;
  9907.  
  9908. var lbase = [ /* Length codes 257..285 base */
  9909. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  9910. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  9911. ];
  9912.  
  9913. var lext = [ /* Length codes 257..285 extra */
  9914. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  9915. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  9916. ];
  9917.  
  9918. var dbase = [ /* Distance codes 0..29 base */
  9919. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  9920. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  9921. 8193, 12289, 16385, 24577, 0, 0
  9922. ];
  9923.  
  9924. var dext = [ /* Distance codes 0..29 extra */
  9925. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  9926. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  9927. 28, 28, 29, 29, 64, 64
  9928. ];
  9929.  
  9930. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  9931. {
  9932. var bits = opts.bits;
  9933. //here = opts.here; /* table entry for duplication */
  9934.  
  9935. var len = 0; /* a code's length in bits */
  9936. var sym = 0; /* index of code symbols */
  9937. var min = 0, max = 0; /* minimum and maximum code lengths */
  9938. var root = 0; /* number of index bits for root table */
  9939. var curr = 0; /* number of index bits for current table */
  9940. var drop = 0; /* code bits to drop for sub-table */
  9941. var left = 0; /* number of prefix codes available */
  9942. var used = 0; /* code entries in table used */
  9943. var huff = 0; /* Huffman code */
  9944. var incr; /* for incrementing code, index */
  9945. var fill; /* index for replicating entries */
  9946. var low; /* low bits for current root entry */
  9947. var mask; /* mask for low root bits */
  9948. var next; /* next available space in table */
  9949. var base = null; /* base value table to use */
  9950. var base_index = 0;
  9951. // var shoextra; /* extra bits table to use */
  9952. var end; /* use base and extra for symbol > end */
  9953. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  9954. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  9955. var extra = null;
  9956. var extra_index = 0;
  9957.  
  9958. var here_bits, here_op, here_val;
  9959.  
  9960. /*
  9961. Process a set of code lengths to create a canonical Huffman code. The
  9962. code lengths are lens[0..codes-1]. Each length corresponds to the
  9963. symbols 0..codes-1. The Huffman code is generated by first sorting the
  9964. symbols by length from short to long, and retaining the symbol order
  9965. for codes with equal lengths. Then the code starts with all zero bits
  9966. for the first code of the shortest length, and the codes are integer
  9967. increments for the same length, and zeros are appended as the length
  9968. increases. For the deflate format, these bits are stored backwards
  9969. from their more natural integer increment ordering, and so when the
  9970. decoding tables are built in the large loop below, the integer codes
  9971. are incremented backwards.
  9972.  
  9973. This routine assumes, but does not check, that all of the entries in
  9974. lens[] are in the range 0..MAXBITS. The caller must assure this.
  9975. 1..MAXBITS is interpreted as that code length. zero means that that
  9976. symbol does not occur in this code.
  9977.  
  9978. The codes are sorted by computing a count of codes for each length,
  9979. creating from that a table of starting indices for each length in the
  9980. sorted table, and then entering the symbols in order in the sorted
  9981. table. The sorted table is work[], with that space being provided by
  9982. the caller.
  9983.  
  9984. The length counts are used for other purposes as well, i.e. finding
  9985. the minimum and maximum length codes, determining if there are any
  9986. codes at all, checking for a valid set of lengths, and looking ahead
  9987. at length counts to determine sub-table sizes when building the
  9988. decoding tables.
  9989. */
  9990.  
  9991. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  9992. for (len = 0; len <= MAXBITS; len++) {
  9993. count[len] = 0;
  9994. }
  9995. for (sym = 0; sym < codes; sym++) {
  9996. count[lens[lens_index + sym]]++;
  9997. }
  9998.  
  9999. /* bound code lengths, force root to be within code lengths */
  10000. root = bits;
  10001. for (max = MAXBITS; max >= 1; max--) {
  10002. if (count[max] !== 0) { break; }
  10003. }
  10004. if (root > max) {
  10005. root = max;
  10006. }
  10007. if (max === 0) { /* no symbols to code at all */
  10008. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  10009. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  10010. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  10011. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  10012.  
  10013.  
  10014. //table.op[opts.table_index] = 64;
  10015. //table.bits[opts.table_index] = 1;
  10016. //table.val[opts.table_index++] = 0;
  10017. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  10018.  
  10019. opts.bits = 1;
  10020. return 0; /* no symbols, but wait for decoding to report error */
  10021. }
  10022. for (min = 1; min < max; min++) {
  10023. if (count[min] !== 0) { break; }
  10024. }
  10025. if (root < min) {
  10026. root = min;
  10027. }
  10028.  
  10029. /* check for an over-subscribed or incomplete set of lengths */
  10030. left = 1;
  10031. for (len = 1; len <= MAXBITS; len++) {
  10032. left <<= 1;
  10033. left -= count[len];
  10034. if (left < 0) {
  10035. return -1;
  10036. } /* over-subscribed */
  10037. }
  10038. if (left > 0 && (type === CODES || max !== 1)) {
  10039. return -1; /* incomplete set */
  10040. }
  10041.  
  10042. /* generate offsets into symbol table for each length for sorting */
  10043. offs[1] = 0;
  10044. for (len = 1; len < MAXBITS; len++) {
  10045. offs[len + 1] = offs[len] + count[len];
  10046. }
  10047.  
  10048. /* sort symbols by length, by symbol order within each length */
  10049. for (sym = 0; sym < codes; sym++) {
  10050. if (lens[lens_index + sym] !== 0) {
  10051. work[offs[lens[lens_index + sym]]++] = sym;
  10052. }
  10053. }
  10054.  
  10055. /*
  10056. Create and fill in decoding tables. In this loop, the table being
  10057. filled is at next and has curr index bits. The code being used is huff
  10058. with length len. That code is converted to an index by dropping drop
  10059. bits off of the bottom. For codes where len is less than drop + curr,
  10060. those top drop + curr - len bits are incremented through all values to
  10061. fill the table with replicated entries.
  10062.  
  10063. root is the number of index bits for the root table. When len exceeds
  10064. root, sub-tables are created pointed to by the root entry with an index
  10065. of the low root bits of huff. This is saved in low to check for when a
  10066. new sub-table should be started. drop is zero when the root table is
  10067. being filled, and drop is root when sub-tables are being filled.
  10068.  
  10069. When a new sub-table is needed, it is necessary to look ahead in the
  10070. code lengths to determine what size sub-table is needed. The length
  10071. counts are used for this, and so count[] is decremented as codes are
  10072. entered in the tables.
  10073.  
  10074. used keeps track of how many table entries have been allocated from the
  10075. provided *table space. It is checked for LENS and DIST tables against
  10076. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  10077. the initial root table size constants. See the comments in inftrees.h
  10078. for more information.
  10079.  
  10080. sym increments through all symbols, and the loop terminates when
  10081. all codes of length max, i.e. all codes, have been processed. This
  10082. routine permits incomplete codes, so another loop after this one fills
  10083. in the rest of the decoding tables with invalid code markers.
  10084. */
  10085.  
  10086. /* set up for code type */
  10087. // poor man optimization - use if-else instead of switch,
  10088. // to avoid deopts in old v8
  10089. if (type === CODES) {
  10090. base = extra = work; /* dummy value--not used */
  10091. end = 19;
  10092.  
  10093. } else if (type === LENS) {
  10094. base = lbase;
  10095. base_index -= 257;
  10096. extra = lext;
  10097. extra_index -= 257;
  10098. end = 256;
  10099.  
  10100. } else { /* DISTS */
  10101. base = dbase;
  10102. extra = dext;
  10103. end = -1;
  10104. }
  10105.  
  10106. /* initialize opts for loop */
  10107. huff = 0; /* starting code */
  10108. sym = 0; /* starting code symbol */
  10109. len = min; /* starting code length */
  10110. next = table_index; /* current table to fill in */
  10111. curr = root; /* current table index bits */
  10112. drop = 0; /* current bits to drop from code for index */
  10113. low = -1; /* trigger new sub-table when len > root */
  10114. used = 1 << root; /* use root table entries */
  10115. mask = used - 1; /* mask for comparing low */
  10116.  
  10117. /* check available table space */
  10118. if ((type === LENS && used > ENOUGH_LENS) ||
  10119. (type === DISTS && used > ENOUGH_DISTS)) {
  10120. return 1;
  10121. }
  10122.  
  10123. var i = 0;
  10124. /* process all codes and make table entries */
  10125. for (;;) {
  10126. i++;
  10127. /* create table entry */
  10128. here_bits = len - drop;
  10129. if (work[sym] < end) {
  10130. here_op = 0;
  10131. here_val = work[sym];
  10132. }
  10133. else if (work[sym] > end) {
  10134. here_op = extra[extra_index + work[sym]];
  10135. here_val = base[base_index + work[sym]];
  10136. }
  10137. else {
  10138. here_op = 32 + 64; /* end of block */
  10139. here_val = 0;
  10140. }
  10141.  
  10142. /* replicate for those indices with low len bits equal to huff */
  10143. incr = 1 << (len - drop);
  10144. fill = 1 << curr;
  10145. min = fill; /* save offset to next table */
  10146. do {
  10147. fill -= incr;
  10148. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  10149. } while (fill !== 0);
  10150.  
  10151. /* backwards increment the len-bit code huff */
  10152. incr = 1 << (len - 1);
  10153. while (huff & incr) {
  10154. incr >>= 1;
  10155. }
  10156. if (incr !== 0) {
  10157. huff &= incr - 1;
  10158. huff += incr;
  10159. } else {
  10160. huff = 0;
  10161. }
  10162.  
  10163. /* go to next symbol, update count, len */
  10164. sym++;
  10165. if (--count[len] === 0) {
  10166. if (len === max) { break; }
  10167. len = lens[lens_index + work[sym]];
  10168. }
  10169.  
  10170. /* create new sub-table if needed */
  10171. if (len > root && (huff & mask) !== low) {
  10172. /* if first time, transition to sub-tables */
  10173. if (drop === 0) {
  10174. drop = root;
  10175. }
  10176.  
  10177. /* increment past last table */
  10178. next += min; /* here min is 1 << curr */
  10179.  
  10180. /* determine length of next table */
  10181. curr = len - drop;
  10182. left = 1 << curr;
  10183. while (curr + drop < max) {
  10184. left -= count[curr + drop];
  10185. if (left <= 0) { break; }
  10186. curr++;
  10187. left <<= 1;
  10188. }
  10189.  
  10190. /* check for enough space */
  10191. used += 1 << curr;
  10192. if ((type === LENS && used > ENOUGH_LENS) ||
  10193. (type === DISTS && used > ENOUGH_DISTS)) {
  10194. return 1;
  10195. }
  10196.  
  10197. /* point entry in root table to sub-table */
  10198. low = huff & mask;
  10199. /*table.op[low] = curr;
  10200. table.bits[low] = root;
  10201. table.val[low] = next - opts.table_index;*/
  10202. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  10203. }
  10204. }
  10205.  
  10206. /* fill in remaining table entry if code is incomplete (guaranteed to have
  10207. at most one remaining entry, since if the code is incomplete, the
  10208. maximum code length that was allowed to get this far is one bit) */
  10209. if (huff !== 0) {
  10210. //table.op[next + huff] = 64; /* invalid code marker */
  10211. //table.bits[next + huff] = len - drop;
  10212. //table.val[next + huff] = 0;
  10213. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  10214. }
  10215.  
  10216. /* set return parameters */
  10217. //opts.table_index += used;
  10218. opts.bits = root;
  10219. return 0;
  10220. };
  10221.  
  10222. },{"../utils/common":62}],72:[function(require,module,exports){
  10223. 'use strict';
  10224.  
  10225. module.exports = {
  10226. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  10227. 1: 'stream end', /* Z_STREAM_END 1 */
  10228. 0: '', /* Z_OK 0 */
  10229. '-1': 'file error', /* Z_ERRNO (-1) */
  10230. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  10231. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  10232. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  10233. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  10234. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  10235. };
  10236.  
  10237. },{}],73:[function(require,module,exports){
  10238. 'use strict';
  10239.  
  10240.  
  10241. var utils = require('../utils/common');
  10242.  
  10243. /* Public constants ==========================================================*/
  10244. /* ===========================================================================*/
  10245.  
  10246.  
  10247. //var Z_FILTERED = 1;
  10248. //var Z_HUFFMAN_ONLY = 2;
  10249. //var Z_RLE = 3;
  10250. var Z_FIXED = 4;
  10251. //var Z_DEFAULT_STRATEGY = 0;
  10252.  
  10253. /* Possible values of the data_type field (though see inflate()) */
  10254. var Z_BINARY = 0;
  10255. var Z_TEXT = 1;
  10256. //var Z_ASCII = 1; // = Z_TEXT
  10257. var Z_UNKNOWN = 2;
  10258.  
  10259. /*============================================================================*/
  10260.  
  10261.  
  10262. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  10263.  
  10264. // From zutil.h
  10265.  
  10266. var STORED_BLOCK = 0;
  10267. var STATIC_TREES = 1;
  10268. var DYN_TREES = 2;
  10269. /* The three kinds of block type */
  10270.  
  10271. var MIN_MATCH = 3;
  10272. var MAX_MATCH = 258;
  10273. /* The minimum and maximum match lengths */
  10274.  
  10275. // From deflate.h
  10276. /* ===========================================================================
  10277. * Internal compression state.
  10278. */
  10279.  
  10280. var LENGTH_CODES = 29;
  10281. /* number of length codes, not counting the special END_BLOCK code */
  10282.  
  10283. var LITERALS = 256;
  10284. /* number of literal bytes 0..255 */
  10285.  
  10286. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  10287. /* number of Literal or Length codes, including the END_BLOCK code */
  10288.  
  10289. var D_CODES = 30;
  10290. /* number of distance codes */
  10291.  
  10292. var BL_CODES = 19;
  10293. /* number of codes used to transfer the bit lengths */
  10294.  
  10295. var HEAP_SIZE = 2 * L_CODES + 1;
  10296. /* maximum heap size */
  10297.  
  10298. var MAX_BITS = 15;
  10299. /* All codes must not exceed MAX_BITS bits */
  10300.  
  10301. var Buf_size = 16;
  10302. /* size of bit buffer in bi_buf */
  10303.  
  10304.  
  10305. /* ===========================================================================
  10306. * Constants
  10307. */
  10308.  
  10309. var MAX_BL_BITS = 7;
  10310. /* Bit length codes must not exceed MAX_BL_BITS bits */
  10311.  
  10312. var END_BLOCK = 256;
  10313. /* end of block literal code */
  10314.  
  10315. var REP_3_6 = 16;
  10316. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  10317.  
  10318. var REPZ_3_10 = 17;
  10319. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  10320.  
  10321. var REPZ_11_138 = 18;
  10322. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  10323.  
  10324. /* eslint-disable comma-spacing,array-bracket-spacing */
  10325. var extra_lbits = /* extra bits for each length code */
  10326. [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];
  10327.  
  10328. var extra_dbits = /* extra bits for each distance code */
  10329. [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];
  10330.  
  10331. var extra_blbits = /* extra bits for each bit length code */
  10332. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  10333.  
  10334. var bl_order =
  10335. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  10336. /* eslint-enable comma-spacing,array-bracket-spacing */
  10337.  
  10338. /* The lengths of the bit length codes are sent in order of decreasing
  10339. * probability, to avoid transmitting the lengths for unused bit length codes.
  10340. */
  10341.  
  10342. /* ===========================================================================
  10343. * Local data. These are initialized only once.
  10344. */
  10345.  
  10346. // We pre-fill arrays with 0 to avoid uninitialized gaps
  10347.  
  10348. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  10349.  
  10350. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  10351. var static_ltree = new Array((L_CODES + 2) * 2);
  10352. zero(static_ltree);
  10353. /* The static literal tree. Since the bit lengths are imposed, there is no
  10354. * need for the L_CODES extra codes used during heap construction. However
  10355. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  10356. * below).
  10357. */
  10358.  
  10359. var static_dtree = new Array(D_CODES * 2);
  10360. zero(static_dtree);
  10361. /* The static distance tree. (Actually a trivial tree since all codes use
  10362. * 5 bits.)
  10363. */
  10364.  
  10365. var _dist_code = new Array(DIST_CODE_LEN);
  10366. zero(_dist_code);
  10367. /* Distance codes. The first 256 values correspond to the distances
  10368. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  10369. * the 15 bit distances.
  10370. */
  10371.  
  10372. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  10373. zero(_length_code);
  10374. /* length code for each normalized match length (0 == MIN_MATCH) */
  10375.  
  10376. var base_length = new Array(LENGTH_CODES);
  10377. zero(base_length);
  10378. /* First normalized length for each code (0 = MIN_MATCH) */
  10379.  
  10380. var base_dist = new Array(D_CODES);
  10381. zero(base_dist);
  10382. /* First normalized distance for each code (0 = distance of 1) */
  10383.  
  10384.  
  10385. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  10386.  
  10387. this.static_tree = static_tree; /* static tree or NULL */
  10388. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  10389. this.extra_base = extra_base; /* base index for extra_bits */
  10390. this.elems = elems; /* max number of elements in the tree */
  10391. this.max_length = max_length; /* max bit length for the codes */
  10392.  
  10393. // show if `static_tree` has data or dummy - needed for monomorphic objects
  10394. this.has_stree = static_tree && static_tree.length;
  10395. }
  10396.  
  10397.  
  10398. var static_l_desc;
  10399. var static_d_desc;
  10400. var static_bl_desc;
  10401.  
  10402.  
  10403. function TreeDesc(dyn_tree, stat_desc) {
  10404. this.dyn_tree = dyn_tree; /* the dynamic tree */
  10405. this.max_code = 0; /* largest code with non zero frequency */
  10406. this.stat_desc = stat_desc; /* the corresponding static tree */
  10407. }
  10408.  
  10409.  
  10410.  
  10411. function d_code(dist) {
  10412. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  10413. }
  10414.  
  10415.  
  10416. /* ===========================================================================
  10417. * Output a short LSB first on the stream.
  10418. * IN assertion: there is enough room in pendingBuf.
  10419. */
  10420. function put_short(s, w) {
  10421. // put_byte(s, (uch)((w) & 0xff));
  10422. // put_byte(s, (uch)((ush)(w) >> 8));
  10423. s.pending_buf[s.pending++] = (w) & 0xff;
  10424. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  10425. }
  10426.  
  10427.  
  10428. /* ===========================================================================
  10429. * Send a value on a given number of bits.
  10430. * IN assertion: length <= 16 and value fits in length bits.
  10431. */
  10432. function send_bits(s, value, length) {
  10433. if (s.bi_valid > (Buf_size - length)) {
  10434. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10435. put_short(s, s.bi_buf);
  10436. s.bi_buf = value >> (Buf_size - s.bi_valid);
  10437. s.bi_valid += length - Buf_size;
  10438. } else {
  10439. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10440. s.bi_valid += length;
  10441. }
  10442. }
  10443.  
  10444.  
  10445. function send_code(s, c, tree) {
  10446. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  10447. }
  10448.  
  10449.  
  10450. /* ===========================================================================
  10451. * Reverse the first len bits of a code, using straightforward code (a faster
  10452. * method would use a table)
  10453. * IN assertion: 1 <= len <= 15
  10454. */
  10455. function bi_reverse(code, len) {
  10456. var res = 0;
  10457. do {
  10458. res |= code & 1;
  10459. code >>>= 1;
  10460. res <<= 1;
  10461. } while (--len > 0);
  10462. return res >>> 1;
  10463. }
  10464.  
  10465.  
  10466. /* ===========================================================================
  10467. * Flush the bit buffer, keeping at most 7 bits in it.
  10468. */
  10469. function bi_flush(s) {
  10470. if (s.bi_valid === 16) {
  10471. put_short(s, s.bi_buf);
  10472. s.bi_buf = 0;
  10473. s.bi_valid = 0;
  10474.  
  10475. } else if (s.bi_valid >= 8) {
  10476. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  10477. s.bi_buf >>= 8;
  10478. s.bi_valid -= 8;
  10479. }
  10480. }
  10481.  
  10482.  
  10483. /* ===========================================================================
  10484. * Compute the optimal bit lengths for a tree and update the total bit length
  10485. * for the current block.
  10486. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  10487. * above are the tree nodes sorted by increasing frequency.
  10488. * OUT assertions: the field len is set to the optimal bit length, the
  10489. * array bl_count contains the frequencies for each bit length.
  10490. * The length opt_len is updated; static_len is also updated if stree is
  10491. * not null.
  10492. */
  10493. function gen_bitlen(s, desc)
  10494. // deflate_state *s;
  10495. // tree_desc *desc; /* the tree descriptor */
  10496. {
  10497. var tree = desc.dyn_tree;
  10498. var max_code = desc.max_code;
  10499. var stree = desc.stat_desc.static_tree;
  10500. var has_stree = desc.stat_desc.has_stree;
  10501. var extra = desc.stat_desc.extra_bits;
  10502. var base = desc.stat_desc.extra_base;
  10503. var max_length = desc.stat_desc.max_length;
  10504. var h; /* heap index */
  10505. var n, m; /* iterate over the tree elements */
  10506. var bits; /* bit length */
  10507. var xbits; /* extra bits */
  10508. var f; /* frequency */
  10509. var overflow = 0; /* number of elements with bit length too large */
  10510.  
  10511. for (bits = 0; bits <= MAX_BITS; bits++) {
  10512. s.bl_count[bits] = 0;
  10513. }
  10514.  
  10515. /* In a first pass, compute the optimal bit lengths (which may
  10516. * overflow in the case of the bit length tree).
  10517. */
  10518. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  10519.  
  10520. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  10521. n = s.heap[h];
  10522. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  10523. if (bits > max_length) {
  10524. bits = max_length;
  10525. overflow++;
  10526. }
  10527. tree[n * 2 + 1]/*.Len*/ = bits;
  10528. /* We overwrite tree[n].Dad which is no longer needed */
  10529.  
  10530. if (n > max_code) { continue; } /* not a leaf node */
  10531.  
  10532. s.bl_count[bits]++;
  10533. xbits = 0;
  10534. if (n >= base) {
  10535. xbits = extra[n - base];
  10536. }
  10537. f = tree[n * 2]/*.Freq*/;
  10538. s.opt_len += f * (bits + xbits);
  10539. if (has_stree) {
  10540. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  10541. }
  10542. }
  10543. if (overflow === 0) { return; }
  10544.  
  10545. // Trace((stderr,"\nbit length overflow\n"));
  10546. /* This happens for example on obj2 and pic of the Calgary corpus */
  10547.  
  10548. /* Find the first bit length which could increase: */
  10549. do {
  10550. bits = max_length - 1;
  10551. while (s.bl_count[bits] === 0) { bits--; }
  10552. s.bl_count[bits]--; /* move one leaf down the tree */
  10553. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  10554. s.bl_count[max_length]--;
  10555. /* The brother of the overflow item also moves one step up,
  10556. * but this does not affect bl_count[max_length]
  10557. */
  10558. overflow -= 2;
  10559. } while (overflow > 0);
  10560.  
  10561. /* Now recompute all bit lengths, scanning in increasing frequency.
  10562. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  10563. * lengths instead of fixing only the wrong ones. This idea is taken
  10564. * from 'ar' written by Haruhiko Okumura.)
  10565. */
  10566. for (bits = max_length; bits !== 0; bits--) {
  10567. n = s.bl_count[bits];
  10568. while (n !== 0) {
  10569. m = s.heap[--h];
  10570. if (m > max_code) { continue; }
  10571. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  10572. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  10573. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  10574. tree[m * 2 + 1]/*.Len*/ = bits;
  10575. }
  10576. n--;
  10577. }
  10578. }
  10579. }
  10580.  
  10581.  
  10582. /* ===========================================================================
  10583. * Generate the codes for a given tree and bit counts (which need not be
  10584. * optimal).
  10585. * IN assertion: the array bl_count contains the bit length statistics for
  10586. * the given tree and the field len is set for all tree elements.
  10587. * OUT assertion: the field code is set for all tree elements of non
  10588. * zero code length.
  10589. */
  10590. function gen_codes(tree, max_code, bl_count)
  10591. // ct_data *tree; /* the tree to decorate */
  10592. // int max_code; /* largest code with non zero frequency */
  10593. // ushf *bl_count; /* number of codes at each bit length */
  10594. {
  10595. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  10596. var code = 0; /* running code value */
  10597. var bits; /* bit index */
  10598. var n; /* code index */
  10599.  
  10600. /* The distribution counts are first used to generate the code values
  10601. * without bit reversal.
  10602. */
  10603. for (bits = 1; bits <= MAX_BITS; bits++) {
  10604. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  10605. }
  10606. /* Check that the bit counts in bl_count are consistent. The last code
  10607. * must be all ones.
  10608. */
  10609. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  10610. // "inconsistent bit counts");
  10611. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  10612.  
  10613. for (n = 0; n <= max_code; n++) {
  10614. var len = tree[n * 2 + 1]/*.Len*/;
  10615. if (len === 0) { continue; }
  10616. /* Now reverse the bits */
  10617. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  10618.  
  10619. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  10620. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  10621. }
  10622. }
  10623.  
  10624.  
  10625. /* ===========================================================================
  10626. * Initialize the various 'constant' tables.
  10627. */
  10628. function tr_static_init() {
  10629. var n; /* iterates over tree elements */
  10630. var bits; /* bit counter */
  10631. var length; /* length value */
  10632. var code; /* code value */
  10633. var dist; /* distance index */
  10634. var bl_count = new Array(MAX_BITS + 1);
  10635. /* number of codes at each bit length for an optimal tree */
  10636.  
  10637. // do check in _tr_init()
  10638. //if (static_init_done) return;
  10639.  
  10640. /* For some embedded targets, global variables are not initialized: */
  10641. /*#ifdef NO_INIT_GLOBAL_POINTERS
  10642. static_l_desc.static_tree = static_ltree;
  10643. static_l_desc.extra_bits = extra_lbits;
  10644. static_d_desc.static_tree = static_dtree;
  10645. static_d_desc.extra_bits = extra_dbits;
  10646. static_bl_desc.extra_bits = extra_blbits;
  10647. #endif*/
  10648.  
  10649. /* Initialize the mapping length (0..255) -> length code (0..28) */
  10650. length = 0;
  10651. for (code = 0; code < LENGTH_CODES - 1; code++) {
  10652. base_length[code] = length;
  10653. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  10654. _length_code[length++] = code;
  10655. }
  10656. }
  10657. //Assert (length == 256, "tr_static_init: length != 256");
  10658. /* Note that the length 255 (match length 258) can be represented
  10659. * in two different ways: code 284 + 5 bits or code 285, so we
  10660. * overwrite length_code[255] to use the best encoding:
  10661. */
  10662. _length_code[length - 1] = code;
  10663.  
  10664. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  10665. dist = 0;
  10666. for (code = 0; code < 16; code++) {
  10667. base_dist[code] = dist;
  10668. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  10669. _dist_code[dist++] = code;
  10670. }
  10671. }
  10672. //Assert (dist == 256, "tr_static_init: dist != 256");
  10673. dist >>= 7; /* from now on, all distances are divided by 128 */
  10674. for (; code < D_CODES; code++) {
  10675. base_dist[code] = dist << 7;
  10676. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  10677. _dist_code[256 + dist++] = code;
  10678. }
  10679. }
  10680. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  10681.  
  10682. /* Construct the codes of the static literal tree */
  10683. for (bits = 0; bits <= MAX_BITS; bits++) {
  10684. bl_count[bits] = 0;
  10685. }
  10686.  
  10687. n = 0;
  10688. while (n <= 143) {
  10689. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10690. n++;
  10691. bl_count[8]++;
  10692. }
  10693. while (n <= 255) {
  10694. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  10695. n++;
  10696. bl_count[9]++;
  10697. }
  10698. while (n <= 279) {
  10699. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  10700. n++;
  10701. bl_count[7]++;
  10702. }
  10703. while (n <= 287) {
  10704. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10705. n++;
  10706. bl_count[8]++;
  10707. }
  10708. /* Codes 286 and 287 do not exist, but we must include them in the
  10709. * tree construction to get a canonical Huffman tree (longest code
  10710. * all ones)
  10711. */
  10712. gen_codes(static_ltree, L_CODES + 1, bl_count);
  10713.  
  10714. /* The static distance tree is trivial: */
  10715. for (n = 0; n < D_CODES; n++) {
  10716. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  10717. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  10718. }
  10719.  
  10720. // Now data ready and we can init static trees
  10721. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  10722. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  10723. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  10724.  
  10725. //static_init_done = true;
  10726. }
  10727.  
  10728.  
  10729. /* ===========================================================================
  10730. * Initialize a new block.
  10731. */
  10732. function init_block(s) {
  10733. var n; /* iterates over tree elements */
  10734.  
  10735. /* Initialize the trees. */
  10736. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  10737. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  10738. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  10739.  
  10740. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  10741. s.opt_len = s.static_len = 0;
  10742. s.last_lit = s.matches = 0;
  10743. }
  10744.  
  10745.  
  10746. /* ===========================================================================
  10747. * Flush the bit buffer and align the output on a byte boundary
  10748. */
  10749. function bi_windup(s)
  10750. {
  10751. if (s.bi_valid > 8) {
  10752. put_short(s, s.bi_buf);
  10753. } else if (s.bi_valid > 0) {
  10754. //put_byte(s, (Byte)s->bi_buf);
  10755. s.pending_buf[s.pending++] = s.bi_buf;
  10756. }
  10757. s.bi_buf = 0;
  10758. s.bi_valid = 0;
  10759. }
  10760.  
  10761. /* ===========================================================================
  10762. * Copy a stored block, storing first the length and its
  10763. * one's complement if requested.
  10764. */
  10765. function copy_block(s, buf, len, header)
  10766. //DeflateState *s;
  10767. //charf *buf; /* the input data */
  10768. //unsigned len; /* its length */
  10769. //int header; /* true if block header must be written */
  10770. {
  10771. bi_windup(s); /* align on byte boundary */
  10772.  
  10773. if (header) {
  10774. put_short(s, len);
  10775. put_short(s, ~len);
  10776. }
  10777. // while (len--) {
  10778. // put_byte(s, *buf++);
  10779. // }
  10780. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  10781. s.pending += len;
  10782. }
  10783.  
  10784. /* ===========================================================================
  10785. * Compares to subtrees, using the tree depth as tie breaker when
  10786. * the subtrees have equal frequency. This minimizes the worst case length.
  10787. */
  10788. function smaller(tree, n, m, depth) {
  10789. var _n2 = n * 2;
  10790. var _m2 = m * 2;
  10791. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  10792. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  10793. }
  10794.  
  10795. /* ===========================================================================
  10796. * Restore the heap property by moving down the tree starting at node k,
  10797. * exchanging a node with the smallest of its two sons if necessary, stopping
  10798. * when the heap property is re-established (each father smaller than its
  10799. * two sons).
  10800. */
  10801. function pqdownheap(s, tree, k)
  10802. // deflate_state *s;
  10803. // ct_data *tree; /* the tree to restore */
  10804. // int k; /* node to move down */
  10805. {
  10806. var v = s.heap[k];
  10807. var j = k << 1; /* left son of k */
  10808. while (j <= s.heap_len) {
  10809. /* Set j to the smallest of the two sons: */
  10810. if (j < s.heap_len &&
  10811. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  10812. j++;
  10813. }
  10814. /* Exit if v is smaller than both sons */
  10815. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  10816.  
  10817. /* Exchange v with the smallest son */
  10818. s.heap[k] = s.heap[j];
  10819. k = j;
  10820.  
  10821. /* And continue down the tree, setting j to the left son of k */
  10822. j <<= 1;
  10823. }
  10824. s.heap[k] = v;
  10825. }
  10826.  
  10827.  
  10828. // inlined manually
  10829. // var SMALLEST = 1;
  10830.  
  10831. /* ===========================================================================
  10832. * Send the block data compressed using the given Huffman trees
  10833. */
  10834. function compress_block(s, ltree, dtree)
  10835. // deflate_state *s;
  10836. // const ct_data *ltree; /* literal tree */
  10837. // const ct_data *dtree; /* distance tree */
  10838. {
  10839. var dist; /* distance of matched string */
  10840. var lc; /* match length or unmatched char (if dist == 0) */
  10841. var lx = 0; /* running index in l_buf */
  10842. var code; /* the code to send */
  10843. var extra; /* number of extra bits to send */
  10844.  
  10845. if (s.last_lit !== 0) {
  10846. do {
  10847. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  10848. lc = s.pending_buf[s.l_buf + lx];
  10849. lx++;
  10850.  
  10851. if (dist === 0) {
  10852. send_code(s, lc, ltree); /* send a literal byte */
  10853. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  10854. } else {
  10855. /* Here, lc is the match length - MIN_MATCH */
  10856. code = _length_code[lc];
  10857. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  10858. extra = extra_lbits[code];
  10859. if (extra !== 0) {
  10860. lc -= base_length[code];
  10861. send_bits(s, lc, extra); /* send the extra length bits */
  10862. }
  10863. dist--; /* dist is now the match distance - 1 */
  10864. code = d_code(dist);
  10865. //Assert (code < D_CODES, "bad d_code");
  10866.  
  10867. send_code(s, code, dtree); /* send the distance code */
  10868. extra = extra_dbits[code];
  10869. if (extra !== 0) {
  10870. dist -= base_dist[code];
  10871. send_bits(s, dist, extra); /* send the extra distance bits */
  10872. }
  10873. } /* literal or match pair ? */
  10874.  
  10875. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  10876. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  10877. // "pendingBuf overflow");
  10878.  
  10879. } while (lx < s.last_lit);
  10880. }
  10881.  
  10882. send_code(s, END_BLOCK, ltree);
  10883. }
  10884.  
  10885.  
  10886. /* ===========================================================================
  10887. * Construct one Huffman tree and assigns the code bit strings and lengths.
  10888. * Update the total bit length for the current block.
  10889. * IN assertion: the field freq is set for all tree elements.
  10890. * OUT assertions: the fields len and code are set to the optimal bit length
  10891. * and corresponding code. The length opt_len is updated; static_len is
  10892. * also updated if stree is not null. The field max_code is set.
  10893. */
  10894. function build_tree(s, desc)
  10895. // deflate_state *s;
  10896. // tree_desc *desc; /* the tree descriptor */
  10897. {
  10898. var tree = desc.dyn_tree;
  10899. var stree = desc.stat_desc.static_tree;
  10900. var has_stree = desc.stat_desc.has_stree;
  10901. var elems = desc.stat_desc.elems;
  10902. var n, m; /* iterate over heap elements */
  10903. var max_code = -1; /* largest code with non zero frequency */
  10904. var node; /* new node being created */
  10905.  
  10906. /* Construct the initial heap, with least frequent element in
  10907. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  10908. * heap[0] is not used.
  10909. */
  10910. s.heap_len = 0;
  10911. s.heap_max = HEAP_SIZE;
  10912.  
  10913. for (n = 0; n < elems; n++) {
  10914. if (tree[n * 2]/*.Freq*/ !== 0) {
  10915. s.heap[++s.heap_len] = max_code = n;
  10916. s.depth[n] = 0;
  10917.  
  10918. } else {
  10919. tree[n * 2 + 1]/*.Len*/ = 0;
  10920. }
  10921. }
  10922.  
  10923. /* The pkzip format requires that at least one distance code exists,
  10924. * and that at least one bit should be sent even if there is only one
  10925. * possible code. So to avoid special checks later on we force at least
  10926. * two codes of non zero frequency.
  10927. */
  10928. while (s.heap_len < 2) {
  10929. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  10930. tree[node * 2]/*.Freq*/ = 1;
  10931. s.depth[node] = 0;
  10932. s.opt_len--;
  10933.  
  10934. if (has_stree) {
  10935. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  10936. }
  10937. /* node is 0 or 1 so it does not have extra bits */
  10938. }
  10939. desc.max_code = max_code;
  10940.  
  10941. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  10942. * establish sub-heaps of increasing lengths:
  10943. */
  10944. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  10945.  
  10946. /* Construct the Huffman tree by repeatedly combining the least two
  10947. * frequent nodes.
  10948. */
  10949. node = elems; /* next internal node of the tree */
  10950. do {
  10951. //pqremove(s, tree, n); /* n = node of least frequency */
  10952. /*** pqremove ***/
  10953. n = s.heap[1/*SMALLEST*/];
  10954. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  10955. pqdownheap(s, tree, 1/*SMALLEST*/);
  10956. /***/
  10957.  
  10958. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  10959.  
  10960. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  10961. s.heap[--s.heap_max] = m;
  10962.  
  10963. /* Create a new node father of n and m */
  10964. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  10965. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  10966. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  10967.  
  10968. /* and insert the new node in the heap */
  10969. s.heap[1/*SMALLEST*/] = node++;
  10970. pqdownheap(s, tree, 1/*SMALLEST*/);
  10971.  
  10972. } while (s.heap_len >= 2);
  10973.  
  10974. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  10975.  
  10976. /* At this point, the fields freq and dad are set. We can now
  10977. * generate the bit lengths.
  10978. */
  10979. gen_bitlen(s, desc);
  10980.  
  10981. /* The field len is now set, we can generate the bit codes */
  10982. gen_codes(tree, max_code, s.bl_count);
  10983. }
  10984.  
  10985.  
  10986. /* ===========================================================================
  10987. * Scan a literal or distance tree to determine the frequencies of the codes
  10988. * in the bit length tree.
  10989. */
  10990. function scan_tree(s, tree, max_code)
  10991. // deflate_state *s;
  10992. // ct_data *tree; /* the tree to be scanned */
  10993. // int max_code; /* and its largest code of non zero frequency */
  10994. {
  10995. var n; /* iterates over all tree elements */
  10996. var prevlen = -1; /* last emitted length */
  10997. var curlen; /* length of current code */
  10998.  
  10999. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  11000.  
  11001. var count = 0; /* repeat count of the current code */
  11002. var max_count = 7; /* max repeat count */
  11003. var min_count = 4; /* min repeat count */
  11004.  
  11005. if (nextlen === 0) {
  11006. max_count = 138;
  11007. min_count = 3;
  11008. }
  11009. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  11010.  
  11011. for (n = 0; n <= max_code; n++) {
  11012. curlen = nextlen;
  11013. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  11014.  
  11015. if (++count < max_count && curlen === nextlen) {
  11016. continue;
  11017.  
  11018. } else if (count < min_count) {
  11019. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  11020.  
  11021. } else if (curlen !== 0) {
  11022.  
  11023. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  11024. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  11025.  
  11026. } else if (count <= 10) {
  11027. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  11028.  
  11029. } else {
  11030. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  11031. }
  11032.  
  11033. count = 0;
  11034. prevlen = curlen;
  11035.  
  11036. if (nextlen === 0) {
  11037. max_count = 138;
  11038. min_count = 3;
  11039.  
  11040. } else if (curlen === nextlen) {
  11041. max_count = 6;
  11042. min_count = 3;
  11043.  
  11044. } else {
  11045. max_count = 7;
  11046. min_count = 4;
  11047. }
  11048. }
  11049. }
  11050.  
  11051.  
  11052. /* ===========================================================================
  11053. * Send a literal or distance tree in compressed form, using the codes in
  11054. * bl_tree.
  11055. */
  11056. function send_tree(s, tree, max_code)
  11057. // deflate_state *s;
  11058. // ct_data *tree; /* the tree to be scanned */
  11059. // int max_code; /* and its largest code of non zero frequency */
  11060. {
  11061. var n; /* iterates over all tree elements */
  11062. var prevlen = -1; /* last emitted length */
  11063. var curlen; /* length of current code */
  11064.  
  11065. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  11066.  
  11067. var count = 0; /* repeat count of the current code */
  11068. var max_count = 7; /* max repeat count */
  11069. var min_count = 4; /* min repeat count */
  11070.  
  11071. /* tree[max_code+1].Len = -1; */ /* guard already set */
  11072. if (nextlen === 0) {
  11073. max_count = 138;
  11074. min_count = 3;
  11075. }
  11076.  
  11077. for (n = 0; n <= max_code; n++) {
  11078. curlen = nextlen;
  11079. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  11080.  
  11081. if (++count < max_count && curlen === nextlen) {
  11082. continue;
  11083.  
  11084. } else if (count < min_count) {
  11085. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  11086.  
  11087. } else if (curlen !== 0) {
  11088. if (curlen !== prevlen) {
  11089. send_code(s, curlen, s.bl_tree);
  11090. count--;
  11091. }
  11092. //Assert(count >= 3 && count <= 6, " 3_6?");
  11093. send_code(s, REP_3_6, s.bl_tree);
  11094. send_bits(s, count - 3, 2);
  11095.  
  11096. } else if (count <= 10) {
  11097. send_code(s, REPZ_3_10, s.bl_tree);
  11098. send_bits(s, count - 3, 3);
  11099.  
  11100. } else {
  11101. send_code(s, REPZ_11_138, s.bl_tree);
  11102. send_bits(s, count - 11, 7);
  11103. }
  11104.  
  11105. count = 0;
  11106. prevlen = curlen;
  11107. if (nextlen === 0) {
  11108. max_count = 138;
  11109. min_count = 3;
  11110.  
  11111. } else if (curlen === nextlen) {
  11112. max_count = 6;
  11113. min_count = 3;
  11114.  
  11115. } else {
  11116. max_count = 7;
  11117. min_count = 4;
  11118. }
  11119. }
  11120. }
  11121.  
  11122.  
  11123. /* ===========================================================================
  11124. * Construct the Huffman tree for the bit lengths and return the index in
  11125. * bl_order of the last bit length code to send.
  11126. */
  11127. function build_bl_tree(s) {
  11128. var max_blindex; /* index of last bit length code of non zero freq */
  11129.  
  11130. /* Determine the bit length frequencies for literal and distance trees */
  11131. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  11132. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  11133.  
  11134. /* Build the bit length tree: */
  11135. build_tree(s, s.bl_desc);
  11136. /* opt_len now includes the length of the tree representations, except
  11137. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  11138. */
  11139.  
  11140. /* Determine the number of bit length codes to send. The pkzip format
  11141. * requires that at least 4 bit length codes be sent. (appnote.txt says
  11142. * 3 but the actual value used is 4.)
  11143. */
  11144. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  11145. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  11146. break;
  11147. }
  11148. }
  11149. /* Update opt_len to include the bit length tree and counts */
  11150. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  11151. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  11152. // s->opt_len, s->static_len));
  11153.  
  11154. return max_blindex;
  11155. }
  11156.  
  11157.  
  11158. /* ===========================================================================
  11159. * Send the header for a block using dynamic Huffman trees: the counts, the
  11160. * lengths of the bit length codes, the literal tree and the distance tree.
  11161. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  11162. */
  11163. function send_all_trees(s, lcodes, dcodes, blcodes)
  11164. // deflate_state *s;
  11165. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  11166. {
  11167. var rank; /* index in bl_order */
  11168.  
  11169. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  11170. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  11171. // "too many codes");
  11172. //Tracev((stderr, "\nbl counts: "));
  11173. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  11174. send_bits(s, dcodes - 1, 5);
  11175. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  11176. for (rank = 0; rank < blcodes; rank++) {
  11177. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  11178. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  11179. }
  11180. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  11181.  
  11182. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  11183. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  11184.  
  11185. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  11186. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  11187. }
  11188.  
  11189.  
  11190. /* ===========================================================================
  11191. * Check if the data type is TEXT or BINARY, using the following algorithm:
  11192. * - TEXT if the two conditions below are satisfied:
  11193. * a) There are no non-portable control characters belonging to the
  11194. * "black list" (0..6, 14..25, 28..31).
  11195. * b) There is at least one printable character belonging to the
  11196. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  11197. * - BINARY otherwise.
  11198. * - The following partially-portable control characters form a
  11199. * "gray list" that is ignored in this detection algorithm:
  11200. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  11201. * IN assertion: the fields Freq of dyn_ltree are set.
  11202. */
  11203. function detect_data_type(s) {
  11204. /* black_mask is the bit mask of black-listed bytes
  11205. * set bits 0..6, 14..25, and 28..31
  11206. * 0xf3ffc07f = binary 11110011111111111100000001111111
  11207. */
  11208. var black_mask = 0xf3ffc07f;
  11209. var n;
  11210.  
  11211. /* Check for non-textual ("black-listed") bytes. */
  11212. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  11213. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  11214. return Z_BINARY;
  11215. }
  11216. }
  11217.  
  11218. /* Check for textual ("white-listed") bytes. */
  11219. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  11220. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  11221. return Z_TEXT;
  11222. }
  11223. for (n = 32; n < LITERALS; n++) {
  11224. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  11225. return Z_TEXT;
  11226. }
  11227. }
  11228.  
  11229. /* There are no "black-listed" or "white-listed" bytes:
  11230. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  11231. */
  11232. return Z_BINARY;
  11233. }
  11234.  
  11235.  
  11236. var static_init_done = false;
  11237.  
  11238. /* ===========================================================================
  11239. * Initialize the tree data structures for a new zlib stream.
  11240. */
  11241. function _tr_init(s)
  11242. {
  11243.  
  11244. if (!static_init_done) {
  11245. tr_static_init();
  11246. static_init_done = true;
  11247. }
  11248.  
  11249. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  11250. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  11251. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  11252.  
  11253. s.bi_buf = 0;
  11254. s.bi_valid = 0;
  11255.  
  11256. /* Initialize the first block of the first file: */
  11257. init_block(s);
  11258. }
  11259.  
  11260.  
  11261. /* ===========================================================================
  11262. * Send a stored block
  11263. */
  11264. function _tr_stored_block(s, buf, stored_len, last)
  11265. //DeflateState *s;
  11266. //charf *buf; /* input block */
  11267. //ulg stored_len; /* length of input block */
  11268. //int last; /* one if this is the last block for a file */
  11269. {
  11270. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  11271. copy_block(s, buf, stored_len, true); /* with header */
  11272. }
  11273.  
  11274.  
  11275. /* ===========================================================================
  11276. * Send one empty static block to give enough lookahead for inflate.
  11277. * This takes 10 bits, of which 7 may remain in the bit buffer.
  11278. */
  11279. function _tr_align(s) {
  11280. send_bits(s, STATIC_TREES << 1, 3);
  11281. send_code(s, END_BLOCK, static_ltree);
  11282. bi_flush(s);
  11283. }
  11284.  
  11285.  
  11286. /* ===========================================================================
  11287. * Determine the best encoding for the current block: dynamic trees, static
  11288. * trees or store, and output the encoded block to the zip file.
  11289. */
  11290. function _tr_flush_block(s, buf, stored_len, last)
  11291. //DeflateState *s;
  11292. //charf *buf; /* input block, or NULL if too old */
  11293. //ulg stored_len; /* length of input block */
  11294. //int last; /* one if this is the last block for a file */
  11295. {
  11296. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  11297. var max_blindex = 0; /* index of last bit length code of non zero freq */
  11298.  
  11299. /* Build the Huffman trees unless a stored block is forced */
  11300. if (s.level > 0) {
  11301.  
  11302. /* Check if the file is binary or text */
  11303. if (s.strm.data_type === Z_UNKNOWN) {
  11304. s.strm.data_type = detect_data_type(s);
  11305. }
  11306.  
  11307. /* Construct the literal and distance trees */
  11308. build_tree(s, s.l_desc);
  11309. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  11310. // s->static_len));
  11311.  
  11312. build_tree(s, s.d_desc);
  11313. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  11314. // s->static_len));
  11315. /* At this point, opt_len and static_len are the total bit lengths of
  11316. * the compressed block data, excluding the tree representations.
  11317. */
  11318.  
  11319. /* Build the bit length tree for the above two trees, and get the index
  11320. * in bl_order of the last bit length code to send.
  11321. */
  11322. max_blindex = build_bl_tree(s);
  11323.  
  11324. /* Determine the best encoding. Compute the block lengths in bytes. */
  11325. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  11326. static_lenb = (s.static_len + 3 + 7) >>> 3;
  11327.  
  11328. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  11329. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  11330. // s->last_lit));
  11331.  
  11332. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  11333.  
  11334. } else {
  11335. // Assert(buf != (char*)0, "lost buf");
  11336. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  11337. }
  11338.  
  11339. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  11340. /* 4: two words for the lengths */
  11341.  
  11342. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  11343. * Otherwise we can't have processed more than WSIZE input bytes since
  11344. * the last block flush, because compression would have been
  11345. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  11346. * transform a block into a stored block.
  11347. */
  11348. _tr_stored_block(s, buf, stored_len, last);
  11349.  
  11350. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  11351.  
  11352. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  11353. compress_block(s, static_ltree, static_dtree);
  11354.  
  11355. } else {
  11356. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  11357. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  11358. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  11359. }
  11360. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  11361. /* The above check is made mod 2^32, for files larger than 512 MB
  11362. * and uLong implemented on 32 bits.
  11363. */
  11364. init_block(s);
  11365.  
  11366. if (last) {
  11367. bi_windup(s);
  11368. }
  11369. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  11370. // s->compressed_len-7*last));
  11371. }
  11372.  
  11373. /* ===========================================================================
  11374. * Save the match info and tally the frequency counts. Return true if
  11375. * the current block must be flushed.
  11376. */
  11377. function _tr_tally(s, dist, lc)
  11378. // deflate_state *s;
  11379. // unsigned dist; /* distance of matched string */
  11380. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  11381. {
  11382. //var out_length, in_length, dcode;
  11383.  
  11384. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  11385. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  11386.  
  11387. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  11388. s.last_lit++;
  11389.  
  11390. if (dist === 0) {
  11391. /* lc is the unmatched char */
  11392. s.dyn_ltree[lc * 2]/*.Freq*/++;
  11393. } else {
  11394. s.matches++;
  11395. /* Here, lc is the match length - MIN_MATCH */
  11396. dist--; /* dist = match distance - 1 */
  11397. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  11398. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  11399. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  11400.  
  11401. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  11402. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  11403. }
  11404.  
  11405. // (!) This block is disabled in zlib defailts,
  11406. // don't enable it for binary compatibility
  11407.  
  11408. //#ifdef TRUNCATE_BLOCK
  11409. // /* Try to guess if it is profitable to stop the current block here */
  11410. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  11411. // /* Compute an upper bound for the compressed length */
  11412. // out_length = s.last_lit*8;
  11413. // in_length = s.strstart - s.block_start;
  11414. //
  11415. // for (dcode = 0; dcode < D_CODES; dcode++) {
  11416. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  11417. // }
  11418. // out_length >>>= 3;
  11419. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  11420. // // s->last_lit, in_length, out_length,
  11421. // // 100L - out_length*100L/in_length));
  11422. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  11423. // return true;
  11424. // }
  11425. // }
  11426. //#endif
  11427.  
  11428. return (s.last_lit === s.lit_bufsize - 1);
  11429. /* We avoid equality with lit_bufsize because of wraparound at 64K
  11430. * on 16 bit machines and because stored blocks are restricted to
  11431. * 64K-1 bytes.
  11432. */
  11433. }
  11434.  
  11435. exports._tr_init = _tr_init;
  11436. exports._tr_stored_block = _tr_stored_block;
  11437. exports._tr_flush_block = _tr_flush_block;
  11438. exports._tr_tally = _tr_tally;
  11439. exports._tr_align = _tr_align;
  11440.  
  11441. },{"../utils/common":62}],74:[function(require,module,exports){
  11442. 'use strict';
  11443.  
  11444.  
  11445. function ZStream() {
  11446. /* next input byte */
  11447. this.input = null; // JS specific, because we have no pointers
  11448. this.next_in = 0;
  11449. /* number of bytes available at input */
  11450. this.avail_in = 0;
  11451. /* total number of input bytes read so far */
  11452. this.total_in = 0;
  11453. /* next output byte should be put there */
  11454. this.output = null; // JS specific, because we have no pointers
  11455. this.next_out = 0;
  11456. /* remaining free space at output */
  11457. this.avail_out = 0;
  11458. /* total number of bytes output so far */
  11459. this.total_out = 0;
  11460. /* last error message, NULL if no error */
  11461. this.msg = ''/*Z_NULL*/;
  11462. /* not visible by applications */
  11463. this.state = null;
  11464. /* best guess about the data type: binary or text */
  11465. this.data_type = 2/*Z_UNKNOWN*/;
  11466. /* adler32 value of the uncompressed data */
  11467. this.adler = 0;
  11468. }
  11469.  
  11470. module.exports = ZStream;
  11471.  
  11472. },{}]},{},[10])(10)
  11473. });/* FileSaver.js
  11474. * A saveAs() FileSaver implementation.
  11475. * 1.1.20160328
  11476. *
  11477. * By Eli Grey, http://eligrey.com
  11478. * License: MIT
  11479. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  11480. */
  11481.  
  11482. /*global self */
  11483. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  11484.  
  11485. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  11486.  
  11487. var saveAs = saveAs || (function(view) {
  11488. "use strict";
  11489. // IE <10 is explicitly unsupported
  11490. if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  11491. return;
  11492. }
  11493. var
  11494. doc = view.document
  11495. // only get URL when necessary in case Blob.js hasn't overridden it yet
  11496. , get_URL = function() {
  11497. return view.URL || view.webkitURL || view;
  11498. }
  11499. , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  11500. , can_use_save_link = "download" in save_link
  11501. , click = function(node) {
  11502. var event = new MouseEvent("click");
  11503. node.dispatchEvent(event);
  11504. }
  11505. , is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent)
  11506. , webkit_req_fs = view.webkitRequestFileSystem
  11507. , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
  11508. , throw_outside = function(ex) {
  11509. (view.setImmediate || view.setTimeout)(function() {
  11510. throw ex;
  11511. }, 0);
  11512. }
  11513. , force_saveable_type = "application/octet-stream"
  11514. , fs_min_size = 0
  11515. // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
  11516. , arbitrary_revoke_timeout = 1000 * 40 // in ms
  11517. , revoke = function(file) {
  11518. var revoker = function() {
  11519. if (typeof file === "string") { // file is an object URL
  11520. get_URL().revokeObjectURL(file);
  11521. } else { // file is a File
  11522. file.remove();
  11523. }
  11524. };
  11525. /* // Take note W3C:
  11526. var
  11527. uri = typeof file === "string" ? file : file.toURL()
  11528. , revoker = function(evt) {
  11529. // idealy DownloadFinishedEvent.data would be the URL requested
  11530. if (evt.data === uri) {
  11531. if (typeof file === "string") { // file is an object URL
  11532. get_URL().revokeObjectURL(file);
  11533. } else { // file is a File
  11534. file.remove();
  11535. }
  11536. }
  11537. }
  11538. ;
  11539. view.addEventListener("downloadfinished", revoker);
  11540. */
  11541. setTimeout(revoker, arbitrary_revoke_timeout);
  11542. }
  11543. , dispatch = function(filesaver, event_types, event) {
  11544. event_types = [].concat(event_types);
  11545. var i = event_types.length;
  11546. while (i--) {
  11547. var listener = filesaver["on" + event_types[i]];
  11548. if (typeof listener === "function") {
  11549. try {
  11550. listener.call(filesaver, event || filesaver);
  11551. } catch (ex) {
  11552. throw_outside(ex);
  11553. }
  11554. }
  11555. }
  11556. }
  11557. , auto_bom = function(blob) {
  11558. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  11559. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  11560. return new Blob(["\ufeff", blob], {type: blob.type});
  11561. }
  11562. return blob;
  11563. }
  11564. , FileSaver = function(blob, name, no_auto_bom) {
  11565. if (!no_auto_bom) {
  11566. blob = auto_bom(blob);
  11567. }
  11568. // First try a.download, then web filesystem, then object URLs
  11569. var
  11570. filesaver = this
  11571. , type = blob.type
  11572. , blob_changed = false
  11573. , object_url
  11574. , target_view
  11575. , dispatch_all = function() {
  11576. dispatch(filesaver, "writestart progress write writeend".split(" "));
  11577. }
  11578. // on any filesys errors revert to saving with object URLs
  11579. , fs_error = function() {
  11580. if (target_view && is_safari && typeof FileReader !== "undefined") {
  11581. // Safari doesn't allow downloading of blob urls
  11582. var reader = new FileReader();
  11583. reader.onloadend = function() {
  11584. var base64Data = reader.result;
  11585. target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
  11586. filesaver.readyState = filesaver.DONE;
  11587. dispatch_all();
  11588. };
  11589. reader.readAsDataURL(blob);
  11590. filesaver.readyState = filesaver.INIT;
  11591. return;
  11592. }
  11593. // don't create more object URLs than needed
  11594. if (blob_changed || !object_url) {
  11595. object_url = get_URL().createObjectURL(blob);
  11596. }
  11597. if (target_view) {
  11598. target_view.location.href = object_url;
  11599. } else {
  11600. var new_tab = view.open(object_url, "_blank");
  11601. if (new_tab === undefined && is_safari) {
  11602. //Apple do not allow window.open, see http://bit.ly/1kZffRI
  11603. view.location.href = object_url
  11604. }
  11605. }
  11606. filesaver.readyState = filesaver.DONE;
  11607. dispatch_all();
  11608. revoke(object_url);
  11609. }
  11610. , abortable = function(func) {
  11611. return function() {
  11612. if (filesaver.readyState !== filesaver.DONE) {
  11613. return func.apply(this, arguments);
  11614. }
  11615. };
  11616. }
  11617. , create_if_not_found = {create: true, exclusive: false}
  11618. , slice
  11619. ;
  11620. filesaver.readyState = filesaver.INIT;
  11621. if (!name) {
  11622. name = "download";
  11623. }
  11624. if (can_use_save_link) {
  11625. object_url = get_URL().createObjectURL(blob);
  11626. setTimeout(function() {
  11627. save_link.href = object_url;
  11628. save_link.download = name;
  11629. click(save_link);
  11630. dispatch_all();
  11631. revoke(object_url);
  11632. filesaver.readyState = filesaver.DONE;
  11633. });
  11634. return;
  11635. }
  11636. // Object and web filesystem URLs have a problem saving in Google Chrome when
  11637. // viewed in a tab, so I force save with application/octet-stream
  11638. // http://code.google.com/p/chromium/issues/detail?id=91158
  11639. // Update: Google errantly closed 91158, I submitted it again:
  11640. // https://code.google.com/p/chromium/issues/detail?id=389642
  11641. if (view.chrome && type && type !== force_saveable_type) {
  11642. slice = blob.slice || blob.webkitSlice;
  11643. blob = slice.call(blob, 0, blob.size, force_saveable_type);
  11644. blob_changed = true;
  11645. }
  11646. // Since I can't be sure that the guessed media type will trigger a download
  11647. // in WebKit, I append .download to the filename.
  11648. // https://bugs.webkit.org/show_bug.cgi?id=65440
  11649. if (webkit_req_fs && name !== "download") {
  11650. name += ".download";
  11651. }
  11652. if (type === force_saveable_type || webkit_req_fs) {
  11653. target_view = view;
  11654. }
  11655. if (!req_fs) {
  11656. fs_error();
  11657. return;
  11658. }
  11659. fs_min_size += blob.size;
  11660. req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
  11661. fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
  11662. var save = function() {
  11663. dir.getFile(name, create_if_not_found, abortable(function(file) {
  11664. file.createWriter(abortable(function(writer) {
  11665. writer.onwriteend = function(event) {
  11666. target_view.location.href = file.toURL();
  11667. filesaver.readyState = filesaver.DONE;
  11668. dispatch(filesaver, "writeend", event);
  11669. revoke(file);
  11670. };
  11671. writer.onerror = function() {
  11672. var error = writer.error;
  11673. if (error.code !== error.ABORT_ERR) {
  11674. fs_error();
  11675. }
  11676. };
  11677. "writestart progress write abort".split(" ").forEach(function(event) {
  11678. writer["on" + event] = filesaver["on" + event];
  11679. });
  11680. writer.write(blob);
  11681. filesaver.abort = function() {
  11682. writer.abort();
  11683. filesaver.readyState = filesaver.DONE;
  11684. };
  11685. filesaver.readyState = filesaver.WRITING;
  11686. }), fs_error);
  11687. }), fs_error);
  11688. };
  11689. dir.getFile(name, {create: false}, abortable(function(file) {
  11690. // delete file if it already exists
  11691. file.remove();
  11692. save();
  11693. }), abortable(function(ex) {
  11694. if (ex.code === ex.NOT_FOUND_ERR) {
  11695. save();
  11696. } else {
  11697. fs_error();
  11698. }
  11699. }));
  11700. }), fs_error);
  11701. }), fs_error);
  11702. }
  11703. , FS_proto = FileSaver.prototype
  11704. , saveAs = function(blob, name, no_auto_bom) {
  11705. return new FileSaver(blob, name, no_auto_bom);
  11706. }
  11707. ;
  11708. // IE 10+ (native saveAs)
  11709. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  11710. return function(blob, name, no_auto_bom) {
  11711. if (!no_auto_bom) {
  11712. blob = auto_bom(blob);
  11713. }
  11714. return navigator.msSaveOrOpenBlob(blob, name || "download");
  11715. };
  11716. }
  11717.  
  11718. FS_proto.abort = function() {
  11719. var filesaver = this;
  11720. filesaver.readyState = filesaver.DONE;
  11721. dispatch(filesaver, "abort");
  11722. };
  11723. FS_proto.readyState = FS_proto.INIT = 0;
  11724. FS_proto.WRITING = 1;
  11725. FS_proto.DONE = 2;
  11726.  
  11727. FS_proto.error =
  11728. FS_proto.onwritestart =
  11729. FS_proto.onprogress =
  11730. FS_proto.onwrite =
  11731. FS_proto.onabort =
  11732. FS_proto.onerror =
  11733. FS_proto.onwriteend =
  11734. null;
  11735.  
  11736. return saveAs;
  11737. }(
  11738. typeof self !== "undefined" && self
  11739. || typeof window !== "undefined" && window
  11740. || this.content
  11741. ));
  11742. // `self` is undefined in Firefox for Android content script context
  11743. // while `this` is nsIContentFrameMessageManager
  11744. // with an attribute `content` that corresponds to the window
  11745.  
  11746. if (typeof module !== "undefined" && module.exports) {
  11747. module.exports.saveAs = saveAs;
  11748. } else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
  11749. define([], function() {
  11750. return saveAs;
  11751. });
  11752. }
  11753.  
  11754. var zip;
  11755. var imageList = [];
  11756. var imageData = [];
  11757. var infoStr;
  11758. var origin = window.location.origin;
  11759. var setting = null;
  11760. var fetchCount = 0;
  11761. var downloadedCount = 0;
  11762. var totalCount = 0;
  11763. var retryCount = 0;
  11764. var failedCount = 0;
  11765. var fetchThread = [];
  11766. var dirName;
  11767. var fileName;
  11768. var progressTable = null;
  11769. var needNumberImages = false;
  11770. var pagesRange = [];
  11771. var isDownloading = false;
  11772. var isPausing = false;
  11773. var isSaving = false;
  11774. var pageURLsList = [];
  11775. var getAllPagesURLFin = false;
  11776. var pretitle = document.title;
  11777. var needTitleStatus = false;
  11778. var fetchPagesXHR = new XMLHttpRequest();
  11779. var emptyAudio;
  11780. 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';
  11781.  
  11782.  
  11783. var ehDownloadRegex = {
  11784. imageURL: [
  11785. /<a href="(\S+?\/fullimg\.php\?\S+?)"/,
  11786. /<img id="img" src="(\S+?)"/,
  11787. /<\/(?:script|iframe)><a[\s\S]+?><img src="(\S+?)"/ // Sometimes preview image may not have id="img"
  11788. ],
  11789. nextFetchURL: [
  11790. /<a id="next"[\s\S]+?href="(\S+?\/s\/\S+?)"/,
  11791. /<a href="(\S+?\/s\/\S+?)"><img src="https?:\/\/ehgt.org\/g\/n.png"/
  11792. ],
  11793. preFetchURL: /<div class="sn"><a[\s\S]+?href="(\S+?\/s\/\S+?)"/,
  11794. nl: /return nl\('([\d-]+)'\)/,
  11795. fileName: /g\/l.png"\s?\/><\/a><\/div><div>([\s\S]+?) :: /,
  11796. resFileName: /filename=['"]?([\s\S]+?)['"]?$/m,
  11797. dangerChars: /[:"*?|<>\/\\\n]/g,
  11798. pagesRange: /^(\d*(-\d*)?\s*?,\s*?)*\d*(-\d*)?$/,
  11799. pagesURL: /(?:<a href=").+?(?=")/gi,
  11800. mpvKey: /var imagelist\s*=\s*(\[.+?\]);/,
  11801. imageLimits: /You are currently at <strong>(\d+)<\/strong> towards a limit of <strong>(\d+)<\/strong>/,
  11802. pagesLength: /<table class="ptt".+>(\d+)<\/a>.+?<\/table>/,
  11803. IPBanExpires: /The ban expires in \d+ hours?( and \d+ minutes?)?/
  11804. };
  11805.  
  11806. var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
  11807. var ehDownloadFS = {
  11808. fs: undefined,
  11809. needFileSystem: false,
  11810. initHandler: function(fs) {
  11811. ehDownloadFS.fs = fs;
  11812. console.log('[EHD] File System is opened! Name >', fs.name);
  11813. ehDownloadFS.removeAllFiles(fs); // It's sure that user have downloaded or ignored temp archive
  11814. },
  11815. errorHandler: function(e) {
  11816. var errorMsg = 'File System Request Error > ';
  11817. errorMsg += e.name || 'Unknown Error';
  11818. console.error('[EHD] ' + errorMsg, e.message);
  11819. console.error(e);
  11820. },
  11821. saveAs: function(fs, forced){
  11822. var fs = fs || ehDownloadFS.fs;
  11823. if (fs === undefined) return;
  11824. fs.root.getFile(unsafeWindow.gid + '.zip', {}, function (fileEntry) {
  11825. var url = fileEntry.toURL();
  11826. console.log('[EHD] File URL >', url);
  11827. var a = document.createElement('a');
  11828. a.setAttribute('href', url);
  11829. a.setAttribute('download', fileName + (setting['save-as-cbz'] ? '.cbz' : '.zip'));
  11830. a.click();
  11831. 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');
  11832. if (!forced) {
  11833. insertCloseButton();
  11834. if (emptyAudio) {
  11835. emptyAudio.pause();
  11836. }
  11837. }
  11838. });
  11839. },
  11840. removeFile: function(fileName, fs, isEntry){
  11841. var fs = fs || ehDownloadFS.fs;
  11842. if (fs === undefined) return;
  11843. var removeFunction = function(fileEntry){
  11844. if (fileEntry.isFile) fileEntry.remove(function(){
  11845. console.log('[EHD] File', fileName, 'is removed.');
  11846. });
  11847. else if (fileEntry.isDirectory) fileEntry.removeRecursively(function() {
  11848. console.log('[EHD] Directory', fileName, 'is removed.');
  11849. });
  11850. };
  11851. if (isEntry) removeFunction(fileName);
  11852. else fs.root.getFile(fileName, {create: false}, removeFunction);
  11853. },
  11854. removeAllFiles: function(fs){
  11855. var fs = fs || ehDownloadFS.fs;
  11856. if (fs === undefined) return;
  11857. console.log('[EHD] Request removing all files in File System.');
  11858. fs.root.createReader().readEntries(function(entries){
  11859. if (entries.length === 0) return;
  11860. for (var i = 0; i < entries.length; i++) {
  11861. ehDownloadFS.removeFile(entries[i], fs, true);
  11862. }
  11863. }, ehDownloadFS.errorHandler);
  11864. },
  11865. initCheckerHandler: function(fs) {
  11866. //ehDownloadFS.fs = fs;
  11867. console.log('[EHD] File System is opened! Name >', fs.name);
  11868. ehDownloadFS.removeFile(unsafeWindow.gid + '.zip', fs);
  11869. fs.root.getFile('config.txt', {create: false}, function(fileEntry){
  11870. fileEntry.file(function(file){
  11871. var fileReader = new FileReader();
  11872. fileReader.onloadend = function() {
  11873. var value = this.result;
  11874. if (value === '' || value == null) return;
  11875. var data = JSON.parse(value);
  11876. 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.')) {
  11877. fileName = data.fileName;
  11878. dirName = data.dirName;
  11879. ehDownloadFS.storeTempArchive(data, fs);
  11880. }
  11881. else {
  11882. ehDownloadFS.removeAllFiles(fs);
  11883. }
  11884. };
  11885. fileReader.readAsText(file);
  11886. });
  11887. });
  11888. },
  11889. storeTempArchive: function(data, fs){
  11890. var fs = fs || ehDownloadFS.fs;
  11891. if (fs === undefined) return;
  11892. fs.root.getDirectory('raw', {}, function(fileEntry){
  11893. fileEntry.createReader().readEntries(function(entries){
  11894. if (entries.length === 0) return;
  11895. var index = 0;
  11896. var fileReader = new FileReader();
  11897. zip = new JSZip();
  11898. ehDownloadDialog.style.display = 'block';
  11899. ehDownloadDialog.innerHTML = '';
  11900. pushDialog('Preparing......');
  11901. fileReader.onloadend = function() {
  11902. (data.dirName ? zip.folder(data.dirName) : zip).file(entries[index].name, this.result);
  11903. index++;
  11904. if (index < entries.length) addFile();
  11905. else {
  11906. ehDownloadFS.removeAllFiles();
  11907. setTimeout(generateZip, 3000, true, fs); // wait for removing all files
  11908. }
  11909. };
  11910. var addFile = function(){
  11911. console.log('[EHD] TempArchiveFileIndex >', index, '| TempArchiveFileName >', entries[index].name, '| TempArchiveFilePath >', entries[index].fullPath, '| TempArchiveFileLength >', entries.length);
  11912. pushDialog('\n' + (index + 1) + '/' + entries.length);
  11913. fs.root.getFile(entries[index].fullPath, {create: false}, function(fileEntry){
  11914. fileEntry.file(function(file){
  11915. fileReader.readAsArrayBuffer(file);
  11916. });
  11917. });
  11918. };
  11919. addFile();
  11920. }, ehDownloadFS.errorHandler);
  11921. }, ehDownloadFS.errorHandler);
  11922. }
  11923. };
  11924.  
  11925. var ehDownloadStyle = '\
  11926. @-webkit-keyframes progress { \
  11927. from { -webkit-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \
  11928. 50% { -webkit-transform: translateX(0%) scaleX(1); transform: translateX(0%) scaleX(1); } \
  11929. to { -webkit-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \
  11930. } \
  11931. @-moz-keyframes progress { \
  11932. from { -moz-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \
  11933. 50% { -moz-transform: translateX(0%) scaleX(1); transform: translateX(0%) scaleX(1); } \
  11934. to { -moz-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \
  11935. } \
  11936. @-ms-keyframes progress { \
  11937. from { -ms-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \
  11938. 50% { -ms-transform: translateX(0%) scaleX(1); transform: translateX(0%) scaleX(1); } \
  11939. to { -ms-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \
  11940. } \
  11941. @keyframes progress { \
  11942. from { -webkit-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \
  11943. 50% { -webkit-transform: translateX(0%) scaleX(1); transform: translateX(0%) scaleX(1); } \
  11944. to { -webkit-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \
  11945. } \
  11946. .ehD-box { margin: 20px auto; width: 732px; box-sizing: border-box; font-size: 12px; border: 1px groove #000000; }\
  11947. .ehD-box a { cursor: pointer; }\
  11948. .ehD-box .g2 { display: inline-block; margin: 10px; padding: 0; line-height: 14px; }\
  11949. .ehD-box legend a { color: inherit; text-decoration: none; }\
  11950. .ehD-box-extend input { width: 255px; }\
  11951. .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; }\
  11952. .ehD-setting-tab { list-style: none; margin: 5px 0; padding: 0 10px; border-bottom: 1px solid #cccccc; overflow: auto; }\
  11953. .ehD-setting-tab li { float: left; padding: 5px 10px; border-bottom: 0; cursor: pointer; }\
  11954. .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; }\
  11955. .ehD-setting-main { overflow: hidden }\
  11956. .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); }\
  11957. .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%); }\
  11958. .ehD-setting-content { width: 50%; float: left; box-sizing: border-box; padding: 5px 10px; height: 295px; max-height: calc(100vh - 85px); overflow: auto; }\
  11959. .ehD-setting .g2 { padding-bottom: 10px; }\
  11960. .ehD-setting input, .ehD-box input { vertical-align: middle; }\
  11961. .ehD-setting input[type="text"], .ehD-box input[type="text"], .ehD-setting input[type="number"] { height: 13px; }\
  11962. .ehD-setting input[type="checkbox"] { margin: 3px 3px 3px 0 } \
  11963. .ehD-setting-note { border: 1px dashed #999999; padding: 10px 10px 0 10px; }\
  11964. .ehD-setting-footer { text-align: center; margin-top: 5px; border-top: 1px solid #cccccc; padding-top: 5px; }\
  11965. .ehD-setting sup { vertical-align: top; }\
  11966. .ehD-box input[type="number"] { height: 17px; }\
  11967. .ehD-dialog progress { height: 12px; -webkit-appearance: none; border: 1px solid #4f535b; color: #4f535b; background: #34353b; position: relative; } \
  11968. .ehD-dialog progress::-webkit-progress-bar { background: #34353b; } \
  11969. .ehD-dialog progress::-webkit-progress-value { background: #4f535b; -webkit-transition: all 0.2s ease; transition: all 0.2s ease; } \
  11970. .ehD-dialog progress::-moz-progress-bar { background: #4f535b; -moz-transition: all 0.2s ease; transition: all 0.2s ease; } \
  11971. .ehD-dialog progress::-ms-fill { background: #4f535b; -ms-transition: all 0.2s ease; transition: all 0.2s ease; } \
  11972. .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 ease-in-out alternate infinite; -moz-animation: progress 1s ease-in-out alternate infinite; -ms-animation: progress 1s ease-in-out alternate infinite; animation: progress 1s ease-in-out alternate infinite; } \
  11973. .ehD-dialog progress:not([value])::-moz-progress-bar { width: 0px !important; } \
  11974. .ehD-pt { table-layout: fixed; width: 100%; }\
  11975. .ehD-pt-name { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\
  11976. .ehD-pt-progress-outer { width: 160px; position: relative; }\
  11977. .ehD-pt-progress { width: 150px; }\
  11978. .ehD-pt-progress-text { position: absolute; width: 100%; text-align: center; color: #b8b8b8; left: 0; right: 0; }\
  11979. .ehD-pt-status { width: 130px; }\
  11980. .ehD-pt-succeed .ehD-pt-status { color: #00ff00; }\
  11981. .ehD-pt-warning .ehD-pt-status { color: #ffff00; }\
  11982. .ehD-pt-failed .ehD-pt-status { color: #ff0000; }\
  11983. .ehD-pt-abort { color: #ffff00; display: none; cursor: pointer; }\
  11984. .ehD-pt-status[data-inited-abort="1"]:hover .ehD-pt-abort, .ehD-pt-failed .ehD-pt-status[data-inited-abort="1"]:hover .ehD-pt-status-text, .ehD-pt-succeed .ehD-pt-status[data-inited-abort="1"]:hover .ehD-pt-status-text { display: inline; }\
  11985. .ehD-pt-status[data-inited-abort="1"]:hover .ehD-pt-status-text, .ehD-pt-failed .ehD-pt-status[data-inited-abort="1"]:hover .ehD-pt-abort, .ehD-pt-succeed .ehD-pt-status[data-inited-abort="1"]:hover .ehD-pt-abort { display: none; }\
  11986. .ehD-pt-gen-progress { width: 50%; }\
  11987. .ehD-pt-gen-filename { margin-bottom: 1em; }\
  11988. .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; }\
  11989. .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; }\
  11990. .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; }\
  11991. .ehD-dialog.hidden, .ehD-dialog.hidden .ehD-status { margin-bottom: -311px; }\
  11992. .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; }\
  11993. .ehD-dialog:hover .ehD-force-download-tips { opacity: 1; }\
  11994. .ehD-dialog.hidden .ehD-force-download-tips { bottom: -24px; }\
  11995. .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; }\
  11996. ';
  11997.  
  11998. function initSetting() {
  11999. loadSetting().then(function (res) {
  12000. setting = res ? JSON.parse(res) : {};
  12001. needNumberImages = setting['number-images'];
  12002. needTitleStatus = setting['status-in-title'] === 'always' ? true : false;
  12003.  
  12004. // overwrite settings or set default settings
  12005. if (setting['status-in-title'] === true) setting['status-in-title'] = 'blur';
  12006. if (!setting['save-info-list']) {
  12007. setting['save-info-list'] = ['title', 'metas', 'uploader-comment', 'page-links'];
  12008. }
  12009. if (localStorage.getItem('ehd-image-limits-g.e-hentai.org')) {
  12010. localStorage.removeItem('ehd-image-limits-g.e-hentai.org');
  12011. }
  12012. // remove config of get image limits from r.e-hentai.org
  12013. if (setting['image-limits-both']) {
  12014. delete setting['image-limits-both'];
  12015. GM_setValue('ehD-setting', JSON.stringify(setting));
  12016. }
  12017. if (localStorage.getItem('ehd-image-limits-r.e-hentai.org')) {
  12018. localStorage.removeItem('ehd-image-limits-r.e-hentai.org');
  12019. }
  12020.  
  12021. console.log('[EHD] E-Hentai Downloader Setting >', JSON.stringify(setting));
  12022.  
  12023. // disable single-thread download
  12024. if (setting['enable-multi-threading'] === false) {
  12025. delete setting['enable-multi-threading'];
  12026. 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');
  12027. GM_setValue('ehD-setting', JSON.stringify(setting));
  12028. }
  12029.  
  12030. if (setting['recheck-file-name']) toggleFilenameConfirmInput();
  12031. ehDownloadNumberInput.querySelector('input').checked = needNumberImages;
  12032. ehDownloadPauseBtn.textContent = setting['force-pause'] ? 'Pause (Downloading images will be aborted)' : 'Pause (Downloading images will keep downloading)';
  12033.  
  12034. if (!setting['hide-image-limits']) {
  12035. getImageLimits(true);
  12036. setInterval(getImageLimits, 60000);
  12037. }
  12038.  
  12039. if (!setting['hide-estimated-cost']) {
  12040. try {
  12041. showPreCalcCost();
  12042. }
  12043. catch (e) { }
  12044. }
  12045.  
  12046. // Forced request File System to check if have temp archive
  12047. if (setting['store-in-fs'] && requestFileSystem) {
  12048. requestFileSystem(window.TEMPORARY, 1024 * 1024 * 1024, ehDownloadFS.initCheckerHandler, ehDownloadFS.errorHandler);
  12049. }
  12050. });
  12051. }
  12052.  
  12053. // log information
  12054. console.log('[EHD] UserAgent >', navigator.userAgent);
  12055. 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)
  12056. console.log('[EHD] Script Handler Version >', GM_info.version);
  12057. console.log('[EHD] E-Hentai Downloader Version >', GM_info.script.version);
  12058. console.log('[EHD] Current URL >', window.location.href);
  12059. console.log('[EHD] Is Logged In >', unsafeWindow.apiuid !== -1);
  12060.  
  12061.  
  12062. String.prototype.replaceHTMLEntites = function() {
  12063. var matchEntity = function(entity) {
  12064. 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":"÷"};
  12065. if (entitesList[entity]) return entitesList[entity];
  12066. else if (/#\d+/.test(entity)) {
  12067. var charCode = entity.match(/#(\d+)/)[1] - 0;
  12068. return String.fromCharCode(charCode);
  12069. }
  12070. else if (/#[xX][0-9a-f]+/.test(entity)) {
  12071. var charCode = parseInt(entity.match(/#[xX]([0-9a-f]+)/)[1] - 0, 16);
  12072. return String.fromCharCode(charCode);
  12073. }
  12074. else return '&' + entity + ';';
  12075. };
  12076. var result = this.replace(/&(#[xX]?\d+|[a-zA-Z]+);/g, function(match, entity) {
  12077. return matchEntity(entity.toLowerCase());
  12078. });
  12079. return result;
  12080. };
  12081.  
  12082. function createBlob(abdata, config) {
  12083. try { // to detect if blob generates successfully
  12084. return new Blob(abdata, config);
  12085. }
  12086. catch (error) {
  12087. pushDialog('An error occurred when generating Blob object.');
  12088. console.error('[EHD] An error occurred when generating Blob object. Error Name >', error.name, '| Error Message >', error.message);
  12089. 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);
  12090.  
  12091. abdata = undefined;
  12092. throw new Error('[EHD] An error occurred when generating Blob object, and user refused to retry.');
  12093. }
  12094. }
  12095.  
  12096. // show info in dialog box
  12097. function pushDialog(str) {
  12098. var needScrollIntoView = ehDownloadDialog.clientHeight + ehDownloadDialog.scrollTop >= ehDownloadDialog.scrollHeight;
  12099.  
  12100. if (typeof str === 'string') {
  12101. var tn = document.createElement('span');
  12102. tn.innerHTML += str.replace(/\n/gi, '<br>');
  12103. ehDownloadDialog.appendChild(tn);
  12104. }
  12105. else ehDownloadDialog.appendChild(str);
  12106.  
  12107. if (getAllPagesURLFin && isDownloading && ehDownloadDialog.contains(ehDownloadPauseBtn)) {
  12108. ehDownloadDialog.appendChild(ehDownloadPauseBtn);
  12109. }
  12110.  
  12111. if (needScrollIntoView) {
  12112. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  12113. }
  12114. }
  12115.  
  12116. function getSafeName(str, ignoreSlash) {
  12117. var replaceList = {
  12118. ':': ':',
  12119. '"': '"',
  12120. '*': '*',
  12121. '?': '?',
  12122. '|': '|',
  12123. '<': '<',
  12124. '>': '>',
  12125. '/': '/',
  12126. '\\': '\',
  12127. '\n': '-'
  12128. };
  12129. var replaceFn = function(match) {
  12130. if (ignoreSlash && (match === '/' || match === '\\')) {
  12131. return match;
  12132. }
  12133. else if (setting['replace-with-full-width']) {
  12134. return replaceList[match];
  12135. }
  12136. else {
  12137. return '-';
  12138. }
  12139. };
  12140.  
  12141. return str.trim().replace(ehDownloadRegex.dangerChars, replaceFn);
  12142. }
  12143.  
  12144. // replace dir name and zip filename
  12145. function getReplacedName(str) {
  12146. return str.replace(/\{gid\}/gi, unsafeWindow.gid)
  12147. .replace(/\{token\}/gi, unsafeWindow.token)
  12148. .replace(/\{title\}/gi, getSafeName(document.getElementById('gn').textContent))
  12149. .replace(/\{subtitle\}/gi, document.getElementById('gj').textContent ? getSafeName(document.getElementById('gj').textContent) : getSafeName(document.getElementById('gn').textContent))
  12150. .replace(/\{tag\}/gi, document.querySelector('.ic').getAttribute('alt').toUpperCase())
  12151. .replace(/\{uploader\}/gi, getSafeName(document.querySelector('#gdn a').textContent))
  12152. .replaceHTMLEntites();
  12153. }
  12154.  
  12155. function PageData(pageURL, imageURL, imageName, nextNL, realIndex, imageNumber) {
  12156. this.pageURL = pageURL.split('?')[0];
  12157. this.imageURL = imageURL;
  12158. this.imageName = getSafeName(imageName);
  12159. this._imageName = this.imageName;
  12160. this.equalCount = 1;
  12161. this.nextNL = nextNL;
  12162. this.realIndex = realIndex;
  12163. this.imageNumber = imageNumber;
  12164. }
  12165.  
  12166. // rename images that have the same name
  12167. function renameImages() {
  12168. imageList.forEach(function(elem, index) {
  12169. // if Number Images are enabled, filename won't be changed, just numbering
  12170. if (!needNumberImages) {
  12171. for (var i = 0; i < index; i++) {
  12172. if (elem !== undefined && imageList[i] !== undefined && elem.imageName.toLowerCase() === imageList[i]['imageName'].toLowerCase()) {
  12173. var nameParts = elem.imageName.split('.');
  12174. nameParts[nameParts.length - 2] += ' (' + (++imageList[i].equalCount) + ')';
  12175. elem.imageName = nameParts.join('.');
  12176. break;
  12177. }
  12178. }
  12179. }
  12180. else elem['imageName'] = elem['imageNumber'] + (setting['number-separator'] ? setting['number-separator'] : ':') + elem['imageName'];
  12181. });
  12182. }
  12183.  
  12184. // store responsed content from GM_xhr
  12185. // Updated on 1.19: Now the index argument is the page's number - 1 (original is page's number)
  12186. function storeRes(res, index) {
  12187. imageData[index] = res;
  12188. downloadedCount++;
  12189. console.log('[EHD] Index >', index + 1, ' | RealIndex >', imageList[index]['realIndex'], ' | Name >', imageList[index]['imageName'], ' | RetryCount >', retryCount[index], ' | DownloadedCount >', downloadedCount, ' | FetchCount >', fetchCount, ' | FailedCount >', failedCount);
  12190. fetchCount--;
  12191.  
  12192. updateTotalStatus();
  12193. if (!isPausing) checkFailed();
  12194. for (var i in res) {
  12195. delete res[i];
  12196. }
  12197. }
  12198.  
  12199. function generateZip(isFromFS, fs, isRetry, forced){
  12200. isSaving = true;
  12201.  
  12202. // remove pause button
  12203. if (!forced && ehDownloadDialog.contains(ehDownloadPauseBtn)) {
  12204. ehDownloadDialog.removeChild(ehDownloadPauseBtn);
  12205. }
  12206.  
  12207. if (!isFromFS && !isRetry) {
  12208. if (setting['save-info-list'].toString().indexOf('page-links') >= 0) {
  12209. imageList.forEach(function(elem, index){
  12210. // Image URL may useless, see https://github.com/ccloli/E-Hentai-Downloader/issues/6
  12211. infoStr += '\n\nPage ' + elem['realIndex'] + ': ' + elem['pageURL'] + '\nImage ' + elem['realIndex'] + ': ' + elem['imageName'] /*+ '\nImage URL: ' + elem['imageURL']*/;
  12212. });
  12213. }
  12214. pushDialog('\nFinish downloading at ' + new Date() + '\n');
  12215. infoStr += '\n\nDownloaded at ' + new Date() + '\n\nGenerated by E-Hentai Downloader. https://github.com/ccloli/E-Hentai-Downloader';
  12216.  
  12217. if (setting['save-info'] === 'file' || !setting['save-info']) {
  12218. (dirName ? zip.folder(dirName) : zip).file('info.txt', infoStr.replace(/\n/gi, '\r\n'));
  12219. }
  12220. }
  12221.  
  12222. pushDialog('\n\nGenerating Zip file...\n');
  12223.  
  12224. var fs = fs || ehDownloadFS.fs;
  12225.  
  12226. var progress = document.createElement('progress');
  12227. var curFile = document.createElement('div');
  12228. progress.className = 'ehD-pt-gen-progress';
  12229. curFile.className = 'ehD-pt-gen-filename';
  12230. curFile.textContent = ' ';
  12231. ehDownloadDialog.appendChild(progress);
  12232. ehDownloadDialog.appendChild(curFile);
  12233. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  12234.  
  12235. var saveToFileSystem = function(abData) {
  12236. curFile.textContent = ' ';
  12237.  
  12238. var fsErrorHandler = function(error) {
  12239. ehDownloadFS.errorHandler(error);
  12240. ehDownloadFS.removeAllFiles();
  12241.  
  12242. if (confirm('An error occured when storing files to FileSystem.\n' +
  12243. 'Error Name: ' + (error.name || 'Unknown Error') + '\n' +
  12244. 'Error Message: ' + error.message + '\n\n' +
  12245. 'Should I try FileSystem again (Yes) or redirect to try using Blob (No)? \n' +
  12246. '* 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)')) {
  12247. saveToFileSystem(abData);
  12248. }
  12249. else {
  12250. ehDownloadFS.needFileSystem = false;
  12251. saveToBlob(abData);
  12252. }
  12253. };
  12254.  
  12255. var fs = fs || ehDownloadFS.fs;
  12256. pushDialog('\n\nSlicing and storing Zip file to FileSystem...');
  12257. var data = abData;
  12258. var dataIndex = 0;
  12259. var dataLength = data.byteLength;
  12260. var loopWrite = function(fileEntry){
  12261. fileEntry.createWriter(function(fileWriter){
  12262. //fileWriter.seek(fileWriter.length);
  12263. dataIndex = fileWriter.length;
  12264. if (dataIndex >= dataLength) {
  12265. data = undefined;
  12266. abData = undefined;
  12267. return setTimeout(function(){
  12268. ehDownloadFS.saveAs(isFromFS ? fs : undefined, forced);
  12269. isSaving = false;
  12270. }, 1500);
  12271. }
  12272. fileWriter.seek(dataIndex);
  12273. var dataLastIndex = dataIndex + 1024 * 1024 * 10;
  12274. // I tried setting it as 100MB but some parts were still gone, so I have to make it smaller.
  12275. console.log('[EHD] DataIndex >', dataIndex, '| DataLastIndex >', dataLastIndex, '| FileWriterLength >', fileWriter.length, '| DataLength >', dataLength);
  12276. pushDialog('\n' + dataIndex + '-' + dataLastIndex + '/' + dataLength);
  12277. var blob = createBlob([data.slice(dataIndex, dataLastIndex)], {type: 'application/zip'});
  12278. fileWriter.write(blob);
  12279. if ('close' in blob) blob.close(); // File Blob.close() API, not supported by all the browser now
  12280. blob = null;
  12281. setTimeout(loopWrite, 100, fileEntry);
  12282. }, fsErrorHandler);
  12283. };
  12284. fs.root.getFile(unsafeWindow.gid + '.zip', {create: true}, function(fileEntry){
  12285. if (fileEntry.isFile) fileEntry.remove(function(){
  12286. console.log('[EHD] File', fileName, 'is removed.');
  12287. }, fsErrorHandler);
  12288. else if (fileEntry.isDirectory) fileEntry.removeRecursively(function() {
  12289. console.log('[EHD] Directory', fileName, 'is removed.');
  12290. }, fsErrorHandler);
  12291. fs.root.getFile(unsafeWindow.gid + '.zip', {create: true}, loopWrite, fsErrorHandler);
  12292. }, fsErrorHandler);
  12293. //fs.root.getFile(unsafeWindow.gid + '.zip', {create: true}, loopWrite, fsErrorHandler);
  12294. };
  12295.  
  12296. var saveToBlob = function(abData){
  12297. curFile.textContent = 'Generating Blob object...';
  12298. var blob = createBlob([abData], {type: setting['save-as-cbz'] ? 'application/vnd.comicbook+zip' : 'application/zip'});
  12299. saveAs(blob, fileName + (setting['save-as-cbz'] ? '.cbz' : '.zip'));
  12300.  
  12301. var redownloadBtn = document.createElement('button');
  12302. redownloadBtn.textContent = 'Not download? Click here to download';
  12303. redownloadBtn.addEventListener('click', function(){
  12304. // rebuild blob object if "File is not exist" occured
  12305. blob = createBlob([abData], {type: setting['save-as-cbz'] ? 'application/vnd.comicbook+zip' : 'application/zip'});
  12306. saveAs(blob, fileName + (setting['save-as-cbz'] ? '.cbz' : '.zip'));
  12307.  
  12308. setTimeout(function(){
  12309. if ('close' in blob) blob.close();
  12310. blob = null;
  12311. }, 10e3); // 10s to fixed Chrome delay downloads
  12312. });
  12313. ehDownloadDialog.appendChild(redownloadBtn);
  12314.  
  12315. if (!forced) insertCloseButton();
  12316. isSaving = false;
  12317.  
  12318. setTimeout(function(){
  12319. if ('close' in blob) blob.close();
  12320. blob = null;
  12321. }, 10e3); // 10s to fixed Chrome delay downloads
  12322. };
  12323.  
  12324. try {
  12325. var lastMetaTime = 0;
  12326. // build arraybuffer object to detect if it generates successfully
  12327. zip.generateAsync({
  12328. type: 'arraybuffer',
  12329. compression: setting['compression-level'] ? 'DEFLATE' : 'STORE',
  12330. compressionOptions: {
  12331. level: setting['compression-level'] > 0 ? (setting['compression-level'] < 10 ? setting['compression-level'] : 9) : 1
  12332. },
  12333. streamFiles: setting['file-descriptor'] ? true : false,
  12334. comment: setting['save-info'] === 'comment' ? infoStr.replace(/\n/gi, '\r\n') : undefined
  12335. }, function(meta){
  12336. // meta update function will be called nearly every 1ms, for performance, update every 300ms
  12337. // anyway it's still too fast so that you may still cannot see the update
  12338. var thisMetaTime = Date.now();
  12339. if (thisMetaTime - lastMetaTime < 300) {
  12340. return;
  12341. }
  12342. lastMetaTime = thisMetaTime;
  12343. progress.value = meta.percent / 100;
  12344. curFile.textContent = meta.currentFile || 'Calculating extra data...';
  12345. }).then(function(abData){
  12346. progress.value = 1;
  12347.  
  12348. if (!forced) {
  12349. if (emptyAudio) {
  12350. emptyAudio.pause();
  12351. }
  12352. }
  12353.  
  12354. if (isFromFS || ehDownloadFS.needFileSystem) { // using filesystem to save file is needed
  12355. saveToFileSystem(abData);
  12356. }
  12357. else { // or just using blob
  12358. saveToBlob(abData);
  12359. }
  12360.  
  12361. if (!forced) {
  12362. zip.file(/.*/).forEach(function(elem){
  12363. zip.remove(elem);
  12364. });
  12365. }
  12366. });
  12367. }
  12368. catch (error) {
  12369. abData = undefined;
  12370.  
  12371. pushDialog('An error occurred when generating Zip file as ArrayBuffer.');
  12372. console.error('[EHD] An error occurred when generating Zip file as ArrayBuffer.');
  12373. console.error(error);
  12374. if (confirm('An error occurred when generating Zip file as ArrayBuffer. Try again?')) return generateZip(isFromFS, fs, 1);
  12375.  
  12376. var fsErrorHandler = function(error) {
  12377. ehDownloadFS.errorHandler(error);
  12378. ehDownloadFS.removeAllFiles();
  12379.  
  12380. if (confirm('An error occured when storing files to FileSystem.\n' +
  12381. 'Error Name: ' + (error.name || 'Unknown Error') + '\n' +
  12382. 'Error Message: ' + error.message + '\n\n' +
  12383. 'Should I try again (Yes) or stop it (No, and the downloaded file will be removed)? \n' +
  12384. '* 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)')) {
  12385. generateZip(isFromFS, fs, isRetry, forced);
  12386. }
  12387. };
  12388.  
  12389. if (isFromFS || ehDownloadFS.needFileSystem) {
  12390. // if enabled file system, then store all files into file system
  12391. pushDialog('Storing files into File System...');
  12392. var files = zip.file(/.*/);
  12393. var fileIndex = 0;
  12394. var filesLength = files.length;
  12395. var initFS = function(r){
  12396. fs = r;
  12397. fs.root.getDirectory('raw', {create: true}, loopWrite, fsErrorHandler);
  12398. };
  12399. var loopWrite = function(){
  12400. fs.root.getFile('raw/' + files[fileIndex]['name'], {create: true}, function(fileEntry){
  12401. fileEntry.createWriter(function(fileWriter){
  12402. console.log('[EHD] FileIndex >', fileIndex, '| FilesLength >', filesLength);
  12403. var blob = createBlob([files[fileIndex].asArrayBuffer()], {type: 'application/octet-stream'});
  12404. fileWriter.write(blob);
  12405. if ('close' in blob) blob.close(); // File Blob.close() API, not supported by all the browser now
  12406. blob = null;
  12407. fileIndex++; // some files may still gone in this way, I have no good way to solve it
  12408. if (fileIndex < filesLength) setTimeout(loopWrite, 100);
  12409. else {
  12410. fs.root.getFile('config.txt', {create: true}, function(fileEntry){
  12411. fileEntry.createWriter(function(fileWriter){
  12412. var t = JSON.stringify({fileName: fileName, dirName: dirName});
  12413. var blob = createBlob([t], {type: 'text/plain'});
  12414. fileWriter.write(blob);
  12415. if ('close' in blob) blob.close(); // File Blob.close() API, not supported by all the browser now
  12416. blob = null;
  12417. 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.');
  12418.  
  12419. files.forEach(function(elem){
  12420. zip.remove(elem);
  12421. });
  12422. zip = undefined;
  12423. isSaving = false;
  12424. });
  12425. });
  12426. }
  12427. }, fsErrorHandler);
  12428. }, fsErrorHandler);
  12429. };
  12430. requestFileSystem(window.TEMPORARY, 1024 * 1024 * 1024 * 1024, initFS, fsErrorHandler);
  12431. }
  12432. }
  12433. }
  12434.  
  12435. // update progress table info
  12436. function updateProgress(nodeList, data) {
  12437. if (data.name !== undefined) nodeList.fileName.textContent = data.name;
  12438. if (data.progress !== undefined) nodeList.progress.value = data.progress;
  12439. if (data.progressText !== undefined) nodeList.progressText.textContent = data.progressText;
  12440. if (data.status !== undefined) nodeList.statusText.textContent = data.status;
  12441. if (data.class !== undefined) nodeList.current.className = ['ehD-pt-item', data.class].join(' ').trim();
  12442. }
  12443.  
  12444. // update ehDownloadStatus
  12445. function updateTotalStatus(){
  12446. ehDownloadStatus.textContent = 'Total: ' + totalCount + ' | Downloading: ' + fetchCount + ' | Succeed: ' + downloadedCount + ' | Failed: ' + failedCount;
  12447. if (needTitleStatus) document.title = '[' + (isPausing ? '❙❙' : downloadedCount < totalCount ? '↓ ' + downloadedCount + '/' + totalCount : totalCount === 0 ? '↓' : '√' ) + '] ' + pretitle;
  12448. }
  12449.  
  12450. // Updated on 1.19: Now the index argument is the page's number - 1 (original is page's number)
  12451. function failedFetching(index, nodeList, forced){
  12452. if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31
  12453. if (typeof fetchThread[index] !== 'undefined' && 'abort' in fetchThread[index]) fetchThread[index].abort();
  12454. console.error('[EHD] Index >', index + 1, ' | RealIndex >', imageList[index]['realIndex'], ' | Name >', imageList[index]['imageName'], ' | RetryCount >', retryCount[index], ' | DownloadedCount >', downloadedCount, ' | FetchCount >', fetchCount, ' | FailedCount >', failedCount);
  12455.  
  12456. if (!forced && retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  12457. retryCount[index]++;
  12458. fetchOriginalImage(index, nodeList);
  12459. }
  12460. else {
  12461. updateProgress(nodeList, {
  12462. class: 'ehD-pt-failed'
  12463. });
  12464.  
  12465. imageList[index]['imageFinalURL'] = null;
  12466. failedCount++;
  12467. if (!isPausing || !setting['force-pause']) fetchCount--;
  12468.  
  12469. updateTotalStatus();
  12470. checkFailed();
  12471. }
  12472. }
  12473.  
  12474. function saveDownloaded(forced){
  12475. renameImages();
  12476.  
  12477. for (var j = 0; j < imageData.length; j++) {
  12478. if (imageData[j] != null && imageData[j] !== 'Fetching') {
  12479. (dirName ? zip.folder(dirName) : zip).file(imageList[j]['imageName'], imageData[j]);
  12480. if (!forced) imageData[j] = null;
  12481. }
  12482. }
  12483. generateZip(false, undefined, false, forced);
  12484. if (forced) {
  12485. // if force download zip file, image data should be recoverd to original content
  12486. imageList.forEach(function(elem, index) {
  12487. elem.equalCount = 1;
  12488. elem.imageName = elem._imageName;
  12489. });
  12490. }
  12491. }
  12492.  
  12493. function checkFailed() {
  12494. if (downloadedCount + failedCount < totalCount) { // download not finished, some files are not being called to download
  12495. requestDownload();
  12496. }
  12497. else if (failedCount > 0) { // all files are called to download and some files can't be downloaded
  12498. if (fetchCount === 0) { // all files are finished downloading
  12499. for (var i = 0; i < fetchThread.length; i++) {
  12500. if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort();
  12501. }
  12502. if (setting['number-auto-retry'] || confirm('Some images failed to download. Would you like to try them again?')) {
  12503. retryAllFailed();
  12504. }
  12505. else {
  12506. pushDialog('\nFetch images failed.');
  12507. if (confirm('Fetch images failed, Please try again later.\n\nWould you like to download downloaded images?')) {
  12508. saveDownloaded();
  12509. }
  12510. else {
  12511. insertCloseButton();
  12512. }
  12513. zip.file(/.*/).forEach(function (elem) {
  12514. zip.remove(elem);
  12515. });
  12516. isDownloading = false;
  12517. }
  12518. }
  12519. }
  12520. else { // all files are downloaded successfully
  12521. renameImages();
  12522. for (var j = 0; j < totalCount; j++) {
  12523. (dirName ? zip.folder(dirName) : zip).file(imageList[j]['imageName'], imageData.shift());
  12524. }
  12525. generateZip();
  12526. zip.file(/.*/).forEach(function (elem) {
  12527. zip.remove(elem);
  12528. });
  12529. isDownloading = false;
  12530. }
  12531. }
  12532.  
  12533. // Updated on 1.19: Now the index argument is the page's number - 1 (original is page's number)
  12534. function fetchOriginalImage(index, nodeList) {
  12535. // GM_xhr 于 GreaseMonkey 2.3 / 2.4 中开始支持 responseType 以获取返回类型为 ArrayBuffer 的请求
  12536. // GM_xhr support responseType to fetch ArrayBuffer request on 2.3 / 2.4
  12537. // https://github.com/greasemonkey/greasemonkey/issues/1834
  12538. //console.log(imageList[index]);
  12539. if (retryCount[index] === undefined) retryCount[index] = 0;
  12540. if (isPausing) return;
  12541.  
  12542. var requestURL = imageList[index]['imageFinalURL'] || imageList[index]['imageURL'];
  12543. var needScrollIntoView = ehDownloadDialog.clientHeight + ehDownloadDialog.scrollTop >= ehDownloadDialog.scrollHeight;
  12544.  
  12545. if (nodeList === undefined) {
  12546. var node = progressTable.querySelector('tr[data-index="' + index + '"]');
  12547. if (!node) {
  12548. node = document.createElement('tr');
  12549. node.className = 'ehD-pt-item';
  12550. node.setAttribute('data-index', index);
  12551. node.innerHTML = '\
  12552. <td class="ehD-pt-name">#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'] + '</td>\
  12553. <td class="ehD-pt-progress-outer">\
  12554. <progress class="ehD-pt-progress"></progress>\
  12555. <span class="ehD-pt-progress-text"></span>\
  12556. </td>\
  12557. <td class="ehD-pt-status">\
  12558. <span class="ehD-pt-status-text">Pending...</span>\
  12559. <span class="ehD-pt-abort">Force Abort</span>\
  12560. </td>';
  12561. progressTable.appendChild(node);
  12562. }
  12563.  
  12564. nodeList = {
  12565. current: node,
  12566. fileName: node.getElementsByTagName('td')[0],
  12567. status: node.getElementsByTagName('td')[2],
  12568. statusText: node.getElementsByClassName('ehD-pt-status-text')[0],
  12569. progress: node.getElementsByTagName('progress')[0],
  12570. progressText: node.getElementsByTagName('span')[0],
  12571. abort: node.getElementsByClassName('ehD-pt-abort')[0]
  12572. };
  12573. }
  12574. var speedInfo = {
  12575. lastProgress: 0,
  12576. lastTimestamp: new Date().getTime(),
  12577. zeroDetect: null,
  12578. expiredDetect: null
  12579. };
  12580.  
  12581. if (needScrollIntoView) {
  12582. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  12583. }
  12584.  
  12585. var zeroSpeedHandler = function(res){
  12586. if (imageData[index] instanceof ArrayBuffer) { // Has already downloaded
  12587. updateProgress(nodeList, {
  12588. name: '#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'],
  12589. status: 'Succeed!',
  12590. progress: '1',
  12591. progressText: '100%',
  12592. class: 'ehD-pt-succeed'
  12593. });
  12594.  
  12595. return;
  12596. }
  12597. if (!isDownloading) return; // Temporarily fixes #31
  12598. if (isPausing && setting['force-pause']) return;
  12599.  
  12600. updateProgress(nodeList, { progressText: '0 KB/s' });
  12601.  
  12602. if (setting['speed-detect'] && speedInfo.expiredDetect === null) {
  12603. speedInfo.expiredDetect = setTimeout(expiredSpeedHandler, (setting['speed-expired'] ? setting['speed-expired'] : 30) * 1000, res);
  12604. }
  12605. };
  12606.  
  12607. var expiredSpeedHandler = function(res){
  12608. if (imageData[index] instanceof ArrayBuffer) { // Has already downloaded
  12609. updateProgress(nodeList, {
  12610. name: '#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'],
  12611. status: 'Succeed!',
  12612. progress: '1',
  12613. progressText: '100%',
  12614. class: 'ehD-pt-succeed'
  12615. });
  12616.  
  12617. return;
  12618. }
  12619. if (!isDownloading) return; // Temporarily fixes #31
  12620. if (isPausing && setting['force-pause']) return;
  12621.  
  12622. if (typeof fetchThread[index] !== 'undefined' && 'abort' in fetchThread[index]) fetchThread[index].abort();
  12623.  
  12624. console.log('[EHD] #' + (index + 1) + ': Speed Too Low');
  12625. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nResposeHeaders >' + res.responseHeaders);
  12626.  
  12627. updateProgress(nodeList, {
  12628. status: 'Failed! (Low Speed)',
  12629. progress: '0',
  12630. progressText: '',
  12631. class: 'ehD-pt-warning'
  12632. });
  12633.  
  12634. if (imageList[index]['imageURL'].indexOf('fullimg.php') >= 0) imageList[index]['imageFinalURL'] = res.finalUrl;
  12635.  
  12636. for (var i in res) {
  12637. delete res[i];
  12638. }
  12639.  
  12640. failedFetching(index, nodeList);
  12641. };
  12642.  
  12643. var removeTimerHandler = function(){
  12644. if (speedInfo.expiredDetect !== null) {
  12645. clearTimeout(speedInfo.expiredDetect);
  12646. speedInfo.expiredDetect = null;
  12647. }
  12648.  
  12649. if (speedInfo.zeroDetect !== null) {
  12650. clearTimeout(speedInfo.zeroDetect);
  12651. speedInfo.zeroDetect = null;
  12652. }
  12653. };
  12654.  
  12655. fetchThread[index] = GM_xmlhttpRequest({
  12656. method: 'GET',
  12657. url: requestURL,
  12658. responseType: 'arraybuffer',
  12659. timeout: (setting['timeout'] !== undefined) ? Number(setting['timeout']) * 1000 : 300000,
  12660. headers: {
  12661. 'Referer': imageList[index]['pageURL'],
  12662. 'X-Alt-Referer': imageList[index]['pageURL']
  12663. },
  12664. onprogress: function(res) {
  12665. var t = new Date().getTime();
  12666. var speedText;
  12667. var speedKBs = res.lengthComputable ? Number((res.loaded - speedInfo.lastProgress) / (t - speedInfo.lastTimestamp) / 1.024) : -1;
  12668.  
  12669. if (t - speedInfo.lastTimestamp >= 1000 || speedInfo.lastProgress === 0) {
  12670. speedText = res.lengthComputable ? speedKBs.toFixed(2) + ' KB/s' : '';
  12671. speedInfo.lastProgress = res.loaded;
  12672. speedInfo.lastTimestamp = t;
  12673. }
  12674.  
  12675. updateProgress(nodeList, {
  12676. progress: res.lengthComputable ? res.loaded / res.total : '',
  12677. progressText: speedText,
  12678. class: '',
  12679. status: retryCount[index] === 0 ? 'Downloading...' : 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ') ...'
  12680. });
  12681.  
  12682. // set showing speed to 0
  12683. if (speedInfo.zeroDetect !== null) {
  12684. clearTimeout(speedInfo.zeroDetect);
  12685. speedInfo.zeroDetect = null;
  12686. }
  12687. speedInfo.zeroDetect = setTimeout(zeroSpeedHandler, 3000, res);
  12688.  
  12689. if (setting['speed-detect']) {
  12690. if (speedKBs >= setting['speed-min'] ? setting['speed-min'] : 5) {
  12691.  
  12692. if (speedInfo.expiredDetect !== null) {
  12693. clearTimeout(speedInfo.expiredDetect);
  12694. speedInfo.expiredDetect = null;
  12695. }
  12696.  
  12697. for (var i in res) {
  12698. delete res[i];
  12699. }
  12700. }
  12701. else if (speedInfo.expiredDetect === null) {
  12702. speedInfo.expiredDetect = setTimeout(expiredSpeedHandler, (setting['speed-expired'] ? setting['speed-expired'] : 30) * 1000, res);
  12703. console.log('[EHD] Speed detect handler is inited for', index + 1, '!');
  12704. }
  12705. }
  12706. },
  12707. onload: function(res) {
  12708. removeTimerHandler();
  12709. if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31
  12710.  
  12711. // cache them to reduce waiting time and CPU usage on Chrome with Tampermonkey
  12712. // (Tampermonkey uses a dirty way to give res.response, transfer string to arraybuffer every time)
  12713. // now store progress just spent ~1s instead of ~8s
  12714. var response = res.response;
  12715. var byteLength = response.byteLength;
  12716. var responseHeaders = res.responseHeaders;
  12717. // use regex to fixed compatibility with http/2, as its headers are lower case (at least fixed with Yandex Turbo)
  12718. var mime = responseHeaders.match(/Content-Type:/i) ? responseHeaders.split(/Content-Type:/i)[1].split('\n')[0].trim().split('/') : ['', ''];
  12719.  
  12720. if (!response) {
  12721. console.log('[EHD] #' + (index + 1) + ': Empty Response (See: https://github.com/ccloli/E-Hentai-Downloader/issues/16 )');
  12722. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nResposeHeaders >' + res.responseHeaders);
  12723.  
  12724. updateProgress(nodeList, {
  12725. status: 'Failed! (Empty Response)',
  12726. progress: '0',
  12727. progressText: '',
  12728. class: 'ehD-pt-warning'
  12729. });
  12730.  
  12731. for (var i in res) {
  12732. delete res[i];
  12733. }
  12734. return failedFetching(index, nodeList);
  12735.  
  12736. // res.response polyfill is useless, so it has been removed
  12737. }
  12738. else if (byteLength === 925) { // '403 Access Denied' Image Byte Size
  12739. // GM_xhr only support abort()
  12740. console.log('[EHD] #' + (index + 1) + ': 403 Access Denied');
  12741. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL + '\nResposeHeaders >' + res.responseHeaders);
  12742.  
  12743. updateProgress(nodeList, {
  12744. status: 'Failed! (Error 403)',
  12745. progress: '0',
  12746. progressText: '',
  12747. class: 'ehD-pt-warning'
  12748. });
  12749.  
  12750. for (var i in res) {
  12751. delete res[i];
  12752. }
  12753. return failedFetching(index, nodeList, true);
  12754. }
  12755. else if (byteLength === 28) { // 'An error has occurred. (403)' Length
  12756. console.log('[EHD] #' + (index + 1) + ': An error has occurred. (403)');
  12757. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL + '\nResposeHeaders >' + res.responseHeaders);
  12758. updateProgress(nodeList, {
  12759. status: 'Failed! (Error 403)',
  12760. progress: '0',
  12761. progressText: '',
  12762. class: 'ehD-pt-warning'
  12763. });
  12764.  
  12765. for (var i in res) {
  12766. delete res[i];
  12767. }
  12768. return failedFetching(index, nodeList, true);
  12769. }
  12770. else if (
  12771. byteLength === 142 || // Image Viewing Limits String Byte Size (exhentai)
  12772. byteLength === 144 || // Image Viewing Limits String Byte Size (g.e-hentai)
  12773. byteLength === 28658 || // '509 Bandwidth Exceeded' Image Byte Size
  12774. (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
  12775. ) {
  12776. // thought exceed the limits, downloading image is still accessable
  12777. /*for (var i = 0; i < fetchThread.length; i++) {
  12778. if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort();
  12779. }*/
  12780. console.log('[EHD] #' + (index + 1) + ': Exceed Image Viewing Limits / 509 Bandwidth Exceeded');
  12781. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL + '\nResposeHeaders >' + res.responseHeaders);
  12782.  
  12783. updateProgress(nodeList, {
  12784. status: 'Failed! (Exceed Limits)',
  12785. progress: '0',
  12786. progressText: '',
  12787. class: 'ehD-pt-failed'
  12788. });
  12789. updateTotalStatus();
  12790.  
  12791. for (var i in res) {
  12792. delete res[i];
  12793. }
  12794.  
  12795. failedCount++;
  12796. fetchCount--;
  12797. updateTotalStatus();
  12798.  
  12799. if (isPausing) return;
  12800.  
  12801. pushDialog('You have exceeded your image viewing limits.\n');
  12802. isPausing = true;
  12803. updateTotalStatus();
  12804. if (emptyAudio) {
  12805. emptyAudio.pause();
  12806. }
  12807.  
  12808. if (ehDownloadDialog.contains(ehDownloadPauseBtn)) {
  12809. ehDownloadDialog.removeChild(ehDownloadPauseBtn);
  12810. }
  12811.  
  12812. if (confirm('You have temporarily reached the limit for how many images you can browse.\n\n\
  12813. - If you are not signed in, sign up/in with an E-Hentai account at E-Hentai Forums to get double daily quota.\n\
  12814. - You can run Hentai@Home to support E-Hentai and get some points which you can pay to increase your limit.\n\
  12815. - Check back in a few hours, and you will be able to download more (3 points are reduced per minute by default).\n\
  12816. - You can reset your image viewing limits to continue by paying your GPs or credits.\n\n\
  12817. 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.')) {
  12818. window.open('https://e-hentai.org/home.php');
  12819. }
  12820.  
  12821. var resetButton = document.createElement('a');
  12822. resetButton.innerHTML = '<button>Reset Limits</button>';
  12823. resetButton.setAttribute('href', 'https://e-hentai.org/home.php');
  12824. resetButton.setAttribute('target', '_blank');
  12825. ehDownloadDialog.appendChild(resetButton);
  12826.  
  12827. var continueButton = document.createElement('button');
  12828. continueButton.innerHTML = 'Continue Download';
  12829. continueButton.addEventListener('click', function(){
  12830. //fetchCount = 0;
  12831. ehDownloadDialog.removeChild(resetButton);
  12832. ehDownloadDialog.removeChild(continueButton);
  12833. ehDownloadDialog.removeChild(cancelButton);
  12834. ehDownloadDialog.appendChild(ehDownloadPauseBtn);
  12835.  
  12836. isPausing = false;
  12837. initProgressTable();
  12838. requestDownload();
  12839. });
  12840. ehDownloadDialog.appendChild(continueButton);
  12841.  
  12842. var cancelButton = document.createElement('button');
  12843. cancelButton.innerHTML = 'Cancel Download';
  12844. cancelButton.addEventListener('click', function(){
  12845. ehDownloadDialog.removeChild(resetButton);
  12846. ehDownloadDialog.removeChild(continueButton);
  12847. ehDownloadDialog.removeChild(cancelButton);
  12848.  
  12849. if (confirm('You have exceeded your image viewing limits. Would you like to save downloaded images?')) {
  12850. saveDownloaded();
  12851. }
  12852. else {
  12853. insertCloseButton();
  12854. }
  12855. isPausing = false;
  12856. isDownloading = false;
  12857. zip.file(/.*/).forEach(function (elem) {
  12858. zip.remove(elem);
  12859. });
  12860. });
  12861. ehDownloadDialog.appendChild(cancelButton);
  12862. }
  12863. // ip banned
  12864. else if (
  12865. (mime[0] === 'text' && (res.responseText || new TextDecoder().decode(new DataView(response))).indexOf('Your IP address has been temporarily banned') >= 0)
  12866. ) {
  12867. console.log('[EHD] #' + (index + 1) + ': IP address banned');
  12868. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL + '\nResposeHeaders >' + res.responseHeaders);
  12869.  
  12870. updateProgress(nodeList, {
  12871. status: 'Failed! (IP banned)',
  12872. progress: '0',
  12873. progressText: '',
  12874. class: 'ehD-pt-failed'
  12875. });
  12876. updateTotalStatus();
  12877.  
  12878. for (var i in res) {
  12879. delete res[i];
  12880. }
  12881.  
  12882. failedCount++;
  12883. fetchCount--;
  12884. updateTotalStatus();
  12885.  
  12886. if (isPausing) return;
  12887.  
  12888. pushDialog('Your IP address has been temporarily banned.\n');
  12889. isPausing = true;
  12890. updateTotalStatus();
  12891. if (emptyAudio) {
  12892. emptyAudio.pause();
  12893. }
  12894.  
  12895. if (ehDownloadDialog.contains(ehDownloadPauseBtn)) {
  12896. ehDownloadDialog.removeChild(ehDownloadPauseBtn);
  12897. }
  12898.  
  12899. var expiredTime = (res.responseText || new TextDecoder().decode(new DataView(response))).match(ehDownloadRegex.IPBanExpires);
  12900.  
  12901. alert('Your IP address has been temporarily banned. \n\n\
  12902. 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\
  12903. 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' +
  12904. (expiredTime ? '\n' + expiredTime[0] : '')
  12905. );
  12906.  
  12907. var continueButton = document.createElement('button');
  12908. continueButton.innerHTML = 'Continue Download';
  12909. continueButton.addEventListener('click', function () {
  12910. //fetchCount = 0;
  12911. ehDownloadDialog.removeChild(continueButton);
  12912. ehDownloadDialog.removeChild(cancelButton);
  12913. ehDownloadDialog.appendChild(ehDownloadPauseBtn);
  12914.  
  12915. isPausing = false;
  12916. initProgressTable();
  12917. requestDownload();
  12918. });
  12919. ehDownloadDialog.appendChild(continueButton);
  12920.  
  12921. var cancelButton = document.createElement('button');
  12922. cancelButton.innerHTML = 'Cancel Download';
  12923. cancelButton.addEventListener('click', function () {
  12924. ehDownloadDialog.removeChild(continueButton);
  12925. ehDownloadDialog.removeChild(cancelButton);
  12926.  
  12927. if (confirm('Would you like to save downloaded images?')) {
  12928. saveDownloaded();
  12929. }
  12930. else {
  12931. insertCloseButton();
  12932. }
  12933. isPausing = false;
  12934. isDownloading = false;
  12935. zip.file(/.*/).forEach(function (elem) {
  12936. zip.remove(elem);
  12937. });
  12938. });
  12939. ehDownloadDialog.appendChild(cancelButton);
  12940. }
  12941. // res.status should be detected at here, because we should know are we reached image limits at first
  12942. else if (res.status !== 200) {
  12943. console.log('[EHD] #' + (index + 1) + ': Wrong Response Status');
  12944. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL + '\nResposeHeaders >' + res.responseHeaders);
  12945.  
  12946. updateProgress(nodeList, {
  12947. status: 'Failed! (Wrong Status)',
  12948. progress: '0',
  12949. progressText: '',
  12950. class: 'ehD-pt-warning'
  12951. });
  12952.  
  12953. for (var i in res) {
  12954. delete res[i];
  12955. }
  12956. return failedFetching(index, nodeList);
  12957. }
  12958. // GM_xhr doesn't support xhr.getResponseHeader() function
  12959. //if (res.getResponseHeader('Content-Type').split('/')[0] != 'image') {
  12960. else if (mime[0] !== 'image') {
  12961. console.log('[EHD] #' + (index + 1) + ': Wrong Content-Type');
  12962. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL + '\nResposeHeaders >' + res.responseHeaders);
  12963.  
  12964. updateProgress(nodeList, {
  12965. status: 'Failed! (Wrong MIME)',
  12966. progress: '0',
  12967. progressText: '',
  12968. class: 'ehD-pt-warning'
  12969. });
  12970.  
  12971. for (var i in res) {
  12972. delete res[i];
  12973. }
  12974. return failedFetching(index, nodeList);
  12975. }
  12976.  
  12977. // logs in #80 shows sometimes it didn't match the regex, but cannot reproduce right now
  12978. try {
  12979. imageList[index]['_imageName'] = imageList[index]['imageName'] = res.responseHeaders.match(ehDownloadRegex.resFileName) ? getSafeName(res.responseHeaders.match(ehDownloadRegex.resFileName)[1].trim()) : imageList[index]['imageName'];
  12980. }
  12981. catch (error) {
  12982. console.log('[EHD] #' + (index + 1) + ': Parse file name failed');
  12983. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL + '\nResposeHeaders >' + res.responseHeaders);
  12984.  
  12985. imageList[index]['_imageName'] = imageList[index]['imageName'];
  12986. }
  12987.  
  12988. updateProgress(nodeList, {
  12989. name: '#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'],
  12990. status: 'Succeed!',
  12991. progress: '1',
  12992. progressText: '100%',
  12993. class: 'ehD-pt-succeed'
  12994. });
  12995.  
  12996. storeRes(response, index);
  12997.  
  12998. for (var i in res) {
  12999. delete res[i];
  13000. }
  13001. response = null;
  13002. },
  13003. onerror: function(res){
  13004. removeTimerHandler();
  13005. if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31
  13006.  
  13007. console.log('[EHD] #' + (index + 1) + ': Network Error');
  13008. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nResposeHeaders >' + res.responseHeaders);
  13009.  
  13010. updateProgress(nodeList, {
  13011. status: 'Failed! (Network Error)',
  13012. progress: '0',
  13013. progressText: '',
  13014. class: 'ehD-pt-warning'
  13015. });
  13016.  
  13017. if (imageList[index]['imageURL'].indexOf('fullimg.php') >= 0) imageList[index]['imageFinalURL'] = res.finalUrl;
  13018.  
  13019. for (var i in res) {
  13020. delete res[i];
  13021. }
  13022.  
  13023. failedFetching(index, nodeList);
  13024. },
  13025. ontimeout: function(res){
  13026. removeTimerHandler();
  13027. if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31
  13028.  
  13029. console.log('[EHD] #' + (index + 1) + ': Timed Out');
  13030. console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nResposeHeaders >' + res.responseHeaders);
  13031.  
  13032. updateProgress(nodeList, {
  13033. status: 'Failed! (Timed Out)',
  13034. progress: '0',
  13035. progressText: '',
  13036. class: 'ehD-pt-warning'
  13037. });
  13038.  
  13039. if (imageList[index]['imageURL'].indexOf('fullimg.php') >= 0) imageList[index]['imageFinalURL'] = res.finalUrl;
  13040.  
  13041. for (var i in res) {
  13042. delete res[i];
  13043. }
  13044.  
  13045. failedFetching(index, nodeList);
  13046. }
  13047. });
  13048.  
  13049. if (!nodeList.status.dataset.initedAbort) {
  13050. nodeList.abort.addEventListener('click', function(){
  13051. if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31
  13052.  
  13053. if (typeof fetchThread[index] !== 'undefined' && 'abort' in fetchThread[index]) fetchThread[index].abort();
  13054. removeTimerHandler();
  13055. console.log('[EHD] #' + (index + 1) + ': Force Aborted By User');
  13056. updateProgress(nodeList, {
  13057. status: 'Failed! (User Aborted)',
  13058. progress: '0',
  13059. progressText: '',
  13060. class: 'ehD-pt-warning'
  13061. });
  13062.  
  13063. failedFetching(index, nodeList);
  13064. });
  13065.  
  13066. nodeList.status.setAttribute('data-inited-abort', '1');
  13067. }
  13068.  
  13069. updateTotalStatus();
  13070. }
  13071.  
  13072. function retryAllFailed(){
  13073. var index, refetch = 0;
  13074. initProgressTable();
  13075.  
  13076. for (index = 0; index < imageData.length; index++) {
  13077. if (imageData[index] === 'Fetching') {
  13078. imageData[index] = null;
  13079. retryCount[index] = 0;
  13080. }
  13081. }
  13082.  
  13083. failedCount = 0;
  13084. fetchCount = 0;
  13085. requestDownload();
  13086. }
  13087.  
  13088. function insertCloseButton() {
  13089. var exitButton = document.createElement('button');
  13090. exitButton.style.display = 'block';
  13091. exitButton.style.margin = '0 auto';
  13092. exitButton.textContent = 'Close';
  13093. exitButton.onclick = function(){
  13094. ehDownloadDialog.removeChild(exitButton);
  13095. ehDownloadDialog.style.display = 'none';
  13096. if (ehDownloadFS.needFileSystem) ehDownloadFS.removeFile(unsafeWindow.gid + '.zip');
  13097. };
  13098. ehDownloadDialog.appendChild(exitButton);
  13099. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  13100.  
  13101. if (ehDownloadDialog.contains(forceDownloadTips)) ehDownloadDialog.removeChild(forceDownloadTips);
  13102. }
  13103.  
  13104. function getPagesURLFromMPV() {
  13105. var mpvURL = location.origin + '/mpv/' + unsafeWindow.gid + '/' +
  13106. unsafeWindow.token + '/';
  13107.  
  13108. var xhr = new XMLHttpRequest();
  13109. xhr.open('GET', mpvURL);
  13110. xhr.onload = function () {
  13111. if (xhr.status !== 200 || !xhr.responseText) {
  13112. if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13113. pushDialog('Failed! Retrying... ');
  13114. retryCount++;
  13115. xhr.open('GET', mpvURL);
  13116. xhr.timeout = 30000;
  13117. xhr.send();
  13118. }
  13119. else {
  13120. pushDialog('Failed!\nFetch Pages\' URL failed, Please try again later.');
  13121. isDownloading = false;
  13122. alert('Fetch Pages\' URL failed, Please try again later.');
  13123. }
  13124. return;
  13125. }
  13126.  
  13127. var listMatch = xhr.responseText.match(ehDownloadRegex.mpvKey);
  13128. if (!listMatch) {
  13129. console.error('[EHD] Response content is incorrect!');
  13130. if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13131. pushDialog('Failed! Retrying... ');
  13132. retryCount++;
  13133. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13134. xhr.timeout = 30000;
  13135. xhr.send();
  13136. }
  13137. else {
  13138. pushDialog('Failed!\nCan\'t get pages URL from response content.');
  13139. isDownloading = false;
  13140. }
  13141. return;
  13142. }
  13143.  
  13144. var list = new Function('return ' + listMatch[1])();
  13145.  
  13146. list.forEach(function (elem, index) {
  13147. var curURL = location.origin + '/s/' + elem.k + '/' + unsafeWindow.gid + '-' + (index + 1);
  13148. pageURLsList.push(curURL);
  13149. });
  13150. pushDialog('Succeed!');
  13151.  
  13152.  
  13153. // copied from getAllPagesURL(), THAT's UGLY!!!
  13154. // so when will 2.0 comes out /_\
  13155. getAllPagesURLFin = true;
  13156. var wrongPages = pagesRange.filter(function (elem) { return elem > pageURLsList.length; });
  13157. if (wrongPages.length !== 0) {
  13158. pagesRange = pagesRange.filter(function (elem) { return elem <= pageURLsList.length; });
  13159. pushDialog('\nPage ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.\n');
  13160. if (pagesRange.length === 0) {
  13161. pushDialog('Nothing matches provided pages range, stop downloading.');
  13162. alert('Nothing matches provided pages range, stop downloading.');
  13163. insertCloseButton();
  13164. return;
  13165. }
  13166. }
  13167. totalCount = pagesRange.length || pageURLsList.length;
  13168. pushDialog('\n\n');
  13169. initProgressTable();
  13170. requestDownload();
  13171. };
  13172. xhr.send();
  13173. pushDialog('Fetching Gallery Pages URL From MPV...');
  13174. }
  13175.  
  13176. // /*if pages range is set, then*/ get all pages URL to select needed pages
  13177. function getAllPagesURL() {
  13178. pagesRange = [];
  13179. var pagesRangeText = ehDownloadRange.querySelector('input').value.replace(/,/g, ',').trim();
  13180. var retryCount = 0;
  13181.  
  13182. if (pagesRangeText) { // if pages range is defined
  13183. console.log('[EHD] Pages Range >', pagesRangeText);
  13184. if (!ehDownloadRegex.pagesRange.test(pagesRangeText)) return alert('The format of Pages Range is incorrect.');
  13185.  
  13186. var pagesRangeScale = pagesRangeText.match(/\d*-\d*|\d+/g);
  13187. pagesRangeScale.forEach(function(elem){
  13188. if (elem.indexOf('-') < 0) {
  13189. var curElem = Number(elem);
  13190. if (!pagesRange.some(function(e){ return curElem === e; })) pagesRange.push(curElem);
  13191. }
  13192. else {
  13193. var curElem = [Number(elem.split('-')[0] || 1), Number(elem.split('-')[1] || getFileSizeAndLength().page)].sort(function(a, b){ return a - b; });
  13194. for (var i = curElem[0]; i <= curElem[1]; i++) {
  13195. if (!pagesRange.some(function(e){ return i === e; })) pagesRange.push(i);
  13196. }
  13197. }
  13198. });
  13199. pagesRange.sort(function(a, b){ return a - b; });
  13200. }
  13201.  
  13202. ehDownloadDialog.style.display = 'block';
  13203. if (!getAllPagesURLFin) {
  13204. pageURLsList = [];
  13205. var pagesLength;
  13206. try { // in case pages has been modified like #56
  13207. pagesLength = [].reduce.call(document.querySelectorAll('.ptt td'), function(x, y){
  13208. var i = Number(y.textContent);
  13209. if (!isNaN(i)) return x > i ? x : i;
  13210. else return x;
  13211. });
  13212. }
  13213. catch (error) {}
  13214. var curPage = 0;
  13215. retryCount = 0;
  13216.  
  13217. var xhr = fetchPagesXHR;
  13218. xhr.onload = function(){
  13219. if (xhr.status !== 200 || !xhr.responseText) {
  13220. if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13221. pushDialog('Failed! Retrying... ');
  13222. retryCount++;
  13223. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13224. xhr.timeout = 30000;
  13225. xhr.send();
  13226. }
  13227. else {
  13228. pushDialog('Failed!\nFetch Pages\' URL failed, Please try again later.');
  13229. isDownloading = false;
  13230. alert('Fetch Pages\' URL failed, Please try again later.');
  13231. }
  13232. return;
  13233. }
  13234.  
  13235. var pagesURL = xhr.responseText.split('<div id="gdt">')[1].split('<div class="c">')[0].match(ehDownloadRegex.pagesURL);
  13236. if (!pagesURL) {
  13237. console.error('[EHD] Response content is incorrect!');
  13238. if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13239. pushDialog('Failed! Retrying... ');
  13240. retryCount++;
  13241. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13242. xhr.timeout = 30000;
  13243. xhr.send();
  13244. }
  13245. else {
  13246. pushDialog('Failed!\nCan\'t get pages URL from response content.');
  13247. isDownloading = false;
  13248. //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.');
  13249. }
  13250. return;
  13251. }
  13252.  
  13253. if (pagesURL[0].indexOf('/mpv/') >= 0) {
  13254. console.log('[EHD] Page 1 URL > ' + pagesURL[0] + ' , use MPV fetch');
  13255. pushDialog('Pages URL is MPV link\n');
  13256.  
  13257. getPagesURLFromMPV();
  13258. return;
  13259. }
  13260.  
  13261. for (var i = 0; i < pagesURL.length; i++) {
  13262. pageURLsList.push(pagesURL[i].split('"')[1].replaceHTMLEntites());
  13263. }
  13264. pushDialog('Succeed!');
  13265.  
  13266. curPage++;
  13267. if (!pagesLength) { // can't get pagesLength correctly before
  13268. pagesLength = xhr.responseText.match(ehDownloadRegex.pagesLength)[1] - 0;
  13269. }
  13270. if (curPage === pagesLength) {
  13271. getAllPagesURLFin = true;
  13272. var wrongPages = pagesRange.filter(function(elem){ return elem > pageURLsList.length; });
  13273. if (wrongPages.length !== 0) {
  13274. pagesRange = pagesRange.filter(function(elem){ return elem <= pageURLsList.length; });
  13275. pushDialog('\nPage ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.\n');
  13276. if (pagesRange.length === 0) {
  13277. pushDialog('Nothing matches provided pages range, stop downloading.');
  13278. alert('Nothing matches provided pages range, stop downloading.');
  13279. insertCloseButton();
  13280. return;
  13281. }
  13282. }
  13283. totalCount = pagesRange.length || pageURLsList.length;
  13284. pushDialog('\n\n');
  13285. initProgressTable();
  13286. requestDownload();
  13287. }
  13288. else {
  13289. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13290. xhr.send();
  13291. pushDialog('\nFetching Gallery Pages URL (' + (curPage + 1) + '/' + pagesLength + ') ... ');
  13292. }
  13293. };
  13294. xhr.ontimeout = xhr.onerror = function(){
  13295. if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13296. pushDialog('Failed! Retrying... ');
  13297. retryCount++;
  13298. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13299. xhr.timeout = 30000;
  13300. xhr.send();
  13301. }
  13302. else {
  13303. pushDialog('Failed!\nFetch Pages\' URL failed, Please try again later.');
  13304. isDownloading = false;
  13305. alert('Fetch Pages\' URL failed, Please try again later.');
  13306. }
  13307. };
  13308. xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);
  13309. xhr.timeout = 30000;
  13310. xhr.send();
  13311. pushDialog('\nFetching Gallery Pages URL (' + (curPage + 1) + '/' + (pagesLength || '?') + ') ... ');
  13312. }
  13313. else {
  13314. var wrongPages = pagesRange.filter(function(elem){ return elem > pageURLsList.length; });
  13315. if (wrongPages.length !== 0) {
  13316. pagesRange = pagesRange.filter(function(elem){ return elem <= pageURLsList.length; });
  13317. pushDialog('\nPage ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.\n');
  13318. if (pagesRange.length === 0) {
  13319. pushDialog('Nothing matches provided pages range, stop downloading.');
  13320. alert('Nothing matches provided pages range, stop downloading.');
  13321. insertCloseButton();
  13322. return;
  13323. }
  13324. }
  13325.  
  13326. totalCount = pagesRange.length || pageURLsList.length;
  13327. pushDialog('\n\n');
  13328. initProgressTable();
  13329. requestDownload();
  13330. }
  13331. }
  13332.  
  13333. function initEHDownload() {
  13334. for (var i = 0; i < fetchThread.length; i++) {
  13335. if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort();
  13336. }
  13337. imageList = [];
  13338. imageData = [];
  13339. fetchThread = [];
  13340. retryCount = [];
  13341. downloadedCount = fetchCount = failedCount = 0;
  13342. isPausing = false;
  13343. zip = new JSZip();
  13344. infoStr = '';
  13345. fetchPagesXHR.abort();
  13346.  
  13347. if (setting['recheck-file-name']) {
  13348. var dirNameNode = document.querySelector('.ehD-box-extend-dirname');
  13349. var fileNameNode = document.querySelector('.ehD-box-extend-filename');
  13350.  
  13351. if (dirNameNode && dirNameNode.value) {
  13352. dirName = getSafeName(dirNameNode.value, true);
  13353. }
  13354. else {
  13355. dirName = getReplacedName(!setting['dir-name'] ? '{gid}_{token}' : setting['dir-name']);
  13356. }
  13357.  
  13358. if (fileNameNode && fileNameNode.value) {
  13359. fileName = getSafeName(fileNameNode.value);
  13360. }
  13361. else {
  13362. fileName = getReplacedName(!setting['file-name'] ? '{title}' : setting['file-name']);
  13363. }
  13364. }
  13365. else {
  13366. dirName = getReplacedName(!setting['dir-name'] ? '{gid}_{token}' : setting['dir-name']);
  13367. fileName = getReplacedName(!setting['file-name'] ? '{title}' : setting['file-name']);
  13368. }
  13369.  
  13370. if (dirName.trim() === '/') dirName = '';
  13371. needNumberImages = ehDownloadNumberInput.querySelector('input').checked;
  13372.  
  13373. var requiredBytes = Math.ceil(getFileSizeAndLength().size + 100 * 1024);
  13374. var requiredMBs = getFileSizeAndLength().sizeMB + 0.1;
  13375.  
  13376. var fsErrorHandler = function (error) {
  13377. ehDownloadFS.errorHandler(error);
  13378.  
  13379. // roll back and use Blob to handle file
  13380. ehDownloadFS.needFileSystem = false;
  13381. alert('An error occured when requesting FileSystem.\n' +
  13382. 'Error Name: ' + (e.name || 'Unknown Error') + '\n' +
  13383. 'Error Message: ' + e.message + '\n\n' +
  13384. 'Roll back and use Blob to handle file.');
  13385. };
  13386.  
  13387. 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;
  13388. else if (setting['store-in-fs'] && requestFileSystem && requiredMBs >= (setting['fs-size'] !== undefined ? setting['fs-size'] : 200)) {
  13389. ehDownloadFS.needFileSystem = true;
  13390. console.log('[EHD] Required File System Space >', requiredBytes);
  13391.  
  13392. // Chrome can use about 10% of free space of disk where Chrome User Data stored in as TEMPORARY File System Storage.
  13393. if (navigator.webkitTemporaryStorage) { // if support navigator.webkitTemporaryStorage to check usable space
  13394. // use `queryUsageAndQuota` instead of `requestQuota` to check storage space,
  13395. // because `requestQuota` is incorrect when harddisk is full, says have about 5GB storage
  13396. navigator.webkitTemporaryStorage.queryUsageAndQuota(function (usage, quota) {
  13397. console.log('[EHD] Free TEMPORARY File System Space >', quota - usage);
  13398. if (quota - usage < requiredBytes) {
  13399. console.log('[EHD] Free TEMPORARY File System Space is not enough.');
  13400.  
  13401. // free space is not enough, then use persistent space
  13402. // in fact, free space of persisent file storage is always 10GiB, even free disk space is not enough
  13403. navigator.webkitPersistentStorage.queryUsageAndQuota(function (usage, quota) {
  13404. console.log('[EHD] Free PERSISTENT File System Space >', quota - usage);
  13405. if (quota - usage < requiredBytes) {
  13406. // roll back and use Blob to handle file
  13407. ehDownloadFS.needFileSystem = false;
  13408. 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.');
  13409. }
  13410. else {
  13411. pushDialog('\n<strong>Please allow storing large content if the browser asked for it.</strong>\n');
  13412. requestFileSystem(window.PERSISTENT, requiredBytes, ehDownloadFS.initHandler, fsErrorHandler);
  13413. }
  13414. }, fsErrorHandler);
  13415. }
  13416. else requestFileSystem(window.TEMPORARY, requiredBytes, ehDownloadFS.initHandler, fsErrorHandler);
  13417. }, fsErrorHandler);
  13418. }
  13419. else requestFileSystem(window.TEMPORARY, requiredBytes, ehDownloadFS.initHandler, fsErrorHandler);
  13420. }
  13421.  
  13422. // Array.prototype.some() is a bit ugly, so we use toString().indexOf() lol
  13423. var infoNeeds = setting['save-info-list'].toString();
  13424. if (infoNeeds.indexOf('title') >= 0) {
  13425. infoStr += document.getElementById('gn').textContent.replaceHTMLEntites() + '\n' +
  13426. document.getElementById('gj').textContent.replaceHTMLEntites() + '\n' +
  13427. window.location.href.replaceHTMLEntites() + '\n\n';
  13428. }
  13429.  
  13430. if (infoNeeds.indexOf('metas') >= 0) {
  13431. infoStr += 'Category: ' + document.getElementsByClassName('ic')[0].getAttribute('alt').toUpperCase() + '\n' +
  13432. 'Uploader: ' + document.querySelector('#gdn a').textContent.replaceHTMLEntites() + '\n';
  13433. }
  13434. var metaNodes = document.querySelectorAll('#gdd tr');
  13435. for (var i = 0; i < metaNodes.length; i++) {
  13436. var c1 = metaNodes[i].getElementsByClassName('gdt1')[0].textContent.replaceHTMLEntites();
  13437. var c2 = metaNodes[i].getElementsByClassName('gdt2')[0].textContent.replaceHTMLEntites();
  13438. if (infoNeeds.indexOf('metas') >= 0) infoStr += c1 + ' ' + c2 + '\n';
  13439. }
  13440. if (infoNeeds.indexOf('metas') >= 0) infoStr += 'Rating: ' + unsafeWindow.average_rating + '\n\n';
  13441.  
  13442. if (infoNeeds.indexOf('tags') >= 0) {
  13443. infoStr += 'Tags:\n';
  13444.  
  13445. var tagsList = document.querySelectorAll('#taglist tr');
  13446. Array.prototype.forEach.call(tagsList, function(elem){
  13447. var tds = elem.getElementsByTagName('td');
  13448. infoStr += '> ' + tds[0].textContent + ' ';
  13449.  
  13450. var tags = tds[1].querySelectorAll('a');
  13451. infoStr += Array.prototype.map.call(tags, function(e){
  13452. return e.textContent;
  13453. }).join(', ') + '\n';
  13454. });
  13455.  
  13456. infoStr += '\n';
  13457. }
  13458.  
  13459. if (infoNeeds.indexOf('uploader-comment') >= 0 && document.getElementById('comment_0')) {
  13460. infoStr += 'Uploader Comment:\n' + document.getElementById('comment_0').innerHTML.replace(/<br>|<br \/>/gi, '\n') + '\n\n';
  13461. }
  13462. isDownloading = true;
  13463. pushDialog(infoStr);
  13464.  
  13465. pushDialog('Start downloading at ' + new Date() + '\n');
  13466. ehDownloadDialog.appendChild(ehDownloadStatus);
  13467.  
  13468. // get all pages url to fix 403 forbidden (download request was timed out)
  13469. getAllPagesURL();
  13470.  
  13471. // init playing music
  13472. if (setting['play-silent-music']) {
  13473. emptyAudio = new Audio(emptyAudioFile);
  13474. emptyAudio.loop = true;
  13475.  
  13476. var hidden, visibilityChange;
  13477. if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support
  13478. hidden = 'hidden';
  13479. visibilityChange = 'visibilitychange';
  13480. }
  13481. else if (typeof document.mozHidden !== 'undefined') {
  13482. hidden = 'mozHidden';
  13483. visibilityChange = 'mozvisibilitychange';
  13484. }
  13485. else if (typeof document.webkitHidden !== 'undefined') {
  13486. hidden = 'webkitHidden';
  13487. visibilityChange = 'webkitvisibilitychange';
  13488. }
  13489.  
  13490. var visibilityChangeHandler = function(isHidden) {
  13491. if (typeof isHidden !== 'boolean') {
  13492. isHidden = document[hidden];
  13493. }
  13494. if (isHidden && ((isDownloading && !isPausing) || isSaving)) {
  13495. emptyAudio.play();
  13496. }
  13497. else {
  13498. emptyAudio.pause();
  13499. }
  13500. };
  13501.  
  13502. if (visibilityChange) {
  13503. window.addEventListener(visibilityChange, visibilityChangeHandler);
  13504. }
  13505. else {
  13506. window.addEventListener('focus', function() {
  13507. visibilityChangeHandler(false);
  13508. });
  13509. window.addEventListener('blur', function() {
  13510. visibilityChangeHandler(true);
  13511. });
  13512. }
  13513.  
  13514. visibilityChangeHandler();
  13515. }
  13516. }
  13517.  
  13518. function initProgressTable(){
  13519. progressTable = document.createElement('table');
  13520. progressTable.className = 'ehD-pt';
  13521. ehDownloadDialog.style.display = 'block';
  13522. ehDownloadDialog.appendChild(progressTable);
  13523. ehDownloadDialog.appendChild(forceDownloadTips);
  13524. ehDownloadDialog.appendChild(ehDownloadPauseBtn);
  13525. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  13526. }
  13527.  
  13528. function requestDownload(ignoreFailed){
  13529. if (isPausing) return;
  13530. var j = 0;
  13531. for (var i = fetchCount; i < (setting['thread-count'] !== undefined ? setting['thread-count'] : 5); i++) {
  13532. for (/*var j = 0*/; j < totalCount; j++) {
  13533. if (imageData[j] == null && (ignoreFailed || (retryCount[j] || 0) <= (setting['retry-count'] !== undefined ? setting['retry-count'] : 3))) {
  13534. imageData[j] = 'Fetching';
  13535. if (imageList[j] && setting['never-new-url']) fetchOriginalImage(j);
  13536. else getPageData(j);
  13537. fetchCount++;
  13538. break;
  13539. }
  13540. }
  13541. }
  13542.  
  13543. }
  13544.  
  13545. function getPageData(index) {
  13546. if (isPausing) return;
  13547.  
  13548. if (pagesRange.length) var realIndex = pagesRange[index];
  13549. else var realIndex = index + 1;
  13550.  
  13551. var needScrollIntoView = ehDownloadDialog.clientHeight + ehDownloadDialog.scrollTop >= ehDownloadDialog.scrollHeight;
  13552.  
  13553. var node = progressTable.querySelector('tr[data-index="' + index + '"]');
  13554. if (!node) {
  13555. node = document.createElement('tr');
  13556. node.className = 'ehD-pt-item';
  13557. node.setAttribute('data-index', index);
  13558. node.innerHTML = '\
  13559. <td class="ehD-pt-name">#' + realIndex + '</td>\
  13560. <td class="ehD-pt-progress-outer">\
  13561. <progress class="ehD-pt-progress"></progress>\
  13562. <span class="ehD-pt-progress-text"></span>\
  13563. </td>\
  13564. <td class="ehD-pt-status">\
  13565. <span class="ehD-pt-status-text">Pending...</span>\
  13566. <span class="ehD-pt-abort">Force Abort</span>\
  13567. </td>';
  13568. progressTable.appendChild(node);
  13569. }
  13570. if (needScrollIntoView) {
  13571. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  13572. }
  13573.  
  13574. var nodeList = {
  13575. current: node,
  13576. fileName: node.getElementsByTagName('td')[0],
  13577. status: node.getElementsByTagName('td')[2],
  13578. statusText: node.getElementsByClassName('ehD-pt-status-text')[0],
  13579. progress: node.getElementsByTagName('progress')[0],
  13580. progressText: node.getElementsByTagName('span')[0],
  13581. abort: node.getElementsByClassName('ehD-pt-abort')[0]
  13582. };
  13583.  
  13584. retryCount[index] = 0;
  13585. 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?:/, '')*/;
  13586.  
  13587. // assign to fetchThread, so that we can abort them and all GM_xhr by one command fetchThread[i].abort()
  13588. var xhr = fetchThread[index] = new XMLHttpRequest();
  13589. xhr.onload = function() {
  13590. if (xhr.status !== 200 || !xhr.responseText) {
  13591. if (retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13592. retryCount[index]++;
  13593.  
  13594. updateProgress(nodeList, {
  13595. status: 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ')...',
  13596. progress: '',
  13597. progressText: '',
  13598. class: 'ehD-pt-warning'
  13599. });
  13600.  
  13601. xhr.open('GET', fetchURL);
  13602. xhr.timeout = 30000;
  13603. xhr.send();
  13604. }
  13605. else {
  13606. failedCount++;
  13607. fetchCount--;
  13608.  
  13609. console.error('[EHD] #' + realIndex + ': Failed getting image URL');
  13610. updateProgress(nodeList, {
  13611. status: 'Failed getting URL',
  13612. progress: '0',
  13613. progressText: '',
  13614. class: 'ehD-pt-failed'
  13615. });
  13616. updateTotalStatus();
  13617.  
  13618. checkFailed();
  13619. }
  13620.  
  13621. return;
  13622. }
  13623.  
  13624. try {
  13625. 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();
  13626. var fileName = xhr.responseText.match(ehDownloadRegex.fileName)[1].replaceHTMLEntites();
  13627. var nextNL = ehDownloadRegex.nl.test(xhr.responseText) ? xhr.responseText.match(ehDownloadRegex.nl)[1] : null;
  13628. }
  13629. catch (error) {
  13630. console.error('[EHD] Response content is not correct!', error);
  13631. if (retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13632. retryCount[index]++;
  13633.  
  13634. updateProgress(nodeList, {
  13635. status: 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ')...',
  13636. progress: '',
  13637. progressText: '',
  13638. class: 'ehD-pt-warning'
  13639. });
  13640.  
  13641. xhr.open('GET', fetchURL);
  13642. xhr.timeout = 30000;
  13643. xhr.send();
  13644. }
  13645. else {
  13646. failedCount++;
  13647. fetchCount--;
  13648.  
  13649. console.error('[EHD] #' + realIndex + ': Can\'t get request content from response content');
  13650. updateProgress(nodeList, {
  13651. status: 'Response Error',
  13652. progress: '0',
  13653. progressText: '',
  13654. class: 'ehD-pt-failed'
  13655. });
  13656. updateTotalStatus();
  13657. //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.');
  13658.  
  13659. checkFailed();
  13660. }
  13661. return;
  13662. }
  13663.  
  13664. var imageNumber = '';
  13665. if (needNumberImages) {
  13666. // Number images, thanks to JingJang@GitHub, source: https://github.com/JingJang/E-Hentai-Downloader
  13667. if (!setting['number-real-index'] && pagesRange.length) { // if pages range was set and number original index is not required
  13668. var len = pagesRange.length.toString().length,
  13669. padding = new Array(len < 3 ? len + 1 : len).join('0');
  13670. imageNumber = (padding + (index + 1)).slice(0 - len);
  13671. }
  13672. else { // pages range was not set (download all pages, so index + 1 === realIndex) or number original index is required
  13673. var len = pageURLsList.length.toString().length,
  13674. padding = new Array(len < 3 ? len + 1 : len).join('0');
  13675. imageNumber = (padding + realIndex).slice(0 - len);
  13676. }
  13677. }
  13678.  
  13679. //imageList.push(new PageData(fetchURL, imageURL, fileName, nextNL, realIndex));
  13680. imageList[index] = new PageData(fetchURL, imageURL, fileName, nextNL, realIndex, imageNumber);
  13681.  
  13682. if (isPausing) {
  13683. updateProgress(nodeList, {
  13684. name: '#' + realIndex + ': ' + fileName,
  13685. status: 'Force Paused',
  13686. progress: '',
  13687. progressText: '',
  13688. class: ''
  13689. });
  13690. fetchCount--;
  13691. imageData[index] = null;
  13692. updateTotalStatus();
  13693. }
  13694. else {
  13695. fetchOriginalImage(index, nodeList);
  13696. }
  13697.  
  13698. };
  13699. xhr.onerror = xhr.ontimeout = function() {
  13700. if (retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  13701. retryCount[index]++;
  13702.  
  13703. updateProgress(nodeList, {
  13704. status: 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ')...',
  13705. progress: '',
  13706. progressText: '',
  13707. class: 'ehD-pt-warning'
  13708. });
  13709.  
  13710. xhr.open('GET', fetchURL);
  13711. xhr.timeout = 30000;
  13712. xhr.send();
  13713. }
  13714. else {
  13715. failedCount++;
  13716. fetchCount--;
  13717.  
  13718. console.error('[EHD] #' + realIndex + ': Failed getting image URL');
  13719. updateProgress(nodeList, {
  13720. status: 'Failed getting URL',
  13721. progress: '0',
  13722. progressText: '',
  13723. class: 'ehD-pt-failed'
  13724. });
  13725. updateTotalStatus();
  13726.  
  13727. checkFailed();
  13728. }
  13729. };
  13730. xhr.open('GET', fetchURL);
  13731. xhr.timeout = 30000;
  13732. xhr.send();
  13733. }
  13734.  
  13735. function showSettings() {
  13736. var ehDownloadSettingPanel = document.createElement('div');
  13737. ehDownloadSettingPanel.className = 'ehD-setting';
  13738. ehDownloadSettingPanel.setAttribute('data-active-setting', 'basic');
  13739. ehDownloadSettingPanel.innerHTML = '\
  13740. <ul class="ehD-setting-tab">\
  13741. <li data-target-setting="basic">Basic</li>\
  13742. <li data-target-setting="advanced">Advanced</li>\
  13743. </ul>\
  13744. <div class="ehD-setting-main">\
  13745. <div class="ehD-setting-wrapper">\
  13746. <div data-setting-page="basic" class="ehD-setting-content">\
  13747. <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 advised)</label></div>\
  13748. <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>\
  13749. <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>\
  13750. <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>\
  13751. <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>\
  13752. <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>\
  13753. <div class="g2"><label><input type="checkbox" data-ehd-setting="number-auto-retry"> Retry automatically when images download failed</label></div>\
  13754. <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>\
  13755. <div class="g2"><label>Set Zip file name as <input type="text" data-ehd-setting="file-name" placeholder="{title}" style="width: 110px;"> *</label></div>\
  13756. <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>\
  13757. <div class="g2"><label><input type="checkbox" data-ehd-setting="ignore-torrent"> Never show notification if torrents are available</label></div>\
  13758. <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>\
  13759. <div class="g2"><label><input type="checkbox" data-ehd-setting="hide-image-limits"> Disable requesting and showing image limits</label></div>\
  13760. <div class="g2"><label><input type="checkbox" data-ehd-setting="hide-estimated-cost"> Disable pre-calculating image limits cost</label></div>\
  13761. <div class="ehD-setting-note">\
  13762. <div class="g2">\
  13763. * Available templates: \
  13764. <span title="You can find GID and token at the address bar like this: exhentai.org/g/[GID]/[Token]/">{gid} Gallery GID</sapn> | \
  13765. <span title="You can find GID and token at the address bar like this: exhentai.org/g/[GID]/[Token]/">{token} Gallery token</sapn> | \
  13766. <span title="This title is the English title or Latin transliteration, you can find it as the first line of the title.">{title} Gallery title</span> | \
  13767. <span title="This title is the original language title, you can find it as the second line of the title.">{subtitle} Gallery sub-title</span> | \
  13768. <span title="This tag means the sort name of the gallery, and its output string is upper.">{tag} Gallery tag</span> | \
  13769. <span title="You can find it at the left of the gallery page.">{uploader} Gallery uploader</span>\
  13770. </div>\
  13771. </div>\
  13772. </div>\
  13773. <div data-setting-page="advanced" class="ehD-setting-content">\
  13774. <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>\
  13775. <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>\
  13776. <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>\
  13777. <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>\
  13778. <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>\
  13779. <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>\
  13780. <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>\
  13781. <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>\
  13782. <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>\
  13783. <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>\
  13784. <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>\
  13785. <div class="g2"><label><input type="checkbox" data-ehd-setting="force-pause"> Force drop downloaded images data when pausing download</label></div>\
  13786. <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>\
  13787. <div class="ehD-setting-note">\
  13788. <div class="g2">\
  13789. (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.\
  13790. </div>\
  13791. <div class="g2">\
  13792. (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.\
  13793. </div>\
  13794. <div class="g2">\
  13795. (3) If enabled you can save larger Zip files (probably ~1GB).\
  13796. </div>\
  13797. <div class="g2">\
  13798. (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.\
  13799. </div>\
  13800. <div class="g2">\
  13801. (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.\
  13802. </div>\
  13803. </div>\
  13804. </div>\
  13805. </div>\
  13806. </div>\
  13807. <div class="ehD-setting-footer" style="text-align: center">\
  13808. <button data-action="save">Save</button> <button data-action="cancel">Cancel</button>\
  13809. </div>';
  13810. document.body.appendChild(ehDownloadSettingPanel);
  13811. for (var i in setting) {
  13812. if (setting[i] instanceof Array) {
  13813. setting[i].forEach(function(elem){
  13814. var element = ehDownloadSettingPanel.querySelector('input[data-ehd-setting="' + i + '[]"][value="' + elem + '"], select[data-ehd-setting="' + i + '[]"] option[value="' + elem + '"]');
  13815. if (!element) return;
  13816.  
  13817. if (element.getAttribute('type') === 'checkbox') {
  13818. element.setAttribute('checked', 'checked');
  13819. }
  13820. else if (element.tagName.toLowerCase() === 'option') {
  13821. element.setAttribute('selected', 'selected');
  13822. }
  13823. else element.value = elem;
  13824. });
  13825. }
  13826. else {
  13827. var element = ehDownloadSettingPanel.querySelector('input[data-ehd-setting="' + i + '"], select[data-ehd-setting="' + i + '"]');
  13828. if (!element) continue;
  13829. if (element.getAttribute('type') === 'checkbox') {
  13830. if (setting[i]) element.setAttribute('checked', 'checked');
  13831. }
  13832. else if (element.tagName.toLowerCase() === 'select') {
  13833. element = element.querySelector('option[value="' + setting[i] + '"]');
  13834. if (!element) continue;
  13835. element.setAttribute('selected', 'selected');
  13836. }
  13837. else element.setAttribute('value', setting[i]);
  13838. }
  13839. }
  13840.  
  13841. ehDownloadSettingPanel.getElementsByClassName('ehD-setting-tab')[0].addEventListener('click', function(event){
  13842. var target = event.target;
  13843. if (target.tagName.toLowerCase() === 'li') {
  13844. ehDownloadSettingPanel.setAttribute('data-active-setting', target.dataset.targetSetting);
  13845. }
  13846. });
  13847.  
  13848. ehDownloadSettingPanel.getElementsByClassName('ehD-setting-footer')[0].addEventListener('click', function(event){
  13849. var target = event.target;
  13850. if (target.tagName.toLowerCase() === 'button') {
  13851. if (target.dataset.action === 'save') {
  13852. var inputs = ehDownloadSettingPanel.querySelectorAll('input[data-ehd-setting], select[data-ehd-setting]');
  13853. setting = {};
  13854. for (var i = 0; i < inputs.length; i++) {
  13855. if (inputs[i].getAttribute('type') !== 'checkbox' && inputs[i].value === '') continue;
  13856.  
  13857. var curSettingName = inputs[i].dataset.ehdSetting;
  13858.  
  13859. if (inputs[i].getAttribute('type') === 'checkbox') {
  13860. if (inputs[i].checked) {
  13861. if (inputs[i].hasAttribute('value')) {
  13862. if (curSettingName.indexOf('[]') >= 0) {
  13863. curSettingName = curSettingName.split('[]')[0];
  13864. if (!setting[curSettingName]) setting[curSettingName] = [];
  13865. setting[curSettingName].push(inputs[i].getAttribute('value'));
  13866. }
  13867. else {
  13868. setting[curSettingName] = inputs[i].getAttribute('value');
  13869. }
  13870. }
  13871. else {
  13872. setting[curSettingName] = inputs[i].checked;
  13873. }
  13874. }
  13875. }
  13876. else if (inputs[i].getAttribute('type') === 'number') {
  13877. setting[curSettingName] = Number(inputs[i].value);
  13878. if (isNaN(setting[curSettingName])) {
  13879. setting[curSettingName] = Number(inputs[i].getAttribute('placeholder'));
  13880. }
  13881. }
  13882. else {
  13883. setting[curSettingName] = inputs[i].value;
  13884. }
  13885. }
  13886. GM_setValue('ehD-setting', JSON.stringify(setting));
  13887. }
  13888. document.body.removeChild(ehDownloadSettingPanel);
  13889.  
  13890. if (document.querySelector('.ehD-box-extend')) {
  13891. toggleFilenameConfirmInput('reset');
  13892. }
  13893. else {
  13894. toggleFilenameConfirmInput(!setting['recheck-file-name']);
  13895. }
  13896. showPreCalcCost();
  13897. }
  13898. });
  13899.  
  13900. Array.prototype.forEach.call(ehDownloadSettingPanel.getElementsByClassName('ehD-setting-content'), function(elem) {
  13901. elem.addEventListener('focusin', function(event){
  13902. ehDownloadSettingPanel.setAttribute('data-active-setting', this.dataset.settingPage);
  13903. // prevent auto-scroll from browser
  13904. ehDownloadSettingPanel.scrollLeft = 0;
  13905. }, true);
  13906. });
  13907. }
  13908.  
  13909. function getImageLimits(forced, host){
  13910. var host = host || location.hostname;
  13911. if (host === 'exhentai.org') {
  13912. host = 'e-hentai.org';
  13913. }
  13914. var url = 'https://' + host + '/home.php';
  13915.  
  13916. var preData = JSON.parse(localStorage.getItem('ehd-image-limits-' + host) || '{"timestamp":0}');
  13917. if (!forced && new Date() - preData.timestamp < 30000) {
  13918. return showImageLimits();
  13919. }
  13920.  
  13921. console.log('[EHD] Request Image Limits From ' + host);
  13922.  
  13923. GM_xmlhttpRequest({
  13924. method: 'GET',
  13925. url: url,
  13926. timeout: 300000,
  13927. onload: function(res) {
  13928. if (!res.responseText) return;
  13929. var data = res.responseText.match(ehDownloadRegex.imageLimits);
  13930. if (data && data.length === 3) {
  13931. preData.cur = data[1];
  13932. preData.total = data[2];
  13933. preData.timestamp = new Date().getTime();
  13934. localStorage.setItem('ehd-image-limits-' + host, JSON.stringify(preData));
  13935. showImageLimits();
  13936. }
  13937. }
  13938. });
  13939. }
  13940.  
  13941. function showImageLimits(){
  13942. var list = Object.keys(localStorage).filter(function(elem){
  13943. return elem.indexOf('ehd-image-limits-') === 0;
  13944. }).sort().map(function(elem){
  13945. var curData = JSON.parse(localStorage.getItem(elem));
  13946. return curData.cur + '/' + curData.total;
  13947. });
  13948.  
  13949. ehDownloadBox.getElementsByClassName('ehD-box-limit')[0].innerHTML = ' | <a href="https://e-hentai.org/home.php">Image Limits: ' + list.join('; ') + '</a>';
  13950. }
  13951.  
  13952. var getFileSizeAndLength = function() {
  13953. var context = document.getElementById('gdd').textContent;
  13954. var sizeText = context.split('File Size:')[1].split('Length:')[0].trim();
  13955. var pageText = context.split('Length:')[1].split('page')[0].trim();
  13956.  
  13957. var sizeMB, sizeKB;
  13958. var page = pageText - 0;
  13959.  
  13960. if (sizeText.indexOf('MB') >= 0) {
  13961. sizeMB = parseFloat(sizeText) + 0.01;
  13962. sizeKB = sizeMB * 1024;
  13963. }
  13964. else if (sizeText.indexOf('GB') >= 0) {
  13965. sizeMB = (parseFloat(sizeText) + 0.01) * 1024;
  13966. sizeKB = sizeMB * 1024;
  13967. }
  13968. else {
  13969. sizeMB = 1;
  13970. sizeKB = parseFloat(sizeText);
  13971. }
  13972.  
  13973. var result = {
  13974. sizeMB: sizeMB,
  13975. sizeKB: sizeKB,
  13976. size: sizeKB * 1024,
  13977. page: page
  13978. };
  13979.  
  13980. getFileSizeAndLength = function(){
  13981. return result;
  13982. };
  13983.  
  13984. return result;
  13985. };
  13986.  
  13987. function toggleFilenameConfirmInput(hide){
  13988. var extendNodes = document.querySelector('.ehD-box-extend');
  13989. if (extendNodes) {
  13990. if (hide === 'reset') {
  13991. ehDownloadBox.removeChild(extendNodes);
  13992. if (setting['recheck-file-name']) toggleFilenameConfirmInput();
  13993. }
  13994. else if (hide) {
  13995. extendNodes.style.display = 'none';
  13996. }
  13997. else {
  13998. extendNodes.style.display = 'block';
  13999. }
  14000. }
  14001. else if (!hide) {
  14002. extendNodes = document.createElement('div');
  14003. extendNodes.className = 'ehD-box-extend';
  14004. extendNodes.innerHTML = '<div class="g2">' + ehDownloadArrow + ' <a>File Name <input type="text" class="ehD-box-extend-filename"></a></div>' +
  14005. '<div class="g2">' + ehDownloadArrow + ' <a>Path Name <input type="text" class="ehD-box-extend-dirname"></a></div>';
  14006. ehDownloadBox.appendChild(extendNodes);
  14007.  
  14008. dirName = getReplacedName(!setting['dir-name'] ? '{gid}_{token}' : setting['dir-name']);
  14009. fileName = getReplacedName(!setting['file-name'] ? '{title}' : setting['file-name']);
  14010. extendNodes.getElementsByClassName('ehD-box-extend-filename')[0].value = fileName;
  14011. extendNodes.getElementsByClassName('ehD-box-extend-dirname')[0].value = dirName;
  14012. }
  14013. }
  14014.  
  14015. function showPreCalcCost(){
  14016. var size = 0;
  14017. var page = getFileSizeAndLength().page;
  14018.  
  14019. if (!setting['force-resized']) {
  14020. size = getFileSizeAndLength().sizeMB;
  14021. }
  14022.  
  14023. 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">Estimated Limits Cost: ' + (parseInt(size * 5) + page) + '</a>';
  14024. }
  14025.  
  14026. // EHD Box, thanks to JingJang@GitHub, source: https://github.com/JingJang/E-Hentai-Downloader
  14027. var ehDownloadBox = document.createElement('fieldset');
  14028. ehDownloadBox.className = 'ehD-box';
  14029. var ehDownloadBoxTitle = document.createElement('legend');
  14030. ehDownloadBoxTitle.innerHTML = 'E-Hentai Downloader <span class="ehD-box-limit"></span> <span class="ehD-box-cost"></span>';
  14031. ehDownloadBoxTitle.style.cssText = (origin.indexOf('exhentai.org') >= 0 ? 'color: #ffff66; ' : '') + 'font-weight: 700;';
  14032. ehDownloadBox.appendChild(ehDownloadBoxTitle);
  14033. var ehDownloadStylesheet = document.createElement('style');
  14034. ehDownloadStylesheet.textContent = ehDownloadStyle;
  14035. ehDownloadBox.appendChild(ehDownloadStylesheet);
  14036.  
  14037. var ehDownloadArrow = '<img src="data:image/gif;base64,R0lGODlhBQAHALMAAK6vr7OztK+urra2tkJCQsDAwEZGRrKyskdHR0FBQUhISP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAFAAcAAAQUUI1FlREVpbOUSkTgbZ0CUEhBLREAOw==">';
  14038.  
  14039. var ehDownloadAction = document.createElement('div');
  14040. ehDownloadAction.className = 'g2';
  14041. ehDownloadAction.innerHTML = ehDownloadArrow + ' <a>Download Archive</a>';
  14042. ehDownloadAction.addEventListener('click', function(event){
  14043. event.preventDefault();
  14044.  
  14045. var torrentsNode = document.querySelector('#gd5 a[onclick*="gallerytorrents.php"]');
  14046. var torrentsCount = torrentsNode ? torrentsNode.textContent.match(/\d+/)[0] - 0 : 0;
  14047. if (isDownloading && !confirm('E-Hentai Downloader is working now, are you sure to stop downloading and start a new download?')) return;
  14048. 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)')) {
  14049. return torrentsNode.dispatchEvent(new MouseEvent('click'));
  14050. }
  14051. if (unsafeWindow.apiuid === -1 && !confirm('You are not logged in to E-Hentai Forums, so you can\'t download original image. Continue?')) return;
  14052. ehDownloadDialog.innerHTML = '';
  14053.  
  14054. initEHDownload();
  14055. });
  14056. ehDownloadBox.appendChild(ehDownloadAction);
  14057.  
  14058. var ehDownloadNumberInput = document.createElement('div');
  14059. ehDownloadNumberInput.className = 'g2';
  14060. ehDownloadNumberInput.innerHTML = ehDownloadArrow + ' <a><label><input type="checkbox" style="vertical-align: middle; margin: 0;"> Number Images<label></a>';
  14061. ehDownloadBox.appendChild(ehDownloadNumberInput);
  14062.  
  14063. var ehDownloadRange = document.createElement('div');
  14064. ehDownloadRange.className = 'g2';
  14065. ehDownloadRange.innerHTML = ehDownloadArrow + ' <a><label>Pages Range <input type="text" placeholder="eg. -10,12,14-20,27,30-"></label></a>';
  14066. ehDownloadBox.appendChild(ehDownloadRange);
  14067.  
  14068. var ehDownloadSetting = document.createElement('div');
  14069. ehDownloadSetting.className = 'g2';
  14070. ehDownloadSetting.innerHTML = ehDownloadArrow + ' <a>Settings</a>';
  14071. ehDownloadSetting.addEventListener('click', function(event){
  14072. event.preventDefault();
  14073. showSettings();
  14074. });
  14075. ehDownloadBox.appendChild(ehDownloadSetting);
  14076.  
  14077. var ehDownloadFeedback = document.createElement('div');
  14078. ehDownloadFeedback.className = 'g2';
  14079. ehDownloadFeedback.innerHTML = ehDownloadArrow + ' <a href="https://github.com/ccloli/E-Hentai-Downloader/issues" target="_blank">Feedback</a>';
  14080. ehDownloadBox.appendChild(ehDownloadFeedback);
  14081.  
  14082. document.body.insertBefore(ehDownloadBox, document.getElementById('asm') || document.querySelector('.gm').nextElementSibling);
  14083.  
  14084. var ehDownloadDialog = document.createElement('div');
  14085. ehDownloadDialog.className = 'ehD-dialog';
  14086. document.body.appendChild(ehDownloadDialog);
  14087.  
  14088. var ehDownloadStatus = document.createElement('div');
  14089. ehDownloadStatus.className = 'ehD-status';
  14090. ehDownloadStatus.addEventListener('click', function(event){
  14091. event.preventDefault();
  14092. ehDownloadDialog.classList.toggle('hidden');
  14093. });
  14094.  
  14095. var ehDownloadPauseBtn = document.createElement('button');
  14096. ehDownloadPauseBtn.className = 'ehD-pause';
  14097. ehDownloadPauseBtn.textContent ='Pause';
  14098. ehDownloadPauseBtn.addEventListener('click', function(event){
  14099. if (!isPausing) {
  14100. isPausing = true;
  14101. ehDownloadPauseBtn.textContent = 'Resume';
  14102. if (setting['force-pause']) {
  14103. // waiting Tampermonkey for transfering string to ArrayBuffer, it may stuck for a second
  14104. setTimeout(function(){
  14105. for (var i = 0; i < fetchThread.length; i++) {
  14106. if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort();
  14107.  
  14108. if (imageData[i] === 'Fetching' && retryCount[i] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {
  14109. var elem = progressTable.querySelector('tr[data-index="' + i + '"] .ehD-pt-status-text');
  14110. if (elem) elem.textContent = 'Force Paused';
  14111.  
  14112. elem = progressTable.querySelector('tr[data-index="' + i + '"] .ehD-pt-progress-text');
  14113. if (elem) elem.textContent = '';
  14114.  
  14115. imageData[i] = null;
  14116. //fetchCount = 0; // fixed for async
  14117. fetchCount--;
  14118.  
  14119. updateTotalStatus();
  14120. }
  14121. }
  14122. }, 0);
  14123. }
  14124.  
  14125. if (emptyAudio) {
  14126. emptyAudio.pause();
  14127. }
  14128. }
  14129. else {
  14130. isPausing = false;
  14131. ehDownloadPauseBtn.textContent = setting['force-pause'] ? 'Pause (Downloading images will be aborted)' : 'Pause (Downloading images will keep downloading)';
  14132.  
  14133. requestDownload();
  14134. }
  14135. });
  14136.  
  14137. window.addEventListener('focus', function(){
  14138. if (setting['status-in-title'] === 'blur') {
  14139. if (!needTitleStatus) return;
  14140. document.title = pretitle;
  14141. needTitleStatus = false;
  14142. }
  14143. });
  14144.  
  14145. window.addEventListener('blur', function(){
  14146. if (isDownloading && setting['status-in-title'] === 'blur') {
  14147. needTitleStatus = true;
  14148. document.title = '[' + (isPausing ? '❙❙' : downloadedCount < totalCount ? '↓ ' + downloadedCount + '/' + totalCount : totalCount === 0 ? '↓' : '√' ) + '] ' + pretitle;
  14149. }
  14150. });
  14151.  
  14152. var forceDownloadTips = document.createElement('div');
  14153. forceDownloadTips.className = 'ehD-force-download-tips';
  14154. 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.';
  14155. forceDownloadTips.getElementsByTagName('a')[0].addEventListener('click', function(event){
  14156. // fixed permission denied on GreaseMonkey
  14157. event.preventDefault();
  14158. saveDownloaded(true);
  14159. });
  14160.  
  14161. var closeTips = document.createElement('div');
  14162. closeTips.className = 'ehD-close-tips';
  14163. 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.';
  14164.  
  14165. unsafeWindow.getzip = window.getzip = function(){
  14166. saveDownloaded(true);
  14167. };
  14168.  
  14169. initSetting();
  14170.  
  14171. window.addEventListener('storage', showImageLimits);
  14172.  
  14173. window.onbeforeunload = unsafeWindow.onbeforeunload = function(){
  14174. function clearRubbish(){
  14175. for (var i = 0; i < fetchThread.length; i++) {
  14176. if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort();
  14177. }
  14178. ehDownloadFS.removeFile(unsafeWindow.gid + '.zip');
  14179. }
  14180. if (isDownloading || isPausing || isSaving) {
  14181. document.body.appendChild(closeTips);
  14182.  
  14183. setTimeout(function(){
  14184. document.body.removeChild(closeTips);
  14185. }, 100);
  14186.  
  14187. return 'E-Hentai Downloader is still running, please don\'t close this tab until it finished downloading.';
  14188. }
  14189. clearRubbish();
  14190. };