Newer
Older
meshcode-jp / docs / apidocs / jquery / jszip / dist / jszip.js
@haya4 haya4 on 12 May 2022 358 KB docs
  1. /*!
  2.  
  3. JSZip v3.7.1 - A JavaScript class for generating and reading zip files
  4. <http://stuartk.com/jszip>
  5.  
  6. (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
  7. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
  8.  
  9. JSZip uses the library pako released under the MIT license :
  10. https://github.com/nodeca/pako/blob/master/LICENSE
  11. */
  12.  
  13. (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){
  14. 'use strict';
  15. var utils = require('./utils');
  16. var support = require('./support');
  17. // private property
  18. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  19.  
  20.  
  21. // public method for encoding
  22. exports.encode = function(input) {
  23. var output = [];
  24. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  25. var i = 0, len = input.length, remainingBytes = len;
  26.  
  27. var isArray = utils.getTypeOf(input) !== "string";
  28. while (i < input.length) {
  29. remainingBytes = len - i;
  30.  
  31. if (!isArray) {
  32. chr1 = input.charCodeAt(i++);
  33. chr2 = i < len ? input.charCodeAt(i++) : 0;
  34. chr3 = i < len ? input.charCodeAt(i++) : 0;
  35. } else {
  36. chr1 = input[i++];
  37. chr2 = i < len ? input[i++] : 0;
  38. chr3 = i < len ? input[i++] : 0;
  39. }
  40.  
  41. enc1 = chr1 >> 2;
  42. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  43. enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;
  44. enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;
  45.  
  46. output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));
  47.  
  48. }
  49.  
  50. return output.join("");
  51. };
  52.  
  53. // public method for decoding
  54. exports.decode = function(input) {
  55. var chr1, chr2, chr3;
  56. var enc1, enc2, enc3, enc4;
  57. var i = 0, resultIndex = 0;
  58.  
  59. var dataUrlPrefix = "data:";
  60.  
  61. if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {
  62. // This is a common error: people give a data url
  63. // (data:image/png;base64,iVBOR...) with a {base64: true} and
  64. // wonders why things don't work.
  65. // We can detect that the string input looks like a data url but we
  66. // *can't* be sure it is one: removing everything up to the comma would
  67. // be too dangerous.
  68. throw new Error("Invalid base64 input, it looks like a data url.");
  69. }
  70.  
  71. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  72.  
  73. var totalLength = input.length * 3 / 4;
  74. if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {
  75. totalLength--;
  76. }
  77. if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {
  78. totalLength--;
  79. }
  80. if (totalLength % 1 !== 0) {
  81. // totalLength is not an integer, the length does not match a valid
  82. // base64 content. That can happen if:
  83. // - the input is not a base64 content
  84. // - the input is *almost* a base64 content, with a extra chars at the
  85. // beginning or at the end
  86. // - the input uses a base64 variant (base64url for example)
  87. throw new Error("Invalid base64 input, bad content length.");
  88. }
  89. var output;
  90. if (support.uint8array) {
  91. output = new Uint8Array(totalLength|0);
  92. } else {
  93. output = new Array(totalLength|0);
  94. }
  95.  
  96. while (i < input.length) {
  97.  
  98. enc1 = _keyStr.indexOf(input.charAt(i++));
  99. enc2 = _keyStr.indexOf(input.charAt(i++));
  100. enc3 = _keyStr.indexOf(input.charAt(i++));
  101. enc4 = _keyStr.indexOf(input.charAt(i++));
  102.  
  103. chr1 = (enc1 << 2) | (enc2 >> 4);
  104. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  105. chr3 = ((enc3 & 3) << 6) | enc4;
  106.  
  107. output[resultIndex++] = chr1;
  108.  
  109. if (enc3 !== 64) {
  110. output[resultIndex++] = chr2;
  111. }
  112. if (enc4 !== 64) {
  113. output[resultIndex++] = chr3;
  114. }
  115.  
  116. }
  117.  
  118. return output;
  119. };
  120.  
  121. },{"./support":30,"./utils":32}],2:[function(require,module,exports){
  122. 'use strict';
  123.  
  124. var external = require("./external");
  125. var DataWorker = require('./stream/DataWorker');
  126. var Crc32Probe = require('./stream/Crc32Probe');
  127. var DataLengthProbe = require('./stream/DataLengthProbe');
  128.  
  129. /**
  130. * Represent a compressed object, with everything needed to decompress it.
  131. * @constructor
  132. * @param {number} compressedSize the size of the data compressed.
  133. * @param {number} uncompressedSize the size of the data after decompression.
  134. * @param {number} crc32 the crc32 of the decompressed file.
  135. * @param {object} compression the type of compression, see lib/compressions.js.
  136. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
  137. */
  138. function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
  139. this.compressedSize = compressedSize;
  140. this.uncompressedSize = uncompressedSize;
  141. this.crc32 = crc32;
  142. this.compression = compression;
  143. this.compressedContent = data;
  144. }
  145.  
  146. CompressedObject.prototype = {
  147. /**
  148. * Create a worker to get the uncompressed content.
  149. * @return {GenericWorker} the worker.
  150. */
  151. getContentWorker: function () {
  152. var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
  153. .pipe(this.compression.uncompressWorker())
  154. .pipe(new DataLengthProbe("data_length"));
  155.  
  156. var that = this;
  157. worker.on("end", function () {
  158. if (this.streamInfo['data_length'] !== that.uncompressedSize) {
  159. throw new Error("Bug : uncompressed data size mismatch");
  160. }
  161. });
  162. return worker;
  163. },
  164. /**
  165. * Create a worker to get the compressed content.
  166. * @return {GenericWorker} the worker.
  167. */
  168. getCompressedWorker: function () {
  169. return new DataWorker(external.Promise.resolve(this.compressedContent))
  170. .withStreamInfo("compressedSize", this.compressedSize)
  171. .withStreamInfo("uncompressedSize", this.uncompressedSize)
  172. .withStreamInfo("crc32", this.crc32)
  173. .withStreamInfo("compression", this.compression)
  174. ;
  175. }
  176. };
  177.  
  178. /**
  179. * Chain the given worker with other workers to compress the content with the
  180. * given compression.
  181. * @param {GenericWorker} uncompressedWorker the worker to pipe.
  182. * @param {Object} compression the compression object.
  183. * @param {Object} compressionOptions the options to use when compressing.
  184. * @return {GenericWorker} the new worker compressing the content.
  185. */
  186. CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
  187. return uncompressedWorker
  188. .pipe(new Crc32Probe())
  189. .pipe(new DataLengthProbe("uncompressedSize"))
  190. .pipe(compression.compressWorker(compressionOptions))
  191. .pipe(new DataLengthProbe("compressedSize"))
  192. .withStreamInfo("compression", compression);
  193. };
  194.  
  195. module.exports = CompressedObject;
  196.  
  197. },{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){
  198. 'use strict';
  199.  
  200. var GenericWorker = require("./stream/GenericWorker");
  201.  
  202. exports.STORE = {
  203. magic: "\x00\x00",
  204. compressWorker : function (compressionOptions) {
  205. return new GenericWorker("STORE compression");
  206. },
  207. uncompressWorker : function () {
  208. return new GenericWorker("STORE decompression");
  209. }
  210. };
  211. exports.DEFLATE = require('./flate');
  212.  
  213. },{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){
  214. 'use strict';
  215.  
  216. var utils = require('./utils');
  217.  
  218. /**
  219. * The following functions come from pako, from pako/lib/zlib/crc32.js
  220. * released under the MIT license, see pako https://github.com/nodeca/pako/
  221. */
  222.  
  223. // Use ordinary array, since untyped makes no boost here
  224. function makeTable() {
  225. var c, table = [];
  226.  
  227. for(var n =0; n < 256; n++){
  228. c = n;
  229. for(var k =0; k < 8; k++){
  230. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  231. }
  232. table[n] = c;
  233. }
  234.  
  235. return table;
  236. }
  237.  
  238. // Create table on load. Just 255 signed longs. Not a problem.
  239. var crcTable = makeTable();
  240.  
  241.  
  242. function crc32(crc, buf, len, pos) {
  243. var t = crcTable, end = pos + len;
  244.  
  245. crc = crc ^ (-1);
  246.  
  247. for (var i = pos; i < end; i++ ) {
  248. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  249. }
  250.  
  251. return (crc ^ (-1)); // >>> 0;
  252. }
  253.  
  254. // That's all for the pako functions.
  255.  
  256. /**
  257. * Compute the crc32 of a string.
  258. * This is almost the same as the function crc32, but for strings. Using the
  259. * same function for the two use cases leads to horrible performances.
  260. * @param {Number} crc the starting value of the crc.
  261. * @param {String} str the string to use.
  262. * @param {Number} len the length of the string.
  263. * @param {Number} pos the starting position for the crc32 computation.
  264. * @return {Number} the computed crc32.
  265. */
  266. function crc32str(crc, str, len, pos) {
  267. var t = crcTable, end = pos + len;
  268.  
  269. crc = crc ^ (-1);
  270.  
  271. for (var i = pos; i < end; i++ ) {
  272. crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
  273. }
  274.  
  275. return (crc ^ (-1)); // >>> 0;
  276. }
  277.  
  278. module.exports = function crc32wrapper(input, crc) {
  279. if (typeof input === "undefined" || !input.length) {
  280. return 0;
  281. }
  282.  
  283. var isArray = utils.getTypeOf(input) !== "string";
  284.  
  285. if(isArray) {
  286. return crc32(crc|0, input, input.length, 0);
  287. } else {
  288. return crc32str(crc|0, input, input.length, 0);
  289. }
  290. };
  291.  
  292. },{"./utils":32}],5:[function(require,module,exports){
  293. 'use strict';
  294. exports.base64 = false;
  295. exports.binary = false;
  296. exports.dir = false;
  297. exports.createFolders = true;
  298. exports.date = null;
  299. exports.compression = null;
  300. exports.compressionOptions = null;
  301. exports.comment = null;
  302. exports.unixPermissions = null;
  303. exports.dosPermissions = null;
  304.  
  305. },{}],6:[function(require,module,exports){
  306. /* global Promise */
  307. 'use strict';
  308.  
  309. // load the global object first:
  310. // - it should be better integrated in the system (unhandledRejection in node)
  311. // - the environment may have a custom Promise implementation (see zone.js)
  312. var ES6Promise = null;
  313. if (typeof Promise !== "undefined") {
  314. ES6Promise = Promise;
  315. } else {
  316. ES6Promise = require("lie");
  317. }
  318.  
  319. /**
  320. * Let the user use/change some implementations.
  321. */
  322. module.exports = {
  323. Promise: ES6Promise
  324. };
  325.  
  326. },{"lie":37}],7:[function(require,module,exports){
  327. 'use strict';
  328. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  329.  
  330. var pako = require("pako");
  331. var utils = require("./utils");
  332. var GenericWorker = require("./stream/GenericWorker");
  333.  
  334. var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
  335.  
  336. exports.magic = "\x08\x00";
  337.  
  338. /**
  339. * Create a worker that uses pako to inflate/deflate.
  340. * @constructor
  341. * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
  342. * @param {Object} options the options to use when (de)compressing.
  343. */
  344. function FlateWorker(action, options) {
  345. GenericWorker.call(this, "FlateWorker/" + action);
  346.  
  347. this._pako = null;
  348. this._pakoAction = action;
  349. this._pakoOptions = options;
  350. // the `meta` object from the last chunk received
  351. // this allow this worker to pass around metadata
  352. this.meta = {};
  353. }
  354.  
  355. utils.inherits(FlateWorker, GenericWorker);
  356.  
  357. /**
  358. * @see GenericWorker.processChunk
  359. */
  360. FlateWorker.prototype.processChunk = function (chunk) {
  361. this.meta = chunk.meta;
  362. if (this._pako === null) {
  363. this._createPako();
  364. }
  365. this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
  366. };
  367.  
  368. /**
  369. * @see GenericWorker.flush
  370. */
  371. FlateWorker.prototype.flush = function () {
  372. GenericWorker.prototype.flush.call(this);
  373. if (this._pako === null) {
  374. this._createPako();
  375. }
  376. this._pako.push([], true);
  377. };
  378. /**
  379. * @see GenericWorker.cleanUp
  380. */
  381. FlateWorker.prototype.cleanUp = function () {
  382. GenericWorker.prototype.cleanUp.call(this);
  383. this._pako = null;
  384. };
  385.  
  386. /**
  387. * Create the _pako object.
  388. * TODO: lazy-loading this object isn't the best solution but it's the
  389. * quickest. The best solution is to lazy-load the worker list. See also the
  390. * issue #446.
  391. */
  392. FlateWorker.prototype._createPako = function () {
  393. this._pako = new pako[this._pakoAction]({
  394. raw: true,
  395. level: this._pakoOptions.level || -1 // default compression
  396. });
  397. var self = this;
  398. this._pako.onData = function(data) {
  399. self.push({
  400. data : data,
  401. meta : self.meta
  402. });
  403. };
  404. };
  405.  
  406. exports.compressWorker = function (compressionOptions) {
  407. return new FlateWorker("Deflate", compressionOptions);
  408. };
  409. exports.uncompressWorker = function () {
  410. return new FlateWorker("Inflate", {});
  411. };
  412.  
  413. },{"./stream/GenericWorker":28,"./utils":32,"pako":38}],8:[function(require,module,exports){
  414. 'use strict';
  415.  
  416. var utils = require('../utils');
  417. var GenericWorker = require('../stream/GenericWorker');
  418. var utf8 = require('../utf8');
  419. var crc32 = require('../crc32');
  420. var signature = require('../signature');
  421.  
  422. /**
  423. * Transform an integer into a string in hexadecimal.
  424. * @private
  425. * @param {number} dec the number to convert.
  426. * @param {number} bytes the number of bytes to generate.
  427. * @returns {string} the result.
  428. */
  429. var decToHex = function(dec, bytes) {
  430. var hex = "", i;
  431. for (i = 0; i < bytes; i++) {
  432. hex += String.fromCharCode(dec & 0xff);
  433. dec = dec >>> 8;
  434. }
  435. return hex;
  436. };
  437.  
  438. /**
  439. * Generate the UNIX part of the external file attributes.
  440. * @param {Object} unixPermissions the unix permissions or null.
  441. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  442. * @return {Number} a 32 bit integer.
  443. *
  444. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  445. *
  446. * TTTTsstrwxrwxrwx0000000000ADVSHR
  447. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  448. * ^^^_________________________ setuid, setgid, sticky
  449. * ^^^^^^^^^________________ permissions
  450. * ^^^^^^^^^^______ not used ?
  451. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  452. */
  453. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  454.  
  455. var result = unixPermissions;
  456. if (!unixPermissions) {
  457. // I can't use octal values in strict mode, hence the hexa.
  458. // 040775 => 0x41fd
  459. // 0100664 => 0x81b4
  460. result = isDir ? 0x41fd : 0x81b4;
  461. }
  462. return (result & 0xFFFF) << 16;
  463. };
  464.  
  465. /**
  466. * Generate the DOS part of the external file attributes.
  467. * @param {Object} dosPermissions the dos permissions or null.
  468. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  469. * @return {Number} a 32 bit integer.
  470. *
  471. * Bit 0 Read-Only
  472. * Bit 1 Hidden
  473. * Bit 2 System
  474. * Bit 3 Volume Label
  475. * Bit 4 Directory
  476. * Bit 5 Archive
  477. */
  478. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  479.  
  480. // the dir flag is already set for compatibility
  481. return (dosPermissions || 0) & 0x3F;
  482. };
  483.  
  484. /**
  485. * Generate the various parts used in the construction of the final zip file.
  486. * @param {Object} streamInfo the hash with information about the compressed file.
  487. * @param {Boolean} streamedContent is the content streamed ?
  488. * @param {Boolean} streamingEnded is the stream finished ?
  489. * @param {number} offset the current offset from the start of the zip file.
  490. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  491. * @param {Function} encodeFileName the function to encode the file name / comment.
  492. * @return {Object} the zip parts.
  493. */
  494. var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
  495. var file = streamInfo['file'],
  496. compression = streamInfo['compression'],
  497. useCustomEncoding = encodeFileName !== utf8.utf8encode,
  498. encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
  499. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  500. comment = file.comment,
  501. encodedComment = utils.transformTo("string", encodeFileName(comment)),
  502. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  503. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  504. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  505. dosTime,
  506. dosDate,
  507. extraFields = "",
  508. unicodePathExtraField = "",
  509. unicodeCommentExtraField = "",
  510. dir = file.dir,
  511. date = file.date;
  512.  
  513.  
  514. var dataInfo = {
  515. crc32 : 0,
  516. compressedSize : 0,
  517. uncompressedSize : 0
  518. };
  519.  
  520. // if the content is streamed, the sizes/crc32 are only available AFTER
  521. // the end of the stream.
  522. if (!streamedContent || streamingEnded) {
  523. dataInfo.crc32 = streamInfo['crc32'];
  524. dataInfo.compressedSize = streamInfo['compressedSize'];
  525. dataInfo.uncompressedSize = streamInfo['uncompressedSize'];
  526. }
  527.  
  528. var bitflag = 0;
  529. if (streamedContent) {
  530. // Bit 3: the sizes/crc32 are set to zero in the local header.
  531. // The correct values are put in the data descriptor immediately
  532. // following the compressed data.
  533. bitflag |= 0x0008;
  534. }
  535. if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
  536. // Bit 11: Language encoding flag (EFS).
  537. bitflag |= 0x0800;
  538. }
  539.  
  540.  
  541. var extFileAttr = 0;
  542. var versionMadeBy = 0;
  543. if (dir) {
  544. // dos or unix, we set the dos dir flag
  545. extFileAttr |= 0x00010;
  546. }
  547. if(platform === "UNIX") {
  548. versionMadeBy = 0x031E; // UNIX, version 3.0
  549. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  550. } else { // DOS or other, fallback to DOS
  551. versionMadeBy = 0x0014; // DOS, version 2.0
  552. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  553. }
  554.  
  555. // date
  556. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  557. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  558. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  559.  
  560. dosTime = date.getUTCHours();
  561. dosTime = dosTime << 6;
  562. dosTime = dosTime | date.getUTCMinutes();
  563. dosTime = dosTime << 5;
  564. dosTime = dosTime | date.getUTCSeconds() / 2;
  565.  
  566. dosDate = date.getUTCFullYear() - 1980;
  567. dosDate = dosDate << 4;
  568. dosDate = dosDate | (date.getUTCMonth() + 1);
  569. dosDate = dosDate << 5;
  570. dosDate = dosDate | date.getUTCDate();
  571.  
  572. if (useUTF8ForFileName) {
  573. // set the unicode path extra field. unzip needs at least one extra
  574. // field to correctly handle unicode path, so using the path is as good
  575. // as any other information. This could improve the situation with
  576. // other archive managers too.
  577. // This field is usually used without the utf8 flag, with a non
  578. // unicode path in the header (winrar, winzip). This helps (a bit)
  579. // with the messy Windows' default compressed folders feature but
  580. // breaks on p7zip which doesn't seek the unicode path extra field.
  581. // So for now, UTF-8 everywhere !
  582. unicodePathExtraField =
  583. // Version
  584. decToHex(1, 1) +
  585. // NameCRC32
  586. decToHex(crc32(encodedFileName), 4) +
  587. // UnicodeName
  588. utfEncodedFileName;
  589.  
  590. extraFields +=
  591. // Info-ZIP Unicode Path Extra Field
  592. "\x75\x70" +
  593. // size
  594. decToHex(unicodePathExtraField.length, 2) +
  595. // content
  596. unicodePathExtraField;
  597. }
  598.  
  599. if(useUTF8ForComment) {
  600.  
  601. unicodeCommentExtraField =
  602. // Version
  603. decToHex(1, 1) +
  604. // CommentCRC32
  605. decToHex(crc32(encodedComment), 4) +
  606. // UnicodeName
  607. utfEncodedComment;
  608.  
  609. extraFields +=
  610. // Info-ZIP Unicode Path Extra Field
  611. "\x75\x63" +
  612. // size
  613. decToHex(unicodeCommentExtraField.length, 2) +
  614. // content
  615. unicodeCommentExtraField;
  616. }
  617.  
  618. var header = "";
  619.  
  620. // version needed to extract
  621. header += "\x0A\x00";
  622. // general purpose bit flag
  623. header += decToHex(bitflag, 2);
  624. // compression method
  625. header += compression.magic;
  626. // last mod file time
  627. header += decToHex(dosTime, 2);
  628. // last mod file date
  629. header += decToHex(dosDate, 2);
  630. // crc-32
  631. header += decToHex(dataInfo.crc32, 4);
  632. // compressed size
  633. header += decToHex(dataInfo.compressedSize, 4);
  634. // uncompressed size
  635. header += decToHex(dataInfo.uncompressedSize, 4);
  636. // file name length
  637. header += decToHex(encodedFileName.length, 2);
  638. // extra field length
  639. header += decToHex(extraFields.length, 2);
  640.  
  641.  
  642. var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  643.  
  644. var dirRecord = signature.CENTRAL_FILE_HEADER +
  645. // version made by (00: DOS)
  646. decToHex(versionMadeBy, 2) +
  647. // file header (common to file and central directory)
  648. header +
  649. // file comment length
  650. decToHex(encodedComment.length, 2) +
  651. // disk number start
  652. "\x00\x00" +
  653. // internal file attributes TODO
  654. "\x00\x00" +
  655. // external file attributes
  656. decToHex(extFileAttr, 4) +
  657. // relative offset of local header
  658. decToHex(offset, 4) +
  659. // file name
  660. encodedFileName +
  661. // extra field
  662. extraFields +
  663. // file comment
  664. encodedComment;
  665.  
  666. return {
  667. fileRecord: fileRecord,
  668. dirRecord: dirRecord
  669. };
  670. };
  671.  
  672. /**
  673. * Generate the EOCD record.
  674. * @param {Number} entriesCount the number of entries in the zip file.
  675. * @param {Number} centralDirLength the length (in bytes) of the central dir.
  676. * @param {Number} localDirLength the length (in bytes) of the local dir.
  677. * @param {String} comment the zip file comment as a binary string.
  678. * @param {Function} encodeFileName the function to encode the comment.
  679. * @return {String} the EOCD record.
  680. */
  681. var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
  682. var dirEnd = "";
  683. var encodedComment = utils.transformTo("string", encodeFileName(comment));
  684.  
  685. // end of central dir signature
  686. dirEnd = signature.CENTRAL_DIRECTORY_END +
  687. // number of this disk
  688. "\x00\x00" +
  689. // number of the disk with the start of the central directory
  690. "\x00\x00" +
  691. // total number of entries in the central directory on this disk
  692. decToHex(entriesCount, 2) +
  693. // total number of entries in the central directory
  694. decToHex(entriesCount, 2) +
  695. // size of the central directory 4 bytes
  696. decToHex(centralDirLength, 4) +
  697. // offset of start of central directory with respect to the starting disk number
  698. decToHex(localDirLength, 4) +
  699. // .ZIP file comment length
  700. decToHex(encodedComment.length, 2) +
  701. // .ZIP file comment
  702. encodedComment;
  703.  
  704. return dirEnd;
  705. };
  706.  
  707. /**
  708. * Generate data descriptors for a file entry.
  709. * @param {Object} streamInfo the hash generated by a worker, containing information
  710. * on the file entry.
  711. * @return {String} the data descriptors.
  712. */
  713. var generateDataDescriptors = function (streamInfo) {
  714. var descriptor = "";
  715. descriptor = signature.DATA_DESCRIPTOR +
  716. // crc-32 4 bytes
  717. decToHex(streamInfo['crc32'], 4) +
  718. // compressed size 4 bytes
  719. decToHex(streamInfo['compressedSize'], 4) +
  720. // uncompressed size 4 bytes
  721. decToHex(streamInfo['uncompressedSize'], 4);
  722.  
  723. return descriptor;
  724. };
  725.  
  726.  
  727. /**
  728. * A worker to concatenate other workers to create a zip file.
  729. * @param {Boolean} streamFiles `true` to stream the content of the files,
  730. * `false` to accumulate it.
  731. * @param {String} comment the comment to use.
  732. * @param {String} platform the platform to use, "UNIX" or "DOS".
  733. * @param {Function} encodeFileName the function to encode file names and comments.
  734. */
  735. function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
  736. GenericWorker.call(this, "ZipFileWorker");
  737. // The number of bytes written so far. This doesn't count accumulated chunks.
  738. this.bytesWritten = 0;
  739. // The comment of the zip file
  740. this.zipComment = comment;
  741. // The platform "generating" the zip file.
  742. this.zipPlatform = platform;
  743. // the function to encode file names and comments.
  744. this.encodeFileName = encodeFileName;
  745. // Should we stream the content of the files ?
  746. this.streamFiles = streamFiles;
  747. // If `streamFiles` is false, we will need to accumulate the content of the
  748. // files to calculate sizes / crc32 (and write them *before* the content).
  749. // This boolean indicates if we are accumulating chunks (it will change a lot
  750. // during the lifetime of this worker).
  751. this.accumulate = false;
  752. // The buffer receiving chunks when accumulating content.
  753. this.contentBuffer = [];
  754. // The list of generated directory records.
  755. this.dirRecords = [];
  756. // The offset (in bytes) from the beginning of the zip file for the current source.
  757. this.currentSourceOffset = 0;
  758. // The total number of entries in this zip file.
  759. this.entriesCount = 0;
  760. // the name of the file currently being added, null when handling the end of the zip file.
  761. // Used for the emitted metadata.
  762. this.currentFile = null;
  763.  
  764.  
  765.  
  766. this._sources = [];
  767. }
  768. utils.inherits(ZipFileWorker, GenericWorker);
  769.  
  770. /**
  771. * @see GenericWorker.push
  772. */
  773. ZipFileWorker.prototype.push = function (chunk) {
  774.  
  775. var currentFilePercent = chunk.meta.percent || 0;
  776. var entriesCount = this.entriesCount;
  777. var remainingFiles = this._sources.length;
  778.  
  779. if(this.accumulate) {
  780. this.contentBuffer.push(chunk);
  781. } else {
  782. this.bytesWritten += chunk.data.length;
  783.  
  784. GenericWorker.prototype.push.call(this, {
  785. data : chunk.data,
  786. meta : {
  787. currentFile : this.currentFile,
  788. percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
  789. }
  790. });
  791. }
  792. };
  793.  
  794. /**
  795. * The worker started a new source (an other worker).
  796. * @param {Object} streamInfo the streamInfo object from the new source.
  797. */
  798. ZipFileWorker.prototype.openedSource = function (streamInfo) {
  799. this.currentSourceOffset = this.bytesWritten;
  800. this.currentFile = streamInfo['file'].name;
  801.  
  802. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  803.  
  804. // don't stream folders (because they don't have any content)
  805. if(streamedContent) {
  806. var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  807. this.push({
  808. data : record.fileRecord,
  809. meta : {percent:0}
  810. });
  811. } else {
  812. // we need to wait for the whole file before pushing anything
  813. this.accumulate = true;
  814. }
  815. };
  816.  
  817. /**
  818. * The worker finished a source (an other worker).
  819. * @param {Object} streamInfo the streamInfo object from the finished source.
  820. */
  821. ZipFileWorker.prototype.closedSource = function (streamInfo) {
  822. this.accumulate = false;
  823. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  824. var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  825.  
  826. this.dirRecords.push(record.dirRecord);
  827. if(streamedContent) {
  828. // after the streamed file, we put data descriptors
  829. this.push({
  830. data : generateDataDescriptors(streamInfo),
  831. meta : {percent:100}
  832. });
  833. } else {
  834. // the content wasn't streamed, we need to push everything now
  835. // first the file record, then the content
  836. this.push({
  837. data : record.fileRecord,
  838. meta : {percent:0}
  839. });
  840. while(this.contentBuffer.length) {
  841. this.push(this.contentBuffer.shift());
  842. }
  843. }
  844. this.currentFile = null;
  845. };
  846.  
  847. /**
  848. * @see GenericWorker.flush
  849. */
  850. ZipFileWorker.prototype.flush = function () {
  851.  
  852. var localDirLength = this.bytesWritten;
  853. for(var i = 0; i < this.dirRecords.length; i++) {
  854. this.push({
  855. data : this.dirRecords[i],
  856. meta : {percent:100}
  857. });
  858. }
  859. var centralDirLength = this.bytesWritten - localDirLength;
  860.  
  861. var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
  862.  
  863. this.push({
  864. data : dirEnd,
  865. meta : {percent:100}
  866. });
  867. };
  868.  
  869. /**
  870. * Prepare the next source to be read.
  871. */
  872. ZipFileWorker.prototype.prepareNextSource = function () {
  873. this.previous = this._sources.shift();
  874. this.openedSource(this.previous.streamInfo);
  875. if (this.isPaused) {
  876. this.previous.pause();
  877. } else {
  878. this.previous.resume();
  879. }
  880. };
  881.  
  882. /**
  883. * @see GenericWorker.registerPrevious
  884. */
  885. ZipFileWorker.prototype.registerPrevious = function (previous) {
  886. this._sources.push(previous);
  887. var self = this;
  888.  
  889. previous.on('data', function (chunk) {
  890. self.processChunk(chunk);
  891. });
  892. previous.on('end', function () {
  893. self.closedSource(self.previous.streamInfo);
  894. if(self._sources.length) {
  895. self.prepareNextSource();
  896. } else {
  897. self.end();
  898. }
  899. });
  900. previous.on('error', function (e) {
  901. self.error(e);
  902. });
  903. return this;
  904. };
  905.  
  906. /**
  907. * @see GenericWorker.resume
  908. */
  909. ZipFileWorker.prototype.resume = function () {
  910. if(!GenericWorker.prototype.resume.call(this)) {
  911. return false;
  912. }
  913.  
  914. if (!this.previous && this._sources.length) {
  915. this.prepareNextSource();
  916. return true;
  917. }
  918. if (!this.previous && !this._sources.length && !this.generatedError) {
  919. this.end();
  920. return true;
  921. }
  922. };
  923.  
  924. /**
  925. * @see GenericWorker.error
  926. */
  927. ZipFileWorker.prototype.error = function (e) {
  928. var sources = this._sources;
  929. if(!GenericWorker.prototype.error.call(this, e)) {
  930. return false;
  931. }
  932. for(var i = 0; i < sources.length; i++) {
  933. try {
  934. sources[i].error(e);
  935. } catch(e) {
  936. // the `error` exploded, nothing to do
  937. }
  938. }
  939. return true;
  940. };
  941.  
  942. /**
  943. * @see GenericWorker.lock
  944. */
  945. ZipFileWorker.prototype.lock = function () {
  946. GenericWorker.prototype.lock.call(this);
  947. var sources = this._sources;
  948. for(var i = 0; i < sources.length; i++) {
  949. sources[i].lock();
  950. }
  951. };
  952.  
  953. module.exports = ZipFileWorker;
  954.  
  955. },{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){
  956. 'use strict';
  957.  
  958. var compressions = require('../compressions');
  959. var ZipFileWorker = require('./ZipFileWorker');
  960.  
  961. /**
  962. * Find the compression to use.
  963. * @param {String} fileCompression the compression defined at the file level, if any.
  964. * @param {String} zipCompression the compression defined at the load() level.
  965. * @return {Object} the compression object to use.
  966. */
  967. var getCompression = function (fileCompression, zipCompression) {
  968.  
  969. var compressionName = fileCompression || zipCompression;
  970. var compression = compressions[compressionName];
  971. if (!compression) {
  972. throw new Error(compressionName + " is not a valid compression method !");
  973. }
  974. return compression;
  975. };
  976.  
  977. /**
  978. * Create a worker to generate a zip file.
  979. * @param {JSZip} zip the JSZip instance at the right root level.
  980. * @param {Object} options to generate the zip file.
  981. * @param {String} comment the comment to use.
  982. */
  983. exports.generateWorker = function (zip, options, comment) {
  984.  
  985. var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
  986. var entriesCount = 0;
  987. try {
  988.  
  989. zip.forEach(function (relativePath, file) {
  990. entriesCount++;
  991. var compression = getCompression(file.options.compression, options.compression);
  992. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  993. var dir = file.dir, date = file.date;
  994.  
  995. file._compressWorker(compression, compressionOptions)
  996. .withStreamInfo("file", {
  997. name : relativePath,
  998. dir : dir,
  999. date : date,
  1000. comment : file.comment || "",
  1001. unixPermissions : file.unixPermissions,
  1002. dosPermissions : file.dosPermissions
  1003. })
  1004. .pipe(zipFileWorker);
  1005. });
  1006. zipFileWorker.entriesCount = entriesCount;
  1007. } catch (e) {
  1008. zipFileWorker.error(e);
  1009. }
  1010.  
  1011. return zipFileWorker;
  1012. };
  1013.  
  1014. },{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){
  1015. 'use strict';
  1016.  
  1017. /**
  1018. * Representation a of zip file in js
  1019. * @constructor
  1020. */
  1021. function JSZip() {
  1022. // if this constructor is used without `new`, it adds `new` before itself:
  1023. if(!(this instanceof JSZip)) {
  1024. return new JSZip();
  1025. }
  1026.  
  1027. if(arguments.length) {
  1028. throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
  1029. }
  1030.  
  1031. // object containing the files :
  1032. // {
  1033. // "folder/" : {...},
  1034. // "folder/data.txt" : {...}
  1035. // }
  1036. // NOTE: we use a null prototype because we do not
  1037. // want filenames like "toString" coming from a zip file
  1038. // to overwrite methods and attributes in a normal Object.
  1039. this.files = Object.create(null);
  1040.  
  1041. this.comment = null;
  1042.  
  1043. // Where we are in the hierarchy
  1044. this.root = "";
  1045. this.clone = function() {
  1046. var newObj = new JSZip();
  1047. for (var i in this) {
  1048. if (typeof this[i] !== "function") {
  1049. newObj[i] = this[i];
  1050. }
  1051. }
  1052. return newObj;
  1053. };
  1054. }
  1055. JSZip.prototype = require('./object');
  1056. JSZip.prototype.loadAsync = require('./load');
  1057. JSZip.support = require('./support');
  1058. JSZip.defaults = require('./defaults');
  1059.  
  1060. // TODO find a better way to handle this version,
  1061. // a require('package.json').version doesn't work with webpack, see #327
  1062. JSZip.version = "3.7.1";
  1063.  
  1064. JSZip.loadAsync = function (content, options) {
  1065. return new JSZip().loadAsync(content, options);
  1066. };
  1067.  
  1068. JSZip.external = require("./external");
  1069. module.exports = JSZip;
  1070.  
  1071. },{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){
  1072. 'use strict';
  1073. var utils = require('./utils');
  1074. var external = require("./external");
  1075. var utf8 = require('./utf8');
  1076. var ZipEntries = require('./zipEntries');
  1077. var Crc32Probe = require('./stream/Crc32Probe');
  1078. var nodejsUtils = require("./nodejsUtils");
  1079.  
  1080. /**
  1081. * Check the CRC32 of an entry.
  1082. * @param {ZipEntry} zipEntry the zip entry to check.
  1083. * @return {Promise} the result.
  1084. */
  1085. function checkEntryCRC32(zipEntry) {
  1086. return new external.Promise(function (resolve, reject) {
  1087. var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
  1088. worker.on("error", function (e) {
  1089. reject(e);
  1090. })
  1091. .on("end", function () {
  1092. if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
  1093. reject(new Error("Corrupted zip : CRC32 mismatch"));
  1094. } else {
  1095. resolve();
  1096. }
  1097. })
  1098. .resume();
  1099. });
  1100. }
  1101.  
  1102. module.exports = function (data, options) {
  1103. var zip = this;
  1104. options = utils.extend(options || {}, {
  1105. base64: false,
  1106. checkCRC32: false,
  1107. optimizedBinaryString: false,
  1108. createFolders: false,
  1109. decodeFileName: utf8.utf8decode
  1110. });
  1111.  
  1112. if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1113. return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
  1114. }
  1115.  
  1116. return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
  1117. .then(function (data) {
  1118. var zipEntries = new ZipEntries(options);
  1119. zipEntries.load(data);
  1120. return zipEntries;
  1121. }).then(function checkCRC32(zipEntries) {
  1122. var promises = [external.Promise.resolve(zipEntries)];
  1123. var files = zipEntries.files;
  1124. if (options.checkCRC32) {
  1125. for (var i = 0; i < files.length; i++) {
  1126. promises.push(checkEntryCRC32(files[i]));
  1127. }
  1128. }
  1129. return external.Promise.all(promises);
  1130. }).then(function addFiles(results) {
  1131. var zipEntries = results.shift();
  1132. var files = zipEntries.files;
  1133. for (var i = 0; i < files.length; i++) {
  1134. var input = files[i];
  1135. zip.file(input.fileNameStr, input.decompressed, {
  1136. binary: true,
  1137. optimizedBinaryString: true,
  1138. date: input.date,
  1139. dir: input.dir,
  1140. comment: input.fileCommentStr.length ? input.fileCommentStr : null,
  1141. unixPermissions: input.unixPermissions,
  1142. dosPermissions: input.dosPermissions,
  1143. createFolders: options.createFolders
  1144. });
  1145. }
  1146. if (zipEntries.zipComment.length) {
  1147. zip.comment = zipEntries.zipComment;
  1148. }
  1149.  
  1150. return zip;
  1151. });
  1152. };
  1153.  
  1154. },{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){
  1155. "use strict";
  1156.  
  1157. var utils = require('../utils');
  1158. var GenericWorker = require('../stream/GenericWorker');
  1159.  
  1160. /**
  1161. * A worker that use a nodejs stream as source.
  1162. * @constructor
  1163. * @param {String} filename the name of the file entry for this stream.
  1164. * @param {Readable} stream the nodejs stream.
  1165. */
  1166. function NodejsStreamInputAdapter(filename, stream) {
  1167. GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
  1168. this._upstreamEnded = false;
  1169. this._bindStream(stream);
  1170. }
  1171.  
  1172. utils.inherits(NodejsStreamInputAdapter, GenericWorker);
  1173.  
  1174. /**
  1175. * Prepare the stream and bind the callbacks on it.
  1176. * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
  1177. * @param {Stream} stream the nodejs stream to use.
  1178. */
  1179. NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
  1180. var self = this;
  1181. this._stream = stream;
  1182. stream.pause();
  1183. stream
  1184. .on("data", function (chunk) {
  1185. self.push({
  1186. data: chunk,
  1187. meta : {
  1188. percent : 0
  1189. }
  1190. });
  1191. })
  1192. .on("error", function (e) {
  1193. if(self.isPaused) {
  1194. this.generatedError = e;
  1195. } else {
  1196. self.error(e);
  1197. }
  1198. })
  1199. .on("end", function () {
  1200. if(self.isPaused) {
  1201. self._upstreamEnded = true;
  1202. } else {
  1203. self.end();
  1204. }
  1205. });
  1206. };
  1207. NodejsStreamInputAdapter.prototype.pause = function () {
  1208. if(!GenericWorker.prototype.pause.call(this)) {
  1209. return false;
  1210. }
  1211. this._stream.pause();
  1212. return true;
  1213. };
  1214. NodejsStreamInputAdapter.prototype.resume = function () {
  1215. if(!GenericWorker.prototype.resume.call(this)) {
  1216. return false;
  1217. }
  1218.  
  1219. if(this._upstreamEnded) {
  1220. this.end();
  1221. } else {
  1222. this._stream.resume();
  1223. }
  1224.  
  1225. return true;
  1226. };
  1227.  
  1228. module.exports = NodejsStreamInputAdapter;
  1229.  
  1230. },{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){
  1231. 'use strict';
  1232.  
  1233. var Readable = require('readable-stream').Readable;
  1234.  
  1235. var utils = require('../utils');
  1236. utils.inherits(NodejsStreamOutputAdapter, Readable);
  1237.  
  1238. /**
  1239. * A nodejs stream using a worker as source.
  1240. * @see the SourceWrapper in http://nodejs.org/api/stream.html
  1241. * @constructor
  1242. * @param {StreamHelper} helper the helper wrapping the worker
  1243. * @param {Object} options the nodejs stream options
  1244. * @param {Function} updateCb the update callback.
  1245. */
  1246. function NodejsStreamOutputAdapter(helper, options, updateCb) {
  1247. Readable.call(this, options);
  1248. this._helper = helper;
  1249.  
  1250. var self = this;
  1251. helper.on("data", function (data, meta) {
  1252. if (!self.push(data)) {
  1253. self._helper.pause();
  1254. }
  1255. if(updateCb) {
  1256. updateCb(meta);
  1257. }
  1258. })
  1259. .on("error", function(e) {
  1260. self.emit('error', e);
  1261. })
  1262. .on("end", function () {
  1263. self.push(null);
  1264. });
  1265. }
  1266.  
  1267.  
  1268. NodejsStreamOutputAdapter.prototype._read = function() {
  1269. this._helper.resume();
  1270. };
  1271.  
  1272. module.exports = NodejsStreamOutputAdapter;
  1273.  
  1274. },{"../utils":32,"readable-stream":16}],14:[function(require,module,exports){
  1275. 'use strict';
  1276.  
  1277. module.exports = {
  1278. /**
  1279. * True if this is running in Nodejs, will be undefined in a browser.
  1280. * In a browser, browserify won't include this file and the whole module
  1281. * will be resolved an empty object.
  1282. */
  1283. isNode : typeof Buffer !== "undefined",
  1284. /**
  1285. * Create a new nodejs Buffer from an existing content.
  1286. * @param {Object} data the data to pass to the constructor.
  1287. * @param {String} encoding the encoding to use.
  1288. * @return {Buffer} a new Buffer.
  1289. */
  1290. newBufferFrom: function(data, encoding) {
  1291. if (Buffer.from && Buffer.from !== Uint8Array.from) {
  1292. return Buffer.from(data, encoding);
  1293. } else {
  1294. if (typeof data === "number") {
  1295. // Safeguard for old Node.js versions. On newer versions,
  1296. // Buffer.from(number) / Buffer(number, encoding) already throw.
  1297. throw new Error("The \"data\" argument must not be a number");
  1298. }
  1299. return new Buffer(data, encoding);
  1300. }
  1301. },
  1302. /**
  1303. * Create a new nodejs Buffer with the specified size.
  1304. * @param {Integer} size the size of the buffer.
  1305. * @return {Buffer} a new Buffer.
  1306. */
  1307. allocBuffer: function (size) {
  1308. if (Buffer.alloc) {
  1309. return Buffer.alloc(size);
  1310. } else {
  1311. var buf = new Buffer(size);
  1312. buf.fill(0);
  1313. return buf;
  1314. }
  1315. },
  1316. /**
  1317. * Find out if an object is a Buffer.
  1318. * @param {Object} b the object to test.
  1319. * @return {Boolean} true if the object is a Buffer, false otherwise.
  1320. */
  1321. isBuffer : function(b){
  1322. return Buffer.isBuffer(b);
  1323. },
  1324.  
  1325. isStream : function (obj) {
  1326. return obj &&
  1327. typeof obj.on === "function" &&
  1328. typeof obj.pause === "function" &&
  1329. typeof obj.resume === "function";
  1330. }
  1331. };
  1332.  
  1333. },{}],15:[function(require,module,exports){
  1334. 'use strict';
  1335. var utf8 = require('./utf8');
  1336. var utils = require('./utils');
  1337. var GenericWorker = require('./stream/GenericWorker');
  1338. var StreamHelper = require('./stream/StreamHelper');
  1339. var defaults = require('./defaults');
  1340. var CompressedObject = require('./compressedObject');
  1341. var ZipObject = require('./zipObject');
  1342. var generate = require("./generate");
  1343. var nodejsUtils = require("./nodejsUtils");
  1344. var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
  1345.  
  1346.  
  1347. /**
  1348. * Add a file in the current folder.
  1349. * @private
  1350. * @param {string} name the name of the file
  1351. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  1352. * @param {Object} originalOptions the options of the file
  1353. * @return {Object} the new file.
  1354. */
  1355. var fileAdd = function(name, data, originalOptions) {
  1356. // be sure sub folders exist
  1357. var dataType = utils.getTypeOf(data),
  1358. parent;
  1359.  
  1360.  
  1361. /*
  1362. * Correct options.
  1363. */
  1364.  
  1365. var o = utils.extend(originalOptions || {}, defaults);
  1366. o.date = o.date || new Date();
  1367. if (o.compression !== null) {
  1368. o.compression = o.compression.toUpperCase();
  1369. }
  1370.  
  1371. if (typeof o.unixPermissions === "string") {
  1372. o.unixPermissions = parseInt(o.unixPermissions, 8);
  1373. }
  1374.  
  1375. // UNX_IFDIR 0040000 see zipinfo.c
  1376. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  1377. o.dir = true;
  1378. }
  1379. // Bit 4 Directory
  1380. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  1381. o.dir = true;
  1382. }
  1383.  
  1384. if (o.dir) {
  1385. name = forceTrailingSlash(name);
  1386. }
  1387. if (o.createFolders && (parent = parentFolder(name))) {
  1388. folderAdd.call(this, parent, true);
  1389. }
  1390.  
  1391. var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
  1392. if (!originalOptions || typeof originalOptions.binary === "undefined") {
  1393. o.binary = !isUnicodeString;
  1394. }
  1395.  
  1396.  
  1397. var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
  1398.  
  1399. if (isCompressedEmpty || o.dir || !data || data.length === 0) {
  1400. o.base64 = false;
  1401. o.binary = true;
  1402. data = "";
  1403. o.compression = "STORE";
  1404. dataType = "string";
  1405. }
  1406.  
  1407. /*
  1408. * Convert content to fit.
  1409. */
  1410.  
  1411. var zipObjectContent = null;
  1412. if (data instanceof CompressedObject || data instanceof GenericWorker) {
  1413. zipObjectContent = data;
  1414. } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1415. zipObjectContent = new NodejsStreamInputAdapter(name, data);
  1416. } else {
  1417. zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
  1418. }
  1419.  
  1420. var object = new ZipObject(name, zipObjectContent, o);
  1421. this.files[name] = object;
  1422. /*
  1423. TODO: we can't throw an exception because we have async promises
  1424. (we can have a promise of a Date() for example) but returning a
  1425. promise is useless because file(name, data) returns the JSZip
  1426. object for chaining. Should we break that to allow the user
  1427. to catch the error ?
  1428.  
  1429. return external.Promise.resolve(zipObjectContent)
  1430. .then(function () {
  1431. return object;
  1432. });
  1433. */
  1434. };
  1435.  
  1436. /**
  1437. * Find the parent folder of the path.
  1438. * @private
  1439. * @param {string} path the path to use
  1440. * @return {string} the parent folder, or ""
  1441. */
  1442. var parentFolder = function (path) {
  1443. if (path.slice(-1) === '/') {
  1444. path = path.substring(0, path.length - 1);
  1445. }
  1446. var lastSlash = path.lastIndexOf('/');
  1447. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  1448. };
  1449.  
  1450. /**
  1451. * Returns the path with a slash at the end.
  1452. * @private
  1453. * @param {String} path the path to check.
  1454. * @return {String} the path with a trailing slash.
  1455. */
  1456. var forceTrailingSlash = function(path) {
  1457. // Check the name ends with a /
  1458. if (path.slice(-1) !== "/") {
  1459. path += "/"; // IE doesn't like substr(-1)
  1460. }
  1461. return path;
  1462. };
  1463.  
  1464. /**
  1465. * Add a (sub) folder in the current folder.
  1466. * @private
  1467. * @param {string} name the folder's name
  1468. * @param {boolean=} [createFolders] If true, automatically create sub
  1469. * folders. Defaults to false.
  1470. * @return {Object} the new folder.
  1471. */
  1472. var folderAdd = function(name, createFolders) {
  1473. createFolders = (typeof createFolders !== 'undefined') ? createFolders : defaults.createFolders;
  1474.  
  1475. name = forceTrailingSlash(name);
  1476.  
  1477. // Does this folder already exist?
  1478. if (!this.files[name]) {
  1479. fileAdd.call(this, name, null, {
  1480. dir: true,
  1481. createFolders: createFolders
  1482. });
  1483. }
  1484. return this.files[name];
  1485. };
  1486.  
  1487. /**
  1488. * Cross-window, cross-Node-context regular expression detection
  1489. * @param {Object} object Anything
  1490. * @return {Boolean} true if the object is a regular expression,
  1491. * false otherwise
  1492. */
  1493. function isRegExp(object) {
  1494. return Object.prototype.toString.call(object) === "[object RegExp]";
  1495. }
  1496.  
  1497. // return the actual prototype of JSZip
  1498. var out = {
  1499. /**
  1500. * @see loadAsync
  1501. */
  1502. load: function() {
  1503. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1504. },
  1505.  
  1506.  
  1507. /**
  1508. * Call a callback function for each entry at this folder level.
  1509. * @param {Function} cb the callback function:
  1510. * function (relativePath, file) {...}
  1511. * It takes 2 arguments : the relative path and the file.
  1512. */
  1513. forEach: function(cb) {
  1514. var filename, relativePath, file;
  1515. /* jshint ignore:start */
  1516. // ignore warning about unwanted properties because this.files is a null prototype object
  1517. for (filename in this.files) {
  1518. file = this.files[filename];
  1519. relativePath = filename.slice(this.root.length, filename.length);
  1520. if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
  1521. cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
  1522. }
  1523. }
  1524. /* jshint ignore:end */
  1525. },
  1526.  
  1527. /**
  1528. * Filter nested files/folders with the specified function.
  1529. * @param {Function} search the predicate to use :
  1530. * function (relativePath, file) {...}
  1531. * It takes 2 arguments : the relative path and the file.
  1532. * @return {Array} An array of matching elements.
  1533. */
  1534. filter: function(search) {
  1535. var result = [];
  1536. this.forEach(function (relativePath, entry) {
  1537. if (search(relativePath, entry)) { // the file matches the function
  1538. result.push(entry);
  1539. }
  1540.  
  1541. });
  1542. return result;
  1543. },
  1544.  
  1545. /**
  1546. * Add a file to the zip file, or search a file.
  1547. * @param {string|RegExp} name The name of the file to add (if data is defined),
  1548. * the name of the file to find (if no data) or a regex to match files.
  1549. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  1550. * @param {Object} o File options
  1551. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  1552. * a file (when searching by string) or an array of files (when searching by regex).
  1553. */
  1554. file: function(name, data, o) {
  1555. if (arguments.length === 1) {
  1556. if (isRegExp(name)) {
  1557. var regexp = name;
  1558. return this.filter(function(relativePath, file) {
  1559. return !file.dir && regexp.test(relativePath);
  1560. });
  1561. }
  1562. else { // text
  1563. var obj = this.files[this.root + name];
  1564. if (obj && !obj.dir) {
  1565. return obj;
  1566. } else {
  1567. return null;
  1568. }
  1569. }
  1570. }
  1571. else { // more than one argument : we have data !
  1572. name = this.root + name;
  1573. fileAdd.call(this, name, data, o);
  1574. }
  1575. return this;
  1576. },
  1577.  
  1578. /**
  1579. * Add a directory to the zip file, or search.
  1580. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  1581. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  1582. */
  1583. folder: function(arg) {
  1584. if (!arg) {
  1585. return this;
  1586. }
  1587.  
  1588. if (isRegExp(arg)) {
  1589. return this.filter(function(relativePath, file) {
  1590. return file.dir && arg.test(relativePath);
  1591. });
  1592. }
  1593.  
  1594. // else, name is a new folder
  1595. var name = this.root + arg;
  1596. var newFolder = folderAdd.call(this, name);
  1597.  
  1598. // Allow chaining by returning a new object with this folder as the root
  1599. var ret = this.clone();
  1600. ret.root = newFolder.name;
  1601. return ret;
  1602. },
  1603.  
  1604. /**
  1605. * Delete a file, or a directory and all sub-files, from the zip
  1606. * @param {string} name the name of the file to delete
  1607. * @return {JSZip} this JSZip object
  1608. */
  1609. remove: function(name) {
  1610. name = this.root + name;
  1611. var file = this.files[name];
  1612. if (!file) {
  1613. // Look for any folders
  1614. if (name.slice(-1) !== "/") {
  1615. name += "/";
  1616. }
  1617. file = this.files[name];
  1618. }
  1619.  
  1620. if (file && !file.dir) {
  1621. // file
  1622. delete this.files[name];
  1623. } else {
  1624. // maybe a folder, delete recursively
  1625. var kids = this.filter(function(relativePath, file) {
  1626. return file.name.slice(0, name.length) === name;
  1627. });
  1628. for (var i = 0; i < kids.length; i++) {
  1629. delete this.files[kids[i].name];
  1630. }
  1631. }
  1632.  
  1633. return this;
  1634. },
  1635.  
  1636. /**
  1637. * Generate the complete zip file
  1638. * @param {Object} options the options to generate the zip file :
  1639. * - compression, "STORE" by default.
  1640. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1641. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  1642. */
  1643. generate: function(options) {
  1644. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1645. },
  1646.  
  1647. /**
  1648. * Generate the complete zip file as an internal stream.
  1649. * @param {Object} options the options to generate the zip file :
  1650. * - compression, "STORE" by default.
  1651. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1652. * @return {StreamHelper} the streamed zip file.
  1653. */
  1654. generateInternalStream: function(options) {
  1655. var worker, opts = {};
  1656. try {
  1657. opts = utils.extend(options || {}, {
  1658. streamFiles: false,
  1659. compression: "STORE",
  1660. compressionOptions : null,
  1661. type: "",
  1662. platform: "DOS",
  1663. comment: null,
  1664. mimeType: 'application/zip',
  1665. encodeFileName: utf8.utf8encode
  1666. });
  1667.  
  1668. opts.type = opts.type.toLowerCase();
  1669. opts.compression = opts.compression.toUpperCase();
  1670.  
  1671. // "binarystring" is preferred but the internals use "string".
  1672. if(opts.type === "binarystring") {
  1673. opts.type = "string";
  1674. }
  1675.  
  1676. if (!opts.type) {
  1677. throw new Error("No output type specified.");
  1678. }
  1679.  
  1680. utils.checkSupport(opts.type);
  1681.  
  1682. // accept nodejs `process.platform`
  1683. if(
  1684. opts.platform === 'darwin' ||
  1685. opts.platform === 'freebsd' ||
  1686. opts.platform === 'linux' ||
  1687. opts.platform === 'sunos'
  1688. ) {
  1689. opts.platform = "UNIX";
  1690. }
  1691. if (opts.platform === 'win32') {
  1692. opts.platform = "DOS";
  1693. }
  1694.  
  1695. var comment = opts.comment || this.comment || "";
  1696. worker = generate.generateWorker(this, opts, comment);
  1697. } catch (e) {
  1698. worker = new GenericWorker("error");
  1699. worker.error(e);
  1700. }
  1701. return new StreamHelper(worker, opts.type || "string", opts.mimeType);
  1702. },
  1703. /**
  1704. * Generate the complete zip file asynchronously.
  1705. * @see generateInternalStream
  1706. */
  1707. generateAsync: function(options, onUpdate) {
  1708. return this.generateInternalStream(options).accumulate(onUpdate);
  1709. },
  1710. /**
  1711. * Generate the complete zip file asynchronously.
  1712. * @see generateInternalStream
  1713. */
  1714. generateNodeStream: function(options, onUpdate) {
  1715. options = options || {};
  1716. if (!options.type) {
  1717. options.type = "nodebuffer";
  1718. }
  1719. return this.generateInternalStream(options).toNodejsStream(onUpdate);
  1720. }
  1721. };
  1722. module.exports = out;
  1723.  
  1724. },{"./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){
  1725. /*
  1726. * This file is used by module bundlers (browserify/webpack/etc) when
  1727. * including a stream implementation. We use "readable-stream" to get a
  1728. * consistent behavior between nodejs versions but bundlers often have a shim
  1729. * for "stream". Using this shim greatly improve the compatibility and greatly
  1730. * reduce the final size of the bundle (only one stream implementation, not
  1731. * two).
  1732. */
  1733. module.exports = require("stream");
  1734.  
  1735. },{"stream":undefined}],17:[function(require,module,exports){
  1736. 'use strict';
  1737. var DataReader = require('./DataReader');
  1738. var utils = require('../utils');
  1739.  
  1740. function ArrayReader(data) {
  1741. DataReader.call(this, data);
  1742. for(var i = 0; i < this.data.length; i++) {
  1743. data[i] = data[i] & 0xFF;
  1744. }
  1745. }
  1746. utils.inherits(ArrayReader, DataReader);
  1747. /**
  1748. * @see DataReader.byteAt
  1749. */
  1750. ArrayReader.prototype.byteAt = function(i) {
  1751. return this.data[this.zero + i];
  1752. };
  1753. /**
  1754. * @see DataReader.lastIndexOfSignature
  1755. */
  1756. ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  1757. var sig0 = sig.charCodeAt(0),
  1758. sig1 = sig.charCodeAt(1),
  1759. sig2 = sig.charCodeAt(2),
  1760. sig3 = sig.charCodeAt(3);
  1761. for (var i = this.length - 4; i >= 0; --i) {
  1762. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  1763. return i - this.zero;
  1764. }
  1765. }
  1766.  
  1767. return -1;
  1768. };
  1769. /**
  1770. * @see DataReader.readAndCheckSignature
  1771. */
  1772. ArrayReader.prototype.readAndCheckSignature = function (sig) {
  1773. var sig0 = sig.charCodeAt(0),
  1774. sig1 = sig.charCodeAt(1),
  1775. sig2 = sig.charCodeAt(2),
  1776. sig3 = sig.charCodeAt(3),
  1777. data = this.readData(4);
  1778. return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
  1779. };
  1780. /**
  1781. * @see DataReader.readData
  1782. */
  1783. ArrayReader.prototype.readData = function(size) {
  1784. this.checkOffset(size);
  1785. if(size === 0) {
  1786. return [];
  1787. }
  1788. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1789. this.index += size;
  1790. return result;
  1791. };
  1792. module.exports = ArrayReader;
  1793.  
  1794. },{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){
  1795. 'use strict';
  1796. var utils = require('../utils');
  1797.  
  1798. function DataReader(data) {
  1799. this.data = data; // type : see implementation
  1800. this.length = data.length;
  1801. this.index = 0;
  1802. this.zero = 0;
  1803. }
  1804. DataReader.prototype = {
  1805. /**
  1806. * Check that the offset will not go too far.
  1807. * @param {string} offset the additional offset to check.
  1808. * @throws {Error} an Error if the offset is out of bounds.
  1809. */
  1810. checkOffset: function(offset) {
  1811. this.checkIndex(this.index + offset);
  1812. },
  1813. /**
  1814. * Check that the specified index will not be too far.
  1815. * @param {string} newIndex the index to check.
  1816. * @throws {Error} an Error if the index is out of bounds.
  1817. */
  1818. checkIndex: function(newIndex) {
  1819. if (this.length < this.zero + newIndex || newIndex < 0) {
  1820. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  1821. }
  1822. },
  1823. /**
  1824. * Change the index.
  1825. * @param {number} newIndex The new index.
  1826. * @throws {Error} if the new index is out of the data.
  1827. */
  1828. setIndex: function(newIndex) {
  1829. this.checkIndex(newIndex);
  1830. this.index = newIndex;
  1831. },
  1832. /**
  1833. * Skip the next n bytes.
  1834. * @param {number} n the number of bytes to skip.
  1835. * @throws {Error} if the new index is out of the data.
  1836. */
  1837. skip: function(n) {
  1838. this.setIndex(this.index + n);
  1839. },
  1840. /**
  1841. * Get the byte at the specified index.
  1842. * @param {number} i the index to use.
  1843. * @return {number} a byte.
  1844. */
  1845. byteAt: function(i) {
  1846. // see implementations
  1847. },
  1848. /**
  1849. * Get the next number with a given byte size.
  1850. * @param {number} size the number of bytes to read.
  1851. * @return {number} the corresponding number.
  1852. */
  1853. readInt: function(size) {
  1854. var result = 0,
  1855. i;
  1856. this.checkOffset(size);
  1857. for (i = this.index + size - 1; i >= this.index; i--) {
  1858. result = (result << 8) + this.byteAt(i);
  1859. }
  1860. this.index += size;
  1861. return result;
  1862. },
  1863. /**
  1864. * Get the next string with a given byte size.
  1865. * @param {number} size the number of bytes to read.
  1866. * @return {string} the corresponding string.
  1867. */
  1868. readString: function(size) {
  1869. return utils.transformTo("string", this.readData(size));
  1870. },
  1871. /**
  1872. * Get raw data without conversion, <size> bytes.
  1873. * @param {number} size the number of bytes to read.
  1874. * @return {Object} the raw data, implementation specific.
  1875. */
  1876. readData: function(size) {
  1877. // see implementations
  1878. },
  1879. /**
  1880. * Find the last occurrence of a zip signature (4 bytes).
  1881. * @param {string} sig the signature to find.
  1882. * @return {number} the index of the last occurrence, -1 if not found.
  1883. */
  1884. lastIndexOfSignature: function(sig) {
  1885. // see implementations
  1886. },
  1887. /**
  1888. * Read the signature (4 bytes) at the current position and compare it with sig.
  1889. * @param {string} sig the expected signature
  1890. * @return {boolean} true if the signature matches, false otherwise.
  1891. */
  1892. readAndCheckSignature: function(sig) {
  1893. // see implementations
  1894. },
  1895. /**
  1896. * Get the next date.
  1897. * @return {Date} the date.
  1898. */
  1899. readDate: function() {
  1900. var dostime = this.readInt(4);
  1901. return new Date(Date.UTC(
  1902. ((dostime >> 25) & 0x7f) + 1980, // year
  1903. ((dostime >> 21) & 0x0f) - 1, // month
  1904. (dostime >> 16) & 0x1f, // day
  1905. (dostime >> 11) & 0x1f, // hour
  1906. (dostime >> 5) & 0x3f, // minute
  1907. (dostime & 0x1f) << 1)); // second
  1908. }
  1909. };
  1910. module.exports = DataReader;
  1911.  
  1912. },{"../utils":32}],19:[function(require,module,exports){
  1913. 'use strict';
  1914. var Uint8ArrayReader = require('./Uint8ArrayReader');
  1915. var utils = require('../utils');
  1916.  
  1917. function NodeBufferReader(data) {
  1918. Uint8ArrayReader.call(this, data);
  1919. }
  1920. utils.inherits(NodeBufferReader, Uint8ArrayReader);
  1921.  
  1922. /**
  1923. * @see DataReader.readData
  1924. */
  1925. NodeBufferReader.prototype.readData = function(size) {
  1926. this.checkOffset(size);
  1927. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1928. this.index += size;
  1929. return result;
  1930. };
  1931. module.exports = NodeBufferReader;
  1932.  
  1933. },{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){
  1934. 'use strict';
  1935. var DataReader = require('./DataReader');
  1936. var utils = require('../utils');
  1937.  
  1938. function StringReader(data) {
  1939. DataReader.call(this, data);
  1940. }
  1941. utils.inherits(StringReader, DataReader);
  1942. /**
  1943. * @see DataReader.byteAt
  1944. */
  1945. StringReader.prototype.byteAt = function(i) {
  1946. return this.data.charCodeAt(this.zero + i);
  1947. };
  1948. /**
  1949. * @see DataReader.lastIndexOfSignature
  1950. */
  1951. StringReader.prototype.lastIndexOfSignature = function(sig) {
  1952. return this.data.lastIndexOf(sig) - this.zero;
  1953. };
  1954. /**
  1955. * @see DataReader.readAndCheckSignature
  1956. */
  1957. StringReader.prototype.readAndCheckSignature = function (sig) {
  1958. var data = this.readData(4);
  1959. return sig === data;
  1960. };
  1961. /**
  1962. * @see DataReader.readData
  1963. */
  1964. StringReader.prototype.readData = function(size) {
  1965. this.checkOffset(size);
  1966. // this will work because the constructor applied the "& 0xff" mask.
  1967. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1968. this.index += size;
  1969. return result;
  1970. };
  1971. module.exports = StringReader;
  1972.  
  1973. },{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){
  1974. 'use strict';
  1975. var ArrayReader = require('./ArrayReader');
  1976. var utils = require('../utils');
  1977.  
  1978. function Uint8ArrayReader(data) {
  1979. ArrayReader.call(this, data);
  1980. }
  1981. utils.inherits(Uint8ArrayReader, ArrayReader);
  1982. /**
  1983. * @see DataReader.readData
  1984. */
  1985. Uint8ArrayReader.prototype.readData = function(size) {
  1986. this.checkOffset(size);
  1987. if(size === 0) {
  1988. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  1989. return new Uint8Array(0);
  1990. }
  1991. var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
  1992. this.index += size;
  1993. return result;
  1994. };
  1995. module.exports = Uint8ArrayReader;
  1996.  
  1997. },{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){
  1998. 'use strict';
  1999.  
  2000. var utils = require('../utils');
  2001. var support = require('../support');
  2002. var ArrayReader = require('./ArrayReader');
  2003. var StringReader = require('./StringReader');
  2004. var NodeBufferReader = require('./NodeBufferReader');
  2005. var Uint8ArrayReader = require('./Uint8ArrayReader');
  2006.  
  2007. /**
  2008. * Create a reader adapted to the data.
  2009. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
  2010. * @return {DataReader} the data reader.
  2011. */
  2012. module.exports = function (data) {
  2013. var type = utils.getTypeOf(data);
  2014. utils.checkSupport(type);
  2015. if (type === "string" && !support.uint8array) {
  2016. return new StringReader(data);
  2017. }
  2018. if (type === "nodebuffer") {
  2019. return new NodeBufferReader(data);
  2020. }
  2021. if (support.uint8array) {
  2022. return new Uint8ArrayReader(utils.transformTo("uint8array", data));
  2023. }
  2024. return new ArrayReader(utils.transformTo("array", data));
  2025. };
  2026.  
  2027. },{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){
  2028. 'use strict';
  2029. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  2030. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  2031. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  2032. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  2033. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  2034. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  2035.  
  2036. },{}],24:[function(require,module,exports){
  2037. 'use strict';
  2038.  
  2039. var GenericWorker = require('./GenericWorker');
  2040. var utils = require('../utils');
  2041.  
  2042. /**
  2043. * A worker which convert chunks to a specified type.
  2044. * @constructor
  2045. * @param {String} destType the destination type.
  2046. */
  2047. function ConvertWorker(destType) {
  2048. GenericWorker.call(this, "ConvertWorker to " + destType);
  2049. this.destType = destType;
  2050. }
  2051. utils.inherits(ConvertWorker, GenericWorker);
  2052.  
  2053. /**
  2054. * @see GenericWorker.processChunk
  2055. */
  2056. ConvertWorker.prototype.processChunk = function (chunk) {
  2057. this.push({
  2058. data : utils.transformTo(this.destType, chunk.data),
  2059. meta : chunk.meta
  2060. });
  2061. };
  2062. module.exports = ConvertWorker;
  2063.  
  2064. },{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){
  2065. 'use strict';
  2066.  
  2067. var GenericWorker = require('./GenericWorker');
  2068. var crc32 = require('../crc32');
  2069. var utils = require('../utils');
  2070.  
  2071. /**
  2072. * A worker which calculate the crc32 of the data flowing through.
  2073. * @constructor
  2074. */
  2075. function Crc32Probe() {
  2076. GenericWorker.call(this, "Crc32Probe");
  2077. this.withStreamInfo("crc32", 0);
  2078. }
  2079. utils.inherits(Crc32Probe, GenericWorker);
  2080.  
  2081. /**
  2082. * @see GenericWorker.processChunk
  2083. */
  2084. Crc32Probe.prototype.processChunk = function (chunk) {
  2085. this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
  2086. this.push(chunk);
  2087. };
  2088. module.exports = Crc32Probe;
  2089.  
  2090. },{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){
  2091. 'use strict';
  2092.  
  2093. var utils = require('../utils');
  2094. var GenericWorker = require('./GenericWorker');
  2095.  
  2096. /**
  2097. * A worker which calculate the total length of the data flowing through.
  2098. * @constructor
  2099. * @param {String} propName the name used to expose the length
  2100. */
  2101. function DataLengthProbe(propName) {
  2102. GenericWorker.call(this, "DataLengthProbe for " + propName);
  2103. this.propName = propName;
  2104. this.withStreamInfo(propName, 0);
  2105. }
  2106. utils.inherits(DataLengthProbe, GenericWorker);
  2107.  
  2108. /**
  2109. * @see GenericWorker.processChunk
  2110. */
  2111. DataLengthProbe.prototype.processChunk = function (chunk) {
  2112. if(chunk) {
  2113. var length = this.streamInfo[this.propName] || 0;
  2114. this.streamInfo[this.propName] = length + chunk.data.length;
  2115. }
  2116. GenericWorker.prototype.processChunk.call(this, chunk);
  2117. };
  2118. module.exports = DataLengthProbe;
  2119.  
  2120.  
  2121. },{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){
  2122. 'use strict';
  2123.  
  2124. var utils = require('../utils');
  2125. var GenericWorker = require('./GenericWorker');
  2126.  
  2127. // the size of the generated chunks
  2128. // TODO expose this as a public variable
  2129. var DEFAULT_BLOCK_SIZE = 16 * 1024;
  2130.  
  2131. /**
  2132. * A worker that reads a content and emits chunks.
  2133. * @constructor
  2134. * @param {Promise} dataP the promise of the data to split
  2135. */
  2136. function DataWorker(dataP) {
  2137. GenericWorker.call(this, "DataWorker");
  2138. var self = this;
  2139. this.dataIsReady = false;
  2140. this.index = 0;
  2141. this.max = 0;
  2142. this.data = null;
  2143. this.type = "";
  2144.  
  2145. this._tickScheduled = false;
  2146.  
  2147. dataP.then(function (data) {
  2148. self.dataIsReady = true;
  2149. self.data = data;
  2150. self.max = data && data.length || 0;
  2151. self.type = utils.getTypeOf(data);
  2152. if(!self.isPaused) {
  2153. self._tickAndRepeat();
  2154. }
  2155. }, function (e) {
  2156. self.error(e);
  2157. });
  2158. }
  2159.  
  2160. utils.inherits(DataWorker, GenericWorker);
  2161.  
  2162. /**
  2163. * @see GenericWorker.cleanUp
  2164. */
  2165. DataWorker.prototype.cleanUp = function () {
  2166. GenericWorker.prototype.cleanUp.call(this);
  2167. this.data = null;
  2168. };
  2169.  
  2170. /**
  2171. * @see GenericWorker.resume
  2172. */
  2173. DataWorker.prototype.resume = function () {
  2174. if(!GenericWorker.prototype.resume.call(this)) {
  2175. return false;
  2176. }
  2177.  
  2178. if (!this._tickScheduled && this.dataIsReady) {
  2179. this._tickScheduled = true;
  2180. utils.delay(this._tickAndRepeat, [], this);
  2181. }
  2182. return true;
  2183. };
  2184.  
  2185. /**
  2186. * Trigger a tick a schedule an other call to this function.
  2187. */
  2188. DataWorker.prototype._tickAndRepeat = function() {
  2189. this._tickScheduled = false;
  2190. if(this.isPaused || this.isFinished) {
  2191. return;
  2192. }
  2193. this._tick();
  2194. if(!this.isFinished) {
  2195. utils.delay(this._tickAndRepeat, [], this);
  2196. this._tickScheduled = true;
  2197. }
  2198. };
  2199.  
  2200. /**
  2201. * Read and push a chunk.
  2202. */
  2203. DataWorker.prototype._tick = function() {
  2204.  
  2205. if(this.isPaused || this.isFinished) {
  2206. return false;
  2207. }
  2208.  
  2209. var size = DEFAULT_BLOCK_SIZE;
  2210. var data = null, nextIndex = Math.min(this.max, this.index + size);
  2211. if (this.index >= this.max) {
  2212. // EOF
  2213. return this.end();
  2214. } else {
  2215. switch(this.type) {
  2216. case "string":
  2217. data = this.data.substring(this.index, nextIndex);
  2218. break;
  2219. case "uint8array":
  2220. data = this.data.subarray(this.index, nextIndex);
  2221. break;
  2222. case "array":
  2223. case "nodebuffer":
  2224. data = this.data.slice(this.index, nextIndex);
  2225. break;
  2226. }
  2227. this.index = nextIndex;
  2228. return this.push({
  2229. data : data,
  2230. meta : {
  2231. percent : this.max ? this.index / this.max * 100 : 0
  2232. }
  2233. });
  2234. }
  2235. };
  2236.  
  2237. module.exports = DataWorker;
  2238.  
  2239. },{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){
  2240. 'use strict';
  2241.  
  2242. /**
  2243. * A worker that does nothing but passing chunks to the next one. This is like
  2244. * a nodejs stream but with some differences. On the good side :
  2245. * - it works on IE 6-9 without any issue / polyfill
  2246. * - it weights less than the full dependencies bundled with browserify
  2247. * - it forwards errors (no need to declare an error handler EVERYWHERE)
  2248. *
  2249. * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
  2250. * object containing anything (`percent` for example), see each worker for more
  2251. * details. The latter is the real data (String, Uint8Array, etc).
  2252. *
  2253. * @constructor
  2254. * @param {String} name the name of the stream (mainly used for debugging purposes)
  2255. */
  2256. function GenericWorker(name) {
  2257. // the name of the worker
  2258. this.name = name || "default";
  2259. // an object containing metadata about the workers chain
  2260. this.streamInfo = {};
  2261. // an error which happened when the worker was paused
  2262. this.generatedError = null;
  2263. // an object containing metadata to be merged by this worker into the general metadata
  2264. this.extraStreamInfo = {};
  2265. // true if the stream is paused (and should not do anything), false otherwise
  2266. this.isPaused = true;
  2267. // true if the stream is finished (and should not do anything), false otherwise
  2268. this.isFinished = false;
  2269. // true if the stream is locked to prevent further structure updates (pipe), false otherwise
  2270. this.isLocked = false;
  2271. // the event listeners
  2272. this._listeners = {
  2273. 'data':[],
  2274. 'end':[],
  2275. 'error':[]
  2276. };
  2277. // the previous worker, if any
  2278. this.previous = null;
  2279. }
  2280.  
  2281. GenericWorker.prototype = {
  2282. /**
  2283. * Push a chunk to the next workers.
  2284. * @param {Object} chunk the chunk to push
  2285. */
  2286. push : function (chunk) {
  2287. this.emit("data", chunk);
  2288. },
  2289. /**
  2290. * End the stream.
  2291. * @return {Boolean} true if this call ended the worker, false otherwise.
  2292. */
  2293. end : function () {
  2294. if (this.isFinished) {
  2295. return false;
  2296. }
  2297.  
  2298. this.flush();
  2299. try {
  2300. this.emit("end");
  2301. this.cleanUp();
  2302. this.isFinished = true;
  2303. } catch (e) {
  2304. this.emit("error", e);
  2305. }
  2306. return true;
  2307. },
  2308. /**
  2309. * End the stream with an error.
  2310. * @param {Error} e the error which caused the premature end.
  2311. * @return {Boolean} true if this call ended the worker with an error, false otherwise.
  2312. */
  2313. error : function (e) {
  2314. if (this.isFinished) {
  2315. return false;
  2316. }
  2317.  
  2318. if(this.isPaused) {
  2319. this.generatedError = e;
  2320. } else {
  2321. this.isFinished = true;
  2322.  
  2323. this.emit("error", e);
  2324.  
  2325. // in the workers chain exploded in the middle of the chain,
  2326. // the error event will go downward but we also need to notify
  2327. // workers upward that there has been an error.
  2328. if(this.previous) {
  2329. this.previous.error(e);
  2330. }
  2331.  
  2332. this.cleanUp();
  2333. }
  2334. return true;
  2335. },
  2336. /**
  2337. * Add a callback on an event.
  2338. * @param {String} name the name of the event (data, end, error)
  2339. * @param {Function} listener the function to call when the event is triggered
  2340. * @return {GenericWorker} the current object for chainability
  2341. */
  2342. on : function (name, listener) {
  2343. this._listeners[name].push(listener);
  2344. return this;
  2345. },
  2346. /**
  2347. * Clean any references when a worker is ending.
  2348. */
  2349. cleanUp : function () {
  2350. this.streamInfo = this.generatedError = this.extraStreamInfo = null;
  2351. this._listeners = [];
  2352. },
  2353. /**
  2354. * Trigger an event. This will call registered callback with the provided arg.
  2355. * @param {String} name the name of the event (data, end, error)
  2356. * @param {Object} arg the argument to call the callback with.
  2357. */
  2358. emit : function (name, arg) {
  2359. if (this._listeners[name]) {
  2360. for(var i = 0; i < this._listeners[name].length; i++) {
  2361. this._listeners[name][i].call(this, arg);
  2362. }
  2363. }
  2364. },
  2365. /**
  2366. * Chain a worker with an other.
  2367. * @param {Worker} next the worker receiving events from the current one.
  2368. * @return {worker} the next worker for chainability
  2369. */
  2370. pipe : function (next) {
  2371. return next.registerPrevious(this);
  2372. },
  2373. /**
  2374. * Same as `pipe` in the other direction.
  2375. * Using an API with `pipe(next)` is very easy.
  2376. * Implementing the API with the point of view of the next one registering
  2377. * a source is easier, see the ZipFileWorker.
  2378. * @param {Worker} previous the previous worker, sending events to this one
  2379. * @return {Worker} the current worker for chainability
  2380. */
  2381. registerPrevious : function (previous) {
  2382. if (this.isLocked) {
  2383. throw new Error("The stream '" + this + "' has already been used.");
  2384. }
  2385.  
  2386. // sharing the streamInfo...
  2387. this.streamInfo = previous.streamInfo;
  2388. // ... and adding our own bits
  2389. this.mergeStreamInfo();
  2390. this.previous = previous;
  2391. var self = this;
  2392. previous.on('data', function (chunk) {
  2393. self.processChunk(chunk);
  2394. });
  2395. previous.on('end', function () {
  2396. self.end();
  2397. });
  2398. previous.on('error', function (e) {
  2399. self.error(e);
  2400. });
  2401. return this;
  2402. },
  2403. /**
  2404. * Pause the stream so it doesn't send events anymore.
  2405. * @return {Boolean} true if this call paused the worker, false otherwise.
  2406. */
  2407. pause : function () {
  2408. if(this.isPaused || this.isFinished) {
  2409. return false;
  2410. }
  2411. this.isPaused = true;
  2412.  
  2413. if(this.previous) {
  2414. this.previous.pause();
  2415. }
  2416. return true;
  2417. },
  2418. /**
  2419. * Resume a paused stream.
  2420. * @return {Boolean} true if this call resumed the worker, false otherwise.
  2421. */
  2422. resume : function () {
  2423. if(!this.isPaused || this.isFinished) {
  2424. return false;
  2425. }
  2426. this.isPaused = false;
  2427.  
  2428. // if true, the worker tried to resume but failed
  2429. var withError = false;
  2430. if(this.generatedError) {
  2431. this.error(this.generatedError);
  2432. withError = true;
  2433. }
  2434. if(this.previous) {
  2435. this.previous.resume();
  2436. }
  2437.  
  2438. return !withError;
  2439. },
  2440. /**
  2441. * Flush any remaining bytes as the stream is ending.
  2442. */
  2443. flush : function () {},
  2444. /**
  2445. * Process a chunk. This is usually the method overridden.
  2446. * @param {Object} chunk the chunk to process.
  2447. */
  2448. processChunk : function(chunk) {
  2449. this.push(chunk);
  2450. },
  2451. /**
  2452. * Add a key/value to be added in the workers chain streamInfo once activated.
  2453. * @param {String} key the key to use
  2454. * @param {Object} value the associated value
  2455. * @return {Worker} the current worker for chainability
  2456. */
  2457. withStreamInfo : function (key, value) {
  2458. this.extraStreamInfo[key] = value;
  2459. this.mergeStreamInfo();
  2460. return this;
  2461. },
  2462. /**
  2463. * Merge this worker's streamInfo into the chain's streamInfo.
  2464. */
  2465. mergeStreamInfo : function () {
  2466. for(var key in this.extraStreamInfo) {
  2467. if (!this.extraStreamInfo.hasOwnProperty(key)) {
  2468. continue;
  2469. }
  2470. this.streamInfo[key] = this.extraStreamInfo[key];
  2471. }
  2472. },
  2473.  
  2474. /**
  2475. * Lock the stream to prevent further updates on the workers chain.
  2476. * After calling this method, all calls to pipe will fail.
  2477. */
  2478. lock: function () {
  2479. if (this.isLocked) {
  2480. throw new Error("The stream '" + this + "' has already been used.");
  2481. }
  2482. this.isLocked = true;
  2483. if (this.previous) {
  2484. this.previous.lock();
  2485. }
  2486. },
  2487.  
  2488. /**
  2489. *
  2490. * Pretty print the workers chain.
  2491. */
  2492. toString : function () {
  2493. var me = "Worker " + this.name;
  2494. if (this.previous) {
  2495. return this.previous + " -> " + me;
  2496. } else {
  2497. return me;
  2498. }
  2499. }
  2500. };
  2501.  
  2502. module.exports = GenericWorker;
  2503.  
  2504. },{}],29:[function(require,module,exports){
  2505. 'use strict';
  2506.  
  2507. var utils = require('../utils');
  2508. var ConvertWorker = require('./ConvertWorker');
  2509. var GenericWorker = require('./GenericWorker');
  2510. var base64 = require('../base64');
  2511. var support = require("../support");
  2512. var external = require("../external");
  2513.  
  2514. var NodejsStreamOutputAdapter = null;
  2515. if (support.nodestream) {
  2516. try {
  2517. NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter');
  2518. } catch(e) {}
  2519. }
  2520.  
  2521. /**
  2522. * Apply the final transformation of the data. If the user wants a Blob for
  2523. * example, it's easier to work with an U8intArray and finally do the
  2524. * ArrayBuffer/Blob conversion.
  2525. * @param {String} type the name of the final type
  2526. * @param {String|Uint8Array|Buffer} content the content to transform
  2527. * @param {String} mimeType the mime type of the content, if applicable.
  2528. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
  2529. */
  2530. function transformZipOutput(type, content, mimeType) {
  2531. switch(type) {
  2532. case "blob" :
  2533. return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType);
  2534. case "base64" :
  2535. return base64.encode(content);
  2536. default :
  2537. return utils.transformTo(type, content);
  2538. }
  2539. }
  2540.  
  2541. /**
  2542. * Concatenate an array of data of the given type.
  2543. * @param {String} type the type of the data in the given array.
  2544. * @param {Array} dataArray the array containing the data chunks to concatenate
  2545. * @return {String|Uint8Array|Buffer} the concatenated data
  2546. * @throws Error if the asked type is unsupported
  2547. */
  2548. function concat (type, dataArray) {
  2549. var i, index = 0, res = null, totalLength = 0;
  2550. for(i = 0; i < dataArray.length; i++) {
  2551. totalLength += dataArray[i].length;
  2552. }
  2553. switch(type) {
  2554. case "string":
  2555. return dataArray.join("");
  2556. case "array":
  2557. return Array.prototype.concat.apply([], dataArray);
  2558. case "uint8array":
  2559. res = new Uint8Array(totalLength);
  2560. for(i = 0; i < dataArray.length; i++) {
  2561. res.set(dataArray[i], index);
  2562. index += dataArray[i].length;
  2563. }
  2564. return res;
  2565. case "nodebuffer":
  2566. return Buffer.concat(dataArray);
  2567. default:
  2568. throw new Error("concat : unsupported type '" + type + "'");
  2569. }
  2570. }
  2571.  
  2572. /**
  2573. * Listen a StreamHelper, accumulate its content and concatenate it into a
  2574. * complete block.
  2575. * @param {StreamHelper} helper the helper to use.
  2576. * @param {Function} updateCallback a callback called on each update. Called
  2577. * with one arg :
  2578. * - the metadata linked to the update received.
  2579. * @return Promise the promise for the accumulation.
  2580. */
  2581. function accumulate(helper, updateCallback) {
  2582. return new external.Promise(function (resolve, reject){
  2583. var dataArray = [];
  2584. var chunkType = helper._internalType,
  2585. resultType = helper._outputType,
  2586. mimeType = helper._mimeType;
  2587. helper
  2588. .on('data', function (data, meta) {
  2589. dataArray.push(data);
  2590. if(updateCallback) {
  2591. updateCallback(meta);
  2592. }
  2593. })
  2594. .on('error', function(err) {
  2595. dataArray = [];
  2596. reject(err);
  2597. })
  2598. .on('end', function (){
  2599. try {
  2600. var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);
  2601. resolve(result);
  2602. } catch (e) {
  2603. reject(e);
  2604. }
  2605. dataArray = [];
  2606. })
  2607. .resume();
  2608. });
  2609. }
  2610.  
  2611. /**
  2612. * An helper to easily use workers outside of JSZip.
  2613. * @constructor
  2614. * @param {Worker} worker the worker to wrap
  2615. * @param {String} outputType the type of data expected by the use
  2616. * @param {String} mimeType the mime type of the content, if applicable.
  2617. */
  2618. function StreamHelper(worker, outputType, mimeType) {
  2619. var internalType = outputType;
  2620. switch(outputType) {
  2621. case "blob":
  2622. case "arraybuffer":
  2623. internalType = "uint8array";
  2624. break;
  2625. case "base64":
  2626. internalType = "string";
  2627. break;
  2628. }
  2629.  
  2630. try {
  2631. // the type used internally
  2632. this._internalType = internalType;
  2633. // the type used to output results
  2634. this._outputType = outputType;
  2635. // the mime type
  2636. this._mimeType = mimeType;
  2637. utils.checkSupport(internalType);
  2638. this._worker = worker.pipe(new ConvertWorker(internalType));
  2639. // the last workers can be rewired without issues but we need to
  2640. // prevent any updates on previous workers.
  2641. worker.lock();
  2642. } catch(e) {
  2643. this._worker = new GenericWorker("error");
  2644. this._worker.error(e);
  2645. }
  2646. }
  2647.  
  2648. StreamHelper.prototype = {
  2649. /**
  2650. * Listen a StreamHelper, accumulate its content and concatenate it into a
  2651. * complete block.
  2652. * @param {Function} updateCb the update callback.
  2653. * @return Promise the promise for the accumulation.
  2654. */
  2655. accumulate : function (updateCb) {
  2656. return accumulate(this, updateCb);
  2657. },
  2658. /**
  2659. * Add a listener on an event triggered on a stream.
  2660. * @param {String} evt the name of the event
  2661. * @param {Function} fn the listener
  2662. * @return {StreamHelper} the current helper.
  2663. */
  2664. on : function (evt, fn) {
  2665. var self = this;
  2666.  
  2667. if(evt === "data") {
  2668. this._worker.on(evt, function (chunk) {
  2669. fn.call(self, chunk.data, chunk.meta);
  2670. });
  2671. } else {
  2672. this._worker.on(evt, function () {
  2673. utils.delay(fn, arguments, self);
  2674. });
  2675. }
  2676. return this;
  2677. },
  2678. /**
  2679. * Resume the flow of chunks.
  2680. * @return {StreamHelper} the current helper.
  2681. */
  2682. resume : function () {
  2683. utils.delay(this._worker.resume, [], this._worker);
  2684. return this;
  2685. },
  2686. /**
  2687. * Pause the flow of chunks.
  2688. * @return {StreamHelper} the current helper.
  2689. */
  2690. pause : function () {
  2691. this._worker.pause();
  2692. return this;
  2693. },
  2694. /**
  2695. * Return a nodejs stream for this helper.
  2696. * @param {Function} updateCb the update callback.
  2697. * @return {NodejsStreamOutputAdapter} the nodejs stream.
  2698. */
  2699. toNodejsStream : function (updateCb) {
  2700. utils.checkSupport("nodestream");
  2701. if (this._outputType !== "nodebuffer") {
  2702. // an object stream containing blob/arraybuffer/uint8array/string
  2703. // is strange and I don't know if it would be useful.
  2704. // I you find this comment and have a good usecase, please open a
  2705. // bug report !
  2706. throw new Error(this._outputType + " is not supported by this method");
  2707. }
  2708.  
  2709. return new NodejsStreamOutputAdapter(this, {
  2710. objectMode : this._outputType !== "nodebuffer"
  2711. }, updateCb);
  2712. }
  2713. };
  2714.  
  2715.  
  2716. module.exports = StreamHelper;
  2717.  
  2718. },{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){
  2719. 'use strict';
  2720.  
  2721. exports.base64 = true;
  2722. exports.array = true;
  2723. exports.string = true;
  2724. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  2725. exports.nodebuffer = typeof Buffer !== "undefined";
  2726. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  2727. exports.uint8array = typeof Uint8Array !== "undefined";
  2728.  
  2729. if (typeof ArrayBuffer === "undefined") {
  2730. exports.blob = false;
  2731. }
  2732. else {
  2733. var buffer = new ArrayBuffer(0);
  2734. try {
  2735. exports.blob = new Blob([buffer], {
  2736. type: "application/zip"
  2737. }).size === 0;
  2738. }
  2739. catch (e) {
  2740. try {
  2741. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  2742. var builder = new Builder();
  2743. builder.append(buffer);
  2744. exports.blob = builder.getBlob('application/zip').size === 0;
  2745. }
  2746. catch (e) {
  2747. exports.blob = false;
  2748. }
  2749. }
  2750. }
  2751.  
  2752. try {
  2753. exports.nodestream = !!require('readable-stream').Readable;
  2754. } catch(e) {
  2755. exports.nodestream = false;
  2756. }
  2757.  
  2758. },{"readable-stream":16}],31:[function(require,module,exports){
  2759. 'use strict';
  2760.  
  2761. var utils = require('./utils');
  2762. var support = require('./support');
  2763. var nodejsUtils = require('./nodejsUtils');
  2764. var GenericWorker = require('./stream/GenericWorker');
  2765.  
  2766. /**
  2767. * The following functions come from pako, from pako/lib/utils/strings
  2768. * released under the MIT license, see pako https://github.com/nodeca/pako/
  2769. */
  2770.  
  2771. // Table with utf8 lengths (calculated by first byte of sequence)
  2772. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  2773. // because max possible codepoint is 0x10ffff
  2774. var _utf8len = new Array(256);
  2775. for (var i=0; i<256; i++) {
  2776. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  2777. }
  2778. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  2779.  
  2780. // convert string to array (typed, when possible)
  2781. var string2buf = function (str) {
  2782. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  2783.  
  2784. // count binary size
  2785. for (m_pos = 0; m_pos < str_len; m_pos++) {
  2786. c = str.charCodeAt(m_pos);
  2787. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2788. c2 = str.charCodeAt(m_pos+1);
  2789. if ((c2 & 0xfc00) === 0xdc00) {
  2790. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2791. m_pos++;
  2792. }
  2793. }
  2794. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  2795. }
  2796.  
  2797. // allocate buffer
  2798. if (support.uint8array) {
  2799. buf = new Uint8Array(buf_len);
  2800. } else {
  2801. buf = new Array(buf_len);
  2802. }
  2803.  
  2804. // convert
  2805. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  2806. c = str.charCodeAt(m_pos);
  2807. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2808. c2 = str.charCodeAt(m_pos+1);
  2809. if ((c2 & 0xfc00) === 0xdc00) {
  2810. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2811. m_pos++;
  2812. }
  2813. }
  2814. if (c < 0x80) {
  2815. /* one byte */
  2816. buf[i++] = c;
  2817. } else if (c < 0x800) {
  2818. /* two bytes */
  2819. buf[i++] = 0xC0 | (c >>> 6);
  2820. buf[i++] = 0x80 | (c & 0x3f);
  2821. } else if (c < 0x10000) {
  2822. /* three bytes */
  2823. buf[i++] = 0xE0 | (c >>> 12);
  2824. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2825. buf[i++] = 0x80 | (c & 0x3f);
  2826. } else {
  2827. /* four bytes */
  2828. buf[i++] = 0xf0 | (c >>> 18);
  2829. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  2830. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2831. buf[i++] = 0x80 | (c & 0x3f);
  2832. }
  2833. }
  2834.  
  2835. return buf;
  2836. };
  2837.  
  2838. // Calculate max possible position in utf8 buffer,
  2839. // that will not break sequence. If that's not possible
  2840. // - (very small limits) return max size as is.
  2841. //
  2842. // buf[] - utf8 bytes array
  2843. // max - length limit (mandatory);
  2844. var utf8border = function(buf, max) {
  2845. var pos;
  2846.  
  2847. max = max || buf.length;
  2848. if (max > buf.length) { max = buf.length; }
  2849.  
  2850. // go back from last position, until start of sequence found
  2851. pos = max-1;
  2852. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  2853.  
  2854. // Fuckup - very small and broken sequence,
  2855. // return max, because we should return something anyway.
  2856. if (pos < 0) { return max; }
  2857.  
  2858. // If we came to start of buffer - that means vuffer is too small,
  2859. // return max too.
  2860. if (pos === 0) { return max; }
  2861.  
  2862. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  2863. };
  2864.  
  2865. // convert array to string
  2866. var buf2string = function (buf) {
  2867. var str, i, out, c, c_len;
  2868. var len = buf.length;
  2869.  
  2870. // Reserve max possible length (2 words per char)
  2871. // NB: by unknown reasons, Array is significantly faster for
  2872. // String.fromCharCode.apply than Uint16Array.
  2873. var utf16buf = new Array(len*2);
  2874.  
  2875. for (out=0, i=0; i<len;) {
  2876. c = buf[i++];
  2877. // quick process ascii
  2878. if (c < 0x80) { utf16buf[out++] = c; continue; }
  2879.  
  2880. c_len = _utf8len[c];
  2881. // skip 5 & 6 byte codes
  2882. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  2883.  
  2884. // apply mask on first byte
  2885. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  2886. // join the rest
  2887. while (c_len > 1 && i < len) {
  2888. c = (c << 6) | (buf[i++] & 0x3f);
  2889. c_len--;
  2890. }
  2891.  
  2892. // terminated by end of string?
  2893. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  2894.  
  2895. if (c < 0x10000) {
  2896. utf16buf[out++] = c;
  2897. } else {
  2898. c -= 0x10000;
  2899. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  2900. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  2901. }
  2902. }
  2903.  
  2904. // shrinkBuf(utf16buf, out)
  2905. if (utf16buf.length !== out) {
  2906. if(utf16buf.subarray) {
  2907. utf16buf = utf16buf.subarray(0, out);
  2908. } else {
  2909. utf16buf.length = out;
  2910. }
  2911. }
  2912.  
  2913. // return String.fromCharCode.apply(null, utf16buf);
  2914. return utils.applyFromCharCode(utf16buf);
  2915. };
  2916.  
  2917.  
  2918. // That's all for the pako functions.
  2919.  
  2920.  
  2921. /**
  2922. * Transform a javascript string into an array (typed if possible) of bytes,
  2923. * UTF-8 encoded.
  2924. * @param {String} str the string to encode
  2925. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  2926. */
  2927. exports.utf8encode = function utf8encode(str) {
  2928. if (support.nodebuffer) {
  2929. return nodejsUtils.newBufferFrom(str, "utf-8");
  2930. }
  2931.  
  2932. return string2buf(str);
  2933. };
  2934.  
  2935.  
  2936. /**
  2937. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  2938. * string into a javascript string.
  2939. * @param {Array|Uint8Array|Buffer} buf the data de decode
  2940. * @return {String} the decoded string.
  2941. */
  2942. exports.utf8decode = function utf8decode(buf) {
  2943. if (support.nodebuffer) {
  2944. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  2945. }
  2946.  
  2947. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  2948.  
  2949. return buf2string(buf);
  2950. };
  2951.  
  2952. /**
  2953. * A worker to decode utf8 encoded binary chunks into string chunks.
  2954. * @constructor
  2955. */
  2956. function Utf8DecodeWorker() {
  2957. GenericWorker.call(this, "utf-8 decode");
  2958. // the last bytes if a chunk didn't end with a complete codepoint.
  2959. this.leftOver = null;
  2960. }
  2961. utils.inherits(Utf8DecodeWorker, GenericWorker);
  2962.  
  2963. /**
  2964. * @see GenericWorker.processChunk
  2965. */
  2966. Utf8DecodeWorker.prototype.processChunk = function (chunk) {
  2967.  
  2968. var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
  2969.  
  2970. // 1st step, re-use what's left of the previous chunk
  2971. if (this.leftOver && this.leftOver.length) {
  2972. if(support.uint8array) {
  2973. var previousData = data;
  2974. data = new Uint8Array(previousData.length + this.leftOver.length);
  2975. data.set(this.leftOver, 0);
  2976. data.set(previousData, this.leftOver.length);
  2977. } else {
  2978. data = this.leftOver.concat(data);
  2979. }
  2980. this.leftOver = null;
  2981. }
  2982.  
  2983. var nextBoundary = utf8border(data);
  2984. var usableData = data;
  2985. if (nextBoundary !== data.length) {
  2986. if (support.uint8array) {
  2987. usableData = data.subarray(0, nextBoundary);
  2988. this.leftOver = data.subarray(nextBoundary, data.length);
  2989. } else {
  2990. usableData = data.slice(0, nextBoundary);
  2991. this.leftOver = data.slice(nextBoundary, data.length);
  2992. }
  2993. }
  2994.  
  2995. this.push({
  2996. data : exports.utf8decode(usableData),
  2997. meta : chunk.meta
  2998. });
  2999. };
  3000.  
  3001. /**
  3002. * @see GenericWorker.flush
  3003. */
  3004. Utf8DecodeWorker.prototype.flush = function () {
  3005. if(this.leftOver && this.leftOver.length) {
  3006. this.push({
  3007. data : exports.utf8decode(this.leftOver),
  3008. meta : {}
  3009. });
  3010. this.leftOver = null;
  3011. }
  3012. };
  3013. exports.Utf8DecodeWorker = Utf8DecodeWorker;
  3014.  
  3015. /**
  3016. * A worker to endcode string chunks into utf8 encoded binary chunks.
  3017. * @constructor
  3018. */
  3019. function Utf8EncodeWorker() {
  3020. GenericWorker.call(this, "utf-8 encode");
  3021. }
  3022. utils.inherits(Utf8EncodeWorker, GenericWorker);
  3023.  
  3024. /**
  3025. * @see GenericWorker.processChunk
  3026. */
  3027. Utf8EncodeWorker.prototype.processChunk = function (chunk) {
  3028. this.push({
  3029. data : exports.utf8encode(chunk.data),
  3030. meta : chunk.meta
  3031. });
  3032. };
  3033. exports.Utf8EncodeWorker = Utf8EncodeWorker;
  3034.  
  3035. },{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){
  3036. 'use strict';
  3037.  
  3038. var support = require('./support');
  3039. var base64 = require('./base64');
  3040. var nodejsUtils = require('./nodejsUtils');
  3041. var setImmediate = require('set-immediate-shim');
  3042. var external = require("./external");
  3043.  
  3044.  
  3045. /**
  3046. * Convert a string that pass as a "binary string": it should represent a byte
  3047. * array but may have > 255 char codes. Be sure to take only the first byte
  3048. * and returns the byte array.
  3049. * @param {String} str the string to transform.
  3050. * @return {Array|Uint8Array} the string in a binary format.
  3051. */
  3052. function string2binary(str) {
  3053. var result = null;
  3054. if (support.uint8array) {
  3055. result = new Uint8Array(str.length);
  3056. } else {
  3057. result = new Array(str.length);
  3058. }
  3059. return stringToArrayLike(str, result);
  3060. }
  3061.  
  3062. /**
  3063. * Create a new blob with the given content and the given type.
  3064. * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use
  3065. * an Uint8Array because the stock browser of android 4 won't accept it (it
  3066. * will be silently converted to a string, "[object Uint8Array]").
  3067. *
  3068. * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:
  3069. * when a large amount of Array is used to create the Blob, the amount of
  3070. * memory consumed is nearly 100 times the original data amount.
  3071. *
  3072. * @param {String} type the mime type of the blob.
  3073. * @return {Blob} the created blob.
  3074. */
  3075. exports.newBlob = function(part, type) {
  3076. exports.checkSupport("blob");
  3077.  
  3078. try {
  3079. // Blob constructor
  3080. return new Blob([part], {
  3081. type: type
  3082. });
  3083. }
  3084. catch (e) {
  3085.  
  3086. try {
  3087. // deprecated, browser only, old way
  3088. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  3089. var builder = new Builder();
  3090. builder.append(part);
  3091. return builder.getBlob(type);
  3092. }
  3093. catch (e) {
  3094.  
  3095. // well, fuck ?!
  3096. throw new Error("Bug : can't construct the Blob.");
  3097. }
  3098. }
  3099.  
  3100.  
  3101. };
  3102. /**
  3103. * The identity function.
  3104. * @param {Object} input the input.
  3105. * @return {Object} the same input.
  3106. */
  3107. function identity(input) {
  3108. return input;
  3109. }
  3110.  
  3111. /**
  3112. * Fill in an array with a string.
  3113. * @param {String} str the string to use.
  3114. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  3115. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  3116. */
  3117. function stringToArrayLike(str, array) {
  3118. for (var i = 0; i < str.length; ++i) {
  3119. array[i] = str.charCodeAt(i) & 0xFF;
  3120. }
  3121. return array;
  3122. }
  3123.  
  3124. /**
  3125. * An helper for the function arrayLikeToString.
  3126. * This contains static information and functions that
  3127. * can be optimized by the browser JIT compiler.
  3128. */
  3129. var arrayToStringHelper = {
  3130. /**
  3131. * Transform an array of int into a string, chunk by chunk.
  3132. * See the performances notes on arrayLikeToString.
  3133. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3134. * @param {String} type the type of the array.
  3135. * @param {Integer} chunk the chunk size.
  3136. * @return {String} the resulting string.
  3137. * @throws Error if the chunk is too big for the stack.
  3138. */
  3139. stringifyByChunk: function(array, type, chunk) {
  3140. var result = [], k = 0, len = array.length;
  3141. // shortcut
  3142. if (len <= chunk) {
  3143. return String.fromCharCode.apply(null, array);
  3144. }
  3145. while (k < len) {
  3146. if (type === "array" || type === "nodebuffer") {
  3147. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  3148. }
  3149. else {
  3150. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  3151. }
  3152. k += chunk;
  3153. }
  3154. return result.join("");
  3155. },
  3156. /**
  3157. * Call String.fromCharCode on every item in the array.
  3158. * This is the naive implementation, which generate A LOT of intermediate string.
  3159. * This should be used when everything else fail.
  3160. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3161. * @return {String} the result.
  3162. */
  3163. stringifyByChar: function(array){
  3164. var resultStr = "";
  3165. for(var i = 0; i < array.length; i++) {
  3166. resultStr += String.fromCharCode(array[i]);
  3167. }
  3168. return resultStr;
  3169. },
  3170. applyCanBeUsed : {
  3171. /**
  3172. * true if the browser accepts to use String.fromCharCode on Uint8Array
  3173. */
  3174. uint8array : (function () {
  3175. try {
  3176. return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
  3177. } catch (e) {
  3178. return false;
  3179. }
  3180. })(),
  3181. /**
  3182. * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
  3183. */
  3184. nodebuffer : (function () {
  3185. try {
  3186. return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;
  3187. } catch (e) {
  3188. return false;
  3189. }
  3190. })()
  3191. }
  3192. };
  3193.  
  3194. /**
  3195. * Transform an array-like object to a string.
  3196. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3197. * @return {String} the result.
  3198. */
  3199. function arrayLikeToString(array) {
  3200. // Performances notes :
  3201. // --------------------
  3202. // String.fromCharCode.apply(null, array) is the fastest, see
  3203. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  3204. // but the stack is limited (and we can get huge arrays !).
  3205. //
  3206. // result += String.fromCharCode(array[i]); generate too many strings !
  3207. //
  3208. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  3209. // TODO : we now have workers that split the work. Do we still need that ?
  3210. var chunk = 65536,
  3211. type = exports.getTypeOf(array),
  3212. canUseApply = true;
  3213. if (type === "uint8array") {
  3214. canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
  3215. } else if (type === "nodebuffer") {
  3216. canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
  3217. }
  3218.  
  3219. if (canUseApply) {
  3220. while (chunk > 1) {
  3221. try {
  3222. return arrayToStringHelper.stringifyByChunk(array, type, chunk);
  3223. } catch (e) {
  3224. chunk = Math.floor(chunk / 2);
  3225. }
  3226. }
  3227. }
  3228.  
  3229. // no apply or chunk error : slow and painful algorithm
  3230. // default browser on android 4.*
  3231. return arrayToStringHelper.stringifyByChar(array);
  3232. }
  3233.  
  3234. exports.applyFromCharCode = arrayLikeToString;
  3235.  
  3236.  
  3237. /**
  3238. * Copy the data from an array-like to an other array-like.
  3239. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  3240. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  3241. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  3242. */
  3243. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  3244. for (var i = 0; i < arrayFrom.length; i++) {
  3245. arrayTo[i] = arrayFrom[i];
  3246. }
  3247. return arrayTo;
  3248. }
  3249.  
  3250. // a matrix containing functions to transform everything into everything.
  3251. var transform = {};
  3252.  
  3253. // string to ?
  3254. transform["string"] = {
  3255. "string": identity,
  3256. "array": function(input) {
  3257. return stringToArrayLike(input, new Array(input.length));
  3258. },
  3259. "arraybuffer": function(input) {
  3260. return transform["string"]["uint8array"](input).buffer;
  3261. },
  3262. "uint8array": function(input) {
  3263. return stringToArrayLike(input, new Uint8Array(input.length));
  3264. },
  3265. "nodebuffer": function(input) {
  3266. return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));
  3267. }
  3268. };
  3269.  
  3270. // array to ?
  3271. transform["array"] = {
  3272. "string": arrayLikeToString,
  3273. "array": identity,
  3274. "arraybuffer": function(input) {
  3275. return (new Uint8Array(input)).buffer;
  3276. },
  3277. "uint8array": function(input) {
  3278. return new Uint8Array(input);
  3279. },
  3280. "nodebuffer": function(input) {
  3281. return nodejsUtils.newBufferFrom(input);
  3282. }
  3283. };
  3284.  
  3285. // arraybuffer to ?
  3286. transform["arraybuffer"] = {
  3287. "string": function(input) {
  3288. return arrayLikeToString(new Uint8Array(input));
  3289. },
  3290. "array": function(input) {
  3291. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  3292. },
  3293. "arraybuffer": identity,
  3294. "uint8array": function(input) {
  3295. return new Uint8Array(input);
  3296. },
  3297. "nodebuffer": function(input) {
  3298. return nodejsUtils.newBufferFrom(new Uint8Array(input));
  3299. }
  3300. };
  3301.  
  3302. // uint8array to ?
  3303. transform["uint8array"] = {
  3304. "string": arrayLikeToString,
  3305. "array": function(input) {
  3306. return arrayLikeToArrayLike(input, new Array(input.length));
  3307. },
  3308. "arraybuffer": function(input) {
  3309. return input.buffer;
  3310. },
  3311. "uint8array": identity,
  3312. "nodebuffer": function(input) {
  3313. return nodejsUtils.newBufferFrom(input);
  3314. }
  3315. };
  3316.  
  3317. // nodebuffer to ?
  3318. transform["nodebuffer"] = {
  3319. "string": arrayLikeToString,
  3320. "array": function(input) {
  3321. return arrayLikeToArrayLike(input, new Array(input.length));
  3322. },
  3323. "arraybuffer": function(input) {
  3324. return transform["nodebuffer"]["uint8array"](input).buffer;
  3325. },
  3326. "uint8array": function(input) {
  3327. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  3328. },
  3329. "nodebuffer": identity
  3330. };
  3331.  
  3332. /**
  3333. * Transform an input into any type.
  3334. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  3335. * If no output type is specified, the unmodified input will be returned.
  3336. * @param {String} outputType the output type.
  3337. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  3338. * @throws {Error} an Error if the browser doesn't support the requested output type.
  3339. */
  3340. exports.transformTo = function(outputType, input) {
  3341. if (!input) {
  3342. // undefined, null, etc
  3343. // an empty string won't harm.
  3344. input = "";
  3345. }
  3346. if (!outputType) {
  3347. return input;
  3348. }
  3349. exports.checkSupport(outputType);
  3350. var inputType = exports.getTypeOf(input);
  3351. var result = transform[inputType][outputType](input);
  3352. return result;
  3353. };
  3354.  
  3355. /**
  3356. * Return the type of the input.
  3357. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  3358. * @param {Object} input the input to identify.
  3359. * @return {String} the (lowercase) type of the input.
  3360. */
  3361. exports.getTypeOf = function(input) {
  3362. if (typeof input === "string") {
  3363. return "string";
  3364. }
  3365. if (Object.prototype.toString.call(input) === "[object Array]") {
  3366. return "array";
  3367. }
  3368. if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
  3369. return "nodebuffer";
  3370. }
  3371. if (support.uint8array && input instanceof Uint8Array) {
  3372. return "uint8array";
  3373. }
  3374. if (support.arraybuffer && input instanceof ArrayBuffer) {
  3375. return "arraybuffer";
  3376. }
  3377. };
  3378.  
  3379. /**
  3380. * Throw an exception if the type is not supported.
  3381. * @param {String} type the type to check.
  3382. * @throws {Error} an Error if the browser doesn't support the requested type.
  3383. */
  3384. exports.checkSupport = function(type) {
  3385. var supported = support[type.toLowerCase()];
  3386. if (!supported) {
  3387. throw new Error(type + " is not supported by this platform");
  3388. }
  3389. };
  3390.  
  3391. exports.MAX_VALUE_16BITS = 65535;
  3392. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  3393.  
  3394. /**
  3395. * Prettify a string read as binary.
  3396. * @param {string} str the string to prettify.
  3397. * @return {string} a pretty string.
  3398. */
  3399. exports.pretty = function(str) {
  3400. var res = '',
  3401. code, i;
  3402. for (i = 0; i < (str || "").length; i++) {
  3403. code = str.charCodeAt(i);
  3404. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  3405. }
  3406. return res;
  3407. };
  3408.  
  3409. /**
  3410. * Defer the call of a function.
  3411. * @param {Function} callback the function to call asynchronously.
  3412. * @param {Array} args the arguments to give to the callback.
  3413. */
  3414. exports.delay = function(callback, args, self) {
  3415. setImmediate(function () {
  3416. callback.apply(self || null, args || []);
  3417. });
  3418. };
  3419.  
  3420. /**
  3421. * Extends a prototype with an other, without calling a constructor with
  3422. * side effects. Inspired by nodejs' `utils.inherits`
  3423. * @param {Function} ctor the constructor to augment
  3424. * @param {Function} superCtor the parent constructor to use
  3425. */
  3426. exports.inherits = function (ctor, superCtor) {
  3427. var Obj = function() {};
  3428. Obj.prototype = superCtor.prototype;
  3429. ctor.prototype = new Obj();
  3430. };
  3431.  
  3432. /**
  3433. * Merge the objects passed as parameters into a new one.
  3434. * @private
  3435. * @param {...Object} var_args All objects to merge.
  3436. * @return {Object} a new object with the data of the others.
  3437. */
  3438. exports.extend = function() {
  3439. var result = {}, i, attr;
  3440. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  3441. for (attr in arguments[i]) {
  3442. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  3443. result[attr] = arguments[i][attr];
  3444. }
  3445. }
  3446. }
  3447. return result;
  3448. };
  3449.  
  3450. /**
  3451. * Transform arbitrary content into a Promise.
  3452. * @param {String} name a name for the content being processed.
  3453. * @param {Object} inputData the content to process.
  3454. * @param {Boolean} isBinary true if the content is not an unicode string
  3455. * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
  3456. * @param {Boolean} isBase64 true if the string content is encoded with base64.
  3457. * @return {Promise} a promise in a format usable by JSZip.
  3458. */
  3459. exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
  3460.  
  3461. // if inputData is already a promise, this flatten it.
  3462. var promise = external.Promise.resolve(inputData).then(function(data) {
  3463. var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);
  3464.  
  3465. if (isBlob && typeof FileReader !== "undefined") {
  3466. return new external.Promise(function (resolve, reject) {
  3467. var reader = new FileReader();
  3468.  
  3469. reader.onload = function(e) {
  3470. resolve(e.target.result);
  3471. };
  3472. reader.onerror = function(e) {
  3473. reject(e.target.error);
  3474. };
  3475. reader.readAsArrayBuffer(data);
  3476. });
  3477. } else {
  3478. return data;
  3479. }
  3480. });
  3481.  
  3482. return promise.then(function(data) {
  3483. var dataType = exports.getTypeOf(data);
  3484.  
  3485. if (!dataType) {
  3486. return external.Promise.reject(
  3487. new Error("Can't read the data of '" + name + "'. Is it " +
  3488. "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")
  3489. );
  3490. }
  3491. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  3492. if (dataType === "arraybuffer") {
  3493. data = exports.transformTo("uint8array", data);
  3494. } else if (dataType === "string") {
  3495. if (isBase64) {
  3496. data = base64.decode(data);
  3497. }
  3498. else if (isBinary) {
  3499. // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
  3500. if (isOptimizedBinaryString !== true) {
  3501. // this is a string, not in a base64 format.
  3502. // Be sure that this is a correct "binary string"
  3503. data = string2binary(data);
  3504. }
  3505. }
  3506. }
  3507. return data;
  3508. });
  3509. };
  3510.  
  3511. },{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"set-immediate-shim":54}],33:[function(require,module,exports){
  3512. 'use strict';
  3513. var readerFor = require('./reader/readerFor');
  3514. var utils = require('./utils');
  3515. var sig = require('./signature');
  3516. var ZipEntry = require('./zipEntry');
  3517. var utf8 = require('./utf8');
  3518. var support = require('./support');
  3519. // class ZipEntries {{{
  3520. /**
  3521. * All the entries in the zip file.
  3522. * @constructor
  3523. * @param {Object} loadOptions Options for loading the stream.
  3524. */
  3525. function ZipEntries(loadOptions) {
  3526. this.files = [];
  3527. this.loadOptions = loadOptions;
  3528. }
  3529. ZipEntries.prototype = {
  3530. /**
  3531. * Check that the reader is on the specified signature.
  3532. * @param {string} expectedSignature the expected signature.
  3533. * @throws {Error} if it is an other signature.
  3534. */
  3535. checkSignature: function(expectedSignature) {
  3536. if (!this.reader.readAndCheckSignature(expectedSignature)) {
  3537. this.reader.index -= 4;
  3538. var signature = this.reader.readString(4);
  3539. throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  3540. }
  3541. },
  3542. /**
  3543. * Check if the given signature is at the given index.
  3544. * @param {number} askedIndex the index to check.
  3545. * @param {string} expectedSignature the signature to expect.
  3546. * @return {boolean} true if the signature is here, false otherwise.
  3547. */
  3548. isSignature: function(askedIndex, expectedSignature) {
  3549. var currentIndex = this.reader.index;
  3550. this.reader.setIndex(askedIndex);
  3551. var signature = this.reader.readString(4);
  3552. var result = signature === expectedSignature;
  3553. this.reader.setIndex(currentIndex);
  3554. return result;
  3555. },
  3556. /**
  3557. * Read the end of the central directory.
  3558. */
  3559. readBlockEndOfCentral: function() {
  3560. this.diskNumber = this.reader.readInt(2);
  3561. this.diskWithCentralDirStart = this.reader.readInt(2);
  3562. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  3563. this.centralDirRecords = this.reader.readInt(2);
  3564. this.centralDirSize = this.reader.readInt(4);
  3565. this.centralDirOffset = this.reader.readInt(4);
  3566.  
  3567. this.zipCommentLength = this.reader.readInt(2);
  3568. // warning : the encoding depends of the system locale
  3569. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  3570. // On a windows machine, this field is encoded with the localized windows code page.
  3571. var zipComment = this.reader.readData(this.zipCommentLength);
  3572. var decodeParamType = support.uint8array ? "uint8array" : "array";
  3573. // To get consistent behavior with the generation part, we will assume that
  3574. // this is utf8 encoded unless specified otherwise.
  3575. var decodeContent = utils.transformTo(decodeParamType, zipComment);
  3576. this.zipComment = this.loadOptions.decodeFileName(decodeContent);
  3577. },
  3578. /**
  3579. * Read the end of the Zip 64 central directory.
  3580. * Not merged with the method readEndOfCentral :
  3581. * The end of central can coexist with its Zip64 brother,
  3582. * I don't want to read the wrong number of bytes !
  3583. */
  3584. readBlockZip64EndOfCentral: function() {
  3585. this.zip64EndOfCentralSize = this.reader.readInt(8);
  3586. this.reader.skip(4);
  3587. // this.versionMadeBy = this.reader.readString(2);
  3588. // this.versionNeeded = this.reader.readInt(2);
  3589. this.diskNumber = this.reader.readInt(4);
  3590. this.diskWithCentralDirStart = this.reader.readInt(4);
  3591. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  3592. this.centralDirRecords = this.reader.readInt(8);
  3593. this.centralDirSize = this.reader.readInt(8);
  3594. this.centralDirOffset = this.reader.readInt(8);
  3595.  
  3596. this.zip64ExtensibleData = {};
  3597. var extraDataSize = this.zip64EndOfCentralSize - 44,
  3598. index = 0,
  3599. extraFieldId,
  3600. extraFieldLength,
  3601. extraFieldValue;
  3602. while (index < extraDataSize) {
  3603. extraFieldId = this.reader.readInt(2);
  3604. extraFieldLength = this.reader.readInt(4);
  3605. extraFieldValue = this.reader.readData(extraFieldLength);
  3606. this.zip64ExtensibleData[extraFieldId] = {
  3607. id: extraFieldId,
  3608. length: extraFieldLength,
  3609. value: extraFieldValue
  3610. };
  3611. }
  3612. },
  3613. /**
  3614. * Read the end of the Zip 64 central directory locator.
  3615. */
  3616. readBlockZip64EndOfCentralLocator: function() {
  3617. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  3618. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  3619. this.disksCount = this.reader.readInt(4);
  3620. if (this.disksCount > 1) {
  3621. throw new Error("Multi-volumes zip are not supported");
  3622. }
  3623. },
  3624. /**
  3625. * Read the local files, based on the offset read in the central part.
  3626. */
  3627. readLocalFiles: function() {
  3628. var i, file;
  3629. for (i = 0; i < this.files.length; i++) {
  3630. file = this.files[i];
  3631. this.reader.setIndex(file.localHeaderOffset);
  3632. this.checkSignature(sig.LOCAL_FILE_HEADER);
  3633. file.readLocalPart(this.reader);
  3634. file.handleUTF8();
  3635. file.processAttributes();
  3636. }
  3637. },
  3638. /**
  3639. * Read the central directory.
  3640. */
  3641. readCentralDir: function() {
  3642. var file;
  3643.  
  3644. this.reader.setIndex(this.centralDirOffset);
  3645. while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
  3646. file = new ZipEntry({
  3647. zip64: this.zip64
  3648. }, this.loadOptions);
  3649. file.readCentralPart(this.reader);
  3650. this.files.push(file);
  3651. }
  3652.  
  3653. if (this.centralDirRecords !== this.files.length) {
  3654. if (this.centralDirRecords !== 0 && this.files.length === 0) {
  3655. // We expected some records but couldn't find ANY.
  3656. // This is really suspicious, as if something went wrong.
  3657. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  3658. } else {
  3659. // We found some records but not all.
  3660. // Something is wrong but we got something for the user: no error here.
  3661. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
  3662. }
  3663. }
  3664. },
  3665. /**
  3666. * Read the end of central directory.
  3667. */
  3668. readEndOfCentral: function() {
  3669. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  3670. if (offset < 0) {
  3671. // Check if the content is a truncated zip or complete garbage.
  3672. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  3673. // extractible zip for example) but it can give a good hint.
  3674. // If an ajax request was used without responseType, we will also
  3675. // get unreadable data.
  3676. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  3677.  
  3678. if (isGarbage) {
  3679. throw new Error("Can't find end of central directory : is this a zip file ? " +
  3680. "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");
  3681. } else {
  3682. throw new Error("Corrupted zip: can't find end of central directory");
  3683. }
  3684.  
  3685. }
  3686. this.reader.setIndex(offset);
  3687. var endOfCentralDirOffset = offset;
  3688. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  3689. this.readBlockEndOfCentral();
  3690.  
  3691.  
  3692. /* extract from the zip spec :
  3693. 4) If one of the fields in the end of central directory
  3694. record is too small to hold required data, the field
  3695. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  3696. ZIP64 format record should be created.
  3697. 5) The end of central directory record and the
  3698. Zip64 end of central directory locator record must
  3699. reside on the same disk when splitting or spanning
  3700. an archive.
  3701. */
  3702. 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) {
  3703. this.zip64 = true;
  3704.  
  3705. /*
  3706. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  3707. the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents
  3708. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  3709. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  3710. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  3711. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  3712. */
  3713.  
  3714. // should look for a zip64 EOCD locator
  3715. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3716. if (offset < 0) {
  3717. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
  3718. }
  3719. this.reader.setIndex(offset);
  3720. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3721. this.readBlockZip64EndOfCentralLocator();
  3722.  
  3723. // now the zip64 EOCD record
  3724. if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
  3725. // console.warn("ZIP64 end of central directory not where expected.");
  3726. this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3727. if (this.relativeOffsetEndOfZip64CentralDir < 0) {
  3728. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
  3729. }
  3730. }
  3731. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  3732. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3733. this.readBlockZip64EndOfCentral();
  3734. }
  3735.  
  3736. var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
  3737. if (this.zip64) {
  3738. expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
  3739. expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
  3740. }
  3741.  
  3742. var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  3743.  
  3744. if (extraBytes > 0) {
  3745. // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
  3746. if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
  3747. // The offsets seem wrong, but we have something at the specified offset.
  3748. // So… we keep it.
  3749. } else {
  3750. // the offset is wrong, update the "zero" of the reader
  3751. // this happens if data has been prepended (crx files for example)
  3752. this.reader.zero = extraBytes;
  3753. }
  3754. } else if (extraBytes < 0) {
  3755. throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
  3756. }
  3757. },
  3758. prepareReader: function(data) {
  3759. this.reader = readerFor(data);
  3760. },
  3761. /**
  3762. * Read a zip file and create ZipEntries.
  3763. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  3764. */
  3765. load: function(data) {
  3766. this.prepareReader(data);
  3767. this.readEndOfCentral();
  3768. this.readCentralDir();
  3769. this.readLocalFiles();
  3770. }
  3771. };
  3772. // }}} end of ZipEntries
  3773. module.exports = ZipEntries;
  3774.  
  3775. },{"./reader/readerFor":22,"./signature":23,"./support":30,"./utf8":31,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){
  3776. 'use strict';
  3777. var readerFor = require('./reader/readerFor');
  3778. var utils = require('./utils');
  3779. var CompressedObject = require('./compressedObject');
  3780. var crc32fn = require('./crc32');
  3781. var utf8 = require('./utf8');
  3782. var compressions = require('./compressions');
  3783. var support = require('./support');
  3784.  
  3785. var MADE_BY_DOS = 0x00;
  3786. var MADE_BY_UNIX = 0x03;
  3787.  
  3788. /**
  3789. * Find a compression registered in JSZip.
  3790. * @param {string} compressionMethod the method magic to find.
  3791. * @return {Object|null} the JSZip compression object, null if none found.
  3792. */
  3793. var findCompression = function(compressionMethod) {
  3794. for (var method in compressions) {
  3795. if (!compressions.hasOwnProperty(method)) {
  3796. continue;
  3797. }
  3798. if (compressions[method].magic === compressionMethod) {
  3799. return compressions[method];
  3800. }
  3801. }
  3802. return null;
  3803. };
  3804.  
  3805. // class ZipEntry {{{
  3806. /**
  3807. * An entry in the zip file.
  3808. * @constructor
  3809. * @param {Object} options Options of the current file.
  3810. * @param {Object} loadOptions Options for loading the stream.
  3811. */
  3812. function ZipEntry(options, loadOptions) {
  3813. this.options = options;
  3814. this.loadOptions = loadOptions;
  3815. }
  3816. ZipEntry.prototype = {
  3817. /**
  3818. * say if the file is encrypted.
  3819. * @return {boolean} true if the file is encrypted, false otherwise.
  3820. */
  3821. isEncrypted: function() {
  3822. // bit 1 is set
  3823. return (this.bitFlag & 0x0001) === 0x0001;
  3824. },
  3825. /**
  3826. * say if the file has utf-8 filename/comment.
  3827. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  3828. */
  3829. useUTF8: function() {
  3830. // bit 11 is set
  3831. return (this.bitFlag & 0x0800) === 0x0800;
  3832. },
  3833. /**
  3834. * Read the local part of a zip file and add the info in this object.
  3835. * @param {DataReader} reader the reader to use.
  3836. */
  3837. readLocalPart: function(reader) {
  3838. var compression, localExtraFieldsLength;
  3839.  
  3840. // we already know everything from the central dir !
  3841. // If the central dir data are false, we are doomed.
  3842. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  3843. // The less data we get here, the more reliable this should be.
  3844. // Let's skip the whole header and dash to the data !
  3845. reader.skip(22);
  3846. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  3847. // Strangely, the filename here is OK.
  3848. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  3849. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  3850. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  3851. // the internet.
  3852. //
  3853. // I think I see the logic here : the central directory is used to display
  3854. // content and the local directory is used to extract the files. Mixing / and \
  3855. // may be used to display \ to windows users and use / when extracting the files.
  3856. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  3857. this.fileNameLength = reader.readInt(2);
  3858. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  3859. // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
  3860. this.fileName = reader.readData(this.fileNameLength);
  3861. reader.skip(localExtraFieldsLength);
  3862.  
  3863. if (this.compressedSize === -1 || this.uncompressedSize === -1) {
  3864. throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
  3865. }
  3866.  
  3867. compression = findCompression(this.compressionMethod);
  3868. if (compression === null) { // no compression found
  3869. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
  3870. }
  3871. this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
  3872. },
  3873.  
  3874. /**
  3875. * Read the central part of a zip file and add the info in this object.
  3876. * @param {DataReader} reader the reader to use.
  3877. */
  3878. readCentralPart: function(reader) {
  3879. this.versionMadeBy = reader.readInt(2);
  3880. reader.skip(2);
  3881. // this.versionNeeded = reader.readInt(2);
  3882. this.bitFlag = reader.readInt(2);
  3883. this.compressionMethod = reader.readString(2);
  3884. this.date = reader.readDate();
  3885. this.crc32 = reader.readInt(4);
  3886. this.compressedSize = reader.readInt(4);
  3887. this.uncompressedSize = reader.readInt(4);
  3888. var fileNameLength = reader.readInt(2);
  3889. this.extraFieldsLength = reader.readInt(2);
  3890. this.fileCommentLength = reader.readInt(2);
  3891. this.diskNumberStart = reader.readInt(2);
  3892. this.internalFileAttributes = reader.readInt(2);
  3893. this.externalFileAttributes = reader.readInt(4);
  3894. this.localHeaderOffset = reader.readInt(4);
  3895.  
  3896. if (this.isEncrypted()) {
  3897. throw new Error("Encrypted zip are not supported");
  3898. }
  3899.  
  3900. // will be read in the local part, see the comments there
  3901. reader.skip(fileNameLength);
  3902. this.readExtraFields(reader);
  3903. this.parseZIP64ExtraField(reader);
  3904. this.fileComment = reader.readData(this.fileCommentLength);
  3905. },
  3906.  
  3907. /**
  3908. * Parse the external file attributes and get the unix/dos permissions.
  3909. */
  3910. processAttributes: function () {
  3911. this.unixPermissions = null;
  3912. this.dosPermissions = null;
  3913. var madeBy = this.versionMadeBy >> 8;
  3914.  
  3915. // Check if we have the DOS directory flag set.
  3916. // We look for it in the DOS and UNIX permissions
  3917. // but some unknown platform could set it as a compatibility flag.
  3918. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  3919.  
  3920. if(madeBy === MADE_BY_DOS) {
  3921. // first 6 bits (0 to 5)
  3922. this.dosPermissions = this.externalFileAttributes & 0x3F;
  3923. }
  3924.  
  3925. if(madeBy === MADE_BY_UNIX) {
  3926. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  3927. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  3928. }
  3929.  
  3930. // fail safe : if the name ends with a / it probably means a folder
  3931. if (!this.dir && this.fileNameStr.slice(-1) === '/') {
  3932. this.dir = true;
  3933. }
  3934. },
  3935.  
  3936. /**
  3937. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  3938. * @param {DataReader} reader the reader to use.
  3939. */
  3940. parseZIP64ExtraField: function(reader) {
  3941.  
  3942. if (!this.extraFields[0x0001]) {
  3943. return;
  3944. }
  3945.  
  3946. // should be something, preparing the extra reader
  3947. var extraReader = readerFor(this.extraFields[0x0001].value);
  3948.  
  3949. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  3950. // won't let us have more.
  3951. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  3952. this.uncompressedSize = extraReader.readInt(8);
  3953. }
  3954. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  3955. this.compressedSize = extraReader.readInt(8);
  3956. }
  3957. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  3958. this.localHeaderOffset = extraReader.readInt(8);
  3959. }
  3960. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  3961. this.diskNumberStart = extraReader.readInt(4);
  3962. }
  3963. },
  3964. /**
  3965. * Read the central part of a zip file and add the info in this object.
  3966. * @param {DataReader} reader the reader to use.
  3967. */
  3968. readExtraFields: function(reader) {
  3969. var end = reader.index + this.extraFieldsLength,
  3970. extraFieldId,
  3971. extraFieldLength,
  3972. extraFieldValue;
  3973.  
  3974. if (!this.extraFields) {
  3975. this.extraFields = {};
  3976. }
  3977.  
  3978. while (reader.index + 4 < end) {
  3979. extraFieldId = reader.readInt(2);
  3980. extraFieldLength = reader.readInt(2);
  3981. extraFieldValue = reader.readData(extraFieldLength);
  3982.  
  3983. this.extraFields[extraFieldId] = {
  3984. id: extraFieldId,
  3985. length: extraFieldLength,
  3986. value: extraFieldValue
  3987. };
  3988. }
  3989.  
  3990. reader.setIndex(end);
  3991. },
  3992. /**
  3993. * Apply an UTF8 transformation if needed.
  3994. */
  3995. handleUTF8: function() {
  3996. var decodeParamType = support.uint8array ? "uint8array" : "array";
  3997. if (this.useUTF8()) {
  3998. this.fileNameStr = utf8.utf8decode(this.fileName);
  3999. this.fileCommentStr = utf8.utf8decode(this.fileComment);
  4000. } else {
  4001. var upath = this.findExtraFieldUnicodePath();
  4002. if (upath !== null) {
  4003. this.fileNameStr = upath;
  4004. } else {
  4005. // ASCII text or unsupported code page
  4006. var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);
  4007. this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
  4008. }
  4009.  
  4010. var ucomment = this.findExtraFieldUnicodeComment();
  4011. if (ucomment !== null) {
  4012. this.fileCommentStr = ucomment;
  4013. } else {
  4014. // ASCII text or unsupported code page
  4015. var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);
  4016. this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
  4017. }
  4018. }
  4019. },
  4020.  
  4021. /**
  4022. * Find the unicode path declared in the extra field, if any.
  4023. * @return {String} the unicode path, null otherwise.
  4024. */
  4025. findExtraFieldUnicodePath: function() {
  4026. var upathField = this.extraFields[0x7075];
  4027. if (upathField) {
  4028. var extraReader = readerFor(upathField.value);
  4029.  
  4030. // wrong version
  4031. if (extraReader.readInt(1) !== 1) {
  4032. return null;
  4033. }
  4034.  
  4035. // the crc of the filename changed, this field is out of date.
  4036. if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
  4037. return null;
  4038. }
  4039.  
  4040. return utf8.utf8decode(extraReader.readData(upathField.length - 5));
  4041. }
  4042. return null;
  4043. },
  4044.  
  4045. /**
  4046. * Find the unicode comment declared in the extra field, if any.
  4047. * @return {String} the unicode comment, null otherwise.
  4048. */
  4049. findExtraFieldUnicodeComment: function() {
  4050. var ucommentField = this.extraFields[0x6375];
  4051. if (ucommentField) {
  4052. var extraReader = readerFor(ucommentField.value);
  4053.  
  4054. // wrong version
  4055. if (extraReader.readInt(1) !== 1) {
  4056. return null;
  4057. }
  4058.  
  4059. // the crc of the comment changed, this field is out of date.
  4060. if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
  4061. return null;
  4062. }
  4063.  
  4064. return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
  4065. }
  4066. return null;
  4067. }
  4068. };
  4069. module.exports = ZipEntry;
  4070.  
  4071. },{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){
  4072. 'use strict';
  4073.  
  4074. var StreamHelper = require('./stream/StreamHelper');
  4075. var DataWorker = require('./stream/DataWorker');
  4076. var utf8 = require('./utf8');
  4077. var CompressedObject = require('./compressedObject');
  4078. var GenericWorker = require('./stream/GenericWorker');
  4079.  
  4080. /**
  4081. * A simple object representing a file in the zip file.
  4082. * @constructor
  4083. * @param {string} name the name of the file
  4084. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  4085. * @param {Object} options the options of the file
  4086. */
  4087. var ZipObject = function(name, data, options) {
  4088. this.name = name;
  4089. this.dir = options.dir;
  4090. this.date = options.date;
  4091. this.comment = options.comment;
  4092. this.unixPermissions = options.unixPermissions;
  4093. this.dosPermissions = options.dosPermissions;
  4094.  
  4095. this._data = data;
  4096. this._dataBinary = options.binary;
  4097. // keep only the compression
  4098. this.options = {
  4099. compression : options.compression,
  4100. compressionOptions : options.compressionOptions
  4101. };
  4102. };
  4103.  
  4104. ZipObject.prototype = {
  4105. /**
  4106. * Create an internal stream for the content of this object.
  4107. * @param {String} type the type of each chunk.
  4108. * @return StreamHelper the stream.
  4109. */
  4110. internalStream: function (type) {
  4111. var result = null, outputType = "string";
  4112. try {
  4113. if (!type) {
  4114. throw new Error("No output type specified.");
  4115. }
  4116. outputType = type.toLowerCase();
  4117. var askUnicodeString = outputType === "string" || outputType === "text";
  4118. if (outputType === "binarystring" || outputType === "text") {
  4119. outputType = "string";
  4120. }
  4121. result = this._decompressWorker();
  4122.  
  4123. var isUnicodeString = !this._dataBinary;
  4124.  
  4125. if (isUnicodeString && !askUnicodeString) {
  4126. result = result.pipe(new utf8.Utf8EncodeWorker());
  4127. }
  4128. if (!isUnicodeString && askUnicodeString) {
  4129. result = result.pipe(new utf8.Utf8DecodeWorker());
  4130. }
  4131. } catch (e) {
  4132. result = new GenericWorker("error");
  4133. result.error(e);
  4134. }
  4135.  
  4136. return new StreamHelper(result, outputType, "");
  4137. },
  4138.  
  4139. /**
  4140. * Prepare the content in the asked type.
  4141. * @param {String} type the type of the result.
  4142. * @param {Function} onUpdate a function to call on each internal update.
  4143. * @return Promise the promise of the result.
  4144. */
  4145. async: function (type, onUpdate) {
  4146. return this.internalStream(type).accumulate(onUpdate);
  4147. },
  4148.  
  4149. /**
  4150. * Prepare the content as a nodejs stream.
  4151. * @param {String} type the type of each chunk.
  4152. * @param {Function} onUpdate a function to call on each internal update.
  4153. * @return Stream the stream.
  4154. */
  4155. nodeStream: function (type, onUpdate) {
  4156. return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
  4157. },
  4158.  
  4159. /**
  4160. * Return a worker for the compressed content.
  4161. * @private
  4162. * @param {Object} compression the compression object to use.
  4163. * @param {Object} compressionOptions the options to use when compressing.
  4164. * @return Worker the worker.
  4165. */
  4166. _compressWorker: function (compression, compressionOptions) {
  4167. if (
  4168. this._data instanceof CompressedObject &&
  4169. this._data.compression.magic === compression.magic
  4170. ) {
  4171. return this._data.getCompressedWorker();
  4172. } else {
  4173. var result = this._decompressWorker();
  4174. if(!this._dataBinary) {
  4175. result = result.pipe(new utf8.Utf8EncodeWorker());
  4176. }
  4177. return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
  4178. }
  4179. },
  4180. /**
  4181. * Return a worker for the decompressed content.
  4182. * @private
  4183. * @return Worker the worker.
  4184. */
  4185. _decompressWorker : function () {
  4186. if (this._data instanceof CompressedObject) {
  4187. return this._data.getContentWorker();
  4188. } else if (this._data instanceof GenericWorker) {
  4189. return this._data;
  4190. } else {
  4191. return new DataWorker(this._data);
  4192. }
  4193. }
  4194. };
  4195.  
  4196. var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
  4197. var removedFn = function () {
  4198. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  4199. };
  4200.  
  4201. for(var i = 0; i < removedMethods.length; i++) {
  4202. ZipObject.prototype[removedMethods[i]] = removedFn;
  4203. }
  4204. module.exports = ZipObject;
  4205.  
  4206. },{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){
  4207. (function (global){
  4208. 'use strict';
  4209. var Mutation = global.MutationObserver || global.WebKitMutationObserver;
  4210.  
  4211. var scheduleDrain;
  4212.  
  4213. {
  4214. if (Mutation) {
  4215. var called = 0;
  4216. var observer = new Mutation(nextTick);
  4217. var element = global.document.createTextNode('');
  4218. observer.observe(element, {
  4219. characterData: true
  4220. });
  4221. scheduleDrain = function () {
  4222. element.data = (called = ++called % 2);
  4223. };
  4224. } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
  4225. var channel = new global.MessageChannel();
  4226. channel.port1.onmessage = nextTick;
  4227. scheduleDrain = function () {
  4228. channel.port2.postMessage(0);
  4229. };
  4230. } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
  4231. scheduleDrain = function () {
  4232.  
  4233. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  4234. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  4235. var scriptEl = global.document.createElement('script');
  4236. scriptEl.onreadystatechange = function () {
  4237. nextTick();
  4238.  
  4239. scriptEl.onreadystatechange = null;
  4240. scriptEl.parentNode.removeChild(scriptEl);
  4241. scriptEl = null;
  4242. };
  4243. global.document.documentElement.appendChild(scriptEl);
  4244. };
  4245. } else {
  4246. scheduleDrain = function () {
  4247. setTimeout(nextTick, 0);
  4248. };
  4249. }
  4250. }
  4251.  
  4252. var draining;
  4253. var queue = [];
  4254. //named nextTick for less confusing stack traces
  4255. function nextTick() {
  4256. draining = true;
  4257. var i, oldQueue;
  4258. var len = queue.length;
  4259. while (len) {
  4260. oldQueue = queue;
  4261. queue = [];
  4262. i = -1;
  4263. while (++i < len) {
  4264. oldQueue[i]();
  4265. }
  4266. len = queue.length;
  4267. }
  4268. draining = false;
  4269. }
  4270.  
  4271. module.exports = immediate;
  4272. function immediate(task) {
  4273. if (queue.push(task) === 1 && !draining) {
  4274. scheduleDrain();
  4275. }
  4276. }
  4277.  
  4278. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4279. },{}],37:[function(require,module,exports){
  4280. 'use strict';
  4281. var immediate = require('immediate');
  4282.  
  4283. /* istanbul ignore next */
  4284. function INTERNAL() {}
  4285.  
  4286. var handlers = {};
  4287.  
  4288. var REJECTED = ['REJECTED'];
  4289. var FULFILLED = ['FULFILLED'];
  4290. var PENDING = ['PENDING'];
  4291.  
  4292. module.exports = Promise;
  4293.  
  4294. function Promise(resolver) {
  4295. if (typeof resolver !== 'function') {
  4296. throw new TypeError('resolver must be a function');
  4297. }
  4298. this.state = PENDING;
  4299. this.queue = [];
  4300. this.outcome = void 0;
  4301. if (resolver !== INTERNAL) {
  4302. safelyResolveThenable(this, resolver);
  4303. }
  4304. }
  4305.  
  4306. Promise.prototype["finally"] = function (callback) {
  4307. if (typeof callback !== 'function') {
  4308. return this;
  4309. }
  4310. var p = this.constructor;
  4311. return this.then(resolve, reject);
  4312.  
  4313. function resolve(value) {
  4314. function yes () {
  4315. return value;
  4316. }
  4317. return p.resolve(callback()).then(yes);
  4318. }
  4319. function reject(reason) {
  4320. function no () {
  4321. throw reason;
  4322. }
  4323. return p.resolve(callback()).then(no);
  4324. }
  4325. };
  4326. Promise.prototype["catch"] = function (onRejected) {
  4327. return this.then(null, onRejected);
  4328. };
  4329. Promise.prototype.then = function (onFulfilled, onRejected) {
  4330. if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
  4331. typeof onRejected !== 'function' && this.state === REJECTED) {
  4332. return this;
  4333. }
  4334. var promise = new this.constructor(INTERNAL);
  4335. if (this.state !== PENDING) {
  4336. var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
  4337. unwrap(promise, resolver, this.outcome);
  4338. } else {
  4339. this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  4340. }
  4341.  
  4342. return promise;
  4343. };
  4344. function QueueItem(promise, onFulfilled, onRejected) {
  4345. this.promise = promise;
  4346. if (typeof onFulfilled === 'function') {
  4347. this.onFulfilled = onFulfilled;
  4348. this.callFulfilled = this.otherCallFulfilled;
  4349. }
  4350. if (typeof onRejected === 'function') {
  4351. this.onRejected = onRejected;
  4352. this.callRejected = this.otherCallRejected;
  4353. }
  4354. }
  4355. QueueItem.prototype.callFulfilled = function (value) {
  4356. handlers.resolve(this.promise, value);
  4357. };
  4358. QueueItem.prototype.otherCallFulfilled = function (value) {
  4359. unwrap(this.promise, this.onFulfilled, value);
  4360. };
  4361. QueueItem.prototype.callRejected = function (value) {
  4362. handlers.reject(this.promise, value);
  4363. };
  4364. QueueItem.prototype.otherCallRejected = function (value) {
  4365. unwrap(this.promise, this.onRejected, value);
  4366. };
  4367.  
  4368. function unwrap(promise, func, value) {
  4369. immediate(function () {
  4370. var returnValue;
  4371. try {
  4372. returnValue = func(value);
  4373. } catch (e) {
  4374. return handlers.reject(promise, e);
  4375. }
  4376. if (returnValue === promise) {
  4377. handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
  4378. } else {
  4379. handlers.resolve(promise, returnValue);
  4380. }
  4381. });
  4382. }
  4383.  
  4384. handlers.resolve = function (self, value) {
  4385. var result = tryCatch(getThen, value);
  4386. if (result.status === 'error') {
  4387. return handlers.reject(self, result.value);
  4388. }
  4389. var thenable = result.value;
  4390.  
  4391. if (thenable) {
  4392. safelyResolveThenable(self, thenable);
  4393. } else {
  4394. self.state = FULFILLED;
  4395. self.outcome = value;
  4396. var i = -1;
  4397. var len = self.queue.length;
  4398. while (++i < len) {
  4399. self.queue[i].callFulfilled(value);
  4400. }
  4401. }
  4402. return self;
  4403. };
  4404. handlers.reject = function (self, error) {
  4405. self.state = REJECTED;
  4406. self.outcome = error;
  4407. var i = -1;
  4408. var len = self.queue.length;
  4409. while (++i < len) {
  4410. self.queue[i].callRejected(error);
  4411. }
  4412. return self;
  4413. };
  4414.  
  4415. function getThen(obj) {
  4416. // Make sure we only access the accessor once as required by the spec
  4417. var then = obj && obj.then;
  4418. if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
  4419. return function appyThen() {
  4420. then.apply(obj, arguments);
  4421. };
  4422. }
  4423. }
  4424.  
  4425. function safelyResolveThenable(self, thenable) {
  4426. // Either fulfill, reject or reject with error
  4427. var called = false;
  4428. function onError(value) {
  4429. if (called) {
  4430. return;
  4431. }
  4432. called = true;
  4433. handlers.reject(self, value);
  4434. }
  4435.  
  4436. function onSuccess(value) {
  4437. if (called) {
  4438. return;
  4439. }
  4440. called = true;
  4441. handlers.resolve(self, value);
  4442. }
  4443.  
  4444. function tryToUnwrap() {
  4445. thenable(onSuccess, onError);
  4446. }
  4447.  
  4448. var result = tryCatch(tryToUnwrap);
  4449. if (result.status === 'error') {
  4450. onError(result.value);
  4451. }
  4452. }
  4453.  
  4454. function tryCatch(func, value) {
  4455. var out = {};
  4456. try {
  4457. out.value = func(value);
  4458. out.status = 'success';
  4459. } catch (e) {
  4460. out.status = 'error';
  4461. out.value = e;
  4462. }
  4463. return out;
  4464. }
  4465.  
  4466. Promise.resolve = resolve;
  4467. function resolve(value) {
  4468. if (value instanceof this) {
  4469. return value;
  4470. }
  4471. return handlers.resolve(new this(INTERNAL), value);
  4472. }
  4473.  
  4474. Promise.reject = reject;
  4475. function reject(reason) {
  4476. var promise = new this(INTERNAL);
  4477. return handlers.reject(promise, reason);
  4478. }
  4479.  
  4480. Promise.all = all;
  4481. function all(iterable) {
  4482. var self = this;
  4483. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4484. return this.reject(new TypeError('must be an array'));
  4485. }
  4486.  
  4487. var len = iterable.length;
  4488. var called = false;
  4489. if (!len) {
  4490. return this.resolve([]);
  4491. }
  4492.  
  4493. var values = new Array(len);
  4494. var resolved = 0;
  4495. var i = -1;
  4496. var promise = new this(INTERNAL);
  4497.  
  4498. while (++i < len) {
  4499. allResolver(iterable[i], i);
  4500. }
  4501. return promise;
  4502. function allResolver(value, i) {
  4503. self.resolve(value).then(resolveFromAll, function (error) {
  4504. if (!called) {
  4505. called = true;
  4506. handlers.reject(promise, error);
  4507. }
  4508. });
  4509. function resolveFromAll(outValue) {
  4510. values[i] = outValue;
  4511. if (++resolved === len && !called) {
  4512. called = true;
  4513. handlers.resolve(promise, values);
  4514. }
  4515. }
  4516. }
  4517. }
  4518.  
  4519. Promise.race = race;
  4520. function race(iterable) {
  4521. var self = this;
  4522. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4523. return this.reject(new TypeError('must be an array'));
  4524. }
  4525.  
  4526. var len = iterable.length;
  4527. var called = false;
  4528. if (!len) {
  4529. return this.resolve([]);
  4530. }
  4531.  
  4532. var i = -1;
  4533. var promise = new this(INTERNAL);
  4534.  
  4535. while (++i < len) {
  4536. resolver(iterable[i]);
  4537. }
  4538. return promise;
  4539. function resolver(value) {
  4540. self.resolve(value).then(function (response) {
  4541. if (!called) {
  4542. called = true;
  4543. handlers.resolve(promise, response);
  4544. }
  4545. }, function (error) {
  4546. if (!called) {
  4547. called = true;
  4548. handlers.reject(promise, error);
  4549. }
  4550. });
  4551. }
  4552. }
  4553.  
  4554. },{"immediate":36}],38:[function(require,module,exports){
  4555. // Top level file is just a mixin of submodules & constants
  4556. 'use strict';
  4557.  
  4558. var assign = require('./lib/utils/common').assign;
  4559.  
  4560. var deflate = require('./lib/deflate');
  4561. var inflate = require('./lib/inflate');
  4562. var constants = require('./lib/zlib/constants');
  4563.  
  4564. var pako = {};
  4565.  
  4566. assign(pako, deflate, inflate, constants);
  4567.  
  4568. module.exports = pako;
  4569.  
  4570. },{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(require,module,exports){
  4571. 'use strict';
  4572.  
  4573.  
  4574. var zlib_deflate = require('./zlib/deflate');
  4575. var utils = require('./utils/common');
  4576. var strings = require('./utils/strings');
  4577. var msg = require('./zlib/messages');
  4578. var ZStream = require('./zlib/zstream');
  4579.  
  4580. var toString = Object.prototype.toString;
  4581.  
  4582. /* Public constants ==========================================================*/
  4583. /* ===========================================================================*/
  4584.  
  4585. var Z_NO_FLUSH = 0;
  4586. var Z_FINISH = 4;
  4587.  
  4588. var Z_OK = 0;
  4589. var Z_STREAM_END = 1;
  4590. var Z_SYNC_FLUSH = 2;
  4591.  
  4592. var Z_DEFAULT_COMPRESSION = -1;
  4593.  
  4594. var Z_DEFAULT_STRATEGY = 0;
  4595.  
  4596. var Z_DEFLATED = 8;
  4597.  
  4598. /* ===========================================================================*/
  4599.  
  4600.  
  4601. /**
  4602. * class Deflate
  4603. *
  4604. * Generic JS-style wrapper for zlib calls. If you don't need
  4605. * streaming behaviour - use more simple functions: [[deflate]],
  4606. * [[deflateRaw]] and [[gzip]].
  4607. **/
  4608.  
  4609. /* internal
  4610. * Deflate.chunks -> Array
  4611. *
  4612. * Chunks of output data, if [[Deflate#onData]] not overriden.
  4613. **/
  4614.  
  4615. /**
  4616. * Deflate.result -> Uint8Array|Array
  4617. *
  4618. * Compressed result, generated by default [[Deflate#onData]]
  4619. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  4620. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  4621. * push a chunk with explicit flush (call [[Deflate#push]] with
  4622. * `Z_SYNC_FLUSH` param).
  4623. **/
  4624.  
  4625. /**
  4626. * Deflate.err -> Number
  4627. *
  4628. * Error code after deflate finished. 0 (Z_OK) on success.
  4629. * You will not need it in real life, because deflate errors
  4630. * are possible only on wrong options or bad `onData` / `onEnd`
  4631. * custom handlers.
  4632. **/
  4633.  
  4634. /**
  4635. * Deflate.msg -> String
  4636. *
  4637. * Error message, if [[Deflate.err]] != 0
  4638. **/
  4639.  
  4640.  
  4641. /**
  4642. * new Deflate(options)
  4643. * - options (Object): zlib deflate options.
  4644. *
  4645. * Creates new deflator instance with specified params. Throws exception
  4646. * on bad params. Supported options:
  4647. *
  4648. * - `level`
  4649. * - `windowBits`
  4650. * - `memLevel`
  4651. * - `strategy`
  4652. * - `dictionary`
  4653. *
  4654. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4655. * for more information on these.
  4656. *
  4657. * Additional options, for internal needs:
  4658. *
  4659. * - `chunkSize` - size of generated data chunks (16K by default)
  4660. * - `raw` (Boolean) - do raw deflate
  4661. * - `gzip` (Boolean) - create gzip wrapper
  4662. * - `to` (String) - if equal to 'string', then result will be "binary string"
  4663. * (each char code [0..255])
  4664. * - `header` (Object) - custom header for gzip
  4665. * - `text` (Boolean) - true if compressed data believed to be text
  4666. * - `time` (Number) - modification time, unix timestamp
  4667. * - `os` (Number) - operation system code
  4668. * - `extra` (Array) - array of bytes with extra data (max 65536)
  4669. * - `name` (String) - file name (binary string)
  4670. * - `comment` (String) - comment (binary string)
  4671. * - `hcrc` (Boolean) - true if header crc should be added
  4672. *
  4673. * ##### Example:
  4674. *
  4675. * ```javascript
  4676. * var pako = require('pako')
  4677. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  4678. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  4679. *
  4680. * var deflate = new pako.Deflate({ level: 3});
  4681. *
  4682. * deflate.push(chunk1, false);
  4683. * deflate.push(chunk2, true); // true -> last chunk
  4684. *
  4685. * if (deflate.err) { throw new Error(deflate.err); }
  4686. *
  4687. * console.log(deflate.result);
  4688. * ```
  4689. **/
  4690. function Deflate(options) {
  4691. if (!(this instanceof Deflate)) return new Deflate(options);
  4692.  
  4693. this.options = utils.assign({
  4694. level: Z_DEFAULT_COMPRESSION,
  4695. method: Z_DEFLATED,
  4696. chunkSize: 16384,
  4697. windowBits: 15,
  4698. memLevel: 8,
  4699. strategy: Z_DEFAULT_STRATEGY,
  4700. to: ''
  4701. }, options || {});
  4702.  
  4703. var opt = this.options;
  4704.  
  4705. if (opt.raw && (opt.windowBits > 0)) {
  4706. opt.windowBits = -opt.windowBits;
  4707. }
  4708.  
  4709. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  4710. opt.windowBits += 16;
  4711. }
  4712.  
  4713. this.err = 0; // error code, if happens (0 = Z_OK)
  4714. this.msg = ''; // error message
  4715. this.ended = false; // used to avoid multiple onEnd() calls
  4716. this.chunks = []; // chunks of compressed data
  4717.  
  4718. this.strm = new ZStream();
  4719. this.strm.avail_out = 0;
  4720.  
  4721. var status = zlib_deflate.deflateInit2(
  4722. this.strm,
  4723. opt.level,
  4724. opt.method,
  4725. opt.windowBits,
  4726. opt.memLevel,
  4727. opt.strategy
  4728. );
  4729.  
  4730. if (status !== Z_OK) {
  4731. throw new Error(msg[status]);
  4732. }
  4733.  
  4734. if (opt.header) {
  4735. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  4736. }
  4737.  
  4738. if (opt.dictionary) {
  4739. var dict;
  4740. // Convert data if needed
  4741. if (typeof opt.dictionary === 'string') {
  4742. // If we need to compress text, change encoding to utf8.
  4743. dict = strings.string2buf(opt.dictionary);
  4744. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  4745. dict = new Uint8Array(opt.dictionary);
  4746. } else {
  4747. dict = opt.dictionary;
  4748. }
  4749.  
  4750. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  4751.  
  4752. if (status !== Z_OK) {
  4753. throw new Error(msg[status]);
  4754. }
  4755.  
  4756. this._dict_set = true;
  4757. }
  4758. }
  4759.  
  4760. /**
  4761. * Deflate#push(data[, mode]) -> Boolean
  4762. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  4763. * converted to utf8 byte sequence.
  4764. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  4765. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  4766. *
  4767. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  4768. * new compressed chunks. Returns `true` on success. The last data block must have
  4769. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  4770. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  4771. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  4772. *
  4773. * On fail call [[Deflate#onEnd]] with error code and return false.
  4774. *
  4775. * We strongly recommend to use `Uint8Array` on input for best speed (output
  4776. * array format is detected automatically). Also, don't skip last param and always
  4777. * use the same type in your code (boolean or number). That will improve JS speed.
  4778. *
  4779. * For regular `Array`-s make sure all elements are [0..255].
  4780. *
  4781. * ##### Example
  4782. *
  4783. * ```javascript
  4784. * push(chunk, false); // push one of data chunks
  4785. * ...
  4786. * push(chunk, true); // push last chunk
  4787. * ```
  4788. **/
  4789. Deflate.prototype.push = function (data, mode) {
  4790. var strm = this.strm;
  4791. var chunkSize = this.options.chunkSize;
  4792. var status, _mode;
  4793.  
  4794. if (this.ended) { return false; }
  4795.  
  4796. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  4797.  
  4798. // Convert data if needed
  4799. if (typeof data === 'string') {
  4800. // If we need to compress text, change encoding to utf8.
  4801. strm.input = strings.string2buf(data);
  4802. } else if (toString.call(data) === '[object ArrayBuffer]') {
  4803. strm.input = new Uint8Array(data);
  4804. } else {
  4805. strm.input = data;
  4806. }
  4807.  
  4808. strm.next_in = 0;
  4809. strm.avail_in = strm.input.length;
  4810.  
  4811. do {
  4812. if (strm.avail_out === 0) {
  4813. strm.output = new utils.Buf8(chunkSize);
  4814. strm.next_out = 0;
  4815. strm.avail_out = chunkSize;
  4816. }
  4817. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  4818.  
  4819. if (status !== Z_STREAM_END && status !== Z_OK) {
  4820. this.onEnd(status);
  4821. this.ended = true;
  4822. return false;
  4823. }
  4824. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  4825. if (this.options.to === 'string') {
  4826. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  4827. } else {
  4828. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  4829. }
  4830. }
  4831. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  4832.  
  4833. // Finalize on the last chunk.
  4834. if (_mode === Z_FINISH) {
  4835. status = zlib_deflate.deflateEnd(this.strm);
  4836. this.onEnd(status);
  4837. this.ended = true;
  4838. return status === Z_OK;
  4839. }
  4840.  
  4841. // callback interim results if Z_SYNC_FLUSH.
  4842. if (_mode === Z_SYNC_FLUSH) {
  4843. this.onEnd(Z_OK);
  4844. strm.avail_out = 0;
  4845. return true;
  4846. }
  4847.  
  4848. return true;
  4849. };
  4850.  
  4851.  
  4852. /**
  4853. * Deflate#onData(chunk) -> Void
  4854. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  4855. * on js engine support. When string output requested, each chunk
  4856. * will be string.
  4857. *
  4858. * By default, stores data blocks in `chunks[]` property and glue
  4859. * those in `onEnd`. Override this handler, if you need another behaviour.
  4860. **/
  4861. Deflate.prototype.onData = function (chunk) {
  4862. this.chunks.push(chunk);
  4863. };
  4864.  
  4865.  
  4866. /**
  4867. * Deflate#onEnd(status) -> Void
  4868. * - status (Number): deflate status. 0 (Z_OK) on success,
  4869. * other if not.
  4870. *
  4871. * Called once after you tell deflate that the input stream is
  4872. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  4873. * or if an error happened. By default - join collected chunks,
  4874. * free memory and fill `results` / `err` properties.
  4875. **/
  4876. Deflate.prototype.onEnd = function (status) {
  4877. // On success - join
  4878. if (status === Z_OK) {
  4879. if (this.options.to === 'string') {
  4880. this.result = this.chunks.join('');
  4881. } else {
  4882. this.result = utils.flattenChunks(this.chunks);
  4883. }
  4884. }
  4885. this.chunks = [];
  4886. this.err = status;
  4887. this.msg = this.strm.msg;
  4888. };
  4889.  
  4890.  
  4891. /**
  4892. * deflate(data[, options]) -> Uint8Array|Array|String
  4893. * - data (Uint8Array|Array|String): input data to compress.
  4894. * - options (Object): zlib deflate options.
  4895. *
  4896. * Compress `data` with deflate algorithm and `options`.
  4897. *
  4898. * Supported options are:
  4899. *
  4900. * - level
  4901. * - windowBits
  4902. * - memLevel
  4903. * - strategy
  4904. * - dictionary
  4905. *
  4906. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4907. * for more information on these.
  4908. *
  4909. * Sugar (options):
  4910. *
  4911. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  4912. * negative windowBits implicitly.
  4913. * - `to` (String) - if equal to 'string', then result will be "binary string"
  4914. * (each char code [0..255])
  4915. *
  4916. * ##### Example:
  4917. *
  4918. * ```javascript
  4919. * var pako = require('pako')
  4920. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  4921. *
  4922. * console.log(pako.deflate(data));
  4923. * ```
  4924. **/
  4925. function deflate(input, options) {
  4926. var deflator = new Deflate(options);
  4927.  
  4928. deflator.push(input, true);
  4929.  
  4930. // That will never happens, if you don't cheat with options :)
  4931. if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
  4932.  
  4933. return deflator.result;
  4934. }
  4935.  
  4936.  
  4937. /**
  4938. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  4939. * - data (Uint8Array|Array|String): input data to compress.
  4940. * - options (Object): zlib deflate options.
  4941. *
  4942. * The same as [[deflate]], but creates raw data, without wrapper
  4943. * (header and adler32 crc).
  4944. **/
  4945. function deflateRaw(input, options) {
  4946. options = options || {};
  4947. options.raw = true;
  4948. return deflate(input, options);
  4949. }
  4950.  
  4951.  
  4952. /**
  4953. * gzip(data[, options]) -> Uint8Array|Array|String
  4954. * - data (Uint8Array|Array|String): input data to compress.
  4955. * - options (Object): zlib deflate options.
  4956. *
  4957. * The same as [[deflate]], but create gzip wrapper instead of
  4958. * deflate one.
  4959. **/
  4960. function gzip(input, options) {
  4961. options = options || {};
  4962. options.gzip = true;
  4963. return deflate(input, options);
  4964. }
  4965.  
  4966.  
  4967. exports.Deflate = Deflate;
  4968. exports.deflate = deflate;
  4969. exports.deflateRaw = deflateRaw;
  4970. exports.gzip = gzip;
  4971.  
  4972. },{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(require,module,exports){
  4973. 'use strict';
  4974.  
  4975.  
  4976. var zlib_inflate = require('./zlib/inflate');
  4977. var utils = require('./utils/common');
  4978. var strings = require('./utils/strings');
  4979. var c = require('./zlib/constants');
  4980. var msg = require('./zlib/messages');
  4981. var ZStream = require('./zlib/zstream');
  4982. var GZheader = require('./zlib/gzheader');
  4983.  
  4984. var toString = Object.prototype.toString;
  4985.  
  4986. /**
  4987. * class Inflate
  4988. *
  4989. * Generic JS-style wrapper for zlib calls. If you don't need
  4990. * streaming behaviour - use more simple functions: [[inflate]]
  4991. * and [[inflateRaw]].
  4992. **/
  4993.  
  4994. /* internal
  4995. * inflate.chunks -> Array
  4996. *
  4997. * Chunks of output data, if [[Inflate#onData]] not overriden.
  4998. **/
  4999.  
  5000. /**
  5001. * Inflate.result -> Uint8Array|Array|String
  5002. *
  5003. * Uncompressed result, generated by default [[Inflate#onData]]
  5004. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  5005. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  5006. * push a chunk with explicit flush (call [[Inflate#push]] with
  5007. * `Z_SYNC_FLUSH` param).
  5008. **/
  5009.  
  5010. /**
  5011. * Inflate.err -> Number
  5012. *
  5013. * Error code after inflate finished. 0 (Z_OK) on success.
  5014. * Should be checked if broken data possible.
  5015. **/
  5016.  
  5017. /**
  5018. * Inflate.msg -> String
  5019. *
  5020. * Error message, if [[Inflate.err]] != 0
  5021. **/
  5022.  
  5023.  
  5024. /**
  5025. * new Inflate(options)
  5026. * - options (Object): zlib inflate options.
  5027. *
  5028. * Creates new inflator instance with specified params. Throws exception
  5029. * on bad params. Supported options:
  5030. *
  5031. * - `windowBits`
  5032. * - `dictionary`
  5033. *
  5034. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5035. * for more information on these.
  5036. *
  5037. * Additional options, for internal needs:
  5038. *
  5039. * - `chunkSize` - size of generated data chunks (16K by default)
  5040. * - `raw` (Boolean) - do raw inflate
  5041. * - `to` (String) - if equal to 'string', then result will be converted
  5042. * from utf8 to utf16 (javascript) string. When string output requested,
  5043. * chunk length can differ from `chunkSize`, depending on content.
  5044. *
  5045. * By default, when no options set, autodetect deflate/gzip data format via
  5046. * wrapper header.
  5047. *
  5048. * ##### Example:
  5049. *
  5050. * ```javascript
  5051. * var pako = require('pako')
  5052. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5053. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5054. *
  5055. * var inflate = new pako.Inflate({ level: 3});
  5056. *
  5057. * inflate.push(chunk1, false);
  5058. * inflate.push(chunk2, true); // true -> last chunk
  5059. *
  5060. * if (inflate.err) { throw new Error(inflate.err); }
  5061. *
  5062. * console.log(inflate.result);
  5063. * ```
  5064. **/
  5065. function Inflate(options) {
  5066. if (!(this instanceof Inflate)) return new Inflate(options);
  5067.  
  5068. this.options = utils.assign({
  5069. chunkSize: 16384,
  5070. windowBits: 0,
  5071. to: ''
  5072. }, options || {});
  5073.  
  5074. var opt = this.options;
  5075.  
  5076. // Force window size for `raw` data, if not set directly,
  5077. // because we have no header for autodetect.
  5078. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  5079. opt.windowBits = -opt.windowBits;
  5080. if (opt.windowBits === 0) { opt.windowBits = -15; }
  5081. }
  5082.  
  5083. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  5084. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  5085. !(options && options.windowBits)) {
  5086. opt.windowBits += 32;
  5087. }
  5088.  
  5089. // Gzip header has no info about windows size, we can do autodetect only
  5090. // for deflate. So, if window size not set, force it to max when gzip possible
  5091. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  5092. // bit 3 (16) -> gzipped data
  5093. // bit 4 (32) -> autodetect gzip/deflate
  5094. if ((opt.windowBits & 15) === 0) {
  5095. opt.windowBits |= 15;
  5096. }
  5097. }
  5098.  
  5099. this.err = 0; // error code, if happens (0 = Z_OK)
  5100. this.msg = ''; // error message
  5101. this.ended = false; // used to avoid multiple onEnd() calls
  5102. this.chunks = []; // chunks of compressed data
  5103.  
  5104. this.strm = new ZStream();
  5105. this.strm.avail_out = 0;
  5106.  
  5107. var status = zlib_inflate.inflateInit2(
  5108. this.strm,
  5109. opt.windowBits
  5110. );
  5111.  
  5112. if (status !== c.Z_OK) {
  5113. throw new Error(msg[status]);
  5114. }
  5115.  
  5116. this.header = new GZheader();
  5117.  
  5118. zlib_inflate.inflateGetHeader(this.strm, this.header);
  5119. }
  5120.  
  5121. /**
  5122. * Inflate#push(data[, mode]) -> Boolean
  5123. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  5124. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5125. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5126. *
  5127. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  5128. * new output chunks. Returns `true` on success. The last data block must have
  5129. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5130. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5131. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  5132. *
  5133. * On fail call [[Inflate#onEnd]] with error code and return false.
  5134. *
  5135. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5136. * format is detected automatically). Also, don't skip last param and always
  5137. * use the same type in your code (boolean or number). That will improve JS speed.
  5138. *
  5139. * For regular `Array`-s make sure all elements are [0..255].
  5140. *
  5141. * ##### Example
  5142. *
  5143. * ```javascript
  5144. * push(chunk, false); // push one of data chunks
  5145. * ...
  5146. * push(chunk, true); // push last chunk
  5147. * ```
  5148. **/
  5149. Inflate.prototype.push = function (data, mode) {
  5150. var strm = this.strm;
  5151. var chunkSize = this.options.chunkSize;
  5152. var dictionary = this.options.dictionary;
  5153. var status, _mode;
  5154. var next_out_utf8, tail, utf8str;
  5155. var dict;
  5156.  
  5157. // Flag to properly process Z_BUF_ERROR on testing inflate call
  5158. // when we check that all output data was flushed.
  5159. var allowBufError = false;
  5160.  
  5161. if (this.ended) { return false; }
  5162. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  5163.  
  5164. // Convert data if needed
  5165. if (typeof data === 'string') {
  5166. // Only binary strings can be decompressed on practice
  5167. strm.input = strings.binstring2buf(data);
  5168. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5169. strm.input = new Uint8Array(data);
  5170. } else {
  5171. strm.input = data;
  5172. }
  5173.  
  5174. strm.next_in = 0;
  5175. strm.avail_in = strm.input.length;
  5176.  
  5177. do {
  5178. if (strm.avail_out === 0) {
  5179. strm.output = new utils.Buf8(chunkSize);
  5180. strm.next_out = 0;
  5181. strm.avail_out = chunkSize;
  5182. }
  5183.  
  5184. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  5185.  
  5186. if (status === c.Z_NEED_DICT && dictionary) {
  5187. // Convert data if needed
  5188. if (typeof dictionary === 'string') {
  5189. dict = strings.string2buf(dictionary);
  5190. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  5191. dict = new Uint8Array(dictionary);
  5192. } else {
  5193. dict = dictionary;
  5194. }
  5195.  
  5196. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  5197.  
  5198. }
  5199.  
  5200. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  5201. status = c.Z_OK;
  5202. allowBufError = false;
  5203. }
  5204.  
  5205. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  5206. this.onEnd(status);
  5207. this.ended = true;
  5208. return false;
  5209. }
  5210.  
  5211. if (strm.next_out) {
  5212. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  5213.  
  5214. if (this.options.to === 'string') {
  5215.  
  5216. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  5217.  
  5218. tail = strm.next_out - next_out_utf8;
  5219. utf8str = strings.buf2string(strm.output, next_out_utf8);
  5220.  
  5221. // move tail
  5222. strm.next_out = tail;
  5223. strm.avail_out = chunkSize - tail;
  5224. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  5225.  
  5226. this.onData(utf8str);
  5227.  
  5228. } else {
  5229. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5230. }
  5231. }
  5232. }
  5233.  
  5234. // When no more input data, we should check that internal inflate buffers
  5235. // are flushed. The only way to do it when avail_out = 0 - run one more
  5236. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  5237. // Here we set flag to process this error properly.
  5238. //
  5239. // NOTE. Deflate does not return error in this case and does not needs such
  5240. // logic.
  5241. if (strm.avail_in === 0 && strm.avail_out === 0) {
  5242. allowBufError = true;
  5243. }
  5244.  
  5245. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  5246.  
  5247. if (status === c.Z_STREAM_END) {
  5248. _mode = c.Z_FINISH;
  5249. }
  5250.  
  5251. // Finalize on the last chunk.
  5252. if (_mode === c.Z_FINISH) {
  5253. status = zlib_inflate.inflateEnd(this.strm);
  5254. this.onEnd(status);
  5255. this.ended = true;
  5256. return status === c.Z_OK;
  5257. }
  5258.  
  5259. // callback interim results if Z_SYNC_FLUSH.
  5260. if (_mode === c.Z_SYNC_FLUSH) {
  5261. this.onEnd(c.Z_OK);
  5262. strm.avail_out = 0;
  5263. return true;
  5264. }
  5265.  
  5266. return true;
  5267. };
  5268.  
  5269.  
  5270. /**
  5271. * Inflate#onData(chunk) -> Void
  5272. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5273. * on js engine support. When string output requested, each chunk
  5274. * will be string.
  5275. *
  5276. * By default, stores data blocks in `chunks[]` property and glue
  5277. * those in `onEnd`. Override this handler, if you need another behaviour.
  5278. **/
  5279. Inflate.prototype.onData = function (chunk) {
  5280. this.chunks.push(chunk);
  5281. };
  5282.  
  5283.  
  5284. /**
  5285. * Inflate#onEnd(status) -> Void
  5286. * - status (Number): inflate status. 0 (Z_OK) on success,
  5287. * other if not.
  5288. *
  5289. * Called either after you tell inflate that the input stream is
  5290. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5291. * or if an error happened. By default - join collected chunks,
  5292. * free memory and fill `results` / `err` properties.
  5293. **/
  5294. Inflate.prototype.onEnd = function (status) {
  5295. // On success - join
  5296. if (status === c.Z_OK) {
  5297. if (this.options.to === 'string') {
  5298. // Glue & convert here, until we teach pako to send
  5299. // utf8 alligned strings to onData
  5300. this.result = this.chunks.join('');
  5301. } else {
  5302. this.result = utils.flattenChunks(this.chunks);
  5303. }
  5304. }
  5305. this.chunks = [];
  5306. this.err = status;
  5307. this.msg = this.strm.msg;
  5308. };
  5309.  
  5310.  
  5311. /**
  5312. * inflate(data[, options]) -> Uint8Array|Array|String
  5313. * - data (Uint8Array|Array|String): input data to decompress.
  5314. * - options (Object): zlib inflate options.
  5315. *
  5316. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  5317. * format via wrapper header by default. That's why we don't provide
  5318. * separate `ungzip` method.
  5319. *
  5320. * Supported options are:
  5321. *
  5322. * - windowBits
  5323. *
  5324. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5325. * for more information.
  5326. *
  5327. * Sugar (options):
  5328. *
  5329. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5330. * negative windowBits implicitly.
  5331. * - `to` (String) - if equal to 'string', then result will be converted
  5332. * from utf8 to utf16 (javascript) string. When string output requested,
  5333. * chunk length can differ from `chunkSize`, depending on content.
  5334. *
  5335. *
  5336. * ##### Example:
  5337. *
  5338. * ```javascript
  5339. * var pako = require('pako')
  5340. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  5341. * , output;
  5342. *
  5343. * try {
  5344. * output = pako.inflate(input);
  5345. * } catch (err)
  5346. * console.log(err);
  5347. * }
  5348. * ```
  5349. **/
  5350. function inflate(input, options) {
  5351. var inflator = new Inflate(options);
  5352.  
  5353. inflator.push(input, true);
  5354.  
  5355. // That will never happens, if you don't cheat with options :)
  5356. if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
  5357.  
  5358. return inflator.result;
  5359. }
  5360.  
  5361.  
  5362. /**
  5363. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  5364. * - data (Uint8Array|Array|String): input data to decompress.
  5365. * - options (Object): zlib inflate options.
  5366. *
  5367. * The same as [[inflate]], but creates raw data, without wrapper
  5368. * (header and adler32 crc).
  5369. **/
  5370. function inflateRaw(input, options) {
  5371. options = options || {};
  5372. options.raw = true;
  5373. return inflate(input, options);
  5374. }
  5375.  
  5376.  
  5377. /**
  5378. * ungzip(data[, options]) -> Uint8Array|Array|String
  5379. * - data (Uint8Array|Array|String): input data to decompress.
  5380. * - options (Object): zlib inflate options.
  5381. *
  5382. * Just shortcut to [[inflate]], because it autodetects format
  5383. * by header.content. Done for convenience.
  5384. **/
  5385.  
  5386.  
  5387. exports.Inflate = Inflate;
  5388. exports.inflate = inflate;
  5389. exports.inflateRaw = inflateRaw;
  5390. exports.ungzip = inflate;
  5391.  
  5392. },{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(require,module,exports){
  5393. 'use strict';
  5394.  
  5395.  
  5396. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  5397. (typeof Uint16Array !== 'undefined') &&
  5398. (typeof Int32Array !== 'undefined');
  5399.  
  5400.  
  5401. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  5402. var sources = Array.prototype.slice.call(arguments, 1);
  5403. while (sources.length) {
  5404. var source = sources.shift();
  5405. if (!source) { continue; }
  5406.  
  5407. if (typeof source !== 'object') {
  5408. throw new TypeError(source + 'must be non-object');
  5409. }
  5410.  
  5411. for (var p in source) {
  5412. if (source.hasOwnProperty(p)) {
  5413. obj[p] = source[p];
  5414. }
  5415. }
  5416. }
  5417.  
  5418. return obj;
  5419. };
  5420.  
  5421.  
  5422. // reduce buffer size, avoiding mem copy
  5423. exports.shrinkBuf = function (buf, size) {
  5424. if (buf.length === size) { return buf; }
  5425. if (buf.subarray) { return buf.subarray(0, size); }
  5426. buf.length = size;
  5427. return buf;
  5428. };
  5429.  
  5430.  
  5431. var fnTyped = {
  5432. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5433. if (src.subarray && dest.subarray) {
  5434. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  5435. return;
  5436. }
  5437. // Fallback to ordinary array
  5438. for (var i = 0; i < len; i++) {
  5439. dest[dest_offs + i] = src[src_offs + i];
  5440. }
  5441. },
  5442. // Join array of chunks to single array.
  5443. flattenChunks: function (chunks) {
  5444. var i, l, len, pos, chunk, result;
  5445.  
  5446. // calculate data length
  5447. len = 0;
  5448. for (i = 0, l = chunks.length; i < l; i++) {
  5449. len += chunks[i].length;
  5450. }
  5451.  
  5452. // join chunks
  5453. result = new Uint8Array(len);
  5454. pos = 0;
  5455. for (i = 0, l = chunks.length; i < l; i++) {
  5456. chunk = chunks[i];
  5457. result.set(chunk, pos);
  5458. pos += chunk.length;
  5459. }
  5460.  
  5461. return result;
  5462. }
  5463. };
  5464.  
  5465. var fnUntyped = {
  5466. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5467. for (var i = 0; i < len; i++) {
  5468. dest[dest_offs + i] = src[src_offs + i];
  5469. }
  5470. },
  5471. // Join array of chunks to single array.
  5472. flattenChunks: function (chunks) {
  5473. return [].concat.apply([], chunks);
  5474. }
  5475. };
  5476.  
  5477.  
  5478. // Enable/Disable typed arrays use, for testing
  5479. //
  5480. exports.setTyped = function (on) {
  5481. if (on) {
  5482. exports.Buf8 = Uint8Array;
  5483. exports.Buf16 = Uint16Array;
  5484. exports.Buf32 = Int32Array;
  5485. exports.assign(exports, fnTyped);
  5486. } else {
  5487. exports.Buf8 = Array;
  5488. exports.Buf16 = Array;
  5489. exports.Buf32 = Array;
  5490. exports.assign(exports, fnUntyped);
  5491. }
  5492. };
  5493.  
  5494. exports.setTyped(TYPED_OK);
  5495.  
  5496. },{}],42:[function(require,module,exports){
  5497. // String encode/decode helpers
  5498. 'use strict';
  5499.  
  5500.  
  5501. var utils = require('./common');
  5502.  
  5503.  
  5504. // Quick check if we can use fast array to bin string conversion
  5505. //
  5506. // - apply(Array) can fail on Android 2.2
  5507. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  5508. //
  5509. var STR_APPLY_OK = true;
  5510. var STR_APPLY_UIA_OK = true;
  5511.  
  5512. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  5513. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  5514.  
  5515.  
  5516. // Table with utf8 lengths (calculated by first byte of sequence)
  5517. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  5518. // because max possible codepoint is 0x10ffff
  5519. var _utf8len = new utils.Buf8(256);
  5520. for (var q = 0; q < 256; q++) {
  5521. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  5522. }
  5523. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  5524.  
  5525.  
  5526. // convert string to array (typed, when possible)
  5527. exports.string2buf = function (str) {
  5528. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  5529.  
  5530. // count binary size
  5531. for (m_pos = 0; m_pos < str_len; m_pos++) {
  5532. c = str.charCodeAt(m_pos);
  5533. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  5534. c2 = str.charCodeAt(m_pos + 1);
  5535. if ((c2 & 0xfc00) === 0xdc00) {
  5536. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5537. m_pos++;
  5538. }
  5539. }
  5540. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  5541. }
  5542.  
  5543. // allocate buffer
  5544. buf = new utils.Buf8(buf_len);
  5545.  
  5546. // convert
  5547. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  5548. c = str.charCodeAt(m_pos);
  5549. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  5550. c2 = str.charCodeAt(m_pos + 1);
  5551. if ((c2 & 0xfc00) === 0xdc00) {
  5552. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5553. m_pos++;
  5554. }
  5555. }
  5556. if (c < 0x80) {
  5557. /* one byte */
  5558. buf[i++] = c;
  5559. } else if (c < 0x800) {
  5560. /* two bytes */
  5561. buf[i++] = 0xC0 | (c >>> 6);
  5562. buf[i++] = 0x80 | (c & 0x3f);
  5563. } else if (c < 0x10000) {
  5564. /* three bytes */
  5565. buf[i++] = 0xE0 | (c >>> 12);
  5566. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5567. buf[i++] = 0x80 | (c & 0x3f);
  5568. } else {
  5569. /* four bytes */
  5570. buf[i++] = 0xf0 | (c >>> 18);
  5571. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  5572. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5573. buf[i++] = 0x80 | (c & 0x3f);
  5574. }
  5575. }
  5576.  
  5577. return buf;
  5578. };
  5579.  
  5580. // Helper (used in 2 places)
  5581. function buf2binstring(buf, len) {
  5582. // use fallback for big arrays to avoid stack overflow
  5583. if (len < 65537) {
  5584. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  5585. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  5586. }
  5587. }
  5588.  
  5589. var result = '';
  5590. for (var i = 0; i < len; i++) {
  5591. result += String.fromCharCode(buf[i]);
  5592. }
  5593. return result;
  5594. }
  5595.  
  5596.  
  5597. // Convert byte array to binary string
  5598. exports.buf2binstring = function (buf) {
  5599. return buf2binstring(buf, buf.length);
  5600. };
  5601.  
  5602.  
  5603. // Convert binary string (typed, when possible)
  5604. exports.binstring2buf = function (str) {
  5605. var buf = new utils.Buf8(str.length);
  5606. for (var i = 0, len = buf.length; i < len; i++) {
  5607. buf[i] = str.charCodeAt(i);
  5608. }
  5609. return buf;
  5610. };
  5611.  
  5612.  
  5613. // convert array to string
  5614. exports.buf2string = function (buf, max) {
  5615. var i, out, c, c_len;
  5616. var len = max || buf.length;
  5617.  
  5618. // Reserve max possible length (2 words per char)
  5619. // NB: by unknown reasons, Array is significantly faster for
  5620. // String.fromCharCode.apply than Uint16Array.
  5621. var utf16buf = new Array(len * 2);
  5622.  
  5623. for (out = 0, i = 0; i < len;) {
  5624. c = buf[i++];
  5625. // quick process ascii
  5626. if (c < 0x80) { utf16buf[out++] = c; continue; }
  5627.  
  5628. c_len = _utf8len[c];
  5629. // skip 5 & 6 byte codes
  5630. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  5631.  
  5632. // apply mask on first byte
  5633. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  5634. // join the rest
  5635. while (c_len > 1 && i < len) {
  5636. c = (c << 6) | (buf[i++] & 0x3f);
  5637. c_len--;
  5638. }
  5639.  
  5640. // terminated by end of string?
  5641. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  5642.  
  5643. if (c < 0x10000) {
  5644. utf16buf[out++] = c;
  5645. } else {
  5646. c -= 0x10000;
  5647. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  5648. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  5649. }
  5650. }
  5651.  
  5652. return buf2binstring(utf16buf, out);
  5653. };
  5654.  
  5655.  
  5656. // Calculate max possible position in utf8 buffer,
  5657. // that will not break sequence. If that's not possible
  5658. // - (very small limits) return max size as is.
  5659. //
  5660. // buf[] - utf8 bytes array
  5661. // max - length limit (mandatory);
  5662. exports.utf8border = function (buf, max) {
  5663. var pos;
  5664.  
  5665. max = max || buf.length;
  5666. if (max > buf.length) { max = buf.length; }
  5667.  
  5668. // go back from last position, until start of sequence found
  5669. pos = max - 1;
  5670. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  5671.  
  5672. // Fuckup - very small and broken sequence,
  5673. // return max, because we should return something anyway.
  5674. if (pos < 0) { return max; }
  5675.  
  5676. // If we came to start of buffer - that means vuffer is too small,
  5677. // return max too.
  5678. if (pos === 0) { return max; }
  5679.  
  5680. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  5681. };
  5682.  
  5683. },{"./common":41}],43:[function(require,module,exports){
  5684. 'use strict';
  5685.  
  5686. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  5687. // It doesn't worth to make additional optimizationa as in original.
  5688. // Small size is preferable.
  5689.  
  5690. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5691. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5692. //
  5693. // This software is provided 'as-is', without any express or implied
  5694. // warranty. In no event will the authors be held liable for any damages
  5695. // arising from the use of this software.
  5696. //
  5697. // Permission is granted to anyone to use this software for any purpose,
  5698. // including commercial applications, and to alter it and redistribute it
  5699. // freely, subject to the following restrictions:
  5700. //
  5701. // 1. The origin of this software must not be misrepresented; you must not
  5702. // claim that you wrote the original software. If you use this software
  5703. // in a product, an acknowledgment in the product documentation would be
  5704. // appreciated but is not required.
  5705. // 2. Altered source versions must be plainly marked as such, and must not be
  5706. // misrepresented as being the original software.
  5707. // 3. This notice may not be removed or altered from any source distribution.
  5708.  
  5709. function adler32(adler, buf, len, pos) {
  5710. var s1 = (adler & 0xffff) |0,
  5711. s2 = ((adler >>> 16) & 0xffff) |0,
  5712. n = 0;
  5713.  
  5714. while (len !== 0) {
  5715. // Set limit ~ twice less than 5552, to keep
  5716. // s2 in 31-bits, because we force signed ints.
  5717. // in other case %= will fail.
  5718. n = len > 2000 ? 2000 : len;
  5719. len -= n;
  5720.  
  5721. do {
  5722. s1 = (s1 + buf[pos++]) |0;
  5723. s2 = (s2 + s1) |0;
  5724. } while (--n);
  5725.  
  5726. s1 %= 65521;
  5727. s2 %= 65521;
  5728. }
  5729.  
  5730. return (s1 | (s2 << 16)) |0;
  5731. }
  5732.  
  5733.  
  5734. module.exports = adler32;
  5735.  
  5736. },{}],44:[function(require,module,exports){
  5737. 'use strict';
  5738.  
  5739. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5740. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5741. //
  5742. // This software is provided 'as-is', without any express or implied
  5743. // warranty. In no event will the authors be held liable for any damages
  5744. // arising from the use of this software.
  5745. //
  5746. // Permission is granted to anyone to use this software for any purpose,
  5747. // including commercial applications, and to alter it and redistribute it
  5748. // freely, subject to the following restrictions:
  5749. //
  5750. // 1. The origin of this software must not be misrepresented; you must not
  5751. // claim that you wrote the original software. If you use this software
  5752. // in a product, an acknowledgment in the product documentation would be
  5753. // appreciated but is not required.
  5754. // 2. Altered source versions must be plainly marked as such, and must not be
  5755. // misrepresented as being the original software.
  5756. // 3. This notice may not be removed or altered from any source distribution.
  5757.  
  5758. module.exports = {
  5759.  
  5760. /* Allowed flush values; see deflate() and inflate() below for details */
  5761. Z_NO_FLUSH: 0,
  5762. Z_PARTIAL_FLUSH: 1,
  5763. Z_SYNC_FLUSH: 2,
  5764. Z_FULL_FLUSH: 3,
  5765. Z_FINISH: 4,
  5766. Z_BLOCK: 5,
  5767. Z_TREES: 6,
  5768.  
  5769. /* Return codes for the compression/decompression functions. Negative values
  5770. * are errors, positive values are used for special but normal events.
  5771. */
  5772. Z_OK: 0,
  5773. Z_STREAM_END: 1,
  5774. Z_NEED_DICT: 2,
  5775. Z_ERRNO: -1,
  5776. Z_STREAM_ERROR: -2,
  5777. Z_DATA_ERROR: -3,
  5778. //Z_MEM_ERROR: -4,
  5779. Z_BUF_ERROR: -5,
  5780. //Z_VERSION_ERROR: -6,
  5781.  
  5782. /* compression levels */
  5783. Z_NO_COMPRESSION: 0,
  5784. Z_BEST_SPEED: 1,
  5785. Z_BEST_COMPRESSION: 9,
  5786. Z_DEFAULT_COMPRESSION: -1,
  5787.  
  5788.  
  5789. Z_FILTERED: 1,
  5790. Z_HUFFMAN_ONLY: 2,
  5791. Z_RLE: 3,
  5792. Z_FIXED: 4,
  5793. Z_DEFAULT_STRATEGY: 0,
  5794.  
  5795. /* Possible values of the data_type field (though see inflate()) */
  5796. Z_BINARY: 0,
  5797. Z_TEXT: 1,
  5798. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  5799. Z_UNKNOWN: 2,
  5800.  
  5801. /* The deflate compression method */
  5802. Z_DEFLATED: 8
  5803. //Z_NULL: null // Use -1 or null inline, depending on var type
  5804. };
  5805.  
  5806. },{}],45:[function(require,module,exports){
  5807. 'use strict';
  5808.  
  5809. // Note: we can't get significant speed boost here.
  5810. // So write code to minimize size - no pregenerated tables
  5811. // and array tools dependencies.
  5812.  
  5813. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5814. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5815. //
  5816. // This software is provided 'as-is', without any express or implied
  5817. // warranty. In no event will the authors be held liable for any damages
  5818. // arising from the use of this software.
  5819. //
  5820. // Permission is granted to anyone to use this software for any purpose,
  5821. // including commercial applications, and to alter it and redistribute it
  5822. // freely, subject to the following restrictions:
  5823. //
  5824. // 1. The origin of this software must not be misrepresented; you must not
  5825. // claim that you wrote the original software. If you use this software
  5826. // in a product, an acknowledgment in the product documentation would be
  5827. // appreciated but is not required.
  5828. // 2. Altered source versions must be plainly marked as such, and must not be
  5829. // misrepresented as being the original software.
  5830. // 3. This notice may not be removed or altered from any source distribution.
  5831.  
  5832. // Use ordinary array, since untyped makes no boost here
  5833. function makeTable() {
  5834. var c, table = [];
  5835.  
  5836. for (var n = 0; n < 256; n++) {
  5837. c = n;
  5838. for (var k = 0; k < 8; k++) {
  5839. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  5840. }
  5841. table[n] = c;
  5842. }
  5843.  
  5844. return table;
  5845. }
  5846.  
  5847. // Create table on load. Just 255 signed longs. Not a problem.
  5848. var crcTable = makeTable();
  5849.  
  5850.  
  5851. function crc32(crc, buf, len, pos) {
  5852. var t = crcTable,
  5853. end = pos + len;
  5854.  
  5855. crc ^= -1;
  5856.  
  5857. for (var i = pos; i < end; i++) {
  5858. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  5859. }
  5860.  
  5861. return (crc ^ (-1)); // >>> 0;
  5862. }
  5863.  
  5864.  
  5865. module.exports = crc32;
  5866.  
  5867. },{}],46:[function(require,module,exports){
  5868. 'use strict';
  5869.  
  5870. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5871. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5872. //
  5873. // This software is provided 'as-is', without any express or implied
  5874. // warranty. In no event will the authors be held liable for any damages
  5875. // arising from the use of this software.
  5876. //
  5877. // Permission is granted to anyone to use this software for any purpose,
  5878. // including commercial applications, and to alter it and redistribute it
  5879. // freely, subject to the following restrictions:
  5880. //
  5881. // 1. The origin of this software must not be misrepresented; you must not
  5882. // claim that you wrote the original software. If you use this software
  5883. // in a product, an acknowledgment in the product documentation would be
  5884. // appreciated but is not required.
  5885. // 2. Altered source versions must be plainly marked as such, and must not be
  5886. // misrepresented as being the original software.
  5887. // 3. This notice may not be removed or altered from any source distribution.
  5888.  
  5889. var utils = require('../utils/common');
  5890. var trees = require('./trees');
  5891. var adler32 = require('./adler32');
  5892. var crc32 = require('./crc32');
  5893. var msg = require('./messages');
  5894.  
  5895. /* Public constants ==========================================================*/
  5896. /* ===========================================================================*/
  5897.  
  5898.  
  5899. /* Allowed flush values; see deflate() and inflate() below for details */
  5900. var Z_NO_FLUSH = 0;
  5901. var Z_PARTIAL_FLUSH = 1;
  5902. //var Z_SYNC_FLUSH = 2;
  5903. var Z_FULL_FLUSH = 3;
  5904. var Z_FINISH = 4;
  5905. var Z_BLOCK = 5;
  5906. //var Z_TREES = 6;
  5907.  
  5908.  
  5909. /* Return codes for the compression/decompression functions. Negative values
  5910. * are errors, positive values are used for special but normal events.
  5911. */
  5912. var Z_OK = 0;
  5913. var Z_STREAM_END = 1;
  5914. //var Z_NEED_DICT = 2;
  5915. //var Z_ERRNO = -1;
  5916. var Z_STREAM_ERROR = -2;
  5917. var Z_DATA_ERROR = -3;
  5918. //var Z_MEM_ERROR = -4;
  5919. var Z_BUF_ERROR = -5;
  5920. //var Z_VERSION_ERROR = -6;
  5921.  
  5922.  
  5923. /* compression levels */
  5924. //var Z_NO_COMPRESSION = 0;
  5925. //var Z_BEST_SPEED = 1;
  5926. //var Z_BEST_COMPRESSION = 9;
  5927. var Z_DEFAULT_COMPRESSION = -1;
  5928.  
  5929.  
  5930. var Z_FILTERED = 1;
  5931. var Z_HUFFMAN_ONLY = 2;
  5932. var Z_RLE = 3;
  5933. var Z_FIXED = 4;
  5934. var Z_DEFAULT_STRATEGY = 0;
  5935.  
  5936. /* Possible values of the data_type field (though see inflate()) */
  5937. //var Z_BINARY = 0;
  5938. //var Z_TEXT = 1;
  5939. //var Z_ASCII = 1; // = Z_TEXT
  5940. var Z_UNKNOWN = 2;
  5941.  
  5942.  
  5943. /* The deflate compression method */
  5944. var Z_DEFLATED = 8;
  5945.  
  5946. /*============================================================================*/
  5947.  
  5948.  
  5949. var MAX_MEM_LEVEL = 9;
  5950. /* Maximum value for memLevel in deflateInit2 */
  5951. var MAX_WBITS = 15;
  5952. /* 32K LZ77 window */
  5953. var DEF_MEM_LEVEL = 8;
  5954.  
  5955.  
  5956. var LENGTH_CODES = 29;
  5957. /* number of length codes, not counting the special END_BLOCK code */
  5958. var LITERALS = 256;
  5959. /* number of literal bytes 0..255 */
  5960. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  5961. /* number of Literal or Length codes, including the END_BLOCK code */
  5962. var D_CODES = 30;
  5963. /* number of distance codes */
  5964. var BL_CODES = 19;
  5965. /* number of codes used to transfer the bit lengths */
  5966. var HEAP_SIZE = 2 * L_CODES + 1;
  5967. /* maximum heap size */
  5968. var MAX_BITS = 15;
  5969. /* All codes must not exceed MAX_BITS bits */
  5970.  
  5971. var MIN_MATCH = 3;
  5972. var MAX_MATCH = 258;
  5973. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  5974.  
  5975. var PRESET_DICT = 0x20;
  5976.  
  5977. var INIT_STATE = 42;
  5978. var EXTRA_STATE = 69;
  5979. var NAME_STATE = 73;
  5980. var COMMENT_STATE = 91;
  5981. var HCRC_STATE = 103;
  5982. var BUSY_STATE = 113;
  5983. var FINISH_STATE = 666;
  5984.  
  5985. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  5986. var BS_BLOCK_DONE = 2; /* block flush performed */
  5987. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  5988. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  5989.  
  5990. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  5991.  
  5992. function err(strm, errorCode) {
  5993. strm.msg = msg[errorCode];
  5994. return errorCode;
  5995. }
  5996.  
  5997. function rank(f) {
  5998. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  5999. }
  6000.  
  6001. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  6002.  
  6003.  
  6004. /* =========================================================================
  6005. * Flush as much pending output as possible. All deflate() output goes
  6006. * through this function so some applications may wish to modify it
  6007. * to avoid allocating a large strm->output buffer and copying into it.
  6008. * (See also read_buf()).
  6009. */
  6010. function flush_pending(strm) {
  6011. var s = strm.state;
  6012.  
  6013. //_tr_flush_bits(s);
  6014. var len = s.pending;
  6015. if (len > strm.avail_out) {
  6016. len = strm.avail_out;
  6017. }
  6018. if (len === 0) { return; }
  6019.  
  6020. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  6021. strm.next_out += len;
  6022. s.pending_out += len;
  6023. strm.total_out += len;
  6024. strm.avail_out -= len;
  6025. s.pending -= len;
  6026. if (s.pending === 0) {
  6027. s.pending_out = 0;
  6028. }
  6029. }
  6030.  
  6031.  
  6032. function flush_block_only(s, last) {
  6033. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  6034. s.block_start = s.strstart;
  6035. flush_pending(s.strm);
  6036. }
  6037.  
  6038.  
  6039. function put_byte(s, b) {
  6040. s.pending_buf[s.pending++] = b;
  6041. }
  6042.  
  6043.  
  6044. /* =========================================================================
  6045. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  6046. * IN assertion: the stream state is correct and there is enough room in
  6047. * pending_buf.
  6048. */
  6049. function putShortMSB(s, b) {
  6050. // put_byte(s, (Byte)(b >> 8));
  6051. // put_byte(s, (Byte)(b & 0xff));
  6052. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  6053. s.pending_buf[s.pending++] = b & 0xff;
  6054. }
  6055.  
  6056.  
  6057. /* ===========================================================================
  6058. * Read a new buffer from the current input stream, update the adler32
  6059. * and total number of bytes read. All deflate() input goes through
  6060. * this function so some applications may wish to modify it to avoid
  6061. * allocating a large strm->input buffer and copying from it.
  6062. * (See also flush_pending()).
  6063. */
  6064. function read_buf(strm, buf, start, size) {
  6065. var len = strm.avail_in;
  6066.  
  6067. if (len > size) { len = size; }
  6068. if (len === 0) { return 0; }
  6069.  
  6070. strm.avail_in -= len;
  6071.  
  6072. // zmemcpy(buf, strm->next_in, len);
  6073. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  6074. if (strm.state.wrap === 1) {
  6075. strm.adler = adler32(strm.adler, buf, len, start);
  6076. }
  6077.  
  6078. else if (strm.state.wrap === 2) {
  6079. strm.adler = crc32(strm.adler, buf, len, start);
  6080. }
  6081.  
  6082. strm.next_in += len;
  6083. strm.total_in += len;
  6084.  
  6085. return len;
  6086. }
  6087.  
  6088.  
  6089. /* ===========================================================================
  6090. * Set match_start to the longest match starting at the given string and
  6091. * return its length. Matches shorter or equal to prev_length are discarded,
  6092. * in which case the result is equal to prev_length and match_start is
  6093. * garbage.
  6094. * IN assertions: cur_match is the head of the hash chain for the current
  6095. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  6096. * OUT assertion: the match length is not greater than s->lookahead.
  6097. */
  6098. function longest_match(s, cur_match) {
  6099. var chain_length = s.max_chain_length; /* max hash chain length */
  6100. var scan = s.strstart; /* current string */
  6101. var match; /* matched string */
  6102. var len; /* length of current match */
  6103. var best_len = s.prev_length; /* best match length so far */
  6104. var nice_match = s.nice_match; /* stop if match long enough */
  6105. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  6106. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  6107.  
  6108. var _win = s.window; // shortcut
  6109.  
  6110. var wmask = s.w_mask;
  6111. var prev = s.prev;
  6112.  
  6113. /* Stop when cur_match becomes <= limit. To simplify the code,
  6114. * we prevent matches with the string of window index 0.
  6115. */
  6116.  
  6117. var strend = s.strstart + MAX_MATCH;
  6118. var scan_end1 = _win[scan + best_len - 1];
  6119. var scan_end = _win[scan + best_len];
  6120.  
  6121. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  6122. * It is easy to get rid of this optimization if necessary.
  6123. */
  6124. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  6125.  
  6126. /* Do not waste too much time if we already have a good match: */
  6127. if (s.prev_length >= s.good_match) {
  6128. chain_length >>= 2;
  6129. }
  6130. /* Do not look for matches beyond the end of the input. This is necessary
  6131. * to make deflate deterministic.
  6132. */
  6133. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  6134.  
  6135. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  6136.  
  6137. do {
  6138. // Assert(cur_match < s->strstart, "no future");
  6139. match = cur_match;
  6140.  
  6141. /* Skip to next match if the match length cannot increase
  6142. * or if the match length is less than 2. Note that the checks below
  6143. * for insufficient lookahead only occur occasionally for performance
  6144. * reasons. Therefore uninitialized memory will be accessed, and
  6145. * conditional jumps will be made that depend on those values.
  6146. * However the length of the match is limited to the lookahead, so
  6147. * the output of deflate is not affected by the uninitialized values.
  6148. */
  6149.  
  6150. if (_win[match + best_len] !== scan_end ||
  6151. _win[match + best_len - 1] !== scan_end1 ||
  6152. _win[match] !== _win[scan] ||
  6153. _win[++match] !== _win[scan + 1]) {
  6154. continue;
  6155. }
  6156.  
  6157. /* The check at best_len-1 can be removed because it will be made
  6158. * again later. (This heuristic is not always a win.)
  6159. * It is not necessary to compare scan[2] and match[2] since they
  6160. * are always equal when the other bytes match, given that
  6161. * the hash keys are equal and that HASH_BITS >= 8.
  6162. */
  6163. scan += 2;
  6164. match++;
  6165. // Assert(*scan == *match, "match[2]?");
  6166.  
  6167. /* We check for insufficient lookahead only every 8th comparison;
  6168. * the 256th check will be made at strstart+258.
  6169. */
  6170. do {
  6171. /*jshint noempty:false*/
  6172. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6173. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6174. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6175. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6176. scan < strend);
  6177.  
  6178. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  6179.  
  6180. len = MAX_MATCH - (strend - scan);
  6181. scan = strend - MAX_MATCH;
  6182.  
  6183. if (len > best_len) {
  6184. s.match_start = cur_match;
  6185. best_len = len;
  6186. if (len >= nice_match) {
  6187. break;
  6188. }
  6189. scan_end1 = _win[scan + best_len - 1];
  6190. scan_end = _win[scan + best_len];
  6191. }
  6192. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  6193.  
  6194. if (best_len <= s.lookahead) {
  6195. return best_len;
  6196. }
  6197. return s.lookahead;
  6198. }
  6199.  
  6200.  
  6201. /* ===========================================================================
  6202. * Fill the window when the lookahead becomes insufficient.
  6203. * Updates strstart and lookahead.
  6204. *
  6205. * IN assertion: lookahead < MIN_LOOKAHEAD
  6206. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  6207. * At least one byte has been read, or avail_in == 0; reads are
  6208. * performed for at least two bytes (required for the zip translate_eol
  6209. * option -- not supported here).
  6210. */
  6211. function fill_window(s) {
  6212. var _w_size = s.w_size;
  6213. var p, n, m, more, str;
  6214.  
  6215. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  6216.  
  6217. do {
  6218. more = s.window_size - s.lookahead - s.strstart;
  6219.  
  6220. // JS ints have 32 bit, block below not needed
  6221. /* Deal with !@#$% 64K limit: */
  6222. //if (sizeof(int) <= 2) {
  6223. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  6224. // more = wsize;
  6225. //
  6226. // } else if (more == (unsigned)(-1)) {
  6227. // /* Very unlikely, but possible on 16 bit machine if
  6228. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  6229. // */
  6230. // more--;
  6231. // }
  6232. //}
  6233.  
  6234.  
  6235. /* If the window is almost full and there is insufficient lookahead,
  6236. * move the upper half to the lower one to make room in the upper half.
  6237. */
  6238. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  6239.  
  6240. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  6241. s.match_start -= _w_size;
  6242. s.strstart -= _w_size;
  6243. /* we now have strstart >= MAX_DIST */
  6244. s.block_start -= _w_size;
  6245.  
  6246. /* Slide the hash table (could be avoided with 32 bit values
  6247. at the expense of memory usage). We slide even when level == 0
  6248. to keep the hash table consistent if we switch back to level > 0
  6249. later. (Using level 0 permanently is not an optimal usage of
  6250. zlib, so we don't care about this pathological case.)
  6251. */
  6252.  
  6253. n = s.hash_size;
  6254. p = n;
  6255. do {
  6256. m = s.head[--p];
  6257. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  6258. } while (--n);
  6259.  
  6260. n = _w_size;
  6261. p = n;
  6262. do {
  6263. m = s.prev[--p];
  6264. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  6265. /* If n is not on any hash chain, prev[n] is garbage but
  6266. * its value will never be used.
  6267. */
  6268. } while (--n);
  6269.  
  6270. more += _w_size;
  6271. }
  6272. if (s.strm.avail_in === 0) {
  6273. break;
  6274. }
  6275.  
  6276. /* If there was no sliding:
  6277. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  6278. * more == window_size - lookahead - strstart
  6279. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  6280. * => more >= window_size - 2*WSIZE + 2
  6281. * In the BIG_MEM or MMAP case (not yet supported),
  6282. * window_size == input_size + MIN_LOOKAHEAD &&
  6283. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  6284. * Otherwise, window_size == 2*WSIZE so more >= 2.
  6285. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  6286. */
  6287. //Assert(more >= 2, "more < 2");
  6288. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  6289. s.lookahead += n;
  6290.  
  6291. /* Initialize the hash value now that we have some input: */
  6292. if (s.lookahead + s.insert >= MIN_MATCH) {
  6293. str = s.strstart - s.insert;
  6294. s.ins_h = s.window[str];
  6295.  
  6296. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  6297. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  6298. //#if MIN_MATCH != 3
  6299. // Call update_hash() MIN_MATCH-3 more times
  6300. //#endif
  6301. while (s.insert) {
  6302. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6303. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  6304.  
  6305. s.prev[str & s.w_mask] = s.head[s.ins_h];
  6306. s.head[s.ins_h] = str;
  6307. str++;
  6308. s.insert--;
  6309. if (s.lookahead + s.insert < MIN_MATCH) {
  6310. break;
  6311. }
  6312. }
  6313. }
  6314. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  6315. * but this is not important since only literal bytes will be emitted.
  6316. */
  6317.  
  6318. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  6319.  
  6320. /* If the WIN_INIT bytes after the end of the current data have never been
  6321. * written, then zero those bytes in order to avoid memory check reports of
  6322. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  6323. * the longest match routines. Update the high water mark for the next
  6324. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  6325. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  6326. */
  6327. // if (s.high_water < s.window_size) {
  6328. // var curr = s.strstart + s.lookahead;
  6329. // var init = 0;
  6330. //
  6331. // if (s.high_water < curr) {
  6332. // /* Previous high water mark below current data -- zero WIN_INIT
  6333. // * bytes or up to end of window, whichever is less.
  6334. // */
  6335. // init = s.window_size - curr;
  6336. // if (init > WIN_INIT)
  6337. // init = WIN_INIT;
  6338. // zmemzero(s->window + curr, (unsigned)init);
  6339. // s->high_water = curr + init;
  6340. // }
  6341. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  6342. // /* High water mark at or above current data, but below current data
  6343. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  6344. // * to end of window, whichever is less.
  6345. // */
  6346. // init = (ulg)curr + WIN_INIT - s->high_water;
  6347. // if (init > s->window_size - s->high_water)
  6348. // init = s->window_size - s->high_water;
  6349. // zmemzero(s->window + s->high_water, (unsigned)init);
  6350. // s->high_water += init;
  6351. // }
  6352. // }
  6353. //
  6354. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  6355. // "not enough room for search");
  6356. }
  6357.  
  6358. /* ===========================================================================
  6359. * Copy without compression as much as possible from the input stream, return
  6360. * the current block state.
  6361. * This function does not insert new strings in the dictionary since
  6362. * uncompressible data is probably not useful. This function is used
  6363. * only for the level=0 compression option.
  6364. * NOTE: this function should be optimized to avoid extra copying from
  6365. * window to pending_buf.
  6366. */
  6367. function deflate_stored(s, flush) {
  6368. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  6369. * to pending_buf_size, and each stored block has a 5 byte header:
  6370. */
  6371. var max_block_size = 0xffff;
  6372.  
  6373. if (max_block_size > s.pending_buf_size - 5) {
  6374. max_block_size = s.pending_buf_size - 5;
  6375. }
  6376.  
  6377. /* Copy as much as possible from input to output: */
  6378. for (;;) {
  6379. /* Fill the window as much as possible: */
  6380. if (s.lookahead <= 1) {
  6381.  
  6382. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  6383. // s->block_start >= (long)s->w_size, "slide too late");
  6384. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  6385. // s.block_start >= s.w_size)) {
  6386. // throw new Error("slide too late");
  6387. // }
  6388.  
  6389. fill_window(s);
  6390. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  6391. return BS_NEED_MORE;
  6392. }
  6393.  
  6394. if (s.lookahead === 0) {
  6395. break;
  6396. }
  6397. /* flush the current block */
  6398. }
  6399. //Assert(s->block_start >= 0L, "block gone");
  6400. // if (s.block_start < 0) throw new Error("block gone");
  6401.  
  6402. s.strstart += s.lookahead;
  6403. s.lookahead = 0;
  6404.  
  6405. /* Emit a stored block if pending_buf will be full: */
  6406. var max_start = s.block_start + max_block_size;
  6407.  
  6408. if (s.strstart === 0 || s.strstart >= max_start) {
  6409. /* strstart == 0 is possible when wraparound on 16-bit machine */
  6410. s.lookahead = s.strstart - max_start;
  6411. s.strstart = max_start;
  6412. /*** FLUSH_BLOCK(s, 0); ***/
  6413. flush_block_only(s, false);
  6414. if (s.strm.avail_out === 0) {
  6415. return BS_NEED_MORE;
  6416. }
  6417. /***/
  6418.  
  6419.  
  6420. }
  6421. /* Flush if we may have to slide, otherwise block_start may become
  6422. * negative and the data will be gone:
  6423. */
  6424. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  6425. /*** FLUSH_BLOCK(s, 0); ***/
  6426. flush_block_only(s, false);
  6427. if (s.strm.avail_out === 0) {
  6428. return BS_NEED_MORE;
  6429. }
  6430. /***/
  6431. }
  6432. }
  6433.  
  6434. s.insert = 0;
  6435.  
  6436. if (flush === Z_FINISH) {
  6437. /*** FLUSH_BLOCK(s, 1); ***/
  6438. flush_block_only(s, true);
  6439. if (s.strm.avail_out === 0) {
  6440. return BS_FINISH_STARTED;
  6441. }
  6442. /***/
  6443. return BS_FINISH_DONE;
  6444. }
  6445.  
  6446. if (s.strstart > s.block_start) {
  6447. /*** FLUSH_BLOCK(s, 0); ***/
  6448. flush_block_only(s, false);
  6449. if (s.strm.avail_out === 0) {
  6450. return BS_NEED_MORE;
  6451. }
  6452. /***/
  6453. }
  6454.  
  6455. return BS_NEED_MORE;
  6456. }
  6457.  
  6458. /* ===========================================================================
  6459. * Compress as much as possible from the input stream, return the current
  6460. * block state.
  6461. * This function does not perform lazy evaluation of matches and inserts
  6462. * new strings in the dictionary only for unmatched strings or for short
  6463. * matches. It is used only for the fast compression options.
  6464. */
  6465. function deflate_fast(s, flush) {
  6466. var hash_head; /* head of the hash chain */
  6467. var bflush; /* set if current block must be flushed */
  6468.  
  6469. for (;;) {
  6470. /* Make sure that we always have enough lookahead, except
  6471. * at the end of the input file. We need MAX_MATCH bytes
  6472. * for the next match, plus MIN_MATCH bytes to insert the
  6473. * string following the next match.
  6474. */
  6475. if (s.lookahead < MIN_LOOKAHEAD) {
  6476. fill_window(s);
  6477. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6478. return BS_NEED_MORE;
  6479. }
  6480. if (s.lookahead === 0) {
  6481. break; /* flush the current block */
  6482. }
  6483. }
  6484.  
  6485. /* Insert the string window[strstart .. strstart+2] in the
  6486. * dictionary, and set hash_head to the head of the hash chain:
  6487. */
  6488. hash_head = 0/*NIL*/;
  6489. if (s.lookahead >= MIN_MATCH) {
  6490. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6491. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6492. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6493. s.head[s.ins_h] = s.strstart;
  6494. /***/
  6495. }
  6496.  
  6497. /* Find the longest match, discarding those <= prev_length.
  6498. * At this point we have always match_length < MIN_MATCH
  6499. */
  6500. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  6501. /* To simplify the code, we prevent matches with the string
  6502. * of window index 0 (in particular we have to avoid a match
  6503. * of the string with itself at the start of the input file).
  6504. */
  6505. s.match_length = longest_match(s, hash_head);
  6506. /* longest_match() sets match_start */
  6507. }
  6508. if (s.match_length >= MIN_MATCH) {
  6509. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  6510.  
  6511. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  6512. s.match_length - MIN_MATCH, bflush); ***/
  6513. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  6514.  
  6515. s.lookahead -= s.match_length;
  6516.  
  6517. /* Insert new strings in the hash table only if the match length
  6518. * is not too large. This saves time but degrades compression.
  6519. */
  6520. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  6521. s.match_length--; /* string at strstart already in table */
  6522. do {
  6523. s.strstart++;
  6524. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6525. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6526. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6527. s.head[s.ins_h] = s.strstart;
  6528. /***/
  6529. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  6530. * always MIN_MATCH bytes ahead.
  6531. */
  6532. } while (--s.match_length !== 0);
  6533. s.strstart++;
  6534. } else
  6535. {
  6536. s.strstart += s.match_length;
  6537. s.match_length = 0;
  6538. s.ins_h = s.window[s.strstart];
  6539. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  6540. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  6541.  
  6542. //#if MIN_MATCH != 3
  6543. // Call UPDATE_HASH() MIN_MATCH-3 more times
  6544. //#endif
  6545. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  6546. * matter since it will be recomputed at next deflate call.
  6547. */
  6548. }
  6549. } else {
  6550. /* No match, output a literal byte */
  6551. //Tracevv((stderr,"%c", s.window[s.strstart]));
  6552. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6553. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6554.  
  6555. s.lookahead--;
  6556. s.strstart++;
  6557. }
  6558. if (bflush) {
  6559. /*** FLUSH_BLOCK(s, 0); ***/
  6560. flush_block_only(s, false);
  6561. if (s.strm.avail_out === 0) {
  6562. return BS_NEED_MORE;
  6563. }
  6564. /***/
  6565. }
  6566. }
  6567. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  6568. if (flush === Z_FINISH) {
  6569. /*** FLUSH_BLOCK(s, 1); ***/
  6570. flush_block_only(s, true);
  6571. if (s.strm.avail_out === 0) {
  6572. return BS_FINISH_STARTED;
  6573. }
  6574. /***/
  6575. return BS_FINISH_DONE;
  6576. }
  6577. if (s.last_lit) {
  6578. /*** FLUSH_BLOCK(s, 0); ***/
  6579. flush_block_only(s, false);
  6580. if (s.strm.avail_out === 0) {
  6581. return BS_NEED_MORE;
  6582. }
  6583. /***/
  6584. }
  6585. return BS_BLOCK_DONE;
  6586. }
  6587.  
  6588. /* ===========================================================================
  6589. * Same as above, but achieves better compression. We use a lazy
  6590. * evaluation for matches: a match is finally adopted only if there is
  6591. * no better match at the next window position.
  6592. */
  6593. function deflate_slow(s, flush) {
  6594. var hash_head; /* head of hash chain */
  6595. var bflush; /* set if current block must be flushed */
  6596.  
  6597. var max_insert;
  6598.  
  6599. /* Process the input block. */
  6600. for (;;) {
  6601. /* Make sure that we always have enough lookahead, except
  6602. * at the end of the input file. We need MAX_MATCH bytes
  6603. * for the next match, plus MIN_MATCH bytes to insert the
  6604. * string following the next match.
  6605. */
  6606. if (s.lookahead < MIN_LOOKAHEAD) {
  6607. fill_window(s);
  6608. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6609. return BS_NEED_MORE;
  6610. }
  6611. if (s.lookahead === 0) { break; } /* flush the current block */
  6612. }
  6613.  
  6614. /* Insert the string window[strstart .. strstart+2] in the
  6615. * dictionary, and set hash_head to the head of the hash chain:
  6616. */
  6617. hash_head = 0/*NIL*/;
  6618. if (s.lookahead >= MIN_MATCH) {
  6619. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6620. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6621. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6622. s.head[s.ins_h] = s.strstart;
  6623. /***/
  6624. }
  6625.  
  6626. /* Find the longest match, discarding those <= prev_length.
  6627. */
  6628. s.prev_length = s.match_length;
  6629. s.prev_match = s.match_start;
  6630. s.match_length = MIN_MATCH - 1;
  6631.  
  6632. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  6633. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  6634. /* To simplify the code, we prevent matches with the string
  6635. * of window index 0 (in particular we have to avoid a match
  6636. * of the string with itself at the start of the input file).
  6637. */
  6638. s.match_length = longest_match(s, hash_head);
  6639. /* longest_match() sets match_start */
  6640.  
  6641. if (s.match_length <= 5 &&
  6642. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  6643.  
  6644. /* If prev_match is also MIN_MATCH, match_start is garbage
  6645. * but we will ignore the current match anyway.
  6646. */
  6647. s.match_length = MIN_MATCH - 1;
  6648. }
  6649. }
  6650. /* If there was a match at the previous step and the current
  6651. * match is not better, output the previous match:
  6652. */
  6653. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  6654. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  6655. /* Do not insert strings in hash table beyond this. */
  6656.  
  6657. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  6658.  
  6659. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  6660. s.prev_length - MIN_MATCH, bflush);***/
  6661. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  6662. /* Insert in hash table all strings up to the end of the match.
  6663. * strstart-1 and strstart are already inserted. If there is not
  6664. * enough lookahead, the last two strings are not inserted in
  6665. * the hash table.
  6666. */
  6667. s.lookahead -= s.prev_length - 1;
  6668. s.prev_length -= 2;
  6669. do {
  6670. if (++s.strstart <= max_insert) {
  6671. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6672. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6673. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6674. s.head[s.ins_h] = s.strstart;
  6675. /***/
  6676. }
  6677. } while (--s.prev_length !== 0);
  6678. s.match_available = 0;
  6679. s.match_length = MIN_MATCH - 1;
  6680. s.strstart++;
  6681.  
  6682. if (bflush) {
  6683. /*** FLUSH_BLOCK(s, 0); ***/
  6684. flush_block_only(s, false);
  6685. if (s.strm.avail_out === 0) {
  6686. return BS_NEED_MORE;
  6687. }
  6688. /***/
  6689. }
  6690.  
  6691. } else if (s.match_available) {
  6692. /* If there was no match at the previous position, output a
  6693. * single literal. If there was a match but the current match
  6694. * is longer, truncate the previous match to a single literal.
  6695. */
  6696. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6697. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6698. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6699.  
  6700. if (bflush) {
  6701. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  6702. flush_block_only(s, false);
  6703. /***/
  6704. }
  6705. s.strstart++;
  6706. s.lookahead--;
  6707. if (s.strm.avail_out === 0) {
  6708. return BS_NEED_MORE;
  6709. }
  6710. } else {
  6711. /* There is no previous match to compare with, wait for
  6712. * the next step to decide.
  6713. */
  6714. s.match_available = 1;
  6715. s.strstart++;
  6716. s.lookahead--;
  6717. }
  6718. }
  6719. //Assert (flush != Z_NO_FLUSH, "no flush?");
  6720. if (s.match_available) {
  6721. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6722. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6723. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6724.  
  6725. s.match_available = 0;
  6726. }
  6727. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  6728. if (flush === Z_FINISH) {
  6729. /*** FLUSH_BLOCK(s, 1); ***/
  6730. flush_block_only(s, true);
  6731. if (s.strm.avail_out === 0) {
  6732. return BS_FINISH_STARTED;
  6733. }
  6734. /***/
  6735. return BS_FINISH_DONE;
  6736. }
  6737. if (s.last_lit) {
  6738. /*** FLUSH_BLOCK(s, 0); ***/
  6739. flush_block_only(s, false);
  6740. if (s.strm.avail_out === 0) {
  6741. return BS_NEED_MORE;
  6742. }
  6743. /***/
  6744. }
  6745.  
  6746. return BS_BLOCK_DONE;
  6747. }
  6748.  
  6749.  
  6750. /* ===========================================================================
  6751. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  6752. * one. Do not maintain a hash table. (It will be regenerated if this run of
  6753. * deflate switches away from Z_RLE.)
  6754. */
  6755. function deflate_rle(s, flush) {
  6756. var bflush; /* set if current block must be flushed */
  6757. var prev; /* byte at distance one to match */
  6758. var scan, strend; /* scan goes up to strend for length of run */
  6759.  
  6760. var _win = s.window;
  6761.  
  6762. for (;;) {
  6763. /* Make sure that we always have enough lookahead, except
  6764. * at the end of the input file. We need MAX_MATCH bytes
  6765. * for the longest run, plus one for the unrolled loop.
  6766. */
  6767. if (s.lookahead <= MAX_MATCH) {
  6768. fill_window(s);
  6769. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  6770. return BS_NEED_MORE;
  6771. }
  6772. if (s.lookahead === 0) { break; } /* flush the current block */
  6773. }
  6774.  
  6775. /* See how many times the previous byte repeats */
  6776. s.match_length = 0;
  6777. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  6778. scan = s.strstart - 1;
  6779. prev = _win[scan];
  6780. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  6781. strend = s.strstart + MAX_MATCH;
  6782. do {
  6783. /*jshint noempty:false*/
  6784. } while (prev === _win[++scan] && prev === _win[++scan] &&
  6785. prev === _win[++scan] && prev === _win[++scan] &&
  6786. prev === _win[++scan] && prev === _win[++scan] &&
  6787. prev === _win[++scan] && prev === _win[++scan] &&
  6788. scan < strend);
  6789. s.match_length = MAX_MATCH - (strend - scan);
  6790. if (s.match_length > s.lookahead) {
  6791. s.match_length = s.lookahead;
  6792. }
  6793. }
  6794. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  6795. }
  6796.  
  6797. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  6798. if (s.match_length >= MIN_MATCH) {
  6799. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  6800.  
  6801. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  6802. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  6803.  
  6804. s.lookahead -= s.match_length;
  6805. s.strstart += s.match_length;
  6806. s.match_length = 0;
  6807. } else {
  6808. /* No match, output a literal byte */
  6809. //Tracevv((stderr,"%c", s->window[s->strstart]));
  6810. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6811. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6812.  
  6813. s.lookahead--;
  6814. s.strstart++;
  6815. }
  6816. if (bflush) {
  6817. /*** FLUSH_BLOCK(s, 0); ***/
  6818. flush_block_only(s, false);
  6819. if (s.strm.avail_out === 0) {
  6820. return BS_NEED_MORE;
  6821. }
  6822. /***/
  6823. }
  6824. }
  6825. s.insert = 0;
  6826. if (flush === Z_FINISH) {
  6827. /*** FLUSH_BLOCK(s, 1); ***/
  6828. flush_block_only(s, true);
  6829. if (s.strm.avail_out === 0) {
  6830. return BS_FINISH_STARTED;
  6831. }
  6832. /***/
  6833. return BS_FINISH_DONE;
  6834. }
  6835. if (s.last_lit) {
  6836. /*** FLUSH_BLOCK(s, 0); ***/
  6837. flush_block_only(s, false);
  6838. if (s.strm.avail_out === 0) {
  6839. return BS_NEED_MORE;
  6840. }
  6841. /***/
  6842. }
  6843. return BS_BLOCK_DONE;
  6844. }
  6845.  
  6846. /* ===========================================================================
  6847. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  6848. * (It will be regenerated if this run of deflate switches away from Huffman.)
  6849. */
  6850. function deflate_huff(s, flush) {
  6851. var bflush; /* set if current block must be flushed */
  6852.  
  6853. for (;;) {
  6854. /* Make sure that we have a literal to write. */
  6855. if (s.lookahead === 0) {
  6856. fill_window(s);
  6857. if (s.lookahead === 0) {
  6858. if (flush === Z_NO_FLUSH) {
  6859. return BS_NEED_MORE;
  6860. }
  6861. break; /* flush the current block */
  6862. }
  6863. }
  6864.  
  6865. /* Output a literal byte */
  6866. s.match_length = 0;
  6867. //Tracevv((stderr,"%c", s->window[s->strstart]));
  6868. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6869. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6870. s.lookahead--;
  6871. s.strstart++;
  6872. if (bflush) {
  6873. /*** FLUSH_BLOCK(s, 0); ***/
  6874. flush_block_only(s, false);
  6875. if (s.strm.avail_out === 0) {
  6876. return BS_NEED_MORE;
  6877. }
  6878. /***/
  6879. }
  6880. }
  6881. s.insert = 0;
  6882. if (flush === Z_FINISH) {
  6883. /*** FLUSH_BLOCK(s, 1); ***/
  6884. flush_block_only(s, true);
  6885. if (s.strm.avail_out === 0) {
  6886. return BS_FINISH_STARTED;
  6887. }
  6888. /***/
  6889. return BS_FINISH_DONE;
  6890. }
  6891. if (s.last_lit) {
  6892. /*** FLUSH_BLOCK(s, 0); ***/
  6893. flush_block_only(s, false);
  6894. if (s.strm.avail_out === 0) {
  6895. return BS_NEED_MORE;
  6896. }
  6897. /***/
  6898. }
  6899. return BS_BLOCK_DONE;
  6900. }
  6901.  
  6902. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  6903. * the desired pack level (0..9). The values given below have been tuned to
  6904. * exclude worst case performance for pathological files. Better values may be
  6905. * found for specific files.
  6906. */
  6907. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  6908. this.good_length = good_length;
  6909. this.max_lazy = max_lazy;
  6910. this.nice_length = nice_length;
  6911. this.max_chain = max_chain;
  6912. this.func = func;
  6913. }
  6914.  
  6915. var configuration_table;
  6916.  
  6917. configuration_table = [
  6918. /* good lazy nice chain */
  6919. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  6920. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  6921. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  6922. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  6923.  
  6924. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  6925. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  6926. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  6927. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  6928. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  6929. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  6930. ];
  6931.  
  6932.  
  6933. /* ===========================================================================
  6934. * Initialize the "longest match" routines for a new zlib stream
  6935. */
  6936. function lm_init(s) {
  6937. s.window_size = 2 * s.w_size;
  6938.  
  6939. /*** CLEAR_HASH(s); ***/
  6940. zero(s.head); // Fill with NIL (= 0);
  6941.  
  6942. /* Set the default configuration parameters:
  6943. */
  6944. s.max_lazy_match = configuration_table[s.level].max_lazy;
  6945. s.good_match = configuration_table[s.level].good_length;
  6946. s.nice_match = configuration_table[s.level].nice_length;
  6947. s.max_chain_length = configuration_table[s.level].max_chain;
  6948.  
  6949. s.strstart = 0;
  6950. s.block_start = 0;
  6951. s.lookahead = 0;
  6952. s.insert = 0;
  6953. s.match_length = s.prev_length = MIN_MATCH - 1;
  6954. s.match_available = 0;
  6955. s.ins_h = 0;
  6956. }
  6957.  
  6958.  
  6959. function DeflateState() {
  6960. this.strm = null; /* pointer back to this zlib stream */
  6961. this.status = 0; /* as the name implies */
  6962. this.pending_buf = null; /* output still pending */
  6963. this.pending_buf_size = 0; /* size of pending_buf */
  6964. this.pending_out = 0; /* next pending byte to output to the stream */
  6965. this.pending = 0; /* nb of bytes in the pending buffer */
  6966. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  6967. this.gzhead = null; /* gzip header information to write */
  6968. this.gzindex = 0; /* where in extra, name, or comment */
  6969. this.method = Z_DEFLATED; /* can only be DEFLATED */
  6970. this.last_flush = -1; /* value of flush param for previous deflate call */
  6971.  
  6972. this.w_size = 0; /* LZ77 window size (32K by default) */
  6973. this.w_bits = 0; /* log2(w_size) (8..16) */
  6974. this.w_mask = 0; /* w_size - 1 */
  6975.  
  6976. this.window = null;
  6977. /* Sliding window. Input bytes are read into the second half of the window,
  6978. * and move to the first half later to keep a dictionary of at least wSize
  6979. * bytes. With this organization, matches are limited to a distance of
  6980. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  6981. * performed with a length multiple of the block size.
  6982. */
  6983.  
  6984. this.window_size = 0;
  6985. /* Actual size of window: 2*wSize, except when the user input buffer
  6986. * is directly used as sliding window.
  6987. */
  6988.  
  6989. this.prev = null;
  6990. /* Link to older string with same hash index. To limit the size of this
  6991. * array to 64K, this link is maintained only for the last 32K strings.
  6992. * An index in this array is thus a window index modulo 32K.
  6993. */
  6994.  
  6995. this.head = null; /* Heads of the hash chains or NIL. */
  6996.  
  6997. this.ins_h = 0; /* hash index of string to be inserted */
  6998. this.hash_size = 0; /* number of elements in hash table */
  6999. this.hash_bits = 0; /* log2(hash_size) */
  7000. this.hash_mask = 0; /* hash_size-1 */
  7001.  
  7002. this.hash_shift = 0;
  7003. /* Number of bits by which ins_h must be shifted at each input
  7004. * step. It must be such that after MIN_MATCH steps, the oldest
  7005. * byte no longer takes part in the hash key, that is:
  7006. * hash_shift * MIN_MATCH >= hash_bits
  7007. */
  7008.  
  7009. this.block_start = 0;
  7010. /* Window position at the beginning of the current output block. Gets
  7011. * negative when the window is moved backwards.
  7012. */
  7013.  
  7014. this.match_length = 0; /* length of best match */
  7015. this.prev_match = 0; /* previous match */
  7016. this.match_available = 0; /* set if previous match exists */
  7017. this.strstart = 0; /* start of string to insert */
  7018. this.match_start = 0; /* start of matching string */
  7019. this.lookahead = 0; /* number of valid bytes ahead in window */
  7020.  
  7021. this.prev_length = 0;
  7022. /* Length of the best match at previous step. Matches not greater than this
  7023. * are discarded. This is used in the lazy match evaluation.
  7024. */
  7025.  
  7026. this.max_chain_length = 0;
  7027. /* To speed up deflation, hash chains are never searched beyond this
  7028. * length. A higher limit improves compression ratio but degrades the
  7029. * speed.
  7030. */
  7031.  
  7032. this.max_lazy_match = 0;
  7033. /* Attempt to find a better match only when the current match is strictly
  7034. * smaller than this value. This mechanism is used only for compression
  7035. * levels >= 4.
  7036. */
  7037. // That's alias to max_lazy_match, don't use directly
  7038. //this.max_insert_length = 0;
  7039. /* Insert new strings in the hash table only if the match length is not
  7040. * greater than this length. This saves time but degrades compression.
  7041. * max_insert_length is used only for compression levels <= 3.
  7042. */
  7043.  
  7044. this.level = 0; /* compression level (1..9) */
  7045. this.strategy = 0; /* favor or force Huffman coding*/
  7046.  
  7047. this.good_match = 0;
  7048. /* Use a faster search when the previous match is longer than this */
  7049.  
  7050. this.nice_match = 0; /* Stop searching when current match exceeds this */
  7051.  
  7052. /* used by trees.c: */
  7053.  
  7054. /* Didn't use ct_data typedef below to suppress compiler warning */
  7055.  
  7056. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  7057. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  7058. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  7059.  
  7060. // Use flat array of DOUBLE size, with interleaved fata,
  7061. // because JS does not support effective
  7062. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  7063. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  7064. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  7065. zero(this.dyn_ltree);
  7066. zero(this.dyn_dtree);
  7067. zero(this.bl_tree);
  7068.  
  7069. this.l_desc = null; /* desc. for literal tree */
  7070. this.d_desc = null; /* desc. for distance tree */
  7071. this.bl_desc = null; /* desc. for bit length tree */
  7072.  
  7073. //ush bl_count[MAX_BITS+1];
  7074. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  7075. /* number of codes at each bit length for an optimal tree */
  7076.  
  7077. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  7078. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  7079. zero(this.heap);
  7080.  
  7081. this.heap_len = 0; /* number of elements in the heap */
  7082. this.heap_max = 0; /* element of largest frequency */
  7083. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  7084. * The same heap array is used to build all trees.
  7085. */
  7086.  
  7087. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  7088. zero(this.depth);
  7089. /* Depth of each subtree used as tie breaker for trees of equal frequency
  7090. */
  7091.  
  7092. this.l_buf = 0; /* buffer index for literals or lengths */
  7093.  
  7094. this.lit_bufsize = 0;
  7095. /* Size of match buffer for literals/lengths. There are 4 reasons for
  7096. * limiting lit_bufsize to 64K:
  7097. * - frequencies can be kept in 16 bit counters
  7098. * - if compression is not successful for the first block, all input
  7099. * data is still in the window so we can still emit a stored block even
  7100. * when input comes from standard input. (This can also be done for
  7101. * all blocks if lit_bufsize is not greater than 32K.)
  7102. * - if compression is not successful for a file smaller than 64K, we can
  7103. * even emit a stored file instead of a stored block (saving 5 bytes).
  7104. * This is applicable only for zip (not gzip or zlib).
  7105. * - creating new Huffman trees less frequently may not provide fast
  7106. * adaptation to changes in the input data statistics. (Take for
  7107. * example a binary file with poorly compressible code followed by
  7108. * a highly compressible string table.) Smaller buffer sizes give
  7109. * fast adaptation but have of course the overhead of transmitting
  7110. * trees more frequently.
  7111. * - I can't count above 4
  7112. */
  7113.  
  7114. this.last_lit = 0; /* running index in l_buf */
  7115.  
  7116. this.d_buf = 0;
  7117. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  7118. * the same number of elements. To use different lengths, an extra flag
  7119. * array would be necessary.
  7120. */
  7121.  
  7122. this.opt_len = 0; /* bit length of current block with optimal trees */
  7123. this.static_len = 0; /* bit length of current block with static trees */
  7124. this.matches = 0; /* number of string matches in current block */
  7125. this.insert = 0; /* bytes at end of window left to insert */
  7126.  
  7127.  
  7128. this.bi_buf = 0;
  7129. /* Output buffer. bits are inserted starting at the bottom (least
  7130. * significant bits).
  7131. */
  7132. this.bi_valid = 0;
  7133. /* Number of valid bits in bi_buf. All bits above the last valid bit
  7134. * are always zero.
  7135. */
  7136.  
  7137. // Used for window memory init. We safely ignore it for JS. That makes
  7138. // sense only for pointers and memory check tools.
  7139. //this.high_water = 0;
  7140. /* High water mark offset in window for initialized bytes -- bytes above
  7141. * this are set to zero in order to avoid memory check warnings when
  7142. * longest match routines access bytes past the input. This is then
  7143. * updated to the new high water mark.
  7144. */
  7145. }
  7146.  
  7147.  
  7148. function deflateResetKeep(strm) {
  7149. var s;
  7150.  
  7151. if (!strm || !strm.state) {
  7152. return err(strm, Z_STREAM_ERROR);
  7153. }
  7154.  
  7155. strm.total_in = strm.total_out = 0;
  7156. strm.data_type = Z_UNKNOWN;
  7157.  
  7158. s = strm.state;
  7159. s.pending = 0;
  7160. s.pending_out = 0;
  7161.  
  7162. if (s.wrap < 0) {
  7163. s.wrap = -s.wrap;
  7164. /* was made negative by deflate(..., Z_FINISH); */
  7165. }
  7166. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  7167. strm.adler = (s.wrap === 2) ?
  7168. 0 // crc32(0, Z_NULL, 0)
  7169. :
  7170. 1; // adler32(0, Z_NULL, 0)
  7171. s.last_flush = Z_NO_FLUSH;
  7172. trees._tr_init(s);
  7173. return Z_OK;
  7174. }
  7175.  
  7176.  
  7177. function deflateReset(strm) {
  7178. var ret = deflateResetKeep(strm);
  7179. if (ret === Z_OK) {
  7180. lm_init(strm.state);
  7181. }
  7182. return ret;
  7183. }
  7184.  
  7185.  
  7186. function deflateSetHeader(strm, head) {
  7187. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7188. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  7189. strm.state.gzhead = head;
  7190. return Z_OK;
  7191. }
  7192.  
  7193.  
  7194. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  7195. if (!strm) { // === Z_NULL
  7196. return Z_STREAM_ERROR;
  7197. }
  7198. var wrap = 1;
  7199.  
  7200. if (level === Z_DEFAULT_COMPRESSION) {
  7201. level = 6;
  7202. }
  7203.  
  7204. if (windowBits < 0) { /* suppress zlib wrapper */
  7205. wrap = 0;
  7206. windowBits = -windowBits;
  7207. }
  7208.  
  7209. else if (windowBits > 15) {
  7210. wrap = 2; /* write gzip wrapper instead */
  7211. windowBits -= 16;
  7212. }
  7213.  
  7214.  
  7215. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  7216. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  7217. strategy < 0 || strategy > Z_FIXED) {
  7218. return err(strm, Z_STREAM_ERROR);
  7219. }
  7220.  
  7221.  
  7222. if (windowBits === 8) {
  7223. windowBits = 9;
  7224. }
  7225. /* until 256-byte window bug fixed */
  7226.  
  7227. var s = new DeflateState();
  7228.  
  7229. strm.state = s;
  7230. s.strm = strm;
  7231.  
  7232. s.wrap = wrap;
  7233. s.gzhead = null;
  7234. s.w_bits = windowBits;
  7235. s.w_size = 1 << s.w_bits;
  7236. s.w_mask = s.w_size - 1;
  7237.  
  7238. s.hash_bits = memLevel + 7;
  7239. s.hash_size = 1 << s.hash_bits;
  7240. s.hash_mask = s.hash_size - 1;
  7241. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  7242.  
  7243. s.window = new utils.Buf8(s.w_size * 2);
  7244. s.head = new utils.Buf16(s.hash_size);
  7245. s.prev = new utils.Buf16(s.w_size);
  7246.  
  7247. // Don't need mem init magic for JS.
  7248. //s.high_water = 0; /* nothing written to s->window yet */
  7249.  
  7250. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  7251.  
  7252. s.pending_buf_size = s.lit_bufsize * 4;
  7253.  
  7254. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  7255. //s->pending_buf = (uchf *) overlay;
  7256. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  7257.  
  7258. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  7259. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  7260. s.d_buf = 1 * s.lit_bufsize;
  7261.  
  7262. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  7263. s.l_buf = (1 + 2) * s.lit_bufsize;
  7264.  
  7265. s.level = level;
  7266. s.strategy = strategy;
  7267. s.method = method;
  7268.  
  7269. return deflateReset(strm);
  7270. }
  7271.  
  7272. function deflateInit(strm, level) {
  7273. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  7274. }
  7275.  
  7276.  
  7277. function deflate(strm, flush) {
  7278. var old_flush, s;
  7279. var beg, val; // for gzip header write only
  7280.  
  7281. if (!strm || !strm.state ||
  7282. flush > Z_BLOCK || flush < 0) {
  7283. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  7284. }
  7285.  
  7286. s = strm.state;
  7287.  
  7288. if (!strm.output ||
  7289. (!strm.input && strm.avail_in !== 0) ||
  7290. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  7291. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  7292. }
  7293.  
  7294. s.strm = strm; /* just in case */
  7295. old_flush = s.last_flush;
  7296. s.last_flush = flush;
  7297.  
  7298. /* Write the header */
  7299. if (s.status === INIT_STATE) {
  7300.  
  7301. if (s.wrap === 2) { // GZIP header
  7302. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7303. put_byte(s, 31);
  7304. put_byte(s, 139);
  7305. put_byte(s, 8);
  7306. if (!s.gzhead) { // s->gzhead == Z_NULL
  7307. put_byte(s, 0);
  7308. put_byte(s, 0);
  7309. put_byte(s, 0);
  7310. put_byte(s, 0);
  7311. put_byte(s, 0);
  7312. put_byte(s, s.level === 9 ? 2 :
  7313. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7314. 4 : 0));
  7315. put_byte(s, OS_CODE);
  7316. s.status = BUSY_STATE;
  7317. }
  7318. else {
  7319. put_byte(s, (s.gzhead.text ? 1 : 0) +
  7320. (s.gzhead.hcrc ? 2 : 0) +
  7321. (!s.gzhead.extra ? 0 : 4) +
  7322. (!s.gzhead.name ? 0 : 8) +
  7323. (!s.gzhead.comment ? 0 : 16)
  7324. );
  7325. put_byte(s, s.gzhead.time & 0xff);
  7326. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  7327. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  7328. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  7329. put_byte(s, s.level === 9 ? 2 :
  7330. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7331. 4 : 0));
  7332. put_byte(s, s.gzhead.os & 0xff);
  7333. if (s.gzhead.extra && s.gzhead.extra.length) {
  7334. put_byte(s, s.gzhead.extra.length & 0xff);
  7335. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  7336. }
  7337. if (s.gzhead.hcrc) {
  7338. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  7339. }
  7340. s.gzindex = 0;
  7341. s.status = EXTRA_STATE;
  7342. }
  7343. }
  7344. else // DEFLATE header
  7345. {
  7346. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  7347. var level_flags = -1;
  7348.  
  7349. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  7350. level_flags = 0;
  7351. } else if (s.level < 6) {
  7352. level_flags = 1;
  7353. } else if (s.level === 6) {
  7354. level_flags = 2;
  7355. } else {
  7356. level_flags = 3;
  7357. }
  7358. header |= (level_flags << 6);
  7359. if (s.strstart !== 0) { header |= PRESET_DICT; }
  7360. header += 31 - (header % 31);
  7361.  
  7362. s.status = BUSY_STATE;
  7363. putShortMSB(s, header);
  7364.  
  7365. /* Save the adler32 of the preset dictionary: */
  7366. if (s.strstart !== 0) {
  7367. putShortMSB(s, strm.adler >>> 16);
  7368. putShortMSB(s, strm.adler & 0xffff);
  7369. }
  7370. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  7371. }
  7372. }
  7373.  
  7374. //#ifdef GZIP
  7375. if (s.status === EXTRA_STATE) {
  7376. if (s.gzhead.extra/* != Z_NULL*/) {
  7377. beg = s.pending; /* start of bytes to update crc */
  7378.  
  7379. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  7380. if (s.pending === s.pending_buf_size) {
  7381. if (s.gzhead.hcrc && s.pending > beg) {
  7382. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7383. }
  7384. flush_pending(strm);
  7385. beg = s.pending;
  7386. if (s.pending === s.pending_buf_size) {
  7387. break;
  7388. }
  7389. }
  7390. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  7391. s.gzindex++;
  7392. }
  7393. if (s.gzhead.hcrc && s.pending > beg) {
  7394. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7395. }
  7396. if (s.gzindex === s.gzhead.extra.length) {
  7397. s.gzindex = 0;
  7398. s.status = NAME_STATE;
  7399. }
  7400. }
  7401. else {
  7402. s.status = NAME_STATE;
  7403. }
  7404. }
  7405. if (s.status === NAME_STATE) {
  7406. if (s.gzhead.name/* != Z_NULL*/) {
  7407. beg = s.pending; /* start of bytes to update crc */
  7408. //int val;
  7409.  
  7410. do {
  7411. if (s.pending === s.pending_buf_size) {
  7412. if (s.gzhead.hcrc && s.pending > beg) {
  7413. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7414. }
  7415. flush_pending(strm);
  7416. beg = s.pending;
  7417. if (s.pending === s.pending_buf_size) {
  7418. val = 1;
  7419. break;
  7420. }
  7421. }
  7422. // JS specific: little magic to add zero terminator to end of string
  7423. if (s.gzindex < s.gzhead.name.length) {
  7424. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  7425. } else {
  7426. val = 0;
  7427. }
  7428. put_byte(s, val);
  7429. } while (val !== 0);
  7430.  
  7431. if (s.gzhead.hcrc && s.pending > beg) {
  7432. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7433. }
  7434. if (val === 0) {
  7435. s.gzindex = 0;
  7436. s.status = COMMENT_STATE;
  7437. }
  7438. }
  7439. else {
  7440. s.status = COMMENT_STATE;
  7441. }
  7442. }
  7443. if (s.status === COMMENT_STATE) {
  7444. if (s.gzhead.comment/* != Z_NULL*/) {
  7445. beg = s.pending; /* start of bytes to update crc */
  7446. //int val;
  7447.  
  7448. do {
  7449. if (s.pending === s.pending_buf_size) {
  7450. if (s.gzhead.hcrc && s.pending > beg) {
  7451. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7452. }
  7453. flush_pending(strm);
  7454. beg = s.pending;
  7455. if (s.pending === s.pending_buf_size) {
  7456. val = 1;
  7457. break;
  7458. }
  7459. }
  7460. // JS specific: little magic to add zero terminator to end of string
  7461. if (s.gzindex < s.gzhead.comment.length) {
  7462. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  7463. } else {
  7464. val = 0;
  7465. }
  7466. put_byte(s, val);
  7467. } while (val !== 0);
  7468.  
  7469. if (s.gzhead.hcrc && s.pending > beg) {
  7470. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7471. }
  7472. if (val === 0) {
  7473. s.status = HCRC_STATE;
  7474. }
  7475. }
  7476. else {
  7477. s.status = HCRC_STATE;
  7478. }
  7479. }
  7480. if (s.status === HCRC_STATE) {
  7481. if (s.gzhead.hcrc) {
  7482. if (s.pending + 2 > s.pending_buf_size) {
  7483. flush_pending(strm);
  7484. }
  7485. if (s.pending + 2 <= s.pending_buf_size) {
  7486. put_byte(s, strm.adler & 0xff);
  7487. put_byte(s, (strm.adler >> 8) & 0xff);
  7488. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7489. s.status = BUSY_STATE;
  7490. }
  7491. }
  7492. else {
  7493. s.status = BUSY_STATE;
  7494. }
  7495. }
  7496. //#endif
  7497.  
  7498. /* Flush as much pending output as possible */
  7499. if (s.pending !== 0) {
  7500. flush_pending(strm);
  7501. if (strm.avail_out === 0) {
  7502. /* Since avail_out is 0, deflate will be called again with
  7503. * more output space, but possibly with both pending and
  7504. * avail_in equal to zero. There won't be anything to do,
  7505. * but this is not an error situation so make sure we
  7506. * return OK instead of BUF_ERROR at next call of deflate:
  7507. */
  7508. s.last_flush = -1;
  7509. return Z_OK;
  7510. }
  7511.  
  7512. /* Make sure there is something to do and avoid duplicate consecutive
  7513. * flushes. For repeated and useless calls with Z_FINISH, we keep
  7514. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  7515. */
  7516. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  7517. flush !== Z_FINISH) {
  7518. return err(strm, Z_BUF_ERROR);
  7519. }
  7520.  
  7521. /* User must not provide more input after the first FINISH: */
  7522. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  7523. return err(strm, Z_BUF_ERROR);
  7524. }
  7525.  
  7526. /* Start a new block or continue the current one.
  7527. */
  7528. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  7529. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  7530. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  7531. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  7532. configuration_table[s.level].func(s, flush));
  7533.  
  7534. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  7535. s.status = FINISH_STATE;
  7536. }
  7537. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  7538. if (strm.avail_out === 0) {
  7539. s.last_flush = -1;
  7540. /* avoid BUF_ERROR next call, see above */
  7541. }
  7542. return Z_OK;
  7543. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  7544. * of deflate should use the same flush parameter to make sure
  7545. * that the flush is complete. So we don't have to output an
  7546. * empty block here, this will be done at next call. This also
  7547. * ensures that for a very small output buffer, we emit at most
  7548. * one empty block.
  7549. */
  7550. }
  7551. if (bstate === BS_BLOCK_DONE) {
  7552. if (flush === Z_PARTIAL_FLUSH) {
  7553. trees._tr_align(s);
  7554. }
  7555. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  7556.  
  7557. trees._tr_stored_block(s, 0, 0, false);
  7558. /* For a full flush, this empty block will be recognized
  7559. * as a special marker by inflate_sync().
  7560. */
  7561. if (flush === Z_FULL_FLUSH) {
  7562. /*** CLEAR_HASH(s); ***/ /* forget history */
  7563. zero(s.head); // Fill with NIL (= 0);
  7564.  
  7565. if (s.lookahead === 0) {
  7566. s.strstart = 0;
  7567. s.block_start = 0;
  7568. s.insert = 0;
  7569. }
  7570. }
  7571. }
  7572. flush_pending(strm);
  7573. if (strm.avail_out === 0) {
  7574. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  7575. return Z_OK;
  7576. }
  7577. }
  7578. }
  7579. //Assert(strm->avail_out > 0, "bug2");
  7580. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  7581.  
  7582. if (flush !== Z_FINISH) { return Z_OK; }
  7583. if (s.wrap <= 0) { return Z_STREAM_END; }
  7584.  
  7585. /* Write the trailer */
  7586. if (s.wrap === 2) {
  7587. put_byte(s, strm.adler & 0xff);
  7588. put_byte(s, (strm.adler >> 8) & 0xff);
  7589. put_byte(s, (strm.adler >> 16) & 0xff);
  7590. put_byte(s, (strm.adler >> 24) & 0xff);
  7591. put_byte(s, strm.total_in & 0xff);
  7592. put_byte(s, (strm.total_in >> 8) & 0xff);
  7593. put_byte(s, (strm.total_in >> 16) & 0xff);
  7594. put_byte(s, (strm.total_in >> 24) & 0xff);
  7595. }
  7596. else
  7597. {
  7598. putShortMSB(s, strm.adler >>> 16);
  7599. putShortMSB(s, strm.adler & 0xffff);
  7600. }
  7601.  
  7602. flush_pending(strm);
  7603. /* If avail_out is zero, the application will call deflate again
  7604. * to flush the rest.
  7605. */
  7606. if (s.wrap > 0) { s.wrap = -s.wrap; }
  7607. /* write the trailer only once! */
  7608. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  7609. }
  7610.  
  7611. function deflateEnd(strm) {
  7612. var status;
  7613.  
  7614. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7615. return Z_STREAM_ERROR;
  7616. }
  7617.  
  7618. status = strm.state.status;
  7619. if (status !== INIT_STATE &&
  7620. status !== EXTRA_STATE &&
  7621. status !== NAME_STATE &&
  7622. status !== COMMENT_STATE &&
  7623. status !== HCRC_STATE &&
  7624. status !== BUSY_STATE &&
  7625. status !== FINISH_STATE
  7626. ) {
  7627. return err(strm, Z_STREAM_ERROR);
  7628. }
  7629.  
  7630. strm.state = null;
  7631.  
  7632. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  7633. }
  7634.  
  7635.  
  7636. /* =========================================================================
  7637. * Initializes the compression dictionary from the given byte
  7638. * sequence without producing any compressed output.
  7639. */
  7640. function deflateSetDictionary(strm, dictionary) {
  7641. var dictLength = dictionary.length;
  7642.  
  7643. var s;
  7644. var str, n;
  7645. var wrap;
  7646. var avail;
  7647. var next;
  7648. var input;
  7649. var tmpDict;
  7650.  
  7651. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7652. return Z_STREAM_ERROR;
  7653. }
  7654.  
  7655. s = strm.state;
  7656. wrap = s.wrap;
  7657.  
  7658. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  7659. return Z_STREAM_ERROR;
  7660. }
  7661.  
  7662. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  7663. if (wrap === 1) {
  7664. /* adler32(strm->adler, dictionary, dictLength); */
  7665. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  7666. }
  7667.  
  7668. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  7669.  
  7670. /* if dictionary would fill window, just replace the history */
  7671. if (dictLength >= s.w_size) {
  7672. if (wrap === 0) { /* already empty otherwise */
  7673. /*** CLEAR_HASH(s); ***/
  7674. zero(s.head); // Fill with NIL (= 0);
  7675. s.strstart = 0;
  7676. s.block_start = 0;
  7677. s.insert = 0;
  7678. }
  7679. /* use the tail */
  7680. // dictionary = dictionary.slice(dictLength - s.w_size);
  7681. tmpDict = new utils.Buf8(s.w_size);
  7682. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  7683. dictionary = tmpDict;
  7684. dictLength = s.w_size;
  7685. }
  7686. /* insert dictionary into window and hash */
  7687. avail = strm.avail_in;
  7688. next = strm.next_in;
  7689. input = strm.input;
  7690. strm.avail_in = dictLength;
  7691. strm.next_in = 0;
  7692. strm.input = dictionary;
  7693. fill_window(s);
  7694. while (s.lookahead >= MIN_MATCH) {
  7695. str = s.strstart;
  7696. n = s.lookahead - (MIN_MATCH - 1);
  7697. do {
  7698. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  7699. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  7700.  
  7701. s.prev[str & s.w_mask] = s.head[s.ins_h];
  7702.  
  7703. s.head[s.ins_h] = str;
  7704. str++;
  7705. } while (--n);
  7706. s.strstart = str;
  7707. s.lookahead = MIN_MATCH - 1;
  7708. fill_window(s);
  7709. }
  7710. s.strstart += s.lookahead;
  7711. s.block_start = s.strstart;
  7712. s.insert = s.lookahead;
  7713. s.lookahead = 0;
  7714. s.match_length = s.prev_length = MIN_MATCH - 1;
  7715. s.match_available = 0;
  7716. strm.next_in = next;
  7717. strm.input = input;
  7718. strm.avail_in = avail;
  7719. s.wrap = wrap;
  7720. return Z_OK;
  7721. }
  7722.  
  7723.  
  7724. exports.deflateInit = deflateInit;
  7725. exports.deflateInit2 = deflateInit2;
  7726. exports.deflateReset = deflateReset;
  7727. exports.deflateResetKeep = deflateResetKeep;
  7728. exports.deflateSetHeader = deflateSetHeader;
  7729. exports.deflate = deflate;
  7730. exports.deflateEnd = deflateEnd;
  7731. exports.deflateSetDictionary = deflateSetDictionary;
  7732. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  7733.  
  7734. /* Not implemented
  7735. exports.deflateBound = deflateBound;
  7736. exports.deflateCopy = deflateCopy;
  7737. exports.deflateParams = deflateParams;
  7738. exports.deflatePending = deflatePending;
  7739. exports.deflatePrime = deflatePrime;
  7740. exports.deflateTune = deflateTune;
  7741. */
  7742.  
  7743. },{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(require,module,exports){
  7744. 'use strict';
  7745.  
  7746. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7747. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7748. //
  7749. // This software is provided 'as-is', without any express or implied
  7750. // warranty. In no event will the authors be held liable for any damages
  7751. // arising from the use of this software.
  7752. //
  7753. // Permission is granted to anyone to use this software for any purpose,
  7754. // including commercial applications, and to alter it and redistribute it
  7755. // freely, subject to the following restrictions:
  7756. //
  7757. // 1. The origin of this software must not be misrepresented; you must not
  7758. // claim that you wrote the original software. If you use this software
  7759. // in a product, an acknowledgment in the product documentation would be
  7760. // appreciated but is not required.
  7761. // 2. Altered source versions must be plainly marked as such, and must not be
  7762. // misrepresented as being the original software.
  7763. // 3. This notice may not be removed or altered from any source distribution.
  7764.  
  7765. function GZheader() {
  7766. /* true if compressed data believed to be text */
  7767. this.text = 0;
  7768. /* modification time */
  7769. this.time = 0;
  7770. /* extra flags (not used when writing a gzip file) */
  7771. this.xflags = 0;
  7772. /* operating system */
  7773. this.os = 0;
  7774. /* pointer to extra field or Z_NULL if none */
  7775. this.extra = null;
  7776. /* extra field length (valid if extra != Z_NULL) */
  7777. this.extra_len = 0; // Actually, we don't need it in JS,
  7778. // but leave for few code modifications
  7779.  
  7780. //
  7781. // Setup limits is not necessary because in js we should not preallocate memory
  7782. // for inflate use constant limit in 65536 bytes
  7783. //
  7784.  
  7785. /* space at extra (only when reading header) */
  7786. // this.extra_max = 0;
  7787. /* pointer to zero-terminated file name or Z_NULL */
  7788. this.name = '';
  7789. /* space at name (only when reading header) */
  7790. // this.name_max = 0;
  7791. /* pointer to zero-terminated comment or Z_NULL */
  7792. this.comment = '';
  7793. /* space at comment (only when reading header) */
  7794. // this.comm_max = 0;
  7795. /* true if there was or will be a header crc */
  7796. this.hcrc = 0;
  7797. /* true when done reading gzip header (not used when writing a gzip file) */
  7798. this.done = false;
  7799. }
  7800.  
  7801. module.exports = GZheader;
  7802.  
  7803. },{}],48:[function(require,module,exports){
  7804. 'use strict';
  7805.  
  7806. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7807. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7808. //
  7809. // This software is provided 'as-is', without any express or implied
  7810. // warranty. In no event will the authors be held liable for any damages
  7811. // arising from the use of this software.
  7812. //
  7813. // Permission is granted to anyone to use this software for any purpose,
  7814. // including commercial applications, and to alter it and redistribute it
  7815. // freely, subject to the following restrictions:
  7816. //
  7817. // 1. The origin of this software must not be misrepresented; you must not
  7818. // claim that you wrote the original software. If you use this software
  7819. // in a product, an acknowledgment in the product documentation would be
  7820. // appreciated but is not required.
  7821. // 2. Altered source versions must be plainly marked as such, and must not be
  7822. // misrepresented as being the original software.
  7823. // 3. This notice may not be removed or altered from any source distribution.
  7824.  
  7825. // See state defs from inflate.js
  7826. var BAD = 30; /* got a data error -- remain here until reset */
  7827. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  7828.  
  7829. /*
  7830. Decode literal, length, and distance codes and write out the resulting
  7831. literal and match bytes until either not enough input or output is
  7832. available, an end-of-block is encountered, or a data error is encountered.
  7833. When large enough input and output buffers are supplied to inflate(), for
  7834. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  7835. inflate execution time is spent in this routine.
  7836.  
  7837. Entry assumptions:
  7838.  
  7839. state.mode === LEN
  7840. strm.avail_in >= 6
  7841. strm.avail_out >= 258
  7842. start >= strm.avail_out
  7843. state.bits < 8
  7844.  
  7845. On return, state.mode is one of:
  7846.  
  7847. LEN -- ran out of enough output space or enough available input
  7848. TYPE -- reached end of block code, inflate() to interpret next block
  7849. BAD -- error in block data
  7850.  
  7851. Notes:
  7852.  
  7853. - The maximum input bits used by a length/distance pair is 15 bits for the
  7854. length code, 5 bits for the length extra, 15 bits for the distance code,
  7855. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  7856. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  7857. checking for available input while decoding.
  7858.  
  7859. - The maximum bytes that a single length/distance pair can output is 258
  7860. bytes, which is the maximum length that can be coded. inflate_fast()
  7861. requires strm.avail_out >= 258 for each loop to avoid checking for
  7862. output space.
  7863. */
  7864. module.exports = function inflate_fast(strm, start) {
  7865. var state;
  7866. var _in; /* local strm.input */
  7867. var last; /* have enough input while in < last */
  7868. var _out; /* local strm.output */
  7869. var beg; /* inflate()'s initial strm.output */
  7870. var end; /* while out < end, enough space available */
  7871. //#ifdef INFLATE_STRICT
  7872. var dmax; /* maximum distance from zlib header */
  7873. //#endif
  7874. var wsize; /* window size or zero if not using window */
  7875. var whave; /* valid bytes in the window */
  7876. var wnext; /* window write index */
  7877. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  7878. var s_window; /* allocated sliding window, if wsize != 0 */
  7879. var hold; /* local strm.hold */
  7880. var bits; /* local strm.bits */
  7881. var lcode; /* local strm.lencode */
  7882. var dcode; /* local strm.distcode */
  7883. var lmask; /* mask for first level of length codes */
  7884. var dmask; /* mask for first level of distance codes */
  7885. var here; /* retrieved table entry */
  7886. var op; /* code bits, operation, extra bits, or */
  7887. /* window position, window bytes to copy */
  7888. var len; /* match length, unused bytes */
  7889. var dist; /* match distance */
  7890. var from; /* where to copy match from */
  7891. var from_source;
  7892.  
  7893.  
  7894. var input, output; // JS specific, because we have no pointers
  7895.  
  7896. /* copy state to local variables */
  7897. state = strm.state;
  7898. //here = state.here;
  7899. _in = strm.next_in;
  7900. input = strm.input;
  7901. last = _in + (strm.avail_in - 5);
  7902. _out = strm.next_out;
  7903. output = strm.output;
  7904. beg = _out - (start - strm.avail_out);
  7905. end = _out + (strm.avail_out - 257);
  7906. //#ifdef INFLATE_STRICT
  7907. dmax = state.dmax;
  7908. //#endif
  7909. wsize = state.wsize;
  7910. whave = state.whave;
  7911. wnext = state.wnext;
  7912. s_window = state.window;
  7913. hold = state.hold;
  7914. bits = state.bits;
  7915. lcode = state.lencode;
  7916. dcode = state.distcode;
  7917. lmask = (1 << state.lenbits) - 1;
  7918. dmask = (1 << state.distbits) - 1;
  7919.  
  7920.  
  7921. /* decode literals and length/distances until end-of-block or not enough
  7922. input data or output space */
  7923.  
  7924. top:
  7925. do {
  7926. if (bits < 15) {
  7927. hold += input[_in++] << bits;
  7928. bits += 8;
  7929. hold += input[_in++] << bits;
  7930. bits += 8;
  7931. }
  7932.  
  7933. here = lcode[hold & lmask];
  7934.  
  7935. dolen:
  7936. for (;;) { // Goto emulation
  7937. op = here >>> 24/*here.bits*/;
  7938. hold >>>= op;
  7939. bits -= op;
  7940. op = (here >>> 16) & 0xff/*here.op*/;
  7941. if (op === 0) { /* literal */
  7942. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  7943. // "inflate: literal '%c'\n" :
  7944. // "inflate: literal 0x%02x\n", here.val));
  7945. output[_out++] = here & 0xffff/*here.val*/;
  7946. }
  7947. else if (op & 16) { /* length base */
  7948. len = here & 0xffff/*here.val*/;
  7949. op &= 15; /* number of extra bits */
  7950. if (op) {
  7951. if (bits < op) {
  7952. hold += input[_in++] << bits;
  7953. bits += 8;
  7954. }
  7955. len += hold & ((1 << op) - 1);
  7956. hold >>>= op;
  7957. bits -= op;
  7958. }
  7959. //Tracevv((stderr, "inflate: length %u\n", len));
  7960. if (bits < 15) {
  7961. hold += input[_in++] << bits;
  7962. bits += 8;
  7963. hold += input[_in++] << bits;
  7964. bits += 8;
  7965. }
  7966. here = dcode[hold & dmask];
  7967.  
  7968. dodist:
  7969. for (;;) { // goto emulation
  7970. op = here >>> 24/*here.bits*/;
  7971. hold >>>= op;
  7972. bits -= op;
  7973. op = (here >>> 16) & 0xff/*here.op*/;
  7974.  
  7975. if (op & 16) { /* distance base */
  7976. dist = here & 0xffff/*here.val*/;
  7977. op &= 15; /* number of extra bits */
  7978. if (bits < op) {
  7979. hold += input[_in++] << bits;
  7980. bits += 8;
  7981. if (bits < op) {
  7982. hold += input[_in++] << bits;
  7983. bits += 8;
  7984. }
  7985. }
  7986. dist += hold & ((1 << op) - 1);
  7987. //#ifdef INFLATE_STRICT
  7988. if (dist > dmax) {
  7989. strm.msg = 'invalid distance too far back';
  7990. state.mode = BAD;
  7991. break top;
  7992. }
  7993. //#endif
  7994. hold >>>= op;
  7995. bits -= op;
  7996. //Tracevv((stderr, "inflate: distance %u\n", dist));
  7997. op = _out - beg; /* max distance in output */
  7998. if (dist > op) { /* see if copy from window */
  7999. op = dist - op; /* distance back in window */
  8000. if (op > whave) {
  8001. if (state.sane) {
  8002. strm.msg = 'invalid distance too far back';
  8003. state.mode = BAD;
  8004. break top;
  8005. }
  8006.  
  8007. // (!) This block is disabled in zlib defailts,
  8008. // don't enable it for binary compatibility
  8009. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  8010. // if (len <= op - whave) {
  8011. // do {
  8012. // output[_out++] = 0;
  8013. // } while (--len);
  8014. // continue top;
  8015. // }
  8016. // len -= op - whave;
  8017. // do {
  8018. // output[_out++] = 0;
  8019. // } while (--op > whave);
  8020. // if (op === 0) {
  8021. // from = _out - dist;
  8022. // do {
  8023. // output[_out++] = output[from++];
  8024. // } while (--len);
  8025. // continue top;
  8026. // }
  8027. //#endif
  8028. }
  8029. from = 0; // window index
  8030. from_source = s_window;
  8031. if (wnext === 0) { /* very common case */
  8032. from += wsize - op;
  8033. if (op < len) { /* some from window */
  8034. len -= op;
  8035. do {
  8036. output[_out++] = s_window[from++];
  8037. } while (--op);
  8038. from = _out - dist; /* rest from output */
  8039. from_source = output;
  8040. }
  8041. }
  8042. else if (wnext < op) { /* wrap around window */
  8043. from += wsize + wnext - op;
  8044. op -= wnext;
  8045. if (op < len) { /* some from end of window */
  8046. len -= op;
  8047. do {
  8048. output[_out++] = s_window[from++];
  8049. } while (--op);
  8050. from = 0;
  8051. if (wnext < len) { /* some from start of window */
  8052. op = wnext;
  8053. len -= op;
  8054. do {
  8055. output[_out++] = s_window[from++];
  8056. } while (--op);
  8057. from = _out - dist; /* rest from output */
  8058. from_source = output;
  8059. }
  8060. }
  8061. }
  8062. else { /* contiguous in window */
  8063. from += wnext - op;
  8064. if (op < len) { /* some from window */
  8065. len -= op;
  8066. do {
  8067. output[_out++] = s_window[from++];
  8068. } while (--op);
  8069. from = _out - dist; /* rest from output */
  8070. from_source = output;
  8071. }
  8072. }
  8073. while (len > 2) {
  8074. output[_out++] = from_source[from++];
  8075. output[_out++] = from_source[from++];
  8076. output[_out++] = from_source[from++];
  8077. len -= 3;
  8078. }
  8079. if (len) {
  8080. output[_out++] = from_source[from++];
  8081. if (len > 1) {
  8082. output[_out++] = from_source[from++];
  8083. }
  8084. }
  8085. }
  8086. else {
  8087. from = _out - dist; /* copy direct from output */
  8088. do { /* minimum length is three */
  8089. output[_out++] = output[from++];
  8090. output[_out++] = output[from++];
  8091. output[_out++] = output[from++];
  8092. len -= 3;
  8093. } while (len > 2);
  8094. if (len) {
  8095. output[_out++] = output[from++];
  8096. if (len > 1) {
  8097. output[_out++] = output[from++];
  8098. }
  8099. }
  8100. }
  8101. }
  8102. else if ((op & 64) === 0) { /* 2nd level distance code */
  8103. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8104. continue dodist;
  8105. }
  8106. else {
  8107. strm.msg = 'invalid distance code';
  8108. state.mode = BAD;
  8109. break top;
  8110. }
  8111.  
  8112. break; // need to emulate goto via "continue"
  8113. }
  8114. }
  8115. else if ((op & 64) === 0) { /* 2nd level length code */
  8116. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8117. continue dolen;
  8118. }
  8119. else if (op & 32) { /* end-of-block */
  8120. //Tracevv((stderr, "inflate: end of block\n"));
  8121. state.mode = TYPE;
  8122. break top;
  8123. }
  8124. else {
  8125. strm.msg = 'invalid literal/length code';
  8126. state.mode = BAD;
  8127. break top;
  8128. }
  8129.  
  8130. break; // need to emulate goto via "continue"
  8131. }
  8132. } while (_in < last && _out < end);
  8133.  
  8134. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  8135. len = bits >> 3;
  8136. _in -= len;
  8137. bits -= len << 3;
  8138. hold &= (1 << bits) - 1;
  8139.  
  8140. /* update state and return */
  8141. strm.next_in = _in;
  8142. strm.next_out = _out;
  8143. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  8144. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  8145. state.hold = hold;
  8146. state.bits = bits;
  8147. return;
  8148. };
  8149.  
  8150. },{}],49:[function(require,module,exports){
  8151. 'use strict';
  8152.  
  8153. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8154. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8155. //
  8156. // This software is provided 'as-is', without any express or implied
  8157. // warranty. In no event will the authors be held liable for any damages
  8158. // arising from the use of this software.
  8159. //
  8160. // Permission is granted to anyone to use this software for any purpose,
  8161. // including commercial applications, and to alter it and redistribute it
  8162. // freely, subject to the following restrictions:
  8163. //
  8164. // 1. The origin of this software must not be misrepresented; you must not
  8165. // claim that you wrote the original software. If you use this software
  8166. // in a product, an acknowledgment in the product documentation would be
  8167. // appreciated but is not required.
  8168. // 2. Altered source versions must be plainly marked as such, and must not be
  8169. // misrepresented as being the original software.
  8170. // 3. This notice may not be removed or altered from any source distribution.
  8171.  
  8172. var utils = require('../utils/common');
  8173. var adler32 = require('./adler32');
  8174. var crc32 = require('./crc32');
  8175. var inflate_fast = require('./inffast');
  8176. var inflate_table = require('./inftrees');
  8177.  
  8178. var CODES = 0;
  8179. var LENS = 1;
  8180. var DISTS = 2;
  8181.  
  8182. /* Public constants ==========================================================*/
  8183. /* ===========================================================================*/
  8184.  
  8185.  
  8186. /* Allowed flush values; see deflate() and inflate() below for details */
  8187. //var Z_NO_FLUSH = 0;
  8188. //var Z_PARTIAL_FLUSH = 1;
  8189. //var Z_SYNC_FLUSH = 2;
  8190. //var Z_FULL_FLUSH = 3;
  8191. var Z_FINISH = 4;
  8192. var Z_BLOCK = 5;
  8193. var Z_TREES = 6;
  8194.  
  8195.  
  8196. /* Return codes for the compression/decompression functions. Negative values
  8197. * are errors, positive values are used for special but normal events.
  8198. */
  8199. var Z_OK = 0;
  8200. var Z_STREAM_END = 1;
  8201. var Z_NEED_DICT = 2;
  8202. //var Z_ERRNO = -1;
  8203. var Z_STREAM_ERROR = -2;
  8204. var Z_DATA_ERROR = -3;
  8205. var Z_MEM_ERROR = -4;
  8206. var Z_BUF_ERROR = -5;
  8207. //var Z_VERSION_ERROR = -6;
  8208.  
  8209. /* The deflate compression method */
  8210. var Z_DEFLATED = 8;
  8211.  
  8212.  
  8213. /* STATES ====================================================================*/
  8214. /* ===========================================================================*/
  8215.  
  8216.  
  8217. var HEAD = 1; /* i: waiting for magic header */
  8218. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  8219. var TIME = 3; /* i: waiting for modification time (gzip) */
  8220. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  8221. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  8222. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  8223. var NAME = 7; /* i: waiting for end of file name (gzip) */
  8224. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  8225. var HCRC = 9; /* i: waiting for header crc (gzip) */
  8226. var DICTID = 10; /* i: waiting for dictionary check value */
  8227. var DICT = 11; /* waiting for inflateSetDictionary() call */
  8228. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  8229. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  8230. var STORED = 14; /* i: waiting for stored size (length and complement) */
  8231. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  8232. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  8233. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  8234. var LENLENS = 18; /* i: waiting for code length code lengths */
  8235. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  8236. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  8237. var LEN = 21; /* i: waiting for length/lit/eob code */
  8238. var LENEXT = 22; /* i: waiting for length extra bits */
  8239. var DIST = 23; /* i: waiting for distance code */
  8240. var DISTEXT = 24; /* i: waiting for distance extra bits */
  8241. var MATCH = 25; /* o: waiting for output space to copy string */
  8242. var LIT = 26; /* o: waiting for output space to write literal */
  8243. var CHECK = 27; /* i: waiting for 32-bit check value */
  8244. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  8245. var DONE = 29; /* finished check, done -- remain here until reset */
  8246. var BAD = 30; /* got a data error -- remain here until reset */
  8247. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  8248. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  8249.  
  8250. /* ===========================================================================*/
  8251.  
  8252.  
  8253.  
  8254. var ENOUGH_LENS = 852;
  8255. var ENOUGH_DISTS = 592;
  8256. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  8257.  
  8258. var MAX_WBITS = 15;
  8259. /* 32K LZ77 window */
  8260. var DEF_WBITS = MAX_WBITS;
  8261.  
  8262.  
  8263. function zswap32(q) {
  8264. return (((q >>> 24) & 0xff) +
  8265. ((q >>> 8) & 0xff00) +
  8266. ((q & 0xff00) << 8) +
  8267. ((q & 0xff) << 24));
  8268. }
  8269.  
  8270.  
  8271. function InflateState() {
  8272. this.mode = 0; /* current inflate mode */
  8273. this.last = false; /* true if processing last block */
  8274. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  8275. this.havedict = false; /* true if dictionary provided */
  8276. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  8277. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  8278. this.check = 0; /* protected copy of check value */
  8279. this.total = 0; /* protected copy of output count */
  8280. // TODO: may be {}
  8281. this.head = null; /* where to save gzip header information */
  8282.  
  8283. /* sliding window */
  8284. this.wbits = 0; /* log base 2 of requested window size */
  8285. this.wsize = 0; /* window size or zero if not using window */
  8286. this.whave = 0; /* valid bytes in the window */
  8287. this.wnext = 0; /* window write index */
  8288. this.window = null; /* allocated sliding window, if needed */
  8289.  
  8290. /* bit accumulator */
  8291. this.hold = 0; /* input bit accumulator */
  8292. this.bits = 0; /* number of bits in "in" */
  8293.  
  8294. /* for string and stored block copying */
  8295. this.length = 0; /* literal or length of data to copy */
  8296. this.offset = 0; /* distance back to copy string from */
  8297.  
  8298. /* for table and code decoding */
  8299. this.extra = 0; /* extra bits needed */
  8300.  
  8301. /* fixed and dynamic code tables */
  8302. this.lencode = null; /* starting table for length/literal codes */
  8303. this.distcode = null; /* starting table for distance codes */
  8304. this.lenbits = 0; /* index bits for lencode */
  8305. this.distbits = 0; /* index bits for distcode */
  8306.  
  8307. /* dynamic table building */
  8308. this.ncode = 0; /* number of code length code lengths */
  8309. this.nlen = 0; /* number of length code lengths */
  8310. this.ndist = 0; /* number of distance code lengths */
  8311. this.have = 0; /* number of code lengths in lens[] */
  8312. this.next = null; /* next available space in codes[] */
  8313.  
  8314. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  8315. this.work = new utils.Buf16(288); /* work area for code table building */
  8316.  
  8317. /*
  8318. because we don't have pointers in js, we use lencode and distcode directly
  8319. as buffers so we don't need codes
  8320. */
  8321. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  8322. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  8323. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  8324. this.sane = 0; /* if false, allow invalid distance too far */
  8325. this.back = 0; /* bits back of last unprocessed length/lit */
  8326. this.was = 0; /* initial length of match */
  8327. }
  8328.  
  8329. function inflateResetKeep(strm) {
  8330. var state;
  8331.  
  8332. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8333. state = strm.state;
  8334. strm.total_in = strm.total_out = state.total = 0;
  8335. strm.msg = ''; /*Z_NULL*/
  8336. if (state.wrap) { /* to support ill-conceived Java test suite */
  8337. strm.adler = state.wrap & 1;
  8338. }
  8339. state.mode = HEAD;
  8340. state.last = 0;
  8341. state.havedict = 0;
  8342. state.dmax = 32768;
  8343. state.head = null/*Z_NULL*/;
  8344. state.hold = 0;
  8345. state.bits = 0;
  8346. //state.lencode = state.distcode = state.next = state.codes;
  8347. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  8348. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  8349.  
  8350. state.sane = 1;
  8351. state.back = -1;
  8352. //Tracev((stderr, "inflate: reset\n"));
  8353. return Z_OK;
  8354. }
  8355.  
  8356. function inflateReset(strm) {
  8357. var state;
  8358.  
  8359. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8360. state = strm.state;
  8361. state.wsize = 0;
  8362. state.whave = 0;
  8363. state.wnext = 0;
  8364. return inflateResetKeep(strm);
  8365.  
  8366. }
  8367.  
  8368. function inflateReset2(strm, windowBits) {
  8369. var wrap;
  8370. var state;
  8371.  
  8372. /* get the state */
  8373. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8374. state = strm.state;
  8375.  
  8376. /* extract wrap request from windowBits parameter */
  8377. if (windowBits < 0) {
  8378. wrap = 0;
  8379. windowBits = -windowBits;
  8380. }
  8381. else {
  8382. wrap = (windowBits >> 4) + 1;
  8383. if (windowBits < 48) {
  8384. windowBits &= 15;
  8385. }
  8386. }
  8387.  
  8388. /* set number of window bits, free window if different */
  8389. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  8390. return Z_STREAM_ERROR;
  8391. }
  8392. if (state.window !== null && state.wbits !== windowBits) {
  8393. state.window = null;
  8394. }
  8395.  
  8396. /* update state and reset the rest of it */
  8397. state.wrap = wrap;
  8398. state.wbits = windowBits;
  8399. return inflateReset(strm);
  8400. }
  8401.  
  8402. function inflateInit2(strm, windowBits) {
  8403. var ret;
  8404. var state;
  8405.  
  8406. if (!strm) { return Z_STREAM_ERROR; }
  8407. //strm.msg = Z_NULL; /* in case we return an error */
  8408.  
  8409. state = new InflateState();
  8410.  
  8411. //if (state === Z_NULL) return Z_MEM_ERROR;
  8412. //Tracev((stderr, "inflate: allocated\n"));
  8413. strm.state = state;
  8414. state.window = null/*Z_NULL*/;
  8415. ret = inflateReset2(strm, windowBits);
  8416. if (ret !== Z_OK) {
  8417. strm.state = null/*Z_NULL*/;
  8418. }
  8419. return ret;
  8420. }
  8421.  
  8422. function inflateInit(strm) {
  8423. return inflateInit2(strm, DEF_WBITS);
  8424. }
  8425.  
  8426.  
  8427. /*
  8428. Return state with length and distance decoding tables and index sizes set to
  8429. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  8430. If BUILDFIXED is defined, then instead this routine builds the tables the
  8431. first time it's called, and returns those tables the first time and
  8432. thereafter. This reduces the size of the code by about 2K bytes, in
  8433. exchange for a little execution time. However, BUILDFIXED should not be
  8434. used for threaded applications, since the rewriting of the tables and virgin
  8435. may not be thread-safe.
  8436. */
  8437. var virgin = true;
  8438.  
  8439. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  8440.  
  8441. function fixedtables(state) {
  8442. /* build fixed huffman tables if first call (may not be thread safe) */
  8443. if (virgin) {
  8444. var sym;
  8445.  
  8446. lenfix = new utils.Buf32(512);
  8447. distfix = new utils.Buf32(32);
  8448.  
  8449. /* literal/length table */
  8450. sym = 0;
  8451. while (sym < 144) { state.lens[sym++] = 8; }
  8452. while (sym < 256) { state.lens[sym++] = 9; }
  8453. while (sym < 280) { state.lens[sym++] = 7; }
  8454. while (sym < 288) { state.lens[sym++] = 8; }
  8455.  
  8456. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  8457.  
  8458. /* distance table */
  8459. sym = 0;
  8460. while (sym < 32) { state.lens[sym++] = 5; }
  8461.  
  8462. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  8463.  
  8464. /* do this just once */
  8465. virgin = false;
  8466. }
  8467.  
  8468. state.lencode = lenfix;
  8469. state.lenbits = 9;
  8470. state.distcode = distfix;
  8471. state.distbits = 5;
  8472. }
  8473.  
  8474.  
  8475. /*
  8476. Update the window with the last wsize (normally 32K) bytes written before
  8477. returning. If window does not exist yet, create it. This is only called
  8478. when a window is already in use, or when output has been written during this
  8479. inflate call, but the end of the deflate stream has not been reached yet.
  8480. It is also called to create a window for dictionary data when a dictionary
  8481. is loaded.
  8482.  
  8483. Providing output buffers larger than 32K to inflate() should provide a speed
  8484. advantage, since only the last 32K of output is copied to the sliding window
  8485. upon return from inflate(), and since all distances after the first 32K of
  8486. output will fall in the output data, making match copies simpler and faster.
  8487. The advantage may be dependent on the size of the processor's data caches.
  8488. */
  8489. function updatewindow(strm, src, end, copy) {
  8490. var dist;
  8491. var state = strm.state;
  8492.  
  8493. /* if it hasn't been done already, allocate space for the window */
  8494. if (state.window === null) {
  8495. state.wsize = 1 << state.wbits;
  8496. state.wnext = 0;
  8497. state.whave = 0;
  8498.  
  8499. state.window = new utils.Buf8(state.wsize);
  8500. }
  8501.  
  8502. /* copy state->wsize or less output bytes into the circular window */
  8503. if (copy >= state.wsize) {
  8504. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  8505. state.wnext = 0;
  8506. state.whave = state.wsize;
  8507. }
  8508. else {
  8509. dist = state.wsize - state.wnext;
  8510. if (dist > copy) {
  8511. dist = copy;
  8512. }
  8513. //zmemcpy(state->window + state->wnext, end - copy, dist);
  8514. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  8515. copy -= dist;
  8516. if (copy) {
  8517. //zmemcpy(state->window, end - copy, copy);
  8518. utils.arraySet(state.window, src, end - copy, copy, 0);
  8519. state.wnext = copy;
  8520. state.whave = state.wsize;
  8521. }
  8522. else {
  8523. state.wnext += dist;
  8524. if (state.wnext === state.wsize) { state.wnext = 0; }
  8525. if (state.whave < state.wsize) { state.whave += dist; }
  8526. }
  8527. }
  8528. return 0;
  8529. }
  8530.  
  8531. function inflate(strm, flush) {
  8532. var state;
  8533. var input, output; // input/output buffers
  8534. var next; /* next input INDEX */
  8535. var put; /* next output INDEX */
  8536. var have, left; /* available input and output */
  8537. var hold; /* bit buffer */
  8538. var bits; /* bits in bit buffer */
  8539. var _in, _out; /* save starting available input and output */
  8540. var copy; /* number of stored or match bytes to copy */
  8541. var from; /* where to copy match bytes from */
  8542. var from_source;
  8543. var here = 0; /* current decoding table entry */
  8544. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  8545. //var last; /* parent table entry */
  8546. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  8547. var len; /* length to copy for repeats, bits to drop */
  8548. var ret; /* return code */
  8549. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  8550. var opts;
  8551.  
  8552. var n; // temporary var for NEED_BITS
  8553.  
  8554. var order = /* permutation of code lengths */
  8555. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  8556.  
  8557.  
  8558. if (!strm || !strm.state || !strm.output ||
  8559. (!strm.input && strm.avail_in !== 0)) {
  8560. return Z_STREAM_ERROR;
  8561. }
  8562.  
  8563. state = strm.state;
  8564. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  8565.  
  8566.  
  8567. //--- LOAD() ---
  8568. put = strm.next_out;
  8569. output = strm.output;
  8570. left = strm.avail_out;
  8571. next = strm.next_in;
  8572. input = strm.input;
  8573. have = strm.avail_in;
  8574. hold = state.hold;
  8575. bits = state.bits;
  8576. //---
  8577.  
  8578. _in = have;
  8579. _out = left;
  8580. ret = Z_OK;
  8581.  
  8582. inf_leave: // goto emulation
  8583. for (;;) {
  8584. switch (state.mode) {
  8585. case HEAD:
  8586. if (state.wrap === 0) {
  8587. state.mode = TYPEDO;
  8588. break;
  8589. }
  8590. //=== NEEDBITS(16);
  8591. while (bits < 16) {
  8592. if (have === 0) { break inf_leave; }
  8593. have--;
  8594. hold += input[next++] << bits;
  8595. bits += 8;
  8596. }
  8597. //===//
  8598. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  8599. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  8600. //=== CRC2(state.check, hold);
  8601. hbuf[0] = hold & 0xff;
  8602. hbuf[1] = (hold >>> 8) & 0xff;
  8603. state.check = crc32(state.check, hbuf, 2, 0);
  8604. //===//
  8605.  
  8606. //=== INITBITS();
  8607. hold = 0;
  8608. bits = 0;
  8609. //===//
  8610. state.mode = FLAGS;
  8611. break;
  8612. }
  8613. state.flags = 0; /* expect zlib header */
  8614. if (state.head) {
  8615. state.head.done = false;
  8616. }
  8617. if (!(state.wrap & 1) || /* check if zlib header allowed */
  8618. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  8619. strm.msg = 'incorrect header check';
  8620. state.mode = BAD;
  8621. break;
  8622. }
  8623. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  8624. strm.msg = 'unknown compression method';
  8625. state.mode = BAD;
  8626. break;
  8627. }
  8628. //--- DROPBITS(4) ---//
  8629. hold >>>= 4;
  8630. bits -= 4;
  8631. //---//
  8632. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  8633. if (state.wbits === 0) {
  8634. state.wbits = len;
  8635. }
  8636. else if (len > state.wbits) {
  8637. strm.msg = 'invalid window size';
  8638. state.mode = BAD;
  8639. break;
  8640. }
  8641. state.dmax = 1 << len;
  8642. //Tracev((stderr, "inflate: zlib header ok\n"));
  8643. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8644. state.mode = hold & 0x200 ? DICTID : TYPE;
  8645. //=== INITBITS();
  8646. hold = 0;
  8647. bits = 0;
  8648. //===//
  8649. break;
  8650. case FLAGS:
  8651. //=== NEEDBITS(16); */
  8652. while (bits < 16) {
  8653. if (have === 0) { break inf_leave; }
  8654. have--;
  8655. hold += input[next++] << bits;
  8656. bits += 8;
  8657. }
  8658. //===//
  8659. state.flags = hold;
  8660. if ((state.flags & 0xff) !== Z_DEFLATED) {
  8661. strm.msg = 'unknown compression method';
  8662. state.mode = BAD;
  8663. break;
  8664. }
  8665. if (state.flags & 0xe000) {
  8666. strm.msg = 'unknown header flags set';
  8667. state.mode = BAD;
  8668. break;
  8669. }
  8670. if (state.head) {
  8671. state.head.text = ((hold >> 8) & 1);
  8672. }
  8673. if (state.flags & 0x0200) {
  8674. //=== CRC2(state.check, hold);
  8675. hbuf[0] = hold & 0xff;
  8676. hbuf[1] = (hold >>> 8) & 0xff;
  8677. state.check = crc32(state.check, hbuf, 2, 0);
  8678. //===//
  8679. }
  8680. //=== INITBITS();
  8681. hold = 0;
  8682. bits = 0;
  8683. //===//
  8684. state.mode = TIME;
  8685. /* falls through */
  8686. case TIME:
  8687. //=== NEEDBITS(32); */
  8688. while (bits < 32) {
  8689. if (have === 0) { break inf_leave; }
  8690. have--;
  8691. hold += input[next++] << bits;
  8692. bits += 8;
  8693. }
  8694. //===//
  8695. if (state.head) {
  8696. state.head.time = hold;
  8697. }
  8698. if (state.flags & 0x0200) {
  8699. //=== CRC4(state.check, hold)
  8700. hbuf[0] = hold & 0xff;
  8701. hbuf[1] = (hold >>> 8) & 0xff;
  8702. hbuf[2] = (hold >>> 16) & 0xff;
  8703. hbuf[3] = (hold >>> 24) & 0xff;
  8704. state.check = crc32(state.check, hbuf, 4, 0);
  8705. //===
  8706. }
  8707. //=== INITBITS();
  8708. hold = 0;
  8709. bits = 0;
  8710. //===//
  8711. state.mode = OS;
  8712. /* falls through */
  8713. case OS:
  8714. //=== NEEDBITS(16); */
  8715. while (bits < 16) {
  8716. if (have === 0) { break inf_leave; }
  8717. have--;
  8718. hold += input[next++] << bits;
  8719. bits += 8;
  8720. }
  8721. //===//
  8722. if (state.head) {
  8723. state.head.xflags = (hold & 0xff);
  8724. state.head.os = (hold >> 8);
  8725. }
  8726. if (state.flags & 0x0200) {
  8727. //=== CRC2(state.check, hold);
  8728. hbuf[0] = hold & 0xff;
  8729. hbuf[1] = (hold >>> 8) & 0xff;
  8730. state.check = crc32(state.check, hbuf, 2, 0);
  8731. //===//
  8732. }
  8733. //=== INITBITS();
  8734. hold = 0;
  8735. bits = 0;
  8736. //===//
  8737. state.mode = EXLEN;
  8738. /* falls through */
  8739. case EXLEN:
  8740. if (state.flags & 0x0400) {
  8741. //=== NEEDBITS(16); */
  8742. while (bits < 16) {
  8743. if (have === 0) { break inf_leave; }
  8744. have--;
  8745. hold += input[next++] << bits;
  8746. bits += 8;
  8747. }
  8748. //===//
  8749. state.length = hold;
  8750. if (state.head) {
  8751. state.head.extra_len = hold;
  8752. }
  8753. if (state.flags & 0x0200) {
  8754. //=== CRC2(state.check, hold);
  8755. hbuf[0] = hold & 0xff;
  8756. hbuf[1] = (hold >>> 8) & 0xff;
  8757. state.check = crc32(state.check, hbuf, 2, 0);
  8758. //===//
  8759. }
  8760. //=== INITBITS();
  8761. hold = 0;
  8762. bits = 0;
  8763. //===//
  8764. }
  8765. else if (state.head) {
  8766. state.head.extra = null/*Z_NULL*/;
  8767. }
  8768. state.mode = EXTRA;
  8769. /* falls through */
  8770. case EXTRA:
  8771. if (state.flags & 0x0400) {
  8772. copy = state.length;
  8773. if (copy > have) { copy = have; }
  8774. if (copy) {
  8775. if (state.head) {
  8776. len = state.head.extra_len - state.length;
  8777. if (!state.head.extra) {
  8778. // Use untyped array for more conveniend processing later
  8779. state.head.extra = new Array(state.head.extra_len);
  8780. }
  8781. utils.arraySet(
  8782. state.head.extra,
  8783. input,
  8784. next,
  8785. // extra field is limited to 65536 bytes
  8786. // - no need for additional size check
  8787. copy,
  8788. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  8789. len
  8790. );
  8791. //zmemcpy(state.head.extra + len, next,
  8792. // len + copy > state.head.extra_max ?
  8793. // state.head.extra_max - len : copy);
  8794. }
  8795. if (state.flags & 0x0200) {
  8796. state.check = crc32(state.check, input, copy, next);
  8797. }
  8798. have -= copy;
  8799. next += copy;
  8800. state.length -= copy;
  8801. }
  8802. if (state.length) { break inf_leave; }
  8803. }
  8804. state.length = 0;
  8805. state.mode = NAME;
  8806. /* falls through */
  8807. case NAME:
  8808. if (state.flags & 0x0800) {
  8809. if (have === 0) { break inf_leave; }
  8810. copy = 0;
  8811. do {
  8812. // TODO: 2 or 1 bytes?
  8813. len = input[next + copy++];
  8814. /* use constant limit because in js we should not preallocate memory */
  8815. if (state.head && len &&
  8816. (state.length < 65536 /*state.head.name_max*/)) {
  8817. state.head.name += String.fromCharCode(len);
  8818. }
  8819. } while (len && copy < have);
  8820.  
  8821. if (state.flags & 0x0200) {
  8822. state.check = crc32(state.check, input, copy, next);
  8823. }
  8824. have -= copy;
  8825. next += copy;
  8826. if (len) { break inf_leave; }
  8827. }
  8828. else if (state.head) {
  8829. state.head.name = null;
  8830. }
  8831. state.length = 0;
  8832. state.mode = COMMENT;
  8833. /* falls through */
  8834. case COMMENT:
  8835. if (state.flags & 0x1000) {
  8836. if (have === 0) { break inf_leave; }
  8837. copy = 0;
  8838. do {
  8839. len = input[next + copy++];
  8840. /* use constant limit because in js we should not preallocate memory */
  8841. if (state.head && len &&
  8842. (state.length < 65536 /*state.head.comm_max*/)) {
  8843. state.head.comment += String.fromCharCode(len);
  8844. }
  8845. } while (len && copy < have);
  8846. if (state.flags & 0x0200) {
  8847. state.check = crc32(state.check, input, copy, next);
  8848. }
  8849. have -= copy;
  8850. next += copy;
  8851. if (len) { break inf_leave; }
  8852. }
  8853. else if (state.head) {
  8854. state.head.comment = null;
  8855. }
  8856. state.mode = HCRC;
  8857. /* falls through */
  8858. case HCRC:
  8859. if (state.flags & 0x0200) {
  8860. //=== NEEDBITS(16); */
  8861. while (bits < 16) {
  8862. if (have === 0) { break inf_leave; }
  8863. have--;
  8864. hold += input[next++] << bits;
  8865. bits += 8;
  8866. }
  8867. //===//
  8868. if (hold !== (state.check & 0xffff)) {
  8869. strm.msg = 'header crc mismatch';
  8870. state.mode = BAD;
  8871. break;
  8872. }
  8873. //=== INITBITS();
  8874. hold = 0;
  8875. bits = 0;
  8876. //===//
  8877. }
  8878. if (state.head) {
  8879. state.head.hcrc = ((state.flags >> 9) & 1);
  8880. state.head.done = true;
  8881. }
  8882. strm.adler = state.check = 0;
  8883. state.mode = TYPE;
  8884. break;
  8885. case DICTID:
  8886. //=== NEEDBITS(32); */
  8887. while (bits < 32) {
  8888. if (have === 0) { break inf_leave; }
  8889. have--;
  8890. hold += input[next++] << bits;
  8891. bits += 8;
  8892. }
  8893. //===//
  8894. strm.adler = state.check = zswap32(hold);
  8895. //=== INITBITS();
  8896. hold = 0;
  8897. bits = 0;
  8898. //===//
  8899. state.mode = DICT;
  8900. /* falls through */
  8901. case DICT:
  8902. if (state.havedict === 0) {
  8903. //--- RESTORE() ---
  8904. strm.next_out = put;
  8905. strm.avail_out = left;
  8906. strm.next_in = next;
  8907. strm.avail_in = have;
  8908. state.hold = hold;
  8909. state.bits = bits;
  8910. //---
  8911. return Z_NEED_DICT;
  8912. }
  8913. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8914. state.mode = TYPE;
  8915. /* falls through */
  8916. case TYPE:
  8917. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  8918. /* falls through */
  8919. case TYPEDO:
  8920. if (state.last) {
  8921. //--- BYTEBITS() ---//
  8922. hold >>>= bits & 7;
  8923. bits -= bits & 7;
  8924. //---//
  8925. state.mode = CHECK;
  8926. break;
  8927. }
  8928. //=== NEEDBITS(3); */
  8929. while (bits < 3) {
  8930. if (have === 0) { break inf_leave; }
  8931. have--;
  8932. hold += input[next++] << bits;
  8933. bits += 8;
  8934. }
  8935. //===//
  8936. state.last = (hold & 0x01)/*BITS(1)*/;
  8937. //--- DROPBITS(1) ---//
  8938. hold >>>= 1;
  8939. bits -= 1;
  8940. //---//
  8941.  
  8942. switch ((hold & 0x03)/*BITS(2)*/) {
  8943. case 0: /* stored block */
  8944. //Tracev((stderr, "inflate: stored block%s\n",
  8945. // state.last ? " (last)" : ""));
  8946. state.mode = STORED;
  8947. break;
  8948. case 1: /* fixed block */
  8949. fixedtables(state);
  8950. //Tracev((stderr, "inflate: fixed codes block%s\n",
  8951. // state.last ? " (last)" : ""));
  8952. state.mode = LEN_; /* decode codes */
  8953. if (flush === Z_TREES) {
  8954. //--- DROPBITS(2) ---//
  8955. hold >>>= 2;
  8956. bits -= 2;
  8957. //---//
  8958. break inf_leave;
  8959. }
  8960. break;
  8961. case 2: /* dynamic block */
  8962. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  8963. // state.last ? " (last)" : ""));
  8964. state.mode = TABLE;
  8965. break;
  8966. case 3:
  8967. strm.msg = 'invalid block type';
  8968. state.mode = BAD;
  8969. }
  8970. //--- DROPBITS(2) ---//
  8971. hold >>>= 2;
  8972. bits -= 2;
  8973. //---//
  8974. break;
  8975. case STORED:
  8976. //--- BYTEBITS() ---// /* go to byte boundary */
  8977. hold >>>= bits & 7;
  8978. bits -= bits & 7;
  8979. //---//
  8980. //=== NEEDBITS(32); */
  8981. while (bits < 32) {
  8982. if (have === 0) { break inf_leave; }
  8983. have--;
  8984. hold += input[next++] << bits;
  8985. bits += 8;
  8986. }
  8987. //===//
  8988. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  8989. strm.msg = 'invalid stored block lengths';
  8990. state.mode = BAD;
  8991. break;
  8992. }
  8993. state.length = hold & 0xffff;
  8994. //Tracev((stderr, "inflate: stored length %u\n",
  8995. // state.length));
  8996. //=== INITBITS();
  8997. hold = 0;
  8998. bits = 0;
  8999. //===//
  9000. state.mode = COPY_;
  9001. if (flush === Z_TREES) { break inf_leave; }
  9002. /* falls through */
  9003. case COPY_:
  9004. state.mode = COPY;
  9005. /* falls through */
  9006. case COPY:
  9007. copy = state.length;
  9008. if (copy) {
  9009. if (copy > have) { copy = have; }
  9010. if (copy > left) { copy = left; }
  9011. if (copy === 0) { break inf_leave; }
  9012. //--- zmemcpy(put, next, copy); ---
  9013. utils.arraySet(output, input, next, copy, put);
  9014. //---//
  9015. have -= copy;
  9016. next += copy;
  9017. left -= copy;
  9018. put += copy;
  9019. state.length -= copy;
  9020. break;
  9021. }
  9022. //Tracev((stderr, "inflate: stored end\n"));
  9023. state.mode = TYPE;
  9024. break;
  9025. case TABLE:
  9026. //=== NEEDBITS(14); */
  9027. while (bits < 14) {
  9028. if (have === 0) { break inf_leave; }
  9029. have--;
  9030. hold += input[next++] << bits;
  9031. bits += 8;
  9032. }
  9033. //===//
  9034. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  9035. //--- DROPBITS(5) ---//
  9036. hold >>>= 5;
  9037. bits -= 5;
  9038. //---//
  9039. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  9040. //--- DROPBITS(5) ---//
  9041. hold >>>= 5;
  9042. bits -= 5;
  9043. //---//
  9044. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  9045. //--- DROPBITS(4) ---//
  9046. hold >>>= 4;
  9047. bits -= 4;
  9048. //---//
  9049. //#ifndef PKZIP_BUG_WORKAROUND
  9050. if (state.nlen > 286 || state.ndist > 30) {
  9051. strm.msg = 'too many length or distance symbols';
  9052. state.mode = BAD;
  9053. break;
  9054. }
  9055. //#endif
  9056. //Tracev((stderr, "inflate: table sizes ok\n"));
  9057. state.have = 0;
  9058. state.mode = LENLENS;
  9059. /* falls through */
  9060. case LENLENS:
  9061. while (state.have < state.ncode) {
  9062. //=== NEEDBITS(3);
  9063. while (bits < 3) {
  9064. if (have === 0) { break inf_leave; }
  9065. have--;
  9066. hold += input[next++] << bits;
  9067. bits += 8;
  9068. }
  9069. //===//
  9070. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  9071. //--- DROPBITS(3) ---//
  9072. hold >>>= 3;
  9073. bits -= 3;
  9074. //---//
  9075. }
  9076. while (state.have < 19) {
  9077. state.lens[order[state.have++]] = 0;
  9078. }
  9079. // We have separate tables & no pointers. 2 commented lines below not needed.
  9080. //state.next = state.codes;
  9081. //state.lencode = state.next;
  9082. // Switch to use dynamic table
  9083. state.lencode = state.lendyn;
  9084. state.lenbits = 7;
  9085.  
  9086. opts = { bits: state.lenbits };
  9087. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  9088. state.lenbits = opts.bits;
  9089.  
  9090. if (ret) {
  9091. strm.msg = 'invalid code lengths set';
  9092. state.mode = BAD;
  9093. break;
  9094. }
  9095. //Tracev((stderr, "inflate: code lengths ok\n"));
  9096. state.have = 0;
  9097. state.mode = CODELENS;
  9098. /* falls through */
  9099. case CODELENS:
  9100. while (state.have < state.nlen + state.ndist) {
  9101. for (;;) {
  9102. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  9103. here_bits = here >>> 24;
  9104. here_op = (here >>> 16) & 0xff;
  9105. here_val = here & 0xffff;
  9106.  
  9107. if ((here_bits) <= bits) { break; }
  9108. //--- PULLBYTE() ---//
  9109. if (have === 0) { break inf_leave; }
  9110. have--;
  9111. hold += input[next++] << bits;
  9112. bits += 8;
  9113. //---//
  9114. }
  9115. if (here_val < 16) {
  9116. //--- DROPBITS(here.bits) ---//
  9117. hold >>>= here_bits;
  9118. bits -= here_bits;
  9119. //---//
  9120. state.lens[state.have++] = here_val;
  9121. }
  9122. else {
  9123. if (here_val === 16) {
  9124. //=== NEEDBITS(here.bits + 2);
  9125. n = here_bits + 2;
  9126. while (bits < n) {
  9127. if (have === 0) { break inf_leave; }
  9128. have--;
  9129. hold += input[next++] << bits;
  9130. bits += 8;
  9131. }
  9132. //===//
  9133. //--- DROPBITS(here.bits) ---//
  9134. hold >>>= here_bits;
  9135. bits -= here_bits;
  9136. //---//
  9137. if (state.have === 0) {
  9138. strm.msg = 'invalid bit length repeat';
  9139. state.mode = BAD;
  9140. break;
  9141. }
  9142. len = state.lens[state.have - 1];
  9143. copy = 3 + (hold & 0x03);//BITS(2);
  9144. //--- DROPBITS(2) ---//
  9145. hold >>>= 2;
  9146. bits -= 2;
  9147. //---//
  9148. }
  9149. else if (here_val === 17) {
  9150. //=== NEEDBITS(here.bits + 3);
  9151. n = here_bits + 3;
  9152. while (bits < n) {
  9153. if (have === 0) { break inf_leave; }
  9154. have--;
  9155. hold += input[next++] << bits;
  9156. bits += 8;
  9157. }
  9158. //===//
  9159. //--- DROPBITS(here.bits) ---//
  9160. hold >>>= here_bits;
  9161. bits -= here_bits;
  9162. //---//
  9163. len = 0;
  9164. copy = 3 + (hold & 0x07);//BITS(3);
  9165. //--- DROPBITS(3) ---//
  9166. hold >>>= 3;
  9167. bits -= 3;
  9168. //---//
  9169. }
  9170. else {
  9171. //=== NEEDBITS(here.bits + 7);
  9172. n = here_bits + 7;
  9173. while (bits < n) {
  9174. if (have === 0) { break inf_leave; }
  9175. have--;
  9176. hold += input[next++] << bits;
  9177. bits += 8;
  9178. }
  9179. //===//
  9180. //--- DROPBITS(here.bits) ---//
  9181. hold >>>= here_bits;
  9182. bits -= here_bits;
  9183. //---//
  9184. len = 0;
  9185. copy = 11 + (hold & 0x7f);//BITS(7);
  9186. //--- DROPBITS(7) ---//
  9187. hold >>>= 7;
  9188. bits -= 7;
  9189. //---//
  9190. }
  9191. if (state.have + copy > state.nlen + state.ndist) {
  9192. strm.msg = 'invalid bit length repeat';
  9193. state.mode = BAD;
  9194. break;
  9195. }
  9196. while (copy--) {
  9197. state.lens[state.have++] = len;
  9198. }
  9199. }
  9200. }
  9201.  
  9202. /* handle error breaks in while */
  9203. if (state.mode === BAD) { break; }
  9204.  
  9205. /* check for end-of-block code (better have one) */
  9206. if (state.lens[256] === 0) {
  9207. strm.msg = 'invalid code -- missing end-of-block';
  9208. state.mode = BAD;
  9209. break;
  9210. }
  9211.  
  9212. /* build code tables -- note: do not change the lenbits or distbits
  9213. values here (9 and 6) without reading the comments in inftrees.h
  9214. concerning the ENOUGH constants, which depend on those values */
  9215. state.lenbits = 9;
  9216.  
  9217. opts = { bits: state.lenbits };
  9218. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  9219. // We have separate tables & no pointers. 2 commented lines below not needed.
  9220. // state.next_index = opts.table_index;
  9221. state.lenbits = opts.bits;
  9222. // state.lencode = state.next;
  9223.  
  9224. if (ret) {
  9225. strm.msg = 'invalid literal/lengths set';
  9226. state.mode = BAD;
  9227. break;
  9228. }
  9229.  
  9230. state.distbits = 6;
  9231. //state.distcode.copy(state.codes);
  9232. // Switch to use dynamic table
  9233. state.distcode = state.distdyn;
  9234. opts = { bits: state.distbits };
  9235. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  9236. // We have separate tables & no pointers. 2 commented lines below not needed.
  9237. // state.next_index = opts.table_index;
  9238. state.distbits = opts.bits;
  9239. // state.distcode = state.next;
  9240.  
  9241. if (ret) {
  9242. strm.msg = 'invalid distances set';
  9243. state.mode = BAD;
  9244. break;
  9245. }
  9246. //Tracev((stderr, 'inflate: codes ok\n'));
  9247. state.mode = LEN_;
  9248. if (flush === Z_TREES) { break inf_leave; }
  9249. /* falls through */
  9250. case LEN_:
  9251. state.mode = LEN;
  9252. /* falls through */
  9253. case LEN:
  9254. if (have >= 6 && left >= 258) {
  9255. //--- RESTORE() ---
  9256. strm.next_out = put;
  9257. strm.avail_out = left;
  9258. strm.next_in = next;
  9259. strm.avail_in = have;
  9260. state.hold = hold;
  9261. state.bits = bits;
  9262. //---
  9263. inflate_fast(strm, _out);
  9264. //--- LOAD() ---
  9265. put = strm.next_out;
  9266. output = strm.output;
  9267. left = strm.avail_out;
  9268. next = strm.next_in;
  9269. input = strm.input;
  9270. have = strm.avail_in;
  9271. hold = state.hold;
  9272. bits = state.bits;
  9273. //---
  9274.  
  9275. if (state.mode === TYPE) {
  9276. state.back = -1;
  9277. }
  9278. break;
  9279. }
  9280. state.back = 0;
  9281. for (;;) {
  9282. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  9283. here_bits = here >>> 24;
  9284. here_op = (here >>> 16) & 0xff;
  9285. here_val = here & 0xffff;
  9286.  
  9287. if (here_bits <= bits) { break; }
  9288. //--- PULLBYTE() ---//
  9289. if (have === 0) { break inf_leave; }
  9290. have--;
  9291. hold += input[next++] << bits;
  9292. bits += 8;
  9293. //---//
  9294. }
  9295. if (here_op && (here_op & 0xf0) === 0) {
  9296. last_bits = here_bits;
  9297. last_op = here_op;
  9298. last_val = here_val;
  9299. for (;;) {
  9300. here = state.lencode[last_val +
  9301. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9302. here_bits = here >>> 24;
  9303. here_op = (here >>> 16) & 0xff;
  9304. here_val = here & 0xffff;
  9305.  
  9306. if ((last_bits + here_bits) <= bits) { break; }
  9307. //--- PULLBYTE() ---//
  9308. if (have === 0) { break inf_leave; }
  9309. have--;
  9310. hold += input[next++] << bits;
  9311. bits += 8;
  9312. //---//
  9313. }
  9314. //--- DROPBITS(last.bits) ---//
  9315. hold >>>= last_bits;
  9316. bits -= last_bits;
  9317. //---//
  9318. state.back += last_bits;
  9319. }
  9320. //--- DROPBITS(here.bits) ---//
  9321. hold >>>= here_bits;
  9322. bits -= here_bits;
  9323. //---//
  9324. state.back += here_bits;
  9325. state.length = here_val;
  9326. if (here_op === 0) {
  9327. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  9328. // "inflate: literal '%c'\n" :
  9329. // "inflate: literal 0x%02x\n", here.val));
  9330. state.mode = LIT;
  9331. break;
  9332. }
  9333. if (here_op & 32) {
  9334. //Tracevv((stderr, "inflate: end of block\n"));
  9335. state.back = -1;
  9336. state.mode = TYPE;
  9337. break;
  9338. }
  9339. if (here_op & 64) {
  9340. strm.msg = 'invalid literal/length code';
  9341. state.mode = BAD;
  9342. break;
  9343. }
  9344. state.extra = here_op & 15;
  9345. state.mode = LENEXT;
  9346. /* falls through */
  9347. case LENEXT:
  9348. if (state.extra) {
  9349. //=== NEEDBITS(state.extra);
  9350. n = state.extra;
  9351. while (bits < n) {
  9352. if (have === 0) { break inf_leave; }
  9353. have--;
  9354. hold += input[next++] << bits;
  9355. bits += 8;
  9356. }
  9357. //===//
  9358. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9359. //--- DROPBITS(state.extra) ---//
  9360. hold >>>= state.extra;
  9361. bits -= state.extra;
  9362. //---//
  9363. state.back += state.extra;
  9364. }
  9365. //Tracevv((stderr, "inflate: length %u\n", state.length));
  9366. state.was = state.length;
  9367. state.mode = DIST;
  9368. /* falls through */
  9369. case DIST:
  9370. for (;;) {
  9371. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  9372. here_bits = here >>> 24;
  9373. here_op = (here >>> 16) & 0xff;
  9374. here_val = here & 0xffff;
  9375.  
  9376. if ((here_bits) <= bits) { break; }
  9377. //--- PULLBYTE() ---//
  9378. if (have === 0) { break inf_leave; }
  9379. have--;
  9380. hold += input[next++] << bits;
  9381. bits += 8;
  9382. //---//
  9383. }
  9384. if ((here_op & 0xf0) === 0) {
  9385. last_bits = here_bits;
  9386. last_op = here_op;
  9387. last_val = here_val;
  9388. for (;;) {
  9389. here = state.distcode[last_val +
  9390. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9391. here_bits = here >>> 24;
  9392. here_op = (here >>> 16) & 0xff;
  9393. here_val = here & 0xffff;
  9394.  
  9395. if ((last_bits + here_bits) <= bits) { break; }
  9396. //--- PULLBYTE() ---//
  9397. if (have === 0) { break inf_leave; }
  9398. have--;
  9399. hold += input[next++] << bits;
  9400. bits += 8;
  9401. //---//
  9402. }
  9403. //--- DROPBITS(last.bits) ---//
  9404. hold >>>= last_bits;
  9405. bits -= last_bits;
  9406. //---//
  9407. state.back += last_bits;
  9408. }
  9409. //--- DROPBITS(here.bits) ---//
  9410. hold >>>= here_bits;
  9411. bits -= here_bits;
  9412. //---//
  9413. state.back += here_bits;
  9414. if (here_op & 64) {
  9415. strm.msg = 'invalid distance code';
  9416. state.mode = BAD;
  9417. break;
  9418. }
  9419. state.offset = here_val;
  9420. state.extra = (here_op) & 15;
  9421. state.mode = DISTEXT;
  9422. /* falls through */
  9423. case DISTEXT:
  9424. if (state.extra) {
  9425. //=== NEEDBITS(state.extra);
  9426. n = state.extra;
  9427. while (bits < n) {
  9428. if (have === 0) { break inf_leave; }
  9429. have--;
  9430. hold += input[next++] << bits;
  9431. bits += 8;
  9432. }
  9433. //===//
  9434. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9435. //--- DROPBITS(state.extra) ---//
  9436. hold >>>= state.extra;
  9437. bits -= state.extra;
  9438. //---//
  9439. state.back += state.extra;
  9440. }
  9441. //#ifdef INFLATE_STRICT
  9442. if (state.offset > state.dmax) {
  9443. strm.msg = 'invalid distance too far back';
  9444. state.mode = BAD;
  9445. break;
  9446. }
  9447. //#endif
  9448. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  9449. state.mode = MATCH;
  9450. /* falls through */
  9451. case MATCH:
  9452. if (left === 0) { break inf_leave; }
  9453. copy = _out - left;
  9454. if (state.offset > copy) { /* copy from window */
  9455. copy = state.offset - copy;
  9456. if (copy > state.whave) {
  9457. if (state.sane) {
  9458. strm.msg = 'invalid distance too far back';
  9459. state.mode = BAD;
  9460. break;
  9461. }
  9462. // (!) This block is disabled in zlib defailts,
  9463. // don't enable it for binary compatibility
  9464. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9465. // Trace((stderr, "inflate.c too far\n"));
  9466. // copy -= state.whave;
  9467. // if (copy > state.length) { copy = state.length; }
  9468. // if (copy > left) { copy = left; }
  9469. // left -= copy;
  9470. // state.length -= copy;
  9471. // do {
  9472. // output[put++] = 0;
  9473. // } while (--copy);
  9474. // if (state.length === 0) { state.mode = LEN; }
  9475. // break;
  9476. //#endif
  9477. }
  9478. if (copy > state.wnext) {
  9479. copy -= state.wnext;
  9480. from = state.wsize - copy;
  9481. }
  9482. else {
  9483. from = state.wnext - copy;
  9484. }
  9485. if (copy > state.length) { copy = state.length; }
  9486. from_source = state.window;
  9487. }
  9488. else { /* copy from output */
  9489. from_source = output;
  9490. from = put - state.offset;
  9491. copy = state.length;
  9492. }
  9493. if (copy > left) { copy = left; }
  9494. left -= copy;
  9495. state.length -= copy;
  9496. do {
  9497. output[put++] = from_source[from++];
  9498. } while (--copy);
  9499. if (state.length === 0) { state.mode = LEN; }
  9500. break;
  9501. case LIT:
  9502. if (left === 0) { break inf_leave; }
  9503. output[put++] = state.length;
  9504. left--;
  9505. state.mode = LEN;
  9506. break;
  9507. case CHECK:
  9508. if (state.wrap) {
  9509. //=== NEEDBITS(32);
  9510. while (bits < 32) {
  9511. if (have === 0) { break inf_leave; }
  9512. have--;
  9513. // Use '|' insdead of '+' to make sure that result is signed
  9514. hold |= input[next++] << bits;
  9515. bits += 8;
  9516. }
  9517. //===//
  9518. _out -= left;
  9519. strm.total_out += _out;
  9520. state.total += _out;
  9521. if (_out) {
  9522. strm.adler = state.check =
  9523. /*UPDATE(state.check, put - _out, _out);*/
  9524. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  9525.  
  9526. }
  9527. _out = left;
  9528. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  9529. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  9530. strm.msg = 'incorrect data check';
  9531. state.mode = BAD;
  9532. break;
  9533. }
  9534. //=== INITBITS();
  9535. hold = 0;
  9536. bits = 0;
  9537. //===//
  9538. //Tracev((stderr, "inflate: check matches trailer\n"));
  9539. }
  9540. state.mode = LENGTH;
  9541. /* falls through */
  9542. case LENGTH:
  9543. if (state.wrap && state.flags) {
  9544. //=== NEEDBITS(32);
  9545. while (bits < 32) {
  9546. if (have === 0) { break inf_leave; }
  9547. have--;
  9548. hold += input[next++] << bits;
  9549. bits += 8;
  9550. }
  9551. //===//
  9552. if (hold !== (state.total & 0xffffffff)) {
  9553. strm.msg = 'incorrect length check';
  9554. state.mode = BAD;
  9555. break;
  9556. }
  9557. //=== INITBITS();
  9558. hold = 0;
  9559. bits = 0;
  9560. //===//
  9561. //Tracev((stderr, "inflate: length matches trailer\n"));
  9562. }
  9563. state.mode = DONE;
  9564. /* falls through */
  9565. case DONE:
  9566. ret = Z_STREAM_END;
  9567. break inf_leave;
  9568. case BAD:
  9569. ret = Z_DATA_ERROR;
  9570. break inf_leave;
  9571. case MEM:
  9572. return Z_MEM_ERROR;
  9573. case SYNC:
  9574. /* falls through */
  9575. default:
  9576. return Z_STREAM_ERROR;
  9577. }
  9578. }
  9579.  
  9580. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  9581.  
  9582. /*
  9583. Return from inflate(), updating the total counts and the check value.
  9584. If there was no progress during the inflate() call, return a buffer
  9585. error. Call updatewindow() to create and/or update the window state.
  9586. Note: a memory error from inflate() is non-recoverable.
  9587. */
  9588.  
  9589. //--- RESTORE() ---
  9590. strm.next_out = put;
  9591. strm.avail_out = left;
  9592. strm.next_in = next;
  9593. strm.avail_in = have;
  9594. state.hold = hold;
  9595. state.bits = bits;
  9596. //---
  9597.  
  9598. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  9599. (state.mode < CHECK || flush !== Z_FINISH))) {
  9600. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  9601. state.mode = MEM;
  9602. return Z_MEM_ERROR;
  9603. }
  9604. }
  9605. _in -= strm.avail_in;
  9606. _out -= strm.avail_out;
  9607. strm.total_in += _in;
  9608. strm.total_out += _out;
  9609. state.total += _out;
  9610. if (state.wrap && _out) {
  9611. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  9612. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  9613. }
  9614. strm.data_type = state.bits + (state.last ? 64 : 0) +
  9615. (state.mode === TYPE ? 128 : 0) +
  9616. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  9617. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  9618. ret = Z_BUF_ERROR;
  9619. }
  9620. return ret;
  9621. }
  9622.  
  9623. function inflateEnd(strm) {
  9624.  
  9625. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  9626. return Z_STREAM_ERROR;
  9627. }
  9628.  
  9629. var state = strm.state;
  9630. if (state.window) {
  9631. state.window = null;
  9632. }
  9633. strm.state = null;
  9634. return Z_OK;
  9635. }
  9636.  
  9637. function inflateGetHeader(strm, head) {
  9638. var state;
  9639.  
  9640. /* check state */
  9641. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9642. state = strm.state;
  9643. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  9644.  
  9645. /* save header structure */
  9646. state.head = head;
  9647. head.done = false;
  9648. return Z_OK;
  9649. }
  9650.  
  9651. function inflateSetDictionary(strm, dictionary) {
  9652. var dictLength = dictionary.length;
  9653.  
  9654. var state;
  9655. var dictid;
  9656. var ret;
  9657.  
  9658. /* check state */
  9659. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  9660. state = strm.state;
  9661.  
  9662. if (state.wrap !== 0 && state.mode !== DICT) {
  9663. return Z_STREAM_ERROR;
  9664. }
  9665.  
  9666. /* check for correct dictionary identifier */
  9667. if (state.mode === DICT) {
  9668. dictid = 1; /* adler32(0, null, 0)*/
  9669. /* dictid = adler32(dictid, dictionary, dictLength); */
  9670. dictid = adler32(dictid, dictionary, dictLength, 0);
  9671. if (dictid !== state.check) {
  9672. return Z_DATA_ERROR;
  9673. }
  9674. }
  9675. /* copy dictionary to window using updatewindow(), which will amend the
  9676. existing dictionary if appropriate */
  9677. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  9678. if (ret) {
  9679. state.mode = MEM;
  9680. return Z_MEM_ERROR;
  9681. }
  9682. state.havedict = 1;
  9683. // Tracev((stderr, "inflate: dictionary set\n"));
  9684. return Z_OK;
  9685. }
  9686.  
  9687. exports.inflateReset = inflateReset;
  9688. exports.inflateReset2 = inflateReset2;
  9689. exports.inflateResetKeep = inflateResetKeep;
  9690. exports.inflateInit = inflateInit;
  9691. exports.inflateInit2 = inflateInit2;
  9692. exports.inflate = inflate;
  9693. exports.inflateEnd = inflateEnd;
  9694. exports.inflateGetHeader = inflateGetHeader;
  9695. exports.inflateSetDictionary = inflateSetDictionary;
  9696. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  9697.  
  9698. /* Not implemented
  9699. exports.inflateCopy = inflateCopy;
  9700. exports.inflateGetDictionary = inflateGetDictionary;
  9701. exports.inflateMark = inflateMark;
  9702. exports.inflatePrime = inflatePrime;
  9703. exports.inflateSync = inflateSync;
  9704. exports.inflateSyncPoint = inflateSyncPoint;
  9705. exports.inflateUndermine = inflateUndermine;
  9706. */
  9707.  
  9708. },{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(require,module,exports){
  9709. 'use strict';
  9710.  
  9711. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9712. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9713. //
  9714. // This software is provided 'as-is', without any express or implied
  9715. // warranty. In no event will the authors be held liable for any damages
  9716. // arising from the use of this software.
  9717. //
  9718. // Permission is granted to anyone to use this software for any purpose,
  9719. // including commercial applications, and to alter it and redistribute it
  9720. // freely, subject to the following restrictions:
  9721. //
  9722. // 1. The origin of this software must not be misrepresented; you must not
  9723. // claim that you wrote the original software. If you use this software
  9724. // in a product, an acknowledgment in the product documentation would be
  9725. // appreciated but is not required.
  9726. // 2. Altered source versions must be plainly marked as such, and must not be
  9727. // misrepresented as being the original software.
  9728. // 3. This notice may not be removed or altered from any source distribution.
  9729.  
  9730. var utils = require('../utils/common');
  9731.  
  9732. var MAXBITS = 15;
  9733. var ENOUGH_LENS = 852;
  9734. var ENOUGH_DISTS = 592;
  9735. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  9736.  
  9737. var CODES = 0;
  9738. var LENS = 1;
  9739. var DISTS = 2;
  9740.  
  9741. var lbase = [ /* Length codes 257..285 base */
  9742. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  9743. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  9744. ];
  9745.  
  9746. var lext = [ /* Length codes 257..285 extra */
  9747. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  9748. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  9749. ];
  9750.  
  9751. var dbase = [ /* Distance codes 0..29 base */
  9752. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  9753. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  9754. 8193, 12289, 16385, 24577, 0, 0
  9755. ];
  9756.  
  9757. var dext = [ /* Distance codes 0..29 extra */
  9758. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  9759. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  9760. 28, 28, 29, 29, 64, 64
  9761. ];
  9762.  
  9763. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  9764. {
  9765. var bits = opts.bits;
  9766. //here = opts.here; /* table entry for duplication */
  9767.  
  9768. var len = 0; /* a code's length in bits */
  9769. var sym = 0; /* index of code symbols */
  9770. var min = 0, max = 0; /* minimum and maximum code lengths */
  9771. var root = 0; /* number of index bits for root table */
  9772. var curr = 0; /* number of index bits for current table */
  9773. var drop = 0; /* code bits to drop for sub-table */
  9774. var left = 0; /* number of prefix codes available */
  9775. var used = 0; /* code entries in table used */
  9776. var huff = 0; /* Huffman code */
  9777. var incr; /* for incrementing code, index */
  9778. var fill; /* index for replicating entries */
  9779. var low; /* low bits for current root entry */
  9780. var mask; /* mask for low root bits */
  9781. var next; /* next available space in table */
  9782. var base = null; /* base value table to use */
  9783. var base_index = 0;
  9784. // var shoextra; /* extra bits table to use */
  9785. var end; /* use base and extra for symbol > end */
  9786. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  9787. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  9788. var extra = null;
  9789. var extra_index = 0;
  9790.  
  9791. var here_bits, here_op, here_val;
  9792.  
  9793. /*
  9794. Process a set of code lengths to create a canonical Huffman code. The
  9795. code lengths are lens[0..codes-1]. Each length corresponds to the
  9796. symbols 0..codes-1. The Huffman code is generated by first sorting the
  9797. symbols by length from short to long, and retaining the symbol order
  9798. for codes with equal lengths. Then the code starts with all zero bits
  9799. for the first code of the shortest length, and the codes are integer
  9800. increments for the same length, and zeros are appended as the length
  9801. increases. For the deflate format, these bits are stored backwards
  9802. from their more natural integer increment ordering, and so when the
  9803. decoding tables are built in the large loop below, the integer codes
  9804. are incremented backwards.
  9805.  
  9806. This routine assumes, but does not check, that all of the entries in
  9807. lens[] are in the range 0..MAXBITS. The caller must assure this.
  9808. 1..MAXBITS is interpreted as that code length. zero means that that
  9809. symbol does not occur in this code.
  9810.  
  9811. The codes are sorted by computing a count of codes for each length,
  9812. creating from that a table of starting indices for each length in the
  9813. sorted table, and then entering the symbols in order in the sorted
  9814. table. The sorted table is work[], with that space being provided by
  9815. the caller.
  9816.  
  9817. The length counts are used for other purposes as well, i.e. finding
  9818. the minimum and maximum length codes, determining if there are any
  9819. codes at all, checking for a valid set of lengths, and looking ahead
  9820. at length counts to determine sub-table sizes when building the
  9821. decoding tables.
  9822. */
  9823.  
  9824. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  9825. for (len = 0; len <= MAXBITS; len++) {
  9826. count[len] = 0;
  9827. }
  9828. for (sym = 0; sym < codes; sym++) {
  9829. count[lens[lens_index + sym]]++;
  9830. }
  9831.  
  9832. /* bound code lengths, force root to be within code lengths */
  9833. root = bits;
  9834. for (max = MAXBITS; max >= 1; max--) {
  9835. if (count[max] !== 0) { break; }
  9836. }
  9837. if (root > max) {
  9838. root = max;
  9839. }
  9840. if (max === 0) { /* no symbols to code at all */
  9841. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  9842. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  9843. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  9844. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9845.  
  9846.  
  9847. //table.op[opts.table_index] = 64;
  9848. //table.bits[opts.table_index] = 1;
  9849. //table.val[opts.table_index++] = 0;
  9850. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9851.  
  9852. opts.bits = 1;
  9853. return 0; /* no symbols, but wait for decoding to report error */
  9854. }
  9855. for (min = 1; min < max; min++) {
  9856. if (count[min] !== 0) { break; }
  9857. }
  9858. if (root < min) {
  9859. root = min;
  9860. }
  9861.  
  9862. /* check for an over-subscribed or incomplete set of lengths */
  9863. left = 1;
  9864. for (len = 1; len <= MAXBITS; len++) {
  9865. left <<= 1;
  9866. left -= count[len];
  9867. if (left < 0) {
  9868. return -1;
  9869. } /* over-subscribed */
  9870. }
  9871. if (left > 0 && (type === CODES || max !== 1)) {
  9872. return -1; /* incomplete set */
  9873. }
  9874.  
  9875. /* generate offsets into symbol table for each length for sorting */
  9876. offs[1] = 0;
  9877. for (len = 1; len < MAXBITS; len++) {
  9878. offs[len + 1] = offs[len] + count[len];
  9879. }
  9880.  
  9881. /* sort symbols by length, by symbol order within each length */
  9882. for (sym = 0; sym < codes; sym++) {
  9883. if (lens[lens_index + sym] !== 0) {
  9884. work[offs[lens[lens_index + sym]]++] = sym;
  9885. }
  9886. }
  9887.  
  9888. /*
  9889. Create and fill in decoding tables. In this loop, the table being
  9890. filled is at next and has curr index bits. The code being used is huff
  9891. with length len. That code is converted to an index by dropping drop
  9892. bits off of the bottom. For codes where len is less than drop + curr,
  9893. those top drop + curr - len bits are incremented through all values to
  9894. fill the table with replicated entries.
  9895.  
  9896. root is the number of index bits for the root table. When len exceeds
  9897. root, sub-tables are created pointed to by the root entry with an index
  9898. of the low root bits of huff. This is saved in low to check for when a
  9899. new sub-table should be started. drop is zero when the root table is
  9900. being filled, and drop is root when sub-tables are being filled.
  9901.  
  9902. When a new sub-table is needed, it is necessary to look ahead in the
  9903. code lengths to determine what size sub-table is needed. The length
  9904. counts are used for this, and so count[] is decremented as codes are
  9905. entered in the tables.
  9906.  
  9907. used keeps track of how many table entries have been allocated from the
  9908. provided *table space. It is checked for LENS and DIST tables against
  9909. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  9910. the initial root table size constants. See the comments in inftrees.h
  9911. for more information.
  9912.  
  9913. sym increments through all symbols, and the loop terminates when
  9914. all codes of length max, i.e. all codes, have been processed. This
  9915. routine permits incomplete codes, so another loop after this one fills
  9916. in the rest of the decoding tables with invalid code markers.
  9917. */
  9918.  
  9919. /* set up for code type */
  9920. // poor man optimization - use if-else instead of switch,
  9921. // to avoid deopts in old v8
  9922. if (type === CODES) {
  9923. base = extra = work; /* dummy value--not used */
  9924. end = 19;
  9925.  
  9926. } else if (type === LENS) {
  9927. base = lbase;
  9928. base_index -= 257;
  9929. extra = lext;
  9930. extra_index -= 257;
  9931. end = 256;
  9932.  
  9933. } else { /* DISTS */
  9934. base = dbase;
  9935. extra = dext;
  9936. end = -1;
  9937. }
  9938.  
  9939. /* initialize opts for loop */
  9940. huff = 0; /* starting code */
  9941. sym = 0; /* starting code symbol */
  9942. len = min; /* starting code length */
  9943. next = table_index; /* current table to fill in */
  9944. curr = root; /* current table index bits */
  9945. drop = 0; /* current bits to drop from code for index */
  9946. low = -1; /* trigger new sub-table when len > root */
  9947. used = 1 << root; /* use root table entries */
  9948. mask = used - 1; /* mask for comparing low */
  9949.  
  9950. /* check available table space */
  9951. if ((type === LENS && used > ENOUGH_LENS) ||
  9952. (type === DISTS && used > ENOUGH_DISTS)) {
  9953. return 1;
  9954. }
  9955.  
  9956. /* process all codes and make table entries */
  9957. for (;;) {
  9958. /* create table entry */
  9959. here_bits = len - drop;
  9960. if (work[sym] < end) {
  9961. here_op = 0;
  9962. here_val = work[sym];
  9963. }
  9964. else if (work[sym] > end) {
  9965. here_op = extra[extra_index + work[sym]];
  9966. here_val = base[base_index + work[sym]];
  9967. }
  9968. else {
  9969. here_op = 32 + 64; /* end of block */
  9970. here_val = 0;
  9971. }
  9972.  
  9973. /* replicate for those indices with low len bits equal to huff */
  9974. incr = 1 << (len - drop);
  9975. fill = 1 << curr;
  9976. min = fill; /* save offset to next table */
  9977. do {
  9978. fill -= incr;
  9979. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  9980. } while (fill !== 0);
  9981.  
  9982. /* backwards increment the len-bit code huff */
  9983. incr = 1 << (len - 1);
  9984. while (huff & incr) {
  9985. incr >>= 1;
  9986. }
  9987. if (incr !== 0) {
  9988. huff &= incr - 1;
  9989. huff += incr;
  9990. } else {
  9991. huff = 0;
  9992. }
  9993.  
  9994. /* go to next symbol, update count, len */
  9995. sym++;
  9996. if (--count[len] === 0) {
  9997. if (len === max) { break; }
  9998. len = lens[lens_index + work[sym]];
  9999. }
  10000.  
  10001. /* create new sub-table if needed */
  10002. if (len > root && (huff & mask) !== low) {
  10003. /* if first time, transition to sub-tables */
  10004. if (drop === 0) {
  10005. drop = root;
  10006. }
  10007.  
  10008. /* increment past last table */
  10009. next += min; /* here min is 1 << curr */
  10010.  
  10011. /* determine length of next table */
  10012. curr = len - drop;
  10013. left = 1 << curr;
  10014. while (curr + drop < max) {
  10015. left -= count[curr + drop];
  10016. if (left <= 0) { break; }
  10017. curr++;
  10018. left <<= 1;
  10019. }
  10020.  
  10021. /* check for enough space */
  10022. used += 1 << curr;
  10023. if ((type === LENS && used > ENOUGH_LENS) ||
  10024. (type === DISTS && used > ENOUGH_DISTS)) {
  10025. return 1;
  10026. }
  10027.  
  10028. /* point entry in root table to sub-table */
  10029. low = huff & mask;
  10030. /*table.op[low] = curr;
  10031. table.bits[low] = root;
  10032. table.val[low] = next - opts.table_index;*/
  10033. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  10034. }
  10035. }
  10036.  
  10037. /* fill in remaining table entry if code is incomplete (guaranteed to have
  10038. at most one remaining entry, since if the code is incomplete, the
  10039. maximum code length that was allowed to get this far is one bit) */
  10040. if (huff !== 0) {
  10041. //table.op[next + huff] = 64; /* invalid code marker */
  10042. //table.bits[next + huff] = len - drop;
  10043. //table.val[next + huff] = 0;
  10044. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  10045. }
  10046.  
  10047. /* set return parameters */
  10048. //opts.table_index += used;
  10049. opts.bits = root;
  10050. return 0;
  10051. };
  10052.  
  10053. },{"../utils/common":41}],51:[function(require,module,exports){
  10054. 'use strict';
  10055.  
  10056. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10057. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10058. //
  10059. // This software is provided 'as-is', without any express or implied
  10060. // warranty. In no event will the authors be held liable for any damages
  10061. // arising from the use of this software.
  10062. //
  10063. // Permission is granted to anyone to use this software for any purpose,
  10064. // including commercial applications, and to alter it and redistribute it
  10065. // freely, subject to the following restrictions:
  10066. //
  10067. // 1. The origin of this software must not be misrepresented; you must not
  10068. // claim that you wrote the original software. If you use this software
  10069. // in a product, an acknowledgment in the product documentation would be
  10070. // appreciated but is not required.
  10071. // 2. Altered source versions must be plainly marked as such, and must not be
  10072. // misrepresented as being the original software.
  10073. // 3. This notice may not be removed or altered from any source distribution.
  10074.  
  10075. module.exports = {
  10076. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  10077. 1: 'stream end', /* Z_STREAM_END 1 */
  10078. 0: '', /* Z_OK 0 */
  10079. '-1': 'file error', /* Z_ERRNO (-1) */
  10080. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  10081. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  10082. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  10083. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  10084. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  10085. };
  10086.  
  10087. },{}],52:[function(require,module,exports){
  10088. 'use strict';
  10089.  
  10090. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10091. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10092. //
  10093. // This software is provided 'as-is', without any express or implied
  10094. // warranty. In no event will the authors be held liable for any damages
  10095. // arising from the use of this software.
  10096. //
  10097. // Permission is granted to anyone to use this software for any purpose,
  10098. // including commercial applications, and to alter it and redistribute it
  10099. // freely, subject to the following restrictions:
  10100. //
  10101. // 1. The origin of this software must not be misrepresented; you must not
  10102. // claim that you wrote the original software. If you use this software
  10103. // in a product, an acknowledgment in the product documentation would be
  10104. // appreciated but is not required.
  10105. // 2. Altered source versions must be plainly marked as such, and must not be
  10106. // misrepresented as being the original software.
  10107. // 3. This notice may not be removed or altered from any source distribution.
  10108.  
  10109. var utils = require('../utils/common');
  10110.  
  10111. /* Public constants ==========================================================*/
  10112. /* ===========================================================================*/
  10113.  
  10114.  
  10115. //var Z_FILTERED = 1;
  10116. //var Z_HUFFMAN_ONLY = 2;
  10117. //var Z_RLE = 3;
  10118. var Z_FIXED = 4;
  10119. //var Z_DEFAULT_STRATEGY = 0;
  10120.  
  10121. /* Possible values of the data_type field (though see inflate()) */
  10122. var Z_BINARY = 0;
  10123. var Z_TEXT = 1;
  10124. //var Z_ASCII = 1; // = Z_TEXT
  10125. var Z_UNKNOWN = 2;
  10126.  
  10127. /*============================================================================*/
  10128.  
  10129.  
  10130. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  10131.  
  10132. // From zutil.h
  10133.  
  10134. var STORED_BLOCK = 0;
  10135. var STATIC_TREES = 1;
  10136. var DYN_TREES = 2;
  10137. /* The three kinds of block type */
  10138.  
  10139. var MIN_MATCH = 3;
  10140. var MAX_MATCH = 258;
  10141. /* The minimum and maximum match lengths */
  10142.  
  10143. // From deflate.h
  10144. /* ===========================================================================
  10145. * Internal compression state.
  10146. */
  10147.  
  10148. var LENGTH_CODES = 29;
  10149. /* number of length codes, not counting the special END_BLOCK code */
  10150.  
  10151. var LITERALS = 256;
  10152. /* number of literal bytes 0..255 */
  10153.  
  10154. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  10155. /* number of Literal or Length codes, including the END_BLOCK code */
  10156.  
  10157. var D_CODES = 30;
  10158. /* number of distance codes */
  10159.  
  10160. var BL_CODES = 19;
  10161. /* number of codes used to transfer the bit lengths */
  10162.  
  10163. var HEAP_SIZE = 2 * L_CODES + 1;
  10164. /* maximum heap size */
  10165.  
  10166. var MAX_BITS = 15;
  10167. /* All codes must not exceed MAX_BITS bits */
  10168.  
  10169. var Buf_size = 16;
  10170. /* size of bit buffer in bi_buf */
  10171.  
  10172.  
  10173. /* ===========================================================================
  10174. * Constants
  10175. */
  10176.  
  10177. var MAX_BL_BITS = 7;
  10178. /* Bit length codes must not exceed MAX_BL_BITS bits */
  10179.  
  10180. var END_BLOCK = 256;
  10181. /* end of block literal code */
  10182.  
  10183. var REP_3_6 = 16;
  10184. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  10185.  
  10186. var REPZ_3_10 = 17;
  10187. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  10188.  
  10189. var REPZ_11_138 = 18;
  10190. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  10191.  
  10192. /* eslint-disable comma-spacing,array-bracket-spacing */
  10193. var extra_lbits = /* extra bits for each length code */
  10194. [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];
  10195.  
  10196. var extra_dbits = /* extra bits for each distance code */
  10197. [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];
  10198.  
  10199. var extra_blbits = /* extra bits for each bit length code */
  10200. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  10201.  
  10202. var bl_order =
  10203. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  10204. /* eslint-enable comma-spacing,array-bracket-spacing */
  10205.  
  10206. /* The lengths of the bit length codes are sent in order of decreasing
  10207. * probability, to avoid transmitting the lengths for unused bit length codes.
  10208. */
  10209.  
  10210. /* ===========================================================================
  10211. * Local data. These are initialized only once.
  10212. */
  10213.  
  10214. // We pre-fill arrays with 0 to avoid uninitialized gaps
  10215.  
  10216. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  10217.  
  10218. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  10219. var static_ltree = new Array((L_CODES + 2) * 2);
  10220. zero(static_ltree);
  10221. /* The static literal tree. Since the bit lengths are imposed, there is no
  10222. * need for the L_CODES extra codes used during heap construction. However
  10223. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  10224. * below).
  10225. */
  10226.  
  10227. var static_dtree = new Array(D_CODES * 2);
  10228. zero(static_dtree);
  10229. /* The static distance tree. (Actually a trivial tree since all codes use
  10230. * 5 bits.)
  10231. */
  10232.  
  10233. var _dist_code = new Array(DIST_CODE_LEN);
  10234. zero(_dist_code);
  10235. /* Distance codes. The first 256 values correspond to the distances
  10236. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  10237. * the 15 bit distances.
  10238. */
  10239.  
  10240. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  10241. zero(_length_code);
  10242. /* length code for each normalized match length (0 == MIN_MATCH) */
  10243.  
  10244. var base_length = new Array(LENGTH_CODES);
  10245. zero(base_length);
  10246. /* First normalized length for each code (0 = MIN_MATCH) */
  10247.  
  10248. var base_dist = new Array(D_CODES);
  10249. zero(base_dist);
  10250. /* First normalized distance for each code (0 = distance of 1) */
  10251.  
  10252.  
  10253. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  10254.  
  10255. this.static_tree = static_tree; /* static tree or NULL */
  10256. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  10257. this.extra_base = extra_base; /* base index for extra_bits */
  10258. this.elems = elems; /* max number of elements in the tree */
  10259. this.max_length = max_length; /* max bit length for the codes */
  10260.  
  10261. // show if `static_tree` has data or dummy - needed for monomorphic objects
  10262. this.has_stree = static_tree && static_tree.length;
  10263. }
  10264.  
  10265.  
  10266. var static_l_desc;
  10267. var static_d_desc;
  10268. var static_bl_desc;
  10269.  
  10270.  
  10271. function TreeDesc(dyn_tree, stat_desc) {
  10272. this.dyn_tree = dyn_tree; /* the dynamic tree */
  10273. this.max_code = 0; /* largest code with non zero frequency */
  10274. this.stat_desc = stat_desc; /* the corresponding static tree */
  10275. }
  10276.  
  10277.  
  10278.  
  10279. function d_code(dist) {
  10280. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  10281. }
  10282.  
  10283.  
  10284. /* ===========================================================================
  10285. * Output a short LSB first on the stream.
  10286. * IN assertion: there is enough room in pendingBuf.
  10287. */
  10288. function put_short(s, w) {
  10289. // put_byte(s, (uch)((w) & 0xff));
  10290. // put_byte(s, (uch)((ush)(w) >> 8));
  10291. s.pending_buf[s.pending++] = (w) & 0xff;
  10292. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  10293. }
  10294.  
  10295.  
  10296. /* ===========================================================================
  10297. * Send a value on a given number of bits.
  10298. * IN assertion: length <= 16 and value fits in length bits.
  10299. */
  10300. function send_bits(s, value, length) {
  10301. if (s.bi_valid > (Buf_size - length)) {
  10302. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10303. put_short(s, s.bi_buf);
  10304. s.bi_buf = value >> (Buf_size - s.bi_valid);
  10305. s.bi_valid += length - Buf_size;
  10306. } else {
  10307. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10308. s.bi_valid += length;
  10309. }
  10310. }
  10311.  
  10312.  
  10313. function send_code(s, c, tree) {
  10314. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  10315. }
  10316.  
  10317.  
  10318. /* ===========================================================================
  10319. * Reverse the first len bits of a code, using straightforward code (a faster
  10320. * method would use a table)
  10321. * IN assertion: 1 <= len <= 15
  10322. */
  10323. function bi_reverse(code, len) {
  10324. var res = 0;
  10325. do {
  10326. res |= code & 1;
  10327. code >>>= 1;
  10328. res <<= 1;
  10329. } while (--len > 0);
  10330. return res >>> 1;
  10331. }
  10332.  
  10333.  
  10334. /* ===========================================================================
  10335. * Flush the bit buffer, keeping at most 7 bits in it.
  10336. */
  10337. function bi_flush(s) {
  10338. if (s.bi_valid === 16) {
  10339. put_short(s, s.bi_buf);
  10340. s.bi_buf = 0;
  10341. s.bi_valid = 0;
  10342.  
  10343. } else if (s.bi_valid >= 8) {
  10344. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  10345. s.bi_buf >>= 8;
  10346. s.bi_valid -= 8;
  10347. }
  10348. }
  10349.  
  10350.  
  10351. /* ===========================================================================
  10352. * Compute the optimal bit lengths for a tree and update the total bit length
  10353. * for the current block.
  10354. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  10355. * above are the tree nodes sorted by increasing frequency.
  10356. * OUT assertions: the field len is set to the optimal bit length, the
  10357. * array bl_count contains the frequencies for each bit length.
  10358. * The length opt_len is updated; static_len is also updated if stree is
  10359. * not null.
  10360. */
  10361. function gen_bitlen(s, desc)
  10362. // deflate_state *s;
  10363. // tree_desc *desc; /* the tree descriptor */
  10364. {
  10365. var tree = desc.dyn_tree;
  10366. var max_code = desc.max_code;
  10367. var stree = desc.stat_desc.static_tree;
  10368. var has_stree = desc.stat_desc.has_stree;
  10369. var extra = desc.stat_desc.extra_bits;
  10370. var base = desc.stat_desc.extra_base;
  10371. var max_length = desc.stat_desc.max_length;
  10372. var h; /* heap index */
  10373. var n, m; /* iterate over the tree elements */
  10374. var bits; /* bit length */
  10375. var xbits; /* extra bits */
  10376. var f; /* frequency */
  10377. var overflow = 0; /* number of elements with bit length too large */
  10378.  
  10379. for (bits = 0; bits <= MAX_BITS; bits++) {
  10380. s.bl_count[bits] = 0;
  10381. }
  10382.  
  10383. /* In a first pass, compute the optimal bit lengths (which may
  10384. * overflow in the case of the bit length tree).
  10385. */
  10386. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  10387.  
  10388. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  10389. n = s.heap[h];
  10390. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  10391. if (bits > max_length) {
  10392. bits = max_length;
  10393. overflow++;
  10394. }
  10395. tree[n * 2 + 1]/*.Len*/ = bits;
  10396. /* We overwrite tree[n].Dad which is no longer needed */
  10397.  
  10398. if (n > max_code) { continue; } /* not a leaf node */
  10399.  
  10400. s.bl_count[bits]++;
  10401. xbits = 0;
  10402. if (n >= base) {
  10403. xbits = extra[n - base];
  10404. }
  10405. f = tree[n * 2]/*.Freq*/;
  10406. s.opt_len += f * (bits + xbits);
  10407. if (has_stree) {
  10408. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  10409. }
  10410. }
  10411. if (overflow === 0) { return; }
  10412.  
  10413. // Trace((stderr,"\nbit length overflow\n"));
  10414. /* This happens for example on obj2 and pic of the Calgary corpus */
  10415.  
  10416. /* Find the first bit length which could increase: */
  10417. do {
  10418. bits = max_length - 1;
  10419. while (s.bl_count[bits] === 0) { bits--; }
  10420. s.bl_count[bits]--; /* move one leaf down the tree */
  10421. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  10422. s.bl_count[max_length]--;
  10423. /* The brother of the overflow item also moves one step up,
  10424. * but this does not affect bl_count[max_length]
  10425. */
  10426. overflow -= 2;
  10427. } while (overflow > 0);
  10428.  
  10429. /* Now recompute all bit lengths, scanning in increasing frequency.
  10430. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  10431. * lengths instead of fixing only the wrong ones. This idea is taken
  10432. * from 'ar' written by Haruhiko Okumura.)
  10433. */
  10434. for (bits = max_length; bits !== 0; bits--) {
  10435. n = s.bl_count[bits];
  10436. while (n !== 0) {
  10437. m = s.heap[--h];
  10438. if (m > max_code) { continue; }
  10439. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  10440. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  10441. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  10442. tree[m * 2 + 1]/*.Len*/ = bits;
  10443. }
  10444. n--;
  10445. }
  10446. }
  10447. }
  10448.  
  10449.  
  10450. /* ===========================================================================
  10451. * Generate the codes for a given tree and bit counts (which need not be
  10452. * optimal).
  10453. * IN assertion: the array bl_count contains the bit length statistics for
  10454. * the given tree and the field len is set for all tree elements.
  10455. * OUT assertion: the field code is set for all tree elements of non
  10456. * zero code length.
  10457. */
  10458. function gen_codes(tree, max_code, bl_count)
  10459. // ct_data *tree; /* the tree to decorate */
  10460. // int max_code; /* largest code with non zero frequency */
  10461. // ushf *bl_count; /* number of codes at each bit length */
  10462. {
  10463. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  10464. var code = 0; /* running code value */
  10465. var bits; /* bit index */
  10466. var n; /* code index */
  10467.  
  10468. /* The distribution counts are first used to generate the code values
  10469. * without bit reversal.
  10470. */
  10471. for (bits = 1; bits <= MAX_BITS; bits++) {
  10472. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  10473. }
  10474. /* Check that the bit counts in bl_count are consistent. The last code
  10475. * must be all ones.
  10476. */
  10477. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  10478. // "inconsistent bit counts");
  10479. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  10480.  
  10481. for (n = 0; n <= max_code; n++) {
  10482. var len = tree[n * 2 + 1]/*.Len*/;
  10483. if (len === 0) { continue; }
  10484. /* Now reverse the bits */
  10485. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  10486.  
  10487. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  10488. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  10489. }
  10490. }
  10491.  
  10492.  
  10493. /* ===========================================================================
  10494. * Initialize the various 'constant' tables.
  10495. */
  10496. function tr_static_init() {
  10497. var n; /* iterates over tree elements */
  10498. var bits; /* bit counter */
  10499. var length; /* length value */
  10500. var code; /* code value */
  10501. var dist; /* distance index */
  10502. var bl_count = new Array(MAX_BITS + 1);
  10503. /* number of codes at each bit length for an optimal tree */
  10504.  
  10505. // do check in _tr_init()
  10506. //if (static_init_done) return;
  10507.  
  10508. /* For some embedded targets, global variables are not initialized: */
  10509. /*#ifdef NO_INIT_GLOBAL_POINTERS
  10510. static_l_desc.static_tree = static_ltree;
  10511. static_l_desc.extra_bits = extra_lbits;
  10512. static_d_desc.static_tree = static_dtree;
  10513. static_d_desc.extra_bits = extra_dbits;
  10514. static_bl_desc.extra_bits = extra_blbits;
  10515. #endif*/
  10516.  
  10517. /* Initialize the mapping length (0..255) -> length code (0..28) */
  10518. length = 0;
  10519. for (code = 0; code < LENGTH_CODES - 1; code++) {
  10520. base_length[code] = length;
  10521. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  10522. _length_code[length++] = code;
  10523. }
  10524. }
  10525. //Assert (length == 256, "tr_static_init: length != 256");
  10526. /* Note that the length 255 (match length 258) can be represented
  10527. * in two different ways: code 284 + 5 bits or code 285, so we
  10528. * overwrite length_code[255] to use the best encoding:
  10529. */
  10530. _length_code[length - 1] = code;
  10531.  
  10532. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  10533. dist = 0;
  10534. for (code = 0; code < 16; code++) {
  10535. base_dist[code] = dist;
  10536. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  10537. _dist_code[dist++] = code;
  10538. }
  10539. }
  10540. //Assert (dist == 256, "tr_static_init: dist != 256");
  10541. dist >>= 7; /* from now on, all distances are divided by 128 */
  10542. for (; code < D_CODES; code++) {
  10543. base_dist[code] = dist << 7;
  10544. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  10545. _dist_code[256 + dist++] = code;
  10546. }
  10547. }
  10548. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  10549.  
  10550. /* Construct the codes of the static literal tree */
  10551. for (bits = 0; bits <= MAX_BITS; bits++) {
  10552. bl_count[bits] = 0;
  10553. }
  10554.  
  10555. n = 0;
  10556. while (n <= 143) {
  10557. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10558. n++;
  10559. bl_count[8]++;
  10560. }
  10561. while (n <= 255) {
  10562. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  10563. n++;
  10564. bl_count[9]++;
  10565. }
  10566. while (n <= 279) {
  10567. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  10568. n++;
  10569. bl_count[7]++;
  10570. }
  10571. while (n <= 287) {
  10572. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10573. n++;
  10574. bl_count[8]++;
  10575. }
  10576. /* Codes 286 and 287 do not exist, but we must include them in the
  10577. * tree construction to get a canonical Huffman tree (longest code
  10578. * all ones)
  10579. */
  10580. gen_codes(static_ltree, L_CODES + 1, bl_count);
  10581.  
  10582. /* The static distance tree is trivial: */
  10583. for (n = 0; n < D_CODES; n++) {
  10584. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  10585. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  10586. }
  10587.  
  10588. // Now data ready and we can init static trees
  10589. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  10590. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  10591. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  10592.  
  10593. //static_init_done = true;
  10594. }
  10595.  
  10596.  
  10597. /* ===========================================================================
  10598. * Initialize a new block.
  10599. */
  10600. function init_block(s) {
  10601. var n; /* iterates over tree elements */
  10602.  
  10603. /* Initialize the trees. */
  10604. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  10605. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  10606. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  10607.  
  10608. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  10609. s.opt_len = s.static_len = 0;
  10610. s.last_lit = s.matches = 0;
  10611. }
  10612.  
  10613.  
  10614. /* ===========================================================================
  10615. * Flush the bit buffer and align the output on a byte boundary
  10616. */
  10617. function bi_windup(s)
  10618. {
  10619. if (s.bi_valid > 8) {
  10620. put_short(s, s.bi_buf);
  10621. } else if (s.bi_valid > 0) {
  10622. //put_byte(s, (Byte)s->bi_buf);
  10623. s.pending_buf[s.pending++] = s.bi_buf;
  10624. }
  10625. s.bi_buf = 0;
  10626. s.bi_valid = 0;
  10627. }
  10628.  
  10629. /* ===========================================================================
  10630. * Copy a stored block, storing first the length and its
  10631. * one's complement if requested.
  10632. */
  10633. function copy_block(s, buf, len, header)
  10634. //DeflateState *s;
  10635. //charf *buf; /* the input data */
  10636. //unsigned len; /* its length */
  10637. //int header; /* true if block header must be written */
  10638. {
  10639. bi_windup(s); /* align on byte boundary */
  10640.  
  10641. if (header) {
  10642. put_short(s, len);
  10643. put_short(s, ~len);
  10644. }
  10645. // while (len--) {
  10646. // put_byte(s, *buf++);
  10647. // }
  10648. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  10649. s.pending += len;
  10650. }
  10651.  
  10652. /* ===========================================================================
  10653. * Compares to subtrees, using the tree depth as tie breaker when
  10654. * the subtrees have equal frequency. This minimizes the worst case length.
  10655. */
  10656. function smaller(tree, n, m, depth) {
  10657. var _n2 = n * 2;
  10658. var _m2 = m * 2;
  10659. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  10660. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  10661. }
  10662.  
  10663. /* ===========================================================================
  10664. * Restore the heap property by moving down the tree starting at node k,
  10665. * exchanging a node with the smallest of its two sons if necessary, stopping
  10666. * when the heap property is re-established (each father smaller than its
  10667. * two sons).
  10668. */
  10669. function pqdownheap(s, tree, k)
  10670. // deflate_state *s;
  10671. // ct_data *tree; /* the tree to restore */
  10672. // int k; /* node to move down */
  10673. {
  10674. var v = s.heap[k];
  10675. var j = k << 1; /* left son of k */
  10676. while (j <= s.heap_len) {
  10677. /* Set j to the smallest of the two sons: */
  10678. if (j < s.heap_len &&
  10679. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  10680. j++;
  10681. }
  10682. /* Exit if v is smaller than both sons */
  10683. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  10684.  
  10685. /* Exchange v with the smallest son */
  10686. s.heap[k] = s.heap[j];
  10687. k = j;
  10688.  
  10689. /* And continue down the tree, setting j to the left son of k */
  10690. j <<= 1;
  10691. }
  10692. s.heap[k] = v;
  10693. }
  10694.  
  10695.  
  10696. // inlined manually
  10697. // var SMALLEST = 1;
  10698.  
  10699. /* ===========================================================================
  10700. * Send the block data compressed using the given Huffman trees
  10701. */
  10702. function compress_block(s, ltree, dtree)
  10703. // deflate_state *s;
  10704. // const ct_data *ltree; /* literal tree */
  10705. // const ct_data *dtree; /* distance tree */
  10706. {
  10707. var dist; /* distance of matched string */
  10708. var lc; /* match length or unmatched char (if dist == 0) */
  10709. var lx = 0; /* running index in l_buf */
  10710. var code; /* the code to send */
  10711. var extra; /* number of extra bits to send */
  10712.  
  10713. if (s.last_lit !== 0) {
  10714. do {
  10715. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  10716. lc = s.pending_buf[s.l_buf + lx];
  10717. lx++;
  10718.  
  10719. if (dist === 0) {
  10720. send_code(s, lc, ltree); /* send a literal byte */
  10721. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  10722. } else {
  10723. /* Here, lc is the match length - MIN_MATCH */
  10724. code = _length_code[lc];
  10725. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  10726. extra = extra_lbits[code];
  10727. if (extra !== 0) {
  10728. lc -= base_length[code];
  10729. send_bits(s, lc, extra); /* send the extra length bits */
  10730. }
  10731. dist--; /* dist is now the match distance - 1 */
  10732. code = d_code(dist);
  10733. //Assert (code < D_CODES, "bad d_code");
  10734.  
  10735. send_code(s, code, dtree); /* send the distance code */
  10736. extra = extra_dbits[code];
  10737. if (extra !== 0) {
  10738. dist -= base_dist[code];
  10739. send_bits(s, dist, extra); /* send the extra distance bits */
  10740. }
  10741. } /* literal or match pair ? */
  10742.  
  10743. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  10744. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  10745. // "pendingBuf overflow");
  10746.  
  10747. } while (lx < s.last_lit);
  10748. }
  10749.  
  10750. send_code(s, END_BLOCK, ltree);
  10751. }
  10752.  
  10753.  
  10754. /* ===========================================================================
  10755. * Construct one Huffman tree and assigns the code bit strings and lengths.
  10756. * Update the total bit length for the current block.
  10757. * IN assertion: the field freq is set for all tree elements.
  10758. * OUT assertions: the fields len and code are set to the optimal bit length
  10759. * and corresponding code. The length opt_len is updated; static_len is
  10760. * also updated if stree is not null. The field max_code is set.
  10761. */
  10762. function build_tree(s, desc)
  10763. // deflate_state *s;
  10764. // tree_desc *desc; /* the tree descriptor */
  10765. {
  10766. var tree = desc.dyn_tree;
  10767. var stree = desc.stat_desc.static_tree;
  10768. var has_stree = desc.stat_desc.has_stree;
  10769. var elems = desc.stat_desc.elems;
  10770. var n, m; /* iterate over heap elements */
  10771. var max_code = -1; /* largest code with non zero frequency */
  10772. var node; /* new node being created */
  10773.  
  10774. /* Construct the initial heap, with least frequent element in
  10775. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  10776. * heap[0] is not used.
  10777. */
  10778. s.heap_len = 0;
  10779. s.heap_max = HEAP_SIZE;
  10780.  
  10781. for (n = 0; n < elems; n++) {
  10782. if (tree[n * 2]/*.Freq*/ !== 0) {
  10783. s.heap[++s.heap_len] = max_code = n;
  10784. s.depth[n] = 0;
  10785.  
  10786. } else {
  10787. tree[n * 2 + 1]/*.Len*/ = 0;
  10788. }
  10789. }
  10790.  
  10791. /* The pkzip format requires that at least one distance code exists,
  10792. * and that at least one bit should be sent even if there is only one
  10793. * possible code. So to avoid special checks later on we force at least
  10794. * two codes of non zero frequency.
  10795. */
  10796. while (s.heap_len < 2) {
  10797. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  10798. tree[node * 2]/*.Freq*/ = 1;
  10799. s.depth[node] = 0;
  10800. s.opt_len--;
  10801.  
  10802. if (has_stree) {
  10803. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  10804. }
  10805. /* node is 0 or 1 so it does not have extra bits */
  10806. }
  10807. desc.max_code = max_code;
  10808.  
  10809. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  10810. * establish sub-heaps of increasing lengths:
  10811. */
  10812. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  10813.  
  10814. /* Construct the Huffman tree by repeatedly combining the least two
  10815. * frequent nodes.
  10816. */
  10817. node = elems; /* next internal node of the tree */
  10818. do {
  10819. //pqremove(s, tree, n); /* n = node of least frequency */
  10820. /*** pqremove ***/
  10821. n = s.heap[1/*SMALLEST*/];
  10822. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  10823. pqdownheap(s, tree, 1/*SMALLEST*/);
  10824. /***/
  10825.  
  10826. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  10827.  
  10828. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  10829. s.heap[--s.heap_max] = m;
  10830.  
  10831. /* Create a new node father of n and m */
  10832. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  10833. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  10834. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  10835.  
  10836. /* and insert the new node in the heap */
  10837. s.heap[1/*SMALLEST*/] = node++;
  10838. pqdownheap(s, tree, 1/*SMALLEST*/);
  10839.  
  10840. } while (s.heap_len >= 2);
  10841.  
  10842. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  10843.  
  10844. /* At this point, the fields freq and dad are set. We can now
  10845. * generate the bit lengths.
  10846. */
  10847. gen_bitlen(s, desc);
  10848.  
  10849. /* The field len is now set, we can generate the bit codes */
  10850. gen_codes(tree, max_code, s.bl_count);
  10851. }
  10852.  
  10853.  
  10854. /* ===========================================================================
  10855. * Scan a literal or distance tree to determine the frequencies of the codes
  10856. * in the bit length tree.
  10857. */
  10858. function scan_tree(s, tree, max_code)
  10859. // deflate_state *s;
  10860. // ct_data *tree; /* the tree to be scanned */
  10861. // int max_code; /* and its largest code of non zero frequency */
  10862. {
  10863. var n; /* iterates over all tree elements */
  10864. var prevlen = -1; /* last emitted length */
  10865. var curlen; /* length of current code */
  10866.  
  10867. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  10868.  
  10869. var count = 0; /* repeat count of the current code */
  10870. var max_count = 7; /* max repeat count */
  10871. var min_count = 4; /* min repeat count */
  10872.  
  10873. if (nextlen === 0) {
  10874. max_count = 138;
  10875. min_count = 3;
  10876. }
  10877. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  10878.  
  10879. for (n = 0; n <= max_code; n++) {
  10880. curlen = nextlen;
  10881. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  10882.  
  10883. if (++count < max_count && curlen === nextlen) {
  10884. continue;
  10885.  
  10886. } else if (count < min_count) {
  10887. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  10888.  
  10889. } else if (curlen !== 0) {
  10890.  
  10891. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  10892. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  10893.  
  10894. } else if (count <= 10) {
  10895. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  10896.  
  10897. } else {
  10898. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  10899. }
  10900.  
  10901. count = 0;
  10902. prevlen = curlen;
  10903.  
  10904. if (nextlen === 0) {
  10905. max_count = 138;
  10906. min_count = 3;
  10907.  
  10908. } else if (curlen === nextlen) {
  10909. max_count = 6;
  10910. min_count = 3;
  10911.  
  10912. } else {
  10913. max_count = 7;
  10914. min_count = 4;
  10915. }
  10916. }
  10917. }
  10918.  
  10919.  
  10920. /* ===========================================================================
  10921. * Send a literal or distance tree in compressed form, using the codes in
  10922. * bl_tree.
  10923. */
  10924. function send_tree(s, tree, max_code)
  10925. // deflate_state *s;
  10926. // ct_data *tree; /* the tree to be scanned */
  10927. // int max_code; /* and its largest code of non zero frequency */
  10928. {
  10929. var n; /* iterates over all tree elements */
  10930. var prevlen = -1; /* last emitted length */
  10931. var curlen; /* length of current code */
  10932.  
  10933. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  10934.  
  10935. var count = 0; /* repeat count of the current code */
  10936. var max_count = 7; /* max repeat count */
  10937. var min_count = 4; /* min repeat count */
  10938.  
  10939. /* tree[max_code+1].Len = -1; */ /* guard already set */
  10940. if (nextlen === 0) {
  10941. max_count = 138;
  10942. min_count = 3;
  10943. }
  10944.  
  10945. for (n = 0; n <= max_code; n++) {
  10946. curlen = nextlen;
  10947. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  10948.  
  10949. if (++count < max_count && curlen === nextlen) {
  10950. continue;
  10951.  
  10952. } else if (count < min_count) {
  10953. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  10954.  
  10955. } else if (curlen !== 0) {
  10956. if (curlen !== prevlen) {
  10957. send_code(s, curlen, s.bl_tree);
  10958. count--;
  10959. }
  10960. //Assert(count >= 3 && count <= 6, " 3_6?");
  10961. send_code(s, REP_3_6, s.bl_tree);
  10962. send_bits(s, count - 3, 2);
  10963.  
  10964. } else if (count <= 10) {
  10965. send_code(s, REPZ_3_10, s.bl_tree);
  10966. send_bits(s, count - 3, 3);
  10967.  
  10968. } else {
  10969. send_code(s, REPZ_11_138, s.bl_tree);
  10970. send_bits(s, count - 11, 7);
  10971. }
  10972.  
  10973. count = 0;
  10974. prevlen = curlen;
  10975. if (nextlen === 0) {
  10976. max_count = 138;
  10977. min_count = 3;
  10978.  
  10979. } else if (curlen === nextlen) {
  10980. max_count = 6;
  10981. min_count = 3;
  10982.  
  10983. } else {
  10984. max_count = 7;
  10985. min_count = 4;
  10986. }
  10987. }
  10988. }
  10989.  
  10990.  
  10991. /* ===========================================================================
  10992. * Construct the Huffman tree for the bit lengths and return the index in
  10993. * bl_order of the last bit length code to send.
  10994. */
  10995. function build_bl_tree(s) {
  10996. var max_blindex; /* index of last bit length code of non zero freq */
  10997.  
  10998. /* Determine the bit length frequencies for literal and distance trees */
  10999. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  11000. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  11001.  
  11002. /* Build the bit length tree: */
  11003. build_tree(s, s.bl_desc);
  11004. /* opt_len now includes the length of the tree representations, except
  11005. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  11006. */
  11007.  
  11008. /* Determine the number of bit length codes to send. The pkzip format
  11009. * requires that at least 4 bit length codes be sent. (appnote.txt says
  11010. * 3 but the actual value used is 4.)
  11011. */
  11012. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  11013. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  11014. break;
  11015. }
  11016. }
  11017. /* Update opt_len to include the bit length tree and counts */
  11018. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  11019. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  11020. // s->opt_len, s->static_len));
  11021.  
  11022. return max_blindex;
  11023. }
  11024.  
  11025.  
  11026. /* ===========================================================================
  11027. * Send the header for a block using dynamic Huffman trees: the counts, the
  11028. * lengths of the bit length codes, the literal tree and the distance tree.
  11029. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  11030. */
  11031. function send_all_trees(s, lcodes, dcodes, blcodes)
  11032. // deflate_state *s;
  11033. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  11034. {
  11035. var rank; /* index in bl_order */
  11036.  
  11037. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  11038. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  11039. // "too many codes");
  11040. //Tracev((stderr, "\nbl counts: "));
  11041. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  11042. send_bits(s, dcodes - 1, 5);
  11043. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  11044. for (rank = 0; rank < blcodes; rank++) {
  11045. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  11046. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  11047. }
  11048. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  11049.  
  11050. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  11051. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  11052.  
  11053. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  11054. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  11055. }
  11056.  
  11057.  
  11058. /* ===========================================================================
  11059. * Check if the data type is TEXT or BINARY, using the following algorithm:
  11060. * - TEXT if the two conditions below are satisfied:
  11061. * a) There are no non-portable control characters belonging to the
  11062. * "black list" (0..6, 14..25, 28..31).
  11063. * b) There is at least one printable character belonging to the
  11064. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  11065. * - BINARY otherwise.
  11066. * - The following partially-portable control characters form a
  11067. * "gray list" that is ignored in this detection algorithm:
  11068. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  11069. * IN assertion: the fields Freq of dyn_ltree are set.
  11070. */
  11071. function detect_data_type(s) {
  11072. /* black_mask is the bit mask of black-listed bytes
  11073. * set bits 0..6, 14..25, and 28..31
  11074. * 0xf3ffc07f = binary 11110011111111111100000001111111
  11075. */
  11076. var black_mask = 0xf3ffc07f;
  11077. var n;
  11078.  
  11079. /* Check for non-textual ("black-listed") bytes. */
  11080. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  11081. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  11082. return Z_BINARY;
  11083. }
  11084. }
  11085.  
  11086. /* Check for textual ("white-listed") bytes. */
  11087. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  11088. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  11089. return Z_TEXT;
  11090. }
  11091. for (n = 32; n < LITERALS; n++) {
  11092. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  11093. return Z_TEXT;
  11094. }
  11095. }
  11096.  
  11097. /* There are no "black-listed" or "white-listed" bytes:
  11098. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  11099. */
  11100. return Z_BINARY;
  11101. }
  11102.  
  11103.  
  11104. var static_init_done = false;
  11105.  
  11106. /* ===========================================================================
  11107. * Initialize the tree data structures for a new zlib stream.
  11108. */
  11109. function _tr_init(s)
  11110. {
  11111.  
  11112. if (!static_init_done) {
  11113. tr_static_init();
  11114. static_init_done = true;
  11115. }
  11116.  
  11117. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  11118. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  11119. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  11120.  
  11121. s.bi_buf = 0;
  11122. s.bi_valid = 0;
  11123.  
  11124. /* Initialize the first block of the first file: */
  11125. init_block(s);
  11126. }
  11127.  
  11128.  
  11129. /* ===========================================================================
  11130. * Send a stored block
  11131. */
  11132. function _tr_stored_block(s, buf, stored_len, last)
  11133. //DeflateState *s;
  11134. //charf *buf; /* input block */
  11135. //ulg stored_len; /* length of input block */
  11136. //int last; /* one if this is the last block for a file */
  11137. {
  11138. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  11139. copy_block(s, buf, stored_len, true); /* with header */
  11140. }
  11141.  
  11142.  
  11143. /* ===========================================================================
  11144. * Send one empty static block to give enough lookahead for inflate.
  11145. * This takes 10 bits, of which 7 may remain in the bit buffer.
  11146. */
  11147. function _tr_align(s) {
  11148. send_bits(s, STATIC_TREES << 1, 3);
  11149. send_code(s, END_BLOCK, static_ltree);
  11150. bi_flush(s);
  11151. }
  11152.  
  11153.  
  11154. /* ===========================================================================
  11155. * Determine the best encoding for the current block: dynamic trees, static
  11156. * trees or store, and output the encoded block to the zip file.
  11157. */
  11158. function _tr_flush_block(s, buf, stored_len, last)
  11159. //DeflateState *s;
  11160. //charf *buf; /* input block, or NULL if too old */
  11161. //ulg stored_len; /* length of input block */
  11162. //int last; /* one if this is the last block for a file */
  11163. {
  11164. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  11165. var max_blindex = 0; /* index of last bit length code of non zero freq */
  11166.  
  11167. /* Build the Huffman trees unless a stored block is forced */
  11168. if (s.level > 0) {
  11169.  
  11170. /* Check if the file is binary or text */
  11171. if (s.strm.data_type === Z_UNKNOWN) {
  11172. s.strm.data_type = detect_data_type(s);
  11173. }
  11174.  
  11175. /* Construct the literal and distance trees */
  11176. build_tree(s, s.l_desc);
  11177. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  11178. // s->static_len));
  11179.  
  11180. build_tree(s, s.d_desc);
  11181. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  11182. // s->static_len));
  11183. /* At this point, opt_len and static_len are the total bit lengths of
  11184. * the compressed block data, excluding the tree representations.
  11185. */
  11186.  
  11187. /* Build the bit length tree for the above two trees, and get the index
  11188. * in bl_order of the last bit length code to send.
  11189. */
  11190. max_blindex = build_bl_tree(s);
  11191.  
  11192. /* Determine the best encoding. Compute the block lengths in bytes. */
  11193. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  11194. static_lenb = (s.static_len + 3 + 7) >>> 3;
  11195.  
  11196. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  11197. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  11198. // s->last_lit));
  11199.  
  11200. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  11201.  
  11202. } else {
  11203. // Assert(buf != (char*)0, "lost buf");
  11204. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  11205. }
  11206.  
  11207. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  11208. /* 4: two words for the lengths */
  11209.  
  11210. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  11211. * Otherwise we can't have processed more than WSIZE input bytes since
  11212. * the last block flush, because compression would have been
  11213. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  11214. * transform a block into a stored block.
  11215. */
  11216. _tr_stored_block(s, buf, stored_len, last);
  11217.  
  11218. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  11219.  
  11220. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  11221. compress_block(s, static_ltree, static_dtree);
  11222.  
  11223. } else {
  11224. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  11225. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  11226. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  11227. }
  11228. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  11229. /* The above check is made mod 2^32, for files larger than 512 MB
  11230. * and uLong implemented on 32 bits.
  11231. */
  11232. init_block(s);
  11233.  
  11234. if (last) {
  11235. bi_windup(s);
  11236. }
  11237. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  11238. // s->compressed_len-7*last));
  11239. }
  11240.  
  11241. /* ===========================================================================
  11242. * Save the match info and tally the frequency counts. Return true if
  11243. * the current block must be flushed.
  11244. */
  11245. function _tr_tally(s, dist, lc)
  11246. // deflate_state *s;
  11247. // unsigned dist; /* distance of matched string */
  11248. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  11249. {
  11250. //var out_length, in_length, dcode;
  11251.  
  11252. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  11253. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  11254.  
  11255. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  11256. s.last_lit++;
  11257.  
  11258. if (dist === 0) {
  11259. /* lc is the unmatched char */
  11260. s.dyn_ltree[lc * 2]/*.Freq*/++;
  11261. } else {
  11262. s.matches++;
  11263. /* Here, lc is the match length - MIN_MATCH */
  11264. dist--; /* dist = match distance - 1 */
  11265. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  11266. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  11267. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  11268.  
  11269. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  11270. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  11271. }
  11272.  
  11273. // (!) This block is disabled in zlib defailts,
  11274. // don't enable it for binary compatibility
  11275.  
  11276. //#ifdef TRUNCATE_BLOCK
  11277. // /* Try to guess if it is profitable to stop the current block here */
  11278. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  11279. // /* Compute an upper bound for the compressed length */
  11280. // out_length = s.last_lit*8;
  11281. // in_length = s.strstart - s.block_start;
  11282. //
  11283. // for (dcode = 0; dcode < D_CODES; dcode++) {
  11284. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  11285. // }
  11286. // out_length >>>= 3;
  11287. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  11288. // // s->last_lit, in_length, out_length,
  11289. // // 100L - out_length*100L/in_length));
  11290. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  11291. // return true;
  11292. // }
  11293. // }
  11294. //#endif
  11295.  
  11296. return (s.last_lit === s.lit_bufsize - 1);
  11297. /* We avoid equality with lit_bufsize because of wraparound at 64K
  11298. * on 16 bit machines and because stored blocks are restricted to
  11299. * 64K-1 bytes.
  11300. */
  11301. }
  11302.  
  11303. exports._tr_init = _tr_init;
  11304. exports._tr_stored_block = _tr_stored_block;
  11305. exports._tr_flush_block = _tr_flush_block;
  11306. exports._tr_tally = _tr_tally;
  11307. exports._tr_align = _tr_align;
  11308.  
  11309. },{"../utils/common":41}],53:[function(require,module,exports){
  11310. 'use strict';
  11311.  
  11312. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  11313. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  11314. //
  11315. // This software is provided 'as-is', without any express or implied
  11316. // warranty. In no event will the authors be held liable for any damages
  11317. // arising from the use of this software.
  11318. //
  11319. // Permission is granted to anyone to use this software for any purpose,
  11320. // including commercial applications, and to alter it and redistribute it
  11321. // freely, subject to the following restrictions:
  11322. //
  11323. // 1. The origin of this software must not be misrepresented; you must not
  11324. // claim that you wrote the original software. If you use this software
  11325. // in a product, an acknowledgment in the product documentation would be
  11326. // appreciated but is not required.
  11327. // 2. Altered source versions must be plainly marked as such, and must not be
  11328. // misrepresented as being the original software.
  11329. // 3. This notice may not be removed or altered from any source distribution.
  11330.  
  11331. function ZStream() {
  11332. /* next input byte */
  11333. this.input = null; // JS specific, because we have no pointers
  11334. this.next_in = 0;
  11335. /* number of bytes available at input */
  11336. this.avail_in = 0;
  11337. /* total number of input bytes read so far */
  11338. this.total_in = 0;
  11339. /* next output byte should be put there */
  11340. this.output = null; // JS specific, because we have no pointers
  11341. this.next_out = 0;
  11342. /* remaining free space at output */
  11343. this.avail_out = 0;
  11344. /* total number of bytes output so far */
  11345. this.total_out = 0;
  11346. /* last error message, NULL if no error */
  11347. this.msg = ''/*Z_NULL*/;
  11348. /* not visible by applications */
  11349. this.state = null;
  11350. /* best guess about the data type: binary or text */
  11351. this.data_type = 2/*Z_UNKNOWN*/;
  11352. /* adler32 value of the uncompressed data */
  11353. this.adler = 0;
  11354. }
  11355.  
  11356. module.exports = ZStream;
  11357.  
  11358. },{}],54:[function(require,module,exports){
  11359. 'use strict';
  11360. module.exports = typeof setImmediate === 'function' ? setImmediate :
  11361. function setImmediate() {
  11362. var args = [].slice.apply(arguments);
  11363. args.splice(1, 0, 0);
  11364. setTimeout.apply(null, args);
  11365. };
  11366.  
  11367. },{}]},{},[10])(10)
  11368. });