Clip Studio Reader Downloader

Download books from the browser version of Clip Studio Reader

目前为 2024-06-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Clip Studio Reader Downloader
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.4
  5. // @description Download books from the browser version of Clip Studio Reader
  6. // @author mrcoconuat
  7. // @supportURL https://github.com/MrCocoNuat/clip-studio-reader-downloader/issues
  8. // @match *://*/*
  9. // @icon https://www.google.com/s2/favicons?sz=64&domain=mobilebook.jp
  10. // @license MIT
  11. // @grant none
  12. // ==/UserScript==
  13.  
  14. 'use strict';
  15.  
  16. // Site-blind Clip Studio Reader integration support:
  17. //------------------------------
  18.  
  19. const ELEMENT = {
  20. SCREEN_CONTROLLER:0, // used to flip pages
  21. CURRENT_PAGE_COUNTER:1, // duh
  22. TOTAL_PAGE_COUNTER:2, // duh
  23. LOADER_SPINNER:3, // used to detect if the reader is loading a page
  24. MENU:4, // used to detect if the menu must be raised since it contains the page scroller
  25. PAGE_SPREAD:5, // contains the actual pages
  26. DOWNLOAD_BUTTON_PARENT:6, // download button is injected into
  27. PAGE_SLIDER: 7 // duh
  28. }
  29.  
  30. // Data distribution for site-specific integrations:
  31. //------------------------------
  32.  
  33. const siteElementIds = {
  34. "mbj-bs.pf.mobilebook.jp": {
  35. [ELEMENT.SCREEN_CONTROLLER]: "screen_surface",
  36. [ELEMENT.CURRENT_PAGE_COUNTER]: "paging_slider_nombre_current",
  37. [ELEMENT.TOTAL_PAGE_COUNTER]: "paging_slider_nombre_total",
  38. [ELEMENT.LOADER_SPINNER]: "loading_spinner_layer",
  39. [ELEMENT.MENU]: "menu_layer",
  40. [ELEMENT.PAGE_SPREAD]: "spread_a",
  41. [ELEMENT.DOWNLOAD_BUTTON_PARENT]: "footer_down",
  42. [ELEMENT.PAGE_SLIDER]: "paging_slider",
  43. },
  44. "api.distribution.mediadotech.com": {
  45. [ELEMENT.SCREEN_CONTROLLER]: "screen_control_pad",
  46. [ELEMENT.CURRENT_PAGE_COUNTER]: "menu_nombre_current",
  47. [ELEMENT.TOTAL_PAGE_COUNTER]: "menu_nombre_total",
  48. [ELEMENT.LOADER_SPINNER]: "screen_loading_spinner_layer",
  49. [ELEMENT.MENU]: "menu_container",
  50. [ELEMENT.PAGE_SPREAD]: "screen_layer"
  51. },
  52. "comic-viewer.iowl.jp": {
  53. [ELEMENT.SCREEN_CONTROLLER]: "screen_control_pad",
  54. [ELEMENT.CURRENT_PAGE_COUNTER]: "menu_nombre_current",
  55. [ELEMENT.TOTAL_PAGE_COUNTER]: "menu_nombre_total",
  56. [ELEMENT.LOADER_SPINNER]: "screen_loading_spinner_layer",
  57. [ELEMENT.MENU]: "menu_footer",
  58. [ELEMENT.PAGE_SPREAD]: "screen_layer",
  59. }
  60. }
  61. // sometimes the necessary element does not have an id, which sucks
  62. const siteElementClasses = {
  63. "api.distribution.mediadotech.com": {
  64. [ELEMENT.DOWNLOAD_BUTTON_PARENT]: "menu-item-block",
  65. },
  66. "comic-viewer.iowl.jp": {
  67. [ELEMENT.DOWNLOAD_BUTTON_PARENT]: "menu-item-block",
  68. }
  69. }
  70.  
  71. const getCSRElement = (elementEnum) => {
  72. return document.getElementById(siteElementIds[window.location.hostname][elementEnum])
  73. ?? document.getElementsByClassName(siteElementClasses[window.location.hostname][elementEnum])[0];
  74. }
  75.  
  76.  
  77.  
  78. init();
  79.  
  80. // SVG Handling
  81. // Convert SVG to image (JPEG, PNG, etc.) in the browser
  82. // Thanks, Thom Kiesewetter
  83. // https://stackoverflow.com/a/58142441
  84. //------------------------------
  85.  
  86. const downloadSvg =`<svg width="800px" height="800px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  87. <defs>
  88. <path id="download-a" d="M4.29289322,1.70710678 C3.90236893,1.31658249 3.90236893,0.683417511 4.29289322,0.292893219 C4.68341751,-0.0976310729 5.31658249,-0.0976310729 5.70710678,0.292893219 L7.70710678,2.29289322 C8.09763107,2.68341751 8.09763107,3.31658249 7.70710678,3.70710678 C7.31658249,4.09763107 6.68341751,4.09763107 6.29289322,3.70710678 L4.29289322,1.70710678 Z M0,8 L16,8 L16,10 L0,10 L0,8 Z"/>
  89. <path id="download-c" d="M11,9.58578644 L13.2928932,7.29289322 C13.6834175,6.90236893 14.3165825,6.90236893 14.7071068,7.29289322 C15.0976311,7.68341751 15.0976311,8.31658249 14.7071068,8.70710678 L10.7071068,12.7071068 C10.3165825,13.0976311 9.68341751,13.0976311 9.29289322,12.7071068 L5.29289322,8.70710678 C4.90236893,8.31658249 4.90236893,7.68341751 5.29289322,7.29289322 C5.68341751,6.90236893 6.31658249,6.90236893 6.70710678,7.29289322 L9,9.58578644 L9,0.998529185 C9,0.447056744 9.44771525,-7.95978809e-15 10,-7.99360578e-15 C10.5522847,-8.02742346e-15 11,0.447056744 11,0.998529185 L11,9.58578644 Z M18,16 L18,10 C18,9.44771525 18.4477153,9 19,9 C19.5522847,9 20,9.44771525 20,10 L20,17 C20,17.5522847 19.5522847,18 19,18 L1,18 C0.44771525,18 0,17.5522847 0,17 L0,10 C0,9.44771525 0.44771525,9 1,9 C1.55228475,9 2,9.44771525 2,10 L2,16 L18,16 Z"/>
  90. </defs>
  91. <g fill="none" fill-rule="evenodd" transform="translate(2 3)">
  92. <g transform="translate(2 6)">
  93. <mask id="download-b" fill="#ffffff">
  94. <use xlink:href="#download-a"/>
  95. </mask>
  96. <use fill="#D8D8D8" fill-rule="nonzero" xlink:href="#download-a"/>
  97. <g fill="#FFA0A0" mask="url(#download-b)">
  98. <rect width="24" height="24" transform="translate(-4 -9)"/>
  99. </g>
  100. </g>
  101. <mask id="download-d" fill="#ffffff">
  102. <use xlink:href="#download-c"/>
  103. </mask>
  104. <use fill="#000000" fill-rule="nonzero" xlink:href="#download-c"/>
  105. <g fill="#7600FF" mask="url(#download-d)">
  106. <rect width="24" height="24" transform="translate(-2 -3)"/>
  107. </g>
  108. </g>
  109. </svg>`
  110.  
  111. function svgToPng(svg, callback) {
  112. const url = getSvgUrl(svg);
  113. svgUrlToPng(url, (imgData) => {
  114. callback(imgData);
  115. URL.revokeObjectURL(url);
  116. });
  117. }
  118. function getSvgUrl(svg) {
  119. return URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));
  120. }
  121. function svgUrlToPng(svgUrl, callback) {
  122. const svgImage = document.createElement('img');
  123. // imgPreview.style.position = 'absolute';
  124. // imgPreview.style.top = '-9999px';
  125. document.body.appendChild(svgImage);
  126. svgImage.onload = function () {
  127. const canvas = document.createElement('canvas');
  128. canvas.width = svgImage.clientWidth;
  129. canvas.height = svgImage.clientHeight;
  130. const canvasCtx = canvas.getContext('2d');
  131. canvasCtx.drawImage(svgImage, 0, 0);
  132. const imgData = canvas.toDataURL('image/png');
  133. callback(imgData);
  134. // document.body.removeChild(imgPreview);
  135. };
  136. svgImage.src = svgUrl;
  137. }
  138.  
  139.  
  140. // Utility
  141. //------------------------------
  142.  
  143. function log(str){
  144. console.log(`[CSRD]: ${str}`);
  145. }
  146.  
  147. async function sleep(ms){
  148. await new Promise(r => setTimeout(r, ms));;// give the browser a break - idle wait
  149. }
  150.  
  151. // How to get the browser viewport dimensions?
  152. // Thanks, ryanve
  153. // https://stackoverflow.com/a/8876069
  154. function viewportX(){
  155. return Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
  156. }
  157.  
  158. function viewportY(){
  159. return Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
  160. }
  161.  
  162. function digitCount(num){
  163. return num.toString().length;
  164. }
  165.  
  166. function dataUrlToData(base64Url){
  167. return base64Url.substr(base64Url.indexOf(',')+1);
  168. }
  169.  
  170.  
  171. // Reader Utility
  172. //------------------------------
  173.  
  174. // positive flips forward (increase page number), negative flips backwards (decrease page number), 0 is to open menu
  175. function flipPage(direction) {
  176. const screen = getCSRElement(ELEMENT.SCREEN_CONTROLLER);
  177. // click on the left, middle, or right of the screen depending on arg
  178. const x = (-direction + 1) * viewportX()/2;
  179. screen.dispatchEvent(new PointerEvent("pointerdown", {buttons:1, clientX:x, clientY:100, bubbles: true}));
  180. screen.dispatchEvent(new PointerEvent("pointerup", {buttons:0, clientX:x, clientY:100, bubbles: true}));
  181. }
  182.  
  183. async function waitForPageLoad(){
  184. while(isLoadingPage()){
  185. await sleep(100);
  186. };
  187. }
  188.  
  189. function currentPage() {
  190. return +getCSRElement(ELEMENT.CURRENT_PAGE_COUNTER).textContent;
  191. }
  192.  
  193. function totalPageCount() {
  194. return +getCSRElement(ELEMENT.TOTAL_PAGE_COUNTER).textContent;
  195. }
  196.  
  197. function isLoadingPage() {
  198. return getCSRElement(ELEMENT.LOADER_SPINNER).classList.contains("onstage");
  199. }
  200.  
  201. function isMenuOpen(){
  202. return getCSRElement(ELEMENT.MENU).style.display !== "none" && getCSRElement(ELEMENT.MENU).classList.contains("onstage");
  203. }
  204.  
  205.  
  206. async function flipToFirstPage(){
  207. const slider = getCSRElement(ELEMENT.PAGE_SLIDER);
  208. if (slider === undefined && currentPage() !== 1){
  209. throw Error("This reader's automatic page slider is not supported, please move to page 1 manually and click the download button again");
  210. }
  211. if (currentPage() === 1){
  212. log(`already on first page`);
  213. return;
  214. }
  215.  
  216. log(`flipping to first page`);
  217.  
  218. if (!isMenuOpen()){
  219. log("opening menu to load scroller");
  220. flipPage(0); // open menu
  221. await sleep(200);
  222. }
  223.  
  224. // click the very right of the page slider - page 1
  225. slider.dispatchEvent(new PointerEvent("pointerdown", {buttons:1, clientX: viewportX() - 25, clientY: viewportY() - 70, bubbles: true}));
  226. slider.dispatchEvent(new PointerEvent("pointerup", {buttons:0, clientX: viewportX() - 25, clientY: viewportY() - 70, bubbles: true}));
  227. await sleep(100);
  228. await waitForPageLoad();
  229. }
  230.  
  231. // Main
  232. //------------------------------
  233.  
  234. async function generateZip() {
  235. const jsZip = new JSZip();
  236.  
  237. let totalPages = totalPageCount();
  238. if (totalPages === 0){
  239. log("ERR: the page slider seems to have been opened incorrectly");
  240. }
  241.  
  242. log(`there are ${totalPages} pages in total to save`);
  243. const zeroPads = digitCount(totalPages);
  244.  
  245. let pageNumber = 1;
  246.  
  247. log("==== downloading pages: ====");
  248.  
  249. while (true){
  250. const element_spread = getCSRElement(ELEMENT.PAGE_SPREAD);
  251. // Right to left means reverse the array
  252. for (const canvas of [...element_spread.children].toReversed()){
  253. if (canvas.style.visibility === "hidden" || canvas.style.display === "none"){
  254. log(`page before ${pageNumber} is a hidden or junk page, skipping it`); //possibly the unseen half of a 1 page spread on 2 canvases.
  255. totalPages--; // there is 1 less page than we thought - but we still want to preserve the page number's continuity. Decrement this instead
  256. continue;
  257. }
  258.  
  259. log(`saving page ${pageNumber}`);
  260. jsZip.file(`${pageNumber.toString().padStart(zeroPads,"0")}.png`, dataUrlToData(canvas.toDataURL()), {base64: true});
  261. pageNumber++;
  262. }
  263.  
  264. if (pageNumber > totalPages){
  265. break;
  266. }
  267.  
  268. flipPage(1);
  269. await sleep(150);
  270. await waitForPageLoad();
  271. await sleep(150);
  272. }
  273. return jsZip;
  274. }
  275.  
  276. function injectErrorMessage(message){
  277. if (document.getElementById("error-message") !== null){
  278. document.getElementById("error-message").remove();
  279. }
  280.  
  281. const parent = getCSRElement(ELEMENT.DOWNLOAD_BUTTON_PARENT);
  282. const div = document.createElement("div");
  283. div.id = "error-message";
  284. div.style.color = "red";
  285. parent.appendChild(div);
  286. const text = document.createTextNode(message);
  287. div.appendChild(text);
  288. }
  289.  
  290. async function downloadBookAsZip(){
  291. if (!isMenuOpen()){
  292. log("opening menu to load scroller");
  293. flipPage(0); // open menu
  294. await sleep(200);
  295. }
  296.  
  297. try{
  298. await flipToFirstPage();
  299. } catch(exception){
  300. injectErrorMessage(exception.message);
  301. throw exception;
  302. }
  303.  
  304. const jsZip = await generateZip();
  305. log("generating zip file, rename it however you like - this script cannot figure out the book's name");
  306. await jsZip.generateAsync({type:"blob"}).then(blob => saveAs(blob, "Clip_Studio_Reader_Downloader_RENAME_ME.zip"));
  307. log("==== all done! Enjoy your book ^_^ ====");
  308. }
  309.  
  310. function injectDownloadButton(){
  311. const parent = getCSRElement(ELEMENT.DOWNLOAD_BUTTON_PARENT);
  312. const div = document.createElement("div");
  313. parent.appendChild(div);
  314. div.id = "download-button";
  315. div.className = "block block_left_2 button circle button-flexible"; // style it to whatever a site wants lol
  316. div.style["margin-left"] = "0px";
  317. div.addEventListener("pointerdown", downloadBookAsZip);
  318. svgToPng(downloadSvg,(imgData)=>{
  319. const image = document.createElement('img');
  320. image.style.height = "36px";
  321. image.style["margin-top"] = "4px";
  322. div.appendChild(image);
  323. image.src = imgData;
  324. });
  325. }
  326.  
  327. // Userscript to wait for page to load before executing code techniques?
  328. // Thanks, goweon
  329. // https://stackoverflow.com/a/47406751
  330. function checkPageLoad(changes, observer) {
  331. if(getCSRElement(ELEMENT.PAGE_SPREAD)) {
  332. observer.disconnect();
  333. log("==== Clip Studio Reader Downloader ====");
  334. log("https://github.com/MrCocoNuat/clip-studio-reader-downloader");
  335. log("waiting 5 seconds for reader to load");
  336. setTimeout(async () => {
  337.  
  338. if (currentPage() === 0){ // a canary
  339. log("ERR: the reader seems to have started incorrectly - do you need to reopen the book?");
  340. return;
  341. }
  342.  
  343. injectDownloadButton();
  344. log("reader is loaded, download button injected");
  345. }, 5000);
  346. }
  347. }
  348.  
  349. function isClipStudioReader(){
  350. return !!siteElementIds[document.location.hostname];
  351. }
  352.  
  353. function init() {
  354. if(isClipStudioReader()){
  355. (new MutationObserver(checkPageLoad)).observe(document, {childList: true, subtree: true});
  356. } else {
  357. log("No instance of Clip Studio Reader found on the current page");
  358. }
  359. };
  360.  
  361. // External Libraries (integrated as best as they can in a userscript)
  362. //------------------------------
  363.  
  364.  
  365. // This section is modified from its original source
  366. //------------------------------------------------
  367.  
  368. /*
  369. * FileSaver.js
  370. * A saveAs() FileSaver implementation.
  371. *
  372. * By Eli Grey, http://eligrey.com
  373. *
  374. * License : https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md (MIT)
  375. * source : http://purl.eligrey.com/github/FileSaver.js
  376. */
  377.  
  378. function saveAs(blob, name, opts) {
  379. var a = document.createElement('a');
  380. name = name || blob.name || 'download';
  381. a.download = name;
  382. a.rel = 'noopener'; // tabnabbing
  383. // TODO: detect chrome extensions & packaged apps
  384. // a.target = '_blank'
  385.  
  386. if (typeof blob === 'string') {
  387. // Support regular links
  388. a.href = blob;
  389.  
  390. if (a.origin !== location.origin) {
  391. corsEnabled(a.href) ? download(blob, name, opts) : click(a, a.target = '_blank');
  392. } else {
  393. click(a);
  394. }
  395. } else {
  396. // Support blobs
  397. a.href = URL.createObjectURL(blob);
  398. setTimeout(function () {
  399. URL.revokeObjectURL(a.href);
  400. }, 4E4); // 40s
  401.  
  402. setTimeout(function () {
  403. click(a);
  404. }, 0);
  405. }
  406. }
  407.  
  408. function bom(blob, opts) {
  409. if (typeof opts === 'undefined') {
  410. opts = {autoBom: false}
  411. }
  412. else if (typeof opts !== 'object') {
  413. console.warn('Deprecated: Expected third argument to be a object');
  414. opts = {
  415. autoBom: !opts
  416. };
  417. } // prepend BOM for UTF-8 XML and text/* types (including HTML)
  418. // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
  419.  
  420. if (opts.autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  421. return new Blob([String.fromCharCode(0xFEFF), blob], {
  422. type: blob.type
  423. });
  424. }
  425.  
  426. return blob;
  427. }
  428.  
  429. function download(url, name, opts) {
  430. var xhr = new XMLHttpRequest();
  431. xhr.open('GET', url);
  432. xhr.responseType = 'blob';
  433.  
  434. xhr.onload = function () {
  435. saveAs(xhr.response, name, opts);
  436. };
  437.  
  438. xhr.onerror = function () {
  439. console.error('could not download file');
  440. };
  441.  
  442. xhr.send();
  443. }
  444.  
  445. function corsEnabled(url) {
  446. var xhr = new XMLHttpRequest(); // use sync to avoid popup blocker
  447.  
  448. xhr.open('HEAD', url, false);
  449.  
  450. try {
  451. xhr.send();
  452. } catch (e) {}
  453.  
  454. return xhr.status >= 200 && xhr.status <= 299;
  455. } // `a.click()` doesn't work for all browsers (#465)
  456.  
  457.  
  458. function click(node) {
  459. try {
  460. node.dispatchEvent(new MouseEvent('click'));
  461. } catch (e) {
  462. var evt = document.createEvent('MouseEvents');
  463. evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
  464. node.dispatchEvent(evt);
  465. }
  466. }
  467.  
  468.  
  469. //------------------------------------------------
  470.  
  471. /*!
  472.  
  473. JSZip v3.10.1 - A JavaScript class for generating and reading zip files
  474. <http://stuartk.com/jszip>
  475.  
  476. (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
  477. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
  478.  
  479. JSZip uses the library pako released under the MIT license :
  480. https://github.com/nodeca/pako/blob/main/LICENSE
  481. */
  482.  
  483. (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){
  484. "use strict";
  485. var utils = require("./utils");
  486. var support = require("./support");
  487. // private property
  488. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  489.  
  490.  
  491. // public method for encoding
  492. exports.encode = function(input) {
  493. var output = [];
  494. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  495. var i = 0, len = input.length, remainingBytes = len;
  496.  
  497. var isArray = utils.getTypeOf(input) !== "string";
  498. while (i < input.length) {
  499. remainingBytes = len - i;
  500.  
  501. if (!isArray) {
  502. chr1 = input.charCodeAt(i++);
  503. chr2 = i < len ? input.charCodeAt(i++) : 0;
  504. chr3 = i < len ? input.charCodeAt(i++) : 0;
  505. } else {
  506. chr1 = input[i++];
  507. chr2 = i < len ? input[i++] : 0;
  508. chr3 = i < len ? input[i++] : 0;
  509. }
  510.  
  511. enc1 = chr1 >> 2;
  512. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  513. enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;
  514. enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;
  515.  
  516. output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));
  517.  
  518. }
  519.  
  520. return output.join("");
  521. };
  522.  
  523. // public method for decoding
  524. exports.decode = function(input) {
  525. var chr1, chr2, chr3;
  526. var enc1, enc2, enc3, enc4;
  527. var i = 0, resultIndex = 0;
  528.  
  529. var dataUrlPrefix = "data:";
  530.  
  531. if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {
  532. // This is a common error: people give a data url
  533. // (data:image/png;base64,iVBOR...) with a {base64: true} and
  534. // wonders why things don't work.
  535. // We can detect that the string input looks like a data url but we
  536. // *can't* be sure it is one: removing everything up to the comma would
  537. // be too dangerous.
  538. throw new Error("Invalid base64 input, it looks like a data url.");
  539. }
  540.  
  541. input = input.replace(/[^A-Za-z0-9+/=]/g, "");
  542.  
  543. var totalLength = input.length * 3 / 4;
  544. if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {
  545. totalLength--;
  546. }
  547. if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {
  548. totalLength--;
  549. }
  550. if (totalLength % 1 !== 0) {
  551. // totalLength is not an integer, the length does not match a valid
  552. // base64 content. That can happen if:
  553. // - the input is not a base64 content
  554. // - the input is *almost* a base64 content, with a extra chars at the
  555. // beginning or at the end
  556. // - the input uses a base64 variant (base64url for example)
  557. throw new Error("Invalid base64 input, bad content length.");
  558. }
  559. var output;
  560. if (support.uint8array) {
  561. output = new Uint8Array(totalLength|0);
  562. } else {
  563. output = new Array(totalLength|0);
  564. }
  565.  
  566. while (i < input.length) {
  567.  
  568. enc1 = _keyStr.indexOf(input.charAt(i++));
  569. enc2 = _keyStr.indexOf(input.charAt(i++));
  570. enc3 = _keyStr.indexOf(input.charAt(i++));
  571. enc4 = _keyStr.indexOf(input.charAt(i++));
  572.  
  573. chr1 = (enc1 << 2) | (enc2 >> 4);
  574. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  575. chr3 = ((enc3 & 3) << 6) | enc4;
  576.  
  577. output[resultIndex++] = chr1;
  578.  
  579. if (enc3 !== 64) {
  580. output[resultIndex++] = chr2;
  581. }
  582. if (enc4 !== 64) {
  583. output[resultIndex++] = chr3;
  584. }
  585.  
  586. }
  587.  
  588. return output;
  589. };
  590.  
  591. },{"./support":30,"./utils":32}],2:[function(require,module,exports){
  592. "use strict";
  593.  
  594. var external = require("./external");
  595. var DataWorker = require("./stream/DataWorker");
  596. var Crc32Probe = require("./stream/Crc32Probe");
  597. var DataLengthProbe = require("./stream/DataLengthProbe");
  598.  
  599. /**
  600. * Represent a compressed object, with everything needed to decompress it.
  601. * @constructor
  602. * @param {number} compressedSize the size of the data compressed.
  603. * @param {number} uncompressedSize the size of the data after decompression.
  604. * @param {number} crc32 the crc32 of the decompressed file.
  605. * @param {object} compression the type of compression, see lib/compressions.js.
  606. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
  607. */
  608. function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
  609. this.compressedSize = compressedSize;
  610. this.uncompressedSize = uncompressedSize;
  611. this.crc32 = crc32;
  612. this.compression = compression;
  613. this.compressedContent = data;
  614. }
  615.  
  616. CompressedObject.prototype = {
  617. /**
  618. * Create a worker to get the uncompressed content.
  619. * @return {GenericWorker} the worker.
  620. */
  621. getContentWorker: function () {
  622. var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
  623. .pipe(this.compression.uncompressWorker())
  624. .pipe(new DataLengthProbe("data_length"));
  625.  
  626. var that = this;
  627. worker.on("end", function () {
  628. if (this.streamInfo["data_length"] !== that.uncompressedSize) {
  629. throw new Error("Bug : uncompressed data size mismatch");
  630. }
  631. });
  632. return worker;
  633. },
  634. /**
  635. * Create a worker to get the compressed content.
  636. * @return {GenericWorker} the worker.
  637. */
  638. getCompressedWorker: function () {
  639. return new DataWorker(external.Promise.resolve(this.compressedContent))
  640. .withStreamInfo("compressedSize", this.compressedSize)
  641. .withStreamInfo("uncompressedSize", this.uncompressedSize)
  642. .withStreamInfo("crc32", this.crc32)
  643. .withStreamInfo("compression", this.compression)
  644. ;
  645. }
  646. };
  647.  
  648. /**
  649. * Chain the given worker with other workers to compress the content with the
  650. * given compression.
  651. * @param {GenericWorker} uncompressedWorker the worker to pipe.
  652. * @param {Object} compression the compression object.
  653. * @param {Object} compressionOptions the options to use when compressing.
  654. * @return {GenericWorker} the new worker compressing the content.
  655. */
  656. CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
  657. return uncompressedWorker
  658. .pipe(new Crc32Probe())
  659. .pipe(new DataLengthProbe("uncompressedSize"))
  660. .pipe(compression.compressWorker(compressionOptions))
  661. .pipe(new DataLengthProbe("compressedSize"))
  662. .withStreamInfo("compression", compression);
  663. };
  664.  
  665. module.exports = CompressedObject;
  666.  
  667. },{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){
  668. "use strict";
  669.  
  670. var GenericWorker = require("./stream/GenericWorker");
  671.  
  672. exports.STORE = {
  673. magic: "\x00\x00",
  674. compressWorker : function () {
  675. return new GenericWorker("STORE compression");
  676. },
  677. uncompressWorker : function () {
  678. return new GenericWorker("STORE decompression");
  679. }
  680. };
  681. exports.DEFLATE = require("./flate");
  682.  
  683. },{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){
  684. "use strict";
  685.  
  686. var utils = require("./utils");
  687.  
  688. /**
  689. * The following functions come from pako, from pako/lib/zlib/crc32.js
  690. * released under the MIT license, see pako https://github.com/nodeca/pako/
  691. */
  692.  
  693. // Use ordinary array, since untyped makes no boost here
  694. function makeTable() {
  695. var c, table = [];
  696.  
  697. for(var n =0; n < 256; n++){
  698. c = n;
  699. for(var k =0; k < 8; k++){
  700. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  701. }
  702. table[n] = c;
  703. }
  704.  
  705. return table;
  706. }
  707.  
  708. // Create table on load. Just 255 signed longs. Not a problem.
  709. var crcTable = makeTable();
  710.  
  711.  
  712. function crc32(crc, buf, len, pos) {
  713. var t = crcTable, end = pos + len;
  714.  
  715. crc = crc ^ (-1);
  716.  
  717. for (var i = pos; i < end; i++ ) {
  718. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  719. }
  720.  
  721. return (crc ^ (-1)); // >>> 0;
  722. }
  723.  
  724. // That's all for the pako functions.
  725.  
  726. /**
  727. * Compute the crc32 of a string.
  728. * This is almost the same as the function crc32, but for strings. Using the
  729. * same function for the two use cases leads to horrible performances.
  730. * @param {Number} crc the starting value of the crc.
  731. * @param {String} str the string to use.
  732. * @param {Number} len the length of the string.
  733. * @param {Number} pos the starting position for the crc32 computation.
  734. * @return {Number} the computed crc32.
  735. */
  736. function crc32str(crc, str, len, pos) {
  737. var t = crcTable, end = pos + len;
  738.  
  739. crc = crc ^ (-1);
  740.  
  741. for (var i = pos; i < end; i++ ) {
  742. crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
  743. }
  744.  
  745. return (crc ^ (-1)); // >>> 0;
  746. }
  747.  
  748. module.exports = function crc32wrapper(input, crc) {
  749. if (typeof input === "undefined" || !input.length) {
  750. return 0;
  751. }
  752.  
  753. var isArray = utils.getTypeOf(input) !== "string";
  754.  
  755. if(isArray) {
  756. return crc32(crc|0, input, input.length, 0);
  757. } else {
  758. return crc32str(crc|0, input, input.length, 0);
  759. }
  760. };
  761.  
  762. },{"./utils":32}],5:[function(require,module,exports){
  763. "use strict";
  764. exports.base64 = false;
  765. exports.binary = false;
  766. exports.dir = false;
  767. exports.createFolders = true;
  768. exports.date = null;
  769. exports.compression = null;
  770. exports.compressionOptions = null;
  771. exports.comment = null;
  772. exports.unixPermissions = null;
  773. exports.dosPermissions = null;
  774.  
  775. },{}],6:[function(require,module,exports){
  776. "use strict";
  777.  
  778. // load the global object first:
  779. // - it should be better integrated in the system (unhandledRejection in node)
  780. // - the environment may have a custom Promise implementation (see zone.js)
  781. var ES6Promise = null;
  782. if (typeof Promise !== "undefined") {
  783. ES6Promise = Promise;
  784. } else {
  785. ES6Promise = require("lie");
  786. }
  787.  
  788. /**
  789. * Let the user use/change some implementations.
  790. */
  791. module.exports = {
  792. Promise: ES6Promise
  793. };
  794.  
  795. },{"lie":37}],7:[function(require,module,exports){
  796. "use strict";
  797. var USE_TYPEDARRAY = (typeof Uint8Array !== "undefined") && (typeof Uint16Array !== "undefined") && (typeof Uint32Array !== "undefined");
  798.  
  799. var pako = require("pako");
  800. var utils = require("./utils");
  801. var GenericWorker = require("./stream/GenericWorker");
  802.  
  803. var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
  804.  
  805. exports.magic = "\x08\x00";
  806.  
  807. /**
  808. * Create a worker that uses pako to inflate/deflate.
  809. * @constructor
  810. * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
  811. * @param {Object} options the options to use when (de)compressing.
  812. */
  813. function FlateWorker(action, options) {
  814. GenericWorker.call(this, "FlateWorker/" + action);
  815.  
  816. this._pako = null;
  817. this._pakoAction = action;
  818. this._pakoOptions = options;
  819. // the `meta` object from the last chunk received
  820. // this allow this worker to pass around metadata
  821. this.meta = {};
  822. }
  823.  
  824. utils.inherits(FlateWorker, GenericWorker);
  825.  
  826. /**
  827. * @see GenericWorker.processChunk
  828. */
  829. FlateWorker.prototype.processChunk = function (chunk) {
  830. this.meta = chunk.meta;
  831. if (this._pako === null) {
  832. this._createPako();
  833. }
  834. this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
  835. };
  836.  
  837. /**
  838. * @see GenericWorker.flush
  839. */
  840. FlateWorker.prototype.flush = function () {
  841. GenericWorker.prototype.flush.call(this);
  842. if (this._pako === null) {
  843. this._createPako();
  844. }
  845. this._pako.push([], true);
  846. };
  847. /**
  848. * @see GenericWorker.cleanUp
  849. */
  850. FlateWorker.prototype.cleanUp = function () {
  851. GenericWorker.prototype.cleanUp.call(this);
  852. this._pako = null;
  853. };
  854.  
  855. /**
  856. * Create the _pako object.
  857. * TODO: lazy-loading this object isn't the best solution but it's the
  858. * quickest. The best solution is to lazy-load the worker list. See also the
  859. * issue #446.
  860. */
  861. FlateWorker.prototype._createPako = function () {
  862. this._pako = new pako[this._pakoAction]({
  863. raw: true,
  864. level: this._pakoOptions.level || -1 // default compression
  865. });
  866. var self = this;
  867. this._pako.onData = function(data) {
  868. self.push({
  869. data : data,
  870. meta : self.meta
  871. });
  872. };
  873. };
  874.  
  875. exports.compressWorker = function (compressionOptions) {
  876. return new FlateWorker("Deflate", compressionOptions);
  877. };
  878. exports.uncompressWorker = function () {
  879. return new FlateWorker("Inflate", {});
  880. };
  881.  
  882. },{"./stream/GenericWorker":28,"./utils":32,"pako":38}],8:[function(require,module,exports){
  883. "use strict";
  884.  
  885. var utils = require("../utils");
  886. var GenericWorker = require("../stream/GenericWorker");
  887. var utf8 = require("../utf8");
  888. var crc32 = require("../crc32");
  889. var signature = require("../signature");
  890.  
  891. /**
  892. * Transform an integer into a string in hexadecimal.
  893. * @private
  894. * @param {number} dec the number to convert.
  895. * @param {number} bytes the number of bytes to generate.
  896. * @returns {string} the result.
  897. */
  898. var decToHex = function(dec, bytes) {
  899. var hex = "", i;
  900. for (i = 0; i < bytes; i++) {
  901. hex += String.fromCharCode(dec & 0xff);
  902. dec = dec >>> 8;
  903. }
  904. return hex;
  905. };
  906.  
  907. /**
  908. * Generate the UNIX part of the external file attributes.
  909. * @param {Object} unixPermissions the unix permissions or null.
  910. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  911. * @return {Number} a 32 bit integer.
  912. *
  913. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  914. *
  915. * TTTTsstrwxrwxrwx0000000000ADVSHR
  916. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  917. * ^^^_________________________ setuid, setgid, sticky
  918. * ^^^^^^^^^________________ permissions
  919. * ^^^^^^^^^^______ not used ?
  920. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  921. */
  922. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  923.  
  924. var result = unixPermissions;
  925. if (!unixPermissions) {
  926. // I can't use octal values in strict mode, hence the hexa.
  927. // 040775 => 0x41fd
  928. // 0100664 => 0x81b4
  929. result = isDir ? 0x41fd : 0x81b4;
  930. }
  931. return (result & 0xFFFF) << 16;
  932. };
  933.  
  934. /**
  935. * Generate the DOS part of the external file attributes.
  936. * @param {Object} dosPermissions the dos permissions or null.
  937. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  938. * @return {Number} a 32 bit integer.
  939. *
  940. * Bit 0 Read-Only
  941. * Bit 1 Hidden
  942. * Bit 2 System
  943. * Bit 3 Volume Label
  944. * Bit 4 Directory
  945. * Bit 5 Archive
  946. */
  947. var generateDosExternalFileAttr = function (dosPermissions) {
  948. // the dir flag is already set for compatibility
  949. return (dosPermissions || 0) & 0x3F;
  950. };
  951.  
  952. /**
  953. * Generate the various parts used in the construction of the final zip file.
  954. * @param {Object} streamInfo the hash with information about the compressed file.
  955. * @param {Boolean} streamedContent is the content streamed ?
  956. * @param {Boolean} streamingEnded is the stream finished ?
  957. * @param {number} offset the current offset from the start of the zip file.
  958. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  959. * @param {Function} encodeFileName the function to encode the file name / comment.
  960. * @return {Object} the zip parts.
  961. */
  962. var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
  963. var file = streamInfo["file"],
  964. compression = streamInfo["compression"],
  965. useCustomEncoding = encodeFileName !== utf8.utf8encode,
  966. encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
  967. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  968. comment = file.comment,
  969. encodedComment = utils.transformTo("string", encodeFileName(comment)),
  970. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  971. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  972. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  973. dosTime,
  974. dosDate,
  975. extraFields = "",
  976. unicodePathExtraField = "",
  977. unicodeCommentExtraField = "",
  978. dir = file.dir,
  979. date = file.date;
  980.  
  981.  
  982. var dataInfo = {
  983. crc32 : 0,
  984. compressedSize : 0,
  985. uncompressedSize : 0
  986. };
  987.  
  988. // if the content is streamed, the sizes/crc32 are only available AFTER
  989. // the end of the stream.
  990. if (!streamedContent || streamingEnded) {
  991. dataInfo.crc32 = streamInfo["crc32"];
  992. dataInfo.compressedSize = streamInfo["compressedSize"];
  993. dataInfo.uncompressedSize = streamInfo["uncompressedSize"];
  994. }
  995.  
  996. var bitflag = 0;
  997. if (streamedContent) {
  998. // Bit 3: the sizes/crc32 are set to zero in the local header.
  999. // The correct values are put in the data descriptor immediately
  1000. // following the compressed data.
  1001. bitflag |= 0x0008;
  1002. }
  1003. if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
  1004. // Bit 11: Language encoding flag (EFS).
  1005. bitflag |= 0x0800;
  1006. }
  1007.  
  1008.  
  1009. var extFileAttr = 0;
  1010. var versionMadeBy = 0;
  1011. if (dir) {
  1012. // dos or unix, we set the dos dir flag
  1013. extFileAttr |= 0x00010;
  1014. }
  1015. if(platform === "UNIX") {
  1016. versionMadeBy = 0x031E; // UNIX, version 3.0
  1017. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  1018. } else { // DOS or other, fallback to DOS
  1019. versionMadeBy = 0x0014; // DOS, version 2.0
  1020. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  1021. }
  1022.  
  1023. // date
  1024. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  1025. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  1026. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  1027.  
  1028. dosTime = date.getUTCHours();
  1029. dosTime = dosTime << 6;
  1030. dosTime = dosTime | date.getUTCMinutes();
  1031. dosTime = dosTime << 5;
  1032. dosTime = dosTime | date.getUTCSeconds() / 2;
  1033.  
  1034. dosDate = date.getUTCFullYear() - 1980;
  1035. dosDate = dosDate << 4;
  1036. dosDate = dosDate | (date.getUTCMonth() + 1);
  1037. dosDate = dosDate << 5;
  1038. dosDate = dosDate | date.getUTCDate();
  1039.  
  1040. if (useUTF8ForFileName) {
  1041. // set the unicode path extra field. unzip needs at least one extra
  1042. // field to correctly handle unicode path, so using the path is as good
  1043. // as any other information. This could improve the situation with
  1044. // other archive managers too.
  1045. // This field is usually used without the utf8 flag, with a non
  1046. // unicode path in the header (winrar, winzip). This helps (a bit)
  1047. // with the messy Windows' default compressed folders feature but
  1048. // breaks on p7zip which doesn't seek the unicode path extra field.
  1049. // So for now, UTF-8 everywhere !
  1050. unicodePathExtraField =
  1051. // Version
  1052. decToHex(1, 1) +
  1053. // NameCRC32
  1054. decToHex(crc32(encodedFileName), 4) +
  1055. // UnicodeName
  1056. utfEncodedFileName;
  1057.  
  1058. extraFields +=
  1059. // Info-ZIP Unicode Path Extra Field
  1060. "\x75\x70" +
  1061. // size
  1062. decToHex(unicodePathExtraField.length, 2) +
  1063. // content
  1064. unicodePathExtraField;
  1065. }
  1066.  
  1067. if(useUTF8ForComment) {
  1068.  
  1069. unicodeCommentExtraField =
  1070. // Version
  1071. decToHex(1, 1) +
  1072. // CommentCRC32
  1073. decToHex(crc32(encodedComment), 4) +
  1074. // UnicodeName
  1075. utfEncodedComment;
  1076.  
  1077. extraFields +=
  1078. // Info-ZIP Unicode Path Extra Field
  1079. "\x75\x63" +
  1080. // size
  1081. decToHex(unicodeCommentExtraField.length, 2) +
  1082. // content
  1083. unicodeCommentExtraField;
  1084. }
  1085.  
  1086. var header = "";
  1087.  
  1088. // version needed to extract
  1089. header += "\x0A\x00";
  1090. // general purpose bit flag
  1091. header += decToHex(bitflag, 2);
  1092. // compression method
  1093. header += compression.magic;
  1094. // last mod file time
  1095. header += decToHex(dosTime, 2);
  1096. // last mod file date
  1097. header += decToHex(dosDate, 2);
  1098. // crc-32
  1099. header += decToHex(dataInfo.crc32, 4);
  1100. // compressed size
  1101. header += decToHex(dataInfo.compressedSize, 4);
  1102. // uncompressed size
  1103. header += decToHex(dataInfo.uncompressedSize, 4);
  1104. // file name length
  1105. header += decToHex(encodedFileName.length, 2);
  1106. // extra field length
  1107. header += decToHex(extraFields.length, 2);
  1108.  
  1109.  
  1110. var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  1111.  
  1112. var dirRecord = signature.CENTRAL_FILE_HEADER +
  1113. // version made by (00: DOS)
  1114. decToHex(versionMadeBy, 2) +
  1115. // file header (common to file and central directory)
  1116. header +
  1117. // file comment length
  1118. decToHex(encodedComment.length, 2) +
  1119. // disk number start
  1120. "\x00\x00" +
  1121. // internal file attributes TODO
  1122. "\x00\x00" +
  1123. // external file attributes
  1124. decToHex(extFileAttr, 4) +
  1125. // relative offset of local header
  1126. decToHex(offset, 4) +
  1127. // file name
  1128. encodedFileName +
  1129. // extra field
  1130. extraFields +
  1131. // file comment
  1132. encodedComment;
  1133.  
  1134. return {
  1135. fileRecord: fileRecord,
  1136. dirRecord: dirRecord
  1137. };
  1138. };
  1139.  
  1140. /**
  1141. * Generate the EOCD record.
  1142. * @param {Number} entriesCount the number of entries in the zip file.
  1143. * @param {Number} centralDirLength the length (in bytes) of the central dir.
  1144. * @param {Number} localDirLength the length (in bytes) of the local dir.
  1145. * @param {String} comment the zip file comment as a binary string.
  1146. * @param {Function} encodeFileName the function to encode the comment.
  1147. * @return {String} the EOCD record.
  1148. */
  1149. var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
  1150. var dirEnd = "";
  1151. var encodedComment = utils.transformTo("string", encodeFileName(comment));
  1152.  
  1153. // end of central dir signature
  1154. dirEnd = signature.CENTRAL_DIRECTORY_END +
  1155. // number of this disk
  1156. "\x00\x00" +
  1157. // number of the disk with the start of the central directory
  1158. "\x00\x00" +
  1159. // total number of entries in the central directory on this disk
  1160. decToHex(entriesCount, 2) +
  1161. // total number of entries in the central directory
  1162. decToHex(entriesCount, 2) +
  1163. // size of the central directory 4 bytes
  1164. decToHex(centralDirLength, 4) +
  1165. // offset of start of central directory with respect to the starting disk number
  1166. decToHex(localDirLength, 4) +
  1167. // .ZIP file comment length
  1168. decToHex(encodedComment.length, 2) +
  1169. // .ZIP file comment
  1170. encodedComment;
  1171.  
  1172. return dirEnd;
  1173. };
  1174.  
  1175. /**
  1176. * Generate data descriptors for a file entry.
  1177. * @param {Object} streamInfo the hash generated by a worker, containing information
  1178. * on the file entry.
  1179. * @return {String} the data descriptors.
  1180. */
  1181. var generateDataDescriptors = function (streamInfo) {
  1182. var descriptor = "";
  1183. descriptor = signature.DATA_DESCRIPTOR +
  1184. // crc-32 4 bytes
  1185. decToHex(streamInfo["crc32"], 4) +
  1186. // compressed size 4 bytes
  1187. decToHex(streamInfo["compressedSize"], 4) +
  1188. // uncompressed size 4 bytes
  1189. decToHex(streamInfo["uncompressedSize"], 4);
  1190.  
  1191. return descriptor;
  1192. };
  1193.  
  1194.  
  1195. /**
  1196. * A worker to concatenate other workers to create a zip file.
  1197. * @param {Boolean} streamFiles `true` to stream the content of the files,
  1198. * `false` to accumulate it.
  1199. * @param {String} comment the comment to use.
  1200. * @param {String} platform the platform to use, "UNIX" or "DOS".
  1201. * @param {Function} encodeFileName the function to encode file names and comments.
  1202. */
  1203. function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
  1204. GenericWorker.call(this, "ZipFileWorker");
  1205. // The number of bytes written so far. This doesn't count accumulated chunks.
  1206. this.bytesWritten = 0;
  1207. // The comment of the zip file
  1208. this.zipComment = comment;
  1209. // The platform "generating" the zip file.
  1210. this.zipPlatform = platform;
  1211. // the function to encode file names and comments.
  1212. this.encodeFileName = encodeFileName;
  1213. // Should we stream the content of the files ?
  1214. this.streamFiles = streamFiles;
  1215. // If `streamFiles` is false, we will need to accumulate the content of the
  1216. // files to calculate sizes / crc32 (and write them *before* the content).
  1217. // This boolean indicates if we are accumulating chunks (it will change a lot
  1218. // during the lifetime of this worker).
  1219. this.accumulate = false;
  1220. // The buffer receiving chunks when accumulating content.
  1221. this.contentBuffer = [];
  1222. // The list of generated directory records.
  1223. this.dirRecords = [];
  1224. // The offset (in bytes) from the beginning of the zip file for the current source.
  1225. this.currentSourceOffset = 0;
  1226. // The total number of entries in this zip file.
  1227. this.entriesCount = 0;
  1228. // the name of the file currently being added, null when handling the end of the zip file.
  1229. // Used for the emitted metadata.
  1230. this.currentFile = null;
  1231.  
  1232.  
  1233.  
  1234. this._sources = [];
  1235. }
  1236. utils.inherits(ZipFileWorker, GenericWorker);
  1237.  
  1238. /**
  1239. * @see GenericWorker.push
  1240. */
  1241. ZipFileWorker.prototype.push = function (chunk) {
  1242.  
  1243. var currentFilePercent = chunk.meta.percent || 0;
  1244. var entriesCount = this.entriesCount;
  1245. var remainingFiles = this._sources.length;
  1246.  
  1247. if(this.accumulate) {
  1248. this.contentBuffer.push(chunk);
  1249. } else {
  1250. this.bytesWritten += chunk.data.length;
  1251.  
  1252. GenericWorker.prototype.push.call(this, {
  1253. data : chunk.data,
  1254. meta : {
  1255. currentFile : this.currentFile,
  1256. percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
  1257. }
  1258. });
  1259. }
  1260. };
  1261.  
  1262. /**
  1263. * The worker started a new source (an other worker).
  1264. * @param {Object} streamInfo the streamInfo object from the new source.
  1265. */
  1266. ZipFileWorker.prototype.openedSource = function (streamInfo) {
  1267. this.currentSourceOffset = this.bytesWritten;
  1268. this.currentFile = streamInfo["file"].name;
  1269.  
  1270. var streamedContent = this.streamFiles && !streamInfo["file"].dir;
  1271.  
  1272. // don't stream folders (because they don't have any content)
  1273. if(streamedContent) {
  1274. var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  1275. this.push({
  1276. data : record.fileRecord,
  1277. meta : {percent:0}
  1278. });
  1279. } else {
  1280. // we need to wait for the whole file before pushing anything
  1281. this.accumulate = true;
  1282. }
  1283. };
  1284.  
  1285. /**
  1286. * The worker finished a source (an other worker).
  1287. * @param {Object} streamInfo the streamInfo object from the finished source.
  1288. */
  1289. ZipFileWorker.prototype.closedSource = function (streamInfo) {
  1290. this.accumulate = false;
  1291. var streamedContent = this.streamFiles && !streamInfo["file"].dir;
  1292. var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  1293.  
  1294. this.dirRecords.push(record.dirRecord);
  1295. if(streamedContent) {
  1296. // after the streamed file, we put data descriptors
  1297. this.push({
  1298. data : generateDataDescriptors(streamInfo),
  1299. meta : {percent:100}
  1300. });
  1301. } else {
  1302. // the content wasn't streamed, we need to push everything now
  1303. // first the file record, then the content
  1304. this.push({
  1305. data : record.fileRecord,
  1306. meta : {percent:0}
  1307. });
  1308. while(this.contentBuffer.length) {
  1309. this.push(this.contentBuffer.shift());
  1310. }
  1311. }
  1312. this.currentFile = null;
  1313. };
  1314.  
  1315. /**
  1316. * @see GenericWorker.flush
  1317. */
  1318. ZipFileWorker.prototype.flush = function () {
  1319.  
  1320. var localDirLength = this.bytesWritten;
  1321. for(var i = 0; i < this.dirRecords.length; i++) {
  1322. this.push({
  1323. data : this.dirRecords[i],
  1324. meta : {percent:100}
  1325. });
  1326. }
  1327. var centralDirLength = this.bytesWritten - localDirLength;
  1328.  
  1329. var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
  1330.  
  1331. this.push({
  1332. data : dirEnd,
  1333. meta : {percent:100}
  1334. });
  1335. };
  1336.  
  1337. /**
  1338. * Prepare the next source to be read.
  1339. */
  1340. ZipFileWorker.prototype.prepareNextSource = function () {
  1341. this.previous = this._sources.shift();
  1342. this.openedSource(this.previous.streamInfo);
  1343. if (this.isPaused) {
  1344. this.previous.pause();
  1345. } else {
  1346. this.previous.resume();
  1347. }
  1348. };
  1349.  
  1350. /**
  1351. * @see GenericWorker.registerPrevious
  1352. */
  1353. ZipFileWorker.prototype.registerPrevious = function (previous) {
  1354. this._sources.push(previous);
  1355. var self = this;
  1356.  
  1357. previous.on("data", function (chunk) {
  1358. self.processChunk(chunk);
  1359. });
  1360. previous.on("end", function () {
  1361. self.closedSource(self.previous.streamInfo);
  1362. if(self._sources.length) {
  1363. self.prepareNextSource();
  1364. } else {
  1365. self.end();
  1366. }
  1367. });
  1368. previous.on("error", function (e) {
  1369. self.error(e);
  1370. });
  1371. return this;
  1372. };
  1373.  
  1374. /**
  1375. * @see GenericWorker.resume
  1376. */
  1377. ZipFileWorker.prototype.resume = function () {
  1378. if(!GenericWorker.prototype.resume.call(this)) {
  1379. return false;
  1380. }
  1381.  
  1382. if (!this.previous && this._sources.length) {
  1383. this.prepareNextSource();
  1384. return true;
  1385. }
  1386. if (!this.previous && !this._sources.length && !this.generatedError) {
  1387. this.end();
  1388. return true;
  1389. }
  1390. };
  1391.  
  1392. /**
  1393. * @see GenericWorker.error
  1394. */
  1395. ZipFileWorker.prototype.error = function (e) {
  1396. var sources = this._sources;
  1397. if(!GenericWorker.prototype.error.call(this, e)) {
  1398. return false;
  1399. }
  1400. for(var i = 0; i < sources.length; i++) {
  1401. try {
  1402. sources[i].error(e);
  1403. } catch(e) {
  1404. // the `error` exploded, nothing to do
  1405. }
  1406. }
  1407. return true;
  1408. };
  1409.  
  1410. /**
  1411. * @see GenericWorker.lock
  1412. */
  1413. ZipFileWorker.prototype.lock = function () {
  1414. GenericWorker.prototype.lock.call(this);
  1415. var sources = this._sources;
  1416. for(var i = 0; i < sources.length; i++) {
  1417. sources[i].lock();
  1418. }
  1419. };
  1420.  
  1421. module.exports = ZipFileWorker;
  1422.  
  1423. },{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){
  1424. "use strict";
  1425.  
  1426. var compressions = require("../compressions");
  1427. var ZipFileWorker = require("./ZipFileWorker");
  1428.  
  1429. /**
  1430. * Find the compression to use.
  1431. * @param {String} fileCompression the compression defined at the file level, if any.
  1432. * @param {String} zipCompression the compression defined at the load() level.
  1433. * @return {Object} the compression object to use.
  1434. */
  1435. var getCompression = function (fileCompression, zipCompression) {
  1436.  
  1437. var compressionName = fileCompression || zipCompression;
  1438. var compression = compressions[compressionName];
  1439. if (!compression) {
  1440. throw new Error(compressionName + " is not a valid compression method !");
  1441. }
  1442. return compression;
  1443. };
  1444.  
  1445. /**
  1446. * Create a worker to generate a zip file.
  1447. * @param {JSZip} zip the JSZip instance at the right root level.
  1448. * @param {Object} options to generate the zip file.
  1449. * @param {String} comment the comment to use.
  1450. */
  1451. exports.generateWorker = function (zip, options, comment) {
  1452.  
  1453. var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
  1454. var entriesCount = 0;
  1455. try {
  1456.  
  1457. zip.forEach(function (relativePath, file) {
  1458. entriesCount++;
  1459. var compression = getCompression(file.options.compression, options.compression);
  1460. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  1461. var dir = file.dir, date = file.date;
  1462.  
  1463. file._compressWorker(compression, compressionOptions)
  1464. .withStreamInfo("file", {
  1465. name : relativePath,
  1466. dir : dir,
  1467. date : date,
  1468. comment : file.comment || "",
  1469. unixPermissions : file.unixPermissions,
  1470. dosPermissions : file.dosPermissions
  1471. })
  1472. .pipe(zipFileWorker);
  1473. });
  1474. zipFileWorker.entriesCount = entriesCount;
  1475. } catch (e) {
  1476. zipFileWorker.error(e);
  1477. }
  1478.  
  1479. return zipFileWorker;
  1480. };
  1481.  
  1482. },{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){
  1483. "use strict";
  1484.  
  1485. /**
  1486. * Representation a of zip file in js
  1487. * @constructor
  1488. */
  1489. function JSZip() {
  1490. // if this constructor is used without `new`, it adds `new` before itself:
  1491. if(!(this instanceof JSZip)) {
  1492. return new JSZip();
  1493. }
  1494.  
  1495. if(arguments.length) {
  1496. throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
  1497. }
  1498.  
  1499. // object containing the files :
  1500. // {
  1501. // "folder/" : {...},
  1502. // "folder/data.txt" : {...}
  1503. // }
  1504. // NOTE: we use a null prototype because we do not
  1505. // want filenames like "toString" coming from a zip file
  1506. // to overwrite methods and attributes in a normal Object.
  1507. this.files = Object.create(null);
  1508.  
  1509. this.comment = null;
  1510.  
  1511. // Where we are in the hierarchy
  1512. this.root = "";
  1513. this.clone = function() {
  1514. var newObj = new JSZip();
  1515. for (var i in this) {
  1516. if (typeof this[i] !== "function") {
  1517. newObj[i] = this[i];
  1518. }
  1519. }
  1520. return newObj;
  1521. };
  1522. }
  1523. JSZip.prototype = require("./object");
  1524. JSZip.prototype.loadAsync = require("./load");
  1525. JSZip.support = require("./support");
  1526. JSZip.defaults = require("./defaults");
  1527.  
  1528. // TODO find a better way to handle this version,
  1529. // a require('package.json').version doesn't work with webpack, see #327
  1530. JSZip.version = "3.10.1";
  1531.  
  1532. JSZip.loadAsync = function (content, options) {
  1533. return new JSZip().loadAsync(content, options);
  1534. };
  1535.  
  1536. JSZip.external = require("./external");
  1537. module.exports = JSZip;
  1538.  
  1539. },{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){
  1540. "use strict";
  1541. var utils = require("./utils");
  1542. var external = require("./external");
  1543. var utf8 = require("./utf8");
  1544. var ZipEntries = require("./zipEntries");
  1545. var Crc32Probe = require("./stream/Crc32Probe");
  1546. var nodejsUtils = require("./nodejsUtils");
  1547.  
  1548. /**
  1549. * Check the CRC32 of an entry.
  1550. * @param {ZipEntry} zipEntry the zip entry to check.
  1551. * @return {Promise} the result.
  1552. */
  1553. function checkEntryCRC32(zipEntry) {
  1554. return new external.Promise(function (resolve, reject) {
  1555. var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
  1556. worker.on("error", function (e) {
  1557. reject(e);
  1558. })
  1559. .on("end", function () {
  1560. if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
  1561. reject(new Error("Corrupted zip : CRC32 mismatch"));
  1562. } else {
  1563. resolve();
  1564. }
  1565. })
  1566. .resume();
  1567. });
  1568. }
  1569.  
  1570. module.exports = function (data, options) {
  1571. var zip = this;
  1572. options = utils.extend(options || {}, {
  1573. base64: false,
  1574. checkCRC32: false,
  1575. optimizedBinaryString: false,
  1576. createFolders: false,
  1577. decodeFileName: utf8.utf8decode
  1578. });
  1579.  
  1580. if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1581. return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
  1582. }
  1583.  
  1584. return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
  1585. .then(function (data) {
  1586. var zipEntries = new ZipEntries(options);
  1587. zipEntries.load(data);
  1588. return zipEntries;
  1589. }).then(function checkCRC32(zipEntries) {
  1590. var promises = [external.Promise.resolve(zipEntries)];
  1591. var files = zipEntries.files;
  1592. if (options.checkCRC32) {
  1593. for (var i = 0; i < files.length; i++) {
  1594. promises.push(checkEntryCRC32(files[i]));
  1595. }
  1596. }
  1597. return external.Promise.all(promises);
  1598. }).then(function addFiles(results) {
  1599. var zipEntries = results.shift();
  1600. var files = zipEntries.files;
  1601. for (var i = 0; i < files.length; i++) {
  1602. var input = files[i];
  1603.  
  1604. var unsafeName = input.fileNameStr;
  1605. var safeName = utils.resolve(input.fileNameStr);
  1606.  
  1607. zip.file(safeName, input.decompressed, {
  1608. binary: true,
  1609. optimizedBinaryString: true,
  1610. date: input.date,
  1611. dir: input.dir,
  1612. comment: input.fileCommentStr.length ? input.fileCommentStr : null,
  1613. unixPermissions: input.unixPermissions,
  1614. dosPermissions: input.dosPermissions,
  1615. createFolders: options.createFolders
  1616. });
  1617. if (!input.dir) {
  1618. zip.file(safeName).unsafeOriginalName = unsafeName;
  1619. }
  1620. }
  1621. if (zipEntries.zipComment.length) {
  1622. zip.comment = zipEntries.zipComment;
  1623. }
  1624.  
  1625. return zip;
  1626. });
  1627. };
  1628.  
  1629. },{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){
  1630. "use strict";
  1631.  
  1632. var utils = require("../utils");
  1633. var GenericWorker = require("../stream/GenericWorker");
  1634.  
  1635. /**
  1636. * A worker that use a nodejs stream as source.
  1637. * @constructor
  1638. * @param {String} filename the name of the file entry for this stream.
  1639. * @param {Readable} stream the nodejs stream.
  1640. */
  1641. function NodejsStreamInputAdapter(filename, stream) {
  1642. GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
  1643. this._upstreamEnded = false;
  1644. this._bindStream(stream);
  1645. }
  1646.  
  1647. utils.inherits(NodejsStreamInputAdapter, GenericWorker);
  1648.  
  1649. /**
  1650. * Prepare the stream and bind the callbacks on it.
  1651. * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
  1652. * @param {Stream} stream the nodejs stream to use.
  1653. */
  1654. NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
  1655. var self = this;
  1656. this._stream = stream;
  1657. stream.pause();
  1658. stream
  1659. .on("data", function (chunk) {
  1660. self.push({
  1661. data: chunk,
  1662. meta : {
  1663. percent : 0
  1664. }
  1665. });
  1666. })
  1667. .on("error", function (e) {
  1668. if(self.isPaused) {
  1669. this.generatedError = e;
  1670. } else {
  1671. self.error(e);
  1672. }
  1673. })
  1674. .on("end", function () {
  1675. if(self.isPaused) {
  1676. self._upstreamEnded = true;
  1677. } else {
  1678. self.end();
  1679. }
  1680. });
  1681. };
  1682. NodejsStreamInputAdapter.prototype.pause = function () {
  1683. if(!GenericWorker.prototype.pause.call(this)) {
  1684. return false;
  1685. }
  1686. this._stream.pause();
  1687. return true;
  1688. };
  1689. NodejsStreamInputAdapter.prototype.resume = function () {
  1690. if(!GenericWorker.prototype.resume.call(this)) {
  1691. return false;
  1692. }
  1693.  
  1694. if(this._upstreamEnded) {
  1695. this.end();
  1696. } else {
  1697. this._stream.resume();
  1698. }
  1699.  
  1700. return true;
  1701. };
  1702.  
  1703. module.exports = NodejsStreamInputAdapter;
  1704.  
  1705. },{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){
  1706. "use strict";
  1707.  
  1708. var Readable = require("readable-stream").Readable;
  1709.  
  1710. var utils = require("../utils");
  1711. utils.inherits(NodejsStreamOutputAdapter, Readable);
  1712.  
  1713. /**
  1714. * A nodejs stream using a worker as source.
  1715. * @see the SourceWrapper in http://nodejs.org/api/stream.html
  1716. * @constructor
  1717. * @param {StreamHelper} helper the helper wrapping the worker
  1718. * @param {Object} options the nodejs stream options
  1719. * @param {Function} updateCb the update callback.
  1720. */
  1721. function NodejsStreamOutputAdapter(helper, options, updateCb) {
  1722. Readable.call(this, options);
  1723. this._helper = helper;
  1724.  
  1725. var self = this;
  1726. helper.on("data", function (data, meta) {
  1727. if (!self.push(data)) {
  1728. self._helper.pause();
  1729. }
  1730. if(updateCb) {
  1731. updateCb(meta);
  1732. }
  1733. })
  1734. .on("error", function(e) {
  1735. self.emit("error", e);
  1736. })
  1737. .on("end", function () {
  1738. self.push(null);
  1739. });
  1740. }
  1741.  
  1742.  
  1743. NodejsStreamOutputAdapter.prototype._read = function() {
  1744. this._helper.resume();
  1745. };
  1746.  
  1747. module.exports = NodejsStreamOutputAdapter;
  1748.  
  1749. },{"../utils":32,"readable-stream":16}],14:[function(require,module,exports){
  1750. "use strict";
  1751.  
  1752. module.exports = {
  1753. /**
  1754. * True if this is running in Nodejs, will be undefined in a browser.
  1755. * In a browser, browserify won't include this file and the whole module
  1756. * will be resolved an empty object.
  1757. */
  1758. isNode : typeof Buffer !== "undefined",
  1759. /**
  1760. * Create a new nodejs Buffer from an existing content.
  1761. * @param {Object} data the data to pass to the constructor.
  1762. * @param {String} encoding the encoding to use.
  1763. * @return {Buffer} a new Buffer.
  1764. */
  1765. newBufferFrom: function(data, encoding) {
  1766. if (Buffer.from && Buffer.from !== Uint8Array.from) {
  1767. return Buffer.from(data, encoding);
  1768. } else {
  1769. if (typeof data === "number") {
  1770. // Safeguard for old Node.js versions. On newer versions,
  1771. // Buffer.from(number) / Buffer(number, encoding) already throw.
  1772. throw new Error("The \"data\" argument must not be a number");
  1773. }
  1774. return new Buffer(data, encoding);
  1775. }
  1776. },
  1777. /**
  1778. * Create a new nodejs Buffer with the specified size.
  1779. * @param {Integer} size the size of the buffer.
  1780. * @return {Buffer} a new Buffer.
  1781. */
  1782. allocBuffer: function (size) {
  1783. if (Buffer.alloc) {
  1784. return Buffer.alloc(size);
  1785. } else {
  1786. var buf = new Buffer(size);
  1787. buf.fill(0);
  1788. return buf;
  1789. }
  1790. },
  1791. /**
  1792. * Find out if an object is a Buffer.
  1793. * @param {Object} b the object to test.
  1794. * @return {Boolean} true if the object is a Buffer, false otherwise.
  1795. */
  1796. isBuffer : function(b){
  1797. return Buffer.isBuffer(b);
  1798. },
  1799.  
  1800. isStream : function (obj) {
  1801. return obj &&
  1802. typeof obj.on === "function" &&
  1803. typeof obj.pause === "function" &&
  1804. typeof obj.resume === "function";
  1805. }
  1806. };
  1807.  
  1808. },{}],15:[function(require,module,exports){
  1809. "use strict";
  1810. var utf8 = require("./utf8");
  1811. var utils = require("./utils");
  1812. var GenericWorker = require("./stream/GenericWorker");
  1813. var StreamHelper = require("./stream/StreamHelper");
  1814. var defaults = require("./defaults");
  1815. var CompressedObject = require("./compressedObject");
  1816. var ZipObject = require("./zipObject");
  1817. var generate = require("./generate");
  1818. var nodejsUtils = require("./nodejsUtils");
  1819. var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
  1820.  
  1821.  
  1822. /**
  1823. * Add a file in the current folder.
  1824. * @private
  1825. * @param {string} name the name of the file
  1826. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  1827. * @param {Object} originalOptions the options of the file
  1828. * @return {Object} the new file.
  1829. */
  1830. var fileAdd = function(name, data, originalOptions) {
  1831. // be sure sub folders exist
  1832. var dataType = utils.getTypeOf(data),
  1833. parent;
  1834.  
  1835.  
  1836. /*
  1837. * Correct options.
  1838. */
  1839.  
  1840. var o = utils.extend(originalOptions || {}, defaults);
  1841. o.date = o.date || new Date();
  1842. if (o.compression !== null) {
  1843. o.compression = o.compression.toUpperCase();
  1844. }
  1845.  
  1846. if (typeof o.unixPermissions === "string") {
  1847. o.unixPermissions = parseInt(o.unixPermissions, 8);
  1848. }
  1849.  
  1850. // UNX_IFDIR 0040000 see zipinfo.c
  1851. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  1852. o.dir = true;
  1853. }
  1854. // Bit 4 Directory
  1855. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  1856. o.dir = true;
  1857. }
  1858.  
  1859. if (o.dir) {
  1860. name = forceTrailingSlash(name);
  1861. }
  1862. if (o.createFolders && (parent = parentFolder(name))) {
  1863. folderAdd.call(this, parent, true);
  1864. }
  1865.  
  1866. var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
  1867. if (!originalOptions || typeof originalOptions.binary === "undefined") {
  1868. o.binary = !isUnicodeString;
  1869. }
  1870.  
  1871.  
  1872. var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
  1873.  
  1874. if (isCompressedEmpty || o.dir || !data || data.length === 0) {
  1875. o.base64 = false;
  1876. o.binary = true;
  1877. data = "";
  1878. o.compression = "STORE";
  1879. dataType = "string";
  1880. }
  1881.  
  1882. /*
  1883. * Convert content to fit.
  1884. */
  1885.  
  1886. var zipObjectContent = null;
  1887. if (data instanceof CompressedObject || data instanceof GenericWorker) {
  1888. zipObjectContent = data;
  1889. } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1890. zipObjectContent = new NodejsStreamInputAdapter(name, data);
  1891. } else {
  1892. zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
  1893. }
  1894.  
  1895. var object = new ZipObject(name, zipObjectContent, o);
  1896. this.files[name] = object;
  1897. /*
  1898. TODO: we can't throw an exception because we have async promises
  1899. (we can have a promise of a Date() for example) but returning a
  1900. promise is useless because file(name, data) returns the JSZip
  1901. object for chaining. Should we break that to allow the user
  1902. to catch the error ?
  1903.  
  1904. return external.Promise.resolve(zipObjectContent)
  1905. .then(function () {
  1906. return object;
  1907. });
  1908. */
  1909. };
  1910.  
  1911. /**
  1912. * Find the parent folder of the path.
  1913. * @private
  1914. * @param {string} path the path to use
  1915. * @return {string} the parent folder, or ""
  1916. */
  1917. var parentFolder = function (path) {
  1918. if (path.slice(-1) === "/") {
  1919. path = path.substring(0, path.length - 1);
  1920. }
  1921. var lastSlash = path.lastIndexOf("/");
  1922. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  1923. };
  1924.  
  1925. /**
  1926. * Returns the path with a slash at the end.
  1927. * @private
  1928. * @param {String} path the path to check.
  1929. * @return {String} the path with a trailing slash.
  1930. */
  1931. var forceTrailingSlash = function(path) {
  1932. // Check the name ends with a /
  1933. if (path.slice(-1) !== "/") {
  1934. path += "/"; // IE doesn't like substr(-1)
  1935. }
  1936. return path;
  1937. };
  1938.  
  1939. /**
  1940. * Add a (sub) folder in the current folder.
  1941. * @private
  1942. * @param {string} name the folder's name
  1943. * @param {boolean=} [createFolders] If true, automatically create sub
  1944. * folders. Defaults to false.
  1945. * @return {Object} the new folder.
  1946. */
  1947. var folderAdd = function(name, createFolders) {
  1948. createFolders = (typeof createFolders !== "undefined") ? createFolders : defaults.createFolders;
  1949.  
  1950. name = forceTrailingSlash(name);
  1951.  
  1952. // Does this folder already exist?
  1953. if (!this.files[name]) {
  1954. fileAdd.call(this, name, null, {
  1955. dir: true,
  1956. createFolders: createFolders
  1957. });
  1958. }
  1959. return this.files[name];
  1960. };
  1961.  
  1962. /**
  1963. * Cross-window, cross-Node-context regular expression detection
  1964. * @param {Object} object Anything
  1965. * @return {Boolean} true if the object is a regular expression,
  1966. * false otherwise
  1967. */
  1968. function isRegExp(object) {
  1969. return Object.prototype.toString.call(object) === "[object RegExp]";
  1970. }
  1971.  
  1972. // return the actual prototype of JSZip
  1973. var out = {
  1974. /**
  1975. * @see loadAsync
  1976. */
  1977. load: function() {
  1978. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1979. },
  1980.  
  1981.  
  1982. /**
  1983. * Call a callback function for each entry at this folder level.
  1984. * @param {Function} cb the callback function:
  1985. * function (relativePath, file) {...}
  1986. * It takes 2 arguments : the relative path and the file.
  1987. */
  1988. forEach: function(cb) {
  1989. var filename, relativePath, file;
  1990. // ignore warning about unwanted properties because this.files is a null prototype object
  1991. /* eslint-disable-next-line guard-for-in */
  1992. for (filename in this.files) {
  1993. file = this.files[filename];
  1994. relativePath = filename.slice(this.root.length, filename.length);
  1995. if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
  1996. cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
  1997. }
  1998. }
  1999. },
  2000.  
  2001. /**
  2002. * Filter nested files/folders with the specified function.
  2003. * @param {Function} search the predicate to use :
  2004. * function (relativePath, file) {...}
  2005. * It takes 2 arguments : the relative path and the file.
  2006. * @return {Array} An array of matching elements.
  2007. */
  2008. filter: function(search) {
  2009. var result = [];
  2010. this.forEach(function (relativePath, entry) {
  2011. if (search(relativePath, entry)) { // the file matches the function
  2012. result.push(entry);
  2013. }
  2014.  
  2015. });
  2016. return result;
  2017. },
  2018.  
  2019. /**
  2020. * Add a file to the zip file, or search a file.
  2021. * @param {string|RegExp} name The name of the file to add (if data is defined),
  2022. * the name of the file to find (if no data) or a regex to match files.
  2023. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  2024. * @param {Object} o File options
  2025. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  2026. * a file (when searching by string) or an array of files (when searching by regex).
  2027. */
  2028. file: function(name, data, o) {
  2029. if (arguments.length === 1) {
  2030. if (isRegExp(name)) {
  2031. var regexp = name;
  2032. return this.filter(function(relativePath, file) {
  2033. return !file.dir && regexp.test(relativePath);
  2034. });
  2035. }
  2036. else { // text
  2037. var obj = this.files[this.root + name];
  2038. if (obj && !obj.dir) {
  2039. return obj;
  2040. } else {
  2041. return null;
  2042. }
  2043. }
  2044. }
  2045. else { // more than one argument : we have data !
  2046. name = this.root + name;
  2047. fileAdd.call(this, name, data, o);
  2048. }
  2049. return this;
  2050. },
  2051.  
  2052. /**
  2053. * Add a directory to the zip file, or search.
  2054. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  2055. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  2056. */
  2057. folder: function(arg) {
  2058. if (!arg) {
  2059. return this;
  2060. }
  2061.  
  2062. if (isRegExp(arg)) {
  2063. return this.filter(function(relativePath, file) {
  2064. return file.dir && arg.test(relativePath);
  2065. });
  2066. }
  2067.  
  2068. // else, name is a new folder
  2069. var name = this.root + arg;
  2070. var newFolder = folderAdd.call(this, name);
  2071.  
  2072. // Allow chaining by returning a new object with this folder as the root
  2073. var ret = this.clone();
  2074. ret.root = newFolder.name;
  2075. return ret;
  2076. },
  2077.  
  2078. /**
  2079. * Delete a file, or a directory and all sub-files, from the zip
  2080. * @param {string} name the name of the file to delete
  2081. * @return {JSZip} this JSZip object
  2082. */
  2083. remove: function(name) {
  2084. name = this.root + name;
  2085. var file = this.files[name];
  2086. if (!file) {
  2087. // Look for any folders
  2088. if (name.slice(-1) !== "/") {
  2089. name += "/";
  2090. }
  2091. file = this.files[name];
  2092. }
  2093.  
  2094. if (file && !file.dir) {
  2095. // file
  2096. delete this.files[name];
  2097. } else {
  2098. // maybe a folder, delete recursively
  2099. var kids = this.filter(function(relativePath, file) {
  2100. return file.name.slice(0, name.length) === name;
  2101. });
  2102. for (var i = 0; i < kids.length; i++) {
  2103. delete this.files[kids[i].name];
  2104. }
  2105. }
  2106.  
  2107. return this;
  2108. },
  2109.  
  2110. /**
  2111. * @deprecated This method has been removed in JSZip 3.0, please check the upgrade guide.
  2112. */
  2113. generate: function() {
  2114. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  2115. },
  2116.  
  2117. /**
  2118. * Generate the complete zip file as an internal stream.
  2119. * @param {Object} options the options to generate the zip file :
  2120. * - compression, "STORE" by default.
  2121. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  2122. * @return {StreamHelper} the streamed zip file.
  2123. */
  2124. generateInternalStream: function(options) {
  2125. var worker, opts = {};
  2126. try {
  2127. opts = utils.extend(options || {}, {
  2128. streamFiles: false,
  2129. compression: "STORE",
  2130. compressionOptions : null,
  2131. type: "",
  2132. platform: "DOS",
  2133. comment: null,
  2134. mimeType: "application/zip",
  2135. encodeFileName: utf8.utf8encode
  2136. });
  2137.  
  2138. opts.type = opts.type.toLowerCase();
  2139. opts.compression = opts.compression.toUpperCase();
  2140.  
  2141. // "binarystring" is preferred but the internals use "string".
  2142. if(opts.type === "binarystring") {
  2143. opts.type = "string";
  2144. }
  2145.  
  2146. if (!opts.type) {
  2147. throw new Error("No output type specified.");
  2148. }
  2149.  
  2150. utils.checkSupport(opts.type);
  2151.  
  2152. // accept nodejs `process.platform`
  2153. if(
  2154. opts.platform === "darwin" ||
  2155. opts.platform === "freebsd" ||
  2156. opts.platform === "linux" ||
  2157. opts.platform === "sunos"
  2158. ) {
  2159. opts.platform = "UNIX";
  2160. }
  2161. if (opts.platform === "win32") {
  2162. opts.platform = "DOS";
  2163. }
  2164.  
  2165. var comment = opts.comment || this.comment || "";
  2166. worker = generate.generateWorker(this, opts, comment);
  2167. } catch (e) {
  2168. worker = new GenericWorker("error");
  2169. worker.error(e);
  2170. }
  2171. return new StreamHelper(worker, opts.type || "string", opts.mimeType);
  2172. },
  2173. /**
  2174. * Generate the complete zip file asynchronously.
  2175. * @see generateInternalStream
  2176. */
  2177. generateAsync: function(options, onUpdate) {
  2178. return this.generateInternalStream(options).accumulate(onUpdate);
  2179. },
  2180. /**
  2181. * Generate the complete zip file asynchronously.
  2182. * @see generateInternalStream
  2183. */
  2184. generateNodeStream: function(options, onUpdate) {
  2185. options = options || {};
  2186. if (!options.type) {
  2187. options.type = "nodebuffer";
  2188. }
  2189. return this.generateInternalStream(options).toNodejsStream(onUpdate);
  2190. }
  2191. };
  2192. module.exports = out;
  2193.  
  2194. },{"./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){
  2195. "use strict";
  2196. /*
  2197. * This file is used by module bundlers (browserify/webpack/etc) when
  2198. * including a stream implementation. We use "readable-stream" to get a
  2199. * consistent behavior between nodejs versions but bundlers often have a shim
  2200. * for "stream". Using this shim greatly improve the compatibility and greatly
  2201. * reduce the final size of the bundle (only one stream implementation, not
  2202. * two).
  2203. */
  2204. module.exports = require("stream");
  2205.  
  2206. },{"stream":undefined}],17:[function(require,module,exports){
  2207. "use strict";
  2208. var DataReader = require("./DataReader");
  2209. var utils = require("../utils");
  2210.  
  2211. function ArrayReader(data) {
  2212. DataReader.call(this, data);
  2213. for(var i = 0; i < this.data.length; i++) {
  2214. data[i] = data[i] & 0xFF;
  2215. }
  2216. }
  2217. utils.inherits(ArrayReader, DataReader);
  2218. /**
  2219. * @see DataReader.byteAt
  2220. */
  2221. ArrayReader.prototype.byteAt = function(i) {
  2222. return this.data[this.zero + i];
  2223. };
  2224. /**
  2225. * @see DataReader.lastIndexOfSignature
  2226. */
  2227. ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  2228. var sig0 = sig.charCodeAt(0),
  2229. sig1 = sig.charCodeAt(1),
  2230. sig2 = sig.charCodeAt(2),
  2231. sig3 = sig.charCodeAt(3);
  2232. for (var i = this.length - 4; i >= 0; --i) {
  2233. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  2234. return i - this.zero;
  2235. }
  2236. }
  2237.  
  2238. return -1;
  2239. };
  2240. /**
  2241. * @see DataReader.readAndCheckSignature
  2242. */
  2243. ArrayReader.prototype.readAndCheckSignature = function (sig) {
  2244. var sig0 = sig.charCodeAt(0),
  2245. sig1 = sig.charCodeAt(1),
  2246. sig2 = sig.charCodeAt(2),
  2247. sig3 = sig.charCodeAt(3),
  2248. data = this.readData(4);
  2249. return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
  2250. };
  2251. /**
  2252. * @see DataReader.readData
  2253. */
  2254. ArrayReader.prototype.readData = function(size) {
  2255. this.checkOffset(size);
  2256. if(size === 0) {
  2257. return [];
  2258. }
  2259. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  2260. this.index += size;
  2261. return result;
  2262. };
  2263. module.exports = ArrayReader;
  2264.  
  2265. },{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){
  2266. "use strict";
  2267. var utils = require("../utils");
  2268.  
  2269. function DataReader(data) {
  2270. this.data = data; // type : see implementation
  2271. this.length = data.length;
  2272. this.index = 0;
  2273. this.zero = 0;
  2274. }
  2275. DataReader.prototype = {
  2276. /**
  2277. * Check that the offset will not go too far.
  2278. * @param {string} offset the additional offset to check.
  2279. * @throws {Error} an Error if the offset is out of bounds.
  2280. */
  2281. checkOffset: function(offset) {
  2282. this.checkIndex(this.index + offset);
  2283. },
  2284. /**
  2285. * Check that the specified index will not be too far.
  2286. * @param {string} newIndex the index to check.
  2287. * @throws {Error} an Error if the index is out of bounds.
  2288. */
  2289. checkIndex: function(newIndex) {
  2290. if (this.length < this.zero + newIndex || newIndex < 0) {
  2291. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  2292. }
  2293. },
  2294. /**
  2295. * Change the index.
  2296. * @param {number} newIndex The new index.
  2297. * @throws {Error} if the new index is out of the data.
  2298. */
  2299. setIndex: function(newIndex) {
  2300. this.checkIndex(newIndex);
  2301. this.index = newIndex;
  2302. },
  2303. /**
  2304. * Skip the next n bytes.
  2305. * @param {number} n the number of bytes to skip.
  2306. * @throws {Error} if the new index is out of the data.
  2307. */
  2308. skip: function(n) {
  2309. this.setIndex(this.index + n);
  2310. },
  2311. /**
  2312. * Get the byte at the specified index.
  2313. * @param {number} i the index to use.
  2314. * @return {number} a byte.
  2315. */
  2316. byteAt: function() {
  2317. // see implementations
  2318. },
  2319. /**
  2320. * Get the next number with a given byte size.
  2321. * @param {number} size the number of bytes to read.
  2322. * @return {number} the corresponding number.
  2323. */
  2324. readInt: function(size) {
  2325. var result = 0,
  2326. i;
  2327. this.checkOffset(size);
  2328. for (i = this.index + size - 1; i >= this.index; i--) {
  2329. result = (result << 8) + this.byteAt(i);
  2330. }
  2331. this.index += size;
  2332. return result;
  2333. },
  2334. /**
  2335. * Get the next string with a given byte size.
  2336. * @param {number} size the number of bytes to read.
  2337. * @return {string} the corresponding string.
  2338. */
  2339. readString: function(size) {
  2340. return utils.transformTo("string", this.readData(size));
  2341. },
  2342. /**
  2343. * Get raw data without conversion, <size> bytes.
  2344. * @param {number} size the number of bytes to read.
  2345. * @return {Object} the raw data, implementation specific.
  2346. */
  2347. readData: function() {
  2348. // see implementations
  2349. },
  2350. /**
  2351. * Find the last occurrence of a zip signature (4 bytes).
  2352. * @param {string} sig the signature to find.
  2353. * @return {number} the index of the last occurrence, -1 if not found.
  2354. */
  2355. lastIndexOfSignature: function() {
  2356. // see implementations
  2357. },
  2358. /**
  2359. * Read the signature (4 bytes) at the current position and compare it with sig.
  2360. * @param {string} sig the expected signature
  2361. * @return {boolean} true if the signature matches, false otherwise.
  2362. */
  2363. readAndCheckSignature: function() {
  2364. // see implementations
  2365. },
  2366. /**
  2367. * Get the next date.
  2368. * @return {Date} the date.
  2369. */
  2370. readDate: function() {
  2371. var dostime = this.readInt(4);
  2372. return new Date(Date.UTC(
  2373. ((dostime >> 25) & 0x7f) + 1980, // year
  2374. ((dostime >> 21) & 0x0f) - 1, // month
  2375. (dostime >> 16) & 0x1f, // day
  2376. (dostime >> 11) & 0x1f, // hour
  2377. (dostime >> 5) & 0x3f, // minute
  2378. (dostime & 0x1f) << 1)); // second
  2379. }
  2380. };
  2381. module.exports = DataReader;
  2382.  
  2383. },{"../utils":32}],19:[function(require,module,exports){
  2384. "use strict";
  2385. var Uint8ArrayReader = require("./Uint8ArrayReader");
  2386. var utils = require("../utils");
  2387.  
  2388. function NodeBufferReader(data) {
  2389. Uint8ArrayReader.call(this, data);
  2390. }
  2391. utils.inherits(NodeBufferReader, Uint8ArrayReader);
  2392.  
  2393. /**
  2394. * @see DataReader.readData
  2395. */
  2396. NodeBufferReader.prototype.readData = function(size) {
  2397. this.checkOffset(size);
  2398. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  2399. this.index += size;
  2400. return result;
  2401. };
  2402. module.exports = NodeBufferReader;
  2403.  
  2404. },{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){
  2405. "use strict";
  2406. var DataReader = require("./DataReader");
  2407. var utils = require("../utils");
  2408.  
  2409. function StringReader(data) {
  2410. DataReader.call(this, data);
  2411. }
  2412. utils.inherits(StringReader, DataReader);
  2413. /**
  2414. * @see DataReader.byteAt
  2415. */
  2416. StringReader.prototype.byteAt = function(i) {
  2417. return this.data.charCodeAt(this.zero + i);
  2418. };
  2419. /**
  2420. * @see DataReader.lastIndexOfSignature
  2421. */
  2422. StringReader.prototype.lastIndexOfSignature = function(sig) {
  2423. return this.data.lastIndexOf(sig) - this.zero;
  2424. };
  2425. /**
  2426. * @see DataReader.readAndCheckSignature
  2427. */
  2428. StringReader.prototype.readAndCheckSignature = function (sig) {
  2429. var data = this.readData(4);
  2430. return sig === data;
  2431. };
  2432. /**
  2433. * @see DataReader.readData
  2434. */
  2435. StringReader.prototype.readData = function(size) {
  2436. this.checkOffset(size);
  2437. // this will work because the constructor applied the "& 0xff" mask.
  2438. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  2439. this.index += size;
  2440. return result;
  2441. };
  2442. module.exports = StringReader;
  2443.  
  2444. },{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){
  2445. "use strict";
  2446. var ArrayReader = require("./ArrayReader");
  2447. var utils = require("../utils");
  2448.  
  2449. function Uint8ArrayReader(data) {
  2450. ArrayReader.call(this, data);
  2451. }
  2452. utils.inherits(Uint8ArrayReader, ArrayReader);
  2453. /**
  2454. * @see DataReader.readData
  2455. */
  2456. Uint8ArrayReader.prototype.readData = function(size) {
  2457. this.checkOffset(size);
  2458. if(size === 0) {
  2459. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  2460. return new Uint8Array(0);
  2461. }
  2462. var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
  2463. this.index += size;
  2464. return result;
  2465. };
  2466. module.exports = Uint8ArrayReader;
  2467.  
  2468. },{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){
  2469. "use strict";
  2470.  
  2471. var utils = require("../utils");
  2472. var support = require("../support");
  2473. var ArrayReader = require("./ArrayReader");
  2474. var StringReader = require("./StringReader");
  2475. var NodeBufferReader = require("./NodeBufferReader");
  2476. var Uint8ArrayReader = require("./Uint8ArrayReader");
  2477.  
  2478. /**
  2479. * Create a reader adapted to the data.
  2480. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
  2481. * @return {DataReader} the data reader.
  2482. */
  2483. module.exports = function (data) {
  2484. var type = utils.getTypeOf(data);
  2485. utils.checkSupport(type);
  2486. if (type === "string" && !support.uint8array) {
  2487. return new StringReader(data);
  2488. }
  2489. if (type === "nodebuffer") {
  2490. return new NodeBufferReader(data);
  2491. }
  2492. if (support.uint8array) {
  2493. return new Uint8ArrayReader(utils.transformTo("uint8array", data));
  2494. }
  2495. return new ArrayReader(utils.transformTo("array", data));
  2496. };
  2497.  
  2498. },{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){
  2499. "use strict";
  2500. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  2501. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  2502. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  2503. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  2504. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  2505. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  2506.  
  2507. },{}],24:[function(require,module,exports){
  2508. "use strict";
  2509.  
  2510. var GenericWorker = require("./GenericWorker");
  2511. var utils = require("../utils");
  2512.  
  2513. /**
  2514. * A worker which convert chunks to a specified type.
  2515. * @constructor
  2516. * @param {String} destType the destination type.
  2517. */
  2518. function ConvertWorker(destType) {
  2519. GenericWorker.call(this, "ConvertWorker to " + destType);
  2520. this.destType = destType;
  2521. }
  2522. utils.inherits(ConvertWorker, GenericWorker);
  2523.  
  2524. /**
  2525. * @see GenericWorker.processChunk
  2526. */
  2527. ConvertWorker.prototype.processChunk = function (chunk) {
  2528. this.push({
  2529. data : utils.transformTo(this.destType, chunk.data),
  2530. meta : chunk.meta
  2531. });
  2532. };
  2533. module.exports = ConvertWorker;
  2534.  
  2535. },{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){
  2536. "use strict";
  2537.  
  2538. var GenericWorker = require("./GenericWorker");
  2539. var crc32 = require("../crc32");
  2540. var utils = require("../utils");
  2541.  
  2542. /**
  2543. * A worker which calculate the crc32 of the data flowing through.
  2544. * @constructor
  2545. */
  2546. function Crc32Probe() {
  2547. GenericWorker.call(this, "Crc32Probe");
  2548. this.withStreamInfo("crc32", 0);
  2549. }
  2550. utils.inherits(Crc32Probe, GenericWorker);
  2551.  
  2552. /**
  2553. * @see GenericWorker.processChunk
  2554. */
  2555. Crc32Probe.prototype.processChunk = function (chunk) {
  2556. this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
  2557. this.push(chunk);
  2558. };
  2559. module.exports = Crc32Probe;
  2560.  
  2561. },{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){
  2562. "use strict";
  2563.  
  2564. var utils = require("../utils");
  2565. var GenericWorker = require("./GenericWorker");
  2566.  
  2567. /**
  2568. * A worker which calculate the total length of the data flowing through.
  2569. * @constructor
  2570. * @param {String} propName the name used to expose the length
  2571. */
  2572. function DataLengthProbe(propName) {
  2573. GenericWorker.call(this, "DataLengthProbe for " + propName);
  2574. this.propName = propName;
  2575. this.withStreamInfo(propName, 0);
  2576. }
  2577. utils.inherits(DataLengthProbe, GenericWorker);
  2578.  
  2579. /**
  2580. * @see GenericWorker.processChunk
  2581. */
  2582. DataLengthProbe.prototype.processChunk = function (chunk) {
  2583. if(chunk) {
  2584. var length = this.streamInfo[this.propName] || 0;
  2585. this.streamInfo[this.propName] = length + chunk.data.length;
  2586. }
  2587. GenericWorker.prototype.processChunk.call(this, chunk);
  2588. };
  2589. module.exports = DataLengthProbe;
  2590.  
  2591.  
  2592. },{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){
  2593. "use strict";
  2594.  
  2595. var utils = require("../utils");
  2596. var GenericWorker = require("./GenericWorker");
  2597.  
  2598. // the size of the generated chunks
  2599. // TODO expose this as a public variable
  2600. var DEFAULT_BLOCK_SIZE = 16 * 1024;
  2601.  
  2602. /**
  2603. * A worker that reads a content and emits chunks.
  2604. * @constructor
  2605. * @param {Promise} dataP the promise of the data to split
  2606. */
  2607. function DataWorker(dataP) {
  2608. GenericWorker.call(this, "DataWorker");
  2609. var self = this;
  2610. this.dataIsReady = false;
  2611. this.index = 0;
  2612. this.max = 0;
  2613. this.data = null;
  2614. this.type = "";
  2615.  
  2616. this._tickScheduled = false;
  2617.  
  2618. dataP.then(function (data) {
  2619. self.dataIsReady = true;
  2620. self.data = data;
  2621. self.max = data && data.length || 0;
  2622. self.type = utils.getTypeOf(data);
  2623. if(!self.isPaused) {
  2624. self._tickAndRepeat();
  2625. }
  2626. }, function (e) {
  2627. self.error(e);
  2628. });
  2629. }
  2630.  
  2631. utils.inherits(DataWorker, GenericWorker);
  2632.  
  2633. /**
  2634. * @see GenericWorker.cleanUp
  2635. */
  2636. DataWorker.prototype.cleanUp = function () {
  2637. GenericWorker.prototype.cleanUp.call(this);
  2638. this.data = null;
  2639. };
  2640.  
  2641. /**
  2642. * @see GenericWorker.resume
  2643. */
  2644. DataWorker.prototype.resume = function () {
  2645. if(!GenericWorker.prototype.resume.call(this)) {
  2646. return false;
  2647. }
  2648.  
  2649. if (!this._tickScheduled && this.dataIsReady) {
  2650. this._tickScheduled = true;
  2651. utils.delay(this._tickAndRepeat, [], this);
  2652. }
  2653. return true;
  2654. };
  2655.  
  2656. /**
  2657. * Trigger a tick a schedule an other call to this function.
  2658. */
  2659. DataWorker.prototype._tickAndRepeat = function() {
  2660. this._tickScheduled = false;
  2661. if(this.isPaused || this.isFinished) {
  2662. return;
  2663. }
  2664. this._tick();
  2665. if(!this.isFinished) {
  2666. utils.delay(this._tickAndRepeat, [], this);
  2667. this._tickScheduled = true;
  2668. }
  2669. };
  2670.  
  2671. /**
  2672. * Read and push a chunk.
  2673. */
  2674. DataWorker.prototype._tick = function() {
  2675.  
  2676. if(this.isPaused || this.isFinished) {
  2677. return false;
  2678. }
  2679.  
  2680. var size = DEFAULT_BLOCK_SIZE;
  2681. var data = null, nextIndex = Math.min(this.max, this.index + size);
  2682. if (this.index >= this.max) {
  2683. // EOF
  2684. return this.end();
  2685. } else {
  2686. switch(this.type) {
  2687. case "string":
  2688. data = this.data.substring(this.index, nextIndex);
  2689. break;
  2690. case "uint8array":
  2691. data = this.data.subarray(this.index, nextIndex);
  2692. break;
  2693. case "array":
  2694. case "nodebuffer":
  2695. data = this.data.slice(this.index, nextIndex);
  2696. break;
  2697. }
  2698. this.index = nextIndex;
  2699. return this.push({
  2700. data : data,
  2701. meta : {
  2702. percent : this.max ? this.index / this.max * 100 : 0
  2703. }
  2704. });
  2705. }
  2706. };
  2707.  
  2708. module.exports = DataWorker;
  2709.  
  2710. },{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){
  2711. "use strict";
  2712.  
  2713. /**
  2714. * A worker that does nothing but passing chunks to the next one. This is like
  2715. * a nodejs stream but with some differences. On the good side :
  2716. * - it works on IE 6-9 without any issue / polyfill
  2717. * - it weights less than the full dependencies bundled with browserify
  2718. * - it forwards errors (no need to declare an error handler EVERYWHERE)
  2719. *
  2720. * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
  2721. * object containing anything (`percent` for example), see each worker for more
  2722. * details. The latter is the real data (String, Uint8Array, etc).
  2723. *
  2724. * @constructor
  2725. * @param {String} name the name of the stream (mainly used for debugging purposes)
  2726. */
  2727. function GenericWorker(name) {
  2728. // the name of the worker
  2729. this.name = name || "default";
  2730. // an object containing metadata about the workers chain
  2731. this.streamInfo = {};
  2732. // an error which happened when the worker was paused
  2733. this.generatedError = null;
  2734. // an object containing metadata to be merged by this worker into the general metadata
  2735. this.extraStreamInfo = {};
  2736. // true if the stream is paused (and should not do anything), false otherwise
  2737. this.isPaused = true;
  2738. // true if the stream is finished (and should not do anything), false otherwise
  2739. this.isFinished = false;
  2740. // true if the stream is locked to prevent further structure updates (pipe), false otherwise
  2741. this.isLocked = false;
  2742. // the event listeners
  2743. this._listeners = {
  2744. "data":[],
  2745. "end":[],
  2746. "error":[]
  2747. };
  2748. // the previous worker, if any
  2749. this.previous = null;
  2750. }
  2751.  
  2752. GenericWorker.prototype = {
  2753. /**
  2754. * Push a chunk to the next workers.
  2755. * @param {Object} chunk the chunk to push
  2756. */
  2757. push : function (chunk) {
  2758. this.emit("data", chunk);
  2759. },
  2760. /**
  2761. * End the stream.
  2762. * @return {Boolean} true if this call ended the worker, false otherwise.
  2763. */
  2764. end : function () {
  2765. if (this.isFinished) {
  2766. return false;
  2767. }
  2768.  
  2769. this.flush();
  2770. try {
  2771. this.emit("end");
  2772. this.cleanUp();
  2773. this.isFinished = true;
  2774. } catch (e) {
  2775. this.emit("error", e);
  2776. }
  2777. return true;
  2778. },
  2779. /**
  2780. * End the stream with an error.
  2781. * @param {Error} e the error which caused the premature end.
  2782. * @return {Boolean} true if this call ended the worker with an error, false otherwise.
  2783. */
  2784. error : function (e) {
  2785. if (this.isFinished) {
  2786. return false;
  2787. }
  2788.  
  2789. if(this.isPaused) {
  2790. this.generatedError = e;
  2791. } else {
  2792. this.isFinished = true;
  2793.  
  2794. this.emit("error", e);
  2795.  
  2796. // in the workers chain exploded in the middle of the chain,
  2797. // the error event will go downward but we also need to notify
  2798. // workers upward that there has been an error.
  2799. if(this.previous) {
  2800. this.previous.error(e);
  2801. }
  2802.  
  2803. this.cleanUp();
  2804. }
  2805. return true;
  2806. },
  2807. /**
  2808. * Add a callback on an event.
  2809. * @param {String} name the name of the event (data, end, error)
  2810. * @param {Function} listener the function to call when the event is triggered
  2811. * @return {GenericWorker} the current object for chainability
  2812. */
  2813. on : function (name, listener) {
  2814. this._listeners[name].push(listener);
  2815. return this;
  2816. },
  2817. /**
  2818. * Clean any references when a worker is ending.
  2819. */
  2820. cleanUp : function () {
  2821. this.streamInfo = this.generatedError = this.extraStreamInfo = null;
  2822. this._listeners = [];
  2823. },
  2824. /**
  2825. * Trigger an event. This will call registered callback with the provided arg.
  2826. * @param {String} name the name of the event (data, end, error)
  2827. * @param {Object} arg the argument to call the callback with.
  2828. */
  2829. emit : function (name, arg) {
  2830. if (this._listeners[name]) {
  2831. for(var i = 0; i < this._listeners[name].length; i++) {
  2832. this._listeners[name][i].call(this, arg);
  2833. }
  2834. }
  2835. },
  2836. /**
  2837. * Chain a worker with an other.
  2838. * @param {Worker} next the worker receiving events from the current one.
  2839. * @return {worker} the next worker for chainability
  2840. */
  2841. pipe : function (next) {
  2842. return next.registerPrevious(this);
  2843. },
  2844. /**
  2845. * Same as `pipe` in the other direction.
  2846. * Using an API with `pipe(next)` is very easy.
  2847. * Implementing the API with the point of view of the next one registering
  2848. * a source is easier, see the ZipFileWorker.
  2849. * @param {Worker} previous the previous worker, sending events to this one
  2850. * @return {Worker} the current worker for chainability
  2851. */
  2852. registerPrevious : function (previous) {
  2853. if (this.isLocked) {
  2854. throw new Error("The stream '" + this + "' has already been used.");
  2855. }
  2856.  
  2857. // sharing the streamInfo...
  2858. this.streamInfo = previous.streamInfo;
  2859. // ... and adding our own bits
  2860. this.mergeStreamInfo();
  2861. this.previous = previous;
  2862. var self = this;
  2863. previous.on("data", function (chunk) {
  2864. self.processChunk(chunk);
  2865. });
  2866. previous.on("end", function () {
  2867. self.end();
  2868. });
  2869. previous.on("error", function (e) {
  2870. self.error(e);
  2871. });
  2872. return this;
  2873. },
  2874. /**
  2875. * Pause the stream so it doesn't send events anymore.
  2876. * @return {Boolean} true if this call paused the worker, false otherwise.
  2877. */
  2878. pause : function () {
  2879. if(this.isPaused || this.isFinished) {
  2880. return false;
  2881. }
  2882. this.isPaused = true;
  2883.  
  2884. if(this.previous) {
  2885. this.previous.pause();
  2886. }
  2887. return true;
  2888. },
  2889. /**
  2890. * Resume a paused stream.
  2891. * @return {Boolean} true if this call resumed the worker, false otherwise.
  2892. */
  2893. resume : function () {
  2894. if(!this.isPaused || this.isFinished) {
  2895. return false;
  2896. }
  2897. this.isPaused = false;
  2898.  
  2899. // if true, the worker tried to resume but failed
  2900. var withError = false;
  2901. if(this.generatedError) {
  2902. this.error(this.generatedError);
  2903. withError = true;
  2904. }
  2905. if(this.previous) {
  2906. this.previous.resume();
  2907. }
  2908.  
  2909. return !withError;
  2910. },
  2911. /**
  2912. * Flush any remaining bytes as the stream is ending.
  2913. */
  2914. flush : function () {},
  2915. /**
  2916. * Process a chunk. This is usually the method overridden.
  2917. * @param {Object} chunk the chunk to process.
  2918. */
  2919. processChunk : function(chunk) {
  2920. this.push(chunk);
  2921. },
  2922. /**
  2923. * Add a key/value to be added in the workers chain streamInfo once activated.
  2924. * @param {String} key the key to use
  2925. * @param {Object} value the associated value
  2926. * @return {Worker} the current worker for chainability
  2927. */
  2928. withStreamInfo : function (key, value) {
  2929. this.extraStreamInfo[key] = value;
  2930. this.mergeStreamInfo();
  2931. return this;
  2932. },
  2933. /**
  2934. * Merge this worker's streamInfo into the chain's streamInfo.
  2935. */
  2936. mergeStreamInfo : function () {
  2937. for(var key in this.extraStreamInfo) {
  2938. if (!Object.prototype.hasOwnProperty.call(this.extraStreamInfo, key)) {
  2939. continue;
  2940. }
  2941. this.streamInfo[key] = this.extraStreamInfo[key];
  2942. }
  2943. },
  2944.  
  2945. /**
  2946. * Lock the stream to prevent further updates on the workers chain.
  2947. * After calling this method, all calls to pipe will fail.
  2948. */
  2949. lock: function () {
  2950. if (this.isLocked) {
  2951. throw new Error("The stream '" + this + "' has already been used.");
  2952. }
  2953. this.isLocked = true;
  2954. if (this.previous) {
  2955. this.previous.lock();
  2956. }
  2957. },
  2958.  
  2959. /**
  2960. *
  2961. * Pretty print the workers chain.
  2962. */
  2963. toString : function () {
  2964. var me = "Worker " + this.name;
  2965. if (this.previous) {
  2966. return this.previous + " -> " + me;
  2967. } else {
  2968. return me;
  2969. }
  2970. }
  2971. };
  2972.  
  2973. module.exports = GenericWorker;
  2974.  
  2975. },{}],29:[function(require,module,exports){
  2976. "use strict";
  2977.  
  2978. var utils = require("../utils");
  2979. var ConvertWorker = require("./ConvertWorker");
  2980. var GenericWorker = require("./GenericWorker");
  2981. var base64 = require("../base64");
  2982. var support = require("../support");
  2983. var external = require("../external");
  2984.  
  2985. var NodejsStreamOutputAdapter = null;
  2986. if (support.nodestream) {
  2987. try {
  2988. NodejsStreamOutputAdapter = require("../nodejs/NodejsStreamOutputAdapter");
  2989. } catch(e) {
  2990. // ignore
  2991. }
  2992. }
  2993.  
  2994. /**
  2995. * Apply the final transformation of the data. If the user wants a Blob for
  2996. * example, it's easier to work with an U8intArray and finally do the
  2997. * ArrayBuffer/Blob conversion.
  2998. * @param {String} type the name of the final type
  2999. * @param {String|Uint8Array|Buffer} content the content to transform
  3000. * @param {String} mimeType the mime type of the content, if applicable.
  3001. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
  3002. */
  3003. function transformZipOutput(type, content, mimeType) {
  3004. switch(type) {
  3005. case "blob" :
  3006. return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType);
  3007. case "base64" :
  3008. return base64.encode(content);
  3009. default :
  3010. return utils.transformTo(type, content);
  3011. }
  3012. }
  3013.  
  3014. /**
  3015. * Concatenate an array of data of the given type.
  3016. * @param {String} type the type of the data in the given array.
  3017. * @param {Array} dataArray the array containing the data chunks to concatenate
  3018. * @return {String|Uint8Array|Buffer} the concatenated data
  3019. * @throws Error if the asked type is unsupported
  3020. */
  3021. function concat (type, dataArray) {
  3022. var i, index = 0, res = null, totalLength = 0;
  3023. for(i = 0; i < dataArray.length; i++) {
  3024. totalLength += dataArray[i].length;
  3025. }
  3026. switch(type) {
  3027. case "string":
  3028. return dataArray.join("");
  3029. case "array":
  3030. return Array.prototype.concat.apply([], dataArray);
  3031. case "uint8array":
  3032. res = new Uint8Array(totalLength);
  3033. for(i = 0; i < dataArray.length; i++) {
  3034. res.set(dataArray[i], index);
  3035. index += dataArray[i].length;
  3036. }
  3037. return res;
  3038. case "nodebuffer":
  3039. return Buffer.concat(dataArray);
  3040. default:
  3041. throw new Error("concat : unsupported type '" + type + "'");
  3042. }
  3043. }
  3044.  
  3045. /**
  3046. * Listen a StreamHelper, accumulate its content and concatenate it into a
  3047. * complete block.
  3048. * @param {StreamHelper} helper the helper to use.
  3049. * @param {Function} updateCallback a callback called on each update. Called
  3050. * with one arg :
  3051. * - the metadata linked to the update received.
  3052. * @return Promise the promise for the accumulation.
  3053. */
  3054. function accumulate(helper, updateCallback) {
  3055. return new external.Promise(function (resolve, reject){
  3056. var dataArray = [];
  3057. var chunkType = helper._internalType,
  3058. resultType = helper._outputType,
  3059. mimeType = helper._mimeType;
  3060. helper
  3061. .on("data", function (data, meta) {
  3062. dataArray.push(data);
  3063. if(updateCallback) {
  3064. updateCallback(meta);
  3065. }
  3066. })
  3067. .on("error", function(err) {
  3068. dataArray = [];
  3069. reject(err);
  3070. })
  3071. .on("end", function (){
  3072. try {
  3073. var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);
  3074. resolve(result);
  3075. } catch (e) {
  3076. reject(e);
  3077. }
  3078. dataArray = [];
  3079. })
  3080. .resume();
  3081. });
  3082. }
  3083.  
  3084. /**
  3085. * An helper to easily use workers outside of JSZip.
  3086. * @constructor
  3087. * @param {Worker} worker the worker to wrap
  3088. * @param {String} outputType the type of data expected by the use
  3089. * @param {String} mimeType the mime type of the content, if applicable.
  3090. */
  3091. function StreamHelper(worker, outputType, mimeType) {
  3092. var internalType = outputType;
  3093. switch(outputType) {
  3094. case "blob":
  3095. case "arraybuffer":
  3096. internalType = "uint8array";
  3097. break;
  3098. case "base64":
  3099. internalType = "string";
  3100. break;
  3101. }
  3102.  
  3103. try {
  3104. // the type used internally
  3105. this._internalType = internalType;
  3106. // the type used to output results
  3107. this._outputType = outputType;
  3108. // the mime type
  3109. this._mimeType = mimeType;
  3110. utils.checkSupport(internalType);
  3111. this._worker = worker.pipe(new ConvertWorker(internalType));
  3112. // the last workers can be rewired without issues but we need to
  3113. // prevent any updates on previous workers.
  3114. worker.lock();
  3115. } catch(e) {
  3116. this._worker = new GenericWorker("error");
  3117. this._worker.error(e);
  3118. }
  3119. }
  3120.  
  3121. StreamHelper.prototype = {
  3122. /**
  3123. * Listen a StreamHelper, accumulate its content and concatenate it into a
  3124. * complete block.
  3125. * @param {Function} updateCb the update callback.
  3126. * @return Promise the promise for the accumulation.
  3127. */
  3128. accumulate : function (updateCb) {
  3129. return accumulate(this, updateCb);
  3130. },
  3131. /**
  3132. * Add a listener on an event triggered on a stream.
  3133. * @param {String} evt the name of the event
  3134. * @param {Function} fn the listener
  3135. * @return {StreamHelper} the current helper.
  3136. */
  3137. on : function (evt, fn) {
  3138. var self = this;
  3139.  
  3140. if(evt === "data") {
  3141. this._worker.on(evt, function (chunk) {
  3142. fn.call(self, chunk.data, chunk.meta);
  3143. });
  3144. } else {
  3145. this._worker.on(evt, function () {
  3146. utils.delay(fn, arguments, self);
  3147. });
  3148. }
  3149. return this;
  3150. },
  3151. /**
  3152. * Resume the flow of chunks.
  3153. * @return {StreamHelper} the current helper.
  3154. */
  3155. resume : function () {
  3156. utils.delay(this._worker.resume, [], this._worker);
  3157. return this;
  3158. },
  3159. /**
  3160. * Pause the flow of chunks.
  3161. * @return {StreamHelper} the current helper.
  3162. */
  3163. pause : function () {
  3164. this._worker.pause();
  3165. return this;
  3166. },
  3167. /**
  3168. * Return a nodejs stream for this helper.
  3169. * @param {Function} updateCb the update callback.
  3170. * @return {NodejsStreamOutputAdapter} the nodejs stream.
  3171. */
  3172. toNodejsStream : function (updateCb) {
  3173. utils.checkSupport("nodestream");
  3174. if (this._outputType !== "nodebuffer") {
  3175. // an object stream containing blob/arraybuffer/uint8array/string
  3176. // is strange and I don't know if it would be useful.
  3177. // I you find this comment and have a good usecase, please open a
  3178. // bug report !
  3179. throw new Error(this._outputType + " is not supported by this method");
  3180. }
  3181.  
  3182. return new NodejsStreamOutputAdapter(this, {
  3183. objectMode : this._outputType !== "nodebuffer"
  3184. }, updateCb);
  3185. }
  3186. };
  3187.  
  3188.  
  3189. module.exports = StreamHelper;
  3190.  
  3191. },{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){
  3192. "use strict";
  3193.  
  3194. exports.base64 = true;
  3195. exports.array = true;
  3196. exports.string = true;
  3197. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  3198. exports.nodebuffer = typeof Buffer !== "undefined";
  3199. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  3200. exports.uint8array = typeof Uint8Array !== "undefined";
  3201.  
  3202. if (typeof ArrayBuffer === "undefined") {
  3203. exports.blob = false;
  3204. }
  3205. else {
  3206. var buffer = new ArrayBuffer(0);
  3207. try {
  3208. exports.blob = new Blob([buffer], {
  3209. type: "application/zip"
  3210. }).size === 0;
  3211. }
  3212. catch (e) {
  3213. try {
  3214. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  3215. var builder = new Builder();
  3216. builder.append(buffer);
  3217. exports.blob = builder.getBlob("application/zip").size === 0;
  3218. }
  3219. catch (e) {
  3220. exports.blob = false;
  3221. }
  3222. }
  3223. }
  3224.  
  3225. try {
  3226. exports.nodestream = !!require("readable-stream").Readable;
  3227. } catch(e) {
  3228. exports.nodestream = false;
  3229. }
  3230.  
  3231. },{"readable-stream":16}],31:[function(require,module,exports){
  3232. "use strict";
  3233.  
  3234. var utils = require("./utils");
  3235. var support = require("./support");
  3236. var nodejsUtils = require("./nodejsUtils");
  3237. var GenericWorker = require("./stream/GenericWorker");
  3238.  
  3239. /**
  3240. * The following functions come from pako, from pako/lib/utils/strings
  3241. * released under the MIT license, see pako https://github.com/nodeca/pako/
  3242. */
  3243.  
  3244. // Table with utf8 lengths (calculated by first byte of sequence)
  3245. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  3246. // because max possible codepoint is 0x10ffff
  3247. var _utf8len = new Array(256);
  3248. for (var i=0; i<256; i++) {
  3249. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  3250. }
  3251. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  3252.  
  3253. // convert string to array (typed, when possible)
  3254. var string2buf = function (str) {
  3255. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  3256.  
  3257. // count binary size
  3258. for (m_pos = 0; m_pos < str_len; m_pos++) {
  3259. c = str.charCodeAt(m_pos);
  3260. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3261. c2 = str.charCodeAt(m_pos+1);
  3262. if ((c2 & 0xfc00) === 0xdc00) {
  3263. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3264. m_pos++;
  3265. }
  3266. }
  3267. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  3268. }
  3269.  
  3270. // allocate buffer
  3271. if (support.uint8array) {
  3272. buf = new Uint8Array(buf_len);
  3273. } else {
  3274. buf = new Array(buf_len);
  3275. }
  3276.  
  3277. // convert
  3278. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  3279. c = str.charCodeAt(m_pos);
  3280. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3281. c2 = str.charCodeAt(m_pos+1);
  3282. if ((c2 & 0xfc00) === 0xdc00) {
  3283. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3284. m_pos++;
  3285. }
  3286. }
  3287. if (c < 0x80) {
  3288. /* one byte */
  3289. buf[i++] = c;
  3290. } else if (c < 0x800) {
  3291. /* two bytes */
  3292. buf[i++] = 0xC0 | (c >>> 6);
  3293. buf[i++] = 0x80 | (c & 0x3f);
  3294. } else if (c < 0x10000) {
  3295. /* three bytes */
  3296. buf[i++] = 0xE0 | (c >>> 12);
  3297. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3298. buf[i++] = 0x80 | (c & 0x3f);
  3299. } else {
  3300. /* four bytes */
  3301. buf[i++] = 0xf0 | (c >>> 18);
  3302. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  3303. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3304. buf[i++] = 0x80 | (c & 0x3f);
  3305. }
  3306. }
  3307.  
  3308. return buf;
  3309. };
  3310.  
  3311. // Calculate max possible position in utf8 buffer,
  3312. // that will not break sequence. If that's not possible
  3313. // - (very small limits) return max size as is.
  3314. //
  3315. // buf[] - utf8 bytes array
  3316. // max - length limit (mandatory);
  3317. var utf8border = function(buf, max) {
  3318. var pos;
  3319.  
  3320. max = max || buf.length;
  3321. if (max > buf.length) { max = buf.length; }
  3322.  
  3323. // go back from last position, until start of sequence found
  3324. pos = max-1;
  3325. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  3326.  
  3327. // Fuckup - very small and broken sequence,
  3328. // return max, because we should return something anyway.
  3329. if (pos < 0) { return max; }
  3330.  
  3331. // If we came to start of buffer - that means vuffer is too small,
  3332. // return max too.
  3333. if (pos === 0) { return max; }
  3334.  
  3335. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  3336. };
  3337.  
  3338. // convert array to string
  3339. var buf2string = function (buf) {
  3340. var i, out, c, c_len;
  3341. var len = buf.length;
  3342.  
  3343. // Reserve max possible length (2 words per char)
  3344. // NB: by unknown reasons, Array is significantly faster for
  3345. // String.fromCharCode.apply than Uint16Array.
  3346. var utf16buf = new Array(len*2);
  3347.  
  3348. for (out=0, i=0; i<len;) {
  3349. c = buf[i++];
  3350. // quick process ascii
  3351. if (c < 0x80) { utf16buf[out++] = c; continue; }
  3352.  
  3353. c_len = _utf8len[c];
  3354. // skip 5 & 6 byte codes
  3355. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  3356.  
  3357. // apply mask on first byte
  3358. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  3359. // join the rest
  3360. while (c_len > 1 && i < len) {
  3361. c = (c << 6) | (buf[i++] & 0x3f);
  3362. c_len--;
  3363. }
  3364.  
  3365. // terminated by end of string?
  3366. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  3367.  
  3368. if (c < 0x10000) {
  3369. utf16buf[out++] = c;
  3370. } else {
  3371. c -= 0x10000;
  3372. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  3373. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  3374. }
  3375. }
  3376.  
  3377. // shrinkBuf(utf16buf, out)
  3378. if (utf16buf.length !== out) {
  3379. if(utf16buf.subarray) {
  3380. utf16buf = utf16buf.subarray(0, out);
  3381. } else {
  3382. utf16buf.length = out;
  3383. }
  3384. }
  3385.  
  3386. // return String.fromCharCode.apply(null, utf16buf);
  3387. return utils.applyFromCharCode(utf16buf);
  3388. };
  3389.  
  3390.  
  3391. // That's all for the pako functions.
  3392.  
  3393.  
  3394. /**
  3395. * Transform a javascript string into an array (typed if possible) of bytes,
  3396. * UTF-8 encoded.
  3397. * @param {String} str the string to encode
  3398. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  3399. */
  3400. exports.utf8encode = function utf8encode(str) {
  3401. if (support.nodebuffer) {
  3402. return nodejsUtils.newBufferFrom(str, "utf-8");
  3403. }
  3404.  
  3405. return string2buf(str);
  3406. };
  3407.  
  3408.  
  3409. /**
  3410. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  3411. * string into a javascript string.
  3412. * @param {Array|Uint8Array|Buffer} buf the data de decode
  3413. * @return {String} the decoded string.
  3414. */
  3415. exports.utf8decode = function utf8decode(buf) {
  3416. if (support.nodebuffer) {
  3417. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  3418. }
  3419.  
  3420. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  3421.  
  3422. return buf2string(buf);
  3423. };
  3424.  
  3425. /**
  3426. * A worker to decode utf8 encoded binary chunks into string chunks.
  3427. * @constructor
  3428. */
  3429. function Utf8DecodeWorker() {
  3430. GenericWorker.call(this, "utf-8 decode");
  3431. // the last bytes if a chunk didn't end with a complete codepoint.
  3432. this.leftOver = null;
  3433. }
  3434. utils.inherits(Utf8DecodeWorker, GenericWorker);
  3435.  
  3436. /**
  3437. * @see GenericWorker.processChunk
  3438. */
  3439. Utf8DecodeWorker.prototype.processChunk = function (chunk) {
  3440.  
  3441. var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
  3442.  
  3443. // 1st step, re-use what's left of the previous chunk
  3444. if (this.leftOver && this.leftOver.length) {
  3445. if(support.uint8array) {
  3446. var previousData = data;
  3447. data = new Uint8Array(previousData.length + this.leftOver.length);
  3448. data.set(this.leftOver, 0);
  3449. data.set(previousData, this.leftOver.length);
  3450. } else {
  3451. data = this.leftOver.concat(data);
  3452. }
  3453. this.leftOver = null;
  3454. }
  3455.  
  3456. var nextBoundary = utf8border(data);
  3457. var usableData = data;
  3458. if (nextBoundary !== data.length) {
  3459. if (support.uint8array) {
  3460. usableData = data.subarray(0, nextBoundary);
  3461. this.leftOver = data.subarray(nextBoundary, data.length);
  3462. } else {
  3463. usableData = data.slice(0, nextBoundary);
  3464. this.leftOver = data.slice(nextBoundary, data.length);
  3465. }
  3466. }
  3467.  
  3468. this.push({
  3469. data : exports.utf8decode(usableData),
  3470. meta : chunk.meta
  3471. });
  3472. };
  3473.  
  3474. /**
  3475. * @see GenericWorker.flush
  3476. */
  3477. Utf8DecodeWorker.prototype.flush = function () {
  3478. if(this.leftOver && this.leftOver.length) {
  3479. this.push({
  3480. data : exports.utf8decode(this.leftOver),
  3481. meta : {}
  3482. });
  3483. this.leftOver = null;
  3484. }
  3485. };
  3486. exports.Utf8DecodeWorker = Utf8DecodeWorker;
  3487.  
  3488. /**
  3489. * A worker to endcode string chunks into utf8 encoded binary chunks.
  3490. * @constructor
  3491. */
  3492. function Utf8EncodeWorker() {
  3493. GenericWorker.call(this, "utf-8 encode");
  3494. }
  3495. utils.inherits(Utf8EncodeWorker, GenericWorker);
  3496.  
  3497. /**
  3498. * @see GenericWorker.processChunk
  3499. */
  3500. Utf8EncodeWorker.prototype.processChunk = function (chunk) {
  3501. this.push({
  3502. data : exports.utf8encode(chunk.data),
  3503. meta : chunk.meta
  3504. });
  3505. };
  3506. exports.Utf8EncodeWorker = Utf8EncodeWorker;
  3507.  
  3508. },{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){
  3509. "use strict";
  3510.  
  3511. var support = require("./support");
  3512. var base64 = require("./base64");
  3513. var nodejsUtils = require("./nodejsUtils");
  3514. var external = require("./external");
  3515. require("setimmediate");
  3516.  
  3517.  
  3518. /**
  3519. * Convert a string that pass as a "binary string": it should represent a byte
  3520. * array but may have > 255 char codes. Be sure to take only the first byte
  3521. * and returns the byte array.
  3522. * @param {String} str the string to transform.
  3523. * @return {Array|Uint8Array} the string in a binary format.
  3524. */
  3525. function string2binary(str) {
  3526. var result = null;
  3527. if (support.uint8array) {
  3528. result = new Uint8Array(str.length);
  3529. } else {
  3530. result = new Array(str.length);
  3531. }
  3532. return stringToArrayLike(str, result);
  3533. }
  3534.  
  3535. /**
  3536. * Create a new blob with the given content and the given type.
  3537. * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use
  3538. * an Uint8Array because the stock browser of android 4 won't accept it (it
  3539. * will be silently converted to a string, "[object Uint8Array]").
  3540. *
  3541. * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:
  3542. * when a large amount of Array is used to create the Blob, the amount of
  3543. * memory consumed is nearly 100 times the original data amount.
  3544. *
  3545. * @param {String} type the mime type of the blob.
  3546. * @return {Blob} the created blob.
  3547. */
  3548. exports.newBlob = function(part, type) {
  3549. exports.checkSupport("blob");
  3550.  
  3551. try {
  3552. // Blob constructor
  3553. return new Blob([part], {
  3554. type: type
  3555. });
  3556. }
  3557. catch (e) {
  3558.  
  3559. try {
  3560. // deprecated, browser only, old way
  3561. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  3562. var builder = new Builder();
  3563. builder.append(part);
  3564. return builder.getBlob(type);
  3565. }
  3566. catch (e) {
  3567.  
  3568. // well, fuck ?!
  3569. throw new Error("Bug : can't construct the Blob.");
  3570. }
  3571. }
  3572.  
  3573.  
  3574. };
  3575. /**
  3576. * The identity function.
  3577. * @param {Object} input the input.
  3578. * @return {Object} the same input.
  3579. */
  3580. function identity(input) {
  3581. return input;
  3582. }
  3583.  
  3584. /**
  3585. * Fill in an array with a string.
  3586. * @param {String} str the string to use.
  3587. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  3588. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  3589. */
  3590. function stringToArrayLike(str, array) {
  3591. for (var i = 0; i < str.length; ++i) {
  3592. array[i] = str.charCodeAt(i) & 0xFF;
  3593. }
  3594. return array;
  3595. }
  3596.  
  3597. /**
  3598. * An helper for the function arrayLikeToString.
  3599. * This contains static information and functions that
  3600. * can be optimized by the browser JIT compiler.
  3601. */
  3602. var arrayToStringHelper = {
  3603. /**
  3604. * Transform an array of int into a string, chunk by chunk.
  3605. * See the performances notes on arrayLikeToString.
  3606. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3607. * @param {String} type the type of the array.
  3608. * @param {Integer} chunk the chunk size.
  3609. * @return {String} the resulting string.
  3610. * @throws Error if the chunk is too big for the stack.
  3611. */
  3612. stringifyByChunk: function(array, type, chunk) {
  3613. var result = [], k = 0, len = array.length;
  3614. // shortcut
  3615. if (len <= chunk) {
  3616. return String.fromCharCode.apply(null, array);
  3617. }
  3618. while (k < len) {
  3619. if (type === "array" || type === "nodebuffer") {
  3620. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  3621. }
  3622. else {
  3623. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  3624. }
  3625. k += chunk;
  3626. }
  3627. return result.join("");
  3628. },
  3629. /**
  3630. * Call String.fromCharCode on every item in the array.
  3631. * This is the naive implementation, which generate A LOT of intermediate string.
  3632. * This should be used when everything else fail.
  3633. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3634. * @return {String} the result.
  3635. */
  3636. stringifyByChar: function(array){
  3637. var resultStr = "";
  3638. for(var i = 0; i < array.length; i++) {
  3639. resultStr += String.fromCharCode(array[i]);
  3640. }
  3641. return resultStr;
  3642. },
  3643. applyCanBeUsed : {
  3644. /**
  3645. * true if the browser accepts to use String.fromCharCode on Uint8Array
  3646. */
  3647. uint8array : (function () {
  3648. try {
  3649. return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
  3650. } catch (e) {
  3651. return false;
  3652. }
  3653. })(),
  3654. /**
  3655. * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
  3656. */
  3657. nodebuffer : (function () {
  3658. try {
  3659. return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;
  3660. } catch (e) {
  3661. return false;
  3662. }
  3663. })()
  3664. }
  3665. };
  3666.  
  3667. /**
  3668. * Transform an array-like object to a string.
  3669. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3670. * @return {String} the result.
  3671. */
  3672. function arrayLikeToString(array) {
  3673. // Performances notes :
  3674. // --------------------
  3675. // String.fromCharCode.apply(null, array) is the fastest, see
  3676. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  3677. // but the stack is limited (and we can get huge arrays !).
  3678. //
  3679. // result += String.fromCharCode(array[i]); generate too many strings !
  3680. //
  3681. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  3682. // TODO : we now have workers that split the work. Do we still need that ?
  3683. var chunk = 65536,
  3684. type = exports.getTypeOf(array),
  3685. canUseApply = true;
  3686. if (type === "uint8array") {
  3687. canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
  3688. } else if (type === "nodebuffer") {
  3689. canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
  3690. }
  3691.  
  3692. if (canUseApply) {
  3693. while (chunk > 1) {
  3694. try {
  3695. return arrayToStringHelper.stringifyByChunk(array, type, chunk);
  3696. } catch (e) {
  3697. chunk = Math.floor(chunk / 2);
  3698. }
  3699. }
  3700. }
  3701.  
  3702. // no apply or chunk error : slow and painful algorithm
  3703. // default browser on android 4.*
  3704. return arrayToStringHelper.stringifyByChar(array);
  3705. }
  3706.  
  3707. exports.applyFromCharCode = arrayLikeToString;
  3708.  
  3709.  
  3710. /**
  3711. * Copy the data from an array-like to an other array-like.
  3712. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  3713. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  3714. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  3715. */
  3716. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  3717. for (var i = 0; i < arrayFrom.length; i++) {
  3718. arrayTo[i] = arrayFrom[i];
  3719. }
  3720. return arrayTo;
  3721. }
  3722.  
  3723. // a matrix containing functions to transform everything into everything.
  3724. var transform = {};
  3725.  
  3726. // string to ?
  3727. transform["string"] = {
  3728. "string": identity,
  3729. "array": function(input) {
  3730. return stringToArrayLike(input, new Array(input.length));
  3731. },
  3732. "arraybuffer": function(input) {
  3733. return transform["string"]["uint8array"](input).buffer;
  3734. },
  3735. "uint8array": function(input) {
  3736. return stringToArrayLike(input, new Uint8Array(input.length));
  3737. },
  3738. "nodebuffer": function(input) {
  3739. return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));
  3740. }
  3741. };
  3742.  
  3743. // array to ?
  3744. transform["array"] = {
  3745. "string": arrayLikeToString,
  3746. "array": identity,
  3747. "arraybuffer": function(input) {
  3748. return (new Uint8Array(input)).buffer;
  3749. },
  3750. "uint8array": function(input) {
  3751. return new Uint8Array(input);
  3752. },
  3753. "nodebuffer": function(input) {
  3754. return nodejsUtils.newBufferFrom(input);
  3755. }
  3756. };
  3757.  
  3758. // arraybuffer to ?
  3759. transform["arraybuffer"] = {
  3760. "string": function(input) {
  3761. return arrayLikeToString(new Uint8Array(input));
  3762. },
  3763. "array": function(input) {
  3764. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  3765. },
  3766. "arraybuffer": identity,
  3767. "uint8array": function(input) {
  3768. return new Uint8Array(input);
  3769. },
  3770. "nodebuffer": function(input) {
  3771. return nodejsUtils.newBufferFrom(new Uint8Array(input));
  3772. }
  3773. };
  3774.  
  3775. // uint8array to ?
  3776. transform["uint8array"] = {
  3777. "string": arrayLikeToString,
  3778. "array": function(input) {
  3779. return arrayLikeToArrayLike(input, new Array(input.length));
  3780. },
  3781. "arraybuffer": function(input) {
  3782. return input.buffer;
  3783. },
  3784. "uint8array": identity,
  3785. "nodebuffer": function(input) {
  3786. return nodejsUtils.newBufferFrom(input);
  3787. }
  3788. };
  3789.  
  3790. // nodebuffer to ?
  3791. transform["nodebuffer"] = {
  3792. "string": arrayLikeToString,
  3793. "array": function(input) {
  3794. return arrayLikeToArrayLike(input, new Array(input.length));
  3795. },
  3796. "arraybuffer": function(input) {
  3797. return transform["nodebuffer"]["uint8array"](input).buffer;
  3798. },
  3799. "uint8array": function(input) {
  3800. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  3801. },
  3802. "nodebuffer": identity
  3803. };
  3804.  
  3805. /**
  3806. * Transform an input into any type.
  3807. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  3808. * If no output type is specified, the unmodified input will be returned.
  3809. * @param {String} outputType the output type.
  3810. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  3811. * @throws {Error} an Error if the browser doesn't support the requested output type.
  3812. */
  3813. exports.transformTo = function(outputType, input) {
  3814. if (!input) {
  3815. // undefined, null, etc
  3816. // an empty string won't harm.
  3817. input = "";
  3818. }
  3819. if (!outputType) {
  3820. return input;
  3821. }
  3822. exports.checkSupport(outputType);
  3823. var inputType = exports.getTypeOf(input);
  3824. var result = transform[inputType][outputType](input);
  3825. return result;
  3826. };
  3827.  
  3828. /**
  3829. * Resolve all relative path components, "." and "..", in a path. If these relative components
  3830. * traverse above the root then the resulting path will only contain the final path component.
  3831. *
  3832. * All empty components, e.g. "//", are removed.
  3833. * @param {string} path A path with / or \ separators
  3834. * @returns {string} The path with all relative path components resolved.
  3835. */
  3836. exports.resolve = function(path) {
  3837. var parts = path.split("/");
  3838. var result = [];
  3839. for (var index = 0; index < parts.length; index++) {
  3840. var part = parts[index];
  3841. // Allow the first and last component to be empty for trailing slashes.
  3842. if (part === "." || (part === "" && index !== 0 && index !== parts.length - 1)) {
  3843. continue;
  3844. } else if (part === "..") {
  3845. result.pop();
  3846. } else {
  3847. result.push(part);
  3848. }
  3849. }
  3850. return result.join("/");
  3851. };
  3852.  
  3853. /**
  3854. * Return the type of the input.
  3855. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  3856. * @param {Object} input the input to identify.
  3857. * @return {String} the (lowercase) type of the input.
  3858. */
  3859. exports.getTypeOf = function(input) {
  3860. if (typeof input === "string") {
  3861. return "string";
  3862. }
  3863. if (Object.prototype.toString.call(input) === "[object Array]") {
  3864. return "array";
  3865. }
  3866. if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
  3867. return "nodebuffer";
  3868. }
  3869. if (support.uint8array && input instanceof Uint8Array) {
  3870. return "uint8array";
  3871. }
  3872. if (support.arraybuffer && input instanceof ArrayBuffer) {
  3873. return "arraybuffer";
  3874. }
  3875. };
  3876.  
  3877. /**
  3878. * Throw an exception if the type is not supported.
  3879. * @param {String} type the type to check.
  3880. * @throws {Error} an Error if the browser doesn't support the requested type.
  3881. */
  3882. exports.checkSupport = function(type) {
  3883. var supported = support[type.toLowerCase()];
  3884. if (!supported) {
  3885. throw new Error(type + " is not supported by this platform");
  3886. }
  3887. };
  3888.  
  3889. exports.MAX_VALUE_16BITS = 65535;
  3890. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  3891.  
  3892. /**
  3893. * Prettify a string read as binary.
  3894. * @param {string} str the string to prettify.
  3895. * @return {string} a pretty string.
  3896. */
  3897. exports.pretty = function(str) {
  3898. var res = "",
  3899. code, i;
  3900. for (i = 0; i < (str || "").length; i++) {
  3901. code = str.charCodeAt(i);
  3902. res += "\\x" + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  3903. }
  3904. return res;
  3905. };
  3906.  
  3907. /**
  3908. * Defer the call of a function.
  3909. * @param {Function} callback the function to call asynchronously.
  3910. * @param {Array} args the arguments to give to the callback.
  3911. */
  3912. exports.delay = function(callback, args, self) {
  3913. setImmediate(function () {
  3914. callback.apply(self || null, args || []);
  3915. });
  3916. };
  3917.  
  3918. /**
  3919. * Extends a prototype with an other, without calling a constructor with
  3920. * side effects. Inspired by nodejs' `utils.inherits`
  3921. * @param {Function} ctor the constructor to augment
  3922. * @param {Function} superCtor the parent constructor to use
  3923. */
  3924. exports.inherits = function (ctor, superCtor) {
  3925. var Obj = function() {};
  3926. Obj.prototype = superCtor.prototype;
  3927. ctor.prototype = new Obj();
  3928. };
  3929.  
  3930. /**
  3931. * Merge the objects passed as parameters into a new one.
  3932. * @private
  3933. * @param {...Object} var_args All objects to merge.
  3934. * @return {Object} a new object with the data of the others.
  3935. */
  3936. exports.extend = function() {
  3937. var result = {}, i, attr;
  3938. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  3939. for (attr in arguments[i]) {
  3940. if (Object.prototype.hasOwnProperty.call(arguments[i], attr) && typeof result[attr] === "undefined") {
  3941. result[attr] = arguments[i][attr];
  3942. }
  3943. }
  3944. }
  3945. return result;
  3946. };
  3947.  
  3948. /**
  3949. * Transform arbitrary content into a Promise.
  3950. * @param {String} name a name for the content being processed.
  3951. * @param {Object} inputData the content to process.
  3952. * @param {Boolean} isBinary true if the content is not an unicode string
  3953. * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
  3954. * @param {Boolean} isBase64 true if the string content is encoded with base64.
  3955. * @return {Promise} a promise in a format usable by JSZip.
  3956. */
  3957. exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
  3958.  
  3959. // if inputData is already a promise, this flatten it.
  3960. var promise = external.Promise.resolve(inputData).then(function(data) {
  3961.  
  3962.  
  3963. var isBlob = support.blob && (data instanceof Blob || ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(data)) !== -1);
  3964.  
  3965. if (isBlob && typeof FileReader !== "undefined") {
  3966. return new external.Promise(function (resolve, reject) {
  3967. var reader = new FileReader();
  3968.  
  3969. reader.onload = function(e) {
  3970. resolve(e.target.result);
  3971. };
  3972. reader.onerror = function(e) {
  3973. reject(e.target.error);
  3974. };
  3975. reader.readAsArrayBuffer(data);
  3976. });
  3977. } else {
  3978. return data;
  3979. }
  3980. });
  3981.  
  3982. return promise.then(function(data) {
  3983. var dataType = exports.getTypeOf(data);
  3984.  
  3985. if (!dataType) {
  3986. return external.Promise.reject(
  3987. new Error("Can't read the data of '" + name + "'. Is it " +
  3988. "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")
  3989. );
  3990. }
  3991. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  3992. if (dataType === "arraybuffer") {
  3993. data = exports.transformTo("uint8array", data);
  3994. } else if (dataType === "string") {
  3995. if (isBase64) {
  3996. data = base64.decode(data);
  3997. }
  3998. else if (isBinary) {
  3999. // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
  4000. if (isOptimizedBinaryString !== true) {
  4001. // this is a string, not in a base64 format.
  4002. // Be sure that this is a correct "binary string"
  4003. data = string2binary(data);
  4004. }
  4005. }
  4006. }
  4007. return data;
  4008. });
  4009. };
  4010.  
  4011. },{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"setimmediate":54}],33:[function(require,module,exports){
  4012. "use strict";
  4013. var readerFor = require("./reader/readerFor");
  4014. var utils = require("./utils");
  4015. var sig = require("./signature");
  4016. var ZipEntry = require("./zipEntry");
  4017. var support = require("./support");
  4018. // class ZipEntries {{{
  4019. /**
  4020. * All the entries in the zip file.
  4021. * @constructor
  4022. * @param {Object} loadOptions Options for loading the stream.
  4023. */
  4024. function ZipEntries(loadOptions) {
  4025. this.files = [];
  4026. this.loadOptions = loadOptions;
  4027. }
  4028. ZipEntries.prototype = {
  4029. /**
  4030. * Check that the reader is on the specified signature.
  4031. * @param {string} expectedSignature the expected signature.
  4032. * @throws {Error} if it is an other signature.
  4033. */
  4034. checkSignature: function(expectedSignature) {
  4035. if (!this.reader.readAndCheckSignature(expectedSignature)) {
  4036. this.reader.index -= 4;
  4037. var signature = this.reader.readString(4);
  4038. throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  4039. }
  4040. },
  4041. /**
  4042. * Check if the given signature is at the given index.
  4043. * @param {number} askedIndex the index to check.
  4044. * @param {string} expectedSignature the signature to expect.
  4045. * @return {boolean} true if the signature is here, false otherwise.
  4046. */
  4047. isSignature: function(askedIndex, expectedSignature) {
  4048. var currentIndex = this.reader.index;
  4049. this.reader.setIndex(askedIndex);
  4050. var signature = this.reader.readString(4);
  4051. var result = signature === expectedSignature;
  4052. this.reader.setIndex(currentIndex);
  4053. return result;
  4054. },
  4055. /**
  4056. * Read the end of the central directory.
  4057. */
  4058. readBlockEndOfCentral: function() {
  4059. this.diskNumber = this.reader.readInt(2);
  4060. this.diskWithCentralDirStart = this.reader.readInt(2);
  4061. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  4062. this.centralDirRecords = this.reader.readInt(2);
  4063. this.centralDirSize = this.reader.readInt(4);
  4064. this.centralDirOffset = this.reader.readInt(4);
  4065.  
  4066. this.zipCommentLength = this.reader.readInt(2);
  4067. // warning : the encoding depends of the system locale
  4068. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  4069. // On a windows machine, this field is encoded with the localized windows code page.
  4070. var zipComment = this.reader.readData(this.zipCommentLength);
  4071. var decodeParamType = support.uint8array ? "uint8array" : "array";
  4072. // To get consistent behavior with the generation part, we will assume that
  4073. // this is utf8 encoded unless specified otherwise.
  4074. var decodeContent = utils.transformTo(decodeParamType, zipComment);
  4075. this.zipComment = this.loadOptions.decodeFileName(decodeContent);
  4076. },
  4077. /**
  4078. * Read the end of the Zip 64 central directory.
  4079. * Not merged with the method readEndOfCentral :
  4080. * The end of central can coexist with its Zip64 brother,
  4081. * I don't want to read the wrong number of bytes !
  4082. */
  4083. readBlockZip64EndOfCentral: function() {
  4084. this.zip64EndOfCentralSize = this.reader.readInt(8);
  4085. this.reader.skip(4);
  4086. // this.versionMadeBy = this.reader.readString(2);
  4087. // this.versionNeeded = this.reader.readInt(2);
  4088. this.diskNumber = this.reader.readInt(4);
  4089. this.diskWithCentralDirStart = this.reader.readInt(4);
  4090. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  4091. this.centralDirRecords = this.reader.readInt(8);
  4092. this.centralDirSize = this.reader.readInt(8);
  4093. this.centralDirOffset = this.reader.readInt(8);
  4094.  
  4095. this.zip64ExtensibleData = {};
  4096. var extraDataSize = this.zip64EndOfCentralSize - 44,
  4097. index = 0,
  4098. extraFieldId,
  4099. extraFieldLength,
  4100. extraFieldValue;
  4101. while (index < extraDataSize) {
  4102. extraFieldId = this.reader.readInt(2);
  4103. extraFieldLength = this.reader.readInt(4);
  4104. extraFieldValue = this.reader.readData(extraFieldLength);
  4105. this.zip64ExtensibleData[extraFieldId] = {
  4106. id: extraFieldId,
  4107. length: extraFieldLength,
  4108. value: extraFieldValue
  4109. };
  4110. }
  4111. },
  4112. /**
  4113. * Read the end of the Zip 64 central directory locator.
  4114. */
  4115. readBlockZip64EndOfCentralLocator: function() {
  4116. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  4117. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  4118. this.disksCount = this.reader.readInt(4);
  4119. if (this.disksCount > 1) {
  4120. throw new Error("Multi-volumes zip are not supported");
  4121. }
  4122. },
  4123. /**
  4124. * Read the local files, based on the offset read in the central part.
  4125. */
  4126. readLocalFiles: function() {
  4127. var i, file;
  4128. for (i = 0; i < this.files.length; i++) {
  4129. file = this.files[i];
  4130. this.reader.setIndex(file.localHeaderOffset);
  4131. this.checkSignature(sig.LOCAL_FILE_HEADER);
  4132. file.readLocalPart(this.reader);
  4133. file.handleUTF8();
  4134. file.processAttributes();
  4135. }
  4136. },
  4137. /**
  4138. * Read the central directory.
  4139. */
  4140. readCentralDir: function() {
  4141. var file;
  4142.  
  4143. this.reader.setIndex(this.centralDirOffset);
  4144. while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
  4145. file = new ZipEntry({
  4146. zip64: this.zip64
  4147. }, this.loadOptions);
  4148. file.readCentralPart(this.reader);
  4149. this.files.push(file);
  4150. }
  4151.  
  4152. if (this.centralDirRecords !== this.files.length) {
  4153. if (this.centralDirRecords !== 0 && this.files.length === 0) {
  4154. // We expected some records but couldn't find ANY.
  4155. // This is really suspicious, as if something went wrong.
  4156. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  4157. } else {
  4158. // We found some records but not all.
  4159. // Something is wrong but we got something for the user: no error here.
  4160. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
  4161. }
  4162. }
  4163. },
  4164. /**
  4165. * Read the end of central directory.
  4166. */
  4167. readEndOfCentral: function() {
  4168. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  4169. if (offset < 0) {
  4170. // Check if the content is a truncated zip or complete garbage.
  4171. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  4172. // extractible zip for example) but it can give a good hint.
  4173. // If an ajax request was used without responseType, we will also
  4174. // get unreadable data.
  4175. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  4176.  
  4177. if (isGarbage) {
  4178. throw new Error("Can't find end of central directory : is this a zip file ? " +
  4179. "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");
  4180. } else {
  4181. throw new Error("Corrupted zip: can't find end of central directory");
  4182. }
  4183.  
  4184. }
  4185. this.reader.setIndex(offset);
  4186. var endOfCentralDirOffset = offset;
  4187. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  4188. this.readBlockEndOfCentral();
  4189.  
  4190.  
  4191. /* extract from the zip spec :
  4192. 4) If one of the fields in the end of central directory
  4193. record is too small to hold required data, the field
  4194. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  4195. ZIP64 format record should be created.
  4196. 5) The end of central directory record and the
  4197. Zip64 end of central directory locator record must
  4198. reside on the same disk when splitting or spanning
  4199. an archive.
  4200. */
  4201. 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) {
  4202. this.zip64 = true;
  4203.  
  4204. /*
  4205. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  4206. the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents
  4207. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  4208. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  4209. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  4210. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  4211. */
  4212.  
  4213. // should look for a zip64 EOCD locator
  4214. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  4215. if (offset < 0) {
  4216. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
  4217. }
  4218. this.reader.setIndex(offset);
  4219. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  4220. this.readBlockZip64EndOfCentralLocator();
  4221.  
  4222. // now the zip64 EOCD record
  4223. if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
  4224. // console.warn("ZIP64 end of central directory not where expected.");
  4225. this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  4226. if (this.relativeOffsetEndOfZip64CentralDir < 0) {
  4227. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
  4228. }
  4229. }
  4230. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  4231. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  4232. this.readBlockZip64EndOfCentral();
  4233. }
  4234.  
  4235. var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
  4236. if (this.zip64) {
  4237. expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
  4238. expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
  4239. }
  4240.  
  4241. var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  4242.  
  4243. if (extraBytes > 0) {
  4244. // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
  4245. if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
  4246. // The offsets seem wrong, but we have something at the specified offset.
  4247. // So… we keep it.
  4248. } else {
  4249. // the offset is wrong, update the "zero" of the reader
  4250. // this happens if data has been prepended (crx files for example)
  4251. this.reader.zero = extraBytes;
  4252. }
  4253. } else if (extraBytes < 0) {
  4254. throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
  4255. }
  4256. },
  4257. prepareReader: function(data) {
  4258. this.reader = readerFor(data);
  4259. },
  4260. /**
  4261. * Read a zip file and create ZipEntries.
  4262. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  4263. */
  4264. load: function(data) {
  4265. this.prepareReader(data);
  4266. this.readEndOfCentral();
  4267. this.readCentralDir();
  4268. this.readLocalFiles();
  4269. }
  4270. };
  4271. // }}} end of ZipEntries
  4272. module.exports = ZipEntries;
  4273.  
  4274. },{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){
  4275. "use strict";
  4276. var readerFor = require("./reader/readerFor");
  4277. var utils = require("./utils");
  4278. var CompressedObject = require("./compressedObject");
  4279. var crc32fn = require("./crc32");
  4280. var utf8 = require("./utf8");
  4281. var compressions = require("./compressions");
  4282. var support = require("./support");
  4283.  
  4284. var MADE_BY_DOS = 0x00;
  4285. var MADE_BY_UNIX = 0x03;
  4286.  
  4287. /**
  4288. * Find a compression registered in JSZip.
  4289. * @param {string} compressionMethod the method magic to find.
  4290. * @return {Object|null} the JSZip compression object, null if none found.
  4291. */
  4292. var findCompression = function(compressionMethod) {
  4293. for (var method in compressions) {
  4294. if (!Object.prototype.hasOwnProperty.call(compressions, method)) {
  4295. continue;
  4296. }
  4297. if (compressions[method].magic === compressionMethod) {
  4298. return compressions[method];
  4299. }
  4300. }
  4301. return null;
  4302. };
  4303.  
  4304. // class ZipEntry {{{
  4305. /**
  4306. * An entry in the zip file.
  4307. * @constructor
  4308. * @param {Object} options Options of the current file.
  4309. * @param {Object} loadOptions Options for loading the stream.
  4310. */
  4311. function ZipEntry(options, loadOptions) {
  4312. this.options = options;
  4313. this.loadOptions = loadOptions;
  4314. }
  4315. ZipEntry.prototype = {
  4316. /**
  4317. * say if the file is encrypted.
  4318. * @return {boolean} true if the file is encrypted, false otherwise.
  4319. */
  4320. isEncrypted: function() {
  4321. // bit 1 is set
  4322. return (this.bitFlag & 0x0001) === 0x0001;
  4323. },
  4324. /**
  4325. * say if the file has utf-8 filename/comment.
  4326. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  4327. */
  4328. useUTF8: function() {
  4329. // bit 11 is set
  4330. return (this.bitFlag & 0x0800) === 0x0800;
  4331. },
  4332. /**
  4333. * Read the local part of a zip file and add the info in this object.
  4334. * @param {DataReader} reader the reader to use.
  4335. */
  4336. readLocalPart: function(reader) {
  4337. var compression, localExtraFieldsLength;
  4338.  
  4339. // we already know everything from the central dir !
  4340. // If the central dir data are false, we are doomed.
  4341. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  4342. // The less data we get here, the more reliable this should be.
  4343. // Let's skip the whole header and dash to the data !
  4344. reader.skip(22);
  4345. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  4346. // Strangely, the filename here is OK.
  4347. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  4348. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  4349. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  4350. // the internet.
  4351. //
  4352. // I think I see the logic here : the central directory is used to display
  4353. // content and the local directory is used to extract the files. Mixing / and \
  4354. // may be used to display \ to windows users and use / when extracting the files.
  4355. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  4356. this.fileNameLength = reader.readInt(2);
  4357. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  4358. // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
  4359. this.fileName = reader.readData(this.fileNameLength);
  4360. reader.skip(localExtraFieldsLength);
  4361.  
  4362. if (this.compressedSize === -1 || this.uncompressedSize === -1) {
  4363. throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
  4364. }
  4365.  
  4366. compression = findCompression(this.compressionMethod);
  4367. if (compression === null) { // no compression found
  4368. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
  4369. }
  4370. this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
  4371. },
  4372.  
  4373. /**
  4374. * Read the central part of a zip file and add the info in this object.
  4375. * @param {DataReader} reader the reader to use.
  4376. */
  4377. readCentralPart: function(reader) {
  4378. this.versionMadeBy = reader.readInt(2);
  4379. reader.skip(2);
  4380. // this.versionNeeded = reader.readInt(2);
  4381. this.bitFlag = reader.readInt(2);
  4382. this.compressionMethod = reader.readString(2);
  4383. this.date = reader.readDate();
  4384. this.crc32 = reader.readInt(4);
  4385. this.compressedSize = reader.readInt(4);
  4386. this.uncompressedSize = reader.readInt(4);
  4387. var fileNameLength = reader.readInt(2);
  4388. this.extraFieldsLength = reader.readInt(2);
  4389. this.fileCommentLength = reader.readInt(2);
  4390. this.diskNumberStart = reader.readInt(2);
  4391. this.internalFileAttributes = reader.readInt(2);
  4392. this.externalFileAttributes = reader.readInt(4);
  4393. this.localHeaderOffset = reader.readInt(4);
  4394.  
  4395. if (this.isEncrypted()) {
  4396. throw new Error("Encrypted zip are not supported");
  4397. }
  4398.  
  4399. // will be read in the local part, see the comments there
  4400. reader.skip(fileNameLength);
  4401. this.readExtraFields(reader);
  4402. this.parseZIP64ExtraField(reader);
  4403. this.fileComment = reader.readData(this.fileCommentLength);
  4404. },
  4405.  
  4406. /**
  4407. * Parse the external file attributes and get the unix/dos permissions.
  4408. */
  4409. processAttributes: function () {
  4410. this.unixPermissions = null;
  4411. this.dosPermissions = null;
  4412. var madeBy = this.versionMadeBy >> 8;
  4413.  
  4414. // Check if we have the DOS directory flag set.
  4415. // We look for it in the DOS and UNIX permissions
  4416. // but some unknown platform could set it as a compatibility flag.
  4417. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  4418.  
  4419. if(madeBy === MADE_BY_DOS) {
  4420. // first 6 bits (0 to 5)
  4421. this.dosPermissions = this.externalFileAttributes & 0x3F;
  4422. }
  4423.  
  4424. if(madeBy === MADE_BY_UNIX) {
  4425. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  4426. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  4427. }
  4428.  
  4429. // fail safe : if the name ends with a / it probably means a folder
  4430. if (!this.dir && this.fileNameStr.slice(-1) === "/") {
  4431. this.dir = true;
  4432. }
  4433. },
  4434.  
  4435. /**
  4436. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  4437. * @param {DataReader} reader the reader to use.
  4438. */
  4439. parseZIP64ExtraField: function() {
  4440. if (!this.extraFields[0x0001]) {
  4441. return;
  4442. }
  4443.  
  4444. // should be something, preparing the extra reader
  4445. var extraReader = readerFor(this.extraFields[0x0001].value);
  4446.  
  4447. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  4448. // won't let us have more.
  4449. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  4450. this.uncompressedSize = extraReader.readInt(8);
  4451. }
  4452. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  4453. this.compressedSize = extraReader.readInt(8);
  4454. }
  4455. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  4456. this.localHeaderOffset = extraReader.readInt(8);
  4457. }
  4458. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  4459. this.diskNumberStart = extraReader.readInt(4);
  4460. }
  4461. },
  4462. /**
  4463. * Read the central part of a zip file and add the info in this object.
  4464. * @param {DataReader} reader the reader to use.
  4465. */
  4466. readExtraFields: function(reader) {
  4467. var end = reader.index + this.extraFieldsLength,
  4468. extraFieldId,
  4469. extraFieldLength,
  4470. extraFieldValue;
  4471.  
  4472. if (!this.extraFields) {
  4473. this.extraFields = {};
  4474. }
  4475.  
  4476. while (reader.index + 4 < end) {
  4477. extraFieldId = reader.readInt(2);
  4478. extraFieldLength = reader.readInt(2);
  4479. extraFieldValue = reader.readData(extraFieldLength);
  4480.  
  4481. this.extraFields[extraFieldId] = {
  4482. id: extraFieldId,
  4483. length: extraFieldLength,
  4484. value: extraFieldValue
  4485. };
  4486. }
  4487.  
  4488. reader.setIndex(end);
  4489. },
  4490. /**
  4491. * Apply an UTF8 transformation if needed.
  4492. */
  4493. handleUTF8: function() {
  4494. var decodeParamType = support.uint8array ? "uint8array" : "array";
  4495. if (this.useUTF8()) {
  4496. this.fileNameStr = utf8.utf8decode(this.fileName);
  4497. this.fileCommentStr = utf8.utf8decode(this.fileComment);
  4498. } else {
  4499. var upath = this.findExtraFieldUnicodePath();
  4500. if (upath !== null) {
  4501. this.fileNameStr = upath;
  4502. } else {
  4503. // ASCII text or unsupported code page
  4504. var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);
  4505. this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
  4506. }
  4507.  
  4508. var ucomment = this.findExtraFieldUnicodeComment();
  4509. if (ucomment !== null) {
  4510. this.fileCommentStr = ucomment;
  4511. } else {
  4512. // ASCII text or unsupported code page
  4513. var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);
  4514. this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
  4515. }
  4516. }
  4517. },
  4518.  
  4519. /**
  4520. * Find the unicode path declared in the extra field, if any.
  4521. * @return {String} the unicode path, null otherwise.
  4522. */
  4523. findExtraFieldUnicodePath: function() {
  4524. var upathField = this.extraFields[0x7075];
  4525. if (upathField) {
  4526. var extraReader = readerFor(upathField.value);
  4527.  
  4528. // wrong version
  4529. if (extraReader.readInt(1) !== 1) {
  4530. return null;
  4531. }
  4532.  
  4533. // the crc of the filename changed, this field is out of date.
  4534. if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
  4535. return null;
  4536. }
  4537.  
  4538. return utf8.utf8decode(extraReader.readData(upathField.length - 5));
  4539. }
  4540. return null;
  4541. },
  4542.  
  4543. /**
  4544. * Find the unicode comment declared in the extra field, if any.
  4545. * @return {String} the unicode comment, null otherwise.
  4546. */
  4547. findExtraFieldUnicodeComment: function() {
  4548. var ucommentField = this.extraFields[0x6375];
  4549. if (ucommentField) {
  4550. var extraReader = readerFor(ucommentField.value);
  4551.  
  4552. // wrong version
  4553. if (extraReader.readInt(1) !== 1) {
  4554. return null;
  4555. }
  4556.  
  4557. // the crc of the comment changed, this field is out of date.
  4558. if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
  4559. return null;
  4560. }
  4561.  
  4562. return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
  4563. }
  4564. return null;
  4565. }
  4566. };
  4567. module.exports = ZipEntry;
  4568.  
  4569. },{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){
  4570. "use strict";
  4571.  
  4572. var StreamHelper = require("./stream/StreamHelper");
  4573. var DataWorker = require("./stream/DataWorker");
  4574. var utf8 = require("./utf8");
  4575. var CompressedObject = require("./compressedObject");
  4576. var GenericWorker = require("./stream/GenericWorker");
  4577.  
  4578. /**
  4579. * A simple object representing a file in the zip file.
  4580. * @constructor
  4581. * @param {string} name the name of the file
  4582. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  4583. * @param {Object} options the options of the file
  4584. */
  4585. var ZipObject = function(name, data, options) {
  4586. this.name = name;
  4587. this.dir = options.dir;
  4588. this.date = options.date;
  4589. this.comment = options.comment;
  4590. this.unixPermissions = options.unixPermissions;
  4591. this.dosPermissions = options.dosPermissions;
  4592.  
  4593. this._data = data;
  4594. this._dataBinary = options.binary;
  4595. // keep only the compression
  4596. this.options = {
  4597. compression : options.compression,
  4598. compressionOptions : options.compressionOptions
  4599. };
  4600. };
  4601.  
  4602. ZipObject.prototype = {
  4603. /**
  4604. * Create an internal stream for the content of this object.
  4605. * @param {String} type the type of each chunk.
  4606. * @return StreamHelper the stream.
  4607. */
  4608. internalStream: function (type) {
  4609. var result = null, outputType = "string";
  4610. try {
  4611. if (!type) {
  4612. throw new Error("No output type specified.");
  4613. }
  4614. outputType = type.toLowerCase();
  4615. var askUnicodeString = outputType === "string" || outputType === "text";
  4616. if (outputType === "binarystring" || outputType === "text") {
  4617. outputType = "string";
  4618. }
  4619. result = this._decompressWorker();
  4620.  
  4621. var isUnicodeString = !this._dataBinary;
  4622.  
  4623. if (isUnicodeString && !askUnicodeString) {
  4624. result = result.pipe(new utf8.Utf8EncodeWorker());
  4625. }
  4626. if (!isUnicodeString && askUnicodeString) {
  4627. result = result.pipe(new utf8.Utf8DecodeWorker());
  4628. }
  4629. } catch (e) {
  4630. result = new GenericWorker("error");
  4631. result.error(e);
  4632. }
  4633.  
  4634. return new StreamHelper(result, outputType, "");
  4635. },
  4636.  
  4637. /**
  4638. * Prepare the content in the asked type.
  4639. * @param {String} type the type of the result.
  4640. * @param {Function} onUpdate a function to call on each internal update.
  4641. * @return Promise the promise of the result.
  4642. */
  4643. async: function (type, onUpdate) {
  4644. return this.internalStream(type).accumulate(onUpdate);
  4645. },
  4646.  
  4647. /**
  4648. * Prepare the content as a nodejs stream.
  4649. * @param {String} type the type of each chunk.
  4650. * @param {Function} onUpdate a function to call on each internal update.
  4651. * @return Stream the stream.
  4652. */
  4653. nodeStream: function (type, onUpdate) {
  4654. return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
  4655. },
  4656.  
  4657. /**
  4658. * Return a worker for the compressed content.
  4659. * @private
  4660. * @param {Object} compression the compression object to use.
  4661. * @param {Object} compressionOptions the options to use when compressing.
  4662. * @return Worker the worker.
  4663. */
  4664. _compressWorker: function (compression, compressionOptions) {
  4665. if (
  4666. this._data instanceof CompressedObject &&
  4667. this._data.compression.magic === compression.magic
  4668. ) {
  4669. return this._data.getCompressedWorker();
  4670. } else {
  4671. var result = this._decompressWorker();
  4672. if(!this._dataBinary) {
  4673. result = result.pipe(new utf8.Utf8EncodeWorker());
  4674. }
  4675. return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
  4676. }
  4677. },
  4678. /**
  4679. * Return a worker for the decompressed content.
  4680. * @private
  4681. * @return Worker the worker.
  4682. */
  4683. _decompressWorker : function () {
  4684. if (this._data instanceof CompressedObject) {
  4685. return this._data.getContentWorker();
  4686. } else if (this._data instanceof GenericWorker) {
  4687. return this._data;
  4688. } else {
  4689. return new DataWorker(this._data);
  4690. }
  4691. }
  4692. };
  4693.  
  4694. var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
  4695. var removedFn = function () {
  4696. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  4697. };
  4698.  
  4699. for(var i = 0; i < removedMethods.length; i++) {
  4700. ZipObject.prototype[removedMethods[i]] = removedFn;
  4701. }
  4702. module.exports = ZipObject;
  4703.  
  4704. },{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){
  4705. (function (global){
  4706. 'use strict';
  4707. var Mutation = global.MutationObserver || global.WebKitMutationObserver;
  4708.  
  4709. var scheduleDrain;
  4710.  
  4711. {
  4712. if (Mutation) {
  4713. var called = 0;
  4714. var observer = new Mutation(nextTick);
  4715. var element = global.document.createTextNode('');
  4716. observer.observe(element, {
  4717. characterData: true
  4718. });
  4719. scheduleDrain = function () {
  4720. element.data = (called = ++called % 2);
  4721. };
  4722. } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
  4723. var channel = new global.MessageChannel();
  4724. channel.port1.onmessage = nextTick;
  4725. scheduleDrain = function () {
  4726. channel.port2.postMessage(0);
  4727. };
  4728. } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
  4729. scheduleDrain = function () {
  4730.  
  4731. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  4732. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  4733. var scriptEl = global.document.createElement('script');
  4734. scriptEl.onreadystatechange = function () {
  4735. nextTick();
  4736.  
  4737. scriptEl.onreadystatechange = null;
  4738. scriptEl.parentNode.removeChild(scriptEl);
  4739. scriptEl = null;
  4740. };
  4741. global.document.documentElement.appendChild(scriptEl);
  4742. };
  4743. } else {
  4744. scheduleDrain = function () {
  4745. setTimeout(nextTick, 0);
  4746. };
  4747. }
  4748. }
  4749.  
  4750. var draining;
  4751. var queue = [];
  4752. //named nextTick for less confusing stack traces
  4753. function nextTick() {
  4754. draining = true;
  4755. var i, oldQueue;
  4756. var len = queue.length;
  4757. while (len) {
  4758. oldQueue = queue;
  4759. queue = [];
  4760. i = -1;
  4761. while (++i < len) {
  4762. oldQueue[i]();
  4763. }
  4764. len = queue.length;
  4765. }
  4766. draining = false;
  4767. }
  4768.  
  4769. module.exports = immediate;
  4770. function immediate(task) {
  4771. if (queue.push(task) === 1 && !draining) {
  4772. scheduleDrain();
  4773. }
  4774. }
  4775.  
  4776. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4777. },{}],37:[function(require,module,exports){
  4778. 'use strict';
  4779. var immediate = require('immediate');
  4780.  
  4781. /* istanbul ignore next */
  4782. function INTERNAL() {}
  4783.  
  4784. var handlers = {};
  4785.  
  4786. var REJECTED = ['REJECTED'];
  4787. var FULFILLED = ['FULFILLED'];
  4788. var PENDING = ['PENDING'];
  4789.  
  4790. module.exports = Promise;
  4791.  
  4792. function Promise(resolver) {
  4793. if (typeof resolver !== 'function') {
  4794. throw new TypeError('resolver must be a function');
  4795. }
  4796. this.state = PENDING;
  4797. this.queue = [];
  4798. this.outcome = void 0;
  4799. if (resolver !== INTERNAL) {
  4800. safelyResolveThenable(this, resolver);
  4801. }
  4802. }
  4803.  
  4804. Promise.prototype["finally"] = function (callback) {
  4805. if (typeof callback !== 'function') {
  4806. return this;
  4807. }
  4808. var p = this.constructor;
  4809. return this.then(resolve, reject);
  4810.  
  4811. function resolve(value) {
  4812. function yes () {
  4813. return value;
  4814. }
  4815. return p.resolve(callback()).then(yes);
  4816. }
  4817. function reject(reason) {
  4818. function no () {
  4819. throw reason;
  4820. }
  4821. return p.resolve(callback()).then(no);
  4822. }
  4823. };
  4824. Promise.prototype["catch"] = function (onRejected) {
  4825. return this.then(null, onRejected);
  4826. };
  4827. Promise.prototype.then = function (onFulfilled, onRejected) {
  4828. if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
  4829. typeof onRejected !== 'function' && this.state === REJECTED) {
  4830. return this;
  4831. }
  4832. var promise = new this.constructor(INTERNAL);
  4833. if (this.state !== PENDING) {
  4834. var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
  4835. unwrap(promise, resolver, this.outcome);
  4836. } else {
  4837. this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  4838. }
  4839.  
  4840. return promise;
  4841. };
  4842. function QueueItem(promise, onFulfilled, onRejected) {
  4843. this.promise = promise;
  4844. if (typeof onFulfilled === 'function') {
  4845. this.onFulfilled = onFulfilled;
  4846. this.callFulfilled = this.otherCallFulfilled;
  4847. }
  4848. if (typeof onRejected === 'function') {
  4849. this.onRejected = onRejected;
  4850. this.callRejected = this.otherCallRejected;
  4851. }
  4852. }
  4853. QueueItem.prototype.callFulfilled = function (value) {
  4854. handlers.resolve(this.promise, value);
  4855. };
  4856. QueueItem.prototype.otherCallFulfilled = function (value) {
  4857. unwrap(this.promise, this.onFulfilled, value);
  4858. };
  4859. QueueItem.prototype.callRejected = function (value) {
  4860. handlers.reject(this.promise, value);
  4861. };
  4862. QueueItem.prototype.otherCallRejected = function (value) {
  4863. unwrap(this.promise, this.onRejected, value);
  4864. };
  4865.  
  4866. function unwrap(promise, func, value) {
  4867. immediate(function () {
  4868. var returnValue;
  4869. try {
  4870. returnValue = func(value);
  4871. } catch (e) {
  4872. return handlers.reject(promise, e);
  4873. }
  4874. if (returnValue === promise) {
  4875. handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
  4876. } else {
  4877. handlers.resolve(promise, returnValue);
  4878. }
  4879. });
  4880. }
  4881.  
  4882. handlers.resolve = function (self, value) {
  4883. var result = tryCatch(getThen, value);
  4884. if (result.status === 'error') {
  4885. return handlers.reject(self, result.value);
  4886. }
  4887. var thenable = result.value;
  4888.  
  4889. if (thenable) {
  4890. safelyResolveThenable(self, thenable);
  4891. } else {
  4892. self.state = FULFILLED;
  4893. self.outcome = value;
  4894. var i = -1;
  4895. var len = self.queue.length;
  4896. while (++i < len) {
  4897. self.queue[i].callFulfilled(value);
  4898. }
  4899. }
  4900. return self;
  4901. };
  4902. handlers.reject = function (self, error) {
  4903. self.state = REJECTED;
  4904. self.outcome = error;
  4905. var i = -1;
  4906. var len = self.queue.length;
  4907. while (++i < len) {
  4908. self.queue[i].callRejected(error);
  4909. }
  4910. return self;
  4911. };
  4912.  
  4913. function getThen(obj) {
  4914. // Make sure we only access the accessor once as required by the spec
  4915. var then = obj && obj.then;
  4916. if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
  4917. return function appyThen() {
  4918. then.apply(obj, arguments);
  4919. };
  4920. }
  4921. }
  4922.  
  4923. function safelyResolveThenable(self, thenable) {
  4924. // Either fulfill, reject or reject with error
  4925. var called = false;
  4926. function onError(value) {
  4927. if (called) {
  4928. return;
  4929. }
  4930. called = true;
  4931. handlers.reject(self, value);
  4932. }
  4933.  
  4934. function onSuccess(value) {
  4935. if (called) {
  4936. return;
  4937. }
  4938. called = true;
  4939. handlers.resolve(self, value);
  4940. }
  4941.  
  4942. function tryToUnwrap() {
  4943. thenable(onSuccess, onError);
  4944. }
  4945.  
  4946. var result = tryCatch(tryToUnwrap);
  4947. if (result.status === 'error') {
  4948. onError(result.value);
  4949. }
  4950. }
  4951.  
  4952. function tryCatch(func, value) {
  4953. var out = {};
  4954. try {
  4955. out.value = func(value);
  4956. out.status = 'success';
  4957. } catch (e) {
  4958. out.status = 'error';
  4959. out.value = e;
  4960. }
  4961. return out;
  4962. }
  4963.  
  4964. Promise.resolve = resolve;
  4965. function resolve(value) {
  4966. if (value instanceof this) {
  4967. return value;
  4968. }
  4969. return handlers.resolve(new this(INTERNAL), value);
  4970. }
  4971.  
  4972. Promise.reject = reject;
  4973. function reject(reason) {
  4974. var promise = new this(INTERNAL);
  4975. return handlers.reject(promise, reason);
  4976. }
  4977.  
  4978. Promise.all = all;
  4979. function all(iterable) {
  4980. var self = this;
  4981. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4982. return this.reject(new TypeError('must be an array'));
  4983. }
  4984.  
  4985. var len = iterable.length;
  4986. var called = false;
  4987. if (!len) {
  4988. return this.resolve([]);
  4989. }
  4990.  
  4991. var values = new Array(len);
  4992. var resolved = 0;
  4993. var i = -1;
  4994. var promise = new this(INTERNAL);
  4995.  
  4996. while (++i < len) {
  4997. allResolver(iterable[i], i);
  4998. }
  4999. return promise;
  5000. function allResolver(value, i) {
  5001. self.resolve(value).then(resolveFromAll, function (error) {
  5002. if (!called) {
  5003. called = true;
  5004. handlers.reject(promise, error);
  5005. }
  5006. });
  5007. function resolveFromAll(outValue) {
  5008. values[i] = outValue;
  5009. if (++resolved === len && !called) {
  5010. called = true;
  5011. handlers.resolve(promise, values);
  5012. }
  5013. }
  5014. }
  5015. }
  5016.  
  5017. Promise.race = race;
  5018. function race(iterable) {
  5019. var self = this;
  5020. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  5021. return this.reject(new TypeError('must be an array'));
  5022. }
  5023.  
  5024. var len = iterable.length;
  5025. var called = false;
  5026. if (!len) {
  5027. return this.resolve([]);
  5028. }
  5029.  
  5030. var i = -1;
  5031. var promise = new this(INTERNAL);
  5032.  
  5033. while (++i < len) {
  5034. resolver(iterable[i]);
  5035. }
  5036. return promise;
  5037. function resolver(value) {
  5038. self.resolve(value).then(function (response) {
  5039. if (!called) {
  5040. called = true;
  5041. handlers.resolve(promise, response);
  5042. }
  5043. }, function (error) {
  5044. if (!called) {
  5045. called = true;
  5046. handlers.reject(promise, error);
  5047. }
  5048. });
  5049. }
  5050. }
  5051.  
  5052. },{"immediate":36}],38:[function(require,module,exports){
  5053. // Top level file is just a mixin of submodules & constants
  5054. 'use strict';
  5055.  
  5056. var assign = require('./lib/utils/common').assign;
  5057.  
  5058. var deflate = require('./lib/deflate');
  5059. var inflate = require('./lib/inflate');
  5060. var constants = require('./lib/zlib/constants');
  5061.  
  5062. var pako = {};
  5063.  
  5064. assign(pako, deflate, inflate, constants);
  5065.  
  5066. module.exports = pako;
  5067.  
  5068. },{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(require,module,exports){
  5069. 'use strict';
  5070.  
  5071.  
  5072. var zlib_deflate = require('./zlib/deflate');
  5073. var utils = require('./utils/common');
  5074. var strings = require('./utils/strings');
  5075. var msg = require('./zlib/messages');
  5076. var ZStream = require('./zlib/zstream');
  5077.  
  5078. var toString = Object.prototype.toString;
  5079.  
  5080. /* Public constants ==========================================================*/
  5081. /* ===========================================================================*/
  5082.  
  5083. var Z_NO_FLUSH = 0;
  5084. var Z_FINISH = 4;
  5085.  
  5086. var Z_OK = 0;
  5087. var Z_STREAM_END = 1;
  5088. var Z_SYNC_FLUSH = 2;
  5089.  
  5090. var Z_DEFAULT_COMPRESSION = -1;
  5091.  
  5092. var Z_DEFAULT_STRATEGY = 0;
  5093.  
  5094. var Z_DEFLATED = 8;
  5095.  
  5096. /* ===========================================================================*/
  5097.  
  5098.  
  5099. /**
  5100. * class Deflate
  5101. *
  5102. * Generic JS-style wrapper for zlib calls. If you don't need
  5103. * streaming behaviour - use more simple functions: [[deflate]],
  5104. * [[deflateRaw]] and [[gzip]].
  5105. **/
  5106.  
  5107. /* internal
  5108. * Deflate.chunks -> Array
  5109. *
  5110. * Chunks of output data, if [[Deflate#onData]] not overriden.
  5111. **/
  5112.  
  5113. /**
  5114. * Deflate.result -> Uint8Array|Array
  5115. *
  5116. * Compressed result, generated by default [[Deflate#onData]]
  5117. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  5118. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  5119. * push a chunk with explicit flush (call [[Deflate#push]] with
  5120. * `Z_SYNC_FLUSH` param).
  5121. **/
  5122.  
  5123. /**
  5124. * Deflate.err -> Number
  5125. *
  5126. * Error code after deflate finished. 0 (Z_OK) on success.
  5127. * You will not need it in real life, because deflate errors
  5128. * are possible only on wrong options or bad `onData` / `onEnd`
  5129. * custom handlers.
  5130. **/
  5131.  
  5132. /**
  5133. * Deflate.msg -> String
  5134. *
  5135. * Error message, if [[Deflate.err]] != 0
  5136. **/
  5137.  
  5138.  
  5139. /**
  5140. * new Deflate(options)
  5141. * - options (Object): zlib deflate options.
  5142. *
  5143. * Creates new deflator instance with specified params. Throws exception
  5144. * on bad params. Supported options:
  5145. *
  5146. * - `level`
  5147. * - `windowBits`
  5148. * - `memLevel`
  5149. * - `strategy`
  5150. * - `dictionary`
  5151. *
  5152. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5153. * for more information on these.
  5154. *
  5155. * Additional options, for internal needs:
  5156. *
  5157. * - `chunkSize` - size of generated data chunks (16K by default)
  5158. * - `raw` (Boolean) - do raw deflate
  5159. * - `gzip` (Boolean) - create gzip wrapper
  5160. * - `to` (String) - if equal to 'string', then result will be "binary string"
  5161. * (each char code [0..255])
  5162. * - `header` (Object) - custom header for gzip
  5163. * - `text` (Boolean) - true if compressed data believed to be text
  5164. * - `time` (Number) - modification time, unix timestamp
  5165. * - `os` (Number) - operation system code
  5166. * - `extra` (Array) - array of bytes with extra data (max 65536)
  5167. * - `name` (String) - file name (binary string)
  5168. * - `comment` (String) - comment (binary string)
  5169. * - `hcrc` (Boolean) - true if header crc should be added
  5170. *
  5171. * ##### Example:
  5172. *
  5173. * ```javascript
  5174. * var pako = require('pako')
  5175. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5176. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5177. *
  5178. * var deflate = new pako.Deflate({ level: 3});
  5179. *
  5180. * deflate.push(chunk1, false);
  5181. * deflate.push(chunk2, true); // true -> last chunk
  5182. *
  5183. * if (deflate.err) { throw new Error(deflate.err); }
  5184. *
  5185. * console.log(deflate.result);
  5186. * ```
  5187. **/
  5188. function Deflate(options) {
  5189. if (!(this instanceof Deflate)) return new Deflate(options);
  5190.  
  5191. this.options = utils.assign({
  5192. level: Z_DEFAULT_COMPRESSION,
  5193. method: Z_DEFLATED,
  5194. chunkSize: 16384,
  5195. windowBits: 15,
  5196. memLevel: 8,
  5197. strategy: Z_DEFAULT_STRATEGY,
  5198. to: ''
  5199. }, options || {});
  5200.  
  5201. var opt = this.options;
  5202.  
  5203. if (opt.raw && (opt.windowBits > 0)) {
  5204. opt.windowBits = -opt.windowBits;
  5205. }
  5206.  
  5207. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  5208. opt.windowBits += 16;
  5209. }
  5210.  
  5211. this.err = 0; // error code, if happens (0 = Z_OK)
  5212. this.msg = ''; // error message
  5213. this.ended = false; // used to avoid multiple onEnd() calls
  5214. this.chunks = []; // chunks of compressed data
  5215.  
  5216. this.strm = new ZStream();
  5217. this.strm.avail_out = 0;
  5218.  
  5219. var status = zlib_deflate.deflateInit2(
  5220. this.strm,
  5221. opt.level,
  5222. opt.method,
  5223. opt.windowBits,
  5224. opt.memLevel,
  5225. opt.strategy
  5226. );
  5227.  
  5228. if (status !== Z_OK) {
  5229. throw new Error(msg[status]);
  5230. }
  5231.  
  5232. if (opt.header) {
  5233. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  5234. }
  5235.  
  5236. if (opt.dictionary) {
  5237. var dict;
  5238. // Convert data if needed
  5239. if (typeof opt.dictionary === 'string') {
  5240. // If we need to compress text, change encoding to utf8.
  5241. dict = strings.string2buf(opt.dictionary);
  5242. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  5243. dict = new Uint8Array(opt.dictionary);
  5244. } else {
  5245. dict = opt.dictionary;
  5246. }
  5247.  
  5248. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  5249.  
  5250. if (status !== Z_OK) {
  5251. throw new Error(msg[status]);
  5252. }
  5253.  
  5254. this._dict_set = true;
  5255. }
  5256. }
  5257.  
  5258. /**
  5259. * Deflate#push(data[, mode]) -> Boolean
  5260. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  5261. * converted to utf8 byte sequence.
  5262. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5263. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5264. *
  5265. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  5266. * new compressed chunks. Returns `true` on success. The last data block must have
  5267. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5268. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5269. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  5270. *
  5271. * On fail call [[Deflate#onEnd]] with error code and return false.
  5272. *
  5273. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5274. * array format is detected automatically). Also, don't skip last param and always
  5275. * use the same type in your code (boolean or number). That will improve JS speed.
  5276. *
  5277. * For regular `Array`-s make sure all elements are [0..255].
  5278. *
  5279. * ##### Example
  5280. *
  5281. * ```javascript
  5282. * push(chunk, false); // push one of data chunks
  5283. * ...
  5284. * push(chunk, true); // push last chunk
  5285. * ```
  5286. **/
  5287. Deflate.prototype.push = function (data, mode) {
  5288. var strm = this.strm;
  5289. var chunkSize = this.options.chunkSize;
  5290. var status, _mode;
  5291.  
  5292. if (this.ended) { return false; }
  5293.  
  5294. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  5295.  
  5296. // Convert data if needed
  5297. if (typeof data === 'string') {
  5298. // If we need to compress text, change encoding to utf8.
  5299. strm.input = strings.string2buf(data);
  5300. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5301. strm.input = new Uint8Array(data);
  5302. } else {
  5303. strm.input = data;
  5304. }
  5305.  
  5306. strm.next_in = 0;
  5307. strm.avail_in = strm.input.length;
  5308.  
  5309. do {
  5310. if (strm.avail_out === 0) {
  5311. strm.output = new utils.Buf8(chunkSize);
  5312. strm.next_out = 0;
  5313. strm.avail_out = chunkSize;
  5314. }
  5315. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  5316.  
  5317. if (status !== Z_STREAM_END && status !== Z_OK) {
  5318. this.onEnd(status);
  5319. this.ended = true;
  5320. return false;
  5321. }
  5322. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  5323. if (this.options.to === 'string') {
  5324. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  5325. } else {
  5326. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5327. }
  5328. }
  5329. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  5330.  
  5331. // Finalize on the last chunk.
  5332. if (_mode === Z_FINISH) {
  5333. status = zlib_deflate.deflateEnd(this.strm);
  5334. this.onEnd(status);
  5335. this.ended = true;
  5336. return status === Z_OK;
  5337. }
  5338.  
  5339. // callback interim results if Z_SYNC_FLUSH.
  5340. if (_mode === Z_SYNC_FLUSH) {
  5341. this.onEnd(Z_OK);
  5342. strm.avail_out = 0;
  5343. return true;
  5344. }
  5345.  
  5346. return true;
  5347. };
  5348.  
  5349.  
  5350. /**
  5351. * Deflate#onData(chunk) -> Void
  5352. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5353. * on js engine support. When string output requested, each chunk
  5354. * will be string.
  5355. *
  5356. * By default, stores data blocks in `chunks[]` property and glue
  5357. * those in `onEnd`. Override this handler, if you need another behaviour.
  5358. **/
  5359. Deflate.prototype.onData = function (chunk) {
  5360. this.chunks.push(chunk);
  5361. };
  5362.  
  5363.  
  5364. /**
  5365. * Deflate#onEnd(status) -> Void
  5366. * - status (Number): deflate status. 0 (Z_OK) on success,
  5367. * other if not.
  5368. *
  5369. * Called once after you tell deflate that the input stream is
  5370. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5371. * or if an error happened. By default - join collected chunks,
  5372. * free memory and fill `results` / `err` properties.
  5373. **/
  5374. Deflate.prototype.onEnd = function (status) {
  5375. // On success - join
  5376. if (status === Z_OK) {
  5377. if (this.options.to === 'string') {
  5378. this.result = this.chunks.join('');
  5379. } else {
  5380. this.result = utils.flattenChunks(this.chunks);
  5381. }
  5382. }
  5383. this.chunks = [];
  5384. this.err = status;
  5385. this.msg = this.strm.msg;
  5386. };
  5387.  
  5388.  
  5389. /**
  5390. * deflate(data[, options]) -> Uint8Array|Array|String
  5391. * - data (Uint8Array|Array|String): input data to compress.
  5392. * - options (Object): zlib deflate options.
  5393. *
  5394. * Compress `data` with deflate algorithm and `options`.
  5395. *
  5396. * Supported options are:
  5397. *
  5398. * - level
  5399. * - windowBits
  5400. * - memLevel
  5401. * - strategy
  5402. * - dictionary
  5403. *
  5404. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5405. * for more information on these.
  5406. *
  5407. * Sugar (options):
  5408. *
  5409. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5410. * negative windowBits implicitly.
  5411. * - `to` (String) - if equal to 'string', then result will be "binary string"
  5412. * (each char code [0..255])
  5413. *
  5414. * ##### Example:
  5415. *
  5416. * ```javascript
  5417. * var pako = require('pako')
  5418. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  5419. *
  5420. * console.log(pako.deflate(data));
  5421. * ```
  5422. **/
  5423. function deflate(input, options) {
  5424. var deflator = new Deflate(options);
  5425.  
  5426. deflator.push(input, true);
  5427.  
  5428. // That will never happens, if you don't cheat with options :)
  5429. if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
  5430.  
  5431. return deflator.result;
  5432. }
  5433.  
  5434.  
  5435. /**
  5436. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  5437. * - data (Uint8Array|Array|String): input data to compress.
  5438. * - options (Object): zlib deflate options.
  5439. *
  5440. * The same as [[deflate]], but creates raw data, without wrapper
  5441. * (header and adler32 crc).
  5442. **/
  5443. function deflateRaw(input, options) {
  5444. options = options || {};
  5445. options.raw = true;
  5446. return deflate(input, options);
  5447. }
  5448.  
  5449.  
  5450. /**
  5451. * gzip(data[, options]) -> Uint8Array|Array|String
  5452. * - data (Uint8Array|Array|String): input data to compress.
  5453. * - options (Object): zlib deflate options.
  5454. *
  5455. * The same as [[deflate]], but create gzip wrapper instead of
  5456. * deflate one.
  5457. **/
  5458. function gzip(input, options) {
  5459. options = options || {};
  5460. options.gzip = true;
  5461. return deflate(input, options);
  5462. }
  5463.  
  5464.  
  5465. exports.Deflate = Deflate;
  5466. exports.deflate = deflate;
  5467. exports.deflateRaw = deflateRaw;
  5468. exports.gzip = gzip;
  5469.  
  5470. },{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(require,module,exports){
  5471. 'use strict';
  5472.  
  5473.  
  5474. var zlib_inflate = require('./zlib/inflate');
  5475. var utils = require('./utils/common');
  5476. var strings = require('./utils/strings');
  5477. var c = require('./zlib/constants');
  5478. var msg = require('./zlib/messages');
  5479. var ZStream = require('./zlib/zstream');
  5480. var GZheader = require('./zlib/gzheader');
  5481.  
  5482. var toString = Object.prototype.toString;
  5483.  
  5484. /**
  5485. * class Inflate
  5486. *
  5487. * Generic JS-style wrapper for zlib calls. If you don't need
  5488. * streaming behaviour - use more simple functions: [[inflate]]
  5489. * and [[inflateRaw]].
  5490. **/
  5491.  
  5492. /* internal
  5493. * inflate.chunks -> Array
  5494. *
  5495. * Chunks of output data, if [[Inflate#onData]] not overriden.
  5496. **/
  5497.  
  5498. /**
  5499. * Inflate.result -> Uint8Array|Array|String
  5500. *
  5501. * Uncompressed result, generated by default [[Inflate#onData]]
  5502. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  5503. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  5504. * push a chunk with explicit flush (call [[Inflate#push]] with
  5505. * `Z_SYNC_FLUSH` param).
  5506. **/
  5507.  
  5508. /**
  5509. * Inflate.err -> Number
  5510. *
  5511. * Error code after inflate finished. 0 (Z_OK) on success.
  5512. * Should be checked if broken data possible.
  5513. **/
  5514.  
  5515. /**
  5516. * Inflate.msg -> String
  5517. *
  5518. * Error message, if [[Inflate.err]] != 0
  5519. **/
  5520.  
  5521.  
  5522. /**
  5523. * new Inflate(options)
  5524. * - options (Object): zlib inflate options.
  5525. *
  5526. * Creates new inflator instance with specified params. Throws exception
  5527. * on bad params. Supported options:
  5528. *
  5529. * - `windowBits`
  5530. * - `dictionary`
  5531. *
  5532. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5533. * for more information on these.
  5534. *
  5535. * Additional options, for internal needs:
  5536. *
  5537. * - `chunkSize` - size of generated data chunks (16K by default)
  5538. * - `raw` (Boolean) - do raw inflate
  5539. * - `to` (String) - if equal to 'string', then result will be converted
  5540. * from utf8 to utf16 (javascript) string. When string output requested,
  5541. * chunk length can differ from `chunkSize`, depending on content.
  5542. *
  5543. * By default, when no options set, autodetect deflate/gzip data format via
  5544. * wrapper header.
  5545. *
  5546. * ##### Example:
  5547. *
  5548. * ```javascript
  5549. * var pako = require('pako')
  5550. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5551. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5552. *
  5553. * var inflate = new pako.Inflate({ level: 3});
  5554. *
  5555. * inflate.push(chunk1, false);
  5556. * inflate.push(chunk2, true); // true -> last chunk
  5557. *
  5558. * if (inflate.err) { throw new Error(inflate.err); }
  5559. *
  5560. * console.log(inflate.result);
  5561. * ```
  5562. **/
  5563. function Inflate(options) {
  5564. if (!(this instanceof Inflate)) return new Inflate(options);
  5565.  
  5566. this.options = utils.assign({
  5567. chunkSize: 16384,
  5568. windowBits: 0,
  5569. to: ''
  5570. }, options || {});
  5571.  
  5572. var opt = this.options;
  5573.  
  5574. // Force window size for `raw` data, if not set directly,
  5575. // because we have no header for autodetect.
  5576. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  5577. opt.windowBits = -opt.windowBits;
  5578. if (opt.windowBits === 0) { opt.windowBits = -15; }
  5579. }
  5580.  
  5581. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  5582. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  5583. !(options && options.windowBits)) {
  5584. opt.windowBits += 32;
  5585. }
  5586.  
  5587. // Gzip header has no info about windows size, we can do autodetect only
  5588. // for deflate. So, if window size not set, force it to max when gzip possible
  5589. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  5590. // bit 3 (16) -> gzipped data
  5591. // bit 4 (32) -> autodetect gzip/deflate
  5592. if ((opt.windowBits & 15) === 0) {
  5593. opt.windowBits |= 15;
  5594. }
  5595. }
  5596.  
  5597. this.err = 0; // error code, if happens (0 = Z_OK)
  5598. this.msg = ''; // error message
  5599. this.ended = false; // used to avoid multiple onEnd() calls
  5600. this.chunks = []; // chunks of compressed data
  5601.  
  5602. this.strm = new ZStream();
  5603. this.strm.avail_out = 0;
  5604.  
  5605. var status = zlib_inflate.inflateInit2(
  5606. this.strm,
  5607. opt.windowBits
  5608. );
  5609.  
  5610. if (status !== c.Z_OK) {
  5611. throw new Error(msg[status]);
  5612. }
  5613.  
  5614. this.header = new GZheader();
  5615.  
  5616. zlib_inflate.inflateGetHeader(this.strm, this.header);
  5617. }
  5618.  
  5619. /**
  5620. * Inflate#push(data[, mode]) -> Boolean
  5621. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  5622. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5623. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5624. *
  5625. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  5626. * new output chunks. Returns `true` on success. The last data block must have
  5627. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5628. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5629. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  5630. *
  5631. * On fail call [[Inflate#onEnd]] with error code and return false.
  5632. *
  5633. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5634. * format is detected automatically). Also, don't skip last param and always
  5635. * use the same type in your code (boolean or number). That will improve JS speed.
  5636. *
  5637. * For regular `Array`-s make sure all elements are [0..255].
  5638. *
  5639. * ##### Example
  5640. *
  5641. * ```javascript
  5642. * push(chunk, false); // push one of data chunks
  5643. * ...
  5644. * push(chunk, true); // push last chunk
  5645. * ```
  5646. **/
  5647. Inflate.prototype.push = function (data, mode) {
  5648. var strm = this.strm;
  5649. var chunkSize = this.options.chunkSize;
  5650. var dictionary = this.options.dictionary;
  5651. var status, _mode;
  5652. var next_out_utf8, tail, utf8str;
  5653. var dict;
  5654.  
  5655. // Flag to properly process Z_BUF_ERROR on testing inflate call
  5656. // when we check that all output data was flushed.
  5657. var allowBufError = false;
  5658.  
  5659. if (this.ended) { return false; }
  5660. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  5661.  
  5662. // Convert data if needed
  5663. if (typeof data === 'string') {
  5664. // Only binary strings can be decompressed on practice
  5665. strm.input = strings.binstring2buf(data);
  5666. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5667. strm.input = new Uint8Array(data);
  5668. } else {
  5669. strm.input = data;
  5670. }
  5671.  
  5672. strm.next_in = 0;
  5673. strm.avail_in = strm.input.length;
  5674.  
  5675. do {
  5676. if (strm.avail_out === 0) {
  5677. strm.output = new utils.Buf8(chunkSize);
  5678. strm.next_out = 0;
  5679. strm.avail_out = chunkSize;
  5680. }
  5681.  
  5682. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  5683.  
  5684. if (status === c.Z_NEED_DICT && dictionary) {
  5685. // Convert data if needed
  5686. if (typeof dictionary === 'string') {
  5687. dict = strings.string2buf(dictionary);
  5688. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  5689. dict = new Uint8Array(dictionary);
  5690. } else {
  5691. dict = dictionary;
  5692. }
  5693.  
  5694. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  5695.  
  5696. }
  5697.  
  5698. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  5699. status = c.Z_OK;
  5700. allowBufError = false;
  5701. }
  5702.  
  5703. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  5704. this.onEnd(status);
  5705. this.ended = true;
  5706. return false;
  5707. }
  5708.  
  5709. if (strm.next_out) {
  5710. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  5711.  
  5712. if (this.options.to === 'string') {
  5713.  
  5714. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  5715.  
  5716. tail = strm.next_out - next_out_utf8;
  5717. utf8str = strings.buf2string(strm.output, next_out_utf8);
  5718.  
  5719. // move tail
  5720. strm.next_out = tail;
  5721. strm.avail_out = chunkSize - tail;
  5722. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  5723.  
  5724. this.onData(utf8str);
  5725.  
  5726. } else {
  5727. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5728. }
  5729. }
  5730. }
  5731.  
  5732. // When no more input data, we should check that internal inflate buffers
  5733. // are flushed. The only way to do it when avail_out = 0 - run one more
  5734. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  5735. // Here we set flag to process this error properly.
  5736. //
  5737. // NOTE. Deflate does not return error in this case and does not needs such
  5738. // logic.
  5739. if (strm.avail_in === 0 && strm.avail_out === 0) {
  5740. allowBufError = true;
  5741. }
  5742.  
  5743. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  5744.  
  5745. if (status === c.Z_STREAM_END) {
  5746. _mode = c.Z_FINISH;
  5747. }
  5748.  
  5749. // Finalize on the last chunk.
  5750. if (_mode === c.Z_FINISH) {
  5751. status = zlib_inflate.inflateEnd(this.strm);
  5752. this.onEnd(status);
  5753. this.ended = true;
  5754. return status === c.Z_OK;
  5755. }
  5756.  
  5757. // callback interim results if Z_SYNC_FLUSH.
  5758. if (_mode === c.Z_SYNC_FLUSH) {
  5759. this.onEnd(c.Z_OK);
  5760. strm.avail_out = 0;
  5761. return true;
  5762. }
  5763.  
  5764. return true;
  5765. };
  5766.  
  5767.  
  5768. /**
  5769. * Inflate#onData(chunk) -> Void
  5770. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5771. * on js engine support. When string output requested, each chunk
  5772. * will be string.
  5773. *
  5774. * By default, stores data blocks in `chunks[]` property and glue
  5775. * those in `onEnd`. Override this handler, if you need another behaviour.
  5776. **/
  5777. Inflate.prototype.onData = function (chunk) {
  5778. this.chunks.push(chunk);
  5779. };
  5780.  
  5781.  
  5782. /**
  5783. * Inflate#onEnd(status) -> Void
  5784. * - status (Number): inflate status. 0 (Z_OK) on success,
  5785. * other if not.
  5786. *
  5787. * Called either after you tell inflate that the input stream is
  5788. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5789. * or if an error happened. By default - join collected chunks,
  5790. * free memory and fill `results` / `err` properties.
  5791. **/
  5792. Inflate.prototype.onEnd = function (status) {
  5793. // On success - join
  5794. if (status === c.Z_OK) {
  5795. if (this.options.to === 'string') {
  5796. // Glue & convert here, until we teach pako to send
  5797. // utf8 alligned strings to onData
  5798. this.result = this.chunks.join('');
  5799. } else {
  5800. this.result = utils.flattenChunks(this.chunks);
  5801. }
  5802. }
  5803. this.chunks = [];
  5804. this.err = status;
  5805. this.msg = this.strm.msg;
  5806. };
  5807.  
  5808.  
  5809. /**
  5810. * inflate(data[, options]) -> Uint8Array|Array|String
  5811. * - data (Uint8Array|Array|String): input data to decompress.
  5812. * - options (Object): zlib inflate options.
  5813. *
  5814. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  5815. * format via wrapper header by default. That's why we don't provide
  5816. * separate `ungzip` method.
  5817. *
  5818. * Supported options are:
  5819. *
  5820. * - windowBits
  5821. *
  5822. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5823. * for more information.
  5824. *
  5825. * Sugar (options):
  5826. *
  5827. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5828. * negative windowBits implicitly.
  5829. * - `to` (String) - if equal to 'string', then result will be converted
  5830. * from utf8 to utf16 (javascript) string. When string output requested,
  5831. * chunk length can differ from `chunkSize`, depending on content.
  5832. *
  5833. *
  5834. * ##### Example:
  5835. *
  5836. * ```javascript
  5837. * var pako = require('pako')
  5838. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  5839. * , output;
  5840. *
  5841. * try {
  5842. * output = pako.inflate(input);
  5843. * } catch (err)
  5844. * console.log(err);
  5845. * }
  5846. * ```
  5847. **/
  5848. function inflate(input, options) {
  5849. var inflator = new Inflate(options);
  5850.  
  5851. inflator.push(input, true);
  5852.  
  5853. // That will never happens, if you don't cheat with options :)
  5854. if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
  5855.  
  5856. return inflator.result;
  5857. }
  5858.  
  5859.  
  5860. /**
  5861. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  5862. * - data (Uint8Array|Array|String): input data to decompress.
  5863. * - options (Object): zlib inflate options.
  5864. *
  5865. * The same as [[inflate]], but creates raw data, without wrapper
  5866. * (header and adler32 crc).
  5867. **/
  5868. function inflateRaw(input, options) {
  5869. options = options || {};
  5870. options.raw = true;
  5871. return inflate(input, options);
  5872. }
  5873.  
  5874.  
  5875. /**
  5876. * ungzip(data[, options]) -> Uint8Array|Array|String
  5877. * - data (Uint8Array|Array|String): input data to decompress.
  5878. * - options (Object): zlib inflate options.
  5879. *
  5880. * Just shortcut to [[inflate]], because it autodetects format
  5881. * by header.content. Done for convenience.
  5882. **/
  5883.  
  5884.  
  5885. exports.Inflate = Inflate;
  5886. exports.inflate = inflate;
  5887. exports.inflateRaw = inflateRaw;
  5888. exports.ungzip = inflate;
  5889.  
  5890. },{"./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){
  5891. 'use strict';
  5892.  
  5893.  
  5894. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  5895. (typeof Uint16Array !== 'undefined') &&
  5896. (typeof Int32Array !== 'undefined');
  5897.  
  5898.  
  5899. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  5900. var sources = Array.prototype.slice.call(arguments, 1);
  5901. while (sources.length) {
  5902. var source = sources.shift();
  5903. if (!source) { continue; }
  5904.  
  5905. if (typeof source !== 'object') {
  5906. throw new TypeError(source + 'must be non-object');
  5907. }
  5908.  
  5909. for (var p in source) {
  5910. if (source.hasOwnProperty(p)) {
  5911. obj[p] = source[p];
  5912. }
  5913. }
  5914. }
  5915.  
  5916. return obj;
  5917. };
  5918.  
  5919.  
  5920. // reduce buffer size, avoiding mem copy
  5921. exports.shrinkBuf = function (buf, size) {
  5922. if (buf.length === size) { return buf; }
  5923. if (buf.subarray) { return buf.subarray(0, size); }
  5924. buf.length = size;
  5925. return buf;
  5926. };
  5927.  
  5928.  
  5929. var fnTyped = {
  5930. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5931. if (src.subarray && dest.subarray) {
  5932. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  5933. return;
  5934. }
  5935. // Fallback to ordinary array
  5936. for (var i = 0; i < len; i++) {
  5937. dest[dest_offs + i] = src[src_offs + i];
  5938. }
  5939. },
  5940. // Join array of chunks to single array.
  5941. flattenChunks: function (chunks) {
  5942. var i, l, len, pos, chunk, result;
  5943.  
  5944. // calculate data length
  5945. len = 0;
  5946. for (i = 0, l = chunks.length; i < l; i++) {
  5947. len += chunks[i].length;
  5948. }
  5949.  
  5950. // join chunks
  5951. result = new Uint8Array(len);
  5952. pos = 0;
  5953. for (i = 0, l = chunks.length; i < l; i++) {
  5954. chunk = chunks[i];
  5955. result.set(chunk, pos);
  5956. pos += chunk.length;
  5957. }
  5958.  
  5959. return result;
  5960. }
  5961. };
  5962.  
  5963. var fnUntyped = {
  5964. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5965. for (var i = 0; i < len; i++) {
  5966. dest[dest_offs + i] = src[src_offs + i];
  5967. }
  5968. },
  5969. // Join array of chunks to single array.
  5970. flattenChunks: function (chunks) {
  5971. return [].concat.apply([], chunks);
  5972. }
  5973. };
  5974.  
  5975.  
  5976. // Enable/Disable typed arrays use, for testing
  5977. //
  5978. exports.setTyped = function (on) {
  5979. if (on) {
  5980. exports.Buf8 = Uint8Array;
  5981. exports.Buf16 = Uint16Array;
  5982. exports.Buf32 = Int32Array;
  5983. exports.assign(exports, fnTyped);
  5984. } else {
  5985. exports.Buf8 = Array;
  5986. exports.Buf16 = Array;
  5987. exports.Buf32 = Array;
  5988. exports.assign(exports, fnUntyped);
  5989. }
  5990. };
  5991.  
  5992. exports.setTyped(TYPED_OK);
  5993.  
  5994. },{}],42:[function(require,module,exports){
  5995. // String encode/decode helpers
  5996. 'use strict';
  5997.  
  5998.  
  5999. var utils = require('./common');
  6000.  
  6001.  
  6002. // Quick check if we can use fast array to bin string conversion
  6003. //
  6004. // - apply(Array) can fail on Android 2.2
  6005. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  6006. //
  6007. var STR_APPLY_OK = true;
  6008. var STR_APPLY_UIA_OK = true;
  6009.  
  6010. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  6011. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  6012.  
  6013.  
  6014. // Table with utf8 lengths (calculated by first byte of sequence)
  6015. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  6016. // because max possible codepoint is 0x10ffff
  6017. var _utf8len = new utils.Buf8(256);
  6018. for (var q = 0; q < 256; q++) {
  6019. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  6020. }
  6021. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  6022.  
  6023.  
  6024. // convert string to array (typed, when possible)
  6025. exports.string2buf = function (str) {
  6026. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  6027.  
  6028. // count binary size
  6029. for (m_pos = 0; m_pos < str_len; m_pos++) {
  6030. c = str.charCodeAt(m_pos);
  6031. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  6032. c2 = str.charCodeAt(m_pos + 1);
  6033. if ((c2 & 0xfc00) === 0xdc00) {
  6034. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  6035. m_pos++;
  6036. }
  6037. }
  6038. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  6039. }
  6040.  
  6041. // allocate buffer
  6042. buf = new utils.Buf8(buf_len);
  6043.  
  6044. // convert
  6045. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  6046. c = str.charCodeAt(m_pos);
  6047. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  6048. c2 = str.charCodeAt(m_pos + 1);
  6049. if ((c2 & 0xfc00) === 0xdc00) {
  6050. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  6051. m_pos++;
  6052. }
  6053. }
  6054. if (c < 0x80) {
  6055. /* one byte */
  6056. buf[i++] = c;
  6057. } else if (c < 0x800) {
  6058. /* two bytes */
  6059. buf[i++] = 0xC0 | (c >>> 6);
  6060. buf[i++] = 0x80 | (c & 0x3f);
  6061. } else if (c < 0x10000) {
  6062. /* three bytes */
  6063. buf[i++] = 0xE0 | (c >>> 12);
  6064. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  6065. buf[i++] = 0x80 | (c & 0x3f);
  6066. } else {
  6067. /* four bytes */
  6068. buf[i++] = 0xf0 | (c >>> 18);
  6069. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  6070. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  6071. buf[i++] = 0x80 | (c & 0x3f);
  6072. }
  6073. }
  6074.  
  6075. return buf;
  6076. };
  6077.  
  6078. // Helper (used in 2 places)
  6079. function buf2binstring(buf, len) {
  6080. // use fallback for big arrays to avoid stack overflow
  6081. if (len < 65537) {
  6082. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  6083. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  6084. }
  6085. }
  6086.  
  6087. var result = '';
  6088. for (var i = 0; i < len; i++) {
  6089. result += String.fromCharCode(buf[i]);
  6090. }
  6091. return result;
  6092. }
  6093.  
  6094.  
  6095. // Convert byte array to binary string
  6096. exports.buf2binstring = function (buf) {
  6097. return buf2binstring(buf, buf.length);
  6098. };
  6099.  
  6100.  
  6101. // Convert binary string (typed, when possible)
  6102. exports.binstring2buf = function (str) {
  6103. var buf = new utils.Buf8(str.length);
  6104. for (var i = 0, len = buf.length; i < len; i++) {
  6105. buf[i] = str.charCodeAt(i);
  6106. }
  6107. return buf;
  6108. };
  6109.  
  6110.  
  6111. // convert array to string
  6112. exports.buf2string = function (buf, max) {
  6113. var i, out, c, c_len;
  6114. var len = max || buf.length;
  6115.  
  6116. // Reserve max possible length (2 words per char)
  6117. // NB: by unknown reasons, Array is significantly faster for
  6118. // String.fromCharCode.apply than Uint16Array.
  6119. var utf16buf = new Array(len * 2);
  6120.  
  6121. for (out = 0, i = 0; i < len;) {
  6122. c = buf[i++];
  6123. // quick process ascii
  6124. if (c < 0x80) { utf16buf[out++] = c; continue; }
  6125.  
  6126. c_len = _utf8len[c];
  6127. // skip 5 & 6 byte codes
  6128. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  6129.  
  6130. // apply mask on first byte
  6131. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  6132. // join the rest
  6133. while (c_len > 1 && i < len) {
  6134. c = (c << 6) | (buf[i++] & 0x3f);
  6135. c_len--;
  6136. }
  6137.  
  6138. // terminated by end of string?
  6139. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  6140.  
  6141. if (c < 0x10000) {
  6142. utf16buf[out++] = c;
  6143. } else {
  6144. c -= 0x10000;
  6145. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  6146. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  6147. }
  6148. }
  6149.  
  6150. return buf2binstring(utf16buf, out);
  6151. };
  6152.  
  6153.  
  6154. // Calculate max possible position in utf8 buffer,
  6155. // that will not break sequence. If that's not possible
  6156. // - (very small limits) return max size as is.
  6157. //
  6158. // buf[] - utf8 bytes array
  6159. // max - length limit (mandatory);
  6160. exports.utf8border = function (buf, max) {
  6161. var pos;
  6162.  
  6163. max = max || buf.length;
  6164. if (max > buf.length) { max = buf.length; }
  6165.  
  6166. // go back from last position, until start of sequence found
  6167. pos = max - 1;
  6168. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  6169.  
  6170. // Fuckup - very small and broken sequence,
  6171. // return max, because we should return something anyway.
  6172. if (pos < 0) { return max; }
  6173.  
  6174. // If we came to start of buffer - that means vuffer is too small,
  6175. // return max too.
  6176. if (pos === 0) { return max; }
  6177.  
  6178. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  6179. };
  6180.  
  6181. },{"./common":41}],43:[function(require,module,exports){
  6182. 'use strict';
  6183.  
  6184. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  6185. // It doesn't worth to make additional optimizationa as in original.
  6186. // Small size is preferable.
  6187.  
  6188. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6189. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6190. //
  6191. // This software is provided 'as-is', without any express or implied
  6192. // warranty. In no event will the authors be held liable for any damages
  6193. // arising from the use of this software.
  6194. //
  6195. // Permission is granted to anyone to use this software for any purpose,
  6196. // including commercial applications, and to alter it and redistribute it
  6197. // freely, subject to the following restrictions:
  6198. //
  6199. // 1. The origin of this software must not be misrepresented; you must not
  6200. // claim that you wrote the original software. If you use this software
  6201. // in a product, an acknowledgment in the product documentation would be
  6202. // appreciated but is not required.
  6203. // 2. Altered source versions must be plainly marked as such, and must not be
  6204. // misrepresented as being the original software.
  6205. // 3. This notice may not be removed or altered from any source distribution.
  6206.  
  6207. function adler32(adler, buf, len, pos) {
  6208. var s1 = (adler & 0xffff) |0,
  6209. s2 = ((adler >>> 16) & 0xffff) |0,
  6210. n = 0;
  6211.  
  6212. while (len !== 0) {
  6213. // Set limit ~ twice less than 5552, to keep
  6214. // s2 in 31-bits, because we force signed ints.
  6215. // in other case %= will fail.
  6216. n = len > 2000 ? 2000 : len;
  6217. len -= n;
  6218.  
  6219. do {
  6220. s1 = (s1 + buf[pos++]) |0;
  6221. s2 = (s2 + s1) |0;
  6222. } while (--n);
  6223.  
  6224. s1 %= 65521;
  6225. s2 %= 65521;
  6226. }
  6227.  
  6228. return (s1 | (s2 << 16)) |0;
  6229. }
  6230.  
  6231.  
  6232. module.exports = adler32;
  6233.  
  6234. },{}],44:[function(require,module,exports){
  6235. 'use strict';
  6236.  
  6237. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6238. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6239. //
  6240. // This software is provided 'as-is', without any express or implied
  6241. // warranty. In no event will the authors be held liable for any damages
  6242. // arising from the use of this software.
  6243. //
  6244. // Permission is granted to anyone to use this software for any purpose,
  6245. // including commercial applications, and to alter it and redistribute it
  6246. // freely, subject to the following restrictions:
  6247. //
  6248. // 1. The origin of this software must not be misrepresented; you must not
  6249. // claim that you wrote the original software. If you use this software
  6250. // in a product, an acknowledgment in the product documentation would be
  6251. // appreciated but is not required.
  6252. // 2. Altered source versions must be plainly marked as such, and must not be
  6253. // misrepresented as being the original software.
  6254. // 3. This notice may not be removed or altered from any source distribution.
  6255.  
  6256. module.exports = {
  6257.  
  6258. /* Allowed flush values; see deflate() and inflate() below for details */
  6259. Z_NO_FLUSH: 0,
  6260. Z_PARTIAL_FLUSH: 1,
  6261. Z_SYNC_FLUSH: 2,
  6262. Z_FULL_FLUSH: 3,
  6263. Z_FINISH: 4,
  6264. Z_BLOCK: 5,
  6265. Z_TREES: 6,
  6266.  
  6267. /* Return codes for the compression/decompression functions. Negative values
  6268. * are errors, positive values are used for special but normal events.
  6269. */
  6270. Z_OK: 0,
  6271. Z_STREAM_END: 1,
  6272. Z_NEED_DICT: 2,
  6273. Z_ERRNO: -1,
  6274. Z_STREAM_ERROR: -2,
  6275. Z_DATA_ERROR: -3,
  6276. //Z_MEM_ERROR: -4,
  6277. Z_BUF_ERROR: -5,
  6278. //Z_VERSION_ERROR: -6,
  6279.  
  6280. /* compression levels */
  6281. Z_NO_COMPRESSION: 0,
  6282. Z_BEST_SPEED: 1,
  6283. Z_BEST_COMPRESSION: 9,
  6284. Z_DEFAULT_COMPRESSION: -1,
  6285.  
  6286.  
  6287. Z_FILTERED: 1,
  6288. Z_HUFFMAN_ONLY: 2,
  6289. Z_RLE: 3,
  6290. Z_FIXED: 4,
  6291. Z_DEFAULT_STRATEGY: 0,
  6292.  
  6293. /* Possible values of the data_type field (though see inflate()) */
  6294. Z_BINARY: 0,
  6295. Z_TEXT: 1,
  6296. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  6297. Z_UNKNOWN: 2,
  6298.  
  6299. /* The deflate compression method */
  6300. Z_DEFLATED: 8
  6301. //Z_NULL: null // Use -1 or null inline, depending on var type
  6302. };
  6303.  
  6304. },{}],45:[function(require,module,exports){
  6305. 'use strict';
  6306.  
  6307. // Note: we can't get significant speed boost here.
  6308. // So write code to minimize size - no pregenerated tables
  6309. // and array tools dependencies.
  6310.  
  6311. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6312. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6313. //
  6314. // This software is provided 'as-is', without any express or implied
  6315. // warranty. In no event will the authors be held liable for any damages
  6316. // arising from the use of this software.
  6317. //
  6318. // Permission is granted to anyone to use this software for any purpose,
  6319. // including commercial applications, and to alter it and redistribute it
  6320. // freely, subject to the following restrictions:
  6321. //
  6322. // 1. The origin of this software must not be misrepresented; you must not
  6323. // claim that you wrote the original software. If you use this software
  6324. // in a product, an acknowledgment in the product documentation would be
  6325. // appreciated but is not required.
  6326. // 2. Altered source versions must be plainly marked as such, and must not be
  6327. // misrepresented as being the original software.
  6328. // 3. This notice may not be removed or altered from any source distribution.
  6329.  
  6330. // Use ordinary array, since untyped makes no boost here
  6331. function makeTable() {
  6332. var c, table = [];
  6333.  
  6334. for (var n = 0; n < 256; n++) {
  6335. c = n;
  6336. for (var k = 0; k < 8; k++) {
  6337. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  6338. }
  6339. table[n] = c;
  6340. }
  6341.  
  6342. return table;
  6343. }
  6344.  
  6345. // Create table on load. Just 255 signed longs. Not a problem.
  6346. var crcTable = makeTable();
  6347.  
  6348.  
  6349. function crc32(crc, buf, len, pos) {
  6350. var t = crcTable,
  6351. end = pos + len;
  6352.  
  6353. crc ^= -1;
  6354.  
  6355. for (var i = pos; i < end; i++) {
  6356. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  6357. }
  6358.  
  6359. return (crc ^ (-1)); // >>> 0;
  6360. }
  6361.  
  6362.  
  6363. module.exports = crc32;
  6364.  
  6365. },{}],46:[function(require,module,exports){
  6366. 'use strict';
  6367.  
  6368. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6369. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6370. //
  6371. // This software is provided 'as-is', without any express or implied
  6372. // warranty. In no event will the authors be held liable for any damages
  6373. // arising from the use of this software.
  6374. //
  6375. // Permission is granted to anyone to use this software for any purpose,
  6376. // including commercial applications, and to alter it and redistribute it
  6377. // freely, subject to the following restrictions:
  6378. //
  6379. // 1. The origin of this software must not be misrepresented; you must not
  6380. // claim that you wrote the original software. If you use this software
  6381. // in a product, an acknowledgment in the product documentation would be
  6382. // appreciated but is not required.
  6383. // 2. Altered source versions must be plainly marked as such, and must not be
  6384. // misrepresented as being the original software.
  6385. // 3. This notice may not be removed or altered from any source distribution.
  6386.  
  6387. var utils = require('../utils/common');
  6388. var trees = require('./trees');
  6389. var adler32 = require('./adler32');
  6390. var crc32 = require('./crc32');
  6391. var msg = require('./messages');
  6392.  
  6393. /* Public constants ==========================================================*/
  6394. /* ===========================================================================*/
  6395.  
  6396.  
  6397. /* Allowed flush values; see deflate() and inflate() below for details */
  6398. var Z_NO_FLUSH = 0;
  6399. var Z_PARTIAL_FLUSH = 1;
  6400. //var Z_SYNC_FLUSH = 2;
  6401. var Z_FULL_FLUSH = 3;
  6402. var Z_FINISH = 4;
  6403. var Z_BLOCK = 5;
  6404. //var Z_TREES = 6;
  6405.  
  6406.  
  6407. /* Return codes for the compression/decompression functions. Negative values
  6408. * are errors, positive values are used for special but normal events.
  6409. */
  6410. var Z_OK = 0;
  6411. var Z_STREAM_END = 1;
  6412. //var Z_NEED_DICT = 2;
  6413. //var Z_ERRNO = -1;
  6414. var Z_STREAM_ERROR = -2;
  6415. var Z_DATA_ERROR = -3;
  6416. //var Z_MEM_ERROR = -4;
  6417. var Z_BUF_ERROR = -5;
  6418. //var Z_VERSION_ERROR = -6;
  6419.  
  6420.  
  6421. /* compression levels */
  6422. //var Z_NO_COMPRESSION = 0;
  6423. //var Z_BEST_SPEED = 1;
  6424. //var Z_BEST_COMPRESSION = 9;
  6425. var Z_DEFAULT_COMPRESSION = -1;
  6426.  
  6427.  
  6428. var Z_FILTERED = 1;
  6429. var Z_HUFFMAN_ONLY = 2;
  6430. var Z_RLE = 3;
  6431. var Z_FIXED = 4;
  6432. var Z_DEFAULT_STRATEGY = 0;
  6433.  
  6434. /* Possible values of the data_type field (though see inflate()) */
  6435. //var Z_BINARY = 0;
  6436. //var Z_TEXT = 1;
  6437. //var Z_ASCII = 1; // = Z_TEXT
  6438. var Z_UNKNOWN = 2;
  6439.  
  6440.  
  6441. /* The deflate compression method */
  6442. var Z_DEFLATED = 8;
  6443.  
  6444. /*============================================================================*/
  6445.  
  6446.  
  6447. var MAX_MEM_LEVEL = 9;
  6448. /* Maximum value for memLevel in deflateInit2 */
  6449. var MAX_WBITS = 15;
  6450. /* 32K LZ77 window */
  6451. var DEF_MEM_LEVEL = 8;
  6452.  
  6453.  
  6454. var LENGTH_CODES = 29;
  6455. /* number of length codes, not counting the special END_BLOCK code */
  6456. var LITERALS = 256;
  6457. /* number of literal bytes 0..255 */
  6458. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  6459. /* number of Literal or Length codes, including the END_BLOCK code */
  6460. var D_CODES = 30;
  6461. /* number of distance codes */
  6462. var BL_CODES = 19;
  6463. /* number of codes used to transfer the bit lengths */
  6464. var HEAP_SIZE = 2 * L_CODES + 1;
  6465. /* maximum heap size */
  6466. var MAX_BITS = 15;
  6467. /* All codes must not exceed MAX_BITS bits */
  6468.  
  6469. var MIN_MATCH = 3;
  6470. var MAX_MATCH = 258;
  6471. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  6472.  
  6473. var PRESET_DICT = 0x20;
  6474.  
  6475. var INIT_STATE = 42;
  6476. var EXTRA_STATE = 69;
  6477. var NAME_STATE = 73;
  6478. var COMMENT_STATE = 91;
  6479. var HCRC_STATE = 103;
  6480. var BUSY_STATE = 113;
  6481. var FINISH_STATE = 666;
  6482.  
  6483. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  6484. var BS_BLOCK_DONE = 2; /* block flush performed */
  6485. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  6486. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  6487.  
  6488. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  6489.  
  6490. function err(strm, errorCode) {
  6491. strm.msg = msg[errorCode];
  6492. return errorCode;
  6493. }
  6494.  
  6495. function rank(f) {
  6496. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  6497. }
  6498.  
  6499. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  6500.  
  6501.  
  6502. /* =========================================================================
  6503. * Flush as much pending output as possible. All deflate() output goes
  6504. * through this function so some applications may wish to modify it
  6505. * to avoid allocating a large strm->output buffer and copying into it.
  6506. * (See also read_buf()).
  6507. */
  6508. function flush_pending(strm) {
  6509. var s = strm.state;
  6510.  
  6511. //_tr_flush_bits(s);
  6512. var len = s.pending;
  6513. if (len > strm.avail_out) {
  6514. len = strm.avail_out;
  6515. }
  6516. if (len === 0) { return; }
  6517.  
  6518. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  6519. strm.next_out += len;
  6520. s.pending_out += len;
  6521. strm.total_out += len;
  6522. strm.avail_out -= len;
  6523. s.pending -= len;
  6524. if (s.pending === 0) {
  6525. s.pending_out = 0;
  6526. }
  6527. }
  6528.  
  6529.  
  6530. function flush_block_only(s, last) {
  6531. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  6532. s.block_start = s.strstart;
  6533. flush_pending(s.strm);
  6534. }
  6535.  
  6536.  
  6537. function put_byte(s, b) {
  6538. s.pending_buf[s.pending++] = b;
  6539. }
  6540.  
  6541.  
  6542. /* =========================================================================
  6543. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  6544. * IN assertion: the stream state is correct and there is enough room in
  6545. * pending_buf.
  6546. */
  6547. function putShortMSB(s, b) {
  6548. // put_byte(s, (Byte)(b >> 8));
  6549. // put_byte(s, (Byte)(b & 0xff));
  6550. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  6551. s.pending_buf[s.pending++] = b & 0xff;
  6552. }
  6553.  
  6554.  
  6555. /* ===========================================================================
  6556. * Read a new buffer from the current input stream, update the adler32
  6557. * and total number of bytes read. All deflate() input goes through
  6558. * this function so some applications may wish to modify it to avoid
  6559. * allocating a large strm->input buffer and copying from it.
  6560. * (See also flush_pending()).
  6561. */
  6562. function read_buf(strm, buf, start, size) {
  6563. var len = strm.avail_in;
  6564.  
  6565. if (len > size) { len = size; }
  6566. if (len === 0) { return 0; }
  6567.  
  6568. strm.avail_in -= len;
  6569.  
  6570. // zmemcpy(buf, strm->next_in, len);
  6571. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  6572. if (strm.state.wrap === 1) {
  6573. strm.adler = adler32(strm.adler, buf, len, start);
  6574. }
  6575.  
  6576. else if (strm.state.wrap === 2) {
  6577. strm.adler = crc32(strm.adler, buf, len, start);
  6578. }
  6579.  
  6580. strm.next_in += len;
  6581. strm.total_in += len;
  6582.  
  6583. return len;
  6584. }
  6585.  
  6586.  
  6587. /* ===========================================================================
  6588. * Set match_start to the longest match starting at the given string and
  6589. * return its length. Matches shorter or equal to prev_length are discarded,
  6590. * in which case the result is equal to prev_length and match_start is
  6591. * garbage.
  6592. * IN assertions: cur_match is the head of the hash chain for the current
  6593. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  6594. * OUT assertion: the match length is not greater than s->lookahead.
  6595. */
  6596. function longest_match(s, cur_match) {
  6597. var chain_length = s.max_chain_length; /* max hash chain length */
  6598. var scan = s.strstart; /* current string */
  6599. var match; /* matched string */
  6600. var len; /* length of current match */
  6601. var best_len = s.prev_length; /* best match length so far */
  6602. var nice_match = s.nice_match; /* stop if match long enough */
  6603. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  6604. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  6605.  
  6606. var _win = s.window; // shortcut
  6607.  
  6608. var wmask = s.w_mask;
  6609. var prev = s.prev;
  6610.  
  6611. /* Stop when cur_match becomes <= limit. To simplify the code,
  6612. * we prevent matches with the string of window index 0.
  6613. */
  6614.  
  6615. var strend = s.strstart + MAX_MATCH;
  6616. var scan_end1 = _win[scan + best_len - 1];
  6617. var scan_end = _win[scan + best_len];
  6618.  
  6619. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  6620. * It is easy to get rid of this optimization if necessary.
  6621. */
  6622. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  6623.  
  6624. /* Do not waste too much time if we already have a good match: */
  6625. if (s.prev_length >= s.good_match) {
  6626. chain_length >>= 2;
  6627. }
  6628. /* Do not look for matches beyond the end of the input. This is necessary
  6629. * to make deflate deterministic.
  6630. */
  6631. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  6632.  
  6633. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  6634.  
  6635. do {
  6636. // Assert(cur_match < s->strstart, "no future");
  6637. match = cur_match;
  6638.  
  6639. /* Skip to next match if the match length cannot increase
  6640. * or if the match length is less than 2. Note that the checks below
  6641. * for insufficient lookahead only occur occasionally for performance
  6642. * reasons. Therefore uninitialized memory will be accessed, and
  6643. * conditional jumps will be made that depend on those values.
  6644. * However the length of the match is limited to the lookahead, so
  6645. * the output of deflate is not affected by the uninitialized values.
  6646. */
  6647.  
  6648. if (_win[match + best_len] !== scan_end ||
  6649. _win[match + best_len - 1] !== scan_end1 ||
  6650. _win[match] !== _win[scan] ||
  6651. _win[++match] !== _win[scan + 1]) {
  6652. continue;
  6653. }
  6654.  
  6655. /* The check at best_len-1 can be removed because it will be made
  6656. * again later. (This heuristic is not always a win.)
  6657. * It is not necessary to compare scan[2] and match[2] since they
  6658. * are always equal when the other bytes match, given that
  6659. * the hash keys are equal and that HASH_BITS >= 8.
  6660. */
  6661. scan += 2;
  6662. match++;
  6663. // Assert(*scan == *match, "match[2]?");
  6664.  
  6665. /* We check for insufficient lookahead only every 8th comparison;
  6666. * the 256th check will be made at strstart+258.
  6667. */
  6668. do {
  6669. /*jshint noempty:false*/
  6670. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6671. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6672. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6673. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6674. scan < strend);
  6675.  
  6676. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  6677.  
  6678. len = MAX_MATCH - (strend - scan);
  6679. scan = strend - MAX_MATCH;
  6680.  
  6681. if (len > best_len) {
  6682. s.match_start = cur_match;
  6683. best_len = len;
  6684. if (len >= nice_match) {
  6685. break;
  6686. }
  6687. scan_end1 = _win[scan + best_len - 1];
  6688. scan_end = _win[scan + best_len];
  6689. }
  6690. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  6691.  
  6692. if (best_len <= s.lookahead) {
  6693. return best_len;
  6694. }
  6695. return s.lookahead;
  6696. }
  6697.  
  6698.  
  6699. /* ===========================================================================
  6700. * Fill the window when the lookahead becomes insufficient.
  6701. * Updates strstart and lookahead.
  6702. *
  6703. * IN assertion: lookahead < MIN_LOOKAHEAD
  6704. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  6705. * At least one byte has been read, or avail_in == 0; reads are
  6706. * performed for at least two bytes (required for the zip translate_eol
  6707. * option -- not supported here).
  6708. */
  6709. function fill_window(s) {
  6710. var _w_size = s.w_size;
  6711. var p, n, m, more, str;
  6712.  
  6713. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  6714.  
  6715. do {
  6716. more = s.window_size - s.lookahead - s.strstart;
  6717.  
  6718. // JS ints have 32 bit, block below not needed
  6719. /* Deal with !@#$% 64K limit: */
  6720. //if (sizeof(int) <= 2) {
  6721. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  6722. // more = wsize;
  6723. //
  6724. // } else if (more == (unsigned)(-1)) {
  6725. // /* Very unlikely, but possible on 16 bit machine if
  6726. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  6727. // */
  6728. // more--;
  6729. // }
  6730. //}
  6731.  
  6732.  
  6733. /* If the window is almost full and there is insufficient lookahead,
  6734. * move the upper half to the lower one to make room in the upper half.
  6735. */
  6736. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  6737.  
  6738. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  6739. s.match_start -= _w_size;
  6740. s.strstart -= _w_size;
  6741. /* we now have strstart >= MAX_DIST */
  6742. s.block_start -= _w_size;
  6743.  
  6744. /* Slide the hash table (could be avoided with 32 bit values
  6745. at the expense of memory usage). We slide even when level == 0
  6746. to keep the hash table consistent if we switch back to level > 0
  6747. later. (Using level 0 permanently is not an optimal usage of
  6748. zlib, so we don't care about this pathological case.)
  6749. */
  6750.  
  6751. n = s.hash_size;
  6752. p = n;
  6753. do {
  6754. m = s.head[--p];
  6755. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  6756. } while (--n);
  6757.  
  6758. n = _w_size;
  6759. p = n;
  6760. do {
  6761. m = s.prev[--p];
  6762. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  6763. /* If n is not on any hash chain, prev[n] is garbage but
  6764. * its value will never be used.
  6765. */
  6766. } while (--n);
  6767.  
  6768. more += _w_size;
  6769. }
  6770. if (s.strm.avail_in === 0) {
  6771. break;
  6772. }
  6773.  
  6774. /* If there was no sliding:
  6775. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  6776. * more == window_size - lookahead - strstart
  6777. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  6778. * => more >= window_size - 2*WSIZE + 2
  6779. * In the BIG_MEM or MMAP case (not yet supported),
  6780. * window_size == input_size + MIN_LOOKAHEAD &&
  6781. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  6782. * Otherwise, window_size == 2*WSIZE so more >= 2.
  6783. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  6784. */
  6785. //Assert(more >= 2, "more < 2");
  6786. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  6787. s.lookahead += n;
  6788.  
  6789. /* Initialize the hash value now that we have some input: */
  6790. if (s.lookahead + s.insert >= MIN_MATCH) {
  6791. str = s.strstart - s.insert;
  6792. s.ins_h = s.window[str];
  6793.  
  6794. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  6795. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  6796. //#if MIN_MATCH != 3
  6797. // Call update_hash() MIN_MATCH-3 more times
  6798. //#endif
  6799. while (s.insert) {
  6800. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6801. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  6802.  
  6803. s.prev[str & s.w_mask] = s.head[s.ins_h];
  6804. s.head[s.ins_h] = str;
  6805. str++;
  6806. s.insert--;
  6807. if (s.lookahead + s.insert < MIN_MATCH) {
  6808. break;
  6809. }
  6810. }
  6811. }
  6812. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  6813. * but this is not important since only literal bytes will be emitted.
  6814. */
  6815.  
  6816. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  6817.  
  6818. /* If the WIN_INIT bytes after the end of the current data have never been
  6819. * written, then zero those bytes in order to avoid memory check reports of
  6820. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  6821. * the longest match routines. Update the high water mark for the next
  6822. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  6823. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  6824. */
  6825. // if (s.high_water < s.window_size) {
  6826. // var curr = s.strstart + s.lookahead;
  6827. // var init = 0;
  6828. //
  6829. // if (s.high_water < curr) {
  6830. // /* Previous high water mark below current data -- zero WIN_INIT
  6831. // * bytes or up to end of window, whichever is less.
  6832. // */
  6833. // init = s.window_size - curr;
  6834. // if (init > WIN_INIT)
  6835. // init = WIN_INIT;
  6836. // zmemzero(s->window + curr, (unsigned)init);
  6837. // s->high_water = curr + init;
  6838. // }
  6839. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  6840. // /* High water mark at or above current data, but below current data
  6841. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  6842. // * to end of window, whichever is less.
  6843. // */
  6844. // init = (ulg)curr + WIN_INIT - s->high_water;
  6845. // if (init > s->window_size - s->high_water)
  6846. // init = s->window_size - s->high_water;
  6847. // zmemzero(s->window + s->high_water, (unsigned)init);
  6848. // s->high_water += init;
  6849. // }
  6850. // }
  6851. //
  6852. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  6853. // "not enough room for search");
  6854. }
  6855.  
  6856. /* ===========================================================================
  6857. * Copy without compression as much as possible from the input stream, return
  6858. * the current block state.
  6859. * This function does not insert new strings in the dictionary since
  6860. * uncompressible data is probably not useful. This function is used
  6861. * only for the level=0 compression option.
  6862. * NOTE: this function should be optimized to avoid extra copying from
  6863. * window to pending_buf.
  6864. */
  6865. function deflate_stored(s, flush) {
  6866. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  6867. * to pending_buf_size, and each stored block has a 5 byte header:
  6868. */
  6869. var max_block_size = 0xffff;
  6870.  
  6871. if (max_block_size > s.pending_buf_size - 5) {
  6872. max_block_size = s.pending_buf_size - 5;
  6873. }
  6874.  
  6875. /* Copy as much as possible from input to output: */
  6876. for (;;) {
  6877. /* Fill the window as much as possible: */
  6878. if (s.lookahead <= 1) {
  6879.  
  6880. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  6881. // s->block_start >= (long)s->w_size, "slide too late");
  6882. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  6883. // s.block_start >= s.w_size)) {
  6884. // throw new Error("slide too late");
  6885. // }
  6886.  
  6887. fill_window(s);
  6888. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  6889. return BS_NEED_MORE;
  6890. }
  6891.  
  6892. if (s.lookahead === 0) {
  6893. break;
  6894. }
  6895. /* flush the current block */
  6896. }
  6897. //Assert(s->block_start >= 0L, "block gone");
  6898. // if (s.block_start < 0) throw new Error("block gone");
  6899.  
  6900. s.strstart += s.lookahead;
  6901. s.lookahead = 0;
  6902.  
  6903. /* Emit a stored block if pending_buf will be full: */
  6904. var max_start = s.block_start + max_block_size;
  6905.  
  6906. if (s.strstart === 0 || s.strstart >= max_start) {
  6907. /* strstart == 0 is possible when wraparound on 16-bit machine */
  6908. s.lookahead = s.strstart - max_start;
  6909. s.strstart = max_start;
  6910. /*** FLUSH_BLOCK(s, 0); ***/
  6911. flush_block_only(s, false);
  6912. if (s.strm.avail_out === 0) {
  6913. return BS_NEED_MORE;
  6914. }
  6915. /***/
  6916.  
  6917.  
  6918. }
  6919. /* Flush if we may have to slide, otherwise block_start may become
  6920. * negative and the data will be gone:
  6921. */
  6922. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  6923. /*** FLUSH_BLOCK(s, 0); ***/
  6924. flush_block_only(s, false);
  6925. if (s.strm.avail_out === 0) {
  6926. return BS_NEED_MORE;
  6927. }
  6928. /***/
  6929. }
  6930. }
  6931.  
  6932. s.insert = 0;
  6933.  
  6934. if (flush === Z_FINISH) {
  6935. /*** FLUSH_BLOCK(s, 1); ***/
  6936. flush_block_only(s, true);
  6937. if (s.strm.avail_out === 0) {
  6938. return BS_FINISH_STARTED;
  6939. }
  6940. /***/
  6941. return BS_FINISH_DONE;
  6942. }
  6943.  
  6944. if (s.strstart > s.block_start) {
  6945. /*** FLUSH_BLOCK(s, 0); ***/
  6946. flush_block_only(s, false);
  6947. if (s.strm.avail_out === 0) {
  6948. return BS_NEED_MORE;
  6949. }
  6950. /***/
  6951. }
  6952.  
  6953. return BS_NEED_MORE;
  6954. }
  6955.  
  6956. /* ===========================================================================
  6957. * Compress as much as possible from the input stream, return the current
  6958. * block state.
  6959. * This function does not perform lazy evaluation of matches and inserts
  6960. * new strings in the dictionary only for unmatched strings or for short
  6961. * matches. It is used only for the fast compression options.
  6962. */
  6963. function deflate_fast(s, flush) {
  6964. var hash_head; /* head of the hash chain */
  6965. var bflush; /* set if current block must be flushed */
  6966.  
  6967. for (;;) {
  6968. /* Make sure that we always have enough lookahead, except
  6969. * at the end of the input file. We need MAX_MATCH bytes
  6970. * for the next match, plus MIN_MATCH bytes to insert the
  6971. * string following the next match.
  6972. */
  6973. if (s.lookahead < MIN_LOOKAHEAD) {
  6974. fill_window(s);
  6975. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6976. return BS_NEED_MORE;
  6977. }
  6978. if (s.lookahead === 0) {
  6979. break; /* flush the current block */
  6980. }
  6981. }
  6982.  
  6983. /* Insert the string window[strstart .. strstart+2] in the
  6984. * dictionary, and set hash_head to the head of the hash chain:
  6985. */
  6986. hash_head = 0/*NIL*/;
  6987. if (s.lookahead >= MIN_MATCH) {
  6988. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6989. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6990. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6991. s.head[s.ins_h] = s.strstart;
  6992. /***/
  6993. }
  6994.  
  6995. /* Find the longest match, discarding those <= prev_length.
  6996. * At this point we have always match_length < MIN_MATCH
  6997. */
  6998. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  6999. /* To simplify the code, we prevent matches with the string
  7000. * of window index 0 (in particular we have to avoid a match
  7001. * of the string with itself at the start of the input file).
  7002. */
  7003. s.match_length = longest_match(s, hash_head);
  7004. /* longest_match() sets match_start */
  7005. }
  7006. if (s.match_length >= MIN_MATCH) {
  7007. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  7008.  
  7009. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  7010. s.match_length - MIN_MATCH, bflush); ***/
  7011. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  7012.  
  7013. s.lookahead -= s.match_length;
  7014.  
  7015. /* Insert new strings in the hash table only if the match length
  7016. * is not too large. This saves time but degrades compression.
  7017. */
  7018. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  7019. s.match_length--; /* string at strstart already in table */
  7020. do {
  7021. s.strstart++;
  7022. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7023. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7024. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7025. s.head[s.ins_h] = s.strstart;
  7026. /***/
  7027. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  7028. * always MIN_MATCH bytes ahead.
  7029. */
  7030. } while (--s.match_length !== 0);
  7031. s.strstart++;
  7032. } else
  7033. {
  7034. s.strstart += s.match_length;
  7035. s.match_length = 0;
  7036. s.ins_h = s.window[s.strstart];
  7037. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  7038. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  7039.  
  7040. //#if MIN_MATCH != 3
  7041. // Call UPDATE_HASH() MIN_MATCH-3 more times
  7042. //#endif
  7043. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  7044. * matter since it will be recomputed at next deflate call.
  7045. */
  7046. }
  7047. } else {
  7048. /* No match, output a literal byte */
  7049. //Tracevv((stderr,"%c", s.window[s.strstart]));
  7050. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7051. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7052.  
  7053. s.lookahead--;
  7054. s.strstart++;
  7055. }
  7056. if (bflush) {
  7057. /*** FLUSH_BLOCK(s, 0); ***/
  7058. flush_block_only(s, false);
  7059. if (s.strm.avail_out === 0) {
  7060. return BS_NEED_MORE;
  7061. }
  7062. /***/
  7063. }
  7064. }
  7065. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  7066. if (flush === Z_FINISH) {
  7067. /*** FLUSH_BLOCK(s, 1); ***/
  7068. flush_block_only(s, true);
  7069. if (s.strm.avail_out === 0) {
  7070. return BS_FINISH_STARTED;
  7071. }
  7072. /***/
  7073. return BS_FINISH_DONE;
  7074. }
  7075. if (s.last_lit) {
  7076. /*** FLUSH_BLOCK(s, 0); ***/
  7077. flush_block_only(s, false);
  7078. if (s.strm.avail_out === 0) {
  7079. return BS_NEED_MORE;
  7080. }
  7081. /***/
  7082. }
  7083. return BS_BLOCK_DONE;
  7084. }
  7085.  
  7086. /* ===========================================================================
  7087. * Same as above, but achieves better compression. We use a lazy
  7088. * evaluation for matches: a match is finally adopted only if there is
  7089. * no better match at the next window position.
  7090. */
  7091. function deflate_slow(s, flush) {
  7092. var hash_head; /* head of hash chain */
  7093. var bflush; /* set if current block must be flushed */
  7094.  
  7095. var max_insert;
  7096.  
  7097. /* Process the input block. */
  7098. for (;;) {
  7099. /* Make sure that we always have enough lookahead, except
  7100. * at the end of the input file. We need MAX_MATCH bytes
  7101. * for the next match, plus MIN_MATCH bytes to insert the
  7102. * string following the next match.
  7103. */
  7104. if (s.lookahead < MIN_LOOKAHEAD) {
  7105. fill_window(s);
  7106. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  7107. return BS_NEED_MORE;
  7108. }
  7109. if (s.lookahead === 0) { break; } /* flush the current block */
  7110. }
  7111.  
  7112. /* Insert the string window[strstart .. strstart+2] in the
  7113. * dictionary, and set hash_head to the head of the hash chain:
  7114. */
  7115. hash_head = 0/*NIL*/;
  7116. if (s.lookahead >= MIN_MATCH) {
  7117. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7118. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7119. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7120. s.head[s.ins_h] = s.strstart;
  7121. /***/
  7122. }
  7123.  
  7124. /* Find the longest match, discarding those <= prev_length.
  7125. */
  7126. s.prev_length = s.match_length;
  7127. s.prev_match = s.match_start;
  7128. s.match_length = MIN_MATCH - 1;
  7129.  
  7130. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  7131. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  7132. /* To simplify the code, we prevent matches with the string
  7133. * of window index 0 (in particular we have to avoid a match
  7134. * of the string with itself at the start of the input file).
  7135. */
  7136. s.match_length = longest_match(s, hash_head);
  7137. /* longest_match() sets match_start */
  7138.  
  7139. if (s.match_length <= 5 &&
  7140. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  7141.  
  7142. /* If prev_match is also MIN_MATCH, match_start is garbage
  7143. * but we will ignore the current match anyway.
  7144. */
  7145. s.match_length = MIN_MATCH - 1;
  7146. }
  7147. }
  7148. /* If there was a match at the previous step and the current
  7149. * match is not better, output the previous match:
  7150. */
  7151. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  7152. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  7153. /* Do not insert strings in hash table beyond this. */
  7154.  
  7155. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  7156.  
  7157. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  7158. s.prev_length - MIN_MATCH, bflush);***/
  7159. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  7160. /* Insert in hash table all strings up to the end of the match.
  7161. * strstart-1 and strstart are already inserted. If there is not
  7162. * enough lookahead, the last two strings are not inserted in
  7163. * the hash table.
  7164. */
  7165. s.lookahead -= s.prev_length - 1;
  7166. s.prev_length -= 2;
  7167. do {
  7168. if (++s.strstart <= max_insert) {
  7169. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7170. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7171. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7172. s.head[s.ins_h] = s.strstart;
  7173. /***/
  7174. }
  7175. } while (--s.prev_length !== 0);
  7176. s.match_available = 0;
  7177. s.match_length = MIN_MATCH - 1;
  7178. s.strstart++;
  7179.  
  7180. if (bflush) {
  7181. /*** FLUSH_BLOCK(s, 0); ***/
  7182. flush_block_only(s, false);
  7183. if (s.strm.avail_out === 0) {
  7184. return BS_NEED_MORE;
  7185. }
  7186. /***/
  7187. }
  7188.  
  7189. } else if (s.match_available) {
  7190. /* If there was no match at the previous position, output a
  7191. * single literal. If there was a match but the current match
  7192. * is longer, truncate the previous match to a single literal.
  7193. */
  7194. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  7195. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  7196. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  7197.  
  7198. if (bflush) {
  7199. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  7200. flush_block_only(s, false);
  7201. /***/
  7202. }
  7203. s.strstart++;
  7204. s.lookahead--;
  7205. if (s.strm.avail_out === 0) {
  7206. return BS_NEED_MORE;
  7207. }
  7208. } else {
  7209. /* There is no previous match to compare with, wait for
  7210. * the next step to decide.
  7211. */
  7212. s.match_available = 1;
  7213. s.strstart++;
  7214. s.lookahead--;
  7215. }
  7216. }
  7217. //Assert (flush != Z_NO_FLUSH, "no flush?");
  7218. if (s.match_available) {
  7219. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  7220. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  7221. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  7222.  
  7223. s.match_available = 0;
  7224. }
  7225. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  7226. if (flush === Z_FINISH) {
  7227. /*** FLUSH_BLOCK(s, 1); ***/
  7228. flush_block_only(s, true);
  7229. if (s.strm.avail_out === 0) {
  7230. return BS_FINISH_STARTED;
  7231. }
  7232. /***/
  7233. return BS_FINISH_DONE;
  7234. }
  7235. if (s.last_lit) {
  7236. /*** FLUSH_BLOCK(s, 0); ***/
  7237. flush_block_only(s, false);
  7238. if (s.strm.avail_out === 0) {
  7239. return BS_NEED_MORE;
  7240. }
  7241. /***/
  7242. }
  7243.  
  7244. return BS_BLOCK_DONE;
  7245. }
  7246.  
  7247.  
  7248. /* ===========================================================================
  7249. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  7250. * one. Do not maintain a hash table. (It will be regenerated if this run of
  7251. * deflate switches away from Z_RLE.)
  7252. */
  7253. function deflate_rle(s, flush) {
  7254. var bflush; /* set if current block must be flushed */
  7255. var prev; /* byte at distance one to match */
  7256. var scan, strend; /* scan goes up to strend for length of run */
  7257.  
  7258. var _win = s.window;
  7259.  
  7260. for (;;) {
  7261. /* Make sure that we always have enough lookahead, except
  7262. * at the end of the input file. We need MAX_MATCH bytes
  7263. * for the longest run, plus one for the unrolled loop.
  7264. */
  7265. if (s.lookahead <= MAX_MATCH) {
  7266. fill_window(s);
  7267. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  7268. return BS_NEED_MORE;
  7269. }
  7270. if (s.lookahead === 0) { break; } /* flush the current block */
  7271. }
  7272.  
  7273. /* See how many times the previous byte repeats */
  7274. s.match_length = 0;
  7275. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  7276. scan = s.strstart - 1;
  7277. prev = _win[scan];
  7278. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  7279. strend = s.strstart + MAX_MATCH;
  7280. do {
  7281. /*jshint noempty:false*/
  7282. } while (prev === _win[++scan] && prev === _win[++scan] &&
  7283. prev === _win[++scan] && prev === _win[++scan] &&
  7284. prev === _win[++scan] && prev === _win[++scan] &&
  7285. prev === _win[++scan] && prev === _win[++scan] &&
  7286. scan < strend);
  7287. s.match_length = MAX_MATCH - (strend - scan);
  7288. if (s.match_length > s.lookahead) {
  7289. s.match_length = s.lookahead;
  7290. }
  7291. }
  7292. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  7293. }
  7294.  
  7295. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  7296. if (s.match_length >= MIN_MATCH) {
  7297. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  7298.  
  7299. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  7300. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  7301.  
  7302. s.lookahead -= s.match_length;
  7303. s.strstart += s.match_length;
  7304. s.match_length = 0;
  7305. } else {
  7306. /* No match, output a literal byte */
  7307. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7308. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7309. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7310.  
  7311. s.lookahead--;
  7312. s.strstart++;
  7313. }
  7314. if (bflush) {
  7315. /*** FLUSH_BLOCK(s, 0); ***/
  7316. flush_block_only(s, false);
  7317. if (s.strm.avail_out === 0) {
  7318. return BS_NEED_MORE;
  7319. }
  7320. /***/
  7321. }
  7322. }
  7323. s.insert = 0;
  7324. if (flush === Z_FINISH) {
  7325. /*** FLUSH_BLOCK(s, 1); ***/
  7326. flush_block_only(s, true);
  7327. if (s.strm.avail_out === 0) {
  7328. return BS_FINISH_STARTED;
  7329. }
  7330. /***/
  7331. return BS_FINISH_DONE;
  7332. }
  7333. if (s.last_lit) {
  7334. /*** FLUSH_BLOCK(s, 0); ***/
  7335. flush_block_only(s, false);
  7336. if (s.strm.avail_out === 0) {
  7337. return BS_NEED_MORE;
  7338. }
  7339. /***/
  7340. }
  7341. return BS_BLOCK_DONE;
  7342. }
  7343.  
  7344. /* ===========================================================================
  7345. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  7346. * (It will be regenerated if this run of deflate switches away from Huffman.)
  7347. */
  7348. function deflate_huff(s, flush) {
  7349. var bflush; /* set if current block must be flushed */
  7350.  
  7351. for (;;) {
  7352. /* Make sure that we have a literal to write. */
  7353. if (s.lookahead === 0) {
  7354. fill_window(s);
  7355. if (s.lookahead === 0) {
  7356. if (flush === Z_NO_FLUSH) {
  7357. return BS_NEED_MORE;
  7358. }
  7359. break; /* flush the current block */
  7360. }
  7361. }
  7362.  
  7363. /* Output a literal byte */
  7364. s.match_length = 0;
  7365. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7366. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7367. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7368. s.lookahead--;
  7369. s.strstart++;
  7370. if (bflush) {
  7371. /*** FLUSH_BLOCK(s, 0); ***/
  7372. flush_block_only(s, false);
  7373. if (s.strm.avail_out === 0) {
  7374. return BS_NEED_MORE;
  7375. }
  7376. /***/
  7377. }
  7378. }
  7379. s.insert = 0;
  7380. if (flush === Z_FINISH) {
  7381. /*** FLUSH_BLOCK(s, 1); ***/
  7382. flush_block_only(s, true);
  7383. if (s.strm.avail_out === 0) {
  7384. return BS_FINISH_STARTED;
  7385. }
  7386. /***/
  7387. return BS_FINISH_DONE;
  7388. }
  7389. if (s.last_lit) {
  7390. /*** FLUSH_BLOCK(s, 0); ***/
  7391. flush_block_only(s, false);
  7392. if (s.strm.avail_out === 0) {
  7393. return BS_NEED_MORE;
  7394. }
  7395. /***/
  7396. }
  7397. return BS_BLOCK_DONE;
  7398. }
  7399.  
  7400. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  7401. * the desired pack level (0..9). The values given below have been tuned to
  7402. * exclude worst case performance for pathological files. Better values may be
  7403. * found for specific files.
  7404. */
  7405. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  7406. this.good_length = good_length;
  7407. this.max_lazy = max_lazy;
  7408. this.nice_length = nice_length;
  7409. this.max_chain = max_chain;
  7410. this.func = func;
  7411. }
  7412.  
  7413. var configuration_table;
  7414.  
  7415. configuration_table = [
  7416. /* good lazy nice chain */
  7417. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  7418. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  7419. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  7420. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  7421.  
  7422. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  7423. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  7424. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  7425. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  7426. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  7427. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  7428. ];
  7429.  
  7430.  
  7431. /* ===========================================================================
  7432. * Initialize the "longest match" routines for a new zlib stream
  7433. */
  7434. function lm_init(s) {
  7435. s.window_size = 2 * s.w_size;
  7436.  
  7437. /*** CLEAR_HASH(s); ***/
  7438. zero(s.head); // Fill with NIL (= 0);
  7439.  
  7440. /* Set the default configuration parameters:
  7441. */
  7442. s.max_lazy_match = configuration_table[s.level].max_lazy;
  7443. s.good_match = configuration_table[s.level].good_length;
  7444. s.nice_match = configuration_table[s.level].nice_length;
  7445. s.max_chain_length = configuration_table[s.level].max_chain;
  7446.  
  7447. s.strstart = 0;
  7448. s.block_start = 0;
  7449. s.lookahead = 0;
  7450. s.insert = 0;
  7451. s.match_length = s.prev_length = MIN_MATCH - 1;
  7452. s.match_available = 0;
  7453. s.ins_h = 0;
  7454. }
  7455.  
  7456.  
  7457. function DeflateState() {
  7458. this.strm = null; /* pointer back to this zlib stream */
  7459. this.status = 0; /* as the name implies */
  7460. this.pending_buf = null; /* output still pending */
  7461. this.pending_buf_size = 0; /* size of pending_buf */
  7462. this.pending_out = 0; /* next pending byte to output to the stream */
  7463. this.pending = 0; /* nb of bytes in the pending buffer */
  7464. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  7465. this.gzhead = null; /* gzip header information to write */
  7466. this.gzindex = 0; /* where in extra, name, or comment */
  7467. this.method = Z_DEFLATED; /* can only be DEFLATED */
  7468. this.last_flush = -1; /* value of flush param for previous deflate call */
  7469.  
  7470. this.w_size = 0; /* LZ77 window size (32K by default) */
  7471. this.w_bits = 0; /* log2(w_size) (8..16) */
  7472. this.w_mask = 0; /* w_size - 1 */
  7473.  
  7474. this.window = null;
  7475. /* Sliding window. Input bytes are read into the second half of the window,
  7476. * and move to the first half later to keep a dictionary of at least wSize
  7477. * bytes. With this organization, matches are limited to a distance of
  7478. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  7479. * performed with a length multiple of the block size.
  7480. */
  7481.  
  7482. this.window_size = 0;
  7483. /* Actual size of window: 2*wSize, except when the user input buffer
  7484. * is directly used as sliding window.
  7485. */
  7486.  
  7487. this.prev = null;
  7488. /* Link to older string with same hash index. To limit the size of this
  7489. * array to 64K, this link is maintained only for the last 32K strings.
  7490. * An index in this array is thus a window index modulo 32K.
  7491. */
  7492.  
  7493. this.head = null; /* Heads of the hash chains or NIL. */
  7494.  
  7495. this.ins_h = 0; /* hash index of string to be inserted */
  7496. this.hash_size = 0; /* number of elements in hash table */
  7497. this.hash_bits = 0; /* log2(hash_size) */
  7498. this.hash_mask = 0; /* hash_size-1 */
  7499.  
  7500. this.hash_shift = 0;
  7501. /* Number of bits by which ins_h must be shifted at each input
  7502. * step. It must be such that after MIN_MATCH steps, the oldest
  7503. * byte no longer takes part in the hash key, that is:
  7504. * hash_shift * MIN_MATCH >= hash_bits
  7505. */
  7506.  
  7507. this.block_start = 0;
  7508. /* Window position at the beginning of the current output block. Gets
  7509. * negative when the window is moved backwards.
  7510. */
  7511.  
  7512. this.match_length = 0; /* length of best match */
  7513. this.prev_match = 0; /* previous match */
  7514. this.match_available = 0; /* set if previous match exists */
  7515. this.strstart = 0; /* start of string to insert */
  7516. this.match_start = 0; /* start of matching string */
  7517. this.lookahead = 0; /* number of valid bytes ahead in window */
  7518.  
  7519. this.prev_length = 0;
  7520. /* Length of the best match at previous step. Matches not greater than this
  7521. * are discarded. This is used in the lazy match evaluation.
  7522. */
  7523.  
  7524. this.max_chain_length = 0;
  7525. /* To speed up deflation, hash chains are never searched beyond this
  7526. * length. A higher limit improves compression ratio but degrades the
  7527. * speed.
  7528. */
  7529.  
  7530. this.max_lazy_match = 0;
  7531. /* Attempt to find a better match only when the current match is strictly
  7532. * smaller than this value. This mechanism is used only for compression
  7533. * levels >= 4.
  7534. */
  7535. // That's alias to max_lazy_match, don't use directly
  7536. //this.max_insert_length = 0;
  7537. /* Insert new strings in the hash table only if the match length is not
  7538. * greater than this length. This saves time but degrades compression.
  7539. * max_insert_length is used only for compression levels <= 3.
  7540. */
  7541.  
  7542. this.level = 0; /* compression level (1..9) */
  7543. this.strategy = 0; /* favor or force Huffman coding*/
  7544.  
  7545. this.good_match = 0;
  7546. /* Use a faster search when the previous match is longer than this */
  7547.  
  7548. this.nice_match = 0; /* Stop searching when current match exceeds this */
  7549.  
  7550. /* used by trees.c: */
  7551.  
  7552. /* Didn't use ct_data typedef below to suppress compiler warning */
  7553.  
  7554. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  7555. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  7556. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  7557.  
  7558. // Use flat array of DOUBLE size, with interleaved fata,
  7559. // because JS does not support effective
  7560. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  7561. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  7562. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  7563. zero(this.dyn_ltree);
  7564. zero(this.dyn_dtree);
  7565. zero(this.bl_tree);
  7566.  
  7567. this.l_desc = null; /* desc. for literal tree */
  7568. this.d_desc = null; /* desc. for distance tree */
  7569. this.bl_desc = null; /* desc. for bit length tree */
  7570.  
  7571. //ush bl_count[MAX_BITS+1];
  7572. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  7573. /* number of codes at each bit length for an optimal tree */
  7574.  
  7575. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  7576. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  7577. zero(this.heap);
  7578.  
  7579. this.heap_len = 0; /* number of elements in the heap */
  7580. this.heap_max = 0; /* element of largest frequency */
  7581. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  7582. * The same heap array is used to build all trees.
  7583. */
  7584.  
  7585. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  7586. zero(this.depth);
  7587. /* Depth of each subtree used as tie breaker for trees of equal frequency
  7588. */
  7589.  
  7590. this.l_buf = 0; /* buffer index for literals or lengths */
  7591.  
  7592. this.lit_bufsize = 0;
  7593. /* Size of match buffer for literals/lengths. There are 4 reasons for
  7594. * limiting lit_bufsize to 64K:
  7595. * - frequencies can be kept in 16 bit counters
  7596. * - if compression is not successful for the first block, all input
  7597. * data is still in the window so we can still emit a stored block even
  7598. * when input comes from standard input. (This can also be done for
  7599. * all blocks if lit_bufsize is not greater than 32K.)
  7600. * - if compression is not successful for a file smaller than 64K, we can
  7601. * even emit a stored file instead of a stored block (saving 5 bytes).
  7602. * This is applicable only for zip (not gzip or zlib).
  7603. * - creating new Huffman trees less frequently may not provide fast
  7604. * adaptation to changes in the input data statistics. (Take for
  7605. * example a binary file with poorly compressible code followed by
  7606. * a highly compressible string table.) Smaller buffer sizes give
  7607. * fast adaptation but have of course the overhead of transmitting
  7608. * trees more frequently.
  7609. * - I can't count above 4
  7610. */
  7611.  
  7612. this.last_lit = 0; /* running index in l_buf */
  7613.  
  7614. this.d_buf = 0;
  7615. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  7616. * the same number of elements. To use different lengths, an extra flag
  7617. * array would be necessary.
  7618. */
  7619.  
  7620. this.opt_len = 0; /* bit length of current block with optimal trees */
  7621. this.static_len = 0; /* bit length of current block with static trees */
  7622. this.matches = 0; /* number of string matches in current block */
  7623. this.insert = 0; /* bytes at end of window left to insert */
  7624.  
  7625.  
  7626. this.bi_buf = 0;
  7627. /* Output buffer. bits are inserted starting at the bottom (least
  7628. * significant bits).
  7629. */
  7630. this.bi_valid = 0;
  7631. /* Number of valid bits in bi_buf. All bits above the last valid bit
  7632. * are always zero.
  7633. */
  7634.  
  7635. // Used for window memory init. We safely ignore it for JS. That makes
  7636. // sense only for pointers and memory check tools.
  7637. //this.high_water = 0;
  7638. /* High water mark offset in window for initialized bytes -- bytes above
  7639. * this are set to zero in order to avoid memory check warnings when
  7640. * longest match routines access bytes past the input. This is then
  7641. * updated to the new high water mark.
  7642. */
  7643. }
  7644.  
  7645.  
  7646. function deflateResetKeep(strm) {
  7647. var s;
  7648.  
  7649. if (!strm || !strm.state) {
  7650. return err(strm, Z_STREAM_ERROR);
  7651. }
  7652.  
  7653. strm.total_in = strm.total_out = 0;
  7654. strm.data_type = Z_UNKNOWN;
  7655.  
  7656. s = strm.state;
  7657. s.pending = 0;
  7658. s.pending_out = 0;
  7659.  
  7660. if (s.wrap < 0) {
  7661. s.wrap = -s.wrap;
  7662. /* was made negative by deflate(..., Z_FINISH); */
  7663. }
  7664. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  7665. strm.adler = (s.wrap === 2) ?
  7666. 0 // crc32(0, Z_NULL, 0)
  7667. :
  7668. 1; // adler32(0, Z_NULL, 0)
  7669. s.last_flush = Z_NO_FLUSH;
  7670. trees._tr_init(s);
  7671. return Z_OK;
  7672. }
  7673.  
  7674.  
  7675. function deflateReset(strm) {
  7676. var ret = deflateResetKeep(strm);
  7677. if (ret === Z_OK) {
  7678. lm_init(strm.state);
  7679. }
  7680. return ret;
  7681. }
  7682.  
  7683.  
  7684. function deflateSetHeader(strm, head) {
  7685. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7686. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  7687. strm.state.gzhead = head;
  7688. return Z_OK;
  7689. }
  7690.  
  7691.  
  7692. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  7693. if (!strm) { // === Z_NULL
  7694. return Z_STREAM_ERROR;
  7695. }
  7696. var wrap = 1;
  7697.  
  7698. if (level === Z_DEFAULT_COMPRESSION) {
  7699. level = 6;
  7700. }
  7701.  
  7702. if (windowBits < 0) { /* suppress zlib wrapper */
  7703. wrap = 0;
  7704. windowBits = -windowBits;
  7705. }
  7706.  
  7707. else if (windowBits > 15) {
  7708. wrap = 2; /* write gzip wrapper instead */
  7709. windowBits -= 16;
  7710. }
  7711.  
  7712.  
  7713. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  7714. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  7715. strategy < 0 || strategy > Z_FIXED) {
  7716. return err(strm, Z_STREAM_ERROR);
  7717. }
  7718.  
  7719.  
  7720. if (windowBits === 8) {
  7721. windowBits = 9;
  7722. }
  7723. /* until 256-byte window bug fixed */
  7724.  
  7725. var s = new DeflateState();
  7726.  
  7727. strm.state = s;
  7728. s.strm = strm;
  7729.  
  7730. s.wrap = wrap;
  7731. s.gzhead = null;
  7732. s.w_bits = windowBits;
  7733. s.w_size = 1 << s.w_bits;
  7734. s.w_mask = s.w_size - 1;
  7735.  
  7736. s.hash_bits = memLevel + 7;
  7737. s.hash_size = 1 << s.hash_bits;
  7738. s.hash_mask = s.hash_size - 1;
  7739. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  7740.  
  7741. s.window = new utils.Buf8(s.w_size * 2);
  7742. s.head = new utils.Buf16(s.hash_size);
  7743. s.prev = new utils.Buf16(s.w_size);
  7744.  
  7745. // Don't need mem init magic for JS.
  7746. //s.high_water = 0; /* nothing written to s->window yet */
  7747.  
  7748. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  7749.  
  7750. s.pending_buf_size = s.lit_bufsize * 4;
  7751.  
  7752. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  7753. //s->pending_buf = (uchf *) overlay;
  7754. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  7755.  
  7756. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  7757. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  7758. s.d_buf = 1 * s.lit_bufsize;
  7759.  
  7760. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  7761. s.l_buf = (1 + 2) * s.lit_bufsize;
  7762.  
  7763. s.level = level;
  7764. s.strategy = strategy;
  7765. s.method = method;
  7766.  
  7767. return deflateReset(strm);
  7768. }
  7769.  
  7770. function deflateInit(strm, level) {
  7771. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  7772. }
  7773.  
  7774.  
  7775. function deflate(strm, flush) {
  7776. var old_flush, s;
  7777. var beg, val; // for gzip header write only
  7778.  
  7779. if (!strm || !strm.state ||
  7780. flush > Z_BLOCK || flush < 0) {
  7781. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  7782. }
  7783.  
  7784. s = strm.state;
  7785.  
  7786. if (!strm.output ||
  7787. (!strm.input && strm.avail_in !== 0) ||
  7788. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  7789. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  7790. }
  7791.  
  7792. s.strm = strm; /* just in case */
  7793. old_flush = s.last_flush;
  7794. s.last_flush = flush;
  7795.  
  7796. /* Write the header */
  7797. if (s.status === INIT_STATE) {
  7798.  
  7799. if (s.wrap === 2) { // GZIP header
  7800. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7801. put_byte(s, 31);
  7802. put_byte(s, 139);
  7803. put_byte(s, 8);
  7804. if (!s.gzhead) { // s->gzhead == Z_NULL
  7805. put_byte(s, 0);
  7806. put_byte(s, 0);
  7807. put_byte(s, 0);
  7808. put_byte(s, 0);
  7809. put_byte(s, 0);
  7810. put_byte(s, s.level === 9 ? 2 :
  7811. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7812. 4 : 0));
  7813. put_byte(s, OS_CODE);
  7814. s.status = BUSY_STATE;
  7815. }
  7816. else {
  7817. put_byte(s, (s.gzhead.text ? 1 : 0) +
  7818. (s.gzhead.hcrc ? 2 : 0) +
  7819. (!s.gzhead.extra ? 0 : 4) +
  7820. (!s.gzhead.name ? 0 : 8) +
  7821. (!s.gzhead.comment ? 0 : 16)
  7822. );
  7823. put_byte(s, s.gzhead.time & 0xff);
  7824. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  7825. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  7826. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  7827. put_byte(s, s.level === 9 ? 2 :
  7828. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7829. 4 : 0));
  7830. put_byte(s, s.gzhead.os & 0xff);
  7831. if (s.gzhead.extra && s.gzhead.extra.length) {
  7832. put_byte(s, s.gzhead.extra.length & 0xff);
  7833. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  7834. }
  7835. if (s.gzhead.hcrc) {
  7836. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  7837. }
  7838. s.gzindex = 0;
  7839. s.status = EXTRA_STATE;
  7840. }
  7841. }
  7842. else // DEFLATE header
  7843. {
  7844. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  7845. var level_flags = -1;
  7846.  
  7847. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  7848. level_flags = 0;
  7849. } else if (s.level < 6) {
  7850. level_flags = 1;
  7851. } else if (s.level === 6) {
  7852. level_flags = 2;
  7853. } else {
  7854. level_flags = 3;
  7855. }
  7856. header |= (level_flags << 6);
  7857. if (s.strstart !== 0) { header |= PRESET_DICT; }
  7858. header += 31 - (header % 31);
  7859.  
  7860. s.status = BUSY_STATE;
  7861. putShortMSB(s, header);
  7862.  
  7863. /* Save the adler32 of the preset dictionary: */
  7864. if (s.strstart !== 0) {
  7865. putShortMSB(s, strm.adler >>> 16);
  7866. putShortMSB(s, strm.adler & 0xffff);
  7867. }
  7868. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  7869. }
  7870. }
  7871.  
  7872. //#ifdef GZIP
  7873. if (s.status === EXTRA_STATE) {
  7874. if (s.gzhead.extra/* != Z_NULL*/) {
  7875. beg = s.pending; /* start of bytes to update crc */
  7876.  
  7877. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  7878. if (s.pending === s.pending_buf_size) {
  7879. if (s.gzhead.hcrc && s.pending > beg) {
  7880. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7881. }
  7882. flush_pending(strm);
  7883. beg = s.pending;
  7884. if (s.pending === s.pending_buf_size) {
  7885. break;
  7886. }
  7887. }
  7888. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  7889. s.gzindex++;
  7890. }
  7891. if (s.gzhead.hcrc && s.pending > beg) {
  7892. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7893. }
  7894. if (s.gzindex === s.gzhead.extra.length) {
  7895. s.gzindex = 0;
  7896. s.status = NAME_STATE;
  7897. }
  7898. }
  7899. else {
  7900. s.status = NAME_STATE;
  7901. }
  7902. }
  7903. if (s.status === NAME_STATE) {
  7904. if (s.gzhead.name/* != Z_NULL*/) {
  7905. beg = s.pending; /* start of bytes to update crc */
  7906. //int val;
  7907.  
  7908. do {
  7909. if (s.pending === s.pending_buf_size) {
  7910. if (s.gzhead.hcrc && s.pending > beg) {
  7911. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7912. }
  7913. flush_pending(strm);
  7914. beg = s.pending;
  7915. if (s.pending === s.pending_buf_size) {
  7916. val = 1;
  7917. break;
  7918. }
  7919. }
  7920. // JS specific: little magic to add zero terminator to end of string
  7921. if (s.gzindex < s.gzhead.name.length) {
  7922. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  7923. } else {
  7924. val = 0;
  7925. }
  7926. put_byte(s, val);
  7927. } while (val !== 0);
  7928.  
  7929. if (s.gzhead.hcrc && s.pending > beg) {
  7930. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7931. }
  7932. if (val === 0) {
  7933. s.gzindex = 0;
  7934. s.status = COMMENT_STATE;
  7935. }
  7936. }
  7937. else {
  7938. s.status = COMMENT_STATE;
  7939. }
  7940. }
  7941. if (s.status === COMMENT_STATE) {
  7942. if (s.gzhead.comment/* != Z_NULL*/) {
  7943. beg = s.pending; /* start of bytes to update crc */
  7944. //int val;
  7945.  
  7946. do {
  7947. if (s.pending === s.pending_buf_size) {
  7948. if (s.gzhead.hcrc && s.pending > beg) {
  7949. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7950. }
  7951. flush_pending(strm);
  7952. beg = s.pending;
  7953. if (s.pending === s.pending_buf_size) {
  7954. val = 1;
  7955. break;
  7956. }
  7957. }
  7958. // JS specific: little magic to add zero terminator to end of string
  7959. if (s.gzindex < s.gzhead.comment.length) {
  7960. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  7961. } else {
  7962. val = 0;
  7963. }
  7964. put_byte(s, val);
  7965. } while (val !== 0);
  7966.  
  7967. if (s.gzhead.hcrc && s.pending > beg) {
  7968. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7969. }
  7970. if (val === 0) {
  7971. s.status = HCRC_STATE;
  7972. }
  7973. }
  7974. else {
  7975. s.status = HCRC_STATE;
  7976. }
  7977. }
  7978. if (s.status === HCRC_STATE) {
  7979. if (s.gzhead.hcrc) {
  7980. if (s.pending + 2 > s.pending_buf_size) {
  7981. flush_pending(strm);
  7982. }
  7983. if (s.pending + 2 <= s.pending_buf_size) {
  7984. put_byte(s, strm.adler & 0xff);
  7985. put_byte(s, (strm.adler >> 8) & 0xff);
  7986. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7987. s.status = BUSY_STATE;
  7988. }
  7989. }
  7990. else {
  7991. s.status = BUSY_STATE;
  7992. }
  7993. }
  7994. //#endif
  7995.  
  7996. /* Flush as much pending output as possible */
  7997. if (s.pending !== 0) {
  7998. flush_pending(strm);
  7999. if (strm.avail_out === 0) {
  8000. /* Since avail_out is 0, deflate will be called again with
  8001. * more output space, but possibly with both pending and
  8002. * avail_in equal to zero. There won't be anything to do,
  8003. * but this is not an error situation so make sure we
  8004. * return OK instead of BUF_ERROR at next call of deflate:
  8005. */
  8006. s.last_flush = -1;
  8007. return Z_OK;
  8008. }
  8009.  
  8010. /* Make sure there is something to do and avoid duplicate consecutive
  8011. * flushes. For repeated and useless calls with Z_FINISH, we keep
  8012. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  8013. */
  8014. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  8015. flush !== Z_FINISH) {
  8016. return err(strm, Z_BUF_ERROR);
  8017. }
  8018.  
  8019. /* User must not provide more input after the first FINISH: */
  8020. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  8021. return err(strm, Z_BUF_ERROR);
  8022. }
  8023.  
  8024. /* Start a new block or continue the current one.
  8025. */
  8026. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  8027. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  8028. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  8029. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  8030. configuration_table[s.level].func(s, flush));
  8031.  
  8032. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  8033. s.status = FINISH_STATE;
  8034. }
  8035. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  8036. if (strm.avail_out === 0) {
  8037. s.last_flush = -1;
  8038. /* avoid BUF_ERROR next call, see above */
  8039. }
  8040. return Z_OK;
  8041. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  8042. * of deflate should use the same flush parameter to make sure
  8043. * that the flush is complete. So we don't have to output an
  8044. * empty block here, this will be done at next call. This also
  8045. * ensures that for a very small output buffer, we emit at most
  8046. * one empty block.
  8047. */
  8048. }
  8049. if (bstate === BS_BLOCK_DONE) {
  8050. if (flush === Z_PARTIAL_FLUSH) {
  8051. trees._tr_align(s);
  8052. }
  8053. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  8054.  
  8055. trees._tr_stored_block(s, 0, 0, false);
  8056. /* For a full flush, this empty block will be recognized
  8057. * as a special marker by inflate_sync().
  8058. */
  8059. if (flush === Z_FULL_FLUSH) {
  8060. /*** CLEAR_HASH(s); ***/ /* forget history */
  8061. zero(s.head); // Fill with NIL (= 0);
  8062.  
  8063. if (s.lookahead === 0) {
  8064. s.strstart = 0;
  8065. s.block_start = 0;
  8066. s.insert = 0;
  8067. }
  8068. }
  8069. }
  8070. flush_pending(strm);
  8071. if (strm.avail_out === 0) {
  8072. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  8073. return Z_OK;
  8074. }
  8075. }
  8076. }
  8077. //Assert(strm->avail_out > 0, "bug2");
  8078. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  8079.  
  8080. if (flush !== Z_FINISH) { return Z_OK; }
  8081. if (s.wrap <= 0) { return Z_STREAM_END; }
  8082.  
  8083. /* Write the trailer */
  8084. if (s.wrap === 2) {
  8085. put_byte(s, strm.adler & 0xff);
  8086. put_byte(s, (strm.adler >> 8) & 0xff);
  8087. put_byte(s, (strm.adler >> 16) & 0xff);
  8088. put_byte(s, (strm.adler >> 24) & 0xff);
  8089. put_byte(s, strm.total_in & 0xff);
  8090. put_byte(s, (strm.total_in >> 8) & 0xff);
  8091. put_byte(s, (strm.total_in >> 16) & 0xff);
  8092. put_byte(s, (strm.total_in >> 24) & 0xff);
  8093. }
  8094. else
  8095. {
  8096. putShortMSB(s, strm.adler >>> 16);
  8097. putShortMSB(s, strm.adler & 0xffff);
  8098. }
  8099.  
  8100. flush_pending(strm);
  8101. /* If avail_out is zero, the application will call deflate again
  8102. * to flush the rest.
  8103. */
  8104. if (s.wrap > 0) { s.wrap = -s.wrap; }
  8105. /* write the trailer only once! */
  8106. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  8107. }
  8108.  
  8109. function deflateEnd(strm) {
  8110. var status;
  8111.  
  8112. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  8113. return Z_STREAM_ERROR;
  8114. }
  8115.  
  8116. status = strm.state.status;
  8117. if (status !== INIT_STATE &&
  8118. status !== EXTRA_STATE &&
  8119. status !== NAME_STATE &&
  8120. status !== COMMENT_STATE &&
  8121. status !== HCRC_STATE &&
  8122. status !== BUSY_STATE &&
  8123. status !== FINISH_STATE
  8124. ) {
  8125. return err(strm, Z_STREAM_ERROR);
  8126. }
  8127.  
  8128. strm.state = null;
  8129.  
  8130. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  8131. }
  8132.  
  8133.  
  8134. /* =========================================================================
  8135. * Initializes the compression dictionary from the given byte
  8136. * sequence without producing any compressed output.
  8137. */
  8138. function deflateSetDictionary(strm, dictionary) {
  8139. var dictLength = dictionary.length;
  8140.  
  8141. var s;
  8142. var str, n;
  8143. var wrap;
  8144. var avail;
  8145. var next;
  8146. var input;
  8147. var tmpDict;
  8148.  
  8149. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  8150. return Z_STREAM_ERROR;
  8151. }
  8152.  
  8153. s = strm.state;
  8154. wrap = s.wrap;
  8155.  
  8156. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  8157. return Z_STREAM_ERROR;
  8158. }
  8159.  
  8160. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  8161. if (wrap === 1) {
  8162. /* adler32(strm->adler, dictionary, dictLength); */
  8163. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  8164. }
  8165.  
  8166. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  8167.  
  8168. /* if dictionary would fill window, just replace the history */
  8169. if (dictLength >= s.w_size) {
  8170. if (wrap === 0) { /* already empty otherwise */
  8171. /*** CLEAR_HASH(s); ***/
  8172. zero(s.head); // Fill with NIL (= 0);
  8173. s.strstart = 0;
  8174. s.block_start = 0;
  8175. s.insert = 0;
  8176. }
  8177. /* use the tail */
  8178. // dictionary = dictionary.slice(dictLength - s.w_size);
  8179. tmpDict = new utils.Buf8(s.w_size);
  8180. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  8181. dictionary = tmpDict;
  8182. dictLength = s.w_size;
  8183. }
  8184. /* insert dictionary into window and hash */
  8185. avail = strm.avail_in;
  8186. next = strm.next_in;
  8187. input = strm.input;
  8188. strm.avail_in = dictLength;
  8189. strm.next_in = 0;
  8190. strm.input = dictionary;
  8191. fill_window(s);
  8192. while (s.lookahead >= MIN_MATCH) {
  8193. str = s.strstart;
  8194. n = s.lookahead - (MIN_MATCH - 1);
  8195. do {
  8196. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  8197. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  8198.  
  8199. s.prev[str & s.w_mask] = s.head[s.ins_h];
  8200.  
  8201. s.head[s.ins_h] = str;
  8202. str++;
  8203. } while (--n);
  8204. s.strstart = str;
  8205. s.lookahead = MIN_MATCH - 1;
  8206. fill_window(s);
  8207. }
  8208. s.strstart += s.lookahead;
  8209. s.block_start = s.strstart;
  8210. s.insert = s.lookahead;
  8211. s.lookahead = 0;
  8212. s.match_length = s.prev_length = MIN_MATCH - 1;
  8213. s.match_available = 0;
  8214. strm.next_in = next;
  8215. strm.input = input;
  8216. strm.avail_in = avail;
  8217. s.wrap = wrap;
  8218. return Z_OK;
  8219. }
  8220.  
  8221.  
  8222. exports.deflateInit = deflateInit;
  8223. exports.deflateInit2 = deflateInit2;
  8224. exports.deflateReset = deflateReset;
  8225. exports.deflateResetKeep = deflateResetKeep;
  8226. exports.deflateSetHeader = deflateSetHeader;
  8227. exports.deflate = deflate;
  8228. exports.deflateEnd = deflateEnd;
  8229. exports.deflateSetDictionary = deflateSetDictionary;
  8230. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  8231.  
  8232. /* Not implemented
  8233. exports.deflateBound = deflateBound;
  8234. exports.deflateCopy = deflateCopy;
  8235. exports.deflateParams = deflateParams;
  8236. exports.deflatePending = deflatePending;
  8237. exports.deflatePrime = deflatePrime;
  8238. exports.deflateTune = deflateTune;
  8239. */
  8240.  
  8241. },{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(require,module,exports){
  8242. 'use strict';
  8243.  
  8244. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8245. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8246. //
  8247. // This software is provided 'as-is', without any express or implied
  8248. // warranty. In no event will the authors be held liable for any damages
  8249. // arising from the use of this software.
  8250. //
  8251. // Permission is granted to anyone to use this software for any purpose,
  8252. // including commercial applications, and to alter it and redistribute it
  8253. // freely, subject to the following restrictions:
  8254. //
  8255. // 1. The origin of this software must not be misrepresented; you must not
  8256. // claim that you wrote the original software. If you use this software
  8257. // in a product, an acknowledgment in the product documentation would be
  8258. // appreciated but is not required.
  8259. // 2. Altered source versions must be plainly marked as such, and must not be
  8260. // misrepresented as being the original software.
  8261. // 3. This notice may not be removed or altered from any source distribution.
  8262.  
  8263. function GZheader() {
  8264. /* true if compressed data believed to be text */
  8265. this.text = 0;
  8266. /* modification time */
  8267. this.time = 0;
  8268. /* extra flags (not used when writing a gzip file) */
  8269. this.xflags = 0;
  8270. /* operating system */
  8271. this.os = 0;
  8272. /* pointer to extra field or Z_NULL if none */
  8273. this.extra = null;
  8274. /* extra field length (valid if extra != Z_NULL) */
  8275. this.extra_len = 0; // Actually, we don't need it in JS,
  8276. // but leave for few code modifications
  8277.  
  8278. //
  8279. // Setup limits is not necessary because in js we should not preallocate memory
  8280. // for inflate use constant limit in 65536 bytes
  8281. //
  8282.  
  8283. /* space at extra (only when reading header) */
  8284. // this.extra_max = 0;
  8285. /* pointer to zero-terminated file name or Z_NULL */
  8286. this.name = '';
  8287. /* space at name (only when reading header) */
  8288. // this.name_max = 0;
  8289. /* pointer to zero-terminated comment or Z_NULL */
  8290. this.comment = '';
  8291. /* space at comment (only when reading header) */
  8292. // this.comm_max = 0;
  8293. /* true if there was or will be a header crc */
  8294. this.hcrc = 0;
  8295. /* true when done reading gzip header (not used when writing a gzip file) */
  8296. this.done = false;
  8297. }
  8298.  
  8299. module.exports = GZheader;
  8300.  
  8301. },{}],48:[function(require,module,exports){
  8302. 'use strict';
  8303.  
  8304. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8305. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8306. //
  8307. // This software is provided 'as-is', without any express or implied
  8308. // warranty. In no event will the authors be held liable for any damages
  8309. // arising from the use of this software.
  8310. //
  8311. // Permission is granted to anyone to use this software for any purpose,
  8312. // including commercial applications, and to alter it and redistribute it
  8313. // freely, subject to the following restrictions:
  8314. //
  8315. // 1. The origin of this software must not be misrepresented; you must not
  8316. // claim that you wrote the original software. If you use this software
  8317. // in a product, an acknowledgment in the product documentation would be
  8318. // appreciated but is not required.
  8319. // 2. Altered source versions must be plainly marked as such, and must not be
  8320. // misrepresented as being the original software.
  8321. // 3. This notice may not be removed or altered from any source distribution.
  8322.  
  8323. // See state defs from inflate.js
  8324. var BAD = 30; /* got a data error -- remain here until reset */
  8325. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  8326.  
  8327. /*
  8328. Decode literal, length, and distance codes and write out the resulting
  8329. literal and match bytes until either not enough input or output is
  8330. available, an end-of-block is encountered, or a data error is encountered.
  8331. When large enough input and output buffers are supplied to inflate(), for
  8332. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  8333. inflate execution time is spent in this routine.
  8334.  
  8335. Entry assumptions:
  8336.  
  8337. state.mode === LEN
  8338. strm.avail_in >= 6
  8339. strm.avail_out >= 258
  8340. start >= strm.avail_out
  8341. state.bits < 8
  8342.  
  8343. On return, state.mode is one of:
  8344.  
  8345. LEN -- ran out of enough output space or enough available input
  8346. TYPE -- reached end of block code, inflate() to interpret next block
  8347. BAD -- error in block data
  8348.  
  8349. Notes:
  8350.  
  8351. - The maximum input bits used by a length/distance pair is 15 bits for the
  8352. length code, 5 bits for the length extra, 15 bits for the distance code,
  8353. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  8354. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  8355. checking for available input while decoding.
  8356.  
  8357. - The maximum bytes that a single length/distance pair can output is 258
  8358. bytes, which is the maximum length that can be coded. inflate_fast()
  8359. requires strm.avail_out >= 258 for each loop to avoid checking for
  8360. output space.
  8361. */
  8362. module.exports = function inflate_fast(strm, start) {
  8363. var state;
  8364. var _in; /* local strm.input */
  8365. var last; /* have enough input while in < last */
  8366. var _out; /* local strm.output */
  8367. var beg; /* inflate()'s initial strm.output */
  8368. var end; /* while out < end, enough space available */
  8369. //#ifdef INFLATE_STRICT
  8370. var dmax; /* maximum distance from zlib header */
  8371. //#endif
  8372. var wsize; /* window size or zero if not using window */
  8373. var whave; /* valid bytes in the window */
  8374. var wnext; /* window write index */
  8375. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  8376. var s_window; /* allocated sliding window, if wsize != 0 */
  8377. var hold; /* local strm.hold */
  8378. var bits; /* local strm.bits */
  8379. var lcode; /* local strm.lencode */
  8380. var dcode; /* local strm.distcode */
  8381. var lmask; /* mask for first level of length codes */
  8382. var dmask; /* mask for first level of distance codes */
  8383. var here; /* retrieved table entry */
  8384. var op; /* code bits, operation, extra bits, or */
  8385. /* window position, window bytes to copy */
  8386. var len; /* match length, unused bytes */
  8387. var dist; /* match distance */
  8388. var from; /* where to copy match from */
  8389. var from_source;
  8390.  
  8391.  
  8392. var input, output; // JS specific, because we have no pointers
  8393.  
  8394. /* copy state to local variables */
  8395. state = strm.state;
  8396. //here = state.here;
  8397. _in = strm.next_in;
  8398. input = strm.input;
  8399. last = _in + (strm.avail_in - 5);
  8400. _out = strm.next_out;
  8401. output = strm.output;
  8402. beg = _out - (start - strm.avail_out);
  8403. end = _out + (strm.avail_out - 257);
  8404. //#ifdef INFLATE_STRICT
  8405. dmax = state.dmax;
  8406. //#endif
  8407. wsize = state.wsize;
  8408. whave = state.whave;
  8409. wnext = state.wnext;
  8410. s_window = state.window;
  8411. hold = state.hold;
  8412. bits = state.bits;
  8413. lcode = state.lencode;
  8414. dcode = state.distcode;
  8415. lmask = (1 << state.lenbits) - 1;
  8416. dmask = (1 << state.distbits) - 1;
  8417.  
  8418.  
  8419. /* decode literals and length/distances until end-of-block or not enough
  8420. input data or output space */
  8421.  
  8422. top:
  8423. do {
  8424. if (bits < 15) {
  8425. hold += input[_in++] << bits;
  8426. bits += 8;
  8427. hold += input[_in++] << bits;
  8428. bits += 8;
  8429. }
  8430.  
  8431. here = lcode[hold & lmask];
  8432.  
  8433. dolen:
  8434. for (;;) { // Goto emulation
  8435. op = here >>> 24/*here.bits*/;
  8436. hold >>>= op;
  8437. bits -= op;
  8438. op = (here >>> 16) & 0xff/*here.op*/;
  8439. if (op === 0) { /* literal */
  8440. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8441. // "inflate: literal '%c'\n" :
  8442. // "inflate: literal 0x%02x\n", here.val));
  8443. output[_out++] = here & 0xffff/*here.val*/;
  8444. }
  8445. else if (op & 16) { /* length base */
  8446. len = here & 0xffff/*here.val*/;
  8447. op &= 15; /* number of extra bits */
  8448. if (op) {
  8449. if (bits < op) {
  8450. hold += input[_in++] << bits;
  8451. bits += 8;
  8452. }
  8453. len += hold & ((1 << op) - 1);
  8454. hold >>>= op;
  8455. bits -= op;
  8456. }
  8457. //Tracevv((stderr, "inflate: length %u\n", len));
  8458. if (bits < 15) {
  8459. hold += input[_in++] << bits;
  8460. bits += 8;
  8461. hold += input[_in++] << bits;
  8462. bits += 8;
  8463. }
  8464. here = dcode[hold & dmask];
  8465.  
  8466. dodist:
  8467. for (;;) { // goto emulation
  8468. op = here >>> 24/*here.bits*/;
  8469. hold >>>= op;
  8470. bits -= op;
  8471. op = (here >>> 16) & 0xff/*here.op*/;
  8472.  
  8473. if (op & 16) { /* distance base */
  8474. dist = here & 0xffff/*here.val*/;
  8475. op &= 15; /* number of extra bits */
  8476. if (bits < op) {
  8477. hold += input[_in++] << bits;
  8478. bits += 8;
  8479. if (bits < op) {
  8480. hold += input[_in++] << bits;
  8481. bits += 8;
  8482. }
  8483. }
  8484. dist += hold & ((1 << op) - 1);
  8485. //#ifdef INFLATE_STRICT
  8486. if (dist > dmax) {
  8487. strm.msg = 'invalid distance too far back';
  8488. state.mode = BAD;
  8489. break top;
  8490. }
  8491. //#endif
  8492. hold >>>= op;
  8493. bits -= op;
  8494. //Tracevv((stderr, "inflate: distance %u\n", dist));
  8495. op = _out - beg; /* max distance in output */
  8496. if (dist > op) { /* see if copy from window */
  8497. op = dist - op; /* distance back in window */
  8498. if (op > whave) {
  8499. if (state.sane) {
  8500. strm.msg = 'invalid distance too far back';
  8501. state.mode = BAD;
  8502. break top;
  8503. }
  8504.  
  8505. // (!) This block is disabled in zlib defailts,
  8506. // don't enable it for binary compatibility
  8507. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  8508. // if (len <= op - whave) {
  8509. // do {
  8510. // output[_out++] = 0;
  8511. // } while (--len);
  8512. // continue top;
  8513. // }
  8514. // len -= op - whave;
  8515. // do {
  8516. // output[_out++] = 0;
  8517. // } while (--op > whave);
  8518. // if (op === 0) {
  8519. // from = _out - dist;
  8520. // do {
  8521. // output[_out++] = output[from++];
  8522. // } while (--len);
  8523. // continue top;
  8524. // }
  8525. //#endif
  8526. }
  8527. from = 0; // window index
  8528. from_source = s_window;
  8529. if (wnext === 0) { /* very common case */
  8530. from += wsize - op;
  8531. if (op < len) { /* some from window */
  8532. len -= op;
  8533. do {
  8534. output[_out++] = s_window[from++];
  8535. } while (--op);
  8536. from = _out - dist; /* rest from output */
  8537. from_source = output;
  8538. }
  8539. }
  8540. else if (wnext < op) { /* wrap around window */
  8541. from += wsize + wnext - op;
  8542. op -= wnext;
  8543. if (op < len) { /* some from end of window */
  8544. len -= op;
  8545. do {
  8546. output[_out++] = s_window[from++];
  8547. } while (--op);
  8548. from = 0;
  8549. if (wnext < len) { /* some from start of window */
  8550. op = wnext;
  8551. len -= op;
  8552. do {
  8553. output[_out++] = s_window[from++];
  8554. } while (--op);
  8555. from = _out - dist; /* rest from output */
  8556. from_source = output;
  8557. }
  8558. }
  8559. }
  8560. else { /* contiguous in window */
  8561. from += wnext - op;
  8562. if (op < len) { /* some from window */
  8563. len -= op;
  8564. do {
  8565. output[_out++] = s_window[from++];
  8566. } while (--op);
  8567. from = _out - dist; /* rest from output */
  8568. from_source = output;
  8569. }
  8570. }
  8571. while (len > 2) {
  8572. output[_out++] = from_source[from++];
  8573. output[_out++] = from_source[from++];
  8574. output[_out++] = from_source[from++];
  8575. len -= 3;
  8576. }
  8577. if (len) {
  8578. output[_out++] = from_source[from++];
  8579. if (len > 1) {
  8580. output[_out++] = from_source[from++];
  8581. }
  8582. }
  8583. }
  8584. else {
  8585. from = _out - dist; /* copy direct from output */
  8586. do { /* minimum length is three */
  8587. output[_out++] = output[from++];
  8588. output[_out++] = output[from++];
  8589. output[_out++] = output[from++];
  8590. len -= 3;
  8591. } while (len > 2);
  8592. if (len) {
  8593. output[_out++] = output[from++];
  8594. if (len > 1) {
  8595. output[_out++] = output[from++];
  8596. }
  8597. }
  8598. }
  8599. }
  8600. else if ((op & 64) === 0) { /* 2nd level distance code */
  8601. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8602. continue dodist;
  8603. }
  8604. else {
  8605. strm.msg = 'invalid distance code';
  8606. state.mode = BAD;
  8607. break top;
  8608. }
  8609.  
  8610. break; // need to emulate goto via "continue"
  8611. }
  8612. }
  8613. else if ((op & 64) === 0) { /* 2nd level length code */
  8614. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8615. continue dolen;
  8616. }
  8617. else if (op & 32) { /* end-of-block */
  8618. //Tracevv((stderr, "inflate: end of block\n"));
  8619. state.mode = TYPE;
  8620. break top;
  8621. }
  8622. else {
  8623. strm.msg = 'invalid literal/length code';
  8624. state.mode = BAD;
  8625. break top;
  8626. }
  8627.  
  8628. break; // need to emulate goto via "continue"
  8629. }
  8630. } while (_in < last && _out < end);
  8631.  
  8632. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  8633. len = bits >> 3;
  8634. _in -= len;
  8635. bits -= len << 3;
  8636. hold &= (1 << bits) - 1;
  8637.  
  8638. /* update state and return */
  8639. strm.next_in = _in;
  8640. strm.next_out = _out;
  8641. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  8642. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  8643. state.hold = hold;
  8644. state.bits = bits;
  8645. return;
  8646. };
  8647.  
  8648. },{}],49:[function(require,module,exports){
  8649. 'use strict';
  8650.  
  8651. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8652. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8653. //
  8654. // This software is provided 'as-is', without any express or implied
  8655. // warranty. In no event will the authors be held liable for any damages
  8656. // arising from the use of this software.
  8657. //
  8658. // Permission is granted to anyone to use this software for any purpose,
  8659. // including commercial applications, and to alter it and redistribute it
  8660. // freely, subject to the following restrictions:
  8661. //
  8662. // 1. The origin of this software must not be misrepresented; you must not
  8663. // claim that you wrote the original software. If you use this software
  8664. // in a product, an acknowledgment in the product documentation would be
  8665. // appreciated but is not required.
  8666. // 2. Altered source versions must be plainly marked as such, and must not be
  8667. // misrepresented as being the original software.
  8668. // 3. This notice may not be removed or altered from any source distribution.
  8669.  
  8670. var utils = require('../utils/common');
  8671. var adler32 = require('./adler32');
  8672. var crc32 = require('./crc32');
  8673. var inflate_fast = require('./inffast');
  8674. var inflate_table = require('./inftrees');
  8675.  
  8676. var CODES = 0;
  8677. var LENS = 1;
  8678. var DISTS = 2;
  8679.  
  8680. /* Public constants ==========================================================*/
  8681. /* ===========================================================================*/
  8682.  
  8683.  
  8684. /* Allowed flush values; see deflate() and inflate() below for details */
  8685. //var Z_NO_FLUSH = 0;
  8686. //var Z_PARTIAL_FLUSH = 1;
  8687. //var Z_SYNC_FLUSH = 2;
  8688. //var Z_FULL_FLUSH = 3;
  8689. var Z_FINISH = 4;
  8690. var Z_BLOCK = 5;
  8691. var Z_TREES = 6;
  8692.  
  8693.  
  8694. /* Return codes for the compression/decompression functions. Negative values
  8695. * are errors, positive values are used for special but normal events.
  8696. */
  8697. var Z_OK = 0;
  8698. var Z_STREAM_END = 1;
  8699. var Z_NEED_DICT = 2;
  8700. //var Z_ERRNO = -1;
  8701. var Z_STREAM_ERROR = -2;
  8702. var Z_DATA_ERROR = -3;
  8703. var Z_MEM_ERROR = -4;
  8704. var Z_BUF_ERROR = -5;
  8705. //var Z_VERSION_ERROR = -6;
  8706.  
  8707. /* The deflate compression method */
  8708. var Z_DEFLATED = 8;
  8709.  
  8710.  
  8711. /* STATES ====================================================================*/
  8712. /* ===========================================================================*/
  8713.  
  8714.  
  8715. var HEAD = 1; /* i: waiting for magic header */
  8716. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  8717. var TIME = 3; /* i: waiting for modification time (gzip) */
  8718. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  8719. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  8720. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  8721. var NAME = 7; /* i: waiting for end of file name (gzip) */
  8722. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  8723. var HCRC = 9; /* i: waiting for header crc (gzip) */
  8724. var DICTID = 10; /* i: waiting for dictionary check value */
  8725. var DICT = 11; /* waiting for inflateSetDictionary() call */
  8726. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  8727. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  8728. var STORED = 14; /* i: waiting for stored size (length and complement) */
  8729. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  8730. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  8731. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  8732. var LENLENS = 18; /* i: waiting for code length code lengths */
  8733. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  8734. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  8735. var LEN = 21; /* i: waiting for length/lit/eob code */
  8736. var LENEXT = 22; /* i: waiting for length extra bits */
  8737. var DIST = 23; /* i: waiting for distance code */
  8738. var DISTEXT = 24; /* i: waiting for distance extra bits */
  8739. var MATCH = 25; /* o: waiting for output space to copy string */
  8740. var LIT = 26; /* o: waiting for output space to write literal */
  8741. var CHECK = 27; /* i: waiting for 32-bit check value */
  8742. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  8743. var DONE = 29; /* finished check, done -- remain here until reset */
  8744. var BAD = 30; /* got a data error -- remain here until reset */
  8745. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  8746. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  8747.  
  8748. /* ===========================================================================*/
  8749.  
  8750.  
  8751.  
  8752. var ENOUGH_LENS = 852;
  8753. var ENOUGH_DISTS = 592;
  8754. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  8755.  
  8756. var MAX_WBITS = 15;
  8757. /* 32K LZ77 window */
  8758. var DEF_WBITS = MAX_WBITS;
  8759.  
  8760.  
  8761. function zswap32(q) {
  8762. return (((q >>> 24) & 0xff) +
  8763. ((q >>> 8) & 0xff00) +
  8764. ((q & 0xff00) << 8) +
  8765. ((q & 0xff) << 24));
  8766. }
  8767.  
  8768.  
  8769. function InflateState() {
  8770. this.mode = 0; /* current inflate mode */
  8771. this.last = false; /* true if processing last block */
  8772. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  8773. this.havedict = false; /* true if dictionary provided */
  8774. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  8775. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  8776. this.check = 0; /* protected copy of check value */
  8777. this.total = 0; /* protected copy of output count */
  8778. // TODO: may be {}
  8779. this.head = null; /* where to save gzip header information */
  8780.  
  8781. /* sliding window */
  8782. this.wbits = 0; /* log base 2 of requested window size */
  8783. this.wsize = 0; /* window size or zero if not using window */
  8784. this.whave = 0; /* valid bytes in the window */
  8785. this.wnext = 0; /* window write index */
  8786. this.window = null; /* allocated sliding window, if needed */
  8787.  
  8788. /* bit accumulator */
  8789. this.hold = 0; /* input bit accumulator */
  8790. this.bits = 0; /* number of bits in "in" */
  8791.  
  8792. /* for string and stored block copying */
  8793. this.length = 0; /* literal or length of data to copy */
  8794. this.offset = 0; /* distance back to copy string from */
  8795.  
  8796. /* for table and code decoding */
  8797. this.extra = 0; /* extra bits needed */
  8798.  
  8799. /* fixed and dynamic code tables */
  8800. this.lencode = null; /* starting table for length/literal codes */
  8801. this.distcode = null; /* starting table for distance codes */
  8802. this.lenbits = 0; /* index bits for lencode */
  8803. this.distbits = 0; /* index bits for distcode */
  8804.  
  8805. /* dynamic table building */
  8806. this.ncode = 0; /* number of code length code lengths */
  8807. this.nlen = 0; /* number of length code lengths */
  8808. this.ndist = 0; /* number of distance code lengths */
  8809. this.have = 0; /* number of code lengths in lens[] */
  8810. this.next = null; /* next available space in codes[] */
  8811.  
  8812. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  8813. this.work = new utils.Buf16(288); /* work area for code table building */
  8814.  
  8815. /*
  8816. because we don't have pointers in js, we use lencode and distcode directly
  8817. as buffers so we don't need codes
  8818. */
  8819. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  8820. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  8821. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  8822. this.sane = 0; /* if false, allow invalid distance too far */
  8823. this.back = 0; /* bits back of last unprocessed length/lit */
  8824. this.was = 0; /* initial length of match */
  8825. }
  8826.  
  8827. function inflateResetKeep(strm) {
  8828. var state;
  8829.  
  8830. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8831. state = strm.state;
  8832. strm.total_in = strm.total_out = state.total = 0;
  8833. strm.msg = ''; /*Z_NULL*/
  8834. if (state.wrap) { /* to support ill-conceived Java test suite */
  8835. strm.adler = state.wrap & 1;
  8836. }
  8837. state.mode = HEAD;
  8838. state.last = 0;
  8839. state.havedict = 0;
  8840. state.dmax = 32768;
  8841. state.head = null/*Z_NULL*/;
  8842. state.hold = 0;
  8843. state.bits = 0;
  8844. //state.lencode = state.distcode = state.next = state.codes;
  8845. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  8846. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  8847.  
  8848. state.sane = 1;
  8849. state.back = -1;
  8850. //Tracev((stderr, "inflate: reset\n"));
  8851. return Z_OK;
  8852. }
  8853.  
  8854. function inflateReset(strm) {
  8855. var state;
  8856.  
  8857. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8858. state = strm.state;
  8859. state.wsize = 0;
  8860. state.whave = 0;
  8861. state.wnext = 0;
  8862. return inflateResetKeep(strm);
  8863.  
  8864. }
  8865.  
  8866. function inflateReset2(strm, windowBits) {
  8867. var wrap;
  8868. var state;
  8869.  
  8870. /* get the state */
  8871. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8872. state = strm.state;
  8873.  
  8874. /* extract wrap request from windowBits parameter */
  8875. if (windowBits < 0) {
  8876. wrap = 0;
  8877. windowBits = -windowBits;
  8878. }
  8879. else {
  8880. wrap = (windowBits >> 4) + 1;
  8881. if (windowBits < 48) {
  8882. windowBits &= 15;
  8883. }
  8884. }
  8885.  
  8886. /* set number of window bits, free window if different */
  8887. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  8888. return Z_STREAM_ERROR;
  8889. }
  8890. if (state.window !== null && state.wbits !== windowBits) {
  8891. state.window = null;
  8892. }
  8893.  
  8894. /* update state and reset the rest of it */
  8895. state.wrap = wrap;
  8896. state.wbits = windowBits;
  8897. return inflateReset(strm);
  8898. }
  8899.  
  8900. function inflateInit2(strm, windowBits) {
  8901. var ret;
  8902. var state;
  8903.  
  8904. if (!strm) { return Z_STREAM_ERROR; }
  8905. //strm.msg = Z_NULL; /* in case we return an error */
  8906.  
  8907. state = new InflateState();
  8908.  
  8909. //if (state === Z_NULL) return Z_MEM_ERROR;
  8910. //Tracev((stderr, "inflate: allocated\n"));
  8911. strm.state = state;
  8912. state.window = null/*Z_NULL*/;
  8913. ret = inflateReset2(strm, windowBits);
  8914. if (ret !== Z_OK) {
  8915. strm.state = null/*Z_NULL*/;
  8916. }
  8917. return ret;
  8918. }
  8919.  
  8920. function inflateInit(strm) {
  8921. return inflateInit2(strm, DEF_WBITS);
  8922. }
  8923.  
  8924.  
  8925. /*
  8926. Return state with length and distance decoding tables and index sizes set to
  8927. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  8928. If BUILDFIXED is defined, then instead this routine builds the tables the
  8929. first time it's called, and returns those tables the first time and
  8930. thereafter. This reduces the size of the code by about 2K bytes, in
  8931. exchange for a little execution time. However, BUILDFIXED should not be
  8932. used for threaded applications, since the rewriting of the tables and virgin
  8933. may not be thread-safe.
  8934. */
  8935. var virgin = true;
  8936.  
  8937. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  8938.  
  8939. function fixedtables(state) {
  8940. /* build fixed huffman tables if first call (may not be thread safe) */
  8941. if (virgin) {
  8942. var sym;
  8943.  
  8944. lenfix = new utils.Buf32(512);
  8945. distfix = new utils.Buf32(32);
  8946.  
  8947. /* literal/length table */
  8948. sym = 0;
  8949. while (sym < 144) { state.lens[sym++] = 8; }
  8950. while (sym < 256) { state.lens[sym++] = 9; }
  8951. while (sym < 280) { state.lens[sym++] = 7; }
  8952. while (sym < 288) { state.lens[sym++] = 8; }
  8953.  
  8954. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  8955.  
  8956. /* distance table */
  8957. sym = 0;
  8958. while (sym < 32) { state.lens[sym++] = 5; }
  8959.  
  8960. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  8961.  
  8962. /* do this just once */
  8963. virgin = false;
  8964. }
  8965.  
  8966. state.lencode = lenfix;
  8967. state.lenbits = 9;
  8968. state.distcode = distfix;
  8969. state.distbits = 5;
  8970. }
  8971.  
  8972.  
  8973. /*
  8974. Update the window with the last wsize (normally 32K) bytes written before
  8975. returning. If window does not exist yet, create it. This is only called
  8976. when a window is already in use, or when output has been written during this
  8977. inflate call, but the end of the deflate stream has not been reached yet.
  8978. It is also called to create a window for dictionary data when a dictionary
  8979. is loaded.
  8980.  
  8981. Providing output buffers larger than 32K to inflate() should provide a speed
  8982. advantage, since only the last 32K of output is copied to the sliding window
  8983. upon return from inflate(), and since all distances after the first 32K of
  8984. output will fall in the output data, making match copies simpler and faster.
  8985. The advantage may be dependent on the size of the processor's data caches.
  8986. */
  8987. function updatewindow(strm, src, end, copy) {
  8988. var dist;
  8989. var state = strm.state;
  8990.  
  8991. /* if it hasn't been done already, allocate space for the window */
  8992. if (state.window === null) {
  8993. state.wsize = 1 << state.wbits;
  8994. state.wnext = 0;
  8995. state.whave = 0;
  8996.  
  8997. state.window = new utils.Buf8(state.wsize);
  8998. }
  8999.  
  9000. /* copy state->wsize or less output bytes into the circular window */
  9001. if (copy >= state.wsize) {
  9002. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  9003. state.wnext = 0;
  9004. state.whave = state.wsize;
  9005. }
  9006. else {
  9007. dist = state.wsize - state.wnext;
  9008. if (dist > copy) {
  9009. dist = copy;
  9010. }
  9011. //zmemcpy(state->window + state->wnext, end - copy, dist);
  9012. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  9013. copy -= dist;
  9014. if (copy) {
  9015. //zmemcpy(state->window, end - copy, copy);
  9016. utils.arraySet(state.window, src, end - copy, copy, 0);
  9017. state.wnext = copy;
  9018. state.whave = state.wsize;
  9019. }
  9020. else {
  9021. state.wnext += dist;
  9022. if (state.wnext === state.wsize) { state.wnext = 0; }
  9023. if (state.whave < state.wsize) { state.whave += dist; }
  9024. }
  9025. }
  9026. return 0;
  9027. }
  9028.  
  9029. function inflate(strm, flush) {
  9030. var state;
  9031. var input, output; // input/output buffers
  9032. var next; /* next input INDEX */
  9033. var put; /* next output INDEX */
  9034. var have, left; /* available input and output */
  9035. var hold; /* bit buffer */
  9036. var bits; /* bits in bit buffer */
  9037. var _in, _out; /* save starting available input and output */
  9038. var copy; /* number of stored or match bytes to copy */
  9039. var from; /* where to copy match bytes from */
  9040. var from_source;
  9041. var here = 0; /* current decoding table entry */
  9042. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  9043. //var last; /* parent table entry */
  9044. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  9045. var len; /* length to copy for repeats, bits to drop */
  9046. var ret; /* return code */
  9047. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  9048. var opts;
  9049.  
  9050. var n; // temporary var for NEED_BITS
  9051.  
  9052. var order = /* permutation of code lengths */
  9053. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  9054.  
  9055.  
  9056. if (!strm || !strm.state || !strm.output ||
  9057. (!strm.input && strm.avail_in !== 0)) {
  9058. return Z_STREAM_ERROR;
  9059. }
  9060.  
  9061. state = strm.state;
  9062. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  9063.  
  9064.  
  9065. //--- LOAD() ---
  9066. put = strm.next_out;
  9067. output = strm.output;
  9068. left = strm.avail_out;
  9069. next = strm.next_in;
  9070. input = strm.input;
  9071. have = strm.avail_in;
  9072. hold = state.hold;
  9073. bits = state.bits;
  9074. //---
  9075.  
  9076. _in = have;
  9077. _out = left;
  9078. ret = Z_OK;
  9079.  
  9080. inf_leave: // goto emulation
  9081. for (;;) {
  9082. switch (state.mode) {
  9083. case HEAD:
  9084. if (state.wrap === 0) {
  9085. state.mode = TYPEDO;
  9086. break;
  9087. }
  9088. //=== NEEDBITS(16);
  9089. while (bits < 16) {
  9090. if (have === 0) { break inf_leave; }
  9091. have--;
  9092. hold += input[next++] << bits;
  9093. bits += 8;
  9094. }
  9095. //===//
  9096. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  9097. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  9098. //=== CRC2(state.check, hold);
  9099. hbuf[0] = hold & 0xff;
  9100. hbuf[1] = (hold >>> 8) & 0xff;
  9101. state.check = crc32(state.check, hbuf, 2, 0);
  9102. //===//
  9103.  
  9104. //=== INITBITS();
  9105. hold = 0;
  9106. bits = 0;
  9107. //===//
  9108. state.mode = FLAGS;
  9109. break;
  9110. }
  9111. state.flags = 0; /* expect zlib header */
  9112. if (state.head) {
  9113. state.head.done = false;
  9114. }
  9115. if (!(state.wrap & 1) || /* check if zlib header allowed */
  9116. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  9117. strm.msg = 'incorrect header check';
  9118. state.mode = BAD;
  9119. break;
  9120. }
  9121. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  9122. strm.msg = 'unknown compression method';
  9123. state.mode = BAD;
  9124. break;
  9125. }
  9126. //--- DROPBITS(4) ---//
  9127. hold >>>= 4;
  9128. bits -= 4;
  9129. //---//
  9130. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  9131. if (state.wbits === 0) {
  9132. state.wbits = len;
  9133. }
  9134. else if (len > state.wbits) {
  9135. strm.msg = 'invalid window size';
  9136. state.mode = BAD;
  9137. break;
  9138. }
  9139. state.dmax = 1 << len;
  9140. //Tracev((stderr, "inflate: zlib header ok\n"));
  9141. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  9142. state.mode = hold & 0x200 ? DICTID : TYPE;
  9143. //=== INITBITS();
  9144. hold = 0;
  9145. bits = 0;
  9146. //===//
  9147. break;
  9148. case FLAGS:
  9149. //=== NEEDBITS(16); */
  9150. while (bits < 16) {
  9151. if (have === 0) { break inf_leave; }
  9152. have--;
  9153. hold += input[next++] << bits;
  9154. bits += 8;
  9155. }
  9156. //===//
  9157. state.flags = hold;
  9158. if ((state.flags & 0xff) !== Z_DEFLATED) {
  9159. strm.msg = 'unknown compression method';
  9160. state.mode = BAD;
  9161. break;
  9162. }
  9163. if (state.flags & 0xe000) {
  9164. strm.msg = 'unknown header flags set';
  9165. state.mode = BAD;
  9166. break;
  9167. }
  9168. if (state.head) {
  9169. state.head.text = ((hold >> 8) & 1);
  9170. }
  9171. if (state.flags & 0x0200) {
  9172. //=== CRC2(state.check, hold);
  9173. hbuf[0] = hold & 0xff;
  9174. hbuf[1] = (hold >>> 8) & 0xff;
  9175. state.check = crc32(state.check, hbuf, 2, 0);
  9176. //===//
  9177. }
  9178. //=== INITBITS();
  9179. hold = 0;
  9180. bits = 0;
  9181. //===//
  9182. state.mode = TIME;
  9183. /* falls through */
  9184. case TIME:
  9185. //=== NEEDBITS(32); */
  9186. while (bits < 32) {
  9187. if (have === 0) { break inf_leave; }
  9188. have--;
  9189. hold += input[next++] << bits;
  9190. bits += 8;
  9191. }
  9192. //===//
  9193. if (state.head) {
  9194. state.head.time = hold;
  9195. }
  9196. if (state.flags & 0x0200) {
  9197. //=== CRC4(state.check, hold)
  9198. hbuf[0] = hold & 0xff;
  9199. hbuf[1] = (hold >>> 8) & 0xff;
  9200. hbuf[2] = (hold >>> 16) & 0xff;
  9201. hbuf[3] = (hold >>> 24) & 0xff;
  9202. state.check = crc32(state.check, hbuf, 4, 0);
  9203. //===
  9204. }
  9205. //=== INITBITS();
  9206. hold = 0;
  9207. bits = 0;
  9208. //===//
  9209. state.mode = OS;
  9210. /* falls through */
  9211. case OS:
  9212. //=== NEEDBITS(16); */
  9213. while (bits < 16) {
  9214. if (have === 0) { break inf_leave; }
  9215. have--;
  9216. hold += input[next++] << bits;
  9217. bits += 8;
  9218. }
  9219. //===//
  9220. if (state.head) {
  9221. state.head.xflags = (hold & 0xff);
  9222. state.head.os = (hold >> 8);
  9223. }
  9224. if (state.flags & 0x0200) {
  9225. //=== CRC2(state.check, hold);
  9226. hbuf[0] = hold & 0xff;
  9227. hbuf[1] = (hold >>> 8) & 0xff;
  9228. state.check = crc32(state.check, hbuf, 2, 0);
  9229. //===//
  9230. }
  9231. //=== INITBITS();
  9232. hold = 0;
  9233. bits = 0;
  9234. //===//
  9235. state.mode = EXLEN;
  9236. /* falls through */
  9237. case EXLEN:
  9238. if (state.flags & 0x0400) {
  9239. //=== NEEDBITS(16); */
  9240. while (bits < 16) {
  9241. if (have === 0) { break inf_leave; }
  9242. have--;
  9243. hold += input[next++] << bits;
  9244. bits += 8;
  9245. }
  9246. //===//
  9247. state.length = hold;
  9248. if (state.head) {
  9249. state.head.extra_len = hold;
  9250. }
  9251. if (state.flags & 0x0200) {
  9252. //=== CRC2(state.check, hold);
  9253. hbuf[0] = hold & 0xff;
  9254. hbuf[1] = (hold >>> 8) & 0xff;
  9255. state.check = crc32(state.check, hbuf, 2, 0);
  9256. //===//
  9257. }
  9258. //=== INITBITS();
  9259. hold = 0;
  9260. bits = 0;
  9261. //===//
  9262. }
  9263. else if (state.head) {
  9264. state.head.extra = null/*Z_NULL*/;
  9265. }
  9266. state.mode = EXTRA;
  9267. /* falls through */
  9268. case EXTRA:
  9269. if (state.flags & 0x0400) {
  9270. copy = state.length;
  9271. if (copy > have) { copy = have; }
  9272. if (copy) {
  9273. if (state.head) {
  9274. len = state.head.extra_len - state.length;
  9275. if (!state.head.extra) {
  9276. // Use untyped array for more conveniend processing later
  9277. state.head.extra = new Array(state.head.extra_len);
  9278. }
  9279. utils.arraySet(
  9280. state.head.extra,
  9281. input,
  9282. next,
  9283. // extra field is limited to 65536 bytes
  9284. // - no need for additional size check
  9285. copy,
  9286. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  9287. len
  9288. );
  9289. //zmemcpy(state.head.extra + len, next,
  9290. // len + copy > state.head.extra_max ?
  9291. // state.head.extra_max - len : copy);
  9292. }
  9293. if (state.flags & 0x0200) {
  9294. state.check = crc32(state.check, input, copy, next);
  9295. }
  9296. have -= copy;
  9297. next += copy;
  9298. state.length -= copy;
  9299. }
  9300. if (state.length) { break inf_leave; }
  9301. }
  9302. state.length = 0;
  9303. state.mode = NAME;
  9304. /* falls through */
  9305. case NAME:
  9306. if (state.flags & 0x0800) {
  9307. if (have === 0) { break inf_leave; }
  9308. copy = 0;
  9309. do {
  9310. // TODO: 2 or 1 bytes?
  9311. len = input[next + copy++];
  9312. /* use constant limit because in js we should not preallocate memory */
  9313. if (state.head && len &&
  9314. (state.length < 65536 /*state.head.name_max*/)) {
  9315. state.head.name += String.fromCharCode(len);
  9316. }
  9317. } while (len && copy < have);
  9318.  
  9319. if (state.flags & 0x0200) {
  9320. state.check = crc32(state.check, input, copy, next);
  9321. }
  9322. have -= copy;
  9323. next += copy;
  9324. if (len) { break inf_leave; }
  9325. }
  9326. else if (state.head) {
  9327. state.head.name = null;
  9328. }
  9329. state.length = 0;
  9330. state.mode = COMMENT;
  9331. /* falls through */
  9332. case COMMENT:
  9333. if (state.flags & 0x1000) {
  9334. if (have === 0) { break inf_leave; }
  9335. copy = 0;
  9336. do {
  9337. len = input[next + copy++];
  9338. /* use constant limit because in js we should not preallocate memory */
  9339. if (state.head && len &&
  9340. (state.length < 65536 /*state.head.comm_max*/)) {
  9341. state.head.comment += String.fromCharCode(len);
  9342. }
  9343. } while (len && copy < have);
  9344. if (state.flags & 0x0200) {
  9345. state.check = crc32(state.check, input, copy, next);
  9346. }
  9347. have -= copy;
  9348. next += copy;
  9349. if (len) { break inf_leave; }
  9350. }
  9351. else if (state.head) {
  9352. state.head.comment = null;
  9353. }
  9354. state.mode = HCRC;
  9355. /* falls through */
  9356. case HCRC:
  9357. if (state.flags & 0x0200) {
  9358. //=== NEEDBITS(16); */
  9359. while (bits < 16) {
  9360. if (have === 0) { break inf_leave; }
  9361. have--;
  9362. hold += input[next++] << bits;
  9363. bits += 8;
  9364. }
  9365. //===//
  9366. if (hold !== (state.check & 0xffff)) {
  9367. strm.msg = 'header crc mismatch';
  9368. state.mode = BAD;
  9369. break;
  9370. }
  9371. //=== INITBITS();
  9372. hold = 0;
  9373. bits = 0;
  9374. //===//
  9375. }
  9376. if (state.head) {
  9377. state.head.hcrc = ((state.flags >> 9) & 1);
  9378. state.head.done = true;
  9379. }
  9380. strm.adler = state.check = 0;
  9381. state.mode = TYPE;
  9382. break;
  9383. case DICTID:
  9384. //=== NEEDBITS(32); */
  9385. while (bits < 32) {
  9386. if (have === 0) { break inf_leave; }
  9387. have--;
  9388. hold += input[next++] << bits;
  9389. bits += 8;
  9390. }
  9391. //===//
  9392. strm.adler = state.check = zswap32(hold);
  9393. //=== INITBITS();
  9394. hold = 0;
  9395. bits = 0;
  9396. //===//
  9397. state.mode = DICT;
  9398. /* falls through */
  9399. case DICT:
  9400. if (state.havedict === 0) {
  9401. //--- RESTORE() ---
  9402. strm.next_out = put;
  9403. strm.avail_out = left;
  9404. strm.next_in = next;
  9405. strm.avail_in = have;
  9406. state.hold = hold;
  9407. state.bits = bits;
  9408. //---
  9409. return Z_NEED_DICT;
  9410. }
  9411. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  9412. state.mode = TYPE;
  9413. /* falls through */
  9414. case TYPE:
  9415. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  9416. /* falls through */
  9417. case TYPEDO:
  9418. if (state.last) {
  9419. //--- BYTEBITS() ---//
  9420. hold >>>= bits & 7;
  9421. bits -= bits & 7;
  9422. //---//
  9423. state.mode = CHECK;
  9424. break;
  9425. }
  9426. //=== NEEDBITS(3); */
  9427. while (bits < 3) {
  9428. if (have === 0) { break inf_leave; }
  9429. have--;
  9430. hold += input[next++] << bits;
  9431. bits += 8;
  9432. }
  9433. //===//
  9434. state.last = (hold & 0x01)/*BITS(1)*/;
  9435. //--- DROPBITS(1) ---//
  9436. hold >>>= 1;
  9437. bits -= 1;
  9438. //---//
  9439.  
  9440. switch ((hold & 0x03)/*BITS(2)*/) {
  9441. case 0: /* stored block */
  9442. //Tracev((stderr, "inflate: stored block%s\n",
  9443. // state.last ? " (last)" : ""));
  9444. state.mode = STORED;
  9445. break;
  9446. case 1: /* fixed block */
  9447. fixedtables(state);
  9448. //Tracev((stderr, "inflate: fixed codes block%s\n",
  9449. // state.last ? " (last)" : ""));
  9450. state.mode = LEN_; /* decode codes */
  9451. if (flush === Z_TREES) {
  9452. //--- DROPBITS(2) ---//
  9453. hold >>>= 2;
  9454. bits -= 2;
  9455. //---//
  9456. break inf_leave;
  9457. }
  9458. break;
  9459. case 2: /* dynamic block */
  9460. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  9461. // state.last ? " (last)" : ""));
  9462. state.mode = TABLE;
  9463. break;
  9464. case 3:
  9465. strm.msg = 'invalid block type';
  9466. state.mode = BAD;
  9467. }
  9468. //--- DROPBITS(2) ---//
  9469. hold >>>= 2;
  9470. bits -= 2;
  9471. //---//
  9472. break;
  9473. case STORED:
  9474. //--- BYTEBITS() ---// /* go to byte boundary */
  9475. hold >>>= bits & 7;
  9476. bits -= bits & 7;
  9477. //---//
  9478. //=== NEEDBITS(32); */
  9479. while (bits < 32) {
  9480. if (have === 0) { break inf_leave; }
  9481. have--;
  9482. hold += input[next++] << bits;
  9483. bits += 8;
  9484. }
  9485. //===//
  9486. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  9487. strm.msg = 'invalid stored block lengths';
  9488. state.mode = BAD;
  9489. break;
  9490. }
  9491. state.length = hold & 0xffff;
  9492. //Tracev((stderr, "inflate: stored length %u\n",
  9493. // state.length));
  9494. //=== INITBITS();
  9495. hold = 0;
  9496. bits = 0;
  9497. //===//
  9498. state.mode = COPY_;
  9499. if (flush === Z_TREES) { break inf_leave; }
  9500. /* falls through */
  9501. case COPY_:
  9502. state.mode = COPY;
  9503. /* falls through */
  9504. case COPY:
  9505. copy = state.length;
  9506. if (copy) {
  9507. if (copy > have) { copy = have; }
  9508. if (copy > left) { copy = left; }
  9509. if (copy === 0) { break inf_leave; }
  9510. //--- zmemcpy(put, next, copy); ---
  9511. utils.arraySet(output, input, next, copy, put);
  9512. //---//
  9513. have -= copy;
  9514. next += copy;
  9515. left -= copy;
  9516. put += copy;
  9517. state.length -= copy;
  9518. break;
  9519. }
  9520. //Tracev((stderr, "inflate: stored end\n"));
  9521. state.mode = TYPE;
  9522. break;
  9523. case TABLE:
  9524. //=== NEEDBITS(14); */
  9525. while (bits < 14) {
  9526. if (have === 0) { break inf_leave; }
  9527. have--;
  9528. hold += input[next++] << bits;
  9529. bits += 8;
  9530. }
  9531. //===//
  9532. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  9533. //--- DROPBITS(5) ---//
  9534. hold >>>= 5;
  9535. bits -= 5;
  9536. //---//
  9537. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  9538. //--- DROPBITS(5) ---//
  9539. hold >>>= 5;
  9540. bits -= 5;
  9541. //---//
  9542. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  9543. //--- DROPBITS(4) ---//
  9544. hold >>>= 4;
  9545. bits -= 4;
  9546. //---//
  9547. //#ifndef PKZIP_BUG_WORKAROUND
  9548. if (state.nlen > 286 || state.ndist > 30) {
  9549. strm.msg = 'too many length or distance symbols';
  9550. state.mode = BAD;
  9551. break;
  9552. }
  9553. //#endif
  9554. //Tracev((stderr, "inflate: table sizes ok\n"));
  9555. state.have = 0;
  9556. state.mode = LENLENS;
  9557. /* falls through */
  9558. case LENLENS:
  9559. while (state.have < state.ncode) {
  9560. //=== NEEDBITS(3);
  9561. while (bits < 3) {
  9562. if (have === 0) { break inf_leave; }
  9563. have--;
  9564. hold += input[next++] << bits;
  9565. bits += 8;
  9566. }
  9567. //===//
  9568. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  9569. //--- DROPBITS(3) ---//
  9570. hold >>>= 3;
  9571. bits -= 3;
  9572. //---//
  9573. }
  9574. while (state.have < 19) {
  9575. state.lens[order[state.have++]] = 0;
  9576. }
  9577. // We have separate tables & no pointers. 2 commented lines below not needed.
  9578. //state.next = state.codes;
  9579. //state.lencode = state.next;
  9580. // Switch to use dynamic table
  9581. state.lencode = state.lendyn;
  9582. state.lenbits = 7;
  9583.  
  9584. opts = { bits: state.lenbits };
  9585. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  9586. state.lenbits = opts.bits;
  9587.  
  9588. if (ret) {
  9589. strm.msg = 'invalid code lengths set';
  9590. state.mode = BAD;
  9591. break;
  9592. }
  9593. //Tracev((stderr, "inflate: code lengths ok\n"));
  9594. state.have = 0;
  9595. state.mode = CODELENS;
  9596. /* falls through */
  9597. case CODELENS:
  9598. while (state.have < state.nlen + state.ndist) {
  9599. for (;;) {
  9600. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  9601. here_bits = here >>> 24;
  9602. here_op = (here >>> 16) & 0xff;
  9603. here_val = here & 0xffff;
  9604.  
  9605. if ((here_bits) <= bits) { break; }
  9606. //--- PULLBYTE() ---//
  9607. if (have === 0) { break inf_leave; }
  9608. have--;
  9609. hold += input[next++] << bits;
  9610. bits += 8;
  9611. //---//
  9612. }
  9613. if (here_val < 16) {
  9614. //--- DROPBITS(here.bits) ---//
  9615. hold >>>= here_bits;
  9616. bits -= here_bits;
  9617. //---//
  9618. state.lens[state.have++] = here_val;
  9619. }
  9620. else {
  9621. if (here_val === 16) {
  9622. //=== NEEDBITS(here.bits + 2);
  9623. n = here_bits + 2;
  9624. while (bits < n) {
  9625. if (have === 0) { break inf_leave; }
  9626. have--;
  9627. hold += input[next++] << bits;
  9628. bits += 8;
  9629. }
  9630. //===//
  9631. //--- DROPBITS(here.bits) ---//
  9632. hold >>>= here_bits;
  9633. bits -= here_bits;
  9634. //---//
  9635. if (state.have === 0) {
  9636. strm.msg = 'invalid bit length repeat';
  9637. state.mode = BAD;
  9638. break;
  9639. }
  9640. len = state.lens[state.have - 1];
  9641. copy = 3 + (hold & 0x03);//BITS(2);
  9642. //--- DROPBITS(2) ---//
  9643. hold >>>= 2;
  9644. bits -= 2;
  9645. //---//
  9646. }
  9647. else if (here_val === 17) {
  9648. //=== NEEDBITS(here.bits + 3);
  9649. n = here_bits + 3;
  9650. while (bits < n) {
  9651. if (have === 0) { break inf_leave; }
  9652. have--;
  9653. hold += input[next++] << bits;
  9654. bits += 8;
  9655. }
  9656. //===//
  9657. //--- DROPBITS(here.bits) ---//
  9658. hold >>>= here_bits;
  9659. bits -= here_bits;
  9660. //---//
  9661. len = 0;
  9662. copy = 3 + (hold & 0x07);//BITS(3);
  9663. //--- DROPBITS(3) ---//
  9664. hold >>>= 3;
  9665. bits -= 3;
  9666. //---//
  9667. }
  9668. else {
  9669. //=== NEEDBITS(here.bits + 7);
  9670. n = here_bits + 7;
  9671. while (bits < n) {
  9672. if (have === 0) { break inf_leave; }
  9673. have--;
  9674. hold += input[next++] << bits;
  9675. bits += 8;
  9676. }
  9677. //===//
  9678. //--- DROPBITS(here.bits) ---//
  9679. hold >>>= here_bits;
  9680. bits -= here_bits;
  9681. //---//
  9682. len = 0;
  9683. copy = 11 + (hold & 0x7f);//BITS(7);
  9684. //--- DROPBITS(7) ---//
  9685. hold >>>= 7;
  9686. bits -= 7;
  9687. //---//
  9688. }
  9689. if (state.have + copy > state.nlen + state.ndist) {
  9690. strm.msg = 'invalid bit length repeat';
  9691. state.mode = BAD;
  9692. break;
  9693. }
  9694. while (copy--) {
  9695. state.lens[state.have++] = len;
  9696. }
  9697. }
  9698. }
  9699.  
  9700. /* handle error breaks in while */
  9701. if (state.mode === BAD) { break; }
  9702.  
  9703. /* check for end-of-block code (better have one) */
  9704. if (state.lens[256] === 0) {
  9705. strm.msg = 'invalid code -- missing end-of-block';
  9706. state.mode = BAD;
  9707. break;
  9708. }
  9709.  
  9710. /* build code tables -- note: do not change the lenbits or distbits
  9711. values here (9 and 6) without reading the comments in inftrees.h
  9712. concerning the ENOUGH constants, which depend on those values */
  9713. state.lenbits = 9;
  9714.  
  9715. opts = { bits: state.lenbits };
  9716. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  9717. // We have separate tables & no pointers. 2 commented lines below not needed.
  9718. // state.next_index = opts.table_index;
  9719. state.lenbits = opts.bits;
  9720. // state.lencode = state.next;
  9721.  
  9722. if (ret) {
  9723. strm.msg = 'invalid literal/lengths set';
  9724. state.mode = BAD;
  9725. break;
  9726. }
  9727.  
  9728. state.distbits = 6;
  9729. //state.distcode.copy(state.codes);
  9730. // Switch to use dynamic table
  9731. state.distcode = state.distdyn;
  9732. opts = { bits: state.distbits };
  9733. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  9734. // We have separate tables & no pointers. 2 commented lines below not needed.
  9735. // state.next_index = opts.table_index;
  9736. state.distbits = opts.bits;
  9737. // state.distcode = state.next;
  9738.  
  9739. if (ret) {
  9740. strm.msg = 'invalid distances set';
  9741. state.mode = BAD;
  9742. break;
  9743. }
  9744. //Tracev((stderr, 'inflate: codes ok\n'));
  9745. state.mode = LEN_;
  9746. if (flush === Z_TREES) { break inf_leave; }
  9747. /* falls through */
  9748. case LEN_:
  9749. state.mode = LEN;
  9750. /* falls through */
  9751. case LEN:
  9752. if (have >= 6 && left >= 258) {
  9753. //--- RESTORE() ---
  9754. strm.next_out = put;
  9755. strm.avail_out = left;
  9756. strm.next_in = next;
  9757. strm.avail_in = have;
  9758. state.hold = hold;
  9759. state.bits = bits;
  9760. //---
  9761. inflate_fast(strm, _out);
  9762. //--- LOAD() ---
  9763. put = strm.next_out;
  9764. output = strm.output;
  9765. left = strm.avail_out;
  9766. next = strm.next_in;
  9767. input = strm.input;
  9768. have = strm.avail_in;
  9769. hold = state.hold;
  9770. bits = state.bits;
  9771. //---
  9772.  
  9773. if (state.mode === TYPE) {
  9774. state.back = -1;
  9775. }
  9776. break;
  9777. }
  9778. state.back = 0;
  9779. for (;;) {
  9780. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  9781. here_bits = here >>> 24;
  9782. here_op = (here >>> 16) & 0xff;
  9783. here_val = here & 0xffff;
  9784.  
  9785. if (here_bits <= bits) { break; }
  9786. //--- PULLBYTE() ---//
  9787. if (have === 0) { break inf_leave; }
  9788. have--;
  9789. hold += input[next++] << bits;
  9790. bits += 8;
  9791. //---//
  9792. }
  9793. if (here_op && (here_op & 0xf0) === 0) {
  9794. last_bits = here_bits;
  9795. last_op = here_op;
  9796. last_val = here_val;
  9797. for (;;) {
  9798. here = state.lencode[last_val +
  9799. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9800. here_bits = here >>> 24;
  9801. here_op = (here >>> 16) & 0xff;
  9802. here_val = here & 0xffff;
  9803.  
  9804. if ((last_bits + here_bits) <= bits) { break; }
  9805. //--- PULLBYTE() ---//
  9806. if (have === 0) { break inf_leave; }
  9807. have--;
  9808. hold += input[next++] << bits;
  9809. bits += 8;
  9810. //---//
  9811. }
  9812. //--- DROPBITS(last.bits) ---//
  9813. hold >>>= last_bits;
  9814. bits -= last_bits;
  9815. //---//
  9816. state.back += last_bits;
  9817. }
  9818. //--- DROPBITS(here.bits) ---//
  9819. hold >>>= here_bits;
  9820. bits -= here_bits;
  9821. //---//
  9822. state.back += here_bits;
  9823. state.length = here_val;
  9824. if (here_op === 0) {
  9825. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  9826. // "inflate: literal '%c'\n" :
  9827. // "inflate: literal 0x%02x\n", here.val));
  9828. state.mode = LIT;
  9829. break;
  9830. }
  9831. if (here_op & 32) {
  9832. //Tracevv((stderr, "inflate: end of block\n"));
  9833. state.back = -1;
  9834. state.mode = TYPE;
  9835. break;
  9836. }
  9837. if (here_op & 64) {
  9838. strm.msg = 'invalid literal/length code';
  9839. state.mode = BAD;
  9840. break;
  9841. }
  9842. state.extra = here_op & 15;
  9843. state.mode = LENEXT;
  9844. /* falls through */
  9845. case LENEXT:
  9846. if (state.extra) {
  9847. //=== NEEDBITS(state.extra);
  9848. n = state.extra;
  9849. while (bits < n) {
  9850. if (have === 0) { break inf_leave; }
  9851. have--;
  9852. hold += input[next++] << bits;
  9853. bits += 8;
  9854. }
  9855. //===//
  9856. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9857. //--- DROPBITS(state.extra) ---//
  9858. hold >>>= state.extra;
  9859. bits -= state.extra;
  9860. //---//
  9861. state.back += state.extra;
  9862. }
  9863. //Tracevv((stderr, "inflate: length %u\n", state.length));
  9864. state.was = state.length;
  9865. state.mode = DIST;
  9866. /* falls through */
  9867. case DIST:
  9868. for (;;) {
  9869. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  9870. here_bits = here >>> 24;
  9871. here_op = (here >>> 16) & 0xff;
  9872. here_val = here & 0xffff;
  9873.  
  9874. if ((here_bits) <= bits) { break; }
  9875. //--- PULLBYTE() ---//
  9876. if (have === 0) { break inf_leave; }
  9877. have--;
  9878. hold += input[next++] << bits;
  9879. bits += 8;
  9880. //---//
  9881. }
  9882. if ((here_op & 0xf0) === 0) {
  9883. last_bits = here_bits;
  9884. last_op = here_op;
  9885. last_val = here_val;
  9886. for (;;) {
  9887. here = state.distcode[last_val +
  9888. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9889. here_bits = here >>> 24;
  9890. here_op = (here >>> 16) & 0xff;
  9891. here_val = here & 0xffff;
  9892.  
  9893. if ((last_bits + here_bits) <= bits) { break; }
  9894. //--- PULLBYTE() ---//
  9895. if (have === 0) { break inf_leave; }
  9896. have--;
  9897. hold += input[next++] << bits;
  9898. bits += 8;
  9899. //---//
  9900. }
  9901. //--- DROPBITS(last.bits) ---//
  9902. hold >>>= last_bits;
  9903. bits -= last_bits;
  9904. //---//
  9905. state.back += last_bits;
  9906. }
  9907. //--- DROPBITS(here.bits) ---//
  9908. hold >>>= here_bits;
  9909. bits -= here_bits;
  9910. //---//
  9911. state.back += here_bits;
  9912. if (here_op & 64) {
  9913. strm.msg = 'invalid distance code';
  9914. state.mode = BAD;
  9915. break;
  9916. }
  9917. state.offset = here_val;
  9918. state.extra = (here_op) & 15;
  9919. state.mode = DISTEXT;
  9920. /* falls through */
  9921. case DISTEXT:
  9922. if (state.extra) {
  9923. //=== NEEDBITS(state.extra);
  9924. n = state.extra;
  9925. while (bits < n) {
  9926. if (have === 0) { break inf_leave; }
  9927. have--;
  9928. hold += input[next++] << bits;
  9929. bits += 8;
  9930. }
  9931. //===//
  9932. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9933. //--- DROPBITS(state.extra) ---//
  9934. hold >>>= state.extra;
  9935. bits -= state.extra;
  9936. //---//
  9937. state.back += state.extra;
  9938. }
  9939. //#ifdef INFLATE_STRICT
  9940. if (state.offset > state.dmax) {
  9941. strm.msg = 'invalid distance too far back';
  9942. state.mode = BAD;
  9943. break;
  9944. }
  9945. //#endif
  9946. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  9947. state.mode = MATCH;
  9948. /* falls through */
  9949. case MATCH:
  9950. if (left === 0) { break inf_leave; }
  9951. copy = _out - left;
  9952. if (state.offset > copy) { /* copy from window */
  9953. copy = state.offset - copy;
  9954. if (copy > state.whave) {
  9955. if (state.sane) {
  9956. strm.msg = 'invalid distance too far back';
  9957. state.mode = BAD;
  9958. break;
  9959. }
  9960. // (!) This block is disabled in zlib defailts,
  9961. // don't enable it for binary compatibility
  9962. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9963. // Trace((stderr, "inflate.c too far\n"));
  9964. // copy -= state.whave;
  9965. // if (copy > state.length) { copy = state.length; }
  9966. // if (copy > left) { copy = left; }
  9967. // left -= copy;
  9968. // state.length -= copy;
  9969. // do {
  9970. // output[put++] = 0;
  9971. // } while (--copy);
  9972. // if (state.length === 0) { state.mode = LEN; }
  9973. // break;
  9974. //#endif
  9975. }
  9976. if (copy > state.wnext) {
  9977. copy -= state.wnext;
  9978. from = state.wsize - copy;
  9979. }
  9980. else {
  9981. from = state.wnext - copy;
  9982. }
  9983. if (copy > state.length) { copy = state.length; }
  9984. from_source = state.window;
  9985. }
  9986. else { /* copy from output */
  9987. from_source = output;
  9988. from = put - state.offset;
  9989. copy = state.length;
  9990. }
  9991. if (copy > left) { copy = left; }
  9992. left -= copy;
  9993. state.length -= copy;
  9994. do {
  9995. output[put++] = from_source[from++];
  9996. } while (--copy);
  9997. if (state.length === 0) { state.mode = LEN; }
  9998. break;
  9999. case LIT:
  10000. if (left === 0) { break inf_leave; }
  10001. output[put++] = state.length;
  10002. left--;
  10003. state.mode = LEN;
  10004. break;
  10005. case CHECK:
  10006. if (state.wrap) {
  10007. //=== NEEDBITS(32);
  10008. while (bits < 32) {
  10009. if (have === 0) { break inf_leave; }
  10010. have--;
  10011. // Use '|' insdead of '+' to make sure that result is signed
  10012. hold |= input[next++] << bits;
  10013. bits += 8;
  10014. }
  10015. //===//
  10016. _out -= left;
  10017. strm.total_out += _out;
  10018. state.total += _out;
  10019. if (_out) {
  10020. strm.adler = state.check =
  10021. /*UPDATE(state.check, put - _out, _out);*/
  10022. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  10023.  
  10024. }
  10025. _out = left;
  10026. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  10027. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  10028. strm.msg = 'incorrect data check';
  10029. state.mode = BAD;
  10030. break;
  10031. }
  10032. //=== INITBITS();
  10033. hold = 0;
  10034. bits = 0;
  10035. //===//
  10036. //Tracev((stderr, "inflate: check matches trailer\n"));
  10037. }
  10038. state.mode = LENGTH;
  10039. /* falls through */
  10040. case LENGTH:
  10041. if (state.wrap && state.flags) {
  10042. //=== NEEDBITS(32);
  10043. while (bits < 32) {
  10044. if (have === 0) { break inf_leave; }
  10045. have--;
  10046. hold += input[next++] << bits;
  10047. bits += 8;
  10048. }
  10049. //===//
  10050. if (hold !== (state.total & 0xffffffff)) {
  10051. strm.msg = 'incorrect length check';
  10052. state.mode = BAD;
  10053. break;
  10054. }
  10055. //=== INITBITS();
  10056. hold = 0;
  10057. bits = 0;
  10058. //===//
  10059. //Tracev((stderr, "inflate: length matches trailer\n"));
  10060. }
  10061. state.mode = DONE;
  10062. /* falls through */
  10063. case DONE:
  10064. ret = Z_STREAM_END;
  10065. break inf_leave;
  10066. case BAD:
  10067. ret = Z_DATA_ERROR;
  10068. break inf_leave;
  10069. case MEM:
  10070. return Z_MEM_ERROR;
  10071. case SYNC:
  10072. /* falls through */
  10073. default:
  10074. return Z_STREAM_ERROR;
  10075. }
  10076. }
  10077.  
  10078. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  10079.  
  10080. /*
  10081. Return from inflate(), updating the total counts and the check value.
  10082. If there was no progress during the inflate() call, return a buffer
  10083. error. Call updatewindow() to create and/or update the window state.
  10084. Note: a memory error from inflate() is non-recoverable.
  10085. */
  10086.  
  10087. //--- RESTORE() ---
  10088. strm.next_out = put;
  10089. strm.avail_out = left;
  10090. strm.next_in = next;
  10091. strm.avail_in = have;
  10092. state.hold = hold;
  10093. state.bits = bits;
  10094. //---
  10095.  
  10096. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  10097. (state.mode < CHECK || flush !== Z_FINISH))) {
  10098. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  10099. state.mode = MEM;
  10100. return Z_MEM_ERROR;
  10101. }
  10102. }
  10103. _in -= strm.avail_in;
  10104. _out -= strm.avail_out;
  10105. strm.total_in += _in;
  10106. strm.total_out += _out;
  10107. state.total += _out;
  10108. if (state.wrap && _out) {
  10109. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  10110. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  10111. }
  10112. strm.data_type = state.bits + (state.last ? 64 : 0) +
  10113. (state.mode === TYPE ? 128 : 0) +
  10114. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  10115. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  10116. ret = Z_BUF_ERROR;
  10117. }
  10118. return ret;
  10119. }
  10120.  
  10121. function inflateEnd(strm) {
  10122.  
  10123. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  10124. return Z_STREAM_ERROR;
  10125. }
  10126.  
  10127. var state = strm.state;
  10128. if (state.window) {
  10129. state.window = null;
  10130. }
  10131. strm.state = null;
  10132. return Z_OK;
  10133. }
  10134.  
  10135. function inflateGetHeader(strm, head) {
  10136. var state;
  10137.  
  10138. /* check state */
  10139. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  10140. state = strm.state;
  10141. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  10142.  
  10143. /* save header structure */
  10144. state.head = head;
  10145. head.done = false;
  10146. return Z_OK;
  10147. }
  10148.  
  10149. function inflateSetDictionary(strm, dictionary) {
  10150. var dictLength = dictionary.length;
  10151.  
  10152. var state;
  10153. var dictid;
  10154. var ret;
  10155.  
  10156. /* check state */
  10157. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  10158. state = strm.state;
  10159.  
  10160. if (state.wrap !== 0 && state.mode !== DICT) {
  10161. return Z_STREAM_ERROR;
  10162. }
  10163.  
  10164. /* check for correct dictionary identifier */
  10165. if (state.mode === DICT) {
  10166. dictid = 1; /* adler32(0, null, 0)*/
  10167. /* dictid = adler32(dictid, dictionary, dictLength); */
  10168. dictid = adler32(dictid, dictionary, dictLength, 0);
  10169. if (dictid !== state.check) {
  10170. return Z_DATA_ERROR;
  10171. }
  10172. }
  10173. /* copy dictionary to window using updatewindow(), which will amend the
  10174. existing dictionary if appropriate */
  10175. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  10176. if (ret) {
  10177. state.mode = MEM;
  10178. return Z_MEM_ERROR;
  10179. }
  10180. state.havedict = 1;
  10181. // Tracev((stderr, "inflate: dictionary set\n"));
  10182. return Z_OK;
  10183. }
  10184.  
  10185. exports.inflateReset = inflateReset;
  10186. exports.inflateReset2 = inflateReset2;
  10187. exports.inflateResetKeep = inflateResetKeep;
  10188. exports.inflateInit = inflateInit;
  10189. exports.inflateInit2 = inflateInit2;
  10190. exports.inflate = inflate;
  10191. exports.inflateEnd = inflateEnd;
  10192. exports.inflateGetHeader = inflateGetHeader;
  10193. exports.inflateSetDictionary = inflateSetDictionary;
  10194. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  10195.  
  10196. /* Not implemented
  10197. exports.inflateCopy = inflateCopy;
  10198. exports.inflateGetDictionary = inflateGetDictionary;
  10199. exports.inflateMark = inflateMark;
  10200. exports.inflatePrime = inflatePrime;
  10201. exports.inflateSync = inflateSync;
  10202. exports.inflateSyncPoint = inflateSyncPoint;
  10203. exports.inflateUndermine = inflateUndermine;
  10204. */
  10205.  
  10206. },{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(require,module,exports){
  10207. 'use strict';
  10208.  
  10209. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10210. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10211. //
  10212. // This software is provided 'as-is', without any express or implied
  10213. // warranty. In no event will the authors be held liable for any damages
  10214. // arising from the use of this software.
  10215. //
  10216. // Permission is granted to anyone to use this software for any purpose,
  10217. // including commercial applications, and to alter it and redistribute it
  10218. // freely, subject to the following restrictions:
  10219. //
  10220. // 1. The origin of this software must not be misrepresented; you must not
  10221. // claim that you wrote the original software. If you use this software
  10222. // in a product, an acknowledgment in the product documentation would be
  10223. // appreciated but is not required.
  10224. // 2. Altered source versions must be plainly marked as such, and must not be
  10225. // misrepresented as being the original software.
  10226. // 3. This notice may not be removed or altered from any source distribution.
  10227.  
  10228. var utils = require('../utils/common');
  10229.  
  10230. var MAXBITS = 15;
  10231. var ENOUGH_LENS = 852;
  10232. var ENOUGH_DISTS = 592;
  10233. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  10234.  
  10235. var CODES = 0;
  10236. var LENS = 1;
  10237. var DISTS = 2;
  10238.  
  10239. var lbase = [ /* Length codes 257..285 base */
  10240. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  10241. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  10242. ];
  10243.  
  10244. var lext = [ /* Length codes 257..285 extra */
  10245. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  10246. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  10247. ];
  10248.  
  10249. var dbase = [ /* Distance codes 0..29 base */
  10250. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  10251. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  10252. 8193, 12289, 16385, 24577, 0, 0
  10253. ];
  10254.  
  10255. var dext = [ /* Distance codes 0..29 extra */
  10256. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  10257. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  10258. 28, 28, 29, 29, 64, 64
  10259. ];
  10260.  
  10261. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  10262. {
  10263. var bits = opts.bits;
  10264. //here = opts.here; /* table entry for duplication */
  10265.  
  10266. var len = 0; /* a code's length in bits */
  10267. var sym = 0; /* index of code symbols */
  10268. var min = 0, max = 0; /* minimum and maximum code lengths */
  10269. var root = 0; /* number of index bits for root table */
  10270. var curr = 0; /* number of index bits for current table */
  10271. var drop = 0; /* code bits to drop for sub-table */
  10272. var left = 0; /* number of prefix codes available */
  10273. var used = 0; /* code entries in table used */
  10274. var huff = 0; /* Huffman code */
  10275. var incr; /* for incrementing code, index */
  10276. var fill; /* index for replicating entries */
  10277. var low; /* low bits for current root entry */
  10278. var mask; /* mask for low root bits */
  10279. var next; /* next available space in table */
  10280. var base = null; /* base value table to use */
  10281. var base_index = 0;
  10282. // var shoextra; /* extra bits table to use */
  10283. var end; /* use base and extra for symbol > end */
  10284. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  10285. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  10286. var extra = null;
  10287. var extra_index = 0;
  10288.  
  10289. var here_bits, here_op, here_val;
  10290.  
  10291. /*
  10292. Process a set of code lengths to create a canonical Huffman code. The
  10293. code lengths are lens[0..codes-1]. Each length corresponds to the
  10294. symbols 0..codes-1. The Huffman code is generated by first sorting the
  10295. symbols by length from short to long, and retaining the symbol order
  10296. for codes with equal lengths. Then the code starts with all zero bits
  10297. for the first code of the shortest length, and the codes are integer
  10298. increments for the same length, and zeros are appended as the length
  10299. increases. For the deflate format, these bits are stored backwards
  10300. from their more natural integer increment ordering, and so when the
  10301. decoding tables are built in the large loop below, the integer codes
  10302. are incremented backwards.
  10303.  
  10304. This routine assumes, but does not check, that all of the entries in
  10305. lens[] are in the range 0..MAXBITS. The caller must assure this.
  10306. 1..MAXBITS is interpreted as that code length. zero means that that
  10307. symbol does not occur in this code.
  10308.  
  10309. The codes are sorted by computing a count of codes for each length,
  10310. creating from that a table of starting indices for each length in the
  10311. sorted table, and then entering the symbols in order in the sorted
  10312. table. The sorted table is work[], with that space being provided by
  10313. the caller.
  10314.  
  10315. The length counts are used for other purposes as well, i.e. finding
  10316. the minimum and maximum length codes, determining if there are any
  10317. codes at all, checking for a valid set of lengths, and looking ahead
  10318. at length counts to determine sub-table sizes when building the
  10319. decoding tables.
  10320. */
  10321.  
  10322. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  10323. for (len = 0; len <= MAXBITS; len++) {
  10324. count[len] = 0;
  10325. }
  10326. for (sym = 0; sym < codes; sym++) {
  10327. count[lens[lens_index + sym]]++;
  10328. }
  10329.  
  10330. /* bound code lengths, force root to be within code lengths */
  10331. root = bits;
  10332. for (max = MAXBITS; max >= 1; max--) {
  10333. if (count[max] !== 0) { break; }
  10334. }
  10335. if (root > max) {
  10336. root = max;
  10337. }
  10338. if (max === 0) { /* no symbols to code at all */
  10339. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  10340. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  10341. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  10342. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  10343.  
  10344.  
  10345. //table.op[opts.table_index] = 64;
  10346. //table.bits[opts.table_index] = 1;
  10347. //table.val[opts.table_index++] = 0;
  10348. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  10349.  
  10350. opts.bits = 1;
  10351. return 0; /* no symbols, but wait for decoding to report error */
  10352. }
  10353. for (min = 1; min < max; min++) {
  10354. if (count[min] !== 0) { break; }
  10355. }
  10356. if (root < min) {
  10357. root = min;
  10358. }
  10359.  
  10360. /* check for an over-subscribed or incomplete set of lengths */
  10361. left = 1;
  10362. for (len = 1; len <= MAXBITS; len++) {
  10363. left <<= 1;
  10364. left -= count[len];
  10365. if (left < 0) {
  10366. return -1;
  10367. } /* over-subscribed */
  10368. }
  10369. if (left > 0 && (type === CODES || max !== 1)) {
  10370. return -1; /* incomplete set */
  10371. }
  10372.  
  10373. /* generate offsets into symbol table for each length for sorting */
  10374. offs[1] = 0;
  10375. for (len = 1; len < MAXBITS; len++) {
  10376. offs[len + 1] = offs[len] + count[len];
  10377. }
  10378.  
  10379. /* sort symbols by length, by symbol order within each length */
  10380. for (sym = 0; sym < codes; sym++) {
  10381. if (lens[lens_index + sym] !== 0) {
  10382. work[offs[lens[lens_index + sym]]++] = sym;
  10383. }
  10384. }
  10385.  
  10386. /*
  10387. Create and fill in decoding tables. In this loop, the table being
  10388. filled is at next and has curr index bits. The code being used is huff
  10389. with length len. That code is converted to an index by dropping drop
  10390. bits off of the bottom. For codes where len is less than drop + curr,
  10391. those top drop + curr - len bits are incremented through all values to
  10392. fill the table with replicated entries.
  10393.  
  10394. root is the number of index bits for the root table. When len exceeds
  10395. root, sub-tables are created pointed to by the root entry with an index
  10396. of the low root bits of huff. This is saved in low to check for when a
  10397. new sub-table should be started. drop is zero when the root table is
  10398. being filled, and drop is root when sub-tables are being filled.
  10399.  
  10400. When a new sub-table is needed, it is necessary to look ahead in the
  10401. code lengths to determine what size sub-table is needed. The length
  10402. counts are used for this, and so count[] is decremented as codes are
  10403. entered in the tables.
  10404.  
  10405. used keeps track of how many table entries have been allocated from the
  10406. provided *table space. It is checked for LENS and DIST tables against
  10407. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  10408. the initial root table size constants. See the comments in inftrees.h
  10409. for more information.
  10410.  
  10411. sym increments through all symbols, and the loop terminates when
  10412. all codes of length max, i.e. all codes, have been processed. This
  10413. routine permits incomplete codes, so another loop after this one fills
  10414. in the rest of the decoding tables with invalid code markers.
  10415. */
  10416.  
  10417. /* set up for code type */
  10418. // poor man optimization - use if-else instead of switch,
  10419. // to avoid deopts in old v8
  10420. if (type === CODES) {
  10421. base = extra = work; /* dummy value--not used */
  10422. end = 19;
  10423.  
  10424. } else if (type === LENS) {
  10425. base = lbase;
  10426. base_index -= 257;
  10427. extra = lext;
  10428. extra_index -= 257;
  10429. end = 256;
  10430.  
  10431. } else { /* DISTS */
  10432. base = dbase;
  10433. extra = dext;
  10434. end = -1;
  10435. }
  10436.  
  10437. /* initialize opts for loop */
  10438. huff = 0; /* starting code */
  10439. sym = 0; /* starting code symbol */
  10440. len = min; /* starting code length */
  10441. next = table_index; /* current table to fill in */
  10442. curr = root; /* current table index bits */
  10443. drop = 0; /* current bits to drop from code for index */
  10444. low = -1; /* trigger new sub-table when len > root */
  10445. used = 1 << root; /* use root table entries */
  10446. mask = used - 1; /* mask for comparing low */
  10447.  
  10448. /* check available table space */
  10449. if ((type === LENS && used > ENOUGH_LENS) ||
  10450. (type === DISTS && used > ENOUGH_DISTS)) {
  10451. return 1;
  10452. }
  10453.  
  10454. /* process all codes and make table entries */
  10455. for (;;) {
  10456. /* create table entry */
  10457. here_bits = len - drop;
  10458. if (work[sym] < end) {
  10459. here_op = 0;
  10460. here_val = work[sym];
  10461. }
  10462. else if (work[sym] > end) {
  10463. here_op = extra[extra_index + work[sym]];
  10464. here_val = base[base_index + work[sym]];
  10465. }
  10466. else {
  10467. here_op = 32 + 64; /* end of block */
  10468. here_val = 0;
  10469. }
  10470.  
  10471. /* replicate for those indices with low len bits equal to huff */
  10472. incr = 1 << (len - drop);
  10473. fill = 1 << curr;
  10474. min = fill; /* save offset to next table */
  10475. do {
  10476. fill -= incr;
  10477. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  10478. } while (fill !== 0);
  10479.  
  10480. /* backwards increment the len-bit code huff */
  10481. incr = 1 << (len - 1);
  10482. while (huff & incr) {
  10483. incr >>= 1;
  10484. }
  10485. if (incr !== 0) {
  10486. huff &= incr - 1;
  10487. huff += incr;
  10488. } else {
  10489. huff = 0;
  10490. }
  10491.  
  10492. /* go to next symbol, update count, len */
  10493. sym++;
  10494. if (--count[len] === 0) {
  10495. if (len === max) { break; }
  10496. len = lens[lens_index + work[sym]];
  10497. }
  10498.  
  10499. /* create new sub-table if needed */
  10500. if (len > root && (huff & mask) !== low) {
  10501. /* if first time, transition to sub-tables */
  10502. if (drop === 0) {
  10503. drop = root;
  10504. }
  10505.  
  10506. /* increment past last table */
  10507. next += min; /* here min is 1 << curr */
  10508.  
  10509. /* determine length of next table */
  10510. curr = len - drop;
  10511. left = 1 << curr;
  10512. while (curr + drop < max) {
  10513. left -= count[curr + drop];
  10514. if (left <= 0) { break; }
  10515. curr++;
  10516. left <<= 1;
  10517. }
  10518.  
  10519. /* check for enough space */
  10520. used += 1 << curr;
  10521. if ((type === LENS && used > ENOUGH_LENS) ||
  10522. (type === DISTS && used > ENOUGH_DISTS)) {
  10523. return 1;
  10524. }
  10525.  
  10526. /* point entry in root table to sub-table */
  10527. low = huff & mask;
  10528. /*table.op[low] = curr;
  10529. table.bits[low] = root;
  10530. table.val[low] = next - opts.table_index;*/
  10531. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  10532. }
  10533. }
  10534.  
  10535. /* fill in remaining table entry if code is incomplete (guaranteed to have
  10536. at most one remaining entry, since if the code is incomplete, the
  10537. maximum code length that was allowed to get this far is one bit) */
  10538. if (huff !== 0) {
  10539. //table.op[next + huff] = 64; /* invalid code marker */
  10540. //table.bits[next + huff] = len - drop;
  10541. //table.val[next + huff] = 0;
  10542. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  10543. }
  10544.  
  10545. /* set return parameters */
  10546. //opts.table_index += used;
  10547. opts.bits = root;
  10548. return 0;
  10549. };
  10550.  
  10551. },{"../utils/common":41}],51:[function(require,module,exports){
  10552. 'use strict';
  10553.  
  10554. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10555. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10556. //
  10557. // This software is provided 'as-is', without any express or implied
  10558. // warranty. In no event will the authors be held liable for any damages
  10559. // arising from the use of this software.
  10560. //
  10561. // Permission is granted to anyone to use this software for any purpose,
  10562. // including commercial applications, and to alter it and redistribute it
  10563. // freely, subject to the following restrictions:
  10564. //
  10565. // 1. The origin of this software must not be misrepresented; you must not
  10566. // claim that you wrote the original software. If you use this software
  10567. // in a product, an acknowledgment in the product documentation would be
  10568. // appreciated but is not required.
  10569. // 2. Altered source versions must be plainly marked as such, and must not be
  10570. // misrepresented as being the original software.
  10571. // 3. This notice may not be removed or altered from any source distribution.
  10572.  
  10573. module.exports = {
  10574. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  10575. 1: 'stream end', /* Z_STREAM_END 1 */
  10576. 0: '', /* Z_OK 0 */
  10577. '-1': 'file error', /* Z_ERRNO (-1) */
  10578. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  10579. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  10580. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  10581. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  10582. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  10583. };
  10584.  
  10585. },{}],52:[function(require,module,exports){
  10586. 'use strict';
  10587.  
  10588. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  10589. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  10590. //
  10591. // This software is provided 'as-is', without any express or implied
  10592. // warranty. In no event will the authors be held liable for any damages
  10593. // arising from the use of this software.
  10594. //
  10595. // Permission is granted to anyone to use this software for any purpose,
  10596. // including commercial applications, and to alter it and redistribute it
  10597. // freely, subject to the following restrictions:
  10598. //
  10599. // 1. The origin of this software must not be misrepresented; you must not
  10600. // claim that you wrote the original software. If you use this software
  10601. // in a product, an acknowledgment in the product documentation would be
  10602. // appreciated but is not required.
  10603. // 2. Altered source versions must be plainly marked as such, and must not be
  10604. // misrepresented as being the original software.
  10605. // 3. This notice may not be removed or altered from any source distribution.
  10606.  
  10607. var utils = require('../utils/common');
  10608.  
  10609. /* Public constants ==========================================================*/
  10610. /* ===========================================================================*/
  10611.  
  10612.  
  10613. //var Z_FILTERED = 1;
  10614. //var Z_HUFFMAN_ONLY = 2;
  10615. //var Z_RLE = 3;
  10616. var Z_FIXED = 4;
  10617. //var Z_DEFAULT_STRATEGY = 0;
  10618.  
  10619. /* Possible values of the data_type field (though see inflate()) */
  10620. var Z_BINARY = 0;
  10621. var Z_TEXT = 1;
  10622. //var Z_ASCII = 1; // = Z_TEXT
  10623. var Z_UNKNOWN = 2;
  10624.  
  10625. /*============================================================================*/
  10626.  
  10627.  
  10628. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  10629.  
  10630. // From zutil.h
  10631.  
  10632. var STORED_BLOCK = 0;
  10633. var STATIC_TREES = 1;
  10634. var DYN_TREES = 2;
  10635. /* The three kinds of block type */
  10636.  
  10637. var MIN_MATCH = 3;
  10638. var MAX_MATCH = 258;
  10639. /* The minimum and maximum match lengths */
  10640.  
  10641. // From deflate.h
  10642. /* ===========================================================================
  10643. * Internal compression state.
  10644. */
  10645.  
  10646. var LENGTH_CODES = 29;
  10647. /* number of length codes, not counting the special END_BLOCK code */
  10648.  
  10649. var LITERALS = 256;
  10650. /* number of literal bytes 0..255 */
  10651.  
  10652. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  10653. /* number of Literal or Length codes, including the END_BLOCK code */
  10654.  
  10655. var D_CODES = 30;
  10656. /* number of distance codes */
  10657.  
  10658. var BL_CODES = 19;
  10659. /* number of codes used to transfer the bit lengths */
  10660.  
  10661. var HEAP_SIZE = 2 * L_CODES + 1;
  10662. /* maximum heap size */
  10663.  
  10664. var MAX_BITS = 15;
  10665. /* All codes must not exceed MAX_BITS bits */
  10666.  
  10667. var Buf_size = 16;
  10668. /* size of bit buffer in bi_buf */
  10669.  
  10670.  
  10671. /* ===========================================================================
  10672. * Constants
  10673. */
  10674.  
  10675. var MAX_BL_BITS = 7;
  10676. /* Bit length codes must not exceed MAX_BL_BITS bits */
  10677.  
  10678. var END_BLOCK = 256;
  10679. /* end of block literal code */
  10680.  
  10681. var REP_3_6 = 16;
  10682. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  10683.  
  10684. var REPZ_3_10 = 17;
  10685. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  10686.  
  10687. var REPZ_11_138 = 18;
  10688. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  10689.  
  10690. /* eslint-disable comma-spacing,array-bracket-spacing */
  10691. var extra_lbits = /* extra bits for each length code */
  10692. [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];
  10693.  
  10694. var extra_dbits = /* extra bits for each distance code */
  10695. [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];
  10696.  
  10697. var extra_blbits = /* extra bits for each bit length code */
  10698. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  10699.  
  10700. var bl_order =
  10701. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  10702. /* eslint-enable comma-spacing,array-bracket-spacing */
  10703.  
  10704. /* The lengths of the bit length codes are sent in order of decreasing
  10705. * probability, to avoid transmitting the lengths for unused bit length codes.
  10706. */
  10707.  
  10708. /* ===========================================================================
  10709. * Local data. These are initialized only once.
  10710. */
  10711.  
  10712. // We pre-fill arrays with 0 to avoid uninitialized gaps
  10713.  
  10714. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  10715.  
  10716. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  10717. var static_ltree = new Array((L_CODES + 2) * 2);
  10718. zero(static_ltree);
  10719. /* The static literal tree. Since the bit lengths are imposed, there is no
  10720. * need for the L_CODES extra codes used during heap construction. However
  10721. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  10722. * below).
  10723. */
  10724.  
  10725. var static_dtree = new Array(D_CODES * 2);
  10726. zero(static_dtree);
  10727. /* The static distance tree. (Actually a trivial tree since all codes use
  10728. * 5 bits.)
  10729. */
  10730.  
  10731. var _dist_code = new Array(DIST_CODE_LEN);
  10732. zero(_dist_code);
  10733. /* Distance codes. The first 256 values correspond to the distances
  10734. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  10735. * the 15 bit distances.
  10736. */
  10737.  
  10738. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  10739. zero(_length_code);
  10740. /* length code for each normalized match length (0 == MIN_MATCH) */
  10741.  
  10742. var base_length = new Array(LENGTH_CODES);
  10743. zero(base_length);
  10744. /* First normalized length for each code (0 = MIN_MATCH) */
  10745.  
  10746. var base_dist = new Array(D_CODES);
  10747. zero(base_dist);
  10748. /* First normalized distance for each code (0 = distance of 1) */
  10749.  
  10750.  
  10751. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  10752.  
  10753. this.static_tree = static_tree; /* static tree or NULL */
  10754. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  10755. this.extra_base = extra_base; /* base index for extra_bits */
  10756. this.elems = elems; /* max number of elements in the tree */
  10757. this.max_length = max_length; /* max bit length for the codes */
  10758.  
  10759. // show if `static_tree` has data or dummy - needed for monomorphic objects
  10760. this.has_stree = static_tree && static_tree.length;
  10761. }
  10762.  
  10763.  
  10764. var static_l_desc;
  10765. var static_d_desc;
  10766. var static_bl_desc;
  10767.  
  10768.  
  10769. function TreeDesc(dyn_tree, stat_desc) {
  10770. this.dyn_tree = dyn_tree; /* the dynamic tree */
  10771. this.max_code = 0; /* largest code with non zero frequency */
  10772. this.stat_desc = stat_desc; /* the corresponding static tree */
  10773. }
  10774.  
  10775.  
  10776.  
  10777. function d_code(dist) {
  10778. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  10779. }
  10780.  
  10781.  
  10782. /* ===========================================================================
  10783. * Output a short LSB first on the stream.
  10784. * IN assertion: there is enough room in pendingBuf.
  10785. */
  10786. function put_short(s, w) {
  10787. // put_byte(s, (uch)((w) & 0xff));
  10788. // put_byte(s, (uch)((ush)(w) >> 8));
  10789. s.pending_buf[s.pending++] = (w) & 0xff;
  10790. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  10791. }
  10792.  
  10793.  
  10794. /* ===========================================================================
  10795. * Send a value on a given number of bits.
  10796. * IN assertion: length <= 16 and value fits in length bits.
  10797. */
  10798. function send_bits(s, value, length) {
  10799. if (s.bi_valid > (Buf_size - length)) {
  10800. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10801. put_short(s, s.bi_buf);
  10802. s.bi_buf = value >> (Buf_size - s.bi_valid);
  10803. s.bi_valid += length - Buf_size;
  10804. } else {
  10805. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10806. s.bi_valid += length;
  10807. }
  10808. }
  10809.  
  10810.  
  10811. function send_code(s, c, tree) {
  10812. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  10813. }
  10814.  
  10815.  
  10816. /* ===========================================================================
  10817. * Reverse the first len bits of a code, using straightforward code (a faster
  10818. * method would use a table)
  10819. * IN assertion: 1 <= len <= 15
  10820. */
  10821. function bi_reverse(code, len) {
  10822. var res = 0;
  10823. do {
  10824. res |= code & 1;
  10825. code >>>= 1;
  10826. res <<= 1;
  10827. } while (--len > 0);
  10828. return res >>> 1;
  10829. }
  10830.  
  10831.  
  10832. /* ===========================================================================
  10833. * Flush the bit buffer, keeping at most 7 bits in it.
  10834. */
  10835. function bi_flush(s) {
  10836. if (s.bi_valid === 16) {
  10837. put_short(s, s.bi_buf);
  10838. s.bi_buf = 0;
  10839. s.bi_valid = 0;
  10840.  
  10841. } else if (s.bi_valid >= 8) {
  10842. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  10843. s.bi_buf >>= 8;
  10844. s.bi_valid -= 8;
  10845. }
  10846. }
  10847.  
  10848.  
  10849. /* ===========================================================================
  10850. * Compute the optimal bit lengths for a tree and update the total bit length
  10851. * for the current block.
  10852. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  10853. * above are the tree nodes sorted by increasing frequency.
  10854. * OUT assertions: the field len is set to the optimal bit length, the
  10855. * array bl_count contains the frequencies for each bit length.
  10856. * The length opt_len is updated; static_len is also updated if stree is
  10857. * not null.
  10858. */
  10859. function gen_bitlen(s, desc)
  10860. // deflate_state *s;
  10861. // tree_desc *desc; /* the tree descriptor */
  10862. {
  10863. var tree = desc.dyn_tree;
  10864. var max_code = desc.max_code;
  10865. var stree = desc.stat_desc.static_tree;
  10866. var has_stree = desc.stat_desc.has_stree;
  10867. var extra = desc.stat_desc.extra_bits;
  10868. var base = desc.stat_desc.extra_base;
  10869. var max_length = desc.stat_desc.max_length;
  10870. var h; /* heap index */
  10871. var n, m; /* iterate over the tree elements */
  10872. var bits; /* bit length */
  10873. var xbits; /* extra bits */
  10874. var f; /* frequency */
  10875. var overflow = 0; /* number of elements with bit length too large */
  10876.  
  10877. for (bits = 0; bits <= MAX_BITS; bits++) {
  10878. s.bl_count[bits] = 0;
  10879. }
  10880.  
  10881. /* In a first pass, compute the optimal bit lengths (which may
  10882. * overflow in the case of the bit length tree).
  10883. */
  10884. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  10885.  
  10886. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  10887. n = s.heap[h];
  10888. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  10889. if (bits > max_length) {
  10890. bits = max_length;
  10891. overflow++;
  10892. }
  10893. tree[n * 2 + 1]/*.Len*/ = bits;
  10894. /* We overwrite tree[n].Dad which is no longer needed */
  10895.  
  10896. if (n > max_code) { continue; } /* not a leaf node */
  10897.  
  10898. s.bl_count[bits]++;
  10899. xbits = 0;
  10900. if (n >= base) {
  10901. xbits = extra[n - base];
  10902. }
  10903. f = tree[n * 2]/*.Freq*/;
  10904. s.opt_len += f * (bits + xbits);
  10905. if (has_stree) {
  10906. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  10907. }
  10908. }
  10909. if (overflow === 0) { return; }
  10910.  
  10911. // Trace((stderr,"\nbit length overflow\n"));
  10912. /* This happens for example on obj2 and pic of the Calgary corpus */
  10913.  
  10914. /* Find the first bit length which could increase: */
  10915. do {
  10916. bits = max_length - 1;
  10917. while (s.bl_count[bits] === 0) { bits--; }
  10918. s.bl_count[bits]--; /* move one leaf down the tree */
  10919. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  10920. s.bl_count[max_length]--;
  10921. /* The brother of the overflow item also moves one step up,
  10922. * but this does not affect bl_count[max_length]
  10923. */
  10924. overflow -= 2;
  10925. } while (overflow > 0);
  10926.  
  10927. /* Now recompute all bit lengths, scanning in increasing frequency.
  10928. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  10929. * lengths instead of fixing only the wrong ones. This idea is taken
  10930. * from 'ar' written by Haruhiko Okumura.)
  10931. */
  10932. for (bits = max_length; bits !== 0; bits--) {
  10933. n = s.bl_count[bits];
  10934. while (n !== 0) {
  10935. m = s.heap[--h];
  10936. if (m > max_code) { continue; }
  10937. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  10938. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  10939. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  10940. tree[m * 2 + 1]/*.Len*/ = bits;
  10941. }
  10942. n--;
  10943. }
  10944. }
  10945. }
  10946.  
  10947.  
  10948. /* ===========================================================================
  10949. * Generate the codes for a given tree and bit counts (which need not be
  10950. * optimal).
  10951. * IN assertion: the array bl_count contains the bit length statistics for
  10952. * the given tree and the field len is set for all tree elements.
  10953. * OUT assertion: the field code is set for all tree elements of non
  10954. * zero code length.
  10955. */
  10956. function gen_codes(tree, max_code, bl_count)
  10957. // ct_data *tree; /* the tree to decorate */
  10958. // int max_code; /* largest code with non zero frequency */
  10959. // ushf *bl_count; /* number of codes at each bit length */
  10960. {
  10961. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  10962. var code = 0; /* running code value */
  10963. var bits; /* bit index */
  10964. var n; /* code index */
  10965.  
  10966. /* The distribution counts are first used to generate the code values
  10967. * without bit reversal.
  10968. */
  10969. for (bits = 1; bits <= MAX_BITS; bits++) {
  10970. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  10971. }
  10972. /* Check that the bit counts in bl_count are consistent. The last code
  10973. * must be all ones.
  10974. */
  10975. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  10976. // "inconsistent bit counts");
  10977. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  10978.  
  10979. for (n = 0; n <= max_code; n++) {
  10980. var len = tree[n * 2 + 1]/*.Len*/;
  10981. if (len === 0) { continue; }
  10982. /* Now reverse the bits */
  10983. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  10984.  
  10985. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  10986. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  10987. }
  10988. }
  10989.  
  10990.  
  10991. /* ===========================================================================
  10992. * Initialize the various 'constant' tables.
  10993. */
  10994. function tr_static_init() {
  10995. var n; /* iterates over tree elements */
  10996. var bits; /* bit counter */
  10997. var length; /* length value */
  10998. var code; /* code value */
  10999. var dist; /* distance index */
  11000. var bl_count = new Array(MAX_BITS + 1);
  11001. /* number of codes at each bit length for an optimal tree */
  11002.  
  11003. // do check in _tr_init()
  11004. //if (static_init_done) return;
  11005.  
  11006. /* For some embedded targets, global variables are not initialized: */
  11007. /*#ifdef NO_INIT_GLOBAL_POINTERS
  11008. static_l_desc.static_tree = static_ltree;
  11009. static_l_desc.extra_bits = extra_lbits;
  11010. static_d_desc.static_tree = static_dtree;
  11011. static_d_desc.extra_bits = extra_dbits;
  11012. static_bl_desc.extra_bits = extra_blbits;
  11013. #endif*/
  11014.  
  11015. /* Initialize the mapping length (0..255) -> length code (0..28) */
  11016. length = 0;
  11017. for (code = 0; code < LENGTH_CODES - 1; code++) {
  11018. base_length[code] = length;
  11019. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  11020. _length_code[length++] = code;
  11021. }
  11022. }
  11023. //Assert (length == 256, "tr_static_init: length != 256");
  11024. /* Note that the length 255 (match length 258) can be represented
  11025. * in two different ways: code 284 + 5 bits or code 285, so we
  11026. * overwrite length_code[255] to use the best encoding:
  11027. */
  11028. _length_code[length - 1] = code;
  11029.  
  11030. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  11031. dist = 0;
  11032. for (code = 0; code < 16; code++) {
  11033. base_dist[code] = dist;
  11034. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  11035. _dist_code[dist++] = code;
  11036. }
  11037. }
  11038. //Assert (dist == 256, "tr_static_init: dist != 256");
  11039. dist >>= 7; /* from now on, all distances are divided by 128 */
  11040. for (; code < D_CODES; code++) {
  11041. base_dist[code] = dist << 7;
  11042. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  11043. _dist_code[256 + dist++] = code;
  11044. }
  11045. }
  11046. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  11047.  
  11048. /* Construct the codes of the static literal tree */
  11049. for (bits = 0; bits <= MAX_BITS; bits++) {
  11050. bl_count[bits] = 0;
  11051. }
  11052.  
  11053. n = 0;
  11054. while (n <= 143) {
  11055. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  11056. n++;
  11057. bl_count[8]++;
  11058. }
  11059. while (n <= 255) {
  11060. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  11061. n++;
  11062. bl_count[9]++;
  11063. }
  11064. while (n <= 279) {
  11065. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  11066. n++;
  11067. bl_count[7]++;
  11068. }
  11069. while (n <= 287) {
  11070. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  11071. n++;
  11072. bl_count[8]++;
  11073. }
  11074. /* Codes 286 and 287 do not exist, but we must include them in the
  11075. * tree construction to get a canonical Huffman tree (longest code
  11076. * all ones)
  11077. */
  11078. gen_codes(static_ltree, L_CODES + 1, bl_count);
  11079.  
  11080. /* The static distance tree is trivial: */
  11081. for (n = 0; n < D_CODES; n++) {
  11082. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  11083. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  11084. }
  11085.  
  11086. // Now data ready and we can init static trees
  11087. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  11088. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  11089. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  11090.  
  11091. //static_init_done = true;
  11092. }
  11093.  
  11094.  
  11095. /* ===========================================================================
  11096. * Initialize a new block.
  11097. */
  11098. function init_block(s) {
  11099. var n; /* iterates over tree elements */
  11100.  
  11101. /* Initialize the trees. */
  11102. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  11103. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  11104. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  11105.  
  11106. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  11107. s.opt_len = s.static_len = 0;
  11108. s.last_lit = s.matches = 0;
  11109. }
  11110.  
  11111.  
  11112. /* ===========================================================================
  11113. * Flush the bit buffer and align the output on a byte boundary
  11114. */
  11115. function bi_windup(s)
  11116. {
  11117. if (s.bi_valid > 8) {
  11118. put_short(s, s.bi_buf);
  11119. } else if (s.bi_valid > 0) {
  11120. //put_byte(s, (Byte)s->bi_buf);
  11121. s.pending_buf[s.pending++] = s.bi_buf;
  11122. }
  11123. s.bi_buf = 0;
  11124. s.bi_valid = 0;
  11125. }
  11126.  
  11127. /* ===========================================================================
  11128. * Copy a stored block, storing first the length and its
  11129. * one's complement if requested.
  11130. */
  11131. function copy_block(s, buf, len, header)
  11132. //DeflateState *s;
  11133. //charf *buf; /* the input data */
  11134. //unsigned len; /* its length */
  11135. //int header; /* true if block header must be written */
  11136. {
  11137. bi_windup(s); /* align on byte boundary */
  11138.  
  11139. if (header) {
  11140. put_short(s, len);
  11141. put_short(s, ~len);
  11142. }
  11143. // while (len--) {
  11144. // put_byte(s, *buf++);
  11145. // }
  11146. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  11147. s.pending += len;
  11148. }
  11149.  
  11150. /* ===========================================================================
  11151. * Compares to subtrees, using the tree depth as tie breaker when
  11152. * the subtrees have equal frequency. This minimizes the worst case length.
  11153. */
  11154. function smaller(tree, n, m, depth) {
  11155. var _n2 = n * 2;
  11156. var _m2 = m * 2;
  11157. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  11158. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  11159. }
  11160.  
  11161. /* ===========================================================================
  11162. * Restore the heap property by moving down the tree starting at node k,
  11163. * exchanging a node with the smallest of its two sons if necessary, stopping
  11164. * when the heap property is re-established (each father smaller than its
  11165. * two sons).
  11166. */
  11167. function pqdownheap(s, tree, k)
  11168. // deflate_state *s;
  11169. // ct_data *tree; /* the tree to restore */
  11170. // int k; /* node to move down */
  11171. {
  11172. var v = s.heap[k];
  11173. var j = k << 1; /* left son of k */
  11174. while (j <= s.heap_len) {
  11175. /* Set j to the smallest of the two sons: */
  11176. if (j < s.heap_len &&
  11177. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  11178. j++;
  11179. }
  11180. /* Exit if v is smaller than both sons */
  11181. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  11182.  
  11183. /* Exchange v with the smallest son */
  11184. s.heap[k] = s.heap[j];
  11185. k = j;
  11186.  
  11187. /* And continue down the tree, setting j to the left son of k */
  11188. j <<= 1;
  11189. }
  11190. s.heap[k] = v;
  11191. }
  11192.  
  11193.  
  11194. // inlined manually
  11195. // var SMALLEST = 1;
  11196.  
  11197. /* ===========================================================================
  11198. * Send the block data compressed using the given Huffman trees
  11199. */
  11200. function compress_block(s, ltree, dtree)
  11201. // deflate_state *s;
  11202. // const ct_data *ltree; /* literal tree */
  11203. // const ct_data *dtree; /* distance tree */
  11204. {
  11205. var dist; /* distance of matched string */
  11206. var lc; /* match length or unmatched char (if dist == 0) */
  11207. var lx = 0; /* running index in l_buf */
  11208. var code; /* the code to send */
  11209. var extra; /* number of extra bits to send */
  11210.  
  11211. if (s.last_lit !== 0) {
  11212. do {
  11213. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  11214. lc = s.pending_buf[s.l_buf + lx];
  11215. lx++;
  11216.  
  11217. if (dist === 0) {
  11218. send_code(s, lc, ltree); /* send a literal byte */
  11219. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  11220. } else {
  11221. /* Here, lc is the match length - MIN_MATCH */
  11222. code = _length_code[lc];
  11223. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  11224. extra = extra_lbits[code];
  11225. if (extra !== 0) {
  11226. lc -= base_length[code];
  11227. send_bits(s, lc, extra); /* send the extra length bits */
  11228. }
  11229. dist--; /* dist is now the match distance - 1 */
  11230. code = d_code(dist);
  11231. //Assert (code < D_CODES, "bad d_code");
  11232.  
  11233. send_code(s, code, dtree); /* send the distance code */
  11234. extra = extra_dbits[code];
  11235. if (extra !== 0) {
  11236. dist -= base_dist[code];
  11237. send_bits(s, dist, extra); /* send the extra distance bits */
  11238. }
  11239. } /* literal or match pair ? */
  11240.  
  11241. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  11242. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  11243. // "pendingBuf overflow");
  11244.  
  11245. } while (lx < s.last_lit);
  11246. }
  11247.  
  11248. send_code(s, END_BLOCK, ltree);
  11249. }
  11250.  
  11251.  
  11252. /* ===========================================================================
  11253. * Construct one Huffman tree and assigns the code bit strings and lengths.
  11254. * Update the total bit length for the current block.
  11255. * IN assertion: the field freq is set for all tree elements.
  11256. * OUT assertions: the fields len and code are set to the optimal bit length
  11257. * and corresponding code. The length opt_len is updated; static_len is
  11258. * also updated if stree is not null. The field max_code is set.
  11259. */
  11260. function build_tree(s, desc)
  11261. // deflate_state *s;
  11262. // tree_desc *desc; /* the tree descriptor */
  11263. {
  11264. var tree = desc.dyn_tree;
  11265. var stree = desc.stat_desc.static_tree;
  11266. var has_stree = desc.stat_desc.has_stree;
  11267. var elems = desc.stat_desc.elems;
  11268. var n, m; /* iterate over heap elements */
  11269. var max_code = -1; /* largest code with non zero frequency */
  11270. var node; /* new node being created */
  11271.  
  11272. /* Construct the initial heap, with least frequent element in
  11273. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  11274. * heap[0] is not used.
  11275. */
  11276. s.heap_len = 0;
  11277. s.heap_max = HEAP_SIZE;
  11278.  
  11279. for (n = 0; n < elems; n++) {
  11280. if (tree[n * 2]/*.Freq*/ !== 0) {
  11281. s.heap[++s.heap_len] = max_code = n;
  11282. s.depth[n] = 0;
  11283.  
  11284. } else {
  11285. tree[n * 2 + 1]/*.Len*/ = 0;
  11286. }
  11287. }
  11288.  
  11289. /* The pkzip format requires that at least one distance code exists,
  11290. * and that at least one bit should be sent even if there is only one
  11291. * possible code. So to avoid special checks later on we force at least
  11292. * two codes of non zero frequency.
  11293. */
  11294. while (s.heap_len < 2) {
  11295. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  11296. tree[node * 2]/*.Freq*/ = 1;
  11297. s.depth[node] = 0;
  11298. s.opt_len--;
  11299.  
  11300. if (has_stree) {
  11301. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  11302. }
  11303. /* node is 0 or 1 so it does not have extra bits */
  11304. }
  11305. desc.max_code = max_code;
  11306.  
  11307. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  11308. * establish sub-heaps of increasing lengths:
  11309. */
  11310. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  11311.  
  11312. /* Construct the Huffman tree by repeatedly combining the least two
  11313. * frequent nodes.
  11314. */
  11315. node = elems; /* next internal node of the tree */
  11316. do {
  11317. //pqremove(s, tree, n); /* n = node of least frequency */
  11318. /*** pqremove ***/
  11319. n = s.heap[1/*SMALLEST*/];
  11320. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  11321. pqdownheap(s, tree, 1/*SMALLEST*/);
  11322. /***/
  11323.  
  11324. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  11325.  
  11326. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  11327. s.heap[--s.heap_max] = m;
  11328.  
  11329. /* Create a new node father of n and m */
  11330. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  11331. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  11332. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  11333.  
  11334. /* and insert the new node in the heap */
  11335. s.heap[1/*SMALLEST*/] = node++;
  11336. pqdownheap(s, tree, 1/*SMALLEST*/);
  11337.  
  11338. } while (s.heap_len >= 2);
  11339.  
  11340. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  11341.  
  11342. /* At this point, the fields freq and dad are set. We can now
  11343. * generate the bit lengths.
  11344. */
  11345. gen_bitlen(s, desc);
  11346.  
  11347. /* The field len is now set, we can generate the bit codes */
  11348. gen_codes(tree, max_code, s.bl_count);
  11349. }
  11350.  
  11351.  
  11352. /* ===========================================================================
  11353. * Scan a literal or distance tree to determine the frequencies of the codes
  11354. * in the bit length tree.
  11355. */
  11356. function scan_tree(s, tree, max_code)
  11357. // deflate_state *s;
  11358. // ct_data *tree; /* the tree to be scanned */
  11359. // int max_code; /* and its largest code of non zero frequency */
  11360. {
  11361. var n; /* iterates over all tree elements */
  11362. var prevlen = -1; /* last emitted length */
  11363. var curlen; /* length of current code */
  11364.  
  11365. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  11366.  
  11367. var count = 0; /* repeat count of the current code */
  11368. var max_count = 7; /* max repeat count */
  11369. var min_count = 4; /* min repeat count */
  11370.  
  11371. if (nextlen === 0) {
  11372. max_count = 138;
  11373. min_count = 3;
  11374. }
  11375. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  11376.  
  11377. for (n = 0; n <= max_code; n++) {
  11378. curlen = nextlen;
  11379. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  11380.  
  11381. if (++count < max_count && curlen === nextlen) {
  11382. continue;
  11383.  
  11384. } else if (count < min_count) {
  11385. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  11386.  
  11387. } else if (curlen !== 0) {
  11388.  
  11389. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  11390. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  11391.  
  11392. } else if (count <= 10) {
  11393. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  11394.  
  11395. } else {
  11396. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  11397. }
  11398.  
  11399. count = 0;
  11400. prevlen = curlen;
  11401.  
  11402. if (nextlen === 0) {
  11403. max_count = 138;
  11404. min_count = 3;
  11405.  
  11406. } else if (curlen === nextlen) {
  11407. max_count = 6;
  11408. min_count = 3;
  11409.  
  11410. } else {
  11411. max_count = 7;
  11412. min_count = 4;
  11413. }
  11414. }
  11415. }
  11416.  
  11417.  
  11418. /* ===========================================================================
  11419. * Send a literal or distance tree in compressed form, using the codes in
  11420. * bl_tree.
  11421. */
  11422. function send_tree(s, tree, max_code)
  11423. // deflate_state *s;
  11424. // ct_data *tree; /* the tree to be scanned */
  11425. // int max_code; /* and its largest code of non zero frequency */
  11426. {
  11427. var n; /* iterates over all tree elements */
  11428. var prevlen = -1; /* last emitted length */
  11429. var curlen; /* length of current code */
  11430.  
  11431. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  11432.  
  11433. var count = 0; /* repeat count of the current code */
  11434. var max_count = 7; /* max repeat count */
  11435. var min_count = 4; /* min repeat count */
  11436.  
  11437. /* tree[max_code+1].Len = -1; */ /* guard already set */
  11438. if (nextlen === 0) {
  11439. max_count = 138;
  11440. min_count = 3;
  11441. }
  11442.  
  11443. for (n = 0; n <= max_code; n++) {
  11444. curlen = nextlen;
  11445. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  11446.  
  11447. if (++count < max_count && curlen === nextlen) {
  11448. continue;
  11449.  
  11450. } else if (count < min_count) {
  11451. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  11452.  
  11453. } else if (curlen !== 0) {
  11454. if (curlen !== prevlen) {
  11455. send_code(s, curlen, s.bl_tree);
  11456. count--;
  11457. }
  11458. //Assert(count >= 3 && count <= 6, " 3_6?");
  11459. send_code(s, REP_3_6, s.bl_tree);
  11460. send_bits(s, count - 3, 2);
  11461.  
  11462. } else if (count <= 10) {
  11463. send_code(s, REPZ_3_10, s.bl_tree);
  11464. send_bits(s, count - 3, 3);
  11465.  
  11466. } else {
  11467. send_code(s, REPZ_11_138, s.bl_tree);
  11468. send_bits(s, count - 11, 7);
  11469. }
  11470.  
  11471. count = 0;
  11472. prevlen = curlen;
  11473. if (nextlen === 0) {
  11474. max_count = 138;
  11475. min_count = 3;
  11476.  
  11477. } else if (curlen === nextlen) {
  11478. max_count = 6;
  11479. min_count = 3;
  11480.  
  11481. } else {
  11482. max_count = 7;
  11483. min_count = 4;
  11484. }
  11485. }
  11486. }
  11487.  
  11488.  
  11489. /* ===========================================================================
  11490. * Construct the Huffman tree for the bit lengths and return the index in
  11491. * bl_order of the last bit length code to send.
  11492. */
  11493. function build_bl_tree(s) {
  11494. var max_blindex; /* index of last bit length code of non zero freq */
  11495.  
  11496. /* Determine the bit length frequencies for literal and distance trees */
  11497. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  11498. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  11499.  
  11500. /* Build the bit length tree: */
  11501. build_tree(s, s.bl_desc);
  11502. /* opt_len now includes the length of the tree representations, except
  11503. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  11504. */
  11505.  
  11506. /* Determine the number of bit length codes to send. The pkzip format
  11507. * requires that at least 4 bit length codes be sent. (appnote.txt says
  11508. * 3 but the actual value used is 4.)
  11509. */
  11510. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  11511. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  11512. break;
  11513. }
  11514. }
  11515. /* Update opt_len to include the bit length tree and counts */
  11516. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  11517. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  11518. // s->opt_len, s->static_len));
  11519.  
  11520. return max_blindex;
  11521. }
  11522.  
  11523.  
  11524. /* ===========================================================================
  11525. * Send the header for a block using dynamic Huffman trees: the counts, the
  11526. * lengths of the bit length codes, the literal tree and the distance tree.
  11527. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  11528. */
  11529. function send_all_trees(s, lcodes, dcodes, blcodes)
  11530. // deflate_state *s;
  11531. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  11532. {
  11533. var rank; /* index in bl_order */
  11534.  
  11535. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  11536. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  11537. // "too many codes");
  11538. //Tracev((stderr, "\nbl counts: "));
  11539. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  11540. send_bits(s, dcodes - 1, 5);
  11541. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  11542. for (rank = 0; rank < blcodes; rank++) {
  11543. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  11544. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  11545. }
  11546. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  11547.  
  11548. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  11549. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  11550.  
  11551. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  11552. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  11553. }
  11554.  
  11555.  
  11556. /* ===========================================================================
  11557. * Check if the data type is TEXT or BINARY, using the following algorithm:
  11558. * - TEXT if the two conditions below are satisfied:
  11559. * a) There are no non-portable control characters belonging to the
  11560. * "black list" (0..6, 14..25, 28..31).
  11561. * b) There is at least one printable character belonging to the
  11562. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  11563. * - BINARY otherwise.
  11564. * - The following partially-portable control characters form a
  11565. * "gray list" that is ignored in this detection algorithm:
  11566. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  11567. * IN assertion: the fields Freq of dyn_ltree are set.
  11568. */
  11569. function detect_data_type(s) {
  11570. /* black_mask is the bit mask of black-listed bytes
  11571. * set bits 0..6, 14..25, and 28..31
  11572. * 0xf3ffc07f = binary 11110011111111111100000001111111
  11573. */
  11574. var black_mask = 0xf3ffc07f;
  11575. var n;
  11576.  
  11577. /* Check for non-textual ("black-listed") bytes. */
  11578. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  11579. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  11580. return Z_BINARY;
  11581. }
  11582. }
  11583.  
  11584. /* Check for textual ("white-listed") bytes. */
  11585. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  11586. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  11587. return Z_TEXT;
  11588. }
  11589. for (n = 32; n < LITERALS; n++) {
  11590. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  11591. return Z_TEXT;
  11592. }
  11593. }
  11594.  
  11595. /* There are no "black-listed" or "white-listed" bytes:
  11596. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  11597. */
  11598. return Z_BINARY;
  11599. }
  11600.  
  11601.  
  11602. var static_init_done = false;
  11603.  
  11604. /* ===========================================================================
  11605. * Initialize the tree data structures for a new zlib stream.
  11606. */
  11607. function _tr_init(s)
  11608. {
  11609.  
  11610. if (!static_init_done) {
  11611. tr_static_init();
  11612. static_init_done = true;
  11613. }
  11614.  
  11615. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  11616. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  11617. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  11618.  
  11619. s.bi_buf = 0;
  11620. s.bi_valid = 0;
  11621.  
  11622. /* Initialize the first block of the first file: */
  11623. init_block(s);
  11624. }
  11625.  
  11626.  
  11627. /* ===========================================================================
  11628. * Send a stored block
  11629. */
  11630. function _tr_stored_block(s, buf, stored_len, last)
  11631. //DeflateState *s;
  11632. //charf *buf; /* input block */
  11633. //ulg stored_len; /* length of input block */
  11634. //int last; /* one if this is the last block for a file */
  11635. {
  11636. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  11637. copy_block(s, buf, stored_len, true); /* with header */
  11638. }
  11639.  
  11640.  
  11641. /* ===========================================================================
  11642. * Send one empty static block to give enough lookahead for inflate.
  11643. * This takes 10 bits, of which 7 may remain in the bit buffer.
  11644. */
  11645. function _tr_align(s) {
  11646. send_bits(s, STATIC_TREES << 1, 3);
  11647. send_code(s, END_BLOCK, static_ltree);
  11648. bi_flush(s);
  11649. }
  11650.  
  11651.  
  11652. /* ===========================================================================
  11653. * Determine the best encoding for the current block: dynamic trees, static
  11654. * trees or store, and output the encoded block to the zip file.
  11655. */
  11656. function _tr_flush_block(s, buf, stored_len, last)
  11657. //DeflateState *s;
  11658. //charf *buf; /* input block, or NULL if too old */
  11659. //ulg stored_len; /* length of input block */
  11660. //int last; /* one if this is the last block for a file */
  11661. {
  11662. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  11663. var max_blindex = 0; /* index of last bit length code of non zero freq */
  11664.  
  11665. /* Build the Huffman trees unless a stored block is forced */
  11666. if (s.level > 0) {
  11667.  
  11668. /* Check if the file is binary or text */
  11669. if (s.strm.data_type === Z_UNKNOWN) {
  11670. s.strm.data_type = detect_data_type(s);
  11671. }
  11672.  
  11673. /* Construct the literal and distance trees */
  11674. build_tree(s, s.l_desc);
  11675. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  11676. // s->static_len));
  11677.  
  11678. build_tree(s, s.d_desc);
  11679. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  11680. // s->static_len));
  11681. /* At this point, opt_len and static_len are the total bit lengths of
  11682. * the compressed block data, excluding the tree representations.
  11683. */
  11684.  
  11685. /* Build the bit length tree for the above two trees, and get the index
  11686. * in bl_order of the last bit length code to send.
  11687. */
  11688. max_blindex = build_bl_tree(s);
  11689.  
  11690. /* Determine the best encoding. Compute the block lengths in bytes. */
  11691. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  11692. static_lenb = (s.static_len + 3 + 7) >>> 3;
  11693.  
  11694. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  11695. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  11696. // s->last_lit));
  11697.  
  11698. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  11699.  
  11700. } else {
  11701. // Assert(buf != (char*)0, "lost buf");
  11702. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  11703. }
  11704.  
  11705. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  11706. /* 4: two words for the lengths */
  11707.  
  11708. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  11709. * Otherwise we can't have processed more than WSIZE input bytes since
  11710. * the last block flush, because compression would have been
  11711. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  11712. * transform a block into a stored block.
  11713. */
  11714. _tr_stored_block(s, buf, stored_len, last);
  11715.  
  11716. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  11717.  
  11718. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  11719. compress_block(s, static_ltree, static_dtree);
  11720.  
  11721. } else {
  11722. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  11723. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  11724. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  11725. }
  11726. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  11727. /* The above check is made mod 2^32, for files larger than 512 MB
  11728. * and uLong implemented on 32 bits.
  11729. */
  11730. init_block(s);
  11731.  
  11732. if (last) {
  11733. bi_windup(s);
  11734. }
  11735. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  11736. // s->compressed_len-7*last));
  11737. }
  11738.  
  11739. /* ===========================================================================
  11740. * Save the match info and tally the frequency counts. Return true if
  11741. * the current block must be flushed.
  11742. */
  11743. function _tr_tally(s, dist, lc)
  11744. // deflate_state *s;
  11745. // unsigned dist; /* distance of matched string */
  11746. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  11747. {
  11748. //var out_length, in_length, dcode;
  11749.  
  11750. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  11751. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  11752.  
  11753. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  11754. s.last_lit++;
  11755.  
  11756. if (dist === 0) {
  11757. /* lc is the unmatched char */
  11758. s.dyn_ltree[lc * 2]/*.Freq*/++;
  11759. } else {
  11760. s.matches++;
  11761. /* Here, lc is the match length - MIN_MATCH */
  11762. dist--; /* dist = match distance - 1 */
  11763. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  11764. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  11765. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  11766.  
  11767. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  11768. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  11769. }
  11770.  
  11771. // (!) This block is disabled in zlib defailts,
  11772. // don't enable it for binary compatibility
  11773.  
  11774. //#ifdef TRUNCATE_BLOCK
  11775. // /* Try to guess if it is profitable to stop the current block here */
  11776. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  11777. // /* Compute an upper bound for the compressed length */
  11778. // out_length = s.last_lit*8;
  11779. // in_length = s.strstart - s.block_start;
  11780. //
  11781. // for (dcode = 0; dcode < D_CODES; dcode++) {
  11782. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  11783. // }
  11784. // out_length >>>= 3;
  11785. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  11786. // // s->last_lit, in_length, out_length,
  11787. // // 100L - out_length*100L/in_length));
  11788. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  11789. // return true;
  11790. // }
  11791. // }
  11792. //#endif
  11793.  
  11794. return (s.last_lit === s.lit_bufsize - 1);
  11795. /* We avoid equality with lit_bufsize because of wraparound at 64K
  11796. * on 16 bit machines and because stored blocks are restricted to
  11797. * 64K-1 bytes.
  11798. */
  11799. }
  11800.  
  11801. exports._tr_init = _tr_init;
  11802. exports._tr_stored_block = _tr_stored_block;
  11803. exports._tr_flush_block = _tr_flush_block;
  11804. exports._tr_tally = _tr_tally;
  11805. exports._tr_align = _tr_align;
  11806.  
  11807. },{"../utils/common":41}],53:[function(require,module,exports){
  11808. 'use strict';
  11809.  
  11810. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  11811. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  11812. //
  11813. // This software is provided 'as-is', without any express or implied
  11814. // warranty. In no event will the authors be held liable for any damages
  11815. // arising from the use of this software.
  11816. //
  11817. // Permission is granted to anyone to use this software for any purpose,
  11818. // including commercial applications, and to alter it and redistribute it
  11819. // freely, subject to the following restrictions:
  11820. //
  11821. // 1. The origin of this software must not be misrepresented; you must not
  11822. // claim that you wrote the original software. If you use this software
  11823. // in a product, an acknowledgment in the product documentation would be
  11824. // appreciated but is not required.
  11825. // 2. Altered source versions must be plainly marked as such, and must not be
  11826. // misrepresented as being the original software.
  11827. // 3. This notice may not be removed or altered from any source distribution.
  11828.  
  11829. function ZStream() {
  11830. /* next input byte */
  11831. this.input = null; // JS specific, because we have no pointers
  11832. this.next_in = 0;
  11833. /* number of bytes available at input */
  11834. this.avail_in = 0;
  11835. /* total number of input bytes read so far */
  11836. this.total_in = 0;
  11837. /* next output byte should be put there */
  11838. this.output = null; // JS specific, because we have no pointers
  11839. this.next_out = 0;
  11840. /* remaining free space at output */
  11841. this.avail_out = 0;
  11842. /* total number of bytes output so far */
  11843. this.total_out = 0;
  11844. /* last error message, NULL if no error */
  11845. this.msg = ''/*Z_NULL*/;
  11846. /* not visible by applications */
  11847. this.state = null;
  11848. /* best guess about the data type: binary or text */
  11849. this.data_type = 2/*Z_UNKNOWN*/;
  11850. /* adler32 value of the uncompressed data */
  11851. this.adler = 0;
  11852. }
  11853.  
  11854. module.exports = ZStream;
  11855.  
  11856. },{}],54:[function(require,module,exports){
  11857. (function (global){
  11858. (function (global, undefined) {
  11859. "use strict";
  11860.  
  11861. if (global.setImmediate) {
  11862. return;
  11863. }
  11864.  
  11865. var nextHandle = 1; // Spec says greater than zero
  11866. var tasksByHandle = {};
  11867. var currentlyRunningATask = false;
  11868. var doc = global.document;
  11869. var registerImmediate;
  11870.  
  11871. function setImmediate(callback) {
  11872. // Callback can either be a function or a string
  11873. if (typeof callback !== "function") {
  11874. callback = new Function("" + callback);
  11875. }
  11876. // Copy function arguments
  11877. var args = new Array(arguments.length - 1);
  11878. for (var i = 0; i < args.length; i++) {
  11879. args[i] = arguments[i + 1];
  11880. }
  11881. // Store and register the task
  11882. var task = { callback: callback, args: args };
  11883. tasksByHandle[nextHandle] = task;
  11884. registerImmediate(nextHandle);
  11885. return nextHandle++;
  11886. }
  11887.  
  11888. function clearImmediate(handle) {
  11889. delete tasksByHandle[handle];
  11890. }
  11891.  
  11892. function run(task) {
  11893. var callback = task.callback;
  11894. var args = task.args;
  11895. switch (args.length) {
  11896. case 0:
  11897. callback();
  11898. break;
  11899. case 1:
  11900. callback(args[0]);
  11901. break;
  11902. case 2:
  11903. callback(args[0], args[1]);
  11904. break;
  11905. case 3:
  11906. callback(args[0], args[1], args[2]);
  11907. break;
  11908. default:
  11909. callback.apply(undefined, args);
  11910. break;
  11911. }
  11912. }
  11913.  
  11914. function runIfPresent(handle) {
  11915. // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
  11916. // So if we're currently running a task, we'll need to delay this invocation.
  11917. if (currentlyRunningATask) {
  11918. // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
  11919. // "too much recursion" error.
  11920. setTimeout(runIfPresent, 0, handle);
  11921. } else {
  11922. var task = tasksByHandle[handle];
  11923. if (task) {
  11924. currentlyRunningATask = true;
  11925. try {
  11926. run(task);
  11927. } finally {
  11928. clearImmediate(handle);
  11929. currentlyRunningATask = false;
  11930. }
  11931. }
  11932. }
  11933. }
  11934.  
  11935. function installNextTickImplementation() {
  11936. registerImmediate = function(handle) {
  11937. process.nextTick(function () { runIfPresent(handle); });
  11938. };
  11939. }
  11940.  
  11941. function canUsePostMessage() {
  11942. // The test against `importScripts` prevents this implementation from being installed inside a web worker,
  11943. // where `global.postMessage` means something completely different and can't be used for this purpose.
  11944. if (global.postMessage && !global.importScripts) {
  11945. var postMessageIsAsynchronous = true;
  11946. var oldOnMessage = global.onmessage;
  11947. global.onmessage = function() {
  11948. postMessageIsAsynchronous = false;
  11949. };
  11950. global.postMessage("", "*");
  11951. global.onmessage = oldOnMessage;
  11952. return postMessageIsAsynchronous;
  11953. }
  11954. }
  11955.  
  11956. function installPostMessageImplementation() {
  11957. // Installs an event handler on `global` for the `message` event: see
  11958. // * https://developer.mozilla.org/en/DOM/window.postMessage
  11959. // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
  11960.  
  11961. var messagePrefix = "setImmediate$" + Math.random() + "$";
  11962. var onGlobalMessage = function(event) {
  11963. if (event.source === global &&
  11964. typeof event.data === "string" &&
  11965. event.data.indexOf(messagePrefix) === 0) {
  11966. runIfPresent(+event.data.slice(messagePrefix.length));
  11967. }
  11968. };
  11969.  
  11970. if (global.addEventListener) {
  11971. global.addEventListener("message", onGlobalMessage, false);
  11972. } else {
  11973. global.attachEvent("onmessage", onGlobalMessage);
  11974. }
  11975.  
  11976. registerImmediate = function(handle) {
  11977. global.postMessage(messagePrefix + handle, "*");
  11978. };
  11979. }
  11980.  
  11981. function installMessageChannelImplementation() {
  11982. var channel = new MessageChannel();
  11983. channel.port1.onmessage = function(event) {
  11984. var handle = event.data;
  11985. runIfPresent(handle);
  11986. };
  11987.  
  11988. registerImmediate = function(handle) {
  11989. channel.port2.postMessage(handle);
  11990. };
  11991. }
  11992.  
  11993. function installReadyStateChangeImplementation() {
  11994. var html = doc.documentElement;
  11995. registerImmediate = function(handle) {
  11996. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  11997. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  11998. var script = doc.createElement("script");
  11999. script.onreadystatechange = function () {
  12000. runIfPresent(handle);
  12001. script.onreadystatechange = null;
  12002. html.removeChild(script);
  12003. script = null;
  12004. };
  12005. html.appendChild(script);
  12006. };
  12007. }
  12008.  
  12009. function installSetTimeoutImplementation() {
  12010. registerImmediate = function(handle) {
  12011. setTimeout(runIfPresent, 0, handle);
  12012. };
  12013. }
  12014.  
  12015. // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
  12016. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
  12017. attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
  12018.  
  12019. // Don't get fooled by e.g. browserify environments.
  12020. if ({}.toString.call(global.process) === "[object process]") {
  12021. // For Node.js before 0.9
  12022. installNextTickImplementation();
  12023.  
  12024. } else if (canUsePostMessage()) {
  12025. // For non-IE10 modern browsers
  12026. installPostMessageImplementation();
  12027.  
  12028. } else if (global.MessageChannel) {
  12029. // For web workers, where supported
  12030. installMessageChannelImplementation();
  12031.  
  12032. } else if (doc && "onreadystatechange" in doc.createElement("script")) {
  12033. // For IE 6–8
  12034. installReadyStateChangeImplementation();
  12035.  
  12036. } else {
  12037. // For older browsers
  12038. installSetTimeoutImplementation();
  12039. }
  12040.  
  12041. attachTo.setImmediate = setImmediate;
  12042. attachTo.clearImmediate = clearImmediate;
  12043. }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
  12044.  
  12045. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12046. },{}]},{},[10])(10)
  12047. });