Make WordPress Core

Ticket #9757: 9757.2.patch

File 9757.2.patch, 403.1 KB (added by imath, 7 years ago)
  • src/wp-admin/css/themes.css

    diff --git src/wp-admin/css/themes.css src/wp-admin/css/themes.css
    index eece216..7865cae 100644
    body.folded .theme-browser ~ .theme-overlay .theme-wrap { 
    10541054        margin: 30px auto;
    10551055        max-width: 380px;
    10561056}
     1057.upload-plugin .wp-upload-form #existing-plugin-info h3 {
     1058        margin-top: 8px;
     1059}
     1060.upload-plugin .wp-upload-form .plugin-card-top {
     1061        padding-top: 10px;
     1062}
     1063.upload-plugin .wp-upload-form.has-existing-plugin #install-plugin-submit,
     1064.upload-plugin .wp-upload-form.has-existing-plugin .install-plugin-reset {
     1065        display: inline-block;
     1066        margin-top: 20px;
     1067        margin-right: 10px;
     1068}
     1069
    10571070.upload-theme .install-help,
    10581071.upload-plugin .install-help {
    10591072        color: #555d66; /* #f1f1f1 background */
  • src/wp-admin/includes/class-plugin-upgrader.php

    diff --git src/wp-admin/includes/class-plugin-upgrader.php src/wp-admin/includes/class-plugin-upgrader.php
    index 3c05353..e6abed1 100644
    class Plugin_Upgrader extends WP_Upgrader { 
    5353                $this->strings['remove_old_failed'] = __('Could not remove the old plugin.');
    5454                $this->strings['process_failed'] = __('Plugin update failed.');
    5555                $this->strings['process_success'] = __('Plugin updated successfully.');
     56                $this->strings['overwrite_success'] = __('Plugin replaced successfully.');
    5657                $this->strings['process_bulk_success'] = __('Plugins updated successfully.');
    5758        }
    5859
    class Plugin_Upgrader extends WP_Upgrader { 
    136137         * @param array  $args {
    137138         *     Optional. Other arguments for upgrading a plugin package. Default empty array.
    138139         *
    139          *     @type bool $clear_update_cache Whether to clear the plugin updates cache if successful.
    140          *                                    Default true.
     140         *     @type bool   $clear_update_cache Whether to clear the plugin updates cache if successful.
     141         *                                      Default true.
     142         *     @type string $package            Path to the package to replace an existing plugin with.
     143         *                                      Default ''.
    141144         * }
    142145         * @return bool|WP_Error True if the upgrade was successful, false or a WP_Error object otherwise.
    143146         */
    class Plugin_Upgrader extends WP_Upgrader { 
    145148
    146149                $defaults = array(
    147150                        'clear_update_cache' => true,
     151                        'package'            => '',
    148152                );
    149153                $parsed_args = wp_parse_args( $args, $defaults );
    150154
    151155                $this->init();
    152156                $this->upgrade_strings();
    153157
    154                 $current = get_site_transient( 'update_plugins' );
    155                 if ( !isset( $current->response[ $plugin ] ) ) {
    156                         $this->skin->before();
    157                         $this->skin->set_result(false);
    158                         $this->skin->error('up_to_date');
    159                         $this->skin->after();
    160                         return false;
    161                 }
     158                $package = $parsed_args['package'];
     159                if ( ! $package ) {
     160                        $current = get_site_transient( 'update_plugins' );
     161                        if ( !isset( $current->response[ $plugin ] ) ) {
     162                                $this->skin->before();
     163                                $this->skin->set_result(false);
     164                                $this->skin->error('up_to_date');
     165                                $this->skin->after();
     166                                return false;
     167                        }
    162168
    163                 // Get the URL to the zip file
    164                 $r = $current->response[ $plugin ];
     169                        // Get the URL to the zip file
     170                        $r = $current->response[ $plugin ];
     171                        $package = $r->package;
     172                        $action  = 'update';
     173                } else {
     174                        $action  = 'overwrite';
     175                }
    165176
    166177                add_filter('upgrader_pre_install', array($this, 'deactivate_plugin_before_upgrade'), 10, 2);
    167178                add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4);
    class Plugin_Upgrader extends WP_Upgrader { 
    172183                }
    173184
    174185                $this->run( array(
    175                         'package' => $r->package,
     186                        'package' => $package,
    176187                        'destination' => WP_PLUGIN_DIR,
    177188                        'clear_destination' => true,
    178189                        'clear_working' => true,
    179190                        'hook_extra' => array(
    180191                                'plugin' => $plugin,
    181192                                'type' => 'plugin',
    182                                 'action' => 'update',
     193                                'action' => $action,
    183194                        ),
    184195                ) );
    185196
  • src/wp-admin/includes/class-wp-upgrader.php

    diff --git src/wp-admin/includes/class-wp-upgrader.php src/wp-admin/includes/class-wp-upgrader.php
    index fd70ba4..7f8469c 100644
    class WP_Upgrader { 
    157157
    158158                $this->strings['download_failed'] = __('Download failed.');
    159159                $this->strings['installing_package'] = __('Installing the latest version…');
     160                $this->strings['package_overwriting'] = __('Replacing the installed version…');
    160161                $this->strings['no_files'] = __('The package contains no files.');
    161162                $this->strings['folder_exists'] = __('Destination folder already exists.');
    162163                $this->strings['mkdir_failed'] = __('Could not create directory.');
    class WP_Upgrader { 
    451452                if ( empty( $source ) || empty( $destination ) ) {
    452453                        return new WP_Error( 'bad_request', $this->strings['bad_request'] );
    453454                }
    454                 $this->skin->feedback( 'installing_package' );
     455
     456                if ( isset( $args['hook_extra']['action'] ) && 'overwrite' === $args['hook_extra']['action'] ) {
     457                        // Overwriting the existing plugin
     458                        $this->skin->feedback( 'package_overwriting' );
     459                } else {
     460                        $this->skin->feedback( 'installing_package' );
     461                }
    455462
    456463                /**
    457464                 * Filters the install response before the installation has started.
    class WP_Upgrader { 
    751758                        $this->skin->error($result);
    752759                        $this->skin->feedback('process_failed');
    753760                } else {
    754                         // Installation succeeded.
    755                         $this->skin->feedback('process_success');
     761
     762                        if ( isset( $options['hook_extra']['action'] ) && 'overwrite' === $options['hook_extra']['action'] ) {
     763                                // Overwrite succeeded.
     764                                $this->skin->feedback( 'overwrite_success' );
     765                        } else {
     766                                // Installation succeeded.
     767                                $this->skin->feedback('process_success');
     768                        }
    756769                }
    757770
    758771                $this->skin->after();
  • src/wp-admin/includes/plugin-install.php

    diff --git src/wp-admin/includes/plugin-install.php src/wp-admin/includes/plugin-install.php
    index 1714acd..c4087f4 100644
    function install_plugins_upload() { 
    310310                <?php submit_button( __( 'Install Now' ), '', 'install-plugin-submit', false ); ?>
    311311        </form>
    312312</div>
     313<script type="text/html" id="tmpl-existing-plugin-data">
     314        <div id="existing-plugin-info">
     315                <p class="attention">{{{data.warnOverwrite}}}</p>
     316                <div class="plugin-card-top">
     317                        <h3>{{data.pluginDetailsIntro}}</h3>
     318                        <div class="desc">
     319                                <h4>{{data.name}} {{data.version}}</h4>
     320                                <p class="description">{{{data.description}}}</p>
     321                        </div>
     322                </div>
     323                <input type="hidden" name="overwrite" value="{{data.id}}"/>
     324        </div>
     325</script>
    313326<?php
    314327}
    315328
  • src/wp-admin/js/common.js

    diff --git src/wp-admin/js/common.js src/wp-admin/js/common.js
    index e57af5d..e40015c 100644
    $document.ready( function() { 
    687687                        e.target.scrollIntoView(false);
    688688        });
    689689
    690         // Disable upload buttons until files are selected
    691         (function(){
    692                 var button, input, form = $('form.wp-upload-form');
    693                 if ( ! form.length )
    694                         return;
    695                 button = form.find('input[type="submit"]');
    696                 input = form.find('input[type="file"]');
    697 
    698                 function toggleUploadButton() {
    699                         button.prop('disabled', '' === input.map( function() {
    700                                 return $(this).val();
    701                         }).get().join(''));
    702                 }
    703                 toggleUploadButton();
    704                 input.on('change', toggleUploadButton);
    705         })();
    706 
    707690        function pinMenu( event ) {
    708691                var windowPos = $window.scrollTop(),
    709692                        resizing = ! event || event.type !== 'scroll';
  • src/wp-admin/js/plugin-install.js

    diff --git src/wp-admin/js/plugin-install.js src/wp-admin/js/plugin-install.js
    index 9fa218f..9faade1 100644
    jQuery( document ).ready( function( $ ) { 
    1212                $firstTabbable,
    1313                $lastTabbable,
    1414                $focusedBefore = $(),
    15                 $uploadViewToggle = $( '.upload-view-toggle' ),
    16                 $wrap = $ ( '.wrap' ),
    1715                $body = $( document.body );
    1816
    1917        tb_position = function() {
    jQuery( document ).ready( function( $ ) { 
    191189                $( '#section-holder div.section' ).hide(); // Hide 'em all.
    192190                $( '#section-' + tab ).show();
    193191        });
    194 
    195         /*
    196          * When a user presses the "Upload Plugin" button, show the upload form in place
    197          * rather than sending them to the devoted upload plugin page.
    198          * The `?tab=upload` page still exists for no-js support and for plugins that
    199          * might access it directly. When we're in this page, let the link behave
    200          * like a link. Otherwise we're in the normal plugin installer pages and the
    201          * link should behave like a toggle button.
    202          */
    203         if ( ! $wrap.hasClass( 'plugin-install-tab-upload' ) ) {
    204                 $uploadViewToggle
    205                         .attr({
    206                                 role: 'button',
    207                                 'aria-expanded': 'false'
    208                         })
    209                         .on( 'click', function( event ) {
    210                                 event.preventDefault();
    211                                 $body.toggleClass( 'show-upload-view' );
    212                                 $uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) );
    213                         });
    214         }
    215192});
  • src/wp-admin/js/plugin-upload.js

    diff --git src/wp-admin/js/plugin-upload.js src/wp-admin/js/plugin-upload.js
    index e69de29..4dd0c62 100644
     
     1window.wp = window.wp || {};
     2
     3( function( $, _, wp ){
     4
     5        window.toggleUploadButton = function() {
     6                var button, input, form = $('form.wp-upload-form');
     7
     8                if ( ! form.length ) {
     9                        return;
     10                }
     11
     12                button = form.find('input[type="submit"]');
     13                input  = form.find('input[type="file"]');
     14
     15                button.prop('disabled', '' === input.map( function() {
     16                        return $(this).val();
     17                } ).get().join( '' ) );
     18        };
     19        window.toggleUploadButton();
     20
     21        // Checks if there is an existing plugin.
     22        window.pluginExists = function( slug, form ) {
     23                var template = wp.template( 'existing-plugin-data' ), pluginData = {};
     24
     25                wp.apiRequest( {
     26                        path: 'wp/v2/plugins/' + slug,
     27                        type: 'GET',
     28                        dataType: 'json'
     29                } ).done( function( response ) {
     30                        // The plugin exists, display a warning and informations about the Plugin.
     31                        if ( response && response.id ) {
     32                                form.addClass( 'has-existing-plugin' );
     33                                window.toggleUploadButton();
     34
     35                                $( '#install-plugin-submit' ).after(
     36                                        $( '<input></input' )
     37                                                .prop( 'type', 'reset' )
     38                                                .val( pluginUploadL10n.cancel )
     39                                                .addClass( 'button button-secondary install-plugin-reset' )
     40                                );
     41
     42                                pluginData = _.extend( response, _.pick( pluginUploadL10n, [ 'warnOverwrite','pluginDetailsIntro' ] ) );
     43
     44                                $( '#pluginzip' ).after( template( pluginData ) );
     45                        }
     46
     47                // The plugin is not installed yet.
     48                } ).fail( function() {
     49                        window.toggleUploadButton();
     50                } );
     51        };
     52
     53        $( 'form.wp-upload-form' ).on( 'change', 'input[type="file"]', function( event ) {
     54                if ( ! event.currentTarget.files || 'undefined' === typeof pluginUploadL10n ) {
     55                        toggleUploadButton();
     56                        return event;
     57                }
     58
     59                var file = _.first( event.currentTarget.files ), form = $( event.delegateTarget ), pluginSlug;
     60
     61                if ( file.name ) {
     62                        // Users using modern Browsers won't need to rename the package.
     63                        if ( window.FileReader && window.File && window.FileList && window.Blob ) {
     64                                JSZip.loadAsync( file ).then( function( zip ) {
     65                                        if ( zip.files ) {
     66                                                pluginSlug = _.first( _.keys( zip.files ) ).replace( '/', '' );
     67                                                window.pluginExists( pluginSlug, form );
     68                                        }
     69                                } );
     70
     71                        // Users using old Browsers will need to rename the package.
     72                        } else {
     73                                pluginSlug = file.name.replace( '.zip', '' );
     74                                window.pluginExists( pluginSlug, form );
     75                        }
     76                }
     77        } );
     78
     79        // Resets the Upload form when 'Cancel' is clicked.
     80        $( 'form.wp-upload-form' ).on( 'reset', function( event ) {
     81                $( '#existing-plugin-info' ).remove();
     82                $( event.currentTarget ).removeClass( 'has-existing-plugin' );
     83                $( event.currentTarget ).find( 'input[type="file"]' ).val( '' );
     84                $( event.currentTarget ).find( '.install-plugin-reset' ).remove();
     85                window.toggleUploadButton();
     86        } );
     87
     88        /*
     89         * When a user presses the "Upload Plugin" button, show the upload form in place
     90         * rather than sending them to the devoted upload plugin page.
     91         * The `?tab=upload` page still exists for no-js support and for plugins that
     92         * might access it directly. When we're in this page, let the link behave
     93         * like a link. Otherwise we're in the normal plugin installer pages and the
     94         * link should behave like a toggle button.
     95         */
     96        if ( ! $( '.wrap' ).hasClass( 'plugin-install-tab-upload' ) ) {
     97                $( '.upload-view-toggle' )
     98                        .attr({
     99                                role: 'button',
     100                                'aria-expanded': 'false'
     101                        } )
     102                        .on( 'click', function( event ) {
     103                                var $body = $( document.body ), $uploadViewToggle = $( event.currentTarget );
     104                                event.preventDefault();
     105                                $body.toggleClass( 'show-upload-view' );
     106                                $uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) );
     107                        } );
     108        }
     109
     110}( jQuery, _, window.wp ) );
  • src/wp-admin/plugin-install.php

    diff --git src/wp-admin/plugin-install.php src/wp-admin/plugin-install.php
    index 855beb6..e59e266 100644
    if ( 'plugin-information' != $tab ) 
    5555$body_id = $tab;
    5656
    5757wp_enqueue_script( 'updates' );
     58wp_enqueue_script( 'plugin-upload' );
    5859
    5960/**
    6061 * Fires before each tab on the Install Plugins screen is loaded.
  • src/wp-admin/update.php

    diff --git src/wp-admin/update.php src/wp-admin/update.php
    index 12b8f56..0573a3a 100644
    if ( isset($_GET['action']) ) { 
    159159                $type = 'upload'; //Install plugin type, From Web or an Upload.
    160160
    161161                $upgrader = new Plugin_Upgrader( new Plugin_Installer_Skin( compact('type', 'title', 'nonce', 'url') ) );
    162                 $result = $upgrader->install( $file_upload->package );
     162
     163                // Overwrite an existing plugin.
     164                if ( isset( $_POST['overwrite'] ) && $_POST['overwrite'] ) {
     165                        $result = $upgrader->upgrade( wp_unslash( $_POST['overwrite'] ), array( 'package' => $file_upload->package ) );
     166
     167                // Install a new plugin.
     168                } else {
     169                        $result = $upgrader->install( $file_upload->package );
     170                }
    163171
    164172                if ( $result || is_wp_error($result) )
    165173                        $file_upload->cleanup();
  • src/wp-includes/js/jszip.js

    diff --git src/wp-includes/js/jszip.js src/wp-includes/js/jszip.js
    index e69de29..6b09f2b 100644
     
     1/*!
     2
     3JSZip v3.1.3 - A Javascript class for generating and reading zip files
     4<http://stuartk.com/jszip>
     5
     6(c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
     7Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
     8
     9JSZip uses the library pako released under the MIT license :
     10https://github.com/nodeca/pako/blob/master/LICENSE
     11*/
     12
     13(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSZip = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
     14'use strict';
     15var utils = require('./utils');
     16var support = require('./support');
     17// private property
     18var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
     19
     20
     21// public method for encoding
     22exports.encode = function(input) {
     23    var output = [];
     24    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
     25    var i = 0, len = input.length, remainingBytes = len;
     26
     27    var isArray = utils.getTypeOf(input) !== "string";
     28    while (i < input.length) {
     29        remainingBytes = len - i;
     30
     31        if (!isArray) {
     32            chr1 = input.charCodeAt(i++);
     33            chr2 = i < len ? input.charCodeAt(i++) : 0;
     34            chr3 = i < len ? input.charCodeAt(i++) : 0;
     35        } else {
     36            chr1 = input[i++];
     37            chr2 = i < len ? input[i++] : 0;
     38            chr3 = i < len ? input[i++] : 0;
     39        }
     40
     41        enc1 = chr1 >> 2;
     42        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
     43        enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;
     44        enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;
     45
     46        output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));
     47
     48    }
     49
     50    return output.join("");
     51};
     52
     53// public method for decoding
     54exports.decode = function(input) {
     55    var chr1, chr2, chr3;
     56    var enc1, enc2, enc3, enc4;
     57    var i = 0, resultIndex = 0;
     58
     59    var dataUrlPrefix = "data:";
     60
     61    if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {
     62        // This is a common error: people give a data url
     63        // (data:image/png;base64,iVBOR...) with a {base64: true} and
     64        // wonders why things don't work.
     65        // We can detect that the string input looks like a data url but we
     66        // *can't* be sure it is one: removing everything up to the comma would
     67        // be too dangerous.
     68        throw new Error("Invalid base64 input, it looks like a data url.");
     69    }
     70
     71    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
     72
     73    var totalLength = input.length * 3 / 4;
     74    if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {
     75        totalLength--;
     76    }
     77    if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {
     78        totalLength--;
     79    }
     80    if (totalLength % 1 !== 0) {
     81        // totalLength is not an integer, the length does not match a valid
     82        // base64 content. That can happen if:
     83        // - the input is not a base64 content
     84        // - the input is *almost* a base64 content, with a extra chars at the
     85        //   beginning or at the end
     86        // - the input uses a base64 variant (base64url for example)
     87        throw new Error("Invalid base64 input, bad content length.");
     88    }
     89    var output;
     90    if (support.uint8array) {
     91        output = new Uint8Array(totalLength|0);
     92    } else {
     93        output = new Array(totalLength|0);
     94    }
     95
     96    while (i < input.length) {
     97
     98        enc1 = _keyStr.indexOf(input.charAt(i++));
     99        enc2 = _keyStr.indexOf(input.charAt(i++));
     100        enc3 = _keyStr.indexOf(input.charAt(i++));
     101        enc4 = _keyStr.indexOf(input.charAt(i++));
     102
     103        chr1 = (enc1 << 2) | (enc2 >> 4);
     104        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
     105        chr3 = ((enc3 & 3) << 6) | enc4;
     106
     107        output[resultIndex++] = chr1;
     108
     109        if (enc3 !== 64) {
     110            output[resultIndex++] = chr2;
     111        }
     112        if (enc4 !== 64) {
     113            output[resultIndex++] = chr3;
     114        }
     115
     116    }
     117
     118    return output;
     119};
     120
     121},{"./support":30,"./utils":32}],2:[function(require,module,exports){
     122'use strict';
     123
     124var external = require("./external");
     125var DataWorker = require('./stream/DataWorker');
     126var DataLengthProbe = require('./stream/DataLengthProbe');
     127var Crc32Probe = require('./stream/Crc32Probe');
     128var DataLengthProbe = require('./stream/DataLengthProbe');
     129
     130/**
     131 * Represent a compressed object, with everything needed to decompress it.
     132 * @constructor
     133 * @param {number} compressedSize the size of the data compressed.
     134 * @param {number} uncompressedSize the size of the data after decompression.
     135 * @param {number} crc32 the crc32 of the decompressed file.
     136 * @param {object} compression the type of compression, see lib/compressions.js.
     137 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
     138 */
     139function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
     140    this.compressedSize = compressedSize;
     141    this.uncompressedSize = uncompressedSize;
     142    this.crc32 = crc32;
     143    this.compression = compression;
     144    this.compressedContent = data;
     145}
     146
     147CompressedObject.prototype = {
     148    /**
     149     * Create a worker to get the uncompressed content.
     150     * @return {GenericWorker} the worker.
     151     */
     152    getContentWorker : function () {
     153        var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
     154        .pipe(this.compression.uncompressWorker())
     155        .pipe(new DataLengthProbe("data_length"));
     156
     157        var that = this;
     158        worker.on("end", function () {
     159            if(this.streamInfo['data_length'] !== that.uncompressedSize) {
     160                throw new Error("Bug : uncompressed data size mismatch");
     161            }
     162        });
     163        return worker;
     164    },
     165    /**
     166     * Create a worker to get the compressed content.
     167     * @return {GenericWorker} the worker.
     168     */
     169    getCompressedWorker : function () {
     170        return new DataWorker(external.Promise.resolve(this.compressedContent))
     171        .withStreamInfo("compressedSize", this.compressedSize)
     172        .withStreamInfo("uncompressedSize", this.uncompressedSize)
     173        .withStreamInfo("crc32", this.crc32)
     174        .withStreamInfo("compression", this.compression)
     175        ;
     176    }
     177};
     178
     179/**
     180 * Chain the given worker with other workers to compress the content with the
     181 * given compresion.
     182 * @param {GenericWorker} uncompressedWorker the worker to pipe.
     183 * @param {Object} compression the compression object.
     184 * @param {Object} compressionOptions the options to use when compressing.
     185 * @return {GenericWorker} the new worker compressing the content.
     186 */
     187CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
     188    return uncompressedWorker
     189    .pipe(new Crc32Probe())
     190    .pipe(new DataLengthProbe("uncompressedSize"))
     191    .pipe(compression.compressWorker(compressionOptions))
     192    .pipe(new DataLengthProbe("compressedSize"))
     193    .withStreamInfo("compression", compression);
     194};
     195
     196module.exports = CompressedObject;
     197
     198},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){
     199'use strict';
     200
     201var GenericWorker = require("./stream/GenericWorker");
     202
     203exports.STORE = {
     204    magic: "\x00\x00",
     205    compressWorker : function (compressionOptions) {
     206        return new GenericWorker("STORE compression");
     207    },
     208    uncompressWorker : function () {
     209        return new GenericWorker("STORE decompression");
     210    }
     211};
     212exports.DEFLATE = require('./flate');
     213
     214},{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){
     215'use strict';
     216
     217var utils = require('./utils');
     218
     219/**
     220 * The following functions come from pako, from pako/lib/zlib/crc32.js
     221 * released under the MIT license, see pako https://github.com/nodeca/pako/
     222 */
     223
     224// Use ordinary array, since untyped makes no boost here
     225function makeTable() {
     226    var c, table = [];
     227
     228    for(var n =0; n < 256; n++){
     229        c = n;
     230        for(var k =0; k < 8; k++){
     231            c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
     232        }
     233        table[n] = c;
     234    }
     235
     236    return table;
     237}
     238
     239// Create table on load. Just 255 signed longs. Not a problem.
     240var crcTable = makeTable();
     241
     242
     243function crc32(crc, buf, len, pos) {
     244    var t = crcTable, end = pos + len;
     245
     246    crc = crc ^ (-1);
     247
     248    for (var i = pos; i < end; i++ ) {
     249        crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
     250    }
     251
     252    return (crc ^ (-1)); // >>> 0;
     253}
     254
     255// That's all for the pako functions.
     256
     257/**
     258 * Compute the crc32 of a string.
     259 * This is almost the same as the function crc32, but for strings. Using the
     260 * same function for the two use cases leads to horrible performances.
     261 * @param {Number} crc the starting value of the crc.
     262 * @param {String} str the string to use.
     263 * @param {Number} len the length of the string.
     264 * @param {Number} pos the starting position for the crc32 computation.
     265 * @return {Number} the computed crc32.
     266 */
     267function crc32str(crc, str, len, pos) {
     268    var t = crcTable, end = pos + len;
     269
     270    crc = crc ^ (-1);
     271
     272    for (var i = pos; i < end; i++ ) {
     273        crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
     274    }
     275
     276    return (crc ^ (-1)); // >>> 0;
     277}
     278
     279module.exports = function crc32wrapper(input, crc) {
     280    if (typeof input === "undefined" || !input.length) {
     281        return 0;
     282    }
     283
     284    var isArray = utils.getTypeOf(input) !== "string";
     285
     286    if(isArray) {
     287        return crc32(crc|0, input, input.length, 0);
     288    } else {
     289        return crc32str(crc|0, input, input.length, 0);
     290    }
     291};
     292
     293},{"./utils":32}],5:[function(require,module,exports){
     294'use strict';
     295exports.base64 = false;
     296exports.binary = false;
     297exports.dir = false;
     298exports.createFolders = true;
     299exports.date = null;
     300exports.compression = null;
     301exports.compressionOptions = null;
     302exports.comment = null;
     303exports.unixPermissions = null;
     304exports.dosPermissions = null;
     305
     306},{}],6:[function(require,module,exports){
     307/* global Promise */
     308'use strict';
     309
     310// load the global object first:
     311// - it should be better integrated in the system (unhandledRejection in node)
     312// - the environment may have a custom Promise implementation (see zone.js)
     313var ES6Promise = null;
     314if (typeof Promise !== "undefined") {
     315    ES6Promise = Promise;
     316} else {
     317    ES6Promise = require("lie");
     318}
     319
     320/**
     321 * Let the user use/change some implementations.
     322 */
     323module.exports = {
     324    Promise: ES6Promise
     325};
     326
     327},{"lie":58}],7:[function(require,module,exports){
     328'use strict';
     329var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
     330
     331var pako = require("pako");
     332var utils = require("./utils");
     333var GenericWorker = require("./stream/GenericWorker");
     334
     335var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
     336
     337exports.magic = "\x08\x00";
     338
     339/**
     340 * Create a worker that uses pako to inflate/deflate.
     341 * @constructor
     342 * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
     343 * @param {Object} options the options to use when (de)compressing.
     344 */
     345function FlateWorker(action, options) {
     346    GenericWorker.call(this, "FlateWorker/" + action);
     347
     348    this._pako = null;
     349    this._pakoAction = action;
     350    this._pakoOptions = options;
     351    // the `meta` object from the last chunk received
     352    // this allow this worker to pass around metadata
     353    this.meta = {};
     354}
     355
     356utils.inherits(FlateWorker, GenericWorker);
     357
     358/**
     359 * @see GenericWorker.processChunk
     360 */
     361FlateWorker.prototype.processChunk = function (chunk) {
     362    this.meta = chunk.meta;
     363    if (this._pako === null) {
     364        this._createPako();
     365    }
     366    this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
     367};
     368
     369/**
     370 * @see GenericWorker.flush
     371 */
     372FlateWorker.prototype.flush = function () {
     373    GenericWorker.prototype.flush.call(this);
     374    if (this._pako === null) {
     375        this._createPako();
     376    }
     377    this._pako.push([], true);
     378};
     379/**
     380 * @see GenericWorker.cleanUp
     381 */
     382FlateWorker.prototype.cleanUp = function () {
     383    GenericWorker.prototype.cleanUp.call(this);
     384    this._pako = null;
     385};
     386
     387/**
     388 * Create the _pako object.
     389 * TODO: lazy-loading this object isn't the best solution but it's the
     390 * quickest. The best solution is to lazy-load the worker list. See also the
     391 * issue #446.
     392 */
     393FlateWorker.prototype._createPako = function () {
     394    this._pako = new pako[this._pakoAction]({
     395        raw: true,
     396        level: this._pakoOptions.level || -1 // default compression
     397    });
     398    var self = this;
     399    this._pako.onData = function(data) {
     400        self.push({
     401            data : data,
     402            meta : self.meta
     403        });
     404    };
     405};
     406
     407exports.compressWorker = function (compressionOptions) {
     408    return new FlateWorker("Deflate", compressionOptions);
     409};
     410exports.uncompressWorker = function () {
     411    return new FlateWorker("Inflate", {});
     412};
     413
     414},{"./stream/GenericWorker":28,"./utils":32,"pako":59}],8:[function(require,module,exports){
     415'use strict';
     416
     417var utils = require('../utils');
     418var GenericWorker = require('../stream/GenericWorker');
     419var utf8 = require('../utf8');
     420var crc32 = require('../crc32');
     421var signature = require('../signature');
     422
     423/**
     424 * Transform an integer into a string in hexadecimal.
     425 * @private
     426 * @param {number} dec the number to convert.
     427 * @param {number} bytes the number of bytes to generate.
     428 * @returns {string} the result.
     429 */
     430var decToHex = function(dec, bytes) {
     431    var hex = "", i;
     432    for (i = 0; i < bytes; i++) {
     433        hex += String.fromCharCode(dec & 0xff);
     434        dec = dec >>> 8;
     435    }
     436    return hex;
     437};
     438
     439/**
     440 * Generate the UNIX part of the external file attributes.
     441 * @param {Object} unixPermissions the unix permissions or null.
     442 * @param {Boolean} isDir true if the entry is a directory, false otherwise.
     443 * @return {Number} a 32 bit integer.
     444 *
     445 * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
     446 *
     447 * TTTTsstrwxrwxrwx0000000000ADVSHR
     448 * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
     449 *     ^^^_________________________ setuid, setgid, sticky
     450 *        ^^^^^^^^^________________ permissions
     451 *                 ^^^^^^^^^^______ not used ?
     452 *                           ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
     453 */
     454var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
     455
     456    var result = unixPermissions;
     457    if (!unixPermissions) {
     458        // I can't use octal values in strict mode, hence the hexa.
     459        //  040775 => 0x41fd
     460        // 0100664 => 0x81b4
     461        result = isDir ? 0x41fd : 0x81b4;
     462    }
     463    return (result & 0xFFFF) << 16;
     464};
     465
     466/**
     467 * Generate the DOS part of the external file attributes.
     468 * @param {Object} dosPermissions the dos permissions or null.
     469 * @param {Boolean} isDir true if the entry is a directory, false otherwise.
     470 * @return {Number} a 32 bit integer.
     471 *
     472 * Bit 0     Read-Only
     473 * Bit 1     Hidden
     474 * Bit 2     System
     475 * Bit 3     Volume Label
     476 * Bit 4     Directory
     477 * Bit 5     Archive
     478 */
     479var generateDosExternalFileAttr = function (dosPermissions, isDir) {
     480
     481    // the dir flag is already set for compatibility
     482    return (dosPermissions || 0)  & 0x3F;
     483};
     484
     485/**
     486 * Generate the various parts used in the construction of the final zip file.
     487 * @param {Object} streamInfo the hash with informations about the compressed file.
     488 * @param {Boolean} streamedContent is the content streamed ?
     489 * @param {Boolean} streamingEnded is the stream finished ?
     490 * @param {number} offset the current offset from the start of the zip file.
     491 * @param {String} platform let's pretend we are this platform (change platform dependents fields)
     492 * @param {Function} encodeFileName the function to encode the file name / comment.
     493 * @return {Object} the zip parts.
     494 */
     495var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
     496    var file = streamInfo['file'],
     497    compression = streamInfo['compression'],
     498    useCustomEncoding = encodeFileName !== utf8.utf8encode,
     499    encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
     500    utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
     501    comment = file.comment,
     502    encodedComment = utils.transformTo("string", encodeFileName(comment)),
     503    utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
     504    useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
     505    useUTF8ForComment = utfEncodedComment.length !== comment.length,
     506    dosTime,
     507    dosDate,
     508    extraFields = "",
     509    unicodePathExtraField = "",
     510    unicodeCommentExtraField = "",
     511    dir = file.dir,
     512    date = file.date;
     513
     514
     515    var dataInfo = {
     516        crc32 : 0,
     517        compressedSize : 0,
     518        uncompressedSize : 0
     519    };
     520
     521    // if the content is streamed, the sizes/crc32 are only available AFTER
     522    // the end of the stream.
     523    if (!streamedContent || streamingEnded) {
     524        dataInfo.crc32 = streamInfo['crc32'];
     525        dataInfo.compressedSize = streamInfo['compressedSize'];
     526        dataInfo.uncompressedSize = streamInfo['uncompressedSize'];
     527    }
     528
     529    var bitflag = 0;
     530    if (streamedContent) {
     531        // Bit 3: the sizes/crc32 are set to zero in the local header.
     532        // The correct values are put in the data descriptor immediately
     533        // following the compressed data.
     534        bitflag |= 0x0008;
     535    }
     536    if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
     537        // Bit 11: Language encoding flag (EFS).
     538        bitflag |= 0x0800;
     539    }
     540
     541
     542    var extFileAttr = 0;
     543    var versionMadeBy = 0;
     544    if (dir) {
     545        // dos or unix, we set the dos dir flag
     546        extFileAttr |= 0x00010;
     547    }
     548    if(platform === "UNIX") {
     549        versionMadeBy = 0x031E; // UNIX, version 3.0
     550        extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
     551    } else { // DOS or other, fallback to DOS
     552        versionMadeBy = 0x0014; // DOS, version 2.0
     553        extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
     554    }
     555
     556    // date
     557    // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
     558    // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
     559    // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
     560
     561    dosTime = date.getUTCHours();
     562    dosTime = dosTime << 6;
     563    dosTime = dosTime | date.getUTCMinutes();
     564    dosTime = dosTime << 5;
     565    dosTime = dosTime | date.getUTCSeconds() / 2;
     566
     567    dosDate = date.getUTCFullYear() - 1980;
     568    dosDate = dosDate << 4;
     569    dosDate = dosDate | (date.getUTCMonth() + 1);
     570    dosDate = dosDate << 5;
     571    dosDate = dosDate | date.getUTCDate();
     572
     573    if (useUTF8ForFileName) {
     574        // set the unicode path extra field. unzip needs at least one extra
     575        // field to correctly handle unicode path, so using the path is as good
     576        // as any other information. This could improve the situation with
     577        // other archive managers too.
     578        // This field is usually used without the utf8 flag, with a non
     579        // unicode path in the header (winrar, winzip). This helps (a bit)
     580        // with the messy Windows' default compressed folders feature but
     581        // breaks on p7zip which doesn't seek the unicode path extra field.
     582        // So for now, UTF-8 everywhere !
     583        unicodePathExtraField =
     584            // Version
     585            decToHex(1, 1) +
     586            // NameCRC32
     587            decToHex(crc32(encodedFileName), 4) +
     588            // UnicodeName
     589            utfEncodedFileName;
     590
     591        extraFields +=
     592            // Info-ZIP Unicode Path Extra Field
     593            "\x75\x70" +
     594            // size
     595            decToHex(unicodePathExtraField.length, 2) +
     596            // content
     597            unicodePathExtraField;
     598    }
     599
     600    if(useUTF8ForComment) {
     601
     602        unicodeCommentExtraField =
     603            // Version
     604            decToHex(1, 1) +
     605            // CommentCRC32
     606            decToHex(crc32(encodedComment), 4) +
     607            // UnicodeName
     608            utfEncodedComment;
     609
     610        extraFields +=
     611            // Info-ZIP Unicode Path Extra Field
     612            "\x75\x63" +
     613            // size
     614            decToHex(unicodeCommentExtraField.length, 2) +
     615            // content
     616            unicodeCommentExtraField;
     617    }
     618
     619    var header = "";
     620
     621    // version needed to extract
     622    header += "\x0A\x00";
     623    // general purpose bit flag
     624    header += decToHex(bitflag, 2);
     625    // compression method
     626    header += compression.magic;
     627    // last mod file time
     628    header += decToHex(dosTime, 2);
     629    // last mod file date
     630    header += decToHex(dosDate, 2);
     631    // crc-32
     632    header += decToHex(dataInfo.crc32, 4);
     633    // compressed size
     634    header += decToHex(dataInfo.compressedSize, 4);
     635    // uncompressed size
     636    header += decToHex(dataInfo.uncompressedSize, 4);
     637    // file name length
     638    header += decToHex(encodedFileName.length, 2);
     639    // extra field length
     640    header += decToHex(extraFields.length, 2);
     641
     642
     643    var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
     644
     645    var dirRecord = signature.CENTRAL_FILE_HEADER +
     646        // version made by (00: DOS)
     647        decToHex(versionMadeBy, 2) +
     648        // file header (common to file and central directory)
     649        header +
     650        // file comment length
     651        decToHex(encodedComment.length, 2) +
     652        // disk number start
     653        "\x00\x00" +
     654        // internal file attributes TODO
     655        "\x00\x00" +
     656        // external file attributes
     657        decToHex(extFileAttr, 4) +
     658        // relative offset of local header
     659        decToHex(offset, 4) +
     660        // file name
     661        encodedFileName +
     662        // extra field
     663        extraFields +
     664        // file comment
     665        encodedComment;
     666
     667    return {
     668        fileRecord: fileRecord,
     669        dirRecord: dirRecord
     670    };
     671};
     672
     673/**
     674 * Generate the EOCD record.
     675 * @param {Number} entriesCount the number of entries in the zip file.
     676 * @param {Number} centralDirLength the length (in bytes) of the central dir.
     677 * @param {Number} localDirLength the length (in bytes) of the local dir.
     678 * @param {String} comment the zip file comment as a binary string.
     679 * @param {Function} encodeFileName the function to encode the comment.
     680 * @return {String} the EOCD record.
     681 */
     682var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
     683    var dirEnd = "";
     684    var encodedComment = utils.transformTo("string", encodeFileName(comment));
     685
     686    // end of central dir signature
     687    dirEnd = signature.CENTRAL_DIRECTORY_END +
     688        // number of this disk
     689        "\x00\x00" +
     690        // number of the disk with the start of the central directory
     691        "\x00\x00" +
     692        // total number of entries in the central directory on this disk
     693        decToHex(entriesCount, 2) +
     694        // total number of entries in the central directory
     695        decToHex(entriesCount, 2) +
     696        // size of the central directory   4 bytes
     697        decToHex(centralDirLength, 4) +
     698        // offset of start of central directory with respect to the starting disk number
     699        decToHex(localDirLength, 4) +
     700        // .ZIP file comment length
     701        decToHex(encodedComment.length, 2) +
     702        // .ZIP file comment
     703        encodedComment;
     704
     705    return dirEnd;
     706};
     707
     708/**
     709 * Generate data descriptors for a file entry.
     710 * @param {Object} streamInfo the hash generated by a worker, containing informations
     711 * on the file entry.
     712 * @return {String} the data descriptors.
     713 */
     714var generateDataDescriptors = function (streamInfo) {
     715    var descriptor = "";
     716    descriptor = signature.DATA_DESCRIPTOR +
     717        // crc-32                          4 bytes
     718        decToHex(streamInfo['crc32'], 4) +
     719        // compressed size                 4 bytes
     720        decToHex(streamInfo['compressedSize'], 4) +
     721        // uncompressed size               4 bytes
     722        decToHex(streamInfo['uncompressedSize'], 4);
     723
     724    return descriptor;
     725};
     726
     727
     728/**
     729 * A worker to concatenate other workers to create a zip file.
     730 * @param {Boolean} streamFiles `true` to stream the content of the files,
     731 * `false` to accumulate it.
     732 * @param {String} comment the comment to use.
     733 * @param {String} platform the platform to use, "UNIX" or "DOS".
     734 * @param {Function} encodeFileName the function to encode file names and comments.
     735 */
     736function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
     737    GenericWorker.call(this, "ZipFileWorker");
     738    // The number of bytes written so far. This doesn't count accumulated chunks.
     739    this.bytesWritten = 0;
     740    // The comment of the zip file
     741    this.zipComment = comment;
     742    // The platform "generating" the zip file.
     743    this.zipPlatform = platform;
     744    // the function to encode file names and comments.
     745    this.encodeFileName = encodeFileName;
     746    // Should we stream the content of the files ?
     747    this.streamFiles = streamFiles;
     748    // If `streamFiles` is false, we will need to accumulate the content of the
     749    // files to calculate sizes / crc32 (and write them *before* the content).
     750    // This boolean indicates if we are accumulating chunks (it will change a lot
     751    // during the lifetime of this worker).
     752    this.accumulate = false;
     753    // The buffer receiving chunks when accumulating content.
     754    this.contentBuffer = [];
     755    // The list of generated directory records.
     756    this.dirRecords = [];
     757    // The offset (in bytes) from the beginning of the zip file for the current source.
     758    this.currentSourceOffset = 0;
     759    // The total number of entries in this zip file.
     760    this.entriesCount = 0;
     761    // the name of the file currently being added, null when handling the end of the zip file.
     762    // Used for the emited metadata.
     763    this.currentFile = null;
     764
     765
     766
     767    this._sources = [];
     768}
     769utils.inherits(ZipFileWorker, GenericWorker);
     770
     771/**
     772 * @see GenericWorker.push
     773 */
     774ZipFileWorker.prototype.push = function (chunk) {
     775
     776    var currentFilePercent = chunk.meta.percent || 0;
     777    var entriesCount = this.entriesCount;
     778    var remainingFiles = this._sources.length;
     779
     780    if(this.accumulate) {
     781        this.contentBuffer.push(chunk);
     782    } else {
     783        this.bytesWritten += chunk.data.length;
     784
     785        GenericWorker.prototype.push.call(this, {
     786            data : chunk.data,
     787            meta : {
     788                currentFile : this.currentFile,
     789                percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
     790            }
     791        });
     792    }
     793};
     794
     795/**
     796 * The worker started a new source (an other worker).
     797 * @param {Object} streamInfo the streamInfo object from the new source.
     798 */
     799ZipFileWorker.prototype.openedSource = function (streamInfo) {
     800    this.currentSourceOffset = this.bytesWritten;
     801    this.currentFile = streamInfo['file'].name;
     802
     803    var streamedContent = this.streamFiles && !streamInfo['file'].dir;
     804
     805    // don't stream folders (because they don't have any content)
     806    if(streamedContent) {
     807        var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
     808        this.push({
     809            data : record.fileRecord,
     810            meta : {percent:0}
     811        });
     812    } else {
     813        // we need to wait for the whole file before pushing anything
     814        this.accumulate = true;
     815    }
     816};
     817
     818/**
     819 * The worker finished a source (an other worker).
     820 * @param {Object} streamInfo the streamInfo object from the finished source.
     821 */
     822ZipFileWorker.prototype.closedSource = function (streamInfo) {
     823    this.accumulate = false;
     824    var streamedContent = this.streamFiles && !streamInfo['file'].dir;
     825    var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
     826
     827    this.dirRecords.push(record.dirRecord);
     828    if(streamedContent) {
     829        // after the streamed file, we put data descriptors
     830        this.push({
     831            data : generateDataDescriptors(streamInfo),
     832            meta : {percent:100}
     833        });
     834    } else {
     835        // the content wasn't streamed, we need to push everything now
     836        // first the file record, then the content
     837        this.push({
     838            data : record.fileRecord,
     839            meta : {percent:0}
     840        });
     841        while(this.contentBuffer.length) {
     842            this.push(this.contentBuffer.shift());
     843        }
     844    }
     845    this.currentFile = null;
     846};
     847
     848/**
     849 * @see GenericWorker.flush
     850 */
     851ZipFileWorker.prototype.flush = function () {
     852
     853    var localDirLength = this.bytesWritten;
     854    for(var i = 0; i < this.dirRecords.length; i++) {
     855        this.push({
     856            data : this.dirRecords[i],
     857            meta : {percent:100}
     858        });
     859    }
     860    var centralDirLength = this.bytesWritten - localDirLength;
     861
     862    var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
     863
     864    this.push({
     865        data : dirEnd,
     866        meta : {percent:100}
     867    });
     868};
     869
     870/**
     871 * Prepare the next source to be read.
     872 */
     873ZipFileWorker.prototype.prepareNextSource = function () {
     874    this.previous = this._sources.shift();
     875    this.openedSource(this.previous.streamInfo);
     876    if (this.isPaused) {
     877        this.previous.pause();
     878    } else {
     879        this.previous.resume();
     880    }
     881};
     882
     883/**
     884 * @see GenericWorker.registerPrevious
     885 */
     886ZipFileWorker.prototype.registerPrevious = function (previous) {
     887    this._sources.push(previous);
     888    var self = this;
     889
     890    previous.on('data', function (chunk) {
     891        self.processChunk(chunk);
     892    });
     893    previous.on('end', function () {
     894        self.closedSource(self.previous.streamInfo);
     895        if(self._sources.length) {
     896            self.prepareNextSource();
     897        } else {
     898            self.end();
     899        }
     900    });
     901    previous.on('error', function (e) {
     902        self.error(e);
     903    });
     904    return this;
     905};
     906
     907/**
     908 * @see GenericWorker.resume
     909 */
     910ZipFileWorker.prototype.resume = function () {
     911    if(!GenericWorker.prototype.resume.call(this)) {
     912        return false;
     913    }
     914
     915    if (!this.previous && this._sources.length) {
     916        this.prepareNextSource();
     917        return true;
     918    }
     919    if (!this.previous && !this._sources.length && !this.generatedError) {
     920        this.end();
     921        return true;
     922    }
     923};
     924
     925/**
     926 * @see GenericWorker.error
     927 */
     928ZipFileWorker.prototype.error = function (e) {
     929    var sources = this._sources;
     930    if(!GenericWorker.prototype.error.call(this, e)) {
     931        return false;
     932    }
     933    for(var i = 0; i < sources.length; i++) {
     934        try {
     935            sources[i].error(e);
     936        } catch(e) {
     937            // the `error` exploded, nothing to do
     938        }
     939    }
     940    return true;
     941};
     942
     943/**
     944 * @see GenericWorker.lock
     945 */
     946ZipFileWorker.prototype.lock = function () {
     947    GenericWorker.prototype.lock.call(this);
     948    var sources = this._sources;
     949    for(var i = 0; i < sources.length; i++) {
     950        sources[i].lock();
     951    }
     952};
     953
     954module.exports = ZipFileWorker;
     955
     956},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){
     957'use strict';
     958
     959var compressions = require('../compressions');
     960var ZipFileWorker = require('./ZipFileWorker');
     961
     962/**
     963 * Find the compression to use.
     964 * @param {String} fileCompression the compression defined at the file level, if any.
     965 * @param {String} zipCompression the compression defined at the load() level.
     966 * @return {Object} the compression object to use.
     967 */
     968var getCompression = function (fileCompression, zipCompression) {
     969
     970    var compressionName = fileCompression || zipCompression;
     971    var compression = compressions[compressionName];
     972    if (!compression) {
     973        throw new Error(compressionName + " is not a valid compression method !");
     974    }
     975    return compression;
     976};
     977
     978/**
     979 * Create a worker to generate a zip file.
     980 * @param {JSZip} zip the JSZip instance at the right root level.
     981 * @param {Object} options to generate the zip file.
     982 * @param {String} comment the comment to use.
     983 */
     984exports.generateWorker = function (zip, options, comment) {
     985
     986    var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
     987    var entriesCount = 0;
     988    try {
     989
     990        zip.forEach(function (relativePath, file) {
     991            entriesCount++;
     992            var compression = getCompression(file.options.compression, options.compression);
     993            var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
     994            var dir = file.dir, date = file.date;
     995
     996            file._compressWorker(compression, compressionOptions)
     997            .withStreamInfo("file", {
     998                name : relativePath,
     999                dir : dir,
     1000                date : date,
     1001                comment : file.comment || "",
     1002                unixPermissions : file.unixPermissions,
     1003                dosPermissions : file.dosPermissions
     1004            })
     1005            .pipe(zipFileWorker);
     1006        });
     1007        zipFileWorker.entriesCount = entriesCount;
     1008    } catch (e) {
     1009        zipFileWorker.error(e);
     1010    }
     1011
     1012    return zipFileWorker;
     1013};
     1014
     1015},{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){
     1016'use strict';
     1017
     1018/**
     1019 * Representation a of zip file in js
     1020 * @constructor
     1021 */
     1022function JSZip() {
     1023    // if this constructor is used without `new`, it adds `new` before itself:
     1024    if(!(this instanceof JSZip)) {
     1025        return new JSZip();
     1026    }
     1027
     1028    if(arguments.length) {
     1029        throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
     1030    }
     1031
     1032    // object containing the files :
     1033    // {
     1034    //   "folder/" : {...},
     1035    //   "folder/data.txt" : {...}
     1036    // }
     1037    this.files = {};
     1038
     1039    this.comment = null;
     1040
     1041    // Where we are in the hierarchy
     1042    this.root = "";
     1043    this.clone = function() {
     1044        var newObj = new JSZip();
     1045        for (var i in this) {
     1046            if (typeof this[i] !== "function") {
     1047                newObj[i] = this[i];
     1048            }
     1049        }
     1050        return newObj;
     1051    };
     1052}
     1053JSZip.prototype = require('./object');
     1054JSZip.prototype.loadAsync = require('./load');
     1055JSZip.support = require('./support');
     1056JSZip.defaults = require('./defaults');
     1057
     1058// TODO find a better way to handle this version,
     1059// a require('package.json').version doesn't work with webpack, see #327
     1060JSZip.version = "3.1.3";
     1061
     1062JSZip.loadAsync = function (content, options) {
     1063    return new JSZip().loadAsync(content, options);
     1064};
     1065
     1066JSZip.external = require("./external");
     1067module.exports = JSZip;
     1068
     1069},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){
     1070'use strict';
     1071var utils = require('./utils');
     1072var external = require("./external");
     1073var utf8 = require('./utf8');
     1074var utils = require('./utils');
     1075var ZipEntries = require('./zipEntries');
     1076var Crc32Probe = require('./stream/Crc32Probe');
     1077var nodejsUtils = require("./nodejsUtils");
     1078
     1079/**
     1080 * Check the CRC32 of an entry.
     1081 * @param {ZipEntry} zipEntry the zip entry to check.
     1082 * @return {Promise} the result.
     1083 */
     1084function checkEntryCRC32(zipEntry) {
     1085    return new external.Promise(function (resolve, reject) {
     1086        var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
     1087        worker.on("error", function (e) {
     1088            reject(e);
     1089        })
     1090        .on("end", function () {
     1091            if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
     1092                reject(new Error("Corrupted zip : CRC32 mismatch"));
     1093            } else {
     1094                resolve();
     1095            }
     1096        })
     1097        .resume();
     1098    });
     1099}
     1100
     1101module.exports = function(data, options) {
     1102    var zip = this;
     1103    options = utils.extend(options || {}, {
     1104        base64: false,
     1105        checkCRC32: false,
     1106        optimizedBinaryString: false,
     1107        createFolders: false,
     1108        decodeFileName: utf8.utf8decode
     1109    });
     1110
     1111    if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
     1112        return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
     1113    }
     1114
     1115    return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
     1116    .then(function(data) {
     1117        var zipEntries = new ZipEntries(options);
     1118        zipEntries.load(data);
     1119        return zipEntries;
     1120    }).then(function checkCRC32(zipEntries) {
     1121        var promises = [external.Promise.resolve(zipEntries)];
     1122        var files = zipEntries.files;
     1123        if (options.checkCRC32) {
     1124            for (var i = 0; i < files.length; i++) {
     1125                promises.push(checkEntryCRC32(files[i]));
     1126            }
     1127        }
     1128        return external.Promise.all(promises);
     1129    }).then(function addFiles(results) {
     1130        var zipEntries = results.shift();
     1131        var files = zipEntries.files;
     1132        for (var i = 0; i < files.length; i++) {
     1133            var input = files[i];
     1134            zip.file(input.fileNameStr, input.decompressed, {
     1135                binary: true,
     1136                optimizedBinaryString: true,
     1137                date: input.date,
     1138                dir: input.dir,
     1139                comment : input.fileCommentStr.length ? input.fileCommentStr : null,
     1140                unixPermissions : input.unixPermissions,
     1141                dosPermissions : input.dosPermissions,
     1142                createFolders: options.createFolders
     1143            });
     1144        }
     1145        if (zipEntries.zipComment.length) {
     1146            zip.comment = zipEntries.zipComment;
     1147        }
     1148
     1149        return zip;
     1150    });
     1151};
     1152
     1153},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){
     1154"use strict";
     1155
     1156var utils = require('../utils');
     1157var GenericWorker = require('../stream/GenericWorker');
     1158
     1159/**
     1160 * A worker that use a nodejs stream as source.
     1161 * @constructor
     1162 * @param {String} filename the name of the file entry for this stream.
     1163 * @param {Readable} stream the nodejs stream.
     1164 */
     1165function NodejsStreamInputAdapter(filename, stream) {
     1166    GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
     1167    this._upstreamEnded = false;
     1168    this._bindStream(stream);
     1169}
     1170
     1171utils.inherits(NodejsStreamInputAdapter, GenericWorker);
     1172
     1173/**
     1174 * Prepare the stream and bind the callbacks on it.
     1175 * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
     1176 * @param {Stream} stream the nodejs stream to use.
     1177 */
     1178NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
     1179    var self = this;
     1180    this._stream = stream;
     1181    stream.pause();
     1182    stream
     1183    .on("data", function (chunk) {
     1184        self.push({
     1185            data: chunk,
     1186            meta : {
     1187                percent : 0
     1188            }
     1189        });
     1190    })
     1191    .on("error", function (e) {
     1192        if(self.isPaused) {
     1193            this.generatedError = e;
     1194        } else {
     1195            self.error(e);
     1196        }
     1197    })
     1198    .on("end", function () {
     1199        if(self.isPaused) {
     1200            self._upstreamEnded = true;
     1201        } else {
     1202            self.end();
     1203        }
     1204    });
     1205};
     1206NodejsStreamInputAdapter.prototype.pause = function () {
     1207    if(!GenericWorker.prototype.pause.call(this)) {
     1208        return false;
     1209    }
     1210    this._stream.pause();
     1211    return true;
     1212};
     1213NodejsStreamInputAdapter.prototype.resume = function () {
     1214    if(!GenericWorker.prototype.resume.call(this)) {
     1215        return false;
     1216    }
     1217
     1218    if(this._upstreamEnded) {
     1219        this.end();
     1220    } else {
     1221        this._stream.resume();
     1222    }
     1223
     1224    return true;
     1225};
     1226
     1227module.exports = NodejsStreamInputAdapter;
     1228
     1229},{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){
     1230'use strict';
     1231
     1232var Readable = require('readable-stream').Readable;
     1233
     1234var utils = require('../utils');
     1235utils.inherits(NodejsStreamOutputAdapter, Readable);
     1236
     1237/**
     1238* A nodejs stream using a worker as source.
     1239* @see the SourceWrapper in http://nodejs.org/api/stream.html
     1240* @constructor
     1241* @param {StreamHelper} helper the helper wrapping the worker
     1242* @param {Object} options the nodejs stream options
     1243* @param {Function} updateCb the update callback.
     1244*/
     1245function NodejsStreamOutputAdapter(helper, options, updateCb) {
     1246    Readable.call(this, options);
     1247    this._helper = helper;
     1248
     1249    var self = this;
     1250    helper.on("data", function (data, meta) {
     1251        if (!self.push(data)) {
     1252            self._helper.pause();
     1253        }
     1254        if(updateCb) {
     1255            updateCb(meta);
     1256        }
     1257    })
     1258    .on("error", function(e) {
     1259        self.emit('error', e);
     1260    })
     1261    .on("end", function () {
     1262        self.push(null);
     1263    });
     1264}
     1265
     1266
     1267NodejsStreamOutputAdapter.prototype._read = function() {
     1268    this._helper.resume();
     1269};
     1270
     1271module.exports = NodejsStreamOutputAdapter;
     1272
     1273},{"../utils":32,"readable-stream":16}],14:[function(require,module,exports){
     1274'use strict';
     1275
     1276module.exports = {
     1277    /**
     1278     * True if this is running in Nodejs, will be undefined in a browser.
     1279     * In a browser, browserify won't include this file and the whole module
     1280     * will be resolved an empty object.
     1281     */
     1282    isNode : typeof Buffer !== "undefined",
     1283    /**
     1284     * Create a new nodejs Buffer.
     1285     * @param {Object} data the data to pass to the constructor.
     1286     * @param {String} encoding the encoding to use.
     1287     * @return {Buffer} a new Buffer.
     1288     */
     1289    newBuffer : function(data, encoding){
     1290        return new Buffer(data, encoding);
     1291    },
     1292    /**
     1293     * Find out if an object is a Buffer.
     1294     * @param {Object} b the object to test.
     1295     * @return {Boolean} true if the object is a Buffer, false otherwise.
     1296     */
     1297    isBuffer : function(b){
     1298        return Buffer.isBuffer(b);
     1299    },
     1300
     1301    isStream : function (obj) {
     1302        return obj &&
     1303            typeof obj.on === "function" &&
     1304            typeof obj.pause === "function" &&
     1305            typeof obj.resume === "function";
     1306    }
     1307};
     1308
     1309},{}],15:[function(require,module,exports){
     1310'use strict';
     1311var utf8 = require('./utf8');
     1312var utils = require('./utils');
     1313var GenericWorker = require('./stream/GenericWorker');
     1314var StreamHelper = require('./stream/StreamHelper');
     1315var defaults = require('./defaults');
     1316var CompressedObject = require('./compressedObject');
     1317var ZipObject = require('./zipObject');
     1318var generate = require("./generate");
     1319var nodejsUtils = require("./nodejsUtils");
     1320var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
     1321
     1322
     1323/**
     1324 * Add a file in the current folder.
     1325 * @private
     1326 * @param {string} name the name of the file
     1327 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
     1328 * @param {Object} originalOptions the options of the file
     1329 * @return {Object} the new file.
     1330 */
     1331var fileAdd = function(name, data, originalOptions) {
     1332    // be sure sub folders exist
     1333    var dataType = utils.getTypeOf(data),
     1334        parent;
     1335
     1336
     1337    /*
     1338     * Correct options.
     1339     */
     1340
     1341    var o = utils.extend(originalOptions || {}, defaults);
     1342    o.date = o.date || new Date();
     1343    if (o.compression !== null) {
     1344        o.compression = o.compression.toUpperCase();
     1345    }
     1346
     1347    if (typeof o.unixPermissions === "string") {
     1348        o.unixPermissions = parseInt(o.unixPermissions, 8);
     1349    }
     1350
     1351    // UNX_IFDIR  0040000 see zipinfo.c
     1352    if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
     1353        o.dir = true;
     1354    }
     1355    // Bit 4    Directory
     1356    if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
     1357        o.dir = true;
     1358    }
     1359
     1360    if (o.dir) {
     1361        name = forceTrailingSlash(name);
     1362    }
     1363    if (o.createFolders && (parent = parentFolder(name))) {
     1364        folderAdd.call(this, parent, true);
     1365    }
     1366
     1367    var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
     1368    if (!originalOptions || typeof originalOptions.binary === "undefined") {
     1369        o.binary = !isUnicodeString;
     1370    }
     1371
     1372
     1373    var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
     1374
     1375    if (isCompressedEmpty || o.dir || !data || data.length === 0) {
     1376        o.base64 = false;
     1377        o.binary = true;
     1378        data = "";
     1379        o.compression = "STORE";
     1380        dataType = "string";
     1381    }
     1382
     1383    /*
     1384     * Convert content to fit.
     1385     */
     1386
     1387    var zipObjectContent = null;
     1388    if (data instanceof CompressedObject || data instanceof GenericWorker) {
     1389        zipObjectContent = data;
     1390    } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
     1391        zipObjectContent = new NodejsStreamInputAdapter(name, data);
     1392    } else {
     1393        zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
     1394    }
     1395
     1396    var object = new ZipObject(name, zipObjectContent, o);
     1397    this.files[name] = object;
     1398    /*
     1399    TODO: we can't throw an exception because we have async promises
     1400    (we can have a promise of a Date() for example) but returning a
     1401    promise is useless because file(name, data) returns the JSZip
     1402    object for chaining. Should we break that to allow the user
     1403    to catch the error ?
     1404
     1405    return external.Promise.resolve(zipObjectContent)
     1406    .then(function () {
     1407        return object;
     1408    });
     1409    */
     1410};
     1411
     1412/**
     1413 * Find the parent folder of the path.
     1414 * @private
     1415 * @param {string} path the path to use
     1416 * @return {string} the parent folder, or ""
     1417 */
     1418var parentFolder = function (path) {
     1419    if (path.slice(-1) === '/') {
     1420        path = path.substring(0, path.length - 1);
     1421    }
     1422    var lastSlash = path.lastIndexOf('/');
     1423    return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
     1424};
     1425
     1426/**
     1427 * Returns the path with a slash at the end.
     1428 * @private
     1429 * @param {String} path the path to check.
     1430 * @return {String} the path with a trailing slash.
     1431 */
     1432var forceTrailingSlash = function(path) {
     1433    // Check the name ends with a /
     1434    if (path.slice(-1) !== "/") {
     1435        path += "/"; // IE doesn't like substr(-1)
     1436    }
     1437    return path;
     1438};
     1439
     1440/**
     1441 * Add a (sub) folder in the current folder.
     1442 * @private
     1443 * @param {string} name the folder's name
     1444 * @param {boolean=} [createFolders] If true, automatically create sub
     1445 *  folders. Defaults to false.
     1446 * @return {Object} the new folder.
     1447 */
     1448var folderAdd = function(name, createFolders) {
     1449    createFolders = (typeof createFolders !== 'undefined') ? createFolders : defaults.createFolders;
     1450
     1451    name = forceTrailingSlash(name);
     1452
     1453    // Does this folder already exist?
     1454    if (!this.files[name]) {
     1455        fileAdd.call(this, name, null, {
     1456            dir: true,
     1457            createFolders: createFolders
     1458        });
     1459    }
     1460    return this.files[name];
     1461};
     1462
     1463/**
     1464* Cross-window, cross-Node-context regular expression detection
     1465* @param  {Object}  object Anything
     1466* @return {Boolean}        true if the object is a regular expression,
     1467* false otherwise
     1468*/
     1469function isRegExp(object) {
     1470    return Object.prototype.toString.call(object) === "[object RegExp]";
     1471}
     1472
     1473// return the actual prototype of JSZip
     1474var out = {
     1475    /**
     1476     * @see loadAsync
     1477     */
     1478    load: function() {
     1479        throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
     1480    },
     1481
     1482
     1483    /**
     1484     * Call a callback function for each entry at this folder level.
     1485     * @param {Function} cb the callback function:
     1486     * function (relativePath, file) {...}
     1487     * It takes 2 arguments : the relative path and the file.
     1488     */
     1489    forEach: function(cb) {
     1490        var filename, relativePath, file;
     1491        for (filename in this.files) {
     1492            if (!this.files.hasOwnProperty(filename)) {
     1493                continue;
     1494            }
     1495            file = this.files[filename];
     1496            relativePath = filename.slice(this.root.length, filename.length);
     1497            if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
     1498                cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
     1499            }
     1500        }
     1501    },
     1502
     1503    /**
     1504     * Filter nested files/folders with the specified function.
     1505     * @param {Function} search the predicate to use :
     1506     * function (relativePath, file) {...}
     1507     * It takes 2 arguments : the relative path and the file.
     1508     * @return {Array} An array of matching elements.
     1509     */
     1510    filter: function(search) {
     1511        var result = [];
     1512        this.forEach(function (relativePath, entry) {
     1513            if (search(relativePath, entry)) { // the file matches the function
     1514                result.push(entry);
     1515            }
     1516
     1517        });
     1518        return result;
     1519    },
     1520
     1521    /**
     1522     * Add a file to the zip file, or search a file.
     1523     * @param   {string|RegExp} name The name of the file to add (if data is defined),
     1524     * the name of the file to find (if no data) or a regex to match files.
     1525     * @param   {String|ArrayBuffer|Uint8Array|Buffer} data  The file data, either raw or base64 encoded
     1526     * @param   {Object} o     File options
     1527     * @return  {JSZip|Object|Array} this JSZip object (when adding a file),
     1528     * a file (when searching by string) or an array of files (when searching by regex).
     1529     */
     1530    file: function(name, data, o) {
     1531        if (arguments.length === 1) {
     1532            if (isRegExp(name)) {
     1533                var regexp = name;
     1534                return this.filter(function(relativePath, file) {
     1535                    return !file.dir && regexp.test(relativePath);
     1536                });
     1537            }
     1538            else { // text
     1539                var obj = this.files[this.root + name];
     1540                if (obj && !obj.dir) {
     1541                    return obj;
     1542                } else {
     1543                    return null;
     1544                }
     1545            }
     1546        }
     1547        else { // more than one argument : we have data !
     1548            name = this.root + name;
     1549            fileAdd.call(this, name, data, o);
     1550        }
     1551        return this;
     1552    },
     1553
     1554    /**
     1555     * Add a directory to the zip file, or search.
     1556     * @param   {String|RegExp} arg The name of the directory to add, or a regex to search folders.
     1557     * @return  {JSZip} an object with the new directory as the root, or an array containing matching folders.
     1558     */
     1559    folder: function(arg) {
     1560        if (!arg) {
     1561            return this;
     1562        }
     1563
     1564        if (isRegExp(arg)) {
     1565            return this.filter(function(relativePath, file) {
     1566                return file.dir && arg.test(relativePath);
     1567            });
     1568        }
     1569
     1570        // else, name is a new folder
     1571        var name = this.root + arg;
     1572        var newFolder = folderAdd.call(this, name);
     1573
     1574        // Allow chaining by returning a new object with this folder as the root
     1575        var ret = this.clone();
     1576        ret.root = newFolder.name;
     1577        return ret;
     1578    },
     1579
     1580    /**
     1581     * Delete a file, or a directory and all sub-files, from the zip
     1582     * @param {string} name the name of the file to delete
     1583     * @return {JSZip} this JSZip object
     1584     */
     1585    remove: function(name) {
     1586        name = this.root + name;
     1587        var file = this.files[name];
     1588        if (!file) {
     1589            // Look for any folders
     1590            if (name.slice(-1) !== "/") {
     1591                name += "/";
     1592            }
     1593            file = this.files[name];
     1594        }
     1595
     1596        if (file && !file.dir) {
     1597            // file
     1598            delete this.files[name];
     1599        } else {
     1600            // maybe a folder, delete recursively
     1601            var kids = this.filter(function(relativePath, file) {
     1602                return file.name.slice(0, name.length) === name;
     1603            });
     1604            for (var i = 0; i < kids.length; i++) {
     1605                delete this.files[kids[i].name];
     1606            }
     1607        }
     1608
     1609        return this;
     1610    },
     1611
     1612    /**
     1613     * Generate the complete zip file
     1614     * @param {Object} options the options to generate the zip file :
     1615     * - compression, "STORE" by default.
     1616     * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
     1617     * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
     1618     */
     1619    generate: function(options) {
     1620        throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
     1621    },
     1622
     1623    /**
     1624     * Generate the complete zip file as an internal stream.
     1625     * @param {Object} options the options to generate the zip file :
     1626     * - compression, "STORE" by default.
     1627     * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
     1628     * @return {StreamHelper} the streamed zip file.
     1629     */
     1630    generateInternalStream: function(options) {
     1631      var worker, opts = {};
     1632      try {
     1633          opts = utils.extend(options || {}, {
     1634              streamFiles: false,
     1635              compression: "STORE",
     1636              compressionOptions : null,
     1637              type: "",
     1638              platform: "DOS",
     1639              comment: null,
     1640              mimeType: 'application/zip',
     1641              encodeFileName: utf8.utf8encode
     1642          });
     1643
     1644          opts.type = opts.type.toLowerCase();
     1645          opts.compression = opts.compression.toUpperCase();
     1646
     1647          // "binarystring" is prefered but the internals use "string".
     1648          if(opts.type === "binarystring") {
     1649            opts.type = "string";
     1650          }
     1651
     1652          if (!opts.type) {
     1653            throw new Error("No output type specified.");
     1654          }
     1655
     1656          utils.checkSupport(opts.type);
     1657
     1658          // accept nodejs `process.platform`
     1659          if(
     1660              opts.platform === 'darwin' ||
     1661              opts.platform === 'freebsd' ||
     1662              opts.platform === 'linux' ||
     1663              opts.platform === 'sunos'
     1664          ) {
     1665              opts.platform = "UNIX";
     1666          }
     1667          if (opts.platform === 'win32') {
     1668              opts.platform = "DOS";
     1669          }
     1670
     1671          var comment = opts.comment || this.comment || "";
     1672          worker = generate.generateWorker(this, opts, comment);
     1673      } catch (e) {
     1674        worker = new GenericWorker("error");
     1675        worker.error(e);
     1676      }
     1677      return new StreamHelper(worker, opts.type || "string", opts.mimeType);
     1678    },
     1679    /**
     1680     * Generate the complete zip file asynchronously.
     1681     * @see generateInternalStream
     1682     */
     1683    generateAsync: function(options, onUpdate) {
     1684        return this.generateInternalStream(options).accumulate(onUpdate);
     1685    },
     1686    /**
     1687     * Generate the complete zip file asynchronously.
     1688     * @see generateInternalStream
     1689     */
     1690    generateNodeStream: function(options, onUpdate) {
     1691        options = options || {};
     1692        if (!options.type) {
     1693            options.type = "nodebuffer";
     1694        }
     1695        return this.generateInternalStream(options).toNodejsStream(onUpdate);
     1696    }
     1697};
     1698module.exports = out;
     1699
     1700},{"./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){
     1701/*
     1702 * This file is used by module bundlers (browserify/webpack/etc) when
     1703 * including a stream implementation. We use "readable-stream" to get a
     1704 * consistent behavior between nodejs versions but bundlers often have a shim
     1705 * for "stream". Using this shim greatly improve the compatibility and greatly
     1706 * reduce the final size of the bundle (only one stream implementation, not
     1707 * two).
     1708 */
     1709module.exports = require("stream");
     1710
     1711},{"stream":undefined}],17:[function(require,module,exports){
     1712'use strict';
     1713var DataReader = require('./DataReader');
     1714var utils = require('../utils');
     1715
     1716function ArrayReader(data) {
     1717    DataReader.call(this, data);
     1718        for(var i = 0; i < this.data.length; i++) {
     1719                data[i] = data[i] & 0xFF;
     1720        }
     1721}
     1722utils.inherits(ArrayReader, DataReader);
     1723/**
     1724 * @see DataReader.byteAt
     1725 */
     1726ArrayReader.prototype.byteAt = function(i) {
     1727    return this.data[this.zero + i];
     1728};
     1729/**
     1730 * @see DataReader.lastIndexOfSignature
     1731 */
     1732ArrayReader.prototype.lastIndexOfSignature = function(sig) {
     1733    var sig0 = sig.charCodeAt(0),
     1734        sig1 = sig.charCodeAt(1),
     1735        sig2 = sig.charCodeAt(2),
     1736        sig3 = sig.charCodeAt(3);
     1737    for (var i = this.length - 4; i >= 0; --i) {
     1738        if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
     1739            return i - this.zero;
     1740        }
     1741    }
     1742
     1743    return -1;
     1744};
     1745/**
     1746 * @see DataReader.readAndCheckSignature
     1747 */
     1748ArrayReader.prototype.readAndCheckSignature = function (sig) {
     1749    var sig0 = sig.charCodeAt(0),
     1750        sig1 = sig.charCodeAt(1),
     1751        sig2 = sig.charCodeAt(2),
     1752        sig3 = sig.charCodeAt(3),
     1753        data = this.readData(4);
     1754    return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
     1755};
     1756/**
     1757 * @see DataReader.readData
     1758 */
     1759ArrayReader.prototype.readData = function(size) {
     1760    this.checkOffset(size);
     1761    if(size === 0) {
     1762        return [];
     1763    }
     1764    var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
     1765    this.index += size;
     1766    return result;
     1767};
     1768module.exports = ArrayReader;
     1769
     1770},{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){
     1771'use strict';
     1772var utils = require('../utils');
     1773
     1774function DataReader(data) {
     1775    this.data = data; // type : see implementation
     1776    this.length = data.length;
     1777    this.index = 0;
     1778    this.zero = 0;
     1779}
     1780DataReader.prototype = {
     1781    /**
     1782     * Check that the offset will not go too far.
     1783     * @param {string} offset the additional offset to check.
     1784     * @throws {Error} an Error if the offset is out of bounds.
     1785     */
     1786    checkOffset: function(offset) {
     1787        this.checkIndex(this.index + offset);
     1788    },
     1789    /**
     1790     * Check that the specifed index will not be too far.
     1791     * @param {string} newIndex the index to check.
     1792     * @throws {Error} an Error if the index is out of bounds.
     1793     */
     1794    checkIndex: function(newIndex) {
     1795        if (this.length < this.zero + newIndex || newIndex < 0) {
     1796            throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
     1797        }
     1798    },
     1799    /**
     1800     * Change the index.
     1801     * @param {number} newIndex The new index.
     1802     * @throws {Error} if the new index is out of the data.
     1803     */
     1804    setIndex: function(newIndex) {
     1805        this.checkIndex(newIndex);
     1806        this.index = newIndex;
     1807    },
     1808    /**
     1809     * Skip the next n bytes.
     1810     * @param {number} n the number of bytes to skip.
     1811     * @throws {Error} if the new index is out of the data.
     1812     */
     1813    skip: function(n) {
     1814        this.setIndex(this.index + n);
     1815    },
     1816    /**
     1817     * Get the byte at the specified index.
     1818     * @param {number} i the index to use.
     1819     * @return {number} a byte.
     1820     */
     1821    byteAt: function(i) {
     1822        // see implementations
     1823    },
     1824    /**
     1825     * Get the next number with a given byte size.
     1826     * @param {number} size the number of bytes to read.
     1827     * @return {number} the corresponding number.
     1828     */
     1829    readInt: function(size) {
     1830        var result = 0,
     1831            i;
     1832        this.checkOffset(size);
     1833        for (i = this.index + size - 1; i >= this.index; i--) {
     1834            result = (result << 8) + this.byteAt(i);
     1835        }
     1836        this.index += size;
     1837        return result;
     1838    },
     1839    /**
     1840     * Get the next string with a given byte size.
     1841     * @param {number} size the number of bytes to read.
     1842     * @return {string} the corresponding string.
     1843     */
     1844    readString: function(size) {
     1845        return utils.transformTo("string", this.readData(size));
     1846    },
     1847    /**
     1848     * Get raw data without conversion, <size> bytes.
     1849     * @param {number} size the number of bytes to read.
     1850     * @return {Object} the raw data, implementation specific.
     1851     */
     1852    readData: function(size) {
     1853        // see implementations
     1854    },
     1855    /**
     1856     * Find the last occurence of a zip signature (4 bytes).
     1857     * @param {string} sig the signature to find.
     1858     * @return {number} the index of the last occurence, -1 if not found.
     1859     */
     1860    lastIndexOfSignature: function(sig) {
     1861        // see implementations
     1862    },
     1863    /**
     1864     * Read the signature (4 bytes) at the current position and compare it with sig.
     1865     * @param {string} sig the expected signature
     1866     * @return {boolean} true if the signature matches, false otherwise.
     1867     */
     1868    readAndCheckSignature: function(sig) {
     1869        // see implementations
     1870    },
     1871    /**
     1872     * Get the next date.
     1873     * @return {Date} the date.
     1874     */
     1875    readDate: function() {
     1876        var dostime = this.readInt(4);
     1877        return new Date(Date.UTC(
     1878        ((dostime >> 25) & 0x7f) + 1980, // year
     1879        ((dostime >> 21) & 0x0f) - 1, // month
     1880        (dostime >> 16) & 0x1f, // day
     1881        (dostime >> 11) & 0x1f, // hour
     1882        (dostime >> 5) & 0x3f, // minute
     1883        (dostime & 0x1f) << 1)); // second
     1884    }
     1885};
     1886module.exports = DataReader;
     1887
     1888},{"../utils":32}],19:[function(require,module,exports){
     1889'use strict';
     1890var Uint8ArrayReader = require('./Uint8ArrayReader');
     1891var utils = require('../utils');
     1892
     1893function NodeBufferReader(data) {
     1894    Uint8ArrayReader.call(this, data);
     1895}
     1896utils.inherits(NodeBufferReader, Uint8ArrayReader);
     1897
     1898/**
     1899 * @see DataReader.readData
     1900 */
     1901NodeBufferReader.prototype.readData = function(size) {
     1902    this.checkOffset(size);
     1903    var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
     1904    this.index += size;
     1905    return result;
     1906};
     1907module.exports = NodeBufferReader;
     1908
     1909},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){
     1910'use strict';
     1911var DataReader = require('./DataReader');
     1912var utils = require('../utils');
     1913
     1914function StringReader(data) {
     1915    DataReader.call(this, data);
     1916}
     1917utils.inherits(StringReader, DataReader);
     1918/**
     1919 * @see DataReader.byteAt
     1920 */
     1921StringReader.prototype.byteAt = function(i) {
     1922    return this.data.charCodeAt(this.zero + i);
     1923};
     1924/**
     1925 * @see DataReader.lastIndexOfSignature
     1926 */
     1927StringReader.prototype.lastIndexOfSignature = function(sig) {
     1928    return this.data.lastIndexOf(sig) - this.zero;
     1929};
     1930/**
     1931 * @see DataReader.readAndCheckSignature
     1932 */
     1933StringReader.prototype.readAndCheckSignature = function (sig) {
     1934    var data = this.readData(4);
     1935    return sig === data;
     1936};
     1937/**
     1938 * @see DataReader.readData
     1939 */
     1940StringReader.prototype.readData = function(size) {
     1941    this.checkOffset(size);
     1942    // this will work because the constructor applied the "& 0xff" mask.
     1943    var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
     1944    this.index += size;
     1945    return result;
     1946};
     1947module.exports = StringReader;
     1948
     1949},{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){
     1950'use strict';
     1951var ArrayReader = require('./ArrayReader');
     1952var utils = require('../utils');
     1953
     1954function Uint8ArrayReader(data) {
     1955    ArrayReader.call(this, data);
     1956}
     1957utils.inherits(Uint8ArrayReader, ArrayReader);
     1958/**
     1959 * @see DataReader.readData
     1960 */
     1961Uint8ArrayReader.prototype.readData = function(size) {
     1962    this.checkOffset(size);
     1963    if(size === 0) {
     1964        // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
     1965        return new Uint8Array(0);
     1966    }
     1967    var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
     1968    this.index += size;
     1969    return result;
     1970};
     1971module.exports = Uint8ArrayReader;
     1972
     1973},{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){
     1974'use strict';
     1975
     1976var utils = require('../utils');
     1977var support = require('../support');
     1978var ArrayReader = require('./ArrayReader');
     1979var StringReader = require('./StringReader');
     1980var NodeBufferReader = require('./NodeBufferReader');
     1981var Uint8ArrayReader = require('./Uint8ArrayReader');
     1982
     1983/**
     1984 * Create a reader adapted to the data.
     1985 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
     1986 * @return {DataReader} the data reader.
     1987 */
     1988module.exports = function (data) {
     1989    var type = utils.getTypeOf(data);
     1990    utils.checkSupport(type);
     1991    if (type === "string" && !support.uint8array) {
     1992        return new StringReader(data);
     1993    }
     1994    if (type === "nodebuffer") {
     1995        return new NodeBufferReader(data);
     1996    }
     1997    if (support.uint8array) {
     1998        return new Uint8ArrayReader(utils.transformTo("uint8array", data));
     1999    }
     2000    return new ArrayReader(utils.transformTo("array", data));
     2001};
     2002
     2003},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){
     2004'use strict';
     2005exports.LOCAL_FILE_HEADER = "PK\x03\x04";
     2006exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
     2007exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
     2008exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
     2009exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
     2010exports.DATA_DESCRIPTOR = "PK\x07\x08";
     2011
     2012},{}],24:[function(require,module,exports){
     2013'use strict';
     2014
     2015var GenericWorker = require('./GenericWorker');
     2016var utils = require('../utils');
     2017
     2018/**
     2019 * A worker which convert chunks to a specified type.
     2020 * @constructor
     2021 * @param {String} destType the destination type.
     2022 */
     2023function ConvertWorker(destType) {
     2024    GenericWorker.call(this, "ConvertWorker to " + destType);
     2025    this.destType = destType;
     2026}
     2027utils.inherits(ConvertWorker, GenericWorker);
     2028
     2029/**
     2030 * @see GenericWorker.processChunk
     2031 */
     2032ConvertWorker.prototype.processChunk = function (chunk) {
     2033    this.push({
     2034        data : utils.transformTo(this.destType, chunk.data),
     2035        meta : chunk.meta
     2036    });
     2037};
     2038module.exports = ConvertWorker;
     2039
     2040},{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){
     2041'use strict';
     2042
     2043var GenericWorker = require('./GenericWorker');
     2044var crc32 = require('../crc32');
     2045var utils = require('../utils');
     2046
     2047/**
     2048 * A worker which calculate the crc32 of the data flowing through.
     2049 * @constructor
     2050 */
     2051function Crc32Probe() {
     2052    GenericWorker.call(this, "Crc32Probe");
     2053    this.withStreamInfo("crc32", 0);
     2054}
     2055utils.inherits(Crc32Probe, GenericWorker);
     2056
     2057/**
     2058 * @see GenericWorker.processChunk
     2059 */
     2060Crc32Probe.prototype.processChunk = function (chunk) {
     2061    this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
     2062    this.push(chunk);
     2063};
     2064module.exports = Crc32Probe;
     2065
     2066},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){
     2067'use strict';
     2068
     2069var utils = require('../utils');
     2070var GenericWorker = require('./GenericWorker');
     2071
     2072/**
     2073 * A worker which calculate the total length of the data flowing through.
     2074 * @constructor
     2075 * @param {String} propName the name used to expose the length
     2076 */
     2077function DataLengthProbe(propName) {
     2078    GenericWorker.call(this, "DataLengthProbe for " + propName);
     2079    this.propName = propName;
     2080    this.withStreamInfo(propName, 0);
     2081}
     2082utils.inherits(DataLengthProbe, GenericWorker);
     2083
     2084/**
     2085 * @see GenericWorker.processChunk
     2086 */
     2087DataLengthProbe.prototype.processChunk = function (chunk) {
     2088    if(chunk) {
     2089        var length = this.streamInfo[this.propName] || 0;
     2090        this.streamInfo[this.propName] = length + chunk.data.length;
     2091    }
     2092    GenericWorker.prototype.processChunk.call(this, chunk);
     2093};
     2094module.exports = DataLengthProbe;
     2095
     2096
     2097},{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){
     2098'use strict';
     2099
     2100var utils = require('../utils');
     2101var GenericWorker = require('./GenericWorker');
     2102
     2103// the size of the generated chunks
     2104// TODO expose this as a public variable
     2105var DEFAULT_BLOCK_SIZE = 16 * 1024;
     2106
     2107/**
     2108 * A worker that reads a content and emits chunks.
     2109 * @constructor
     2110 * @param {Promise} dataP the promise of the data to split
     2111 */
     2112function DataWorker(dataP) {
     2113    GenericWorker.call(this, "DataWorker");
     2114    var self = this;
     2115    this.dataIsReady = false;
     2116    this.index = 0;
     2117    this.max = 0;
     2118    this.data = null;
     2119    this.type = "";
     2120
     2121    this._tickScheduled = false;
     2122
     2123    dataP.then(function (data) {
     2124        self.dataIsReady = true;
     2125        self.data = data;
     2126        self.max = data && data.length || 0;
     2127        self.type = utils.getTypeOf(data);
     2128        if(!self.isPaused) {
     2129            self._tickAndRepeat();
     2130        }
     2131    }, function (e) {
     2132        self.error(e);
     2133    });
     2134}
     2135
     2136utils.inherits(DataWorker, GenericWorker);
     2137
     2138/**
     2139 * @see GenericWorker.cleanUp
     2140 */
     2141DataWorker.prototype.cleanUp = function () {
     2142    GenericWorker.prototype.cleanUp.call(this);
     2143    this.data = null;
     2144};
     2145
     2146/**
     2147 * @see GenericWorker.resume
     2148 */
     2149DataWorker.prototype.resume = function () {
     2150    if(!GenericWorker.prototype.resume.call(this)) {
     2151        return false;
     2152    }
     2153
     2154    if (!this._tickScheduled && this.dataIsReady) {
     2155        this._tickScheduled = true;
     2156        utils.delay(this._tickAndRepeat, [], this);
     2157    }
     2158    return true;
     2159};
     2160
     2161/**
     2162 * Trigger a tick a schedule an other call to this function.
     2163 */
     2164DataWorker.prototype._tickAndRepeat = function() {
     2165    this._tickScheduled = false;
     2166    if(this.isPaused || this.isFinished) {
     2167        return;
     2168    }
     2169    this._tick();
     2170    if(!this.isFinished) {
     2171        utils.delay(this._tickAndRepeat, [], this);
     2172        this._tickScheduled = true;
     2173    }
     2174};
     2175
     2176/**
     2177 * Read and push a chunk.
     2178 */
     2179DataWorker.prototype._tick = function() {
     2180
     2181    if(this.isPaused || this.isFinished) {
     2182        return false;
     2183    }
     2184
     2185    var size = DEFAULT_BLOCK_SIZE;
     2186    var data = null, nextIndex = Math.min(this.max, this.index + size);
     2187    if (this.index >= this.max) {
     2188        // EOF
     2189        return this.end();
     2190    } else {
     2191        switch(this.type) {
     2192            case "string":
     2193                data = this.data.substring(this.index, nextIndex);
     2194            break;
     2195            case "uint8array":
     2196                data = this.data.subarray(this.index, nextIndex);
     2197            break;
     2198            case "array":
     2199            case "nodebuffer":
     2200                data = this.data.slice(this.index, nextIndex);
     2201            break;
     2202        }
     2203        this.index = nextIndex;
     2204        return this.push({
     2205            data : data,
     2206            meta : {
     2207                percent : this.max ? this.index / this.max * 100 : 0
     2208            }
     2209        });
     2210    }
     2211};
     2212
     2213module.exports = DataWorker;
     2214
     2215},{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){
     2216'use strict';
     2217
     2218/**
     2219 * A worker that does nothing but passing chunks to the next one. This is like
     2220 * a nodejs stream but with some differences. On the good side :
     2221 * - it works on IE 6-9 without any issue / polyfill
     2222 * - it weights less than the full dependencies bundled with browserify
     2223 * - it forwards errors (no need to declare an error handler EVERYWHERE)
     2224 *
     2225 * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
     2226 * object containing anything (`percent` for example), see each worker for more
     2227 * details. The latter is the real data (String, Uint8Array, etc).
     2228 *
     2229 * @constructor
     2230 * @param {String} name the name of the stream (mainly used for debugging purposes)
     2231 */
     2232function GenericWorker(name) {
     2233    // the name of the worker
     2234    this.name = name || "default";
     2235    // an object containing metadata about the workers chain
     2236    this.streamInfo = {};
     2237    // an error which happened when the worker was paused
     2238    this.generatedError = null;
     2239    // an object containing metadata to be merged by this worker into the general metadata
     2240    this.extraStreamInfo = {};
     2241    // true if the stream is paused (and should not do anything), false otherwise
     2242    this.isPaused = true;
     2243    // true if the stream is finished (and should not do anything), false otherwise
     2244    this.isFinished = false;
     2245    // true if the stream is locked to prevent further structure updates (pipe), false otherwise
     2246    this.isLocked = false;
     2247    // the event listeners
     2248    this._listeners = {
     2249        'data':[],
     2250        'end':[],
     2251        'error':[]
     2252    };
     2253    // the previous worker, if any
     2254    this.previous = null;
     2255}
     2256
     2257GenericWorker.prototype = {
     2258    /**
     2259     * Push a chunk to the next workers.
     2260     * @param {Object} chunk the chunk to push
     2261     */
     2262    push : function (chunk) {
     2263        this.emit("data", chunk);
     2264    },
     2265    /**
     2266     * End the stream.
     2267     * @return {Boolean} true if this call ended the worker, false otherwise.
     2268     */
     2269    end : function () {
     2270        if (this.isFinished) {
     2271            return false;
     2272        }
     2273
     2274        this.flush();
     2275        try {
     2276            this.emit("end");
     2277            this.cleanUp();
     2278            this.isFinished = true;
     2279        } catch (e) {
     2280            this.emit("error", e);
     2281        }
     2282        return true;
     2283    },
     2284    /**
     2285     * End the stream with an error.
     2286     * @param {Error} e the error which caused the premature end.
     2287     * @return {Boolean} true if this call ended the worker with an error, false otherwise.
     2288     */
     2289    error : function (e) {
     2290        if (this.isFinished) {
     2291            return false;
     2292        }
     2293
     2294        if(this.isPaused) {
     2295            this.generatedError = e;
     2296        } else {
     2297            this.isFinished = true;
     2298
     2299            this.emit("error", e);
     2300
     2301            // in the workers chain exploded in the middle of the chain,
     2302            // the error event will go downward but we also need to notify
     2303            // workers upward that there has been an error.
     2304            if(this.previous) {
     2305                this.previous.error(e);
     2306            }
     2307
     2308            this.cleanUp();
     2309        }
     2310        return true;
     2311    },
     2312    /**
     2313     * Add a callback on an event.
     2314     * @param {String} name the name of the event (data, end, error)
     2315     * @param {Function} listener the function to call when the event is triggered
     2316     * @return {GenericWorker} the current object for chainability
     2317     */
     2318    on : function (name, listener) {
     2319        this._listeners[name].push(listener);
     2320        return this;
     2321    },
     2322    /**
     2323     * Clean any references when a worker is ending.
     2324     */
     2325    cleanUp : function () {
     2326        this.streamInfo = this.generatedError = this.extraStreamInfo = null;
     2327        this._listeners = [];
     2328    },
     2329    /**
     2330     * Trigger an event. This will call registered callback with the provided arg.
     2331     * @param {String} name the name of the event (data, end, error)
     2332     * @param {Object} arg the argument to call the callback with.
     2333     */
     2334    emit : function (name, arg) {
     2335        if (this._listeners[name]) {
     2336            for(var i = 0; i < this._listeners[name].length; i++) {
     2337                this._listeners[name][i].call(this, arg);
     2338            }
     2339        }
     2340    },
     2341    /**
     2342     * Chain a worker with an other.
     2343     * @param {Worker} next the worker receiving events from the current one.
     2344     * @return {worker} the next worker for chainability
     2345     */
     2346    pipe : function (next) {
     2347        return next.registerPrevious(this);
     2348    },
     2349    /**
     2350     * Same as `pipe` in the other direction.
     2351     * Using an API with `pipe(next)` is very easy.
     2352     * Implementing the API with the point of view of the next one registering
     2353     * a source is easier, see the ZipFileWorker.
     2354     * @param {Worker} previous the previous worker, sending events to this one
     2355     * @return {Worker} the current worker for chainability
     2356     */
     2357    registerPrevious : function (previous) {
     2358        if (this.isLocked) {
     2359            throw new Error("The stream '" + this + "' has already been used.");
     2360        }
     2361
     2362        // sharing the streamInfo...
     2363        this.streamInfo = previous.streamInfo;
     2364        // ... and adding our own bits
     2365        this.mergeStreamInfo();
     2366        this.previous =  previous;
     2367        var self = this;
     2368        previous.on('data', function (chunk) {
     2369            self.processChunk(chunk);
     2370        });
     2371        previous.on('end', function () {
     2372            self.end();
     2373        });
     2374        previous.on('error', function (e) {
     2375            self.error(e);
     2376        });
     2377        return this;
     2378    },
     2379    /**
     2380     * Pause the stream so it doesn't send events anymore.
     2381     * @return {Boolean} true if this call paused the worker, false otherwise.
     2382     */
     2383    pause : function () {
     2384        if(this.isPaused || this.isFinished) {
     2385            return false;
     2386        }
     2387        this.isPaused = true;
     2388
     2389        if(this.previous) {
     2390            this.previous.pause();
     2391        }
     2392        return true;
     2393    },
     2394    /**
     2395     * Resume a paused stream.
     2396     * @return {Boolean} true if this call resumed the worker, false otherwise.
     2397     */
     2398    resume : function () {
     2399        if(!this.isPaused || this.isFinished) {
     2400            return false;
     2401        }
     2402        this.isPaused = false;
     2403
     2404        // if true, the worker tried to resume but failed
     2405        var withError = false;
     2406        if(this.generatedError) {
     2407            this.error(this.generatedError);
     2408            withError = true;
     2409        }
     2410        if(this.previous) {
     2411            this.previous.resume();
     2412        }
     2413
     2414        return !withError;
     2415    },
     2416    /**
     2417     * Flush any remaining bytes as the stream is ending.
     2418     */
     2419    flush : function () {},
     2420    /**
     2421     * Process a chunk. This is usually the method overridden.
     2422     * @param {Object} chunk the chunk to process.
     2423     */
     2424    processChunk : function(chunk) {
     2425        this.push(chunk);
     2426    },
     2427    /**
     2428     * Add a key/value to be added in the workers chain streamInfo once activated.
     2429     * @param {String} key the key to use
     2430     * @param {Object} value the associated value
     2431     * @return {Worker} the current worker for chainability
     2432     */
     2433    withStreamInfo : function (key, value) {
     2434        this.extraStreamInfo[key] = value;
     2435        this.mergeStreamInfo();
     2436        return this;
     2437    },
     2438    /**
     2439     * Merge this worker's streamInfo into the chain's streamInfo.
     2440     */
     2441    mergeStreamInfo : function () {
     2442        for(var key in this.extraStreamInfo) {
     2443            if (!this.extraStreamInfo.hasOwnProperty(key)) {
     2444                continue;
     2445            }
     2446            this.streamInfo[key] = this.extraStreamInfo[key];
     2447        }
     2448    },
     2449
     2450    /**
     2451     * Lock the stream to prevent further updates on the workers chain.
     2452     * After calling this method, all calls to pipe will fail.
     2453     */
     2454    lock: function () {
     2455        if (this.isLocked) {
     2456            throw new Error("The stream '" + this + "' has already been used.");
     2457        }
     2458        this.isLocked = true;
     2459        if (this.previous) {
     2460            this.previous.lock();
     2461        }
     2462    },
     2463
     2464    /**
     2465     *
     2466     * Pretty print the workers chain.
     2467     */
     2468    toString : function () {
     2469        var me = "Worker " + this.name;
     2470        if (this.previous) {
     2471            return this.previous + " -> " + me;
     2472        } else {
     2473            return me;
     2474        }
     2475    }
     2476};
     2477
     2478module.exports = GenericWorker;
     2479
     2480},{}],29:[function(require,module,exports){
     2481'use strict';
     2482
     2483var utils = require('../utils');
     2484var ConvertWorker = require('./ConvertWorker');
     2485var GenericWorker = require('./GenericWorker');
     2486var base64 = require('../base64');
     2487var support = require("../support");
     2488var external = require("../external");
     2489
     2490var NodejsStreamOutputAdapter = null;
     2491if (support.nodestream) {
     2492    try {
     2493        NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter');
     2494    } catch(e) {}
     2495}
     2496
     2497/**
     2498 * Apply the final transformation of the data. If the user wants a Blob for
     2499 * example, it's easier to work with an U8intArray and finally do the
     2500 * ArrayBuffer/Blob conversion.
     2501 * @param {String} resultType the name of the final type
     2502 * @param {String} chunkType the type of the data in the given array.
     2503 * @param {Array} dataArray the array containing the data chunks to concatenate
     2504 * @param {String|Uint8Array|Buffer} content the content to transform
     2505 * @param {String} mimeType the mime type of the content, if applicable.
     2506 * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
     2507 */
     2508function transformZipOutput(resultType, chunkType, dataArray, mimeType) {
     2509    var content = null;
     2510    switch(resultType) {
     2511        case "blob" :
     2512            return utils.newBlob(dataArray, mimeType);
     2513        case "base64" :
     2514            content = concat(chunkType, dataArray);
     2515            return base64.encode(content);
     2516        default :
     2517            content = concat(chunkType, dataArray);
     2518            return utils.transformTo(resultType, content);
     2519    }
     2520}
     2521
     2522/**
     2523 * Concatenate an array of data of the given type.
     2524 * @param {String} type the type of the data in the given array.
     2525 * @param {Array} dataArray the array containing the data chunks to concatenate
     2526 * @return {String|Uint8Array|Buffer} the concatenated data
     2527 * @throws Error if the asked type is unsupported
     2528 */
     2529function concat (type, dataArray) {
     2530    var i, index = 0, res = null, totalLength = 0;
     2531    for(i = 0; i < dataArray.length; i++) {
     2532        totalLength += dataArray[i].length;
     2533    }
     2534    switch(type) {
     2535        case "string":
     2536            return dataArray.join("");
     2537          case "array":
     2538            return Array.prototype.concat.apply([], dataArray);
     2539        case "uint8array":
     2540            res = new Uint8Array(totalLength);
     2541            for(i = 0; i < dataArray.length; i++) {
     2542                res.set(dataArray[i], index);
     2543                index += dataArray[i].length;
     2544            }
     2545            return res;
     2546        case "nodebuffer":
     2547            return Buffer.concat(dataArray);
     2548        default:
     2549            throw new Error("concat : unsupported type '"  + type + "'");
     2550    }
     2551}
     2552
     2553/**
     2554 * Listen a StreamHelper, accumulate its content and concatenate it into a
     2555 * complete block.
     2556 * @param {StreamHelper} helper the helper to use.
     2557 * @param {Function} updateCallback a callback called on each update. Called
     2558 * with one arg :
     2559 * - the metadata linked to the update received.
     2560 * @return Promise the promise for the accumulation.
     2561 */
     2562function accumulate(helper, updateCallback) {
     2563    return new external.Promise(function (resolve, reject){
     2564        var dataArray = [];
     2565        var chunkType = helper._internalType,
     2566            resultType = helper._outputType,
     2567            mimeType = helper._mimeType;
     2568        helper
     2569        .on('data', function (data, meta) {
     2570            dataArray.push(data);
     2571            if(updateCallback) {
     2572                updateCallback(meta);
     2573            }
     2574        })
     2575        .on('error', function(err) {
     2576            dataArray = [];
     2577            reject(err);
     2578        })
     2579        .on('end', function (){
     2580            try {
     2581                var result = transformZipOutput(resultType, chunkType, dataArray, mimeType);
     2582                resolve(result);
     2583            } catch (e) {
     2584                reject(e);
     2585            }
     2586            dataArray = [];
     2587        })
     2588        .resume();
     2589    });
     2590}
     2591
     2592/**
     2593 * An helper to easily use workers outside of JSZip.
     2594 * @constructor
     2595 * @param {Worker} worker the worker to wrap
     2596 * @param {String} outputType the type of data expected by the use
     2597 * @param {String} mimeType the mime type of the content, if applicable.
     2598 */
     2599function StreamHelper(worker, outputType, mimeType) {
     2600    var internalType = outputType;
     2601    switch(outputType) {
     2602        case "blob":
     2603            internalType = "arraybuffer";
     2604        break;
     2605        case "arraybuffer":
     2606            internalType = "uint8array";
     2607        break;
     2608        case "base64":
     2609            internalType = "string";
     2610        break;
     2611    }
     2612
     2613    try {
     2614        // the type used internally
     2615        this._internalType = internalType;
     2616        // the type used to output results
     2617        this._outputType = outputType;
     2618        // the mime type
     2619        this._mimeType = mimeType;
     2620        utils.checkSupport(internalType);
     2621        this._worker = worker.pipe(new ConvertWorker(internalType));
     2622        // the last workers can be rewired without issues but we need to
     2623        // prevent any updates on previous workers.
     2624        worker.lock();
     2625    } catch(e) {
     2626        this._worker = new GenericWorker("error");
     2627        this._worker.error(e);
     2628    }
     2629}
     2630
     2631StreamHelper.prototype = {
     2632    /**
     2633     * Listen a StreamHelper, accumulate its content and concatenate it into a
     2634     * complete block.
     2635     * @param {Function} updateCb the update callback.
     2636     * @return Promise the promise for the accumulation.
     2637     */
     2638    accumulate : function (updateCb) {
     2639        return accumulate(this, updateCb);
     2640    },
     2641    /**
     2642     * Add a listener on an event triggered on a stream.
     2643     * @param {String} evt the name of the event
     2644     * @param {Function} fn the listener
     2645     * @return {StreamHelper} the current helper.
     2646     */
     2647    on : function (evt, fn) {
     2648        var self = this;
     2649
     2650        if(evt === "data") {
     2651            this._worker.on(evt, function (chunk) {
     2652                fn.call(self, chunk.data, chunk.meta);
     2653            });
     2654        } else {
     2655            this._worker.on(evt, function () {
     2656                utils.delay(fn, arguments, self);
     2657            });
     2658        }
     2659        return this;
     2660    },
     2661    /**
     2662     * Resume the flow of chunks.
     2663     * @return {StreamHelper} the current helper.
     2664     */
     2665    resume : function () {
     2666        utils.delay(this._worker.resume, [], this._worker);
     2667        return this;
     2668    },
     2669    /**
     2670     * Pause the flow of chunks.
     2671     * @return {StreamHelper} the current helper.
     2672     */
     2673    pause : function () {
     2674        this._worker.pause();
     2675        return this;
     2676    },
     2677    /**
     2678     * Return a nodejs stream for this helper.
     2679     * @param {Function} updateCb the update callback.
     2680     * @return {NodejsStreamOutputAdapter} the nodejs stream.
     2681     */
     2682    toNodejsStream : function (updateCb) {
     2683        utils.checkSupport("nodestream");
     2684        if (this._outputType !== "nodebuffer") {
     2685            // an object stream containing blob/arraybuffer/uint8array/string
     2686            // is strange and I don't know if it would be useful.
     2687            // I you find this comment and have a good usecase, please open a
     2688            // bug report !
     2689            throw new Error(this._outputType + " is not supported by this method");
     2690        }
     2691
     2692        return new NodejsStreamOutputAdapter(this, {
     2693            objectMode : this._outputType !== "nodebuffer"
     2694        }, updateCb);
     2695    }
     2696};
     2697
     2698
     2699module.exports = StreamHelper;
     2700
     2701},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){
     2702'use strict';
     2703
     2704exports.base64 = true;
     2705exports.array = true;
     2706exports.string = true;
     2707exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
     2708exports.nodebuffer = typeof Buffer !== "undefined";
     2709// contains true if JSZip can read/generate Uint8Array, false otherwise.
     2710exports.uint8array = typeof Uint8Array !== "undefined";
     2711
     2712if (typeof ArrayBuffer === "undefined") {
     2713    exports.blob = false;
     2714}
     2715else {
     2716    var buffer = new ArrayBuffer(0);
     2717    try {
     2718        exports.blob = new Blob([buffer], {
     2719            type: "application/zip"
     2720        }).size === 0;
     2721    }
     2722    catch (e) {
     2723        try {
     2724            var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
     2725            var builder = new Builder();
     2726            builder.append(buffer);
     2727            exports.blob = builder.getBlob('application/zip').size === 0;
     2728        }
     2729        catch (e) {
     2730            exports.blob = false;
     2731        }
     2732    }
     2733}
     2734
     2735try {
     2736    exports.nodestream = !!require('readable-stream').Readable;
     2737} catch(e) {
     2738    exports.nodestream = false;
     2739}
     2740
     2741},{"readable-stream":16}],31:[function(require,module,exports){
     2742'use strict';
     2743
     2744var utils = require('./utils');
     2745var support = require('./support');
     2746var nodejsUtils = require('./nodejsUtils');
     2747var GenericWorker = require('./stream/GenericWorker');
     2748
     2749/**
     2750 * The following functions come from pako, from pako/lib/utils/strings
     2751 * released under the MIT license, see pako https://github.com/nodeca/pako/
     2752 */
     2753
     2754// Table with utf8 lengths (calculated by first byte of sequence)
     2755// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
     2756// because max possible codepoint is 0x10ffff
     2757var _utf8len = new Array(256);
     2758for (var i=0; i<256; i++) {
     2759  _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
     2760}
     2761_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
     2762
     2763// convert string to array (typed, when possible)
     2764var string2buf = function (str) {
     2765    var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
     2766
     2767    // count binary size
     2768    for (m_pos = 0; m_pos < str_len; m_pos++) {
     2769        c = str.charCodeAt(m_pos);
     2770        if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
     2771            c2 = str.charCodeAt(m_pos+1);
     2772            if ((c2 & 0xfc00) === 0xdc00) {
     2773                c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
     2774                m_pos++;
     2775            }
     2776        }
     2777        buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
     2778    }
     2779
     2780    // allocate buffer
     2781    if (support.uint8array) {
     2782        buf = new Uint8Array(buf_len);
     2783    } else {
     2784        buf = new Array(buf_len);
     2785    }
     2786
     2787    // convert
     2788    for (i=0, m_pos = 0; i < buf_len; m_pos++) {
     2789        c = str.charCodeAt(m_pos);
     2790        if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
     2791            c2 = str.charCodeAt(m_pos+1);
     2792            if ((c2 & 0xfc00) === 0xdc00) {
     2793                c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
     2794                m_pos++;
     2795            }
     2796        }
     2797        if (c < 0x80) {
     2798            /* one byte */
     2799            buf[i++] = c;
     2800        } else if (c < 0x800) {
     2801            /* two bytes */
     2802            buf[i++] = 0xC0 | (c >>> 6);
     2803            buf[i++] = 0x80 | (c & 0x3f);
     2804        } else if (c < 0x10000) {
     2805            /* three bytes */
     2806            buf[i++] = 0xE0 | (c >>> 12);
     2807            buf[i++] = 0x80 | (c >>> 6 & 0x3f);
     2808            buf[i++] = 0x80 | (c & 0x3f);
     2809        } else {
     2810            /* four bytes */
     2811            buf[i++] = 0xf0 | (c >>> 18);
     2812            buf[i++] = 0x80 | (c >>> 12 & 0x3f);
     2813            buf[i++] = 0x80 | (c >>> 6 & 0x3f);
     2814            buf[i++] = 0x80 | (c & 0x3f);
     2815        }
     2816    }
     2817
     2818    return buf;
     2819};
     2820
     2821// Calculate max possible position in utf8 buffer,
     2822// that will not break sequence. If that's not possible
     2823// - (very small limits) return max size as is.
     2824//
     2825// buf[] - utf8 bytes array
     2826// max   - length limit (mandatory);
     2827var utf8border = function(buf, max) {
     2828    var pos;
     2829
     2830    max = max || buf.length;
     2831    if (max > buf.length) { max = buf.length; }
     2832
     2833    // go back from last position, until start of sequence found
     2834    pos = max-1;
     2835    while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
     2836
     2837    // Fuckup - very small and broken sequence,
     2838    // return max, because we should return something anyway.
     2839    if (pos < 0) { return max; }
     2840
     2841    // If we came to start of buffer - that means vuffer is too small,
     2842    // return max too.
     2843    if (pos === 0) { return max; }
     2844
     2845    return (pos + _utf8len[buf[pos]] > max) ? pos : max;
     2846};
     2847
     2848// convert array to string
     2849var buf2string = function (buf) {
     2850    var str, i, out, c, c_len;
     2851    var len = buf.length;
     2852
     2853    // Reserve max possible length (2 words per char)
     2854    // NB: by unknown reasons, Array is significantly faster for
     2855    //     String.fromCharCode.apply than Uint16Array.
     2856    var utf16buf = new Array(len*2);
     2857
     2858    for (out=0, i=0; i<len;) {
     2859        c = buf[i++];
     2860        // quick process ascii
     2861        if (c < 0x80) { utf16buf[out++] = c; continue; }
     2862
     2863        c_len = _utf8len[c];
     2864        // skip 5 & 6 byte codes
     2865        if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
     2866
     2867        // apply mask on first byte
     2868        c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
     2869        // join the rest
     2870        while (c_len > 1 && i < len) {
     2871            c = (c << 6) | (buf[i++] & 0x3f);
     2872            c_len--;
     2873        }
     2874
     2875        // terminated by end of string?
     2876        if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
     2877
     2878        if (c < 0x10000) {
     2879            utf16buf[out++] = c;
     2880        } else {
     2881            c -= 0x10000;
     2882            utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
     2883            utf16buf[out++] = 0xdc00 | (c & 0x3ff);
     2884        }
     2885    }
     2886
     2887    // shrinkBuf(utf16buf, out)
     2888    if (utf16buf.length !== out) {
     2889        if(utf16buf.subarray) {
     2890            utf16buf = utf16buf.subarray(0, out);
     2891        } else {
     2892            utf16buf.length = out;
     2893        }
     2894    }
     2895
     2896    // return String.fromCharCode.apply(null, utf16buf);
     2897    return utils.applyFromCharCode(utf16buf);
     2898};
     2899
     2900
     2901// That's all for the pako functions.
     2902
     2903
     2904/**
     2905 * Transform a javascript string into an array (typed if possible) of bytes,
     2906 * UTF-8 encoded.
     2907 * @param {String} str the string to encode
     2908 * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
     2909 */
     2910exports.utf8encode = function utf8encode(str) {
     2911    if (support.nodebuffer) {
     2912        return nodejsUtils.newBuffer(str, "utf-8");
     2913    }
     2914
     2915    return string2buf(str);
     2916};
     2917
     2918
     2919/**
     2920 * Transform a bytes array (or a representation) representing an UTF-8 encoded
     2921 * string into a javascript string.
     2922 * @param {Array|Uint8Array|Buffer} buf the data de decode
     2923 * @return {String} the decoded string.
     2924 */
     2925exports.utf8decode = function utf8decode(buf) {
     2926    if (support.nodebuffer) {
     2927        return utils.transformTo("nodebuffer", buf).toString("utf-8");
     2928    }
     2929
     2930    buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
     2931
     2932    return buf2string(buf);
     2933};
     2934
     2935/**
     2936 * A worker to decode utf8 encoded binary chunks into string chunks.
     2937 * @constructor
     2938 */
     2939function Utf8DecodeWorker() {
     2940    GenericWorker.call(this, "utf-8 decode");
     2941    // the last bytes if a chunk didn't end with a complete codepoint.
     2942    this.leftOver = null;
     2943}
     2944utils.inherits(Utf8DecodeWorker, GenericWorker);
     2945
     2946/**
     2947 * @see GenericWorker.processChunk
     2948 */
     2949Utf8DecodeWorker.prototype.processChunk = function (chunk) {
     2950
     2951    var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
     2952
     2953    // 1st step, re-use what's left of the previous chunk
     2954    if (this.leftOver && this.leftOver.length) {
     2955        if(support.uint8array) {
     2956            var previousData = data;
     2957            data = new Uint8Array(previousData.length + this.leftOver.length);
     2958            data.set(this.leftOver, 0);
     2959            data.set(previousData, this.leftOver.length);
     2960        } else {
     2961            data = this.leftOver.concat(data);
     2962        }
     2963        this.leftOver = null;
     2964    }
     2965
     2966    var nextBoundary = utf8border(data);
     2967    var usableData = data;
     2968    if (nextBoundary !== data.length) {
     2969        if (support.uint8array) {
     2970            usableData = data.subarray(0, nextBoundary);
     2971            this.leftOver = data.subarray(nextBoundary, data.length);
     2972        } else {
     2973            usableData = data.slice(0, nextBoundary);
     2974            this.leftOver = data.slice(nextBoundary, data.length);
     2975        }
     2976    }
     2977
     2978    this.push({
     2979        data : exports.utf8decode(usableData),
     2980        meta : chunk.meta
     2981    });
     2982};
     2983
     2984/**
     2985 * @see GenericWorker.flush
     2986 */
     2987Utf8DecodeWorker.prototype.flush = function () {
     2988    if(this.leftOver && this.leftOver.length) {
     2989        this.push({
     2990            data : exports.utf8decode(this.leftOver),
     2991            meta : {}
     2992        });
     2993        this.leftOver = null;
     2994    }
     2995};
     2996exports.Utf8DecodeWorker = Utf8DecodeWorker;
     2997
     2998/**
     2999 * A worker to endcode string chunks into utf8 encoded binary chunks.
     3000 * @constructor
     3001 */
     3002function Utf8EncodeWorker() {
     3003    GenericWorker.call(this, "utf-8 encode");
     3004}
     3005utils.inherits(Utf8EncodeWorker, GenericWorker);
     3006
     3007/**
     3008 * @see GenericWorker.processChunk
     3009 */
     3010Utf8EncodeWorker.prototype.processChunk = function (chunk) {
     3011    this.push({
     3012        data : exports.utf8encode(chunk.data),
     3013        meta : chunk.meta
     3014    });
     3015};
     3016exports.Utf8EncodeWorker = Utf8EncodeWorker;
     3017
     3018},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){
     3019'use strict';
     3020
     3021var support = require('./support');
     3022var base64 = require('./base64');
     3023var nodejsUtils = require('./nodejsUtils');
     3024var setImmediate = require('core-js/library/fn/set-immediate');
     3025var external = require("./external");
     3026
     3027
     3028/**
     3029 * Convert a string that pass as a "binary string": it should represent a byte
     3030 * array but may have > 255 char codes. Be sure to take only the first byte
     3031 * and returns the byte array.
     3032 * @param {String} str the string to transform.
     3033 * @return {Array|Uint8Array} the string in a binary format.
     3034 */
     3035function string2binary(str) {
     3036    var result = null;
     3037    if (support.uint8array) {
     3038      result = new Uint8Array(str.length);
     3039    } else {
     3040      result = new Array(str.length);
     3041    }
     3042    return stringToArrayLike(str, result);
     3043}
     3044
     3045/**
     3046 * Create a new blob with the given content and the given type.
     3047 * @param {Array[String|ArrayBuffer]} parts the content to put in the blob. DO NOT use
     3048 * an Uint8Array because the stock browser of android 4 won't accept it (it
     3049 * will be silently converted to a string, "[object Uint8Array]").
     3050 * @param {String} type the mime type of the blob.
     3051 * @return {Blob} the created blob.
     3052 */
     3053exports.newBlob = function(parts, type) {
     3054    exports.checkSupport("blob");
     3055
     3056    try {
     3057        // Blob constructor
     3058        return new Blob(parts, {
     3059            type: type
     3060        });
     3061    }
     3062    catch (e) {
     3063
     3064        try {
     3065            // deprecated, browser only, old way
     3066            var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
     3067            var builder = new Builder();
     3068            for (var i = 0; i < parts.length; i++) {
     3069                builder.append(parts[i]);
     3070            }
     3071            return builder.getBlob(type);
     3072        }
     3073        catch (e) {
     3074
     3075            // well, fuck ?!
     3076            throw new Error("Bug : can't construct the Blob.");
     3077        }
     3078    }
     3079
     3080
     3081};
     3082/**
     3083 * The identity function.
     3084 * @param {Object} input the input.
     3085 * @return {Object} the same input.
     3086 */
     3087function identity(input) {
     3088    return input;
     3089}
     3090
     3091/**
     3092 * Fill in an array with a string.
     3093 * @param {String} str the string to use.
     3094 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
     3095 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
     3096 */
     3097function stringToArrayLike(str, array) {
     3098    for (var i = 0; i < str.length; ++i) {
     3099        array[i] = str.charCodeAt(i) & 0xFF;
     3100    }
     3101    return array;
     3102}
     3103
     3104/**
     3105 * An helper for the function arrayLikeToString.
     3106 * This contains static informations and functions that
     3107 * can be optimized by the browser JIT compiler.
     3108 */
     3109var arrayToStringHelper = {
     3110    /**
     3111     * Transform an array of int into a string, chunk by chunk.
     3112     * See the performances notes on arrayLikeToString.
     3113     * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
     3114     * @param {String} type the type of the array.
     3115     * @param {Integer} chunk the chunk size.
     3116     * @return {String} the resulting string.
     3117     * @throws Error if the chunk is too big for the stack.
     3118     */
     3119    stringifyByChunk: function(array, type, chunk) {
     3120        var result = [], k = 0, len = array.length;
     3121        // shortcut
     3122        if (len <= chunk) {
     3123            return String.fromCharCode.apply(null, array);
     3124        }
     3125        while (k < len) {
     3126            if (type === "array" || type === "nodebuffer") {
     3127                result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
     3128            }
     3129            else {
     3130                result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
     3131            }
     3132            k += chunk;
     3133        }
     3134        return result.join("");
     3135    },
     3136    /**
     3137     * Call String.fromCharCode on every item in the array.
     3138     * This is the naive implementation, which generate A LOT of intermediate string.
     3139     * This should be used when everything else fail.
     3140     * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
     3141     * @return {String} the result.
     3142     */
     3143    stringifyByChar: function(array){
     3144        var resultStr = "";
     3145        for(var i = 0; i < array.length; i++) {
     3146            resultStr += String.fromCharCode(array[i]);
     3147        }
     3148        return resultStr;
     3149    },
     3150    applyCanBeUsed : {
     3151        /**
     3152         * true if the browser accepts to use String.fromCharCode on Uint8Array
     3153         */
     3154        uint8array : (function () {
     3155            try {
     3156                return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
     3157            } catch (e) {
     3158                return false;
     3159            }
     3160        })(),
     3161        /**
     3162         * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
     3163         */
     3164        nodebuffer : (function () {
     3165            try {
     3166                return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.newBuffer(1)).length === 1;
     3167            } catch (e) {
     3168                return false;
     3169            }
     3170        })()
     3171    }
     3172};
     3173
     3174/**
     3175 * Transform an array-like object to a string.
     3176 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
     3177 * @return {String} the result.
     3178 */
     3179function arrayLikeToString(array) {
     3180    // Performances notes :
     3181    // --------------------
     3182    // String.fromCharCode.apply(null, array) is the fastest, see
     3183    // see http://jsperf.com/converting-a-uint8array-to-a-string/2
     3184    // but the stack is limited (and we can get huge arrays !).
     3185    //
     3186    // result += String.fromCharCode(array[i]); generate too many strings !
     3187    //
     3188    // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
     3189    // TODO : we now have workers that split the work. Do we still need that ?
     3190    var chunk = 65536,
     3191        type = exports.getTypeOf(array),
     3192        canUseApply = true;
     3193    if (type === "uint8array") {
     3194        canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
     3195    } else if (type === "nodebuffer") {
     3196        canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
     3197    }
     3198
     3199    if (canUseApply) {
     3200        while (chunk > 1) {
     3201            try {
     3202                return arrayToStringHelper.stringifyByChunk(array, type, chunk);
     3203            } catch (e) {
     3204                chunk = Math.floor(chunk / 2);
     3205            }
     3206        }
     3207    }
     3208
     3209    // no apply or chunk error : slow and painful algorithm
     3210    // default browser on android 4.*
     3211    return arrayToStringHelper.stringifyByChar(array);
     3212}
     3213
     3214exports.applyFromCharCode = arrayLikeToString;
     3215
     3216
     3217/**
     3218 * Copy the data from an array-like to an other array-like.
     3219 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
     3220 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
     3221 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
     3222 */
     3223function arrayLikeToArrayLike(arrayFrom, arrayTo) {
     3224    for (var i = 0; i < arrayFrom.length; i++) {
     3225        arrayTo[i] = arrayFrom[i];
     3226    }
     3227    return arrayTo;
     3228}
     3229
     3230// a matrix containing functions to transform everything into everything.
     3231var transform = {};
     3232
     3233// string to ?
     3234transform["string"] = {
     3235    "string": identity,
     3236    "array": function(input) {
     3237        return stringToArrayLike(input, new Array(input.length));
     3238    },
     3239    "arraybuffer": function(input) {
     3240        return transform["string"]["uint8array"](input).buffer;
     3241    },
     3242    "uint8array": function(input) {
     3243        return stringToArrayLike(input, new Uint8Array(input.length));
     3244    },
     3245    "nodebuffer": function(input) {
     3246        return stringToArrayLike(input, nodejsUtils.newBuffer(input.length));
     3247    }
     3248};
     3249
     3250// array to ?
     3251transform["array"] = {
     3252    "string": arrayLikeToString,
     3253    "array": identity,
     3254    "arraybuffer": function(input) {
     3255        return (new Uint8Array(input)).buffer;
     3256    },
     3257    "uint8array": function(input) {
     3258        return new Uint8Array(input);
     3259    },
     3260    "nodebuffer": function(input) {
     3261        return nodejsUtils.newBuffer(input);
     3262    }
     3263};
     3264
     3265// arraybuffer to ?
     3266transform["arraybuffer"] = {
     3267    "string": function(input) {
     3268        return arrayLikeToString(new Uint8Array(input));
     3269    },
     3270    "array": function(input) {
     3271        return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
     3272    },
     3273    "arraybuffer": identity,
     3274    "uint8array": function(input) {
     3275        return new Uint8Array(input);
     3276    },
     3277    "nodebuffer": function(input) {
     3278        return nodejsUtils.newBuffer(new Uint8Array(input));
     3279    }
     3280};
     3281
     3282// uint8array to ?
     3283transform["uint8array"] = {
     3284    "string": arrayLikeToString,
     3285    "array": function(input) {
     3286        return arrayLikeToArrayLike(input, new Array(input.length));
     3287    },
     3288    "arraybuffer": function(input) {
     3289        // copy the uint8array: DO NOT propagate the original ArrayBuffer, it
     3290        // can be way larger (the whole zip file for example).
     3291        var copy = new Uint8Array(input.length);
     3292        if (input.length) {
     3293            copy.set(input, 0);
     3294        }
     3295        return copy.buffer;
     3296    },
     3297    "uint8array": identity,
     3298    "nodebuffer": function(input) {
     3299        return nodejsUtils.newBuffer(input);
     3300    }
     3301};
     3302
     3303// nodebuffer to ?
     3304transform["nodebuffer"] = {
     3305    "string": arrayLikeToString,
     3306    "array": function(input) {
     3307        return arrayLikeToArrayLike(input, new Array(input.length));
     3308    },
     3309    "arraybuffer": function(input) {
     3310        return transform["nodebuffer"]["uint8array"](input).buffer;
     3311    },
     3312    "uint8array": function(input) {
     3313        return arrayLikeToArrayLike(input, new Uint8Array(input.length));
     3314    },
     3315    "nodebuffer": identity
     3316};
     3317
     3318/**
     3319 * Transform an input into any type.
     3320 * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
     3321 * If no output type is specified, the unmodified input will be returned.
     3322 * @param {String} outputType the output type.
     3323 * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
     3324 * @throws {Error} an Error if the browser doesn't support the requested output type.
     3325 */
     3326exports.transformTo = function(outputType, input) {
     3327    if (!input) {
     3328        // undefined, null, etc
     3329        // an empty string won't harm.
     3330        input = "";
     3331    }
     3332    if (!outputType) {
     3333        return input;
     3334    }
     3335    exports.checkSupport(outputType);
     3336    var inputType = exports.getTypeOf(input);
     3337    var result = transform[inputType][outputType](input);
     3338    return result;
     3339};
     3340
     3341/**
     3342 * Return the type of the input.
     3343 * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
     3344 * @param {Object} input the input to identify.
     3345 * @return {String} the (lowercase) type of the input.
     3346 */
     3347exports.getTypeOf = function(input) {
     3348    if (typeof input === "string") {
     3349        return "string";
     3350    }
     3351    if (Object.prototype.toString.call(input) === "[object Array]") {
     3352        return "array";
     3353    }
     3354    if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
     3355        return "nodebuffer";
     3356    }
     3357    if (support.uint8array && input instanceof Uint8Array) {
     3358        return "uint8array";
     3359    }
     3360    if (support.arraybuffer && input instanceof ArrayBuffer) {
     3361        return "arraybuffer";
     3362    }
     3363};
     3364
     3365/**
     3366 * Throw an exception if the type is not supported.
     3367 * @param {String} type the type to check.
     3368 * @throws {Error} an Error if the browser doesn't support the requested type.
     3369 */
     3370exports.checkSupport = function(type) {
     3371    var supported = support[type.toLowerCase()];
     3372    if (!supported) {
     3373        throw new Error(type + " is not supported by this platform");
     3374    }
     3375};
     3376
     3377exports.MAX_VALUE_16BITS = 65535;
     3378exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
     3379
     3380/**
     3381 * Prettify a string read as binary.
     3382 * @param {string} str the string to prettify.
     3383 * @return {string} a pretty string.
     3384 */
     3385exports.pretty = function(str) {
     3386    var res = '',
     3387        code, i;
     3388    for (i = 0; i < (str || "").length; i++) {
     3389        code = str.charCodeAt(i);
     3390        res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
     3391    }
     3392    return res;
     3393};
     3394
     3395/**
     3396 * Defer the call of a function.
     3397 * @param {Function} callback the function to call asynchronously.
     3398 * @param {Array} args the arguments to give to the callback.
     3399 */
     3400exports.delay = function(callback, args, self) {
     3401    setImmediate(function () {
     3402        callback.apply(self || null, args || []);
     3403    });
     3404};
     3405
     3406/**
     3407 * Extends a prototype with an other, without calling a constructor with
     3408 * side effects. Inspired by nodejs' `utils.inherits`
     3409 * @param {Function} ctor the constructor to augment
     3410 * @param {Function} superCtor the parent constructor to use
     3411 */
     3412exports.inherits = function (ctor, superCtor) {
     3413    var Obj = function() {};
     3414    Obj.prototype = superCtor.prototype;
     3415    ctor.prototype = new Obj();
     3416};
     3417
     3418/**
     3419 * Merge the objects passed as parameters into a new one.
     3420 * @private
     3421 * @param {...Object} var_args All objects to merge.
     3422 * @return {Object} a new object with the data of the others.
     3423 */
     3424exports.extend = function() {
     3425    var result = {}, i, attr;
     3426    for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
     3427        for (attr in arguments[i]) {
     3428            if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
     3429                result[attr] = arguments[i][attr];
     3430            }
     3431        }
     3432    }
     3433    return result;
     3434};
     3435
     3436/**
     3437 * Transform arbitrary content into a Promise.
     3438 * @param {String} name a name for the content being processed.
     3439 * @param {Object} inputData the content to process.
     3440 * @param {Boolean} isBinary true if the content is not an unicode string
     3441 * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
     3442 * @param {Boolean} isBase64 true if the string content is encoded with base64.
     3443 * @return {Promise} a promise in a format usable by JSZip.
     3444 */
     3445exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
     3446
     3447    // if inputData is already a promise, this flatten it.
     3448    var promise = external.Promise.resolve(inputData).then(function(data) {
     3449       
     3450       
     3451        var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);
     3452
     3453        if (isBlob && typeof FileReader !== "undefined") {
     3454            return new external.Promise(function (resolve, reject) {
     3455                var reader = new FileReader();
     3456
     3457                reader.onload = function(e) {
     3458                    resolve(e.target.result);
     3459                };
     3460                reader.onerror = function(e) {
     3461                    reject(e.target.error);
     3462                };
     3463                reader.readAsArrayBuffer(data);
     3464            });
     3465        } else {
     3466            return data;
     3467        }
     3468    });
     3469
     3470    return promise.then(function(data) {
     3471        var dataType = exports.getTypeOf(data);
     3472
     3473        if (!dataType) {
     3474            return external.Promise.reject(
     3475                new Error("The data of '" + name + "' is in an unsupported format !")
     3476            );
     3477        }
     3478        // special case : it's way easier to work with Uint8Array than with ArrayBuffer
     3479        if (dataType === "arraybuffer") {
     3480            data = exports.transformTo("uint8array", data);
     3481        } else if (dataType === "string") {
     3482            if (isBase64) {
     3483                data = base64.decode(data);
     3484            }
     3485            else if (isBinary) {
     3486                // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
     3487                if (isOptimizedBinaryString !== true) {
     3488                    // this is a string, not in a base64 format.
     3489                    // Be sure that this is a correct "binary string"
     3490                    data = string2binary(data);
     3491                }
     3492            }
     3493        }
     3494        return data;
     3495    });
     3496};
     3497
     3498},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"core-js/library/fn/set-immediate":36}],33:[function(require,module,exports){
     3499'use strict';
     3500var readerFor = require('./reader/readerFor');
     3501var utils = require('./utils');
     3502var sig = require('./signature');
     3503var ZipEntry = require('./zipEntry');
     3504var utf8 = require('./utf8');
     3505var support = require('./support');
     3506//  class ZipEntries {{{
     3507/**
     3508 * All the entries in the zip file.
     3509 * @constructor
     3510 * @param {Object} loadOptions Options for loading the stream.
     3511 */
     3512function ZipEntries(loadOptions) {
     3513    this.files = [];
     3514    this.loadOptions = loadOptions;
     3515}
     3516ZipEntries.prototype = {
     3517    /**
     3518     * Check that the reader is on the speficied signature.
     3519     * @param {string} expectedSignature the expected signature.
     3520     * @throws {Error} if it is an other signature.
     3521     */
     3522    checkSignature: function(expectedSignature) {
     3523        if (!this.reader.readAndCheckSignature(expectedSignature)) {
     3524            this.reader.index -= 4;
     3525            var signature = this.reader.readString(4);
     3526            throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
     3527        }
     3528    },
     3529    /**
     3530     * Check if the given signature is at the given index.
     3531     * @param {number} askedIndex the index to check.
     3532     * @param {string} expectedSignature the signature to expect.
     3533     * @return {boolean} true if the signature is here, false otherwise.
     3534     */
     3535    isSignature: function(askedIndex, expectedSignature) {
     3536        var currentIndex = this.reader.index;
     3537        this.reader.setIndex(askedIndex);
     3538        var signature = this.reader.readString(4);
     3539        var result = signature === expectedSignature;
     3540        this.reader.setIndex(currentIndex);
     3541        return result;
     3542    },
     3543    /**
     3544     * Read the end of the central directory.
     3545     */
     3546    readBlockEndOfCentral: function() {
     3547        this.diskNumber = this.reader.readInt(2);
     3548        this.diskWithCentralDirStart = this.reader.readInt(2);
     3549        this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
     3550        this.centralDirRecords = this.reader.readInt(2);
     3551        this.centralDirSize = this.reader.readInt(4);
     3552        this.centralDirOffset = this.reader.readInt(4);
     3553
     3554        this.zipCommentLength = this.reader.readInt(2);
     3555        // warning : the encoding depends of the system locale
     3556        // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
     3557        // On a windows machine, this field is encoded with the localized windows code page.
     3558        var zipComment = this.reader.readData(this.zipCommentLength);
     3559        var decodeParamType = support.uint8array ? "uint8array" : "array";
     3560        // To get consistent behavior with the generation part, we will assume that
     3561        // this is utf8 encoded unless specified otherwise.
     3562        var decodeContent = utils.transformTo(decodeParamType, zipComment);
     3563        this.zipComment = this.loadOptions.decodeFileName(decodeContent);
     3564    },
     3565    /**
     3566     * Read the end of the Zip 64 central directory.
     3567     * Not merged with the method readEndOfCentral :
     3568     * The end of central can coexist with its Zip64 brother,
     3569     * I don't want to read the wrong number of bytes !
     3570     */
     3571    readBlockZip64EndOfCentral: function() {
     3572        this.zip64EndOfCentralSize = this.reader.readInt(8);
     3573        this.reader.skip(4);
     3574        // this.versionMadeBy = this.reader.readString(2);
     3575        // this.versionNeeded = this.reader.readInt(2);
     3576        this.diskNumber = this.reader.readInt(4);
     3577        this.diskWithCentralDirStart = this.reader.readInt(4);
     3578        this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
     3579        this.centralDirRecords = this.reader.readInt(8);
     3580        this.centralDirSize = this.reader.readInt(8);
     3581        this.centralDirOffset = this.reader.readInt(8);
     3582
     3583        this.zip64ExtensibleData = {};
     3584        var extraDataSize = this.zip64EndOfCentralSize - 44,
     3585            index = 0,
     3586            extraFieldId,
     3587            extraFieldLength,
     3588            extraFieldValue;
     3589        while (index < extraDataSize) {
     3590            extraFieldId = this.reader.readInt(2);
     3591            extraFieldLength = this.reader.readInt(4);
     3592            extraFieldValue = this.reader.readData(extraFieldLength);
     3593            this.zip64ExtensibleData[extraFieldId] = {
     3594                id: extraFieldId,
     3595                length: extraFieldLength,
     3596                value: extraFieldValue
     3597            };
     3598        }
     3599    },
     3600    /**
     3601     * Read the end of the Zip 64 central directory locator.
     3602     */
     3603    readBlockZip64EndOfCentralLocator: function() {
     3604        this.diskWithZip64CentralDirStart = this.reader.readInt(4);
     3605        this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
     3606        this.disksCount = this.reader.readInt(4);
     3607        if (this.disksCount > 1) {
     3608            throw new Error("Multi-volumes zip are not supported");
     3609        }
     3610    },
     3611    /**
     3612     * Read the local files, based on the offset read in the central part.
     3613     */
     3614    readLocalFiles: function() {
     3615        var i, file;
     3616        for (i = 0; i < this.files.length; i++) {
     3617            file = this.files[i];
     3618            this.reader.setIndex(file.localHeaderOffset);
     3619            this.checkSignature(sig.LOCAL_FILE_HEADER);
     3620            file.readLocalPart(this.reader);
     3621            file.handleUTF8();
     3622            file.processAttributes();
     3623        }
     3624    },
     3625    /**
     3626     * Read the central directory.
     3627     */
     3628    readCentralDir: function() {
     3629        var file;
     3630
     3631        this.reader.setIndex(this.centralDirOffset);
     3632        while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
     3633            file = new ZipEntry({
     3634                zip64: this.zip64
     3635            }, this.loadOptions);
     3636            file.readCentralPart(this.reader);
     3637            this.files.push(file);
     3638        }
     3639
     3640        if (this.centralDirRecords !== this.files.length) {
     3641            if (this.centralDirRecords !== 0 && this.files.length === 0) {
     3642                // We expected some records but couldn't find ANY.
     3643                // This is really suspicious, as if something went wrong.
     3644                throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
     3645            } else {
     3646                // We found some records but not all.
     3647                // Something is wrong but we got something for the user: no error here.
     3648                // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
     3649            }
     3650        }
     3651    },
     3652    /**
     3653     * Read the end of central directory.
     3654     */
     3655    readEndOfCentral: function() {
     3656        var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
     3657        if (offset < 0) {
     3658            // Check if the content is a truncated zip or complete garbage.
     3659            // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
     3660            // extractible zip for example) but it can give a good hint.
     3661            // If an ajax request was used without responseType, we will also
     3662            // get unreadable data.
     3663            var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
     3664
     3665            if (isGarbage) {
     3666                throw new Error("Can't find end of central directory : is this a zip file ? " +
     3667                                "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");
     3668            } else {
     3669                throw new Error("Corrupted zip: can't find end of central directory");
     3670            }
     3671
     3672        }
     3673        this.reader.setIndex(offset);
     3674        var endOfCentralDirOffset = offset;
     3675        this.checkSignature(sig.CENTRAL_DIRECTORY_END);
     3676        this.readBlockEndOfCentral();
     3677
     3678
     3679        /* extract from the zip spec :
     3680            4)  If one of the fields in the end of central directory
     3681                record is too small to hold required data, the field
     3682                should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
     3683                ZIP64 format record should be created.
     3684            5)  The end of central directory record and the
     3685                Zip64 end of central directory locator record must
     3686                reside on the same disk when splitting or spanning
     3687                an archive.
     3688         */
     3689        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) {
     3690            this.zip64 = true;
     3691
     3692            /*
     3693            Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
     3694            the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
     3695            all numbers as 64-bit double precision IEEE 754 floating point numbers.
     3696            So, we have 53bits for integers and bitwise operations treat everything as 32bits.
     3697            see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
     3698            and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
     3699            */
     3700
     3701            // should look for a zip64 EOCD locator
     3702            offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
     3703            if (offset < 0) {
     3704                throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
     3705            }
     3706            this.reader.setIndex(offset);
     3707            this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
     3708            this.readBlockZip64EndOfCentralLocator();
     3709
     3710            // now the zip64 EOCD record
     3711            if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
     3712                // console.warn("ZIP64 end of central directory not where expected.");
     3713                this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
     3714                if (this.relativeOffsetEndOfZip64CentralDir < 0) {
     3715                    throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
     3716                }
     3717            }
     3718            this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
     3719            this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
     3720            this.readBlockZip64EndOfCentral();
     3721        }
     3722
     3723        var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
     3724        if (this.zip64) {
     3725            expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
     3726            expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
     3727        }
     3728
     3729        var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
     3730
     3731        if (extraBytes > 0) {
     3732            // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
     3733            if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
     3734                // The offsets seem wrong, but we have something at the specified offset.
     3735                // So… we keep it.
     3736            } else {
     3737                // the offset is wrong, update the "zero" of the reader
     3738                // this happens if data has been prepended (crx files for example)
     3739                this.reader.zero = extraBytes;
     3740            }
     3741        } else if (extraBytes < 0) {
     3742            throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
     3743        }
     3744    },
     3745    prepareReader: function(data) {
     3746        this.reader = readerFor(data);
     3747    },
     3748    /**
     3749     * Read a zip file and create ZipEntries.
     3750     * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
     3751     */
     3752    load: function(data) {
     3753        this.prepareReader(data);
     3754        this.readEndOfCentral();
     3755        this.readCentralDir();
     3756        this.readLocalFiles();
     3757    }
     3758};
     3759// }}} end of ZipEntries
     3760module.exports = ZipEntries;
     3761
     3762},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utf8":31,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){
     3763'use strict';
     3764var readerFor = require('./reader/readerFor');
     3765var utils = require('./utils');
     3766var CompressedObject = require('./compressedObject');
     3767var crc32fn = require('./crc32');
     3768var utf8 = require('./utf8');
     3769var compressions = require('./compressions');
     3770var support = require('./support');
     3771
     3772var MADE_BY_DOS = 0x00;
     3773var MADE_BY_UNIX = 0x03;
     3774
     3775/**
     3776 * Find a compression registered in JSZip.
     3777 * @param {string} compressionMethod the method magic to find.
     3778 * @return {Object|null} the JSZip compression object, null if none found.
     3779 */
     3780var findCompression = function(compressionMethod) {
     3781    for (var method in compressions) {
     3782        if (!compressions.hasOwnProperty(method)) {
     3783            continue;
     3784        }
     3785        if (compressions[method].magic === compressionMethod) {
     3786            return compressions[method];
     3787        }
     3788    }
     3789    return null;
     3790};
     3791
     3792// class ZipEntry {{{
     3793/**
     3794 * An entry in the zip file.
     3795 * @constructor
     3796 * @param {Object} options Options of the current file.
     3797 * @param {Object} loadOptions Options for loading the stream.
     3798 */
     3799function ZipEntry(options, loadOptions) {
     3800    this.options = options;
     3801    this.loadOptions = loadOptions;
     3802}
     3803ZipEntry.prototype = {
     3804    /**
     3805     * say if the file is encrypted.
     3806     * @return {boolean} true if the file is encrypted, false otherwise.
     3807     */
     3808    isEncrypted: function() {
     3809        // bit 1 is set
     3810        return (this.bitFlag & 0x0001) === 0x0001;
     3811    },
     3812    /**
     3813     * say if the file has utf-8 filename/comment.
     3814     * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
     3815     */
     3816    useUTF8: function() {
     3817        // bit 11 is set
     3818        return (this.bitFlag & 0x0800) === 0x0800;
     3819    },
     3820    /**
     3821     * Read the local part of a zip file and add the info in this object.
     3822     * @param {DataReader} reader the reader to use.
     3823     */
     3824    readLocalPart: function(reader) {
     3825        var compression, localExtraFieldsLength;
     3826
     3827        // we already know everything from the central dir !
     3828        // If the central dir data are false, we are doomed.
     3829        // On the bright side, the local part is scary  : zip64, data descriptors, both, etc.
     3830        // The less data we get here, the more reliable this should be.
     3831        // Let's skip the whole header and dash to the data !
     3832        reader.skip(22);
     3833        // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
     3834        // Strangely, the filename here is OK.
     3835        // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
     3836        // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
     3837        // Search "unzip mismatching "local" filename continuing with "central" filename version" on
     3838        // the internet.
     3839        //
     3840        // I think I see the logic here : the central directory is used to display
     3841        // content and the local directory is used to extract the files. Mixing / and \
     3842        // may be used to display \ to windows users and use / when extracting the files.
     3843        // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
     3844        this.fileNameLength = reader.readInt(2);
     3845        localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
     3846        // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
     3847        this.fileName = reader.readData(this.fileNameLength);
     3848        reader.skip(localExtraFieldsLength);
     3849
     3850        if (this.compressedSize === -1 || this.uncompressedSize === -1) {
     3851            throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
     3852        }
     3853
     3854        compression = findCompression(this.compressionMethod);
     3855        if (compression === null) { // no compression found
     3856            throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
     3857        }
     3858        this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
     3859    },
     3860
     3861    /**
     3862     * Read the central part of a zip file and add the info in this object.
     3863     * @param {DataReader} reader the reader to use.
     3864     */
     3865    readCentralPart: function(reader) {
     3866        this.versionMadeBy = reader.readInt(2);
     3867        reader.skip(2);
     3868        // this.versionNeeded = reader.readInt(2);
     3869        this.bitFlag = reader.readInt(2);
     3870        this.compressionMethod = reader.readString(2);
     3871        this.date = reader.readDate();
     3872        this.crc32 = reader.readInt(4);
     3873        this.compressedSize = reader.readInt(4);
     3874        this.uncompressedSize = reader.readInt(4);
     3875        var fileNameLength = reader.readInt(2);
     3876        this.extraFieldsLength = reader.readInt(2);
     3877        this.fileCommentLength = reader.readInt(2);
     3878        this.diskNumberStart = reader.readInt(2);
     3879        this.internalFileAttributes = reader.readInt(2);
     3880        this.externalFileAttributes = reader.readInt(4);
     3881        this.localHeaderOffset = reader.readInt(4);
     3882
     3883        if (this.isEncrypted()) {
     3884            throw new Error("Encrypted zip are not supported");
     3885        }
     3886
     3887        // will be read in the local part, see the comments there
     3888        reader.skip(fileNameLength);
     3889        this.readExtraFields(reader);
     3890        this.parseZIP64ExtraField(reader);
     3891        this.fileComment = reader.readData(this.fileCommentLength);
     3892    },
     3893
     3894    /**
     3895     * Parse the external file attributes and get the unix/dos permissions.
     3896     */
     3897    processAttributes: function () {
     3898        this.unixPermissions = null;
     3899        this.dosPermissions = null;
     3900        var madeBy = this.versionMadeBy >> 8;
     3901
     3902        // Check if we have the DOS directory flag set.
     3903        // We look for it in the DOS and UNIX permissions
     3904        // but some unknown platform could set it as a compatibility flag.
     3905        this.dir = this.externalFileAttributes & 0x0010 ? true : false;
     3906
     3907        if(madeBy === MADE_BY_DOS) {
     3908            // first 6 bits (0 to 5)
     3909            this.dosPermissions = this.externalFileAttributes & 0x3F;
     3910        }
     3911
     3912        if(madeBy === MADE_BY_UNIX) {
     3913            this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
     3914            // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
     3915        }
     3916
     3917        // fail safe : if the name ends with a / it probably means a folder
     3918        if (!this.dir && this.fileNameStr.slice(-1) === '/') {
     3919            this.dir = true;
     3920        }
     3921    },
     3922
     3923    /**
     3924     * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
     3925     * @param {DataReader} reader the reader to use.
     3926     */
     3927    parseZIP64ExtraField: function(reader) {
     3928
     3929        if (!this.extraFields[0x0001]) {
     3930            return;
     3931        }
     3932
     3933        // should be something, preparing the extra reader
     3934        var extraReader = readerFor(this.extraFields[0x0001].value);
     3935
     3936        // I really hope that these 64bits integer can fit in 32 bits integer, because js
     3937        // won't let us have more.
     3938        if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
     3939            this.uncompressedSize = extraReader.readInt(8);
     3940        }
     3941        if (this.compressedSize === utils.MAX_VALUE_32BITS) {
     3942            this.compressedSize = extraReader.readInt(8);
     3943        }
     3944        if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
     3945            this.localHeaderOffset = extraReader.readInt(8);
     3946        }
     3947        if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
     3948            this.diskNumberStart = extraReader.readInt(4);
     3949        }
     3950    },
     3951    /**
     3952     * Read the central part of a zip file and add the info in this object.
     3953     * @param {DataReader} reader the reader to use.
     3954     */
     3955    readExtraFields: function(reader) {
     3956        var end = reader.index + this.extraFieldsLength,
     3957            extraFieldId,
     3958            extraFieldLength,
     3959            extraFieldValue;
     3960
     3961        if (!this.extraFields) {
     3962            this.extraFields = {};
     3963        }
     3964
     3965        while (reader.index < end) {
     3966            extraFieldId = reader.readInt(2);
     3967            extraFieldLength = reader.readInt(2);
     3968            extraFieldValue = reader.readData(extraFieldLength);
     3969
     3970            this.extraFields[extraFieldId] = {
     3971                id: extraFieldId,
     3972                length: extraFieldLength,
     3973                value: extraFieldValue
     3974            };
     3975        }
     3976    },
     3977    /**
     3978     * Apply an UTF8 transformation if needed.
     3979     */
     3980    handleUTF8: function() {
     3981        var decodeParamType = support.uint8array ? "uint8array" : "array";
     3982        if (this.useUTF8()) {
     3983            this.fileNameStr = utf8.utf8decode(this.fileName);
     3984            this.fileCommentStr = utf8.utf8decode(this.fileComment);
     3985        } else {
     3986            var upath = this.findExtraFieldUnicodePath();
     3987            if (upath !== null) {
     3988                this.fileNameStr = upath;
     3989            } else {
     3990                // ASCII text or unsupported code page
     3991                var fileNameByteArray =  utils.transformTo(decodeParamType, this.fileName);
     3992                this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
     3993            }
     3994
     3995            var ucomment = this.findExtraFieldUnicodeComment();
     3996            if (ucomment !== null) {
     3997                this.fileCommentStr = ucomment;
     3998            } else {
     3999                // ASCII text or unsupported code page
     4000                var commentByteArray =  utils.transformTo(decodeParamType, this.fileComment);
     4001                this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
     4002            }
     4003        }
     4004    },
     4005
     4006    /**
     4007     * Find the unicode path declared in the extra field, if any.
     4008     * @return {String} the unicode path, null otherwise.
     4009     */
     4010    findExtraFieldUnicodePath: function() {
     4011        var upathField = this.extraFields[0x7075];
     4012        if (upathField) {
     4013            var extraReader = readerFor(upathField.value);
     4014
     4015            // wrong version
     4016            if (extraReader.readInt(1) !== 1) {
     4017                return null;
     4018            }
     4019
     4020            // the crc of the filename changed, this field is out of date.
     4021            if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
     4022                return null;
     4023            }
     4024
     4025            return utf8.utf8decode(extraReader.readData(upathField.length - 5));
     4026        }
     4027        return null;
     4028    },
     4029
     4030    /**
     4031     * Find the unicode comment declared in the extra field, if any.
     4032     * @return {String} the unicode comment, null otherwise.
     4033     */
     4034    findExtraFieldUnicodeComment: function() {
     4035        var ucommentField = this.extraFields[0x6375];
     4036        if (ucommentField) {
     4037            var extraReader = readerFor(ucommentField.value);
     4038
     4039            // wrong version
     4040            if (extraReader.readInt(1) !== 1) {
     4041                return null;
     4042            }
     4043
     4044            // the crc of the comment changed, this field is out of date.
     4045            if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
     4046                return null;
     4047            }
     4048
     4049            return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
     4050        }
     4051        return null;
     4052    }
     4053};
     4054module.exports = ZipEntry;
     4055
     4056},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){
     4057'use strict';
     4058
     4059var StreamHelper = require('./stream/StreamHelper');
     4060var DataWorker = require('./stream/DataWorker');
     4061var utf8 = require('./utf8');
     4062var CompressedObject = require('./compressedObject');
     4063var GenericWorker = require('./stream/GenericWorker');
     4064
     4065/**
     4066 * A simple object representing a file in the zip file.
     4067 * @constructor
     4068 * @param {string} name the name of the file
     4069 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
     4070 * @param {Object} options the options of the file
     4071 */
     4072var ZipObject = function(name, data, options) {
     4073    this.name = name;
     4074    this.dir = options.dir;
     4075    this.date = options.date;
     4076    this.comment = options.comment;
     4077    this.unixPermissions = options.unixPermissions;
     4078    this.dosPermissions = options.dosPermissions;
     4079
     4080    this._data = data;
     4081    this._dataBinary = options.binary;
     4082    // keep only the compression
     4083    this.options = {
     4084        compression : options.compression,
     4085        compressionOptions : options.compressionOptions
     4086    };
     4087};
     4088
     4089ZipObject.prototype = {
     4090    /**
     4091     * Create an internal stream for the content of this object.
     4092     * @param {String} type the type of each chunk.
     4093     * @return StreamHelper the stream.
     4094     */
     4095    internalStream: function (type) {
     4096        var outputType = type.toLowerCase();
     4097        var askUnicodeString = outputType === "string" || outputType === "text";
     4098        if (outputType === "binarystring" || outputType === "text") {
     4099            outputType = "string";
     4100        }
     4101        var result = this._decompressWorker();
     4102
     4103        var isUnicodeString = !this._dataBinary;
     4104
     4105        if (isUnicodeString && !askUnicodeString) {
     4106            result = result.pipe(new utf8.Utf8EncodeWorker());
     4107        }
     4108        if (!isUnicodeString && askUnicodeString) {
     4109            result = result.pipe(new utf8.Utf8DecodeWorker());
     4110        }
     4111
     4112        return new StreamHelper(result, outputType, "");
     4113    },
     4114
     4115    /**
     4116     * Prepare the content in the asked type.
     4117     * @param {String} type the type of the result.
     4118     * @param {Function} onUpdate a function to call on each internal update.
     4119     * @return Promise the promise of the result.
     4120     */
     4121    async: function (type, onUpdate) {
     4122        return this.internalStream(type).accumulate(onUpdate);
     4123    },
     4124
     4125    /**
     4126     * Prepare the content as a nodejs stream.
     4127     * @param {String} type the type of each chunk.
     4128     * @param {Function} onUpdate a function to call on each internal update.
     4129     * @return Stream the stream.
     4130     */
     4131    nodeStream: function (type, onUpdate) {
     4132        return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
     4133    },
     4134
     4135    /**
     4136     * Return a worker for the compressed content.
     4137     * @private
     4138     * @param {Object} compression the compression object to use.
     4139     * @param {Object} compressionOptions the options to use when compressing.
     4140     * @return Worker the worker.
     4141     */
     4142    _compressWorker: function (compression, compressionOptions) {
     4143        if (
     4144            this._data instanceof CompressedObject &&
     4145            this._data.compression.magic === compression.magic
     4146        ) {
     4147            return this._data.getCompressedWorker();
     4148        } else {
     4149            var result = this._decompressWorker();
     4150            if(!this._dataBinary) {
     4151                result = result.pipe(new utf8.Utf8EncodeWorker());
     4152            }
     4153            return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
     4154        }
     4155    },
     4156    /**
     4157     * Return a worker for the decompressed content.
     4158     * @private
     4159     * @return Worker the worker.
     4160     */
     4161    _decompressWorker : function () {
     4162        if (this._data instanceof CompressedObject) {
     4163            return this._data.getContentWorker();
     4164        } else if (this._data instanceof GenericWorker) {
     4165            return this._data;
     4166        } else {
     4167            return new DataWorker(this._data);
     4168        }
     4169    }
     4170};
     4171
     4172var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
     4173var removedFn = function () {
     4174    throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
     4175};
     4176
     4177for(var i = 0; i < removedMethods.length; i++) {
     4178    ZipObject.prototype[removedMethods[i]] = removedFn;
     4179}
     4180module.exports = ZipObject;
     4181
     4182},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){
     4183require('../modules/web.immediate');
     4184module.exports = require('../modules/_core').setImmediate;
     4185},{"../modules/_core":40,"../modules/web.immediate":56}],37:[function(require,module,exports){
     4186module.exports = function(it){
     4187  if(typeof it != 'function')throw TypeError(it + ' is not a function!');
     4188  return it;
     4189};
     4190},{}],38:[function(require,module,exports){
     4191var isObject = require('./_is-object');
     4192module.exports = function(it){
     4193  if(!isObject(it))throw TypeError(it + ' is not an object!');
     4194  return it;
     4195};
     4196},{"./_is-object":51}],39:[function(require,module,exports){
     4197var toString = {}.toString;
     4198
     4199module.exports = function(it){
     4200  return toString.call(it).slice(8, -1);
     4201};
     4202},{}],40:[function(require,module,exports){
     4203var core = module.exports = {version: '2.3.0'};
     4204if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
     4205},{}],41:[function(require,module,exports){
     4206// optional / simple context binding
     4207var aFunction = require('./_a-function');
     4208module.exports = function(fn, that, length){
     4209  aFunction(fn);
     4210  if(that === undefined)return fn;
     4211  switch(length){
     4212    case 1: return function(a){
     4213      return fn.call(that, a);
     4214    };
     4215    case 2: return function(a, b){
     4216      return fn.call(that, a, b);
     4217    };
     4218    case 3: return function(a, b, c){
     4219      return fn.call(that, a, b, c);
     4220    };
     4221  }
     4222  return function(/* ...args */){
     4223    return fn.apply(that, arguments);
     4224  };
     4225};
     4226},{"./_a-function":37}],42:[function(require,module,exports){
     4227// Thank's IE8 for his funny defineProperty
     4228module.exports = !require('./_fails')(function(){
     4229  return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
     4230});
     4231},{"./_fails":45}],43:[function(require,module,exports){
     4232var isObject = require('./_is-object')
     4233  , document = require('./_global').document
     4234  // in old IE typeof document.createElement is 'object'
     4235  , is = isObject(document) && isObject(document.createElement);
     4236module.exports = function(it){
     4237  return is ? document.createElement(it) : {};
     4238};
     4239},{"./_global":46,"./_is-object":51}],44:[function(require,module,exports){
     4240var global    = require('./_global')
     4241  , core      = require('./_core')
     4242  , ctx       = require('./_ctx')
     4243  , hide      = require('./_hide')
     4244  , PROTOTYPE = 'prototype';
     4245
     4246var $export = function(type, name, source){
     4247  var IS_FORCED = type & $export.F
     4248    , IS_GLOBAL = type & $export.G
     4249    , IS_STATIC = type & $export.S
     4250    , IS_PROTO  = type & $export.P
     4251    , IS_BIND   = type & $export.B
     4252    , IS_WRAP   = type & $export.W
     4253    , exports   = IS_GLOBAL ? core : core[name] || (core[name] = {})
     4254    , expProto  = exports[PROTOTYPE]
     4255    , target    = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
     4256    , key, own, out;
     4257  if(IS_GLOBAL)source = name;
     4258  for(key in source){
     4259    // contains in native
     4260    own = !IS_FORCED && target && target[key] !== undefined;
     4261    if(own && key in exports)continue;
     4262    // export native or passed
     4263    out = own ? target[key] : source[key];
     4264    // prevent global pollution for namespaces
     4265    exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
     4266    // bind timers to global for call from export context
     4267    : IS_BIND && own ? ctx(out, global)
     4268    // wrap global constructors for prevent change them in library
     4269    : IS_WRAP && target[key] == out ? (function(C){
     4270      var F = function(a, b, c){
     4271        if(this instanceof C){
     4272          switch(arguments.length){
     4273            case 0: return new C;
     4274            case 1: return new C(a);
     4275            case 2: return new C(a, b);
     4276          } return new C(a, b, c);
     4277        } return C.apply(this, arguments);
     4278      };
     4279      F[PROTOTYPE] = C[PROTOTYPE];
     4280      return F;
     4281    // make static versions for prototype methods
     4282    })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
     4283    // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
     4284    if(IS_PROTO){
     4285      (exports.virtual || (exports.virtual = {}))[key] = out;
     4286      // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
     4287      if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
     4288    }
     4289  }
     4290};
     4291// type bitmap
     4292$export.F = 1;   // forced
     4293$export.G = 2;   // global
     4294$export.S = 4;   // static
     4295$export.P = 8;   // proto
     4296$export.B = 16;  // bind
     4297$export.W = 32;  // wrap
     4298$export.U = 64;  // safe
     4299$export.R = 128; // real proto method for `library`
     4300module.exports = $export;
     4301},{"./_core":40,"./_ctx":41,"./_global":46,"./_hide":47}],45:[function(require,module,exports){
     4302module.exports = function(exec){
     4303  try {
     4304    return !!exec();
     4305  } catch(e){
     4306    return true;
     4307  }
     4308};
     4309},{}],46:[function(require,module,exports){
     4310// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
     4311var global = module.exports = typeof window != 'undefined' && window.Math == Math
     4312  ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
     4313if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
     4314},{}],47:[function(require,module,exports){
     4315var dP         = require('./_object-dp')
     4316  , createDesc = require('./_property-desc');
     4317module.exports = require('./_descriptors') ? function(object, key, value){
     4318  return dP.f(object, key, createDesc(1, value));
     4319} : function(object, key, value){
     4320  object[key] = value;
     4321  return object;
     4322};
     4323},{"./_descriptors":42,"./_object-dp":52,"./_property-desc":53}],48:[function(require,module,exports){
     4324module.exports = require('./_global').document && document.documentElement;
     4325},{"./_global":46}],49:[function(require,module,exports){
     4326module.exports = !require('./_descriptors') && !require('./_fails')(function(){
     4327  return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7;
     4328});
     4329},{"./_descriptors":42,"./_dom-create":43,"./_fails":45}],50:[function(require,module,exports){
     4330// fast apply, http://jsperf.lnkit.com/fast-apply/5
     4331module.exports = function(fn, args, that){
     4332  var un = that === undefined;
     4333  switch(args.length){
     4334    case 0: return un ? fn()
     4335                      : fn.call(that);
     4336    case 1: return un ? fn(args[0])
     4337                      : fn.call(that, args[0]);
     4338    case 2: return un ? fn(args[0], args[1])
     4339                      : fn.call(that, args[0], args[1]);
     4340    case 3: return un ? fn(args[0], args[1], args[2])
     4341                      : fn.call(that, args[0], args[1], args[2]);
     4342    case 4: return un ? fn(args[0], args[1], args[2], args[3])
     4343                      : fn.call(that, args[0], args[1], args[2], args[3]);
     4344  } return              fn.apply(that, args);
     4345};
     4346},{}],51:[function(require,module,exports){
     4347module.exports = function(it){
     4348  return typeof it === 'object' ? it !== null : typeof it === 'function';
     4349};
     4350},{}],52:[function(require,module,exports){
     4351var anObject       = require('./_an-object')
     4352  , IE8_DOM_DEFINE = require('./_ie8-dom-define')
     4353  , toPrimitive    = require('./_to-primitive')
     4354  , dP             = Object.defineProperty;
     4355
     4356exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){
     4357  anObject(O);
     4358  P = toPrimitive(P, true);
     4359  anObject(Attributes);
     4360  if(IE8_DOM_DEFINE)try {
     4361    return dP(O, P, Attributes);
     4362  } catch(e){ /* empty */ }
     4363  if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
     4364  if('value' in Attributes)O[P] = Attributes.value;
     4365  return O;
     4366};
     4367},{"./_an-object":38,"./_descriptors":42,"./_ie8-dom-define":49,"./_to-primitive":55}],53:[function(require,module,exports){
     4368module.exports = function(bitmap, value){
     4369  return {
     4370    enumerable  : !(bitmap & 1),
     4371    configurable: !(bitmap & 2),
     4372    writable    : !(bitmap & 4),
     4373    value       : value
     4374  };
     4375};
     4376},{}],54:[function(require,module,exports){
     4377var ctx                = require('./_ctx')
     4378  , invoke             = require('./_invoke')
     4379  , html               = require('./_html')
     4380  , cel                = require('./_dom-create')
     4381  , global             = require('./_global')
     4382  , process            = global.process
     4383  , setTask            = global.setImmediate
     4384  , clearTask          = global.clearImmediate
     4385  , MessageChannel     = global.MessageChannel
     4386  , counter            = 0
     4387  , queue              = {}
     4388  , ONREADYSTATECHANGE = 'onreadystatechange'
     4389  , defer, channel, port;
     4390var run = function(){
     4391  var id = +this;
     4392  if(queue.hasOwnProperty(id)){
     4393    var fn = queue[id];
     4394    delete queue[id];
     4395    fn();
     4396  }
     4397};
     4398var listener = function(event){
     4399  run.call(event.data);
     4400};
     4401// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
     4402if(!setTask || !clearTask){
     4403  setTask = function setImmediate(fn){
     4404    var args = [], i = 1;
     4405    while(arguments.length > i)args.push(arguments[i++]);
     4406    queue[++counter] = function(){
     4407      invoke(typeof fn == 'function' ? fn : Function(fn), args);
     4408    };
     4409    defer(counter);
     4410    return counter;
     4411  };
     4412  clearTask = function clearImmediate(id){
     4413    delete queue[id];
     4414  };
     4415  // Node.js 0.8-
     4416  if(require('./_cof')(process) == 'process'){
     4417    defer = function(id){
     4418      process.nextTick(ctx(run, id, 1));
     4419    };
     4420  // Browsers with MessageChannel, includes WebWorkers
     4421  } else if(MessageChannel){
     4422    channel = new MessageChannel;
     4423    port    = channel.port2;
     4424    channel.port1.onmessage = listener;
     4425    defer = ctx(port.postMessage, port, 1);
     4426  // Browsers with postMessage, skip WebWorkers
     4427  // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
     4428  } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
     4429    defer = function(id){
     4430      global.postMessage(id + '', '*');
     4431    };
     4432    global.addEventListener('message', listener, false);
     4433  // IE8-
     4434  } else if(ONREADYSTATECHANGE in cel('script')){
     4435    defer = function(id){
     4436      html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
     4437        html.removeChild(this);
     4438        run.call(id);
     4439      };
     4440    };
     4441  // Rest old browsers
     4442  } else {
     4443    defer = function(id){
     4444      setTimeout(ctx(run, id, 1), 0);
     4445    };
     4446  }
     4447}
     4448module.exports = {
     4449  set:   setTask,
     4450  clear: clearTask
     4451};
     4452},{"./_cof":39,"./_ctx":41,"./_dom-create":43,"./_global":46,"./_html":48,"./_invoke":50}],55:[function(require,module,exports){
     4453// 7.1.1 ToPrimitive(input [, PreferredType])
     4454var isObject = require('./_is-object');
     4455// instead of the ES6 spec version, we didn't implement @@toPrimitive case
     4456// and the second argument - flag - preferred type is a string
     4457module.exports = function(it, S){
     4458  if(!isObject(it))return it;
     4459  var fn, val;
     4460  if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
     4461  if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
     4462  if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
     4463  throw TypeError("Can't convert object to primitive value");
     4464};
     4465},{"./_is-object":51}],56:[function(require,module,exports){
     4466var $export = require('./_export')
     4467  , $task   = require('./_task');
     4468$export($export.G + $export.B, {
     4469  setImmediate:   $task.set,
     4470  clearImmediate: $task.clear
     4471});
     4472},{"./_export":44,"./_task":54}],57:[function(require,module,exports){
     4473(function (global){
     4474'use strict';
     4475var Mutation = global.MutationObserver || global.WebKitMutationObserver;
     4476
     4477var scheduleDrain;
     4478
     4479{
     4480  if (Mutation) {
     4481    var called = 0;
     4482    var observer = new Mutation(nextTick);
     4483    var element = global.document.createTextNode('');
     4484    observer.observe(element, {
     4485      characterData: true
     4486    });
     4487    scheduleDrain = function () {
     4488      element.data = (called = ++called % 2);
     4489    };
     4490  } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
     4491    var channel = new global.MessageChannel();
     4492    channel.port1.onmessage = nextTick;
     4493    scheduleDrain = function () {
     4494      channel.port2.postMessage(0);
     4495    };
     4496  } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
     4497    scheduleDrain = function () {
     4498
     4499      // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
     4500      // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
     4501      var scriptEl = global.document.createElement('script');
     4502      scriptEl.onreadystatechange = function () {
     4503        nextTick();
     4504
     4505        scriptEl.onreadystatechange = null;
     4506        scriptEl.parentNode.removeChild(scriptEl);
     4507        scriptEl = null;
     4508      };
     4509      global.document.documentElement.appendChild(scriptEl);
     4510    };
     4511  } else {
     4512    scheduleDrain = function () {
     4513      setTimeout(nextTick, 0);
     4514    };
     4515  }
     4516}
     4517
     4518var draining;
     4519var queue = [];
     4520//named nextTick for less confusing stack traces
     4521function nextTick() {
     4522  draining = true;
     4523  var i, oldQueue;
     4524  var len = queue.length;
     4525  while (len) {
     4526    oldQueue = queue;
     4527    queue = [];
     4528    i = -1;
     4529    while (++i < len) {
     4530      oldQueue[i]();
     4531    }
     4532    len = queue.length;
     4533  }
     4534  draining = false;
     4535}
     4536
     4537module.exports = immediate;
     4538function immediate(task) {
     4539  if (queue.push(task) === 1 && !draining) {
     4540    scheduleDrain();
     4541  }
     4542}
     4543
     4544}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
     4545},{}],58:[function(require,module,exports){
     4546'use strict';
     4547var immediate = require('immediate');
     4548
     4549/* istanbul ignore next */
     4550function INTERNAL() {}
     4551
     4552var handlers = {};
     4553
     4554var REJECTED = ['REJECTED'];
     4555var FULFILLED = ['FULFILLED'];
     4556var PENDING = ['PENDING'];
     4557
     4558module.exports = Promise;
     4559
     4560function Promise(resolver) {
     4561  if (typeof resolver !== 'function') {
     4562    throw new TypeError('resolver must be a function');
     4563  }
     4564  this.state = PENDING;
     4565  this.queue = [];
     4566  this.outcome = void 0;
     4567  if (resolver !== INTERNAL) {
     4568    safelyResolveThenable(this, resolver);
     4569  }
     4570}
     4571
     4572Promise.prototype["catch"] = function (onRejected) {
     4573  return this.then(null, onRejected);
     4574};
     4575Promise.prototype.then = function (onFulfilled, onRejected) {
     4576  if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
     4577    typeof onRejected !== 'function' && this.state === REJECTED) {
     4578    return this;
     4579  }
     4580  var promise = new this.constructor(INTERNAL);
     4581  if (this.state !== PENDING) {
     4582    var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
     4583    unwrap(promise, resolver, this.outcome);
     4584  } else {
     4585    this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
     4586  }
     4587
     4588  return promise;
     4589};
     4590function QueueItem(promise, onFulfilled, onRejected) {
     4591  this.promise = promise;
     4592  if (typeof onFulfilled === 'function') {
     4593    this.onFulfilled = onFulfilled;
     4594    this.callFulfilled = this.otherCallFulfilled;
     4595  }
     4596  if (typeof onRejected === 'function') {
     4597    this.onRejected = onRejected;
     4598    this.callRejected = this.otherCallRejected;
     4599  }
     4600}
     4601QueueItem.prototype.callFulfilled = function (value) {
     4602  handlers.resolve(this.promise, value);
     4603};
     4604QueueItem.prototype.otherCallFulfilled = function (value) {
     4605  unwrap(this.promise, this.onFulfilled, value);
     4606};
     4607QueueItem.prototype.callRejected = function (value) {
     4608  handlers.reject(this.promise, value);
     4609};
     4610QueueItem.prototype.otherCallRejected = function (value) {
     4611  unwrap(this.promise, this.onRejected, value);
     4612};
     4613
     4614function unwrap(promise, func, value) {
     4615  immediate(function () {
     4616    var returnValue;
     4617    try {
     4618      returnValue = func(value);
     4619    } catch (e) {
     4620      return handlers.reject(promise, e);
     4621    }
     4622    if (returnValue === promise) {
     4623      handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
     4624    } else {
     4625      handlers.resolve(promise, returnValue);
     4626    }
     4627  });
     4628}
     4629
     4630handlers.resolve = function (self, value) {
     4631  var result = tryCatch(getThen, value);
     4632  if (result.status === 'error') {
     4633    return handlers.reject(self, result.value);
     4634  }
     4635  var thenable = result.value;
     4636
     4637  if (thenable) {
     4638    safelyResolveThenable(self, thenable);
     4639  } else {
     4640    self.state = FULFILLED;
     4641    self.outcome = value;
     4642    var i = -1;
     4643    var len = self.queue.length;
     4644    while (++i < len) {
     4645      self.queue[i].callFulfilled(value);
     4646    }
     4647  }
     4648  return self;
     4649};
     4650handlers.reject = function (self, error) {
     4651  self.state = REJECTED;
     4652  self.outcome = error;
     4653  var i = -1;
     4654  var len = self.queue.length;
     4655  while (++i < len) {
     4656    self.queue[i].callRejected(error);
     4657  }
     4658  return self;
     4659};
     4660
     4661function getThen(obj) {
     4662  // Make sure we only access the accessor once as required by the spec
     4663  var then = obj && obj.then;
     4664  if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
     4665    return function appyThen() {
     4666      then.apply(obj, arguments);
     4667    };
     4668  }
     4669}
     4670
     4671function safelyResolveThenable(self, thenable) {
     4672  // Either fulfill, reject or reject with error
     4673  var called = false;
     4674  function onError(value) {
     4675    if (called) {
     4676      return;
     4677    }
     4678    called = true;
     4679    handlers.reject(self, value);
     4680  }
     4681
     4682  function onSuccess(value) {
     4683    if (called) {
     4684      return;
     4685    }
     4686    called = true;
     4687    handlers.resolve(self, value);
     4688  }
     4689
     4690  function tryToUnwrap() {
     4691    thenable(onSuccess, onError);
     4692  }
     4693
     4694  var result = tryCatch(tryToUnwrap);
     4695  if (result.status === 'error') {
     4696    onError(result.value);
     4697  }
     4698}
     4699
     4700function tryCatch(func, value) {
     4701  var out = {};
     4702  try {
     4703    out.value = func(value);
     4704    out.status = 'success';
     4705  } catch (e) {
     4706    out.status = 'error';
     4707    out.value = e;
     4708  }
     4709  return out;
     4710}
     4711
     4712Promise.resolve = resolve;
     4713function resolve(value) {
     4714  if (value instanceof this) {
     4715    return value;
     4716  }
     4717  return handlers.resolve(new this(INTERNAL), value);
     4718}
     4719
     4720Promise.reject = reject;
     4721function reject(reason) {
     4722  var promise = new this(INTERNAL);
     4723  return handlers.reject(promise, reason);
     4724}
     4725
     4726Promise.all = all;
     4727function all(iterable) {
     4728  var self = this;
     4729  if (Object.prototype.toString.call(iterable) !== '[object Array]') {
     4730    return this.reject(new TypeError('must be an array'));
     4731  }
     4732
     4733  var len = iterable.length;
     4734  var called = false;
     4735  if (!len) {
     4736    return this.resolve([]);
     4737  }
     4738
     4739  var values = new Array(len);
     4740  var resolved = 0;
     4741  var i = -1;
     4742  var promise = new this(INTERNAL);
     4743
     4744  while (++i < len) {
     4745    allResolver(iterable[i], i);
     4746  }
     4747  return promise;
     4748  function allResolver(value, i) {
     4749    self.resolve(value).then(resolveFromAll, function (error) {
     4750      if (!called) {
     4751        called = true;
     4752        handlers.reject(promise, error);
     4753      }
     4754    });
     4755    function resolveFromAll(outValue) {
     4756      values[i] = outValue;
     4757      if (++resolved === len && !called) {
     4758        called = true;
     4759        handlers.resolve(promise, values);
     4760      }
     4761    }
     4762  }
     4763}
     4764
     4765Promise.race = race;
     4766function race(iterable) {
     4767  var self = this;
     4768  if (Object.prototype.toString.call(iterable) !== '[object Array]') {
     4769    return this.reject(new TypeError('must be an array'));
     4770  }
     4771
     4772  var len = iterable.length;
     4773  var called = false;
     4774  if (!len) {
     4775    return this.resolve([]);
     4776  }
     4777
     4778  var i = -1;
     4779  var promise = new this(INTERNAL);
     4780
     4781  while (++i < len) {
     4782    resolver(iterable[i]);
     4783  }
     4784  return promise;
     4785  function resolver(value) {
     4786    self.resolve(value).then(function (response) {
     4787      if (!called) {
     4788        called = true;
     4789        handlers.resolve(promise, response);
     4790      }
     4791    }, function (error) {
     4792      if (!called) {
     4793        called = true;
     4794        handlers.reject(promise, error);
     4795      }
     4796    });
     4797  }
     4798}
     4799
     4800},{"immediate":57}],59:[function(require,module,exports){
     4801// Top level file is just a mixin of submodules & constants
     4802'use strict';
     4803
     4804var assign    = require('./lib/utils/common').assign;
     4805
     4806var deflate   = require('./lib/deflate');
     4807var inflate   = require('./lib/inflate');
     4808var constants = require('./lib/zlib/constants');
     4809
     4810var pako = {};
     4811
     4812assign(pako, deflate, inflate, constants);
     4813
     4814module.exports = pako;
     4815
     4816},{"./lib/deflate":60,"./lib/inflate":61,"./lib/utils/common":62,"./lib/zlib/constants":65}],60:[function(require,module,exports){
     4817'use strict';
     4818
     4819
     4820var zlib_deflate = require('./zlib/deflate');
     4821var utils        = require('./utils/common');
     4822var strings      = require('./utils/strings');
     4823var msg          = require('./zlib/messages');
     4824var ZStream      = require('./zlib/zstream');
     4825
     4826var toString = Object.prototype.toString;
     4827
     4828/* Public constants ==========================================================*/
     4829/* ===========================================================================*/
     4830
     4831var Z_NO_FLUSH      = 0;
     4832var Z_FINISH        = 4;
     4833
     4834var Z_OK            = 0;
     4835var Z_STREAM_END    = 1;
     4836var Z_SYNC_FLUSH    = 2;
     4837
     4838var Z_DEFAULT_COMPRESSION = -1;
     4839
     4840var Z_DEFAULT_STRATEGY    = 0;
     4841
     4842var Z_DEFLATED  = 8;
     4843
     4844/* ===========================================================================*/
     4845
     4846
     4847/**
     4848 * class Deflate
     4849 *
     4850 * Generic JS-style wrapper for zlib calls. If you don't need
     4851 * streaming behaviour - use more simple functions: [[deflate]],
     4852 * [[deflateRaw]] and [[gzip]].
     4853 **/
     4854
     4855/* internal
     4856 * Deflate.chunks -> Array
     4857 *
     4858 * Chunks of output data, if [[Deflate#onData]] not overriden.
     4859 **/
     4860
     4861/**
     4862 * Deflate.result -> Uint8Array|Array
     4863 *
     4864 * Compressed result, generated by default [[Deflate#onData]]
     4865 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
     4866 * (call [[Deflate#push]] with `Z_FINISH` / `true` param)  or if you
     4867 * push a chunk with explicit flush (call [[Deflate#push]] with
     4868 * `Z_SYNC_FLUSH` param).
     4869 **/
     4870
     4871/**
     4872 * Deflate.err -> Number
     4873 *
     4874 * Error code after deflate finished. 0 (Z_OK) on success.
     4875 * You will not need it in real life, because deflate errors
     4876 * are possible only on wrong options or bad `onData` / `onEnd`
     4877 * custom handlers.
     4878 **/
     4879
     4880/**
     4881 * Deflate.msg -> String
     4882 *
     4883 * Error message, if [[Deflate.err]] != 0
     4884 **/
     4885
     4886
     4887/**
     4888 * new Deflate(options)
     4889 * - options (Object): zlib deflate options.
     4890 *
     4891 * Creates new deflator instance with specified params. Throws exception
     4892 * on bad params. Supported options:
     4893 *
     4894 * - `level`
     4895 * - `windowBits`
     4896 * - `memLevel`
     4897 * - `strategy`
     4898 * - `dictionary`
     4899 *
     4900 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
     4901 * for more information on these.
     4902 *
     4903 * Additional options, for internal needs:
     4904 *
     4905 * - `chunkSize` - size of generated data chunks (16K by default)
     4906 * - `raw` (Boolean) - do raw deflate
     4907 * - `gzip` (Boolean) - create gzip wrapper
     4908 * - `to` (String) - if equal to 'string', then result will be "binary string"
     4909 *    (each char code [0..255])
     4910 * - `header` (Object) - custom header for gzip
     4911 *   - `text` (Boolean) - true if compressed data believed to be text
     4912 *   - `time` (Number) - modification time, unix timestamp
     4913 *   - `os` (Number) - operation system code
     4914 *   - `extra` (Array) - array of bytes with extra data (max 65536)
     4915 *   - `name` (String) - file name (binary string)
     4916 *   - `comment` (String) - comment (binary string)
     4917 *   - `hcrc` (Boolean) - true if header crc should be added
     4918 *
     4919 * ##### Example:
     4920 *
     4921 * ```javascript
     4922 * var pako = require('pako')
     4923 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
     4924 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
     4925 *
     4926 * var deflate = new pako.Deflate({ level: 3});
     4927 *
     4928 * deflate.push(chunk1, false);
     4929 * deflate.push(chunk2, true);  // true -> last chunk
     4930 *
     4931 * if (deflate.err) { throw new Error(deflate.err); }
     4932 *
     4933 * console.log(deflate.result);
     4934 * ```
     4935 **/
     4936function Deflate(options) {
     4937  if (!(this instanceof Deflate)) return new Deflate(options);
     4938
     4939  this.options = utils.assign({
     4940    level: Z_DEFAULT_COMPRESSION,
     4941    method: Z_DEFLATED,
     4942    chunkSize: 16384,
     4943    windowBits: 15,
     4944    memLevel: 8,
     4945    strategy: Z_DEFAULT_STRATEGY,
     4946    to: ''
     4947  }, options || {});
     4948
     4949  var opt = this.options;
     4950
     4951  if (opt.raw && (opt.windowBits > 0)) {
     4952    opt.windowBits = -opt.windowBits;
     4953  }
     4954
     4955  else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
     4956    opt.windowBits += 16;
     4957  }
     4958
     4959  this.err    = 0;      // error code, if happens (0 = Z_OK)
     4960  this.msg    = '';     // error message
     4961  this.ended  = false;  // used to avoid multiple onEnd() calls
     4962  this.chunks = [];     // chunks of compressed data
     4963
     4964  this.strm = new ZStream();
     4965  this.strm.avail_out = 0;
     4966
     4967  var status = zlib_deflate.deflateInit2(
     4968    this.strm,
     4969    opt.level,
     4970    opt.method,
     4971    opt.windowBits,
     4972    opt.memLevel,
     4973    opt.strategy
     4974  );
     4975
     4976  if (status !== Z_OK) {
     4977    throw new Error(msg[status]);
     4978  }
     4979
     4980  if (opt.header) {
     4981    zlib_deflate.deflateSetHeader(this.strm, opt.header);
     4982  }
     4983
     4984  if (opt.dictionary) {
     4985    var dict;
     4986    // Convert data if needed
     4987    if (typeof opt.dictionary === 'string') {
     4988      // If we need to compress text, change encoding to utf8.
     4989      dict = strings.string2buf(opt.dictionary);
     4990    } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
     4991      dict = new Uint8Array(opt.dictionary);
     4992    } else {
     4993      dict = opt.dictionary;
     4994    }
     4995
     4996    status = zlib_deflate.deflateSetDictionary(this.strm, dict);
     4997
     4998    if (status !== Z_OK) {
     4999      throw new Error(msg[status]);
     5000    }
     5001
     5002    this._dict_set = true;
     5003  }
     5004}
     5005
     5006/**
     5007 * Deflate#push(data[, mode]) -> Boolean
     5008 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
     5009 *   converted to utf8 byte sequence.
     5010 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
     5011 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
     5012 *
     5013 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
     5014 * new compressed chunks. Returns `true` on success. The last data block must have
     5015 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
     5016 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
     5017 * can use mode Z_SYNC_FLUSH, keeping the compression context.
     5018 *
     5019 * On fail call [[Deflate#onEnd]] with error code and return false.
     5020 *
     5021 * We strongly recommend to use `Uint8Array` on input for best speed (output
     5022 * array format is detected automatically). Also, don't skip last param and always
     5023 * use the same type in your code (boolean or number). That will improve JS speed.
     5024 *
     5025 * For regular `Array`-s make sure all elements are [0..255].
     5026 *
     5027 * ##### Example
     5028 *
     5029 * ```javascript
     5030 * push(chunk, false); // push one of data chunks
     5031 * ...
     5032 * push(chunk, true);  // push last chunk
     5033 * ```
     5034 **/
     5035Deflate.prototype.push = function (data, mode) {
     5036  var strm = this.strm;
     5037  var chunkSize = this.options.chunkSize;
     5038  var status, _mode;
     5039
     5040  if (this.ended) { return false; }
     5041
     5042  _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
     5043
     5044  // Convert data if needed
     5045  if (typeof data === 'string') {
     5046    // If we need to compress text, change encoding to utf8.
     5047    strm.input = strings.string2buf(data);
     5048  } else if (toString.call(data) === '[object ArrayBuffer]') {
     5049    strm.input = new Uint8Array(data);
     5050  } else {
     5051    strm.input = data;
     5052  }
     5053
     5054  strm.next_in = 0;
     5055  strm.avail_in = strm.input.length;
     5056
     5057  do {
     5058    if (strm.avail_out === 0) {
     5059      strm.output = new utils.Buf8(chunkSize);
     5060      strm.next_out = 0;
     5061      strm.avail_out = chunkSize;
     5062    }
     5063    status = zlib_deflate.deflate(strm, _mode);    /* no bad return value */
     5064
     5065    if (status !== Z_STREAM_END && status !== Z_OK) {
     5066      this.onEnd(status);
     5067      this.ended = true;
     5068      return false;
     5069    }
     5070    if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
     5071      if (this.options.to === 'string') {
     5072        this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
     5073      } else {
     5074        this.onData(utils.shrinkBuf(strm.output, strm.next_out));
     5075      }
     5076    }
     5077  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
     5078
     5079  // Finalize on the last chunk.
     5080  if (_mode === Z_FINISH) {
     5081    status = zlib_deflate.deflateEnd(this.strm);
     5082    this.onEnd(status);
     5083    this.ended = true;
     5084    return status === Z_OK;
     5085  }
     5086
     5087  // callback interim results if Z_SYNC_FLUSH.
     5088  if (_mode === Z_SYNC_FLUSH) {
     5089    this.onEnd(Z_OK);
     5090    strm.avail_out = 0;
     5091    return true;
     5092  }
     5093
     5094  return true;
     5095};
     5096
     5097
     5098/**
     5099 * Deflate#onData(chunk) -> Void
     5100 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
     5101 *   on js engine support. When string output requested, each chunk
     5102 *   will be string.
     5103 *
     5104 * By default, stores data blocks in `chunks[]` property and glue
     5105 * those in `onEnd`. Override this handler, if you need another behaviour.
     5106 **/
     5107Deflate.prototype.onData = function (chunk) {
     5108  this.chunks.push(chunk);
     5109};
     5110
     5111
     5112/**
     5113 * Deflate#onEnd(status) -> Void
     5114 * - status (Number): deflate status. 0 (Z_OK) on success,
     5115 *   other if not.
     5116 *
     5117 * Called once after you tell deflate that the input stream is
     5118 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
     5119 * or if an error happened. By default - join collected chunks,
     5120 * free memory and fill `results` / `err` properties.
     5121 **/
     5122Deflate.prototype.onEnd = function (status) {
     5123  // On success - join
     5124  if (status === Z_OK) {
     5125    if (this.options.to === 'string') {
     5126      this.result = this.chunks.join('');
     5127    } else {
     5128      this.result = utils.flattenChunks(this.chunks);
     5129    }
     5130  }
     5131  this.chunks = [];
     5132  this.err = status;
     5133  this.msg = this.strm.msg;
     5134};
     5135
     5136
     5137/**
     5138 * deflate(data[, options]) -> Uint8Array|Array|String
     5139 * - data (Uint8Array|Array|String): input data to compress.
     5140 * - options (Object): zlib deflate options.
     5141 *
     5142 * Compress `data` with deflate algorithm and `options`.
     5143 *
     5144 * Supported options are:
     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 * Sugar (options):
     5156 *
     5157 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
     5158 *   negative windowBits implicitly.
     5159 * - `to` (String) - if equal to 'string', then result will be "binary string"
     5160 *    (each char code [0..255])
     5161 *
     5162 * ##### Example:
     5163 *
     5164 * ```javascript
     5165 * var pako = require('pako')
     5166 *   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
     5167 *
     5168 * console.log(pako.deflate(data));
     5169 * ```
     5170 **/
     5171function deflate(input, options) {
     5172  var deflator = new Deflate(options);
     5173
     5174  deflator.push(input, true);
     5175
     5176  // That will never happens, if you don't cheat with options :)
     5177  if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
     5178
     5179  return deflator.result;
     5180}
     5181
     5182
     5183/**
     5184 * deflateRaw(data[, options]) -> Uint8Array|Array|String
     5185 * - data (Uint8Array|Array|String): input data to compress.
     5186 * - options (Object): zlib deflate options.
     5187 *
     5188 * The same as [[deflate]], but creates raw data, without wrapper
     5189 * (header and adler32 crc).
     5190 **/
     5191function deflateRaw(input, options) {
     5192  options = options || {};
     5193  options.raw = true;
     5194  return deflate(input, options);
     5195}
     5196
     5197
     5198/**
     5199 * gzip(data[, options]) -> Uint8Array|Array|String
     5200 * - data (Uint8Array|Array|String): input data to compress.
     5201 * - options (Object): zlib deflate options.
     5202 *
     5203 * The same as [[deflate]], but create gzip wrapper instead of
     5204 * deflate one.
     5205 **/
     5206function gzip(input, options) {
     5207  options = options || {};
     5208  options.gzip = true;
     5209  return deflate(input, options);
     5210}
     5211
     5212
     5213exports.Deflate = Deflate;
     5214exports.deflate = deflate;
     5215exports.deflateRaw = deflateRaw;
     5216exports.gzip = gzip;
     5217
     5218},{"./utils/common":62,"./utils/strings":63,"./zlib/deflate":67,"./zlib/messages":72,"./zlib/zstream":74}],61:[function(require,module,exports){
     5219'use strict';
     5220
     5221
     5222var zlib_inflate = require('./zlib/inflate');
     5223var utils        = require('./utils/common');
     5224var strings      = require('./utils/strings');
     5225var c            = require('./zlib/constants');
     5226var msg          = require('./zlib/messages');
     5227var ZStream      = require('./zlib/zstream');
     5228var GZheader     = require('./zlib/gzheader');
     5229
     5230var toString = Object.prototype.toString;
     5231
     5232/**
     5233 * class Inflate
     5234 *
     5235 * Generic JS-style wrapper for zlib calls. If you don't need
     5236 * streaming behaviour - use more simple functions: [[inflate]]
     5237 * and [[inflateRaw]].
     5238 **/
     5239
     5240/* internal
     5241 * inflate.chunks -> Array
     5242 *
     5243 * Chunks of output data, if [[Inflate#onData]] not overriden.
     5244 **/
     5245
     5246/**
     5247 * Inflate.result -> Uint8Array|Array|String
     5248 *
     5249 * Uncompressed result, generated by default [[Inflate#onData]]
     5250 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
     5251 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
     5252 * push a chunk with explicit flush (call [[Inflate#push]] with
     5253 * `Z_SYNC_FLUSH` param).
     5254 **/
     5255
     5256/**
     5257 * Inflate.err -> Number
     5258 *
     5259 * Error code after inflate finished. 0 (Z_OK) on success.
     5260 * Should be checked if broken data possible.
     5261 **/
     5262
     5263/**
     5264 * Inflate.msg -> String
     5265 *
     5266 * Error message, if [[Inflate.err]] != 0
     5267 **/
     5268
     5269
     5270/**
     5271 * new Inflate(options)
     5272 * - options (Object): zlib inflate options.
     5273 *
     5274 * Creates new inflator instance with specified params. Throws exception
     5275 * on bad params. Supported options:
     5276 *
     5277 * - `windowBits`
     5278 * - `dictionary`
     5279 *
     5280 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
     5281 * for more information on these.
     5282 *
     5283 * Additional options, for internal needs:
     5284 *
     5285 * - `chunkSize` - size of generated data chunks (16K by default)
     5286 * - `raw` (Boolean) - do raw inflate
     5287 * - `to` (String) - if equal to 'string', then result will be converted
     5288 *   from utf8 to utf16 (javascript) string. When string output requested,
     5289 *   chunk length can differ from `chunkSize`, depending on content.
     5290 *
     5291 * By default, when no options set, autodetect deflate/gzip data format via
     5292 * wrapper header.
     5293 *
     5294 * ##### Example:
     5295 *
     5296 * ```javascript
     5297 * var pako = require('pako')
     5298 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
     5299 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
     5300 *
     5301 * var inflate = new pako.Inflate({ level: 3});
     5302 *
     5303 * inflate.push(chunk1, false);
     5304 * inflate.push(chunk2, true);  // true -> last chunk
     5305 *
     5306 * if (inflate.err) { throw new Error(inflate.err); }
     5307 *
     5308 * console.log(inflate.result);
     5309 * ```
     5310 **/
     5311function Inflate(options) {
     5312  if (!(this instanceof Inflate)) return new Inflate(options);
     5313
     5314  this.options = utils.assign({
     5315    chunkSize: 16384,
     5316    windowBits: 0,
     5317    to: ''
     5318  }, options || {});
     5319
     5320  var opt = this.options;
     5321
     5322  // Force window size for `raw` data, if not set directly,
     5323  // because we have no header for autodetect.
     5324  if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
     5325    opt.windowBits = -opt.windowBits;
     5326    if (opt.windowBits === 0) { opt.windowBits = -15; }
     5327  }
     5328
     5329  // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
     5330  if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
     5331      !(options && options.windowBits)) {
     5332    opt.windowBits += 32;
     5333  }
     5334
     5335  // Gzip header has no info about windows size, we can do autodetect only
     5336  // for deflate. So, if window size not set, force it to max when gzip possible
     5337  if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
     5338    // bit 3 (16) -> gzipped data
     5339    // bit 4 (32) -> autodetect gzip/deflate
     5340    if ((opt.windowBits & 15) === 0) {
     5341      opt.windowBits |= 15;
     5342    }
     5343  }
     5344
     5345  this.err    = 0;      // error code, if happens (0 = Z_OK)
     5346  this.msg    = '';     // error message
     5347  this.ended  = false;  // used to avoid multiple onEnd() calls
     5348  this.chunks = [];     // chunks of compressed data
     5349
     5350  this.strm   = new ZStream();
     5351  this.strm.avail_out = 0;
     5352
     5353  var status  = zlib_inflate.inflateInit2(
     5354    this.strm,
     5355    opt.windowBits
     5356  );
     5357
     5358  if (status !== c.Z_OK) {
     5359    throw new Error(msg[status]);
     5360  }
     5361
     5362  this.header = new GZheader();
     5363
     5364  zlib_inflate.inflateGetHeader(this.strm, this.header);
     5365}
     5366
     5367/**
     5368 * Inflate#push(data[, mode]) -> Boolean
     5369 * - data (Uint8Array|Array|ArrayBuffer|String): input data
     5370 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
     5371 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
     5372 *
     5373 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
     5374 * new output chunks. Returns `true` on success. The last data block must have
     5375 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
     5376 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
     5377 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
     5378 *
     5379 * On fail call [[Inflate#onEnd]] with error code and return false.
     5380 *
     5381 * We strongly recommend to use `Uint8Array` on input for best speed (output
     5382 * format is detected automatically). Also, don't skip last param and always
     5383 * use the same type in your code (boolean or number). That will improve JS speed.
     5384 *
     5385 * For regular `Array`-s make sure all elements are [0..255].
     5386 *
     5387 * ##### Example
     5388 *
     5389 * ```javascript
     5390 * push(chunk, false); // push one of data chunks
     5391 * ...
     5392 * push(chunk, true);  // push last chunk
     5393 * ```
     5394 **/
     5395Inflate.prototype.push = function (data, mode) {
     5396  var strm = this.strm;
     5397  var chunkSize = this.options.chunkSize;
     5398  var dictionary = this.options.dictionary;
     5399  var status, _mode;
     5400  var next_out_utf8, tail, utf8str;
     5401  var dict;
     5402
     5403  // Flag to properly process Z_BUF_ERROR on testing inflate call
     5404  // when we check that all output data was flushed.
     5405  var allowBufError = false;
     5406
     5407  if (this.ended) { return false; }
     5408  _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
     5409
     5410  // Convert data if needed
     5411  if (typeof data === 'string') {
     5412    // Only binary strings can be decompressed on practice
     5413    strm.input = strings.binstring2buf(data);
     5414  } else if (toString.call(data) === '[object ArrayBuffer]') {
     5415    strm.input = new Uint8Array(data);
     5416  } else {
     5417    strm.input = data;
     5418  }
     5419
     5420  strm.next_in = 0;
     5421  strm.avail_in = strm.input.length;
     5422
     5423  do {
     5424    if (strm.avail_out === 0) {
     5425      strm.output = new utils.Buf8(chunkSize);
     5426      strm.next_out = 0;
     5427      strm.avail_out = chunkSize;
     5428    }
     5429
     5430    status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);    /* no bad return value */
     5431
     5432    if (status === c.Z_NEED_DICT && dictionary) {
     5433      // Convert data if needed
     5434      if (typeof dictionary === 'string') {
     5435        dict = strings.string2buf(dictionary);
     5436      } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
     5437        dict = new Uint8Array(dictionary);
     5438      } else {
     5439        dict = dictionary;
     5440      }
     5441
     5442      status = zlib_inflate.inflateSetDictionary(this.strm, dict);
     5443
     5444    }
     5445
     5446    if (status === c.Z_BUF_ERROR && allowBufError === true) {
     5447      status = c.Z_OK;
     5448      allowBufError = false;
     5449    }
     5450
     5451    if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
     5452      this.onEnd(status);
     5453      this.ended = true;
     5454      return false;
     5455    }
     5456
     5457    if (strm.next_out) {
     5458      if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
     5459
     5460        if (this.options.to === 'string') {
     5461
     5462          next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
     5463
     5464          tail = strm.next_out - next_out_utf8;
     5465          utf8str = strings.buf2string(strm.output, next_out_utf8);
     5466
     5467          // move tail
     5468          strm.next_out = tail;
     5469          strm.avail_out = chunkSize - tail;
     5470          if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
     5471
     5472          this.onData(utf8str);
     5473
     5474        } else {
     5475          this.onData(utils.shrinkBuf(strm.output, strm.next_out));
     5476        }
     5477      }
     5478    }
     5479
     5480    // When no more input data, we should check that internal inflate buffers
     5481    // are flushed. The only way to do it when avail_out = 0 - run one more
     5482    // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
     5483    // Here we set flag to process this error properly.
     5484    //
     5485    // NOTE. Deflate does not return error in this case and does not needs such
     5486    // logic.
     5487    if (strm.avail_in === 0 && strm.avail_out === 0) {
     5488      allowBufError = true;
     5489    }
     5490
     5491  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
     5492
     5493  if (status === c.Z_STREAM_END) {
     5494    _mode = c.Z_FINISH;
     5495  }
     5496
     5497  // Finalize on the last chunk.
     5498  if (_mode === c.Z_FINISH) {
     5499    status = zlib_inflate.inflateEnd(this.strm);
     5500    this.onEnd(status);
     5501    this.ended = true;
     5502    return status === c.Z_OK;
     5503  }
     5504
     5505  // callback interim results if Z_SYNC_FLUSH.
     5506  if (_mode === c.Z_SYNC_FLUSH) {
     5507    this.onEnd(c.Z_OK);
     5508    strm.avail_out = 0;
     5509    return true;
     5510  }
     5511
     5512  return true;
     5513};
     5514
     5515
     5516/**
     5517 * Inflate#onData(chunk) -> Void
     5518 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
     5519 *   on js engine support. When string output requested, each chunk
     5520 *   will be string.
     5521 *
     5522 * By default, stores data blocks in `chunks[]` property and glue
     5523 * those in `onEnd`. Override this handler, if you need another behaviour.
     5524 **/
     5525Inflate.prototype.onData = function (chunk) {
     5526  this.chunks.push(chunk);
     5527};
     5528
     5529
     5530/**
     5531 * Inflate#onEnd(status) -> Void
     5532 * - status (Number): inflate status. 0 (Z_OK) on success,
     5533 *   other if not.
     5534 *
     5535 * Called either after you tell inflate that the input stream is
     5536 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
     5537 * or if an error happened. By default - join collected chunks,
     5538 * free memory and fill `results` / `err` properties.
     5539 **/
     5540Inflate.prototype.onEnd = function (status) {
     5541  // On success - join
     5542  if (status === c.Z_OK) {
     5543    if (this.options.to === 'string') {
     5544      // Glue & convert here, until we teach pako to send
     5545      // utf8 alligned strings to onData
     5546      this.result = this.chunks.join('');
     5547    } else {
     5548      this.result = utils.flattenChunks(this.chunks);
     5549    }
     5550  }
     5551  this.chunks = [];
     5552  this.err = status;
     5553  this.msg = this.strm.msg;
     5554};
     5555
     5556
     5557/**
     5558 * inflate(data[, options]) -> Uint8Array|Array|String
     5559 * - data (Uint8Array|Array|String): input data to decompress.
     5560 * - options (Object): zlib inflate options.
     5561 *
     5562 * Decompress `data` with inflate/ungzip and `options`. Autodetect
     5563 * format via wrapper header by default. That's why we don't provide
     5564 * separate `ungzip` method.
     5565 *
     5566 * Supported options are:
     5567 *
     5568 * - windowBits
     5569 *
     5570 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
     5571 * for more information.
     5572 *
     5573 * Sugar (options):
     5574 *
     5575 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
     5576 *   negative windowBits implicitly.
     5577 * - `to` (String) - if equal to 'string', then result will be converted
     5578 *   from utf8 to utf16 (javascript) string. When string output requested,
     5579 *   chunk length can differ from `chunkSize`, depending on content.
     5580 *
     5581 *
     5582 * ##### Example:
     5583 *
     5584 * ```javascript
     5585 * var pako = require('pako')
     5586 *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
     5587 *   , output;
     5588 *
     5589 * try {
     5590 *   output = pako.inflate(input);
     5591 * } catch (err)
     5592 *   console.log(err);
     5593 * }
     5594 * ```
     5595 **/
     5596function inflate(input, options) {
     5597  var inflator = new Inflate(options);
     5598
     5599  inflator.push(input, true);
     5600
     5601  // That will never happens, if you don't cheat with options :)
     5602  if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
     5603
     5604  return inflator.result;
     5605}
     5606
     5607
     5608/**
     5609 * inflateRaw(data[, options]) -> Uint8Array|Array|String
     5610 * - data (Uint8Array|Array|String): input data to decompress.
     5611 * - options (Object): zlib inflate options.
     5612 *
     5613 * The same as [[inflate]], but creates raw data, without wrapper
     5614 * (header and adler32 crc).
     5615 **/
     5616function inflateRaw(input, options) {
     5617  options = options || {};
     5618  options.raw = true;
     5619  return inflate(input, options);
     5620}
     5621
     5622
     5623/**
     5624 * ungzip(data[, options]) -> Uint8Array|Array|String
     5625 * - data (Uint8Array|Array|String): input data to decompress.
     5626 * - options (Object): zlib inflate options.
     5627 *
     5628 * Just shortcut to [[inflate]], because it autodetects format
     5629 * by header.content. Done for convenience.
     5630 **/
     5631
     5632
     5633exports.Inflate = Inflate;
     5634exports.inflate = inflate;
     5635exports.inflateRaw = inflateRaw;
     5636exports.ungzip  = inflate;
     5637
     5638},{"./utils/common":62,"./utils/strings":63,"./zlib/constants":65,"./zlib/gzheader":68,"./zlib/inflate":70,"./zlib/messages":72,"./zlib/zstream":74}],62:[function(require,module,exports){
     5639'use strict';
     5640
     5641
     5642var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
     5643                (typeof Uint16Array !== 'undefined') &&
     5644                (typeof Int32Array !== 'undefined');
     5645
     5646
     5647exports.assign = function (obj /*from1, from2, from3, ...*/) {
     5648  var sources = Array.prototype.slice.call(arguments, 1);
     5649  while (sources.length) {
     5650    var source = sources.shift();
     5651    if (!source) { continue; }
     5652
     5653    if (typeof source !== 'object') {
     5654      throw new TypeError(source + 'must be non-object');
     5655    }
     5656
     5657    for (var p in source) {
     5658      if (source.hasOwnProperty(p)) {
     5659        obj[p] = source[p];
     5660      }
     5661    }
     5662  }
     5663
     5664  return obj;
     5665};
     5666
     5667
     5668// reduce buffer size, avoiding mem copy
     5669exports.shrinkBuf = function (buf, size) {
     5670  if (buf.length === size) { return buf; }
     5671  if (buf.subarray) { return buf.subarray(0, size); }
     5672  buf.length = size;
     5673  return buf;
     5674};
     5675
     5676
     5677var fnTyped = {
     5678  arraySet: function (dest, src, src_offs, len, dest_offs) {
     5679    if (src.subarray && dest.subarray) {
     5680      dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
     5681      return;
     5682    }
     5683    // Fallback to ordinary array
     5684    for (var i = 0; i < len; i++) {
     5685      dest[dest_offs + i] = src[src_offs + i];
     5686    }
     5687  },
     5688  // Join array of chunks to single array.
     5689  flattenChunks: function (chunks) {
     5690    var i, l, len, pos, chunk, result;
     5691
     5692    // calculate data length
     5693    len = 0;
     5694    for (i = 0, l = chunks.length; i < l; i++) {
     5695      len += chunks[i].length;
     5696    }
     5697
     5698    // join chunks
     5699    result = new Uint8Array(len);
     5700    pos = 0;
     5701    for (i = 0, l = chunks.length; i < l; i++) {
     5702      chunk = chunks[i];
     5703      result.set(chunk, pos);
     5704      pos += chunk.length;
     5705    }
     5706
     5707    return result;
     5708  }
     5709};
     5710
     5711var fnUntyped = {
     5712  arraySet: function (dest, src, src_offs, len, dest_offs) {
     5713    for (var i = 0; i < len; i++) {
     5714      dest[dest_offs + i] = src[src_offs + i];
     5715    }
     5716  },
     5717  // Join array of chunks to single array.
     5718  flattenChunks: function (chunks) {
     5719    return [].concat.apply([], chunks);
     5720  }
     5721};
     5722
     5723
     5724// Enable/Disable typed arrays use, for testing
     5725//
     5726exports.setTyped = function (on) {
     5727  if (on) {
     5728    exports.Buf8  = Uint8Array;
     5729    exports.Buf16 = Uint16Array;
     5730    exports.Buf32 = Int32Array;
     5731    exports.assign(exports, fnTyped);
     5732  } else {
     5733    exports.Buf8  = Array;
     5734    exports.Buf16 = Array;
     5735    exports.Buf32 = Array;
     5736    exports.assign(exports, fnUntyped);
     5737  }
     5738};
     5739
     5740exports.setTyped(TYPED_OK);
     5741
     5742},{}],63:[function(require,module,exports){
     5743// String encode/decode helpers
     5744'use strict';
     5745
     5746
     5747var utils = require('./common');
     5748
     5749
     5750// Quick check if we can use fast array to bin string conversion
     5751//
     5752// - apply(Array) can fail on Android 2.2
     5753// - apply(Uint8Array) can fail on iOS 5.1 Safary
     5754//
     5755var STR_APPLY_OK = true;
     5756var STR_APPLY_UIA_OK = true;
     5757
     5758try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
     5759try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
     5760
     5761
     5762// Table with utf8 lengths (calculated by first byte of sequence)
     5763// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
     5764// because max possible codepoint is 0x10ffff
     5765var _utf8len = new utils.Buf8(256);
     5766for (var q = 0; q < 256; q++) {
     5767  _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
     5768}
     5769_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
     5770
     5771
     5772// convert string to array (typed, when possible)
     5773exports.string2buf = function (str) {
     5774  var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
     5775
     5776  // count binary size
     5777  for (m_pos = 0; m_pos < str_len; m_pos++) {
     5778    c = str.charCodeAt(m_pos);
     5779    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
     5780      c2 = str.charCodeAt(m_pos + 1);
     5781      if ((c2 & 0xfc00) === 0xdc00) {
     5782        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
     5783        m_pos++;
     5784      }
     5785    }
     5786    buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
     5787  }
     5788
     5789  // allocate buffer
     5790  buf = new utils.Buf8(buf_len);
     5791
     5792  // convert
     5793  for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
     5794    c = str.charCodeAt(m_pos);
     5795    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
     5796      c2 = str.charCodeAt(m_pos + 1);
     5797      if ((c2 & 0xfc00) === 0xdc00) {
     5798        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
     5799        m_pos++;
     5800      }
     5801    }
     5802    if (c < 0x80) {
     5803      /* one byte */
     5804      buf[i++] = c;
     5805    } else if (c < 0x800) {
     5806      /* two bytes */
     5807      buf[i++] = 0xC0 | (c >>> 6);
     5808      buf[i++] = 0x80 | (c & 0x3f);
     5809    } else if (c < 0x10000) {
     5810      /* three bytes */
     5811      buf[i++] = 0xE0 | (c >>> 12);
     5812      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
     5813      buf[i++] = 0x80 | (c & 0x3f);
     5814    } else {
     5815      /* four bytes */
     5816      buf[i++] = 0xf0 | (c >>> 18);
     5817      buf[i++] = 0x80 | (c >>> 12 & 0x3f);
     5818      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
     5819      buf[i++] = 0x80 | (c & 0x3f);
     5820    }
     5821  }
     5822
     5823  return buf;
     5824};
     5825
     5826// Helper (used in 2 places)
     5827function buf2binstring(buf, len) {
     5828  // use fallback for big arrays to avoid stack overflow
     5829  if (len < 65537) {
     5830    if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
     5831      return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
     5832    }
     5833  }
     5834
     5835  var result = '';
     5836  for (var i = 0; i < len; i++) {
     5837    result += String.fromCharCode(buf[i]);
     5838  }
     5839  return result;
     5840}
     5841
     5842
     5843// Convert byte array to binary string
     5844exports.buf2binstring = function (buf) {
     5845  return buf2binstring(buf, buf.length);
     5846};
     5847
     5848
     5849// Convert binary string (typed, when possible)
     5850exports.binstring2buf = function (str) {
     5851  var buf = new utils.Buf8(str.length);
     5852  for (var i = 0, len = buf.length; i < len; i++) {
     5853    buf[i] = str.charCodeAt(i);
     5854  }
     5855  return buf;
     5856};
     5857
     5858
     5859// convert array to string
     5860exports.buf2string = function (buf, max) {
     5861  var i, out, c, c_len;
     5862  var len = max || buf.length;
     5863
     5864  // Reserve max possible length (2 words per char)
     5865  // NB: by unknown reasons, Array is significantly faster for
     5866  //     String.fromCharCode.apply than Uint16Array.
     5867  var utf16buf = new Array(len * 2);
     5868
     5869  for (out = 0, i = 0; i < len;) {
     5870    c = buf[i++];
     5871    // quick process ascii
     5872    if (c < 0x80) { utf16buf[out++] = c; continue; }
     5873
     5874    c_len = _utf8len[c];
     5875    // skip 5 & 6 byte codes
     5876    if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
     5877
     5878    // apply mask on first byte
     5879    c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
     5880    // join the rest
     5881    while (c_len > 1 && i < len) {
     5882      c = (c << 6) | (buf[i++] & 0x3f);
     5883      c_len--;
     5884    }
     5885
     5886    // terminated by end of string?
     5887    if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
     5888
     5889    if (c < 0x10000) {
     5890      utf16buf[out++] = c;
     5891    } else {
     5892      c -= 0x10000;
     5893      utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
     5894      utf16buf[out++] = 0xdc00 | (c & 0x3ff);
     5895    }
     5896  }
     5897
     5898  return buf2binstring(utf16buf, out);
     5899};
     5900
     5901
     5902// Calculate max possible position in utf8 buffer,
     5903// that will not break sequence. If that's not possible
     5904// - (very small limits) return max size as is.
     5905//
     5906// buf[] - utf8 bytes array
     5907// max   - length limit (mandatory);
     5908exports.utf8border = function (buf, max) {
     5909  var pos;
     5910
     5911  max = max || buf.length;
     5912  if (max > buf.length) { max = buf.length; }
     5913
     5914  // go back from last position, until start of sequence found
     5915  pos = max - 1;
     5916  while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
     5917
     5918  // Fuckup - very small and broken sequence,
     5919  // return max, because we should return something anyway.
     5920  if (pos < 0) { return max; }
     5921
     5922  // If we came to start of buffer - that means vuffer is too small,
     5923  // return max too.
     5924  if (pos === 0) { return max; }
     5925
     5926  return (pos + _utf8len[buf[pos]] > max) ? pos : max;
     5927};
     5928
     5929},{"./common":62}],64:[function(require,module,exports){
     5930'use strict';
     5931
     5932// Note: adler32 takes 12% for level 0 and 2% for level 6.
     5933// It doesn't worth to make additional optimizationa as in original.
     5934// Small size is preferable.
     5935
     5936// (C) 1995-2013 Jean-loup Gailly and Mark Adler
     5937// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
     5938//
     5939// This software is provided 'as-is', without any express or implied
     5940// warranty. In no event will the authors be held liable for any damages
     5941// arising from the use of this software.
     5942//
     5943// Permission is granted to anyone to use this software for any purpose,
     5944// including commercial applications, and to alter it and redistribute it
     5945// freely, subject to the following restrictions:
     5946//
     5947// 1. The origin of this software must not be misrepresented; you must not
     5948//   claim that you wrote the original software. If you use this software
     5949//   in a product, an acknowledgment in the product documentation would be
     5950//   appreciated but is not required.
     5951// 2. Altered source versions must be plainly marked as such, and must not be
     5952//   misrepresented as being the original software.
     5953// 3. This notice may not be removed or altered from any source distribution.
     5954
     5955function adler32(adler, buf, len, pos) {
     5956  var s1 = (adler & 0xffff) |0,
     5957      s2 = ((adler >>> 16) & 0xffff) |0,
     5958      n = 0;
     5959
     5960  while (len !== 0) {
     5961    // Set limit ~ twice less than 5552, to keep
     5962    // s2 in 31-bits, because we force signed ints.
     5963    // in other case %= will fail.
     5964    n = len > 2000 ? 2000 : len;
     5965    len -= n;
     5966
     5967    do {
     5968      s1 = (s1 + buf[pos++]) |0;
     5969      s2 = (s2 + s1) |0;
     5970    } while (--n);
     5971
     5972    s1 %= 65521;
     5973    s2 %= 65521;
     5974  }
     5975
     5976  return (s1 | (s2 << 16)) |0;
     5977}
     5978
     5979
     5980module.exports = adler32;
     5981
     5982},{}],65:[function(require,module,exports){
     5983'use strict';
     5984
     5985// (C) 1995-2013 Jean-loup Gailly and Mark Adler
     5986// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
     5987//
     5988// This software is provided 'as-is', without any express or implied
     5989// warranty. In no event will the authors be held liable for any damages
     5990// arising from the use of this software.
     5991//
     5992// Permission is granted to anyone to use this software for any purpose,
     5993// including commercial applications, and to alter it and redistribute it
     5994// freely, subject to the following restrictions:
     5995//
     5996// 1. The origin of this software must not be misrepresented; you must not
     5997//   claim that you wrote the original software. If you use this software
     5998//   in a product, an acknowledgment in the product documentation would be
     5999//   appreciated but is not required.
     6000// 2. Altered source versions must be plainly marked as such, and must not be
     6001//   misrepresented as being the original software.
     6002// 3. This notice may not be removed or altered from any source distribution.
     6003
     6004module.exports = {
     6005
     6006  /* Allowed flush values; see deflate() and inflate() below for details */
     6007  Z_NO_FLUSH:         0,
     6008  Z_PARTIAL_FLUSH:    1,
     6009  Z_SYNC_FLUSH:       2,
     6010  Z_FULL_FLUSH:       3,
     6011  Z_FINISH:           4,
     6012  Z_BLOCK:            5,
     6013  Z_TREES:            6,
     6014
     6015  /* Return codes for the compression/decompression functions. Negative values
     6016  * are errors, positive values are used for special but normal events.
     6017  */
     6018  Z_OK:               0,
     6019  Z_STREAM_END:       1,
     6020  Z_NEED_DICT:        2,
     6021  Z_ERRNO:           -1,
     6022  Z_STREAM_ERROR:    -2,
     6023  Z_DATA_ERROR:      -3,
     6024  //Z_MEM_ERROR:     -4,
     6025  Z_BUF_ERROR:       -5,
     6026  //Z_VERSION_ERROR: -6,
     6027
     6028  /* compression levels */
     6029  Z_NO_COMPRESSION:         0,
     6030  Z_BEST_SPEED:             1,
     6031  Z_BEST_COMPRESSION:       9,
     6032  Z_DEFAULT_COMPRESSION:   -1,
     6033
     6034
     6035  Z_FILTERED:               1,
     6036  Z_HUFFMAN_ONLY:           2,
     6037  Z_RLE:                    3,
     6038  Z_FIXED:                  4,
     6039  Z_DEFAULT_STRATEGY:       0,
     6040
     6041  /* Possible values of the data_type field (though see inflate()) */
     6042  Z_BINARY:                 0,
     6043  Z_TEXT:                   1,
     6044  //Z_ASCII:                1, // = Z_TEXT (deprecated)
     6045  Z_UNKNOWN:                2,
     6046
     6047  /* The deflate compression method */
     6048  Z_DEFLATED:               8
     6049  //Z_NULL:                 null // Use -1 or null inline, depending on var type
     6050};
     6051
     6052},{}],66:[function(require,module,exports){
     6053'use strict';
     6054
     6055// Note: we can't get significant speed boost here.
     6056// So write code to minimize size - no pregenerated tables
     6057// and array tools dependencies.
     6058
     6059// (C) 1995-2013 Jean-loup Gailly and Mark Adler
     6060// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
     6061//
     6062// This software is provided 'as-is', without any express or implied
     6063// warranty. In no event will the authors be held liable for any damages
     6064// arising from the use of this software.
     6065//
     6066// Permission is granted to anyone to use this software for any purpose,
     6067// including commercial applications, and to alter it and redistribute it
     6068// freely, subject to the following restrictions:
     6069//
     6070// 1. The origin of this software must not be misrepresented; you must not
     6071//   claim that you wrote the original software. If you use this software
     6072//   in a product, an acknowledgment in the product documentation would be
     6073//   appreciated but is not required.
     6074// 2. Altered source versions must be plainly marked as such, and must not be
     6075//   misrepresented as being the original software.
     6076// 3. This notice may not be removed or altered from any source distribution.
     6077
     6078// Use ordinary array, since untyped makes no boost here
     6079function makeTable() {
     6080  var c, table = [];
     6081
     6082  for (var n = 0; n < 256; n++) {
     6083    c = n;
     6084    for (var k = 0; k < 8; k++) {
     6085      c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
     6086    }
     6087    table[n] = c;
     6088  }
     6089
     6090  return table;
     6091}
     6092
     6093// Create table on load. Just 255 signed longs. Not a problem.
     6094var crcTable = makeTable();
     6095
     6096
     6097function crc32(crc, buf, len, pos) {
     6098  var t = crcTable,
     6099      end = pos + len;
     6100
     6101  crc ^= -1;
     6102
     6103  for (var i = pos; i < end; i++) {
     6104    crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
     6105  }
     6106
     6107  return (crc ^ (-1)); // >>> 0;
     6108}
     6109
     6110
     6111module.exports = crc32;
     6112
     6113},{}],67:[function(require,module,exports){
     6114'use strict';
     6115
     6116// (C) 1995-2013 Jean-loup Gailly and Mark Adler
     6117// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
     6118//
     6119// This software is provided 'as-is', without any express or implied
     6120// warranty. In no event will the authors be held liable for any damages
     6121// arising from the use of this software.
     6122//
     6123// Permission is granted to anyone to use this software for any purpose,
     6124// including commercial applications, and to alter it and redistribute it
     6125// freely, subject to the following restrictions:
     6126//
     6127// 1. The origin of this software must not be misrepresented; you must not
     6128//   claim that you wrote the original software. If you use this software
     6129//   in a product, an acknowledgment in the product documentation would be
     6130//   appreciated but is not required.
     6131// 2. Altered source versions must be plainly marked as such, and must not be
     6132//   misrepresented as being the original software.
     6133// 3. This notice may not be removed or altered from any source distribution.
     6134
     6135var utils   = require('../utils/common');
     6136var trees   = require('./trees');
     6137var adler32 = require('./adler32');
     6138var crc32   = require('./crc32');
     6139var msg     = require('./messages');
     6140
     6141/* Public constants ==========================================================*/
     6142/* ===========================================================================*/
     6143
     6144
     6145/* Allowed flush values; see deflate() and inflate() below for details */
     6146var Z_NO_FLUSH      = 0;
     6147var Z_PARTIAL_FLUSH = 1;
     6148//var Z_SYNC_FLUSH    = 2;
     6149var Z_FULL_FLUSH    = 3;
     6150var Z_FINISH        = 4;
     6151var Z_BLOCK         = 5;
     6152//var Z_TREES         = 6;
     6153
     6154
     6155/* Return codes for the compression/decompression functions. Negative values
     6156 * are errors, positive values are used for special but normal events.
     6157 */
     6158var Z_OK            = 0;
     6159var Z_STREAM_END    = 1;
     6160//var Z_NEED_DICT     = 2;
     6161//var Z_ERRNO         = -1;
     6162var Z_STREAM_ERROR  = -2;
     6163var Z_DATA_ERROR    = -3;
     6164//var Z_MEM_ERROR     = -4;
     6165var Z_BUF_ERROR     = -5;
     6166//var Z_VERSION_ERROR = -6;
     6167
     6168
     6169/* compression levels */
     6170//var Z_NO_COMPRESSION      = 0;
     6171//var Z_BEST_SPEED          = 1;
     6172//var Z_BEST_COMPRESSION    = 9;
     6173var Z_DEFAULT_COMPRESSION = -1;
     6174
     6175
     6176var Z_FILTERED            = 1;
     6177var Z_HUFFMAN_ONLY        = 2;
     6178var Z_RLE                 = 3;
     6179var Z_FIXED               = 4;
     6180var Z_DEFAULT_STRATEGY    = 0;
     6181
     6182/* Possible values of the data_type field (though see inflate()) */
     6183//var Z_BINARY              = 0;
     6184//var Z_TEXT                = 1;
     6185//var Z_ASCII               = 1; // = Z_TEXT
     6186var Z_UNKNOWN             = 2;
     6187
     6188
     6189/* The deflate compression method */
     6190var Z_DEFLATED  = 8;
     6191
     6192/*============================================================================*/
     6193
     6194
     6195var MAX_MEM_LEVEL = 9;
     6196/* Maximum value for memLevel in deflateInit2 */
     6197var MAX_WBITS = 15;
     6198/* 32K LZ77 window */
     6199var DEF_MEM_LEVEL = 8;
     6200
     6201
     6202var LENGTH_CODES  = 29;
     6203/* number of length codes, not counting the special END_BLOCK code */
     6204var LITERALS      = 256;
     6205/* number of literal bytes 0..255 */
     6206var L_CODES       = LITERALS + 1 + LENGTH_CODES;
     6207/* number of Literal or Length codes, including the END_BLOCK code */
     6208var D_CODES       = 30;
     6209/* number of distance codes */
     6210var BL_CODES      = 19;
     6211/* number of codes used to transfer the bit lengths */
     6212var HEAP_SIZE     = 2 * L_CODES + 1;
     6213/* maximum heap size */
     6214var MAX_BITS  = 15;
     6215/* All codes must not exceed MAX_BITS bits */
     6216
     6217var MIN_MATCH = 3;
     6218var MAX_MATCH = 258;
     6219var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
     6220
     6221var PRESET_DICT = 0x20;
     6222
     6223var INIT_STATE = 42;
     6224var EXTRA_STATE = 69;
     6225var NAME_STATE = 73;
     6226var COMMENT_STATE = 91;
     6227var HCRC_STATE = 103;
     6228var BUSY_STATE = 113;
     6229var FINISH_STATE = 666;
     6230
     6231var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
     6232var BS_BLOCK_DONE     = 2; /* block flush performed */
     6233var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
     6234var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */
     6235
     6236var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
     6237
     6238function err(strm, errorCode) {
     6239  strm.msg = msg[errorCode];
     6240  return errorCode;
     6241}
     6242
     6243function rank(f) {
     6244  return ((f) << 1) - ((f) > 4 ? 9 : 0);
     6245}
     6246
     6247function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
     6248
     6249
     6250/* =========================================================================
     6251 * Flush as much pending output as possible. All deflate() output goes
     6252 * through this function so some applications may wish to modify it
     6253 * to avoid allocating a large strm->output buffer and copying into it.
     6254 * (See also read_buf()).
     6255 */
     6256function flush_pending(strm) {
     6257  var s = strm.state;
     6258
     6259  //_tr_flush_bits(s);
     6260  var len = s.pending;
     6261  if (len > strm.avail_out) {
     6262    len = strm.avail_out;
     6263  }
     6264  if (len === 0) { return; }
     6265
     6266  utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
     6267  strm.next_out += len;
     6268  s.pending_out += len;
     6269  strm.total_out += len;
     6270  strm.avail_out -= len;
     6271  s.pending -= len;
     6272  if (s.pending === 0) {
     6273    s.pending_out = 0;
     6274  }
     6275}
     6276
     6277
     6278function flush_block_only(s, last) {
     6279  trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
     6280  s.block_start = s.strstart;
     6281  flush_pending(s.strm);
     6282}
     6283
     6284
     6285function put_byte(s, b) {
     6286  s.pending_buf[s.pending++] = b;
     6287}
     6288
     6289
     6290/* =========================================================================
     6291 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
     6292 * IN assertion: the stream state is correct and there is enough room in
     6293 * pending_buf.
     6294 */
     6295function putShortMSB(s, b) {
     6296//  put_byte(s, (Byte)(b >> 8));
     6297//  put_byte(s, (Byte)(b & 0xff));
     6298  s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
     6299  s.pending_buf[s.pending++] = b & 0xff;
     6300}
     6301
     6302
     6303/* ===========================================================================
     6304 * Read a new buffer from the current input stream, update the adler32
     6305 * and total number of bytes read.  All deflate() input goes through
     6306 * this function so some applications may wish to modify it to avoid
     6307 * allocating a large strm->input buffer and copying from it.
     6308 * (See also flush_pending()).
     6309 */
     6310function read_buf(strm, buf, start, size) {
     6311  var len = strm.avail_in;
     6312
     6313  if (len > size) { len = size; }
     6314  if (len === 0) { return 0; }
     6315
     6316  strm.avail_in -= len;
     6317
     6318  // zmemcpy(buf, strm->next_in, len);
     6319  utils.arraySet(buf, strm.input, strm.next_in, len, start);
     6320  if (strm.state.wrap === 1) {
     6321    strm.adler = adler32(strm.adler, buf, len, start);
     6322  }
     6323
     6324  else if (strm.state.wrap === 2) {
     6325    strm.adler = crc32(strm.adler, buf, len, start);
     6326  }
     6327
     6328  strm.next_in += len;
     6329  strm.total_in += len;
     6330
     6331  return len;
     6332}
     6333
     6334
     6335/* ===========================================================================
     6336 * Set match_start to the longest match starting at the given string and
     6337 * return its length. Matches shorter or equal to prev_length are discarded,
     6338 * in which case the result is equal to prev_length and match_start is
     6339 * garbage.
     6340 * IN assertions: cur_match is the head of the hash chain for the current
     6341 *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
     6342 * OUT assertion: the match length is not greater than s->lookahead.
     6343 */
     6344function longest_match(s, cur_match) {
     6345  var chain_length = s.max_chain_length;      /* max hash chain length */
     6346  var scan = s.strstart; /* current string */
     6347  var match;                       /* matched string */
     6348  var len;                           /* length of current match */
     6349  var best_len = s.prev_length;              /* best match length so far */
     6350  var nice_match = s.nice_match;             /* stop if match long enough */
     6351  var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
     6352      s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
     6353
     6354  var _win = s.window; // shortcut
     6355
     6356  var wmask = s.w_mask;
     6357  var prev  = s.prev;
     6358
     6359  /* Stop when cur_match becomes <= limit. To simplify the code,
     6360   * we prevent matches with the string of window index 0.
     6361   */
     6362
     6363  var strend = s.strstart + MAX_MATCH;
     6364  var scan_end1  = _win[scan + best_len - 1];
     6365  var scan_end   = _win[scan + best_len];
     6366
     6367  /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
     6368   * It is easy to get rid of this optimization if necessary.
     6369   */
     6370  // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
     6371
     6372  /* Do not waste too much time if we already have a good match: */
     6373  if (s.prev_length >= s.good_match) {
     6374    chain_length >>= 2;
     6375  }
     6376  /* Do not look for matches beyond the end of the input. This is necessary
     6377   * to make deflate deterministic.
     6378   */
     6379  if (nice_match > s.lookahead) { nice_match = s.lookahead; }
     6380
     6381  // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
     6382
     6383  do {
     6384    // Assert(cur_match < s->strstart, "no future");
     6385    match = cur_match;
     6386
     6387    /* Skip to next match if the match length cannot increase
     6388     * or if the match length is less than 2.  Note that the checks below
     6389     * for insufficient lookahead only occur occasionally for performance
     6390     * reasons.  Therefore uninitialized memory will be accessed, and
     6391     * conditional jumps will be made that depend on those values.
     6392     * However the length of the match is limited to the lookahead, so
     6393     * the output of deflate is not affected by the uninitialized values.
     6394     */
     6395
     6396    if (_win[match + best_len]     !== scan_end  ||
     6397        _win[match + best_len - 1] !== scan_end1 ||
     6398        _win[match]                !== _win[scan] ||
     6399        _win[++match]              !== _win[scan + 1]) {
     6400      continue;
     6401    }
     6402
     6403    /* The check at best_len-1 can be removed because it will be made
     6404     * again later. (This heuristic is not always a win.)
     6405     * It is not necessary to compare scan[2] and match[2] since they
     6406     * are always equal when the other bytes match, given that
     6407     * the hash keys are equal and that HASH_BITS >= 8.
     6408     */
     6409    scan += 2;
     6410    match++;
     6411    // Assert(*scan == *match, "match[2]?");
     6412
     6413    /* We check for insufficient lookahead only every 8th comparison;
     6414     * the 256th check will be made at strstart+258.
     6415     */
     6416    do {
     6417      /*jshint noempty:false*/
     6418    } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
     6419             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
     6420             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
     6421             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
     6422             scan < strend);
     6423
     6424    // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
     6425
     6426    len = MAX_MATCH - (strend - scan);
     6427    scan = strend - MAX_MATCH;
     6428
     6429    if (len > best_len) {
     6430      s.match_start = cur_match;
     6431      best_len = len;
     6432      if (len >= nice_match) {
     6433        break;
     6434      }
     6435      scan_end1  = _win[scan + best_len - 1];
     6436      scan_end   = _win[scan + best_len];
     6437    }
     6438  } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
     6439
     6440  if (best_len <= s.lookahead) {
     6441    return best_len;
     6442  }
     6443  return s.lookahead;
     6444}
     6445
     6446
     6447/* ===========================================================================
     6448 * Fill the window when the lookahead becomes insufficient.
     6449 * Updates strstart and lookahead.
     6450 *
     6451 * IN assertion: lookahead < MIN_LOOKAHEAD
     6452 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
     6453 *    At least one byte has been read, or avail_in == 0; reads are
     6454 *    performed for at least two bytes (required for the zip translate_eol
     6455 *    option -- not supported here).
     6456 */
     6457function fill_window(s) {
     6458  var _w_size = s.w_size;
     6459  var p, n, m, more, str;
     6460
     6461  //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
     6462
     6463  do {
     6464    more = s.window_size - s.lookahead - s.strstart;
     6465
     6466    // JS ints have 32 bit, block below not needed
     6467    /* Deal with !@#$% 64K limit: */
     6468    //if (sizeof(int) <= 2) {
     6469    //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
     6470    //        more = wsize;
     6471    //
     6472    //  } else if (more == (unsigned)(-1)) {
     6473    //        /* Very unlikely, but possible on 16 bit machine if
     6474    //         * strstart == 0 && lookahead == 1 (input done a byte at time)
     6475    //         */
     6476    //        more--;
     6477    //    }
     6478    //}
     6479
     6480
     6481    /* If the window is almost full and there is insufficient lookahead,
     6482     * move the upper half to the lower one to make room in the upper half.
     6483     */
     6484    if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
     6485
     6486      utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
     6487      s.match_start -= _w_size;
     6488      s.strstart -= _w_size;
     6489      /* we now have strstart >= MAX_DIST */
     6490      s.block_start -= _w_size;
     6491
     6492      /* Slide the hash table (could be avoided with 32 bit values
     6493       at the expense of memory usage). We slide even when level == 0
     6494       to keep the hash table consistent if we switch back to level > 0
     6495       later. (Using level 0 permanently is not an optimal usage of
     6496       zlib, so we don't care about this pathological case.)
     6497       */
     6498
     6499      n = s.hash_size;
     6500      p = n;
     6501      do {
     6502        m = s.head[--p];
     6503        s.head[p] = (m >= _w_size ? m - _w_size : 0);
     6504      } while (--n);
     6505
     6506      n = _w_size;
     6507      p = n;
     6508      do {
     6509        m = s.prev[--p];
     6510        s.prev[p] = (m >= _w_size ? m - _w_size : 0);
     6511        /* If n is not on any hash chain, prev[n] is garbage but
     6512         * its value will never be used.
     6513         */
     6514      } while (--n);
     6515
     6516      more += _w_size;
     6517    }
     6518    if (s.strm.avail_in === 0) {
     6519      break;
     6520    }
     6521
     6522    /* If there was no sliding:
     6523     *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
     6524     *    more == window_size - lookahead - strstart
     6525     * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
     6526     * => more >= window_size - 2*WSIZE + 2
     6527     * In the BIG_MEM or MMAP case (not yet supported),
     6528     *   window_size == input_size + MIN_LOOKAHEAD  &&
     6529     *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
     6530     * Otherwise, window_size == 2*WSIZE so more >= 2.
     6531     * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
     6532     */
     6533    //Assert(more >= 2, "more < 2");
     6534    n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
     6535    s.lookahead += n;
     6536
     6537    /* Initialize the hash value now that we have some input: */
     6538    if (s.lookahead + s.insert >= MIN_MATCH) {
     6539      str = s.strstart - s.insert;
     6540      s.ins_h = s.window[str];
     6541
     6542      /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
     6543      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
     6544//#if MIN_MATCH != 3
     6545//        Call update_hash() MIN_MATCH-3 more times
     6546//#endif
     6547      while (s.insert) {
     6548        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
     6549        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
     6550
     6551        s.prev[str & s.w_mask] = s.head[s.ins_h];
     6552        s.head[s.ins_h] = str;
     6553        str++;
     6554        s.insert--;
     6555        if (s.lookahead + s.insert < MIN_MATCH) {
     6556          break;
     6557        }
     6558      }
     6559    }
     6560    /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
     6561     * but this is not important since only literal bytes will be emitted.
     6562     */
     6563
     6564  } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
     6565
     6566  /* If the WIN_INIT bytes after the end of the current data have never been
     6567   * written, then zero those bytes in order to avoid memory check reports of
     6568   * the use of uninitialized (or uninitialised as Julian writes) bytes by
     6569   * the longest match routines.  Update the high water mark for the next
     6570   * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
     6571   * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
     6572   */
     6573//  if (s.high_water < s.window_size) {
     6574//    var curr = s.strstart + s.lookahead;
     6575//    var init = 0;
     6576//
     6577//    if (s.high_water < curr) {
     6578//      /* Previous high water mark below current data -- zero WIN_INIT
     6579//       * bytes or up to end of window, whichever is less.
     6580//       */
     6581//      init = s.window_size - curr;
     6582//      if (init > WIN_INIT)
     6583//        init = WIN_INIT;
     6584//      zmemzero(s->window + curr, (unsigned)init);
     6585//      s->high_water = curr + init;
     6586//    }
     6587//    else if (s->high_water < (ulg)curr + WIN_INIT) {
     6588//      /* High water mark at or above current data, but below current data
     6589//       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
     6590//       * to end of window, whichever is less.
     6591//       */
     6592//      init = (ulg)curr + WIN_INIT - s->high_water;
     6593//      if (init > s->window_size - s->high_water)
     6594//        init = s->window_size - s->high_water;
     6595//      zmemzero(s->window + s->high_water, (unsigned)init);
     6596//      s->high_water += init;
     6597//    }
     6598//  }
     6599//
     6600//  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
     6601//    "not enough room for search");
     6602}
     6603
     6604/* ===========================================================================
     6605 * Copy without compression as much as possible from the input stream, return
     6606 * the current block state.
     6607 * This function does not insert new strings in the dictionary since
     6608 * uncompressible data is probably not useful. This function is used
     6609 * only for the level=0 compression option.
     6610 * NOTE: this function should be optimized to avoid extra copying from
     6611 * window to pending_buf.
     6612 */
     6613function deflate_stored(s, flush) {
     6614  /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
     6615   * to pending_buf_size, and each stored block has a 5 byte header:
     6616   */
     6617  var max_block_size = 0xffff;
     6618
     6619  if (max_block_size > s.pending_buf_size - 5) {
     6620    max_block_size = s.pending_buf_size - 5;
     6621  }
     6622
     6623  /* Copy as much as possible from input to output: */
     6624  for (;;) {
     6625    /* Fill the window as much as possible: */
     6626    if (s.lookahead <= 1) {
     6627
     6628      //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
     6629      //  s->block_start >= (long)s->w_size, "slide too late");
     6630//      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
     6631//        s.block_start >= s.w_size)) {
     6632//        throw  new Error("slide too late");
     6633//      }
     6634
     6635      fill_window(s);
     6636      if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
     6637        return BS_NEED_MORE;
     6638      }
     6639
     6640      if (s.lookahead === 0) {
     6641        break;
     6642      }
     6643      /* flush the current block */
     6644    }
     6645    //Assert(s->block_start >= 0L, "block gone");
     6646//    if (s.block_start < 0) throw new Error("block gone");
     6647
     6648    s.strstart += s.lookahead;
     6649    s.lookahead = 0;
     6650
     6651    /* Emit a stored block if pending_buf will be full: */
     6652    var max_start = s.block_start + max_block_size;
     6653
     6654    if (s.strstart === 0 || s.strstart >= max_start) {
     6655      /* strstart == 0 is possible when wraparound on 16-bit machine */
     6656      s.lookahead = s.strstart - max_start;
     6657      s.strstart = max_start;
     6658      /*** FLUSH_BLOCK(s, 0); ***/
     6659      flush_block_only(s, false);
     6660      if (s.strm.avail_out === 0) {
     6661        return BS_NEED_MORE;
     6662      }
     6663      /***/
     6664
     6665
     6666    }
     6667    /* Flush if we may have to slide, otherwise block_start may become
     6668     * negative and the data will be gone:
     6669     */
     6670    if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
     6671      /*** FLUSH_BLOCK(s, 0); ***/
     6672      flush_block_only(s, false);
     6673      if (s.strm.avail_out === 0) {
     6674        return BS_NEED_MORE;
     6675      }
     6676      /***/
     6677    }
     6678  }
     6679
     6680  s.insert = 0;
     6681
     6682  if (flush === Z_FINISH) {
     6683    /*** FLUSH_BLOCK(s, 1); ***/
     6684    flush_block_only(s, true);
     6685    if (s.strm.avail_out === 0) {
     6686      return BS_FINISH_STARTED;
     6687    }
     6688    /***/
     6689    return BS_FINISH_DONE;
     6690  }
     6691
     6692  if (s.strstart > s.block_start) {
     6693    /*** FLUSH_BLOCK(s, 0); ***/
     6694    flush_block_only(s, false);
     6695    if (s.strm.avail_out === 0) {
     6696      return BS_NEED_MORE;
     6697    }
     6698    /***/
     6699  }
     6700
     6701  return BS_NEED_MORE;
     6702}
     6703
     6704/* ===========================================================================
     6705 * Compress as much as possible from the input stream, return the current
     6706 * block state.
     6707 * This function does not perform lazy evaluation of matches and inserts
     6708 * new strings in the dictionary only for unmatched strings or for short
     6709 * matches. It is used only for the fast compression options.
     6710 */
     6711function deflate_fast(s, flush) {
     6712  var hash_head;        /* head of the hash chain */
     6713  var bflush;           /* set if current block must be flushed */
     6714
     6715  for (;;) {
     6716    /* Make sure that we always have enough lookahead, except
     6717     * at the end of the input file. We need MAX_MATCH bytes
     6718     * for the next match, plus MIN_MATCH bytes to insert the
     6719     * string following the next match.
     6720     */
     6721    if (s.lookahead < MIN_LOOKAHEAD) {
     6722      fill_window(s);
     6723      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
     6724        return BS_NEED_MORE;
     6725      }
     6726      if (s.lookahead === 0) {
     6727        break; /* flush the current block */
     6728      }
     6729    }
     6730
     6731    /* Insert the string window[strstart .. strstart+2] in the
     6732     * dictionary, and set hash_head to the head of the hash chain:
     6733     */
     6734    hash_head = 0/*NIL*/;
     6735    if (s.lookahead >= MIN_MATCH) {
     6736      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
     6737      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
     6738      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
     6739      s.head[s.ins_h] = s.strstart;
     6740      /***/
     6741    }
     6742
     6743    /* Find the longest match, discarding those <= prev_length.
     6744     * At this point we have always match_length < MIN_MATCH
     6745     */
     6746    if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
     6747      /* To simplify the code, we prevent matches with the string
     6748       * of window index 0 (in particular we have to avoid a match
     6749       * of the string with itself at the start of the input file).
     6750       */
     6751      s.match_length = longest_match(s, hash_head);
     6752      /* longest_match() sets match_start */
     6753    }
     6754    if (s.match_length >= MIN_MATCH) {
     6755      // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
     6756
     6757      /*** _tr_tally_dist(s, s.strstart - s.match_start,
     6758                     s.match_length - MIN_MATCH, bflush); ***/
     6759      bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
     6760
     6761      s.lookahead -= s.match_length;
     6762
     6763      /* Insert new strings in the hash table only if the match length
     6764       * is not too large. This saves time but degrades compression.
     6765       */
     6766      if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
     6767        s.match_length--; /* string at strstart already in table */
     6768        do {
     6769          s.strstart++;
     6770          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
     6771          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
     6772          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
     6773          s.head[s.ins_h] = s.strstart;
     6774          /***/
     6775          /* strstart never exceeds WSIZE-MAX_MATCH, so there are
     6776           * always MIN_MATCH bytes ahead.
     6777           */
     6778        } while (--s.match_length !== 0);
     6779        s.strstart++;
     6780      } else
     6781      {
     6782        s.strstart += s.match_length;
     6783        s.match_length = 0;
     6784        s.ins_h = s.window[s.strstart];
     6785        /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
     6786        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
     6787
     6788//#if MIN_MATCH != 3
     6789//                Call UPDATE_HASH() MIN_MATCH-3 more times
     6790//#endif
     6791        /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
     6792         * matter since it will be recomputed at next deflate call.
     6793         */
     6794      }
     6795    } else {
     6796      /* No match, output a literal byte */
     6797      //Tracevv((stderr,"%c", s.window[s.strstart]));
     6798      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
     6799      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
     6800
     6801      s.lookahead--;
     6802      s.strstart++;
     6803    }
     6804    if (bflush) {
     6805      /*** FLUSH_BLOCK(s, 0); ***/
     6806      flush_block_only(s, false);
     6807      if (s.strm.avail_out === 0) {
     6808        return BS_NEED_MORE;
     6809      }
     6810      /***/
     6811    }
     6812  }
     6813  s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
     6814  if (flush === Z_FINISH) {
     6815    /*** FLUSH_BLOCK(s, 1); ***/
     6816    flush_block_only(s, true);
     6817    if (s.strm.avail_out === 0) {
     6818      return BS_FINISH_STARTED;
     6819    }
     6820    /***/
     6821    return BS_FINISH_DONE;
     6822  }
     6823  if (s.last_lit) {
     6824    /*** FLUSH_BLOCK(s, 0); ***/
     6825    flush_block_only(s, false);
     6826    if (s.strm.avail_out === 0) {
     6827      return BS_NEED_MORE;
     6828    }
     6829    /***/
     6830  }
     6831  return BS_BLOCK_DONE;
     6832}
     6833
     6834/* ===========================================================================
     6835 * Same as above, but achieves better compression. We use a lazy
     6836 * evaluation for matches: a match is finally adopted only if there is
     6837 * no better match at the next window position.
     6838 */
     6839function deflate_slow(s, flush) {
     6840  var hash_head;          /* head of hash chain */
     6841  var bflush;              /* set if current block must be flushed */
     6842
     6843  var max_insert;
     6844
     6845  /* Process the input block. */
     6846  for (;;) {
     6847    /* Make sure that we always have enough lookahead, except
     6848     * at the end of the input file. We need MAX_MATCH bytes
     6849     * for the next match, plus MIN_MATCH bytes to insert the
     6850     * string following the next match.
     6851     */
     6852    if (s.lookahead < MIN_LOOKAHEAD) {
     6853      fill_window(s);
     6854      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
     6855        return BS_NEED_MORE;
     6856      }
     6857      if (s.lookahead === 0) { break; } /* flush the current block */
     6858    }
     6859
     6860    /* Insert the string window[strstart .. strstart+2] in the
     6861     * dictionary, and set hash_head to the head of the hash chain:
     6862     */
     6863    hash_head = 0/*NIL*/;
     6864    if (s.lookahead >= MIN_MATCH) {
     6865      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
     6866      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
     6867      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
     6868      s.head[s.ins_h] = s.strstart;
     6869      /***/
     6870    }
     6871
     6872    /* Find the longest match, discarding those <= prev_length.
     6873     */
     6874    s.prev_length = s.match_length;
     6875    s.prev_match = s.match_start;
     6876    s.match_length = MIN_MATCH - 1;
     6877
     6878    if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
     6879        s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
     6880      /* To simplify the code, we prevent matches with the string
     6881       * of window index 0 (in particular we have to avoid a match
     6882       * of the string with itself at the start of the input file).
     6883       */
     6884      s.match_length = longest_match(s, hash_head);
     6885      /* longest_match() sets match_start */
     6886
     6887      if (s.match_length <= 5 &&
     6888         (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
     6889
     6890        /* If prev_match is also MIN_MATCH, match_start is garbage
     6891         * but we will ignore the current match anyway.
     6892         */
     6893        s.match_length = MIN_MATCH - 1;
     6894      }
     6895    }
     6896    /* If there was a match at the previous step and the current
     6897     * match is not better, output the previous match:
     6898     */
     6899    if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
     6900      max_insert = s.strstart + s.lookahead - MIN_MATCH;
     6901      /* Do not insert strings in hash table beyond this. */
     6902
     6903      //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
     6904
     6905      /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
     6906                     s.prev_length - MIN_MATCH, bflush);***/
     6907      bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
     6908      /* Insert in hash table all strings up to the end of the match.
     6909       * strstart-1 and strstart are already inserted. If there is not
     6910       * enough lookahead, the last two strings are not inserted in
     6911       * the hash table.
     6912       */
     6913      s.lookahead -= s.prev_length - 1;
     6914      s.prev_length -= 2;
     6915      do {
     6916        if (++s.strstart <= max_insert) {
     6917          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
     6918          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
     6919          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
     6920          s.head[s.ins_h] = s.strstart;
     6921          /***/
     6922        }
     6923      } while (--s.prev_length !== 0);
     6924      s.match_available = 0;
     6925      s.match_length = MIN_MATCH - 1;
     6926      s.strstart++;
     6927
     6928      if (bflush) {
     6929        /*** FLUSH_BLOCK(s, 0); ***/
     6930        flush_block_only(s, false);
     6931        if (s.strm.avail_out === 0) {
     6932          return BS_NEED_MORE;
     6933        }
     6934        /***/
     6935      }
     6936
     6937    } else if (s.match_available) {
     6938      /* If there was no match at the previous position, output a
     6939       * single literal. If there was a match but the current match
     6940       * is longer, truncate the previous match to a single literal.
     6941       */
     6942      //Tracevv((stderr,"%c", s->window[s->strstart-1]));
     6943      /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
     6944      bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
     6945
     6946      if (bflush) {
     6947        /*** FLUSH_BLOCK_ONLY(s, 0) ***/
     6948        flush_block_only(s, false);
     6949        /***/
     6950      }
     6951      s.strstart++;
     6952      s.lookahead--;
     6953      if (s.strm.avail_out === 0) {
     6954        return BS_NEED_MORE;
     6955      }
     6956    } else {
     6957      /* There is no previous match to compare with, wait for
     6958       * the next step to decide.
     6959       */
     6960      s.match_available = 1;
     6961      s.strstart++;
     6962      s.lookahead--;
     6963    }
     6964  }
     6965  //Assert (flush != Z_NO_FLUSH, "no flush?");
     6966  if (s.match_available) {
     6967    //Tracevv((stderr,"%c", s->window[s->strstart-1]));
     6968    /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
     6969    bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
     6970
     6971    s.match_available = 0;
     6972  }
     6973  s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
     6974  if (flush === Z_FINISH) {
     6975    /*** FLUSH_BLOCK(s, 1); ***/
     6976    flush_block_only(s, true);
     6977    if (s.strm.avail_out === 0) {
     6978      return BS_FINISH_STARTED;
     6979    }
     6980    /***/
     6981    return BS_FINISH_DONE;
     6982  }
     6983  if (s.last_lit) {
     6984    /*** FLUSH_BLOCK(s, 0); ***/
     6985    flush_block_only(s, false);
     6986    if (s.strm.avail_out === 0) {
     6987      return BS_NEED_MORE;
     6988    }
     6989    /***/
     6990  }
     6991
     6992  return BS_BLOCK_DONE;
     6993}
     6994
     6995
     6996/* ===========================================================================
     6997 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
     6998 * one.  Do not maintain a hash table.  (It will be regenerated if this run of
     6999 * deflate switches away from Z_RLE.)
     7000 */
     7001function deflate_rle(s, flush) {
     7002  var bflush;            /* set if current block must be flushed */
     7003  var prev;              /* byte at distance one to match */
     7004  var scan, strend;      /* scan goes up to strend for length of run */
     7005
     7006  var _win = s.window;
     7007
     7008  for (;;) {
     7009    /* Make sure that we always have enough lookahead, except
     7010     * at the end of the input file. We need MAX_MATCH bytes
     7011     * for the longest run, plus one for the unrolled loop.
     7012     */
     7013    if (s.lookahead <= MAX_MATCH) {
     7014      fill_window(s);
     7015      if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
     7016        return BS_NEED_MORE;
     7017      }
     7018      if (s.lookahead === 0) { break; } /* flush the current block */
     7019    }
     7020
     7021    /* See how many times the previous byte repeats */
     7022    s.match_length = 0;
     7023    if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
     7024      scan = s.strstart - 1;
     7025      prev = _win[scan];
     7026      if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
     7027        strend = s.strstart + MAX_MATCH;
     7028        do {
     7029          /*jshint noempty:false*/
     7030        } while (prev === _win[++scan] && prev === _win[++scan] &&
     7031                 prev === _win[++scan] && prev === _win[++scan] &&
     7032                 prev === _win[++scan] && prev === _win[++scan] &&
     7033                 prev === _win[++scan] && prev === _win[++scan] &&
     7034                 scan < strend);
     7035        s.match_length = MAX_MATCH - (strend - scan);
     7036        if (s.match_length > s.lookahead) {
     7037          s.match_length = s.lookahead;
     7038        }
     7039      }
     7040      //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
     7041    }
     7042
     7043    /* Emit match if have run of MIN_MATCH or longer, else emit literal */
     7044    if (s.match_length >= MIN_MATCH) {
     7045      //check_match(s, s.strstart, s.strstart - 1, s.match_length);
     7046
     7047      /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
     7048      bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
     7049
     7050      s.lookahead -= s.match_length;
     7051      s.strstart += s.match_length;
     7052      s.match_length = 0;
     7053    } else {
     7054      /* No match, output a literal byte */
     7055      //Tracevv((stderr,"%c", s->window[s->strstart]));
     7056      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
     7057      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
     7058
     7059      s.lookahead--;
     7060      s.strstart++;
     7061    }
     7062    if (bflush) {
     7063      /*** FLUSH_BLOCK(s, 0); ***/
     7064      flush_block_only(s, false);
     7065      if (s.strm.avail_out === 0) {
     7066        return BS_NEED_MORE;
     7067      }
     7068      /***/
     7069    }
     7070  }
     7071  s.insert = 0;
     7072  if (flush === Z_FINISH) {
     7073    /*** FLUSH_BLOCK(s, 1); ***/
     7074    flush_block_only(s, true);
     7075    if (s.strm.avail_out === 0) {
     7076      return BS_FINISH_STARTED;
     7077    }
     7078    /***/
     7079    return BS_FINISH_DONE;
     7080  }
     7081  if (s.last_lit) {
     7082    /*** FLUSH_BLOCK(s, 0); ***/
     7083    flush_block_only(s, false);
     7084    if (s.strm.avail_out === 0) {
     7085      return BS_NEED_MORE;
     7086    }
     7087    /***/
     7088  }
     7089  return BS_BLOCK_DONE;
     7090}
     7091
     7092/* ===========================================================================
     7093 * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
     7094 * (It will be regenerated if this run of deflate switches away from Huffman.)
     7095 */
     7096function deflate_huff(s, flush) {
     7097  var bflush;             /* set if current block must be flushed */
     7098
     7099  for (;;) {
     7100    /* Make sure that we have a literal to write. */
     7101    if (s.lookahead === 0) {
     7102      fill_window(s);
     7103      if (s.lookahead === 0) {
     7104        if (flush === Z_NO_FLUSH) {
     7105          return BS_NEED_MORE;
     7106        }
     7107        break;      /* flush the current block */
     7108      }
     7109    }
     7110
     7111    /* Output a literal byte */
     7112    s.match_length = 0;
     7113    //Tracevv((stderr,"%c", s->window[s->strstart]));
     7114    /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
     7115    bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
     7116    s.lookahead--;
     7117    s.strstart++;
     7118    if (bflush) {
     7119      /*** FLUSH_BLOCK(s, 0); ***/
     7120      flush_block_only(s, false);
     7121      if (s.strm.avail_out === 0) {
     7122        return BS_NEED_MORE;
     7123      }
     7124      /***/
     7125    }
     7126  }
     7127  s.insert = 0;
     7128  if (flush === Z_FINISH) {
     7129    /*** FLUSH_BLOCK(s, 1); ***/
     7130    flush_block_only(s, true);
     7131    if (s.strm.avail_out === 0) {
     7132      return BS_FINISH_STARTED;
     7133    }
     7134    /***/
     7135    return BS_FINISH_DONE;
     7136  }
     7137  if (s.last_lit) {
     7138    /*** FLUSH_BLOCK(s, 0); ***/
     7139    flush_block_only(s, false);
     7140    if (s.strm.avail_out === 0) {
     7141      return BS_NEED_MORE;
     7142    }
     7143    /***/
     7144  }
     7145  return BS_BLOCK_DONE;
     7146}
     7147
     7148/* Values for max_lazy_match, good_match and max_chain_length, depending on
     7149 * the desired pack level (0..9). The values given below have been tuned to
     7150 * exclude worst case performance for pathological files. Better values may be
     7151 * found for specific files.
     7152 */
     7153function Config(good_length, max_lazy, nice_length, max_chain, func) {
     7154  this.good_length = good_length;
     7155  this.max_lazy = max_lazy;
     7156  this.nice_length = nice_length;
     7157  this.max_chain = max_chain;
     7158  this.func = func;
     7159}
     7160
     7161var configuration_table;
     7162
     7163configuration_table = [
     7164  /*      good lazy nice chain */
     7165  new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
     7166  new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
     7167  new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
     7168  new Config(4, 6, 32, 32, deflate_fast),          /* 3 */
     7169
     7170  new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
     7171  new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
     7172  new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
     7173  new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
     7174  new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
     7175  new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
     7176];
     7177
     7178
     7179/* ===========================================================================
     7180 * Initialize the "longest match" routines for a new zlib stream
     7181 */
     7182function lm_init(s) {
     7183  s.window_size = 2 * s.w_size;
     7184
     7185  /*** CLEAR_HASH(s); ***/
     7186  zero(s.head); // Fill with NIL (= 0);
     7187
     7188  /* Set the default configuration parameters:
     7189   */
     7190  s.max_lazy_match = configuration_table[s.level].max_lazy;
     7191  s.good_match = configuration_table[s.level].good_length;
     7192  s.nice_match = configuration_table[s.level].nice_length;
     7193  s.max_chain_length = configuration_table[s.level].max_chain;
     7194
     7195  s.strstart = 0;
     7196  s.block_start = 0;
     7197  s.lookahead = 0;
     7198  s.insert = 0;
     7199  s.match_length = s.prev_length = MIN_MATCH - 1;
     7200  s.match_available = 0;
     7201  s.ins_h = 0;
     7202}
     7203
     7204
     7205function DeflateState() {
     7206  this.strm = null;            /* pointer back to this zlib stream */
     7207  this.status = 0;            /* as the name implies */
     7208  this.pending_buf = null;      /* output still pending */
     7209  this.pending_buf_size = 0;  /* size of pending_buf */
     7210  this.pending_out = 0;       /* next pending byte to output to the stream */
     7211  this.pending = 0;           /* nb of bytes in the pending buffer */
     7212  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
     7213  this.gzhead = null;         /* gzip header information to write */
     7214  this.gzindex = 0;           /* where in extra, name, or comment */
     7215  this.method = Z_DEFLATED; /* can only be DEFLATED */
     7216  this.last_flush = -1;   /* value of flush param for previous deflate call */
     7217
     7218  this.w_size = 0;  /* LZ77 window size (32K by default) */
     7219  this.w_bits = 0;  /* log2(w_size)  (8..16) */
     7220  this.w_mask = 0;  /* w_size - 1 */
     7221
     7222  this.window = null;
     7223  /* Sliding window. Input bytes are read into the second half of the window,
     7224   * and move to the first half later to keep a dictionary of at least wSize
     7225   * bytes. With this organization, matches are limited to a distance of
     7226   * wSize-MAX_MATCH bytes, but this ensures that IO is always
     7227   * performed with a length multiple of the block size.
     7228   */
     7229
     7230  this.window_size = 0;
     7231  /* Actual size of window: 2*wSize, except when the user input buffer
     7232   * is directly used as sliding window.
     7233   */
     7234
     7235  this.prev = null;
     7236  /* Link to older string with same hash index. To limit the size of this
     7237   * array to 64K, this link is maintained only for the last 32K strings.
     7238   * An index in this array is thus a window index modulo 32K.
     7239   */
     7240
     7241  this.head = null;   /* Heads of the hash chains or NIL. */
     7242
     7243  this.ins_h = 0;       /* hash index of string to be inserted */
     7244  this.hash_size = 0;   /* number of elements in hash table */
     7245  this.hash_bits = 0;   /* log2(hash_size) */
     7246  this.hash_mask = 0;   /* hash_size-1 */
     7247
     7248  this.hash_shift = 0;
     7249  /* Number of bits by which ins_h must be shifted at each input
     7250   * step. It must be such that after MIN_MATCH steps, the oldest
     7251   * byte no longer takes part in the hash key, that is:
     7252   *   hash_shift * MIN_MATCH >= hash_bits
     7253   */
     7254
     7255  this.block_start = 0;
     7256  /* Window position at the beginning of the current output block. Gets
     7257   * negative when the window is moved backwards.
     7258   */
     7259
     7260  this.match_length = 0;      /* length of best match */
     7261  this.prev_match = 0;        /* previous match */
     7262  this.match_available = 0;   /* set if previous match exists */
     7263  this.strstart = 0;          /* start of string to insert */
     7264  this.match_start = 0;       /* start of matching string */
     7265  this.lookahead = 0;         /* number of valid bytes ahead in window */
     7266
     7267  this.prev_length = 0;
     7268  /* Length of the best match at previous step. Matches not greater than this
     7269   * are discarded. This is used in the lazy match evaluation.
     7270   */
     7271
     7272  this.max_chain_length = 0;
     7273  /* To speed up deflation, hash chains are never searched beyond this
     7274   * length.  A higher limit improves compression ratio but degrades the
     7275   * speed.
     7276   */
     7277
     7278  this.max_lazy_match = 0;
     7279  /* Attempt to find a better match only when the current match is strictly
     7280   * smaller than this value. This mechanism is used only for compression
     7281   * levels >= 4.
     7282   */
     7283  // That's alias to max_lazy_match, don't use directly
     7284  //this.max_insert_length = 0;
     7285  /* Insert new strings in the hash table only if the match length is not
     7286   * greater than this length. This saves time but degrades compression.
     7287   * max_insert_length is used only for compression levels <= 3.
     7288   */
     7289
     7290  this.level = 0;     /* compression level (1..9) */
     7291  this.strategy = 0;  /* favor or force Huffman coding*/
     7292
     7293  this.good_match = 0;
     7294  /* Use a faster search when the previous match is longer than this */
     7295
     7296  this.nice_match = 0; /* Stop searching when current match exceeds this */
     7297
     7298              /* used by trees.c: */
     7299
     7300  /* Didn't use ct_data typedef below to suppress compiler warning */
     7301
     7302  // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
     7303  // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
     7304  // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
     7305
     7306  // Use flat array of DOUBLE size, with interleaved fata,
     7307  // because JS does not support effective
     7308  this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
     7309  this.dyn_dtree  = new utils.Buf16((2 * D_CODES + 1) * 2);
     7310  this.bl_tree    = new utils.Buf16((2 * BL_CODES + 1) * 2);
     7311  zero(this.dyn_ltree);
     7312  zero(this.dyn_dtree);
     7313  zero(this.bl_tree);
     7314
     7315  this.l_desc   = null;         /* desc. for literal tree */
     7316  this.d_desc   = null;         /* desc. for distance tree */
     7317  this.bl_desc  = null;         /* desc. for bit length tree */
     7318
     7319  //ush bl_count[MAX_BITS+1];
     7320  this.bl_count = new utils.Buf16(MAX_BITS + 1);
     7321  /* number of codes at each bit length for an optimal tree */
     7322
     7323  //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
     7324  this.heap = new utils.Buf16(2 * L_CODES + 1);  /* heap used to build the Huffman trees */
     7325  zero(this.heap);
     7326
     7327  this.heap_len = 0;               /* number of elements in the heap */
     7328  this.heap_max = 0;               /* element of largest frequency */
     7329  /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
     7330   * The same heap array is used to build all trees.
     7331   */
     7332
     7333  this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
     7334  zero(this.depth);
     7335  /* Depth of each subtree used as tie breaker for trees of equal frequency
     7336   */
     7337
     7338  this.l_buf = 0;          /* buffer index for literals or lengths */
     7339
     7340  this.lit_bufsize = 0;
     7341  /* Size of match buffer for literals/lengths.  There are 4 reasons for
     7342   * limiting lit_bufsize to 64K:
     7343   *   - frequencies can be kept in 16 bit counters
     7344   *   - if compression is not successful for the first block, all input
     7345   *     data is still in the window so we can still emit a stored block even
     7346   *     when input comes from standard input.  (This can also be done for
     7347   *     all blocks if lit_bufsize is not greater than 32K.)
     7348   *   - if compression is not successful for a file smaller than 64K, we can
     7349   *     even emit a stored file instead of a stored block (saving 5 bytes).
     7350   *     This is applicable only for zip (not gzip or zlib).
     7351   *   - creating new Huffman trees less frequently may not provide fast
     7352   *     adaptation to changes in the input data statistics. (Take for
     7353   *     example a binary file with poorly compressible code followed by
     7354   *     a highly compressible string table.) Smaller buffer sizes give
     7355   *     fast adaptation but have of course the overhead of transmitting
     7356   *     trees more frequently.
     7357   *   - I can't count above 4
     7358   */
     7359
     7360  this.last_lit = 0;      /* running index in l_buf */
     7361
     7362  this.d_buf = 0;
     7363  /* Buffer index for distances. To simplify the code, d_buf and l_buf have
     7364   * the same number of elements. To use different lengths, an extra flag
     7365   * array would be necessary.
     7366   */
     7367
     7368  this.opt_len = 0;       /* bit length of current block with optimal trees */
     7369  this.static_len = 0;    /* bit length of current block with static trees */
     7370  this.matches = 0;       /* number of string matches in current block */
     7371  this.insert = 0;        /* bytes at end of window left to insert */
     7372
     7373
     7374  this.bi_buf = 0;
     7375  /* Output buffer. bits are inserted starting at the bottom (least
     7376   * significant bits).
     7377   */
     7378  this.bi_valid = 0;
     7379  /* Number of valid bits in bi_buf.  All bits above the last valid bit
     7380   * are always zero.
     7381   */
     7382
     7383  // Used for window memory init. We safely ignore it for JS. That makes
     7384  // sense only for pointers and memory check tools.
     7385  //this.high_water = 0;
     7386  /* High water mark offset in window for initialized bytes -- bytes above
     7387   * this are set to zero in order to avoid memory check warnings when
     7388   * longest match routines access bytes past the input.  This is then
     7389   * updated to the new high water mark.
     7390   */
     7391}
     7392
     7393
     7394function deflateResetKeep(strm) {
     7395  var s;
     7396
     7397  if (!strm || !strm.state) {
     7398    return err(strm, Z_STREAM_ERROR);
     7399  }
     7400
     7401  strm.total_in = strm.total_out = 0;
     7402  strm.data_type = Z_UNKNOWN;
     7403
     7404  s = strm.state;
     7405  s.pending = 0;
     7406  s.pending_out = 0;
     7407
     7408  if (s.wrap < 0) {
     7409    s.wrap = -s.wrap;
     7410    /* was made negative by deflate(..., Z_FINISH); */
     7411  }
     7412  s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
     7413  strm.adler = (s.wrap === 2) ?
     7414    0  // crc32(0, Z_NULL, 0)
     7415  :
     7416    1; // adler32(0, Z_NULL, 0)
     7417  s.last_flush = Z_NO_FLUSH;
     7418  trees._tr_init(s);
     7419  return Z_OK;
     7420}
     7421
     7422
     7423function deflateReset(strm) {
     7424  var ret = deflateResetKeep(strm);
     7425  if (ret === Z_OK) {
     7426    lm_init(strm.state);
     7427  }
     7428  return ret;
     7429}
     7430
     7431
     7432function deflateSetHeader(strm, head) {
     7433  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
     7434  if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
     7435  strm.state.gzhead = head;
     7436  return Z_OK;
     7437}
     7438
     7439
     7440function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
     7441  if (!strm) { // === Z_NULL
     7442    return Z_STREAM_ERROR;
     7443  }
     7444  var wrap = 1;
     7445
     7446  if (level === Z_DEFAULT_COMPRESSION) {
     7447    level = 6;
     7448  }
     7449
     7450  if (windowBits < 0) { /* suppress zlib wrapper */
     7451    wrap = 0;
     7452    windowBits = -windowBits;
     7453  }
     7454
     7455  else if (windowBits > 15) {
     7456    wrap = 2;           /* write gzip wrapper instead */
     7457    windowBits -= 16;
     7458  }
     7459
     7460
     7461  if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
     7462    windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
     7463    strategy < 0 || strategy > Z_FIXED) {
     7464    return err(strm, Z_STREAM_ERROR);
     7465  }
     7466
     7467
     7468  if (windowBits === 8) {
     7469    windowBits = 9;
     7470  }
     7471  /* until 256-byte window bug fixed */
     7472
     7473  var s = new DeflateState();
     7474
     7475  strm.state = s;
     7476  s.strm = strm;
     7477
     7478  s.wrap = wrap;
     7479  s.gzhead = null;
     7480  s.w_bits = windowBits;
     7481  s.w_size = 1 << s.w_bits;
     7482  s.w_mask = s.w_size - 1;
     7483
     7484  s.hash_bits = memLevel + 7;
     7485  s.hash_size = 1 << s.hash_bits;
     7486  s.hash_mask = s.hash_size - 1;
     7487  s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
     7488
     7489  s.window = new utils.Buf8(s.w_size * 2);
     7490  s.head = new utils.Buf16(s.hash_size);
     7491  s.prev = new utils.Buf16(s.w_size);
     7492
     7493  // Don't need mem init magic for JS.
     7494  //s.high_water = 0;  /* nothing written to s->window yet */
     7495
     7496  s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
     7497
     7498  s.pending_buf_size = s.lit_bufsize * 4;
     7499
     7500  //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
     7501  //s->pending_buf = (uchf *) overlay;
     7502  s.pending_buf = new utils.Buf8(s.pending_buf_size);
     7503
     7504  // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
     7505  //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
     7506  s.d_buf = 1 * s.lit_bufsize;
     7507
     7508  //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
     7509  s.l_buf = (1 + 2) * s.lit_bufsize;
     7510
     7511  s.level = level;
     7512  s.strategy = strategy;
     7513  s.method = method;
     7514
     7515  return deflateReset(strm);
     7516}
     7517
     7518function deflateInit(strm, level) {
     7519  return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
     7520}
     7521
     7522
     7523function deflate(strm, flush) {
     7524  var old_flush, s;
     7525  var beg, val; // for gzip header write only
     7526
     7527  if (!strm || !strm.state ||
     7528    flush > Z_BLOCK || flush < 0) {
     7529    return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
     7530  }
     7531
     7532  s = strm.state;
     7533
     7534  if (!strm.output ||
     7535      (!strm.input && strm.avail_in !== 0) ||
     7536      (s.status === FINISH_STATE && flush !== Z_FINISH)) {
     7537    return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
     7538  }
     7539
     7540  s.strm = strm; /* just in case */
     7541  old_flush = s.last_flush;
     7542  s.last_flush = flush;
     7543
     7544  /* Write the header */
     7545  if (s.status === INIT_STATE) {
     7546
     7547    if (s.wrap === 2) { // GZIP header
     7548      strm.adler = 0;  //crc32(0L, Z_NULL, 0);
     7549      put_byte(s, 31);
     7550      put_byte(s, 139);
     7551      put_byte(s, 8);
     7552      if (!s.gzhead) { // s->gzhead == Z_NULL
     7553        put_byte(s, 0);
     7554        put_byte(s, 0);
     7555        put_byte(s, 0);
     7556        put_byte(s, 0);
     7557        put_byte(s, 0);
     7558        put_byte(s, s.level === 9 ? 2 :
     7559                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
     7560                     4 : 0));
     7561        put_byte(s, OS_CODE);
     7562        s.status = BUSY_STATE;
     7563      }
     7564      else {
     7565        put_byte(s, (s.gzhead.text ? 1 : 0) +
     7566                    (s.gzhead.hcrc ? 2 : 0) +
     7567                    (!s.gzhead.extra ? 0 : 4) +
     7568                    (!s.gzhead.name ? 0 : 8) +
     7569                    (!s.gzhead.comment ? 0 : 16)
     7570                );
     7571        put_byte(s, s.gzhead.time & 0xff);
     7572        put_byte(s, (s.gzhead.time >> 8) & 0xff);
     7573        put_byte(s, (s.gzhead.time >> 16) & 0xff);
     7574        put_byte(s, (s.gzhead.time >> 24) & 0xff);
     7575        put_byte(s, s.level === 9 ? 2 :
     7576                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
     7577                     4 : 0));
     7578        put_byte(s, s.gzhead.os & 0xff);
     7579        if (s.gzhead.extra && s.gzhead.extra.length) {
     7580          put_byte(s, s.gzhead.extra.length & 0xff);
     7581          put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
     7582        }
     7583        if (s.gzhead.hcrc) {
     7584          strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
     7585        }
     7586        s.gzindex = 0;
     7587        s.status = EXTRA_STATE;
     7588      }
     7589    }
     7590    else // DEFLATE header
     7591    {
     7592      var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
     7593      var level_flags = -1;
     7594
     7595      if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
     7596        level_flags = 0;
     7597      } else if (s.level < 6) {
     7598        level_flags = 1;
     7599      } else if (s.level === 6) {
     7600        level_flags = 2;
     7601      } else {
     7602        level_flags = 3;
     7603      }
     7604      header |= (level_flags << 6);
     7605      if (s.strstart !== 0) { header |= PRESET_DICT; }
     7606      header += 31 - (header % 31);
     7607
     7608      s.status = BUSY_STATE;
     7609      putShortMSB(s, header);
     7610
     7611      /* Save the adler32 of the preset dictionary: */
     7612      if (s.strstart !== 0) {
     7613        putShortMSB(s, strm.adler >>> 16);
     7614        putShortMSB(s, strm.adler & 0xffff);
     7615      }
     7616      strm.adler = 1; // adler32(0L, Z_NULL, 0);
     7617    }
     7618  }
     7619
     7620//#ifdef GZIP
     7621  if (s.status === EXTRA_STATE) {
     7622    if (s.gzhead.extra/* != Z_NULL*/) {
     7623      beg = s.pending;  /* start of bytes to update crc */
     7624
     7625      while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
     7626        if (s.pending === s.pending_buf_size) {
     7627          if (s.gzhead.hcrc && s.pending > beg) {
     7628            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
     7629          }
     7630          flush_pending(strm);
     7631          beg = s.pending;
     7632          if (s.pending === s.pending_buf_size) {
     7633            break;
     7634          }
     7635        }
     7636        put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
     7637        s.gzindex++;
     7638      }
     7639      if (s.gzhead.hcrc && s.pending > beg) {
     7640        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
     7641      }
     7642      if (s.gzindex === s.gzhead.extra.length) {
     7643        s.gzindex = 0;
     7644        s.status = NAME_STATE;
     7645      }
     7646    }
     7647    else {
     7648      s.status = NAME_STATE;
     7649    }
     7650  }
     7651  if (s.status === NAME_STATE) {
     7652    if (s.gzhead.name/* != Z_NULL*/) {
     7653      beg = s.pending;  /* start of bytes to update crc */
     7654      //int val;
     7655
     7656      do {
     7657        if (s.pending === s.pending_buf_size) {
     7658          if (s.gzhead.hcrc && s.pending > beg) {
     7659            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
     7660          }
     7661          flush_pending(strm);
     7662          beg = s.pending;
     7663          if (s.pending === s.pending_buf_size) {
     7664            val = 1;
     7665            break;
     7666          }
     7667        }
     7668        // JS specific: little magic to add zero terminator to end of string
     7669        if (s.gzindex < s.gzhead.name.length) {
     7670          val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
     7671        } else {
     7672          val = 0;
     7673        }
     7674        put_byte(s, val);
     7675      } while (val !== 0);
     7676
     7677      if (s.gzhead.hcrc && s.pending > beg) {
     7678        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
     7679      }
     7680      if (val === 0) {
     7681        s.gzindex = 0;
     7682        s.status = COMMENT_STATE;
     7683      }
     7684    }
     7685    else {
     7686      s.status = COMMENT_STATE;
     7687    }
     7688  }
     7689  if (s.status === COMMENT_STATE) {
     7690    if (s.gzhead.comment/* != Z_NULL*/) {
     7691      beg = s.pending;  /* start of bytes to update crc */
     7692      //int val;
     7693
     7694      do {
     7695        if (s.pending === s.pending_buf_size) {
     7696          if (s.gzhead.hcrc && s.pending > beg) {
     7697            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
     7698          }
     7699          flush_pending(strm);
     7700          beg = s.pending;
     7701          if (s.pending === s.pending_buf_size) {
     7702            val = 1;
     7703            break;
     7704          }
     7705        }
     7706        // JS specific: little magic to add zero terminator to end of string
     7707        if (s.gzindex < s.gzhead.comment.length) {
     7708          val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
     7709        } else {
     7710          val = 0;
     7711        }
     7712        put_byte(s, val);
     7713      } while (val !== 0);
     7714
     7715      if (s.gzhead.hcrc && s.pending > beg) {
     7716        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
     7717      }
     7718      if (val === 0) {
     7719        s.status = HCRC_STATE;
     7720      }
     7721    }
     7722    else {
     7723      s.status = HCRC_STATE;
     7724    }
     7725  }
     7726  if (s.status === HCRC_STATE) {
     7727    if (s.gzhead.hcrc) {
     7728      if (s.pending + 2 > s.pending_buf_size) {
     7729        flush_pending(strm);
     7730      }
     7731      if (s.pending + 2 <= s.pending_buf_size) {
     7732        put_byte(s, strm.adler & 0xff);
     7733        put_byte(s, (strm.adler >> 8) & 0xff);
     7734        strm.adler = 0; //crc32(0L, Z_NULL, 0);
     7735        s.status = BUSY_STATE;
     7736      }
     7737    }
     7738    else {
     7739      s.status = BUSY_STATE;
     7740    }
     7741  }
     7742//#endif
     7743
     7744  /* Flush as much pending output as possible */
     7745  if (s.pending !== 0) {
     7746    flush_pending(strm);
     7747    if (strm.avail_out === 0) {
     7748      /* Since avail_out is 0, deflate will be called again with
     7749       * more output space, but possibly with both pending and
     7750       * avail_in equal to zero. There won't be anything to do,
     7751       * but this is not an error situation so make sure we
     7752       * return OK instead of BUF_ERROR at next call of deflate:
     7753       */
     7754      s.last_flush = -1;
     7755      return Z_OK;
     7756    }
     7757
     7758    /* Make sure there is something to do and avoid duplicate consecutive
     7759     * flushes. For repeated and useless calls with Z_FINISH, we keep
     7760     * returning Z_STREAM_END instead of Z_BUF_ERROR.
     7761     */
     7762  } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
     7763    flush !== Z_FINISH) {
     7764    return err(strm, Z_BUF_ERROR);
     7765  }
     7766
     7767  /* User must not provide more input after the first FINISH: */
     7768  if (s.status === FINISH_STATE && strm.avail_in !== 0) {
     7769    return err(strm, Z_BUF_ERROR);
     7770  }
     7771
     7772  /* Start a new block or continue the current one.
     7773   */
     7774  if (strm.avail_in !== 0 || s.lookahead !== 0 ||
     7775    (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
     7776    var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
     7777      (s.strategy === Z_RLE ? deflate_rle(s, flush) :
     7778        configuration_table[s.level].func(s, flush));
     7779
     7780    if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
     7781      s.status = FINISH_STATE;
     7782    }
     7783    if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
     7784      if (strm.avail_out === 0) {
     7785        s.last_flush = -1;
     7786        /* avoid BUF_ERROR next call, see above */
     7787      }
     7788      return Z_OK;
     7789      /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
     7790       * of deflate should use the same flush parameter to make sure
     7791       * that the flush is complete. So we don't have to output an
     7792       * empty block here, this will be done at next call. This also
     7793       * ensures that for a very small output buffer, we emit at most
     7794       * one empty block.
     7795       */
     7796    }
     7797    if (bstate === BS_BLOCK_DONE) {
     7798      if (flush === Z_PARTIAL_FLUSH) {
     7799        trees._tr_align(s);
     7800      }
     7801      else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
     7802
     7803        trees._tr_stored_block(s, 0, 0, false);
     7804        /* For a full flush, this empty block will be recognized
     7805         * as a special marker by inflate_sync().
     7806         */
     7807        if (flush === Z_FULL_FLUSH) {
     7808          /*** CLEAR_HASH(s); ***/             /* forget history */
     7809          zero(s.head); // Fill with NIL (= 0);
     7810
     7811          if (s.lookahead === 0) {
     7812            s.strstart = 0;
     7813            s.block_start = 0;
     7814            s.insert = 0;
     7815          }
     7816        }
     7817      }
     7818      flush_pending(strm);
     7819      if (strm.avail_out === 0) {
     7820        s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
     7821        return Z_OK;
     7822      }
     7823    }
     7824  }
     7825  //Assert(strm->avail_out > 0, "bug2");
     7826  //if (strm.avail_out <= 0) { throw new Error("bug2");}
     7827
     7828  if (flush !== Z_FINISH) { return Z_OK; }
     7829  if (s.wrap <= 0) { return Z_STREAM_END; }
     7830
     7831  /* Write the trailer */
     7832  if (s.wrap === 2) {
     7833    put_byte(s, strm.adler & 0xff);
     7834    put_byte(s, (strm.adler >> 8) & 0xff);
     7835    put_byte(s, (strm.adler >> 16) & 0xff);
     7836    put_byte(s, (strm.adler >> 24) & 0xff);
     7837    put_byte(s, strm.total_in & 0xff);
     7838    put_byte(s, (strm.total_in >> 8) & 0xff);
     7839    put_byte(s, (strm.total_in >> 16) & 0xff);
     7840    put_byte(s, (strm.total_in >> 24) & 0xff);
     7841  }
     7842  else
     7843  {
     7844    putShortMSB(s, strm.adler >>> 16);
     7845    putShortMSB(s, strm.adler & 0xffff);
     7846  }
     7847
     7848  flush_pending(strm);
     7849  /* If avail_out is zero, the application will call deflate again
     7850   * to flush the rest.
     7851   */
     7852  if (s.wrap > 0) { s.wrap = -s.wrap; }
     7853  /* write the trailer only once! */
     7854  return s.pending !== 0 ? Z_OK : Z_STREAM_END;
     7855}
     7856
     7857function deflateEnd(strm) {
     7858  var status;
     7859
     7860  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
     7861    return Z_STREAM_ERROR;
     7862  }
     7863
     7864  status = strm.state.status;
     7865  if (status !== INIT_STATE &&
     7866    status !== EXTRA_STATE &&
     7867    status !== NAME_STATE &&
     7868    status !== COMMENT_STATE &&
     7869    status !== HCRC_STATE &&
     7870    status !== BUSY_STATE &&
     7871    status !== FINISH_STATE
     7872  ) {
     7873    return err(strm, Z_STREAM_ERROR);
     7874  }
     7875
     7876  strm.state = null;
     7877
     7878  return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
     7879}
     7880
     7881
     7882/* =========================================================================
     7883 * Initializes the compression dictionary from the given byte
     7884 * sequence without producing any compressed output.
     7885 */
     7886function deflateSetDictionary(strm, dictionary) {
     7887  var dictLength = dictionary.length;
     7888
     7889  var s;
     7890  var str, n;
     7891  var wrap;
     7892  var avail;
     7893  var next;
     7894  var input;
     7895  var tmpDict;
     7896
     7897  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
     7898    return Z_STREAM_ERROR;
     7899  }
     7900
     7901  s = strm.state;
     7902  wrap = s.wrap;
     7903
     7904  if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
     7905    return Z_STREAM_ERROR;
     7906  }
     7907
     7908  /* when using zlib wrappers, compute Adler-32 for provided dictionary */
     7909  if (wrap === 1) {
     7910    /* adler32(strm->adler, dictionary, dictLength); */
     7911    strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
     7912  }
     7913
     7914  s.wrap = 0;   /* avoid computing Adler-32 in read_buf */
     7915
     7916  /* if dictionary would fill window, just replace the history */
     7917  if (dictLength >= s.w_size) {
     7918    if (wrap === 0) {            /* already empty otherwise */
     7919      /*** CLEAR_HASH(s); ***/
     7920      zero(s.head); // Fill with NIL (= 0);
     7921      s.strstart = 0;
     7922      s.block_start = 0;
     7923      s.insert = 0;
     7924    }
     7925    /* use the tail */
     7926    // dictionary = dictionary.slice(dictLength - s.w_size);
     7927    tmpDict = new utils.Buf8(s.w_size);
     7928    utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
     7929    dictionary = tmpDict;
     7930    dictLength = s.w_size;
     7931  }
     7932  /* insert dictionary into window and hash */
     7933  avail = strm.avail_in;
     7934  next = strm.next_in;
     7935  input = strm.input;
     7936  strm.avail_in = dictLength;
     7937  strm.next_in = 0;
     7938  strm.input = dictionary;
     7939  fill_window(s);
     7940  while (s.lookahead >= MIN_MATCH) {
     7941    str = s.strstart;
     7942    n = s.lookahead - (MIN_MATCH - 1);
     7943    do {
     7944      /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
     7945      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
     7946
     7947      s.prev[str & s.w_mask] = s.head[s.ins_h];
     7948
     7949      s.head[s.ins_h] = str;
     7950      str++;
     7951    } while (--n);
     7952    s.strstart = str;
     7953    s.lookahead = MIN_MATCH - 1;
     7954    fill_window(s);
     7955  }
     7956  s.strstart += s.lookahead;
     7957  s.block_start = s.strstart;
     7958  s.insert = s.lookahead;
     7959  s.lookahead = 0;
     7960  s.match_length = s.prev_length = MIN_MATCH - 1;
     7961  s.match_available = 0;
     7962  strm.next_in = next;
     7963  strm.input = input;
     7964  strm.avail_in = avail;
     7965  s.wrap = wrap;
     7966  return Z_OK;
     7967}
     7968
     7969
     7970exports.deflateInit = deflateInit;
     7971exports.deflateInit2 = deflateInit2;
     7972exports.deflateReset = deflateReset;
     7973exports.deflateResetKeep = deflateResetKeep;
     7974exports.deflateSetHeader = deflateSetHeader;
     7975exports.deflate = deflate;
     7976exports.deflateEnd = deflateEnd;
     7977exports.deflateSetDictionary = deflateSetDictionary;
     7978exports.deflateInfo = 'pako deflate (from Nodeca project)';
     7979
     7980/* Not implemented
     7981exports.deflateBound = deflateBound;
     7982exports.deflateCopy = deflateCopy;
     7983exports.deflateParams = deflateParams;
     7984exports.deflatePending = deflatePending;
     7985exports.deflatePrime = deflatePrime;
     7986exports.deflateTune = deflateTune;
     7987*/
     7988
     7989},{"../utils/common":62,"./adler32":64,"./crc32":66,"./messages":72,"./trees":73}],68:[function(require,module,exports){
     7990'use strict';
     7991
     7992// (C) 1995-2013 Jean-loup Gailly and Mark Adler
     7993// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
     7994//
     7995// This software is provided 'as-is', without any express or implied
     7996// warranty. In no event will the authors be held liable for any damages
     7997// arising from the use of this software.
     7998//
     7999// Permission is granted to anyone to use this software for any purpose,
     8000// including commercial applications, and to alter it and redistribute it
     8001// freely, subject to the following restrictions:
     8002//
     8003// 1. The origin of this software must not be misrepresented; you must not
     8004//   claim that you wrote the original software. If you use this software
     8005//   in a product, an acknowledgment in the product documentation would be
     8006//   appreciated but is not required.
     8007// 2. Altered source versions must be plainly marked as such, and must not be
     8008//   misrepresented as being the original software.
     8009// 3. This notice may not be removed or altered from any source distribution.
     8010
     8011function GZheader() {
     8012  /* true if compressed data believed to be text */
     8013  this.text       = 0;
     8014  /* modification time */
     8015  this.time       = 0;
     8016  /* extra flags (not used when writing a gzip file) */
     8017  this.xflags     = 0;
     8018  /* operating system */
     8019  this.os         = 0;
     8020  /* pointer to extra field or Z_NULL if none */
     8021  this.extra      = null;
     8022  /* extra field length (valid if extra != Z_NULL) */
     8023  this.extra_len  = 0; // Actually, we don't need it in JS,
     8024                       // but leave for few code modifications
     8025
     8026  //
     8027  // Setup limits is not necessary because in js we should not preallocate memory
     8028  // for inflate use constant limit in 65536 bytes
     8029  //
     8030
     8031  /* space at extra (only when reading header) */
     8032  // this.extra_max  = 0;
     8033  /* pointer to zero-terminated file name or Z_NULL */
     8034  this.name       = '';
     8035  /* space at name (only when reading header) */
     8036  // this.name_max   = 0;
     8037  /* pointer to zero-terminated comment or Z_NULL */
     8038  this.comment    = '';
     8039  /* space at comment (only when reading header) */
     8040  // this.comm_max   = 0;
     8041  /* true if there was or will be a header crc */
     8042  this.hcrc       = 0;
     8043  /* true when done reading gzip header (not used when writing a gzip file) */
     8044  this.done       = false;
     8045}
     8046
     8047module.exports = GZheader;
     8048
     8049},{}],69:[function(require,module,exports){
     8050'use strict';
     8051
     8052// (C) 1995-2013 Jean-loup Gailly and Mark Adler
     8053// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
     8054//
     8055// This software is provided 'as-is', without any express or implied
     8056// warranty. In no event will the authors be held liable for any damages
     8057// arising from the use of this software.
     8058//
     8059// Permission is granted to anyone to use this software for any purpose,
     8060// including commercial applications, and to alter it and redistribute it
     8061// freely, subject to the following restrictions:
     8062//
     8063// 1. The origin of this software must not be misrepresented; you must not
     8064//   claim that you wrote the original software. If you use this software
     8065//   in a product, an acknowledgment in the product documentation would be
     8066//   appreciated but is not required.
     8067// 2. Altered source versions must be plainly marked as such, and must not be
     8068//   misrepresented as being the original software.
     8069// 3. This notice may not be removed or altered from any source distribution.
     8070
     8071// See state defs from inflate.js
     8072var BAD = 30;       /* got a data error -- remain here until reset */
     8073var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
     8074
     8075/*
     8076   Decode literal, length, and distance codes and write out the resulting
     8077   literal and match bytes until either not enough input or output is
     8078   available, an end-of-block is encountered, or a data error is encountered.
     8079   When large enough input and output buffers are supplied to inflate(), for
     8080   example, a 16K input buffer and a 64K output buffer, more than 95% of the
     8081   inflate execution time is spent in this routine.
     8082
     8083   Entry assumptions:
     8084
     8085        state.mode === LEN
     8086        strm.avail_in >= 6
     8087        strm.avail_out >= 258
     8088        start >= strm.avail_out
     8089        state.bits < 8
     8090
     8091   On return, state.mode is one of:
     8092
     8093        LEN -- ran out of enough output space or enough available input
     8094        TYPE -- reached end of block code, inflate() to interpret next block
     8095        BAD -- error in block data
     8096
     8097   Notes:
     8098
     8099    - The maximum input bits used by a length/distance pair is 15 bits for the
     8100      length code, 5 bits for the length extra, 15 bits for the distance code,
     8101      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
     8102      Therefore if strm.avail_in >= 6, then there is enough input to avoid
     8103      checking for available input while decoding.
     8104
     8105    - The maximum bytes that a single length/distance pair can output is 258
     8106      bytes, which is the maximum length that can be coded.  inflate_fast()
     8107      requires strm.avail_out >= 258 for each loop to avoid checking for
     8108      output space.
     8109 */
     8110module.exports = function inflate_fast(strm, start) {
     8111  var state;
     8112  var _in;                    /* local strm.input */
     8113  var last;                   /* have enough input while in < last */
     8114  var _out;                   /* local strm.output */
     8115  var beg;                    /* inflate()'s initial strm.output */
     8116  var end;                    /* while out < end, enough space available */
     8117//#ifdef INFLATE_STRICT
     8118  var dmax;                   /* maximum distance from zlib header */
     8119//#endif
     8120  var wsize;                  /* window size or zero if not using window */
     8121  var whave;                  /* valid bytes in the window */
     8122  var wnext;                  /* window write index */
     8123  // Use `s_window` instead `window`, avoid conflict with instrumentation tools
     8124  var s_window;               /* allocated sliding window, if wsize != 0 */
     8125  var hold;                   /* local strm.hold */
     8126  var bits;                   /* local strm.bits */
     8127  var lcode;                  /* local strm.lencode */
     8128  var dcode;                  /* local strm.distcode */
     8129  var lmask;                  /* mask for first level of length codes */
     8130  var dmask;                  /* mask for first level of distance codes */
     8131  var here;                   /* retrieved table entry */
     8132  var op;                     /* code bits, operation, extra bits, or */
     8133                              /*  window position, window bytes to copy */
     8134  var len;                    /* match length, unused bytes */
     8135  var dist;                   /* match distance */
     8136  var from;                   /* where to copy match from */
     8137  var from_source;
     8138
     8139
     8140  var input, output; // JS specific, because we have no pointers
     8141
     8142  /* copy state to local variables */
     8143  state = strm.state;
     8144  //here = state.here;
     8145  _in = strm.next_in;
     8146  input = strm.input;
     8147  last = _in + (strm.avail_in - 5);
     8148  _out = strm.next_out;
     8149  output = strm.output;
     8150  beg = _out - (start - strm.avail_out);
     8151  end = _out + (strm.avail_out - 257);
     8152//#ifdef INFLATE_STRICT
     8153  dmax = state.dmax;
     8154//#endif
     8155  wsize = state.wsize;
     8156  whave = state.whave;
     8157  wnext = state.wnext;
     8158  s_window = state.window;
     8159  hold = state.hold;
     8160  bits = state.bits;
     8161  lcode = state.lencode;
     8162  dcode = state.distcode;
     8163  lmask = (1 << state.lenbits) - 1;
     8164  dmask = (1 << state.distbits) - 1;
     8165
     8166
     8167  /* decode literals and length/distances until end-of-block or not enough
     8168     input data or output space */
     8169
     8170  top:
     8171  do {
     8172    if (bits < 15) {
     8173      hold += input[_in++] << bits;
     8174      bits += 8;
     8175      hold += input[_in++] << bits;
     8176      bits += 8;
     8177    }
     8178
     8179    here = lcode[hold & lmask];
     8180
     8181    dolen:
     8182    for (;;) { // Goto emulation
     8183      op = here >>> 24/*here.bits*/;
     8184      hold >>>= op;
     8185      bits -= op;
     8186      op = (here >>> 16) & 0xff/*here.op*/;
     8187      if (op === 0) {                          /* literal */
     8188        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
     8189        //        "inflate:         literal '%c'\n" :
     8190        //        "inflate:         literal 0x%02x\n", here.val));
     8191        output[_out++] = here & 0xffff/*here.val*/;
     8192      }
     8193      else if (op & 16) {                     /* length base */
     8194        len = here & 0xffff/*here.val*/;
     8195        op &= 15;                           /* number of extra bits */
     8196        if (op) {
     8197          if (bits < op) {
     8198            hold += input[_in++] << bits;
     8199            bits += 8;
     8200          }
     8201          len += hold & ((1 << op) - 1);
     8202          hold >>>= op;
     8203          bits -= op;
     8204        }
     8205        //Tracevv((stderr, "inflate:         length %u\n", len));
     8206        if (bits < 15) {
     8207          hold += input[_in++] << bits;
     8208          bits += 8;
     8209          hold += input[_in++] << bits;
     8210          bits += 8;
     8211        }
     8212        here = dcode[hold & dmask];
     8213
     8214        dodist:
     8215        for (;;) { // goto emulation
     8216          op = here >>> 24/*here.bits*/;
     8217          hold >>>= op;
     8218          bits -= op;
     8219          op = (here >>> 16) & 0xff/*here.op*/;
     8220
     8221          if (op & 16) {                      /* distance base */
     8222            dist = here & 0xffff/*here.val*/;
     8223            op &= 15;                       /* number of extra bits */
     8224            if (bits < op) {
     8225              hold += input[_in++] << bits;
     8226              bits += 8;
     8227              if (bits < op) {
     8228                hold += input[_in++] << bits;
     8229                bits += 8;
     8230              }
     8231            }
     8232            dist += hold & ((1 << op) - 1);
     8233//#ifdef INFLATE_STRICT
     8234            if (dist > dmax) {
     8235              strm.msg = 'invalid distance too far back';
     8236              state.mode = BAD;
     8237              break top;
     8238            }
     8239//#endif
     8240            hold >>>= op;
     8241            bits -= op;
     8242            //Tracevv((stderr, "inflate:         distance %u\n", dist));
     8243            op = _out - beg;                /* max distance in output */
     8244            if (dist > op) {                /* see if copy from window */
     8245              op = dist - op;               /* distance back in window */
     8246              if (op > whave) {
     8247                if (state.sane) {
     8248                  strm.msg = 'invalid distance too far back';
     8249                  state.mode = BAD;
     8250                  break top;
     8251                }
     8252
     8253// (!) This block is disabled in zlib defailts,
     8254// don't enable it for binary compatibility
     8255//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
     8256//                if (len <= op - whave) {
     8257//                  do {
     8258//                    output[_out++] = 0;
     8259//                  } while (--len);
     8260//                  continue top;
     8261//                }
     8262//                len -= op - whave;
     8263//                do {
     8264//                  output[_out++] = 0;
     8265//                } while (--op > whave);
     8266//                if (op === 0) {
     8267//                  from = _out - dist;
     8268//                  do {
     8269//                    output[_out++] = output[from++];
     8270//                  } while (--len);
     8271//                  continue top;
     8272//                }
     8273//#endif
     8274              }
     8275              from = 0; // window index
     8276              from_source = s_window;
     8277              if (wnext === 0) {           /* very common case */
     8278                from += wsize - op;
     8279                if (op < len) {         /* some from window */
     8280                  len -= op;
     8281                  do {
     8282                    output[_out++] = s_window[from++];
     8283                  } while (--op);
     8284                  from = _out - dist;  /* rest from output */
     8285                  from_source = output;
     8286                }
     8287              }
     8288              else if (wnext < op) {      /* wrap around window */
     8289                from += wsize + wnext - op;
     8290                op -= wnext;
     8291                if (op < len) {         /* some from end of window */
     8292                  len -= op;
     8293                  do {
     8294                    output[_out++] = s_window[from++];
     8295                  } while (--op);
     8296                  from = 0;
     8297                  if (wnext < len) {  /* some from start of window */
     8298                    op = wnext;
     8299                    len -= op;
     8300                    do {
     8301                      output[_out++] = s_window[from++];
     8302                    } while (--op);
     8303                    from = _out - dist;      /* rest from output */
     8304                    from_source = output;
     8305                  }
     8306                }
     8307              }
     8308              else {                      /* contiguous in window */
     8309                from += wnext - op;
     8310                if (op < len) {         /* some from window */
     8311                  len -= op;
     8312                  do {
     8313                    output[_out++] = s_window[from++];
     8314                  } while (--op);
     8315                  from = _out - dist;  /* rest from output */
     8316                  from_source = output;
     8317                }
     8318              }
     8319              while (len > 2) {
     8320                output[_out++] = from_source[from++];
     8321                output[_out++] = from_source[from++];
     8322                output[_out++] = from_source[from++];
     8323                len -= 3;
     8324              }
     8325              if (len) {
     8326                output[_out++] = from_source[from++];
     8327                if (len > 1) {
     8328                  output[_out++] = from_source[from++];
     8329                }
     8330              }
     8331            }
     8332            else {
     8333              from = _out - dist;          /* copy direct from output */
     8334              do {                        /* minimum length is three */
     8335                output[_out++] = output[from++];
     8336                output[_out++] = output[from++];
     8337                output[_out++] = output[from++];
     8338                len -= 3;
     8339              } while (len > 2);
     8340              if (len) {
     8341                output[_out++] = output[from++];
     8342                if (len > 1) {
     8343                  output[_out++] = output[from++];
     8344                }
     8345              }
     8346            }
     8347          }
     8348          else if ((op & 64) === 0) {          /* 2nd level distance code */
     8349            here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
     8350            continue dodist;
     8351          }
     8352          else {
     8353            strm.msg = 'invalid distance code';
     8354            state.mode = BAD;
     8355            break top;
     8356          }
     8357
     8358          break; // need to emulate goto via "continue"
     8359        }
     8360      }
     8361      else if ((op & 64) === 0) {              /* 2nd level length code */
     8362        here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
     8363        continue dolen;
     8364      }
     8365      else if (op & 32) {                     /* end-of-block */
     8366        //Tracevv((stderr, "inflate:         end of block\n"));
     8367        state.mode = TYPE;
     8368        break top;
     8369      }
     8370      else {
     8371        strm.msg = 'invalid literal/length code';
     8372        state.mode = BAD;
     8373        break top;
     8374      }
     8375
     8376      break; // need to emulate goto via "continue"
     8377    }
     8378  } while (_in < last && _out < end);
     8379
     8380  /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
     8381  len = bits >> 3;
     8382  _in -= len;
     8383  bits -= len << 3;
     8384  hold &= (1 << bits) - 1;
     8385
     8386  /* update state and return */
     8387  strm.next_in = _in;
     8388  strm.next_out = _out;
     8389  strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
     8390  strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
     8391  state.hold = hold;
     8392  state.bits = bits;
     8393  return;
     8394};
     8395
     8396},{}],70:[function(require,module,exports){
     8397'use strict';
     8398
     8399// (C) 1995-2013 Jean-loup Gailly and Mark Adler
     8400// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
     8401//
     8402// This software is provided 'as-is', without any express or implied
     8403// warranty. In no event will the authors be held liable for any damages
     8404// arising from the use of this software.
     8405//
     8406// Permission is granted to anyone to use this software for any purpose,
     8407// including commercial applications, and to alter it and redistribute it
     8408// freely, subject to the following restrictions:
     8409//
     8410// 1. The origin of this software must not be misrepresented; you must not
     8411//   claim that you wrote the original software. If you use this software
     8412//   in a product, an acknowledgment in the product documentation would be
     8413//   appreciated but is not required.
     8414// 2. Altered source versions must be plainly marked as such, and must not be
     8415//   misrepresented as being the original software.
     8416// 3. This notice may not be removed or altered from any source distribution.
     8417
     8418var utils         = require('../utils/common');
     8419var adler32       = require('./adler32');
     8420var crc32         = require('./crc32');
     8421var inflate_fast  = require('./inffast');
     8422var inflate_table = require('./inftrees');
     8423
     8424var CODES = 0;
     8425var LENS = 1;
     8426var DISTS = 2;
     8427
     8428/* Public constants ==========================================================*/
     8429/* ===========================================================================*/
     8430
     8431
     8432/* Allowed flush values; see deflate() and inflate() below for details */
     8433//var Z_NO_FLUSH      = 0;
     8434//var Z_PARTIAL_FLUSH = 1;
     8435//var Z_SYNC_FLUSH    = 2;
     8436//var Z_FULL_FLUSH    = 3;
     8437var Z_FINISH        = 4;
     8438var Z_BLOCK         = 5;
     8439var Z_TREES         = 6;
     8440
     8441
     8442/* Return codes for the compression/decompression functions. Negative values
     8443 * are errors, positive values are used for special but normal events.
     8444 */
     8445var Z_OK            = 0;
     8446var Z_STREAM_END    = 1;
     8447var Z_NEED_DICT     = 2;
     8448//var Z_ERRNO         = -1;
     8449var Z_STREAM_ERROR  = -2;
     8450var Z_DATA_ERROR    = -3;
     8451var Z_MEM_ERROR     = -4;
     8452var Z_BUF_ERROR     = -5;
     8453//var Z_VERSION_ERROR = -6;
     8454
     8455/* The deflate compression method */
     8456var Z_DEFLATED  = 8;
     8457
     8458
     8459/* STATES ====================================================================*/
     8460/* ===========================================================================*/
     8461
     8462
     8463var    HEAD = 1;       /* i: waiting for magic header */
     8464var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
     8465var    TIME = 3;       /* i: waiting for modification time (gzip) */
     8466var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
     8467var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
     8468var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
     8469var    NAME = 7;       /* i: waiting for end of file name (gzip) */
     8470var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
     8471var    HCRC = 9;       /* i: waiting for header crc (gzip) */
     8472var    DICTID = 10;    /* i: waiting for dictionary check value */
     8473var    DICT = 11;      /* waiting for inflateSetDictionary() call */
     8474var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
     8475var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
     8476var        STORED = 14;    /* i: waiting for stored size (length and complement) */
     8477var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
     8478var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
     8479var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
     8480var        LENLENS = 18;   /* i: waiting for code length code lengths */
     8481var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
     8482var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
     8483var            LEN = 21;       /* i: waiting for length/lit/eob code */
     8484var            LENEXT = 22;    /* i: waiting for length extra bits */
     8485var            DIST = 23;      /* i: waiting for distance code */
     8486var            DISTEXT = 24;   /* i: waiting for distance extra bits */
     8487var            MATCH = 25;     /* o: waiting for output space to copy string */
     8488var            LIT = 26;       /* o: waiting for output space to write literal */
     8489var    CHECK = 27;     /* i: waiting for 32-bit check value */
     8490var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
     8491var    DONE = 29;      /* finished check, done -- remain here until reset */
     8492var    BAD = 30;       /* got a data error -- remain here until reset */
     8493var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
     8494var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */
     8495
     8496/* ===========================================================================*/
     8497
     8498
     8499
     8500var ENOUGH_LENS = 852;
     8501var ENOUGH_DISTS = 592;
     8502//var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);
     8503
     8504var MAX_WBITS = 15;
     8505/* 32K LZ77 window */
     8506var DEF_WBITS = MAX_WBITS;
     8507
     8508
     8509function zswap32(q) {
     8510  return  (((q >>> 24) & 0xff) +
     8511          ((q >>> 8) & 0xff00) +
     8512          ((q & 0xff00) << 8) +
     8513          ((q & 0xff) << 24));
     8514}
     8515
     8516
     8517function InflateState() {
     8518  this.mode = 0;             /* current inflate mode */
     8519  this.last = false;          /* true if processing last block */
     8520  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
     8521  this.havedict = false;      /* true if dictionary provided */
     8522  this.flags = 0;             /* gzip header method and flags (0 if zlib) */
     8523  this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
     8524  this.check = 0;             /* protected copy of check value */
     8525  this.total = 0;             /* protected copy of output count */
     8526  // TODO: may be {}
     8527  this.head = null;           /* where to save gzip header information */
     8528
     8529  /* sliding window */
     8530  this.wbits = 0;             /* log base 2 of requested window size */
     8531  this.wsize = 0;             /* window size or zero if not using window */
     8532  this.whave = 0;             /* valid bytes in the window */
     8533  this.wnext = 0;             /* window write index */
     8534  this.window = null;         /* allocated sliding window, if needed */
     8535
     8536  /* bit accumulator */
     8537  this.hold = 0;              /* input bit accumulator */
     8538  this.bits = 0;              /* number of bits in "in" */
     8539
     8540  /* for string and stored block copying */
     8541  this.length = 0;            /* literal or length of data to copy */
     8542  this.offset = 0;            /* distance back to copy string from */
     8543
     8544  /* for table and code decoding */
     8545  this.extra = 0;             /* extra bits needed */
     8546
     8547  /* fixed and dynamic code tables */
     8548  this.lencode = null;          /* starting table for length/literal codes */
     8549  this.distcode = null;         /* starting table for distance codes */
     8550  this.lenbits = 0;           /* index bits for lencode */
     8551  this.distbits = 0;          /* index bits for distcode */
     8552
     8553  /* dynamic table building */
     8554  this.ncode = 0;             /* number of code length code lengths */
     8555  this.nlen = 0;              /* number of length code lengths */
     8556  this.ndist = 0;             /* number of distance code lengths */
     8557  this.have = 0;              /* number of code lengths in lens[] */
     8558  this.next = null;              /* next available space in codes[] */
     8559
     8560  this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
     8561  this.work = new utils.Buf16(288); /* work area for code table building */
     8562
     8563  /*
     8564   because we don't have pointers in js, we use lencode and distcode directly
     8565   as buffers so we don't need codes
     8566  */
     8567  //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
     8568  this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
     8569  this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
     8570  this.sane = 0;                   /* if false, allow invalid distance too far */
     8571  this.back = 0;                   /* bits back of last unprocessed length/lit */
     8572  this.was = 0;                    /* initial length of match */
     8573}
     8574
     8575function inflateResetKeep(strm) {
     8576  var state;
     8577
     8578  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
     8579  state = strm.state;
     8580  strm.total_in = strm.total_out = state.total = 0;
     8581  strm.msg = ''; /*Z_NULL*/
     8582  if (state.wrap) {       /* to support ill-conceived Java test suite */
     8583    strm.adler = state.wrap & 1;
     8584  }
     8585  state.mode = HEAD;
     8586  state.last = 0;
     8587  state.havedict = 0;
     8588  state.dmax = 32768;
     8589  state.head = null/*Z_NULL*/;
     8590  state.hold = 0;
     8591  state.bits = 0;
     8592  //state.lencode = state.distcode = state.next = state.codes;
     8593  state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
     8594  state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
     8595
     8596  state.sane = 1;
     8597  state.back = -1;
     8598  //Tracev((stderr, "inflate: reset\n"));
     8599  return Z_OK;
     8600}
     8601
     8602function inflateReset(strm) {
     8603  var state;
     8604
     8605  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
     8606  state = strm.state;
     8607  state.wsize = 0;
     8608  state.whave = 0;
     8609  state.wnext = 0;
     8610  return inflateResetKeep(strm);
     8611
     8612}
     8613
     8614function inflateReset2(strm, windowBits) {
     8615  var wrap;
     8616  var state;
     8617
     8618  /* get the state */
     8619  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
     8620  state = strm.state;
     8621
     8622  /* extract wrap request from windowBits parameter */
     8623  if (windowBits < 0) {
     8624    wrap = 0;
     8625    windowBits = -windowBits;
     8626  }
     8627  else {
     8628    wrap = (windowBits >> 4) + 1;
     8629    if (windowBits < 48) {
     8630      windowBits &= 15;
     8631    }
     8632  }
     8633
     8634  /* set number of window bits, free window if different */
     8635  if (windowBits && (windowBits < 8 || windowBits > 15)) {
     8636    return Z_STREAM_ERROR;
     8637  }
     8638  if (state.window !== null && state.wbits !== windowBits) {
     8639    state.window = null;
     8640  }
     8641
     8642  /* update state and reset the rest of it */
     8643  state.wrap = wrap;
     8644  state.wbits = windowBits;
     8645  return inflateReset(strm);
     8646}
     8647
     8648function inflateInit2(strm, windowBits) {
     8649  var ret;
     8650  var state;
     8651
     8652  if (!strm) { return Z_STREAM_ERROR; }
     8653  //strm.msg = Z_NULL;                 /* in case we return an error */
     8654
     8655  state = new InflateState();
     8656
     8657  //if (state === Z_NULL) return Z_MEM_ERROR;
     8658  //Tracev((stderr, "inflate: allocated\n"));
     8659  strm.state = state;
     8660  state.window = null/*Z_NULL*/;
     8661  ret = inflateReset2(strm, windowBits);
     8662  if (ret !== Z_OK) {
     8663    strm.state = null/*Z_NULL*/;
     8664  }
     8665  return ret;
     8666}
     8667
     8668function inflateInit(strm) {
     8669  return inflateInit2(strm, DEF_WBITS);
     8670}
     8671
     8672
     8673/*
     8674 Return state with length and distance decoding tables and index sizes set to
     8675 fixed code decoding.  Normally this returns fixed tables from inffixed.h.
     8676 If BUILDFIXED is defined, then instead this routine builds the tables the
     8677 first time it's called, and returns those tables the first time and
     8678 thereafter.  This reduces the size of the code by about 2K bytes, in
     8679 exchange for a little execution time.  However, BUILDFIXED should not be
     8680 used for threaded applications, since the rewriting of the tables and virgin
     8681 may not be thread-safe.
     8682 */
     8683var virgin = true;
     8684
     8685var lenfix, distfix; // We have no pointers in JS, so keep tables separate
     8686
     8687function fixedtables(state) {
     8688  /* build fixed huffman tables if first call (may not be thread safe) */
     8689  if (virgin) {
     8690    var sym;
     8691
     8692    lenfix = new utils.Buf32(512);
     8693    distfix = new utils.Buf32(32);
     8694
     8695    /* literal/length table */
     8696    sym = 0;
     8697    while (sym < 144) { state.lens[sym++] = 8; }
     8698    while (sym < 256) { state.lens[sym++] = 9; }
     8699    while (sym < 280) { state.lens[sym++] = 7; }
     8700    while (sym < 288) { state.lens[sym++] = 8; }
     8701
     8702    inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });
     8703
     8704    /* distance table */
     8705    sym = 0;
     8706    while (sym < 32) { state.lens[sym++] = 5; }
     8707
     8708    inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });
     8709
     8710    /* do this just once */
     8711    virgin = false;
     8712  }
     8713
     8714  state.lencode = lenfix;
     8715  state.lenbits = 9;
     8716  state.distcode = distfix;
     8717  state.distbits = 5;
     8718}
     8719
     8720
     8721/*
     8722 Update the window with the last wsize (normally 32K) bytes written before
     8723 returning.  If window does not exist yet, create it.  This is only called
     8724 when a window is already in use, or when output has been written during this
     8725 inflate call, but the end of the deflate stream has not been reached yet.
     8726 It is also called to create a window for dictionary data when a dictionary
     8727 is loaded.
     8728
     8729 Providing output buffers larger than 32K to inflate() should provide a speed
     8730 advantage, since only the last 32K of output is copied to the sliding window
     8731 upon return from inflate(), and since all distances after the first 32K of
     8732 output will fall in the output data, making match copies simpler and faster.
     8733 The advantage may be dependent on the size of the processor's data caches.
     8734 */
     8735function updatewindow(strm, src, end, copy) {
     8736  var dist;
     8737  var state = strm.state;
     8738
     8739  /* if it hasn't been done already, allocate space for the window */
     8740  if (state.window === null) {
     8741    state.wsize = 1 << state.wbits;
     8742    state.wnext = 0;
     8743    state.whave = 0;
     8744
     8745    state.window = new utils.Buf8(state.wsize);
     8746  }
     8747
     8748  /* copy state->wsize or less output bytes into the circular window */
     8749  if (copy >= state.wsize) {
     8750    utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
     8751    state.wnext = 0;
     8752    state.whave = state.wsize;
     8753  }
     8754  else {
     8755    dist = state.wsize - state.wnext;
     8756    if (dist > copy) {
     8757      dist = copy;
     8758    }
     8759    //zmemcpy(state->window + state->wnext, end - copy, dist);
     8760    utils.arraySet(state.window, src, end - copy, dist, state.wnext);
     8761    copy -= dist;
     8762    if (copy) {
     8763      //zmemcpy(state->window, end - copy, copy);
     8764      utils.arraySet(state.window, src, end - copy, copy, 0);
     8765      state.wnext = copy;
     8766      state.whave = state.wsize;
     8767    }
     8768    else {
     8769      state.wnext += dist;
     8770      if (state.wnext === state.wsize) { state.wnext = 0; }
     8771      if (state.whave < state.wsize) { state.whave += dist; }
     8772    }
     8773  }
     8774  return 0;
     8775}
     8776
     8777function inflate(strm, flush) {
     8778  var state;
     8779  var input, output;          // input/output buffers
     8780  var next;                   /* next input INDEX */
     8781  var put;                    /* next output INDEX */
     8782  var have, left;             /* available input and output */
     8783  var hold;                   /* bit buffer */
     8784  var bits;                   /* bits in bit buffer */
     8785  var _in, _out;              /* save starting available input and output */
     8786  var copy;                   /* number of stored or match bytes to copy */
     8787  var from;                   /* where to copy match bytes from */
     8788  var from_source;
     8789  var here = 0;               /* current decoding table entry */
     8790  var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
     8791  //var last;                   /* parent table entry */
     8792  var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
     8793  var len;                    /* length to copy for repeats, bits to drop */
     8794  var ret;                    /* return code */
     8795  var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
     8796  var opts;
     8797
     8798  var n; // temporary var for NEED_BITS
     8799
     8800  var order = /* permutation of code lengths */
     8801    [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
     8802
     8803
     8804  if (!strm || !strm.state || !strm.output ||
     8805      (!strm.input && strm.avail_in !== 0)) {
     8806    return Z_STREAM_ERROR;
     8807  }
     8808
     8809  state = strm.state;
     8810  if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */
     8811
     8812
     8813  //--- LOAD() ---
     8814  put = strm.next_out;
     8815  output = strm.output;
     8816  left = strm.avail_out;
     8817  next = strm.next_in;
     8818  input = strm.input;
     8819  have = strm.avail_in;
     8820  hold = state.hold;
     8821  bits = state.bits;
     8822  //---
     8823
     8824  _in = have;
     8825  _out = left;
     8826  ret = Z_OK;
     8827
     8828  inf_leave: // goto emulation
     8829  for (;;) {
     8830    switch (state.mode) {
     8831    case HEAD:
     8832      if (state.wrap === 0) {
     8833        state.mode = TYPEDO;
     8834        break;
     8835      }
     8836      //=== NEEDBITS(16);
     8837      while (bits < 16) {
     8838        if (have === 0) { break inf_leave; }
     8839        have--;
     8840        hold += input[next++] << bits;
     8841        bits += 8;
     8842      }
     8843      //===//
     8844      if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
     8845        state.check = 0/*crc32(0L, Z_NULL, 0)*/;
     8846        //=== CRC2(state.check, hold);
     8847        hbuf[0] = hold & 0xff;
     8848        hbuf[1] = (hold >>> 8) & 0xff;
     8849        state.check = crc32(state.check, hbuf, 2, 0);
     8850        //===//
     8851
     8852        //=== INITBITS();
     8853        hold = 0;
     8854        bits = 0;
     8855        //===//
     8856        state.mode = FLAGS;
     8857        break;
     8858      }
     8859      state.flags = 0;           /* expect zlib header */
     8860      if (state.head) {
     8861        state.head.done = false;
     8862      }
     8863      if (!(state.wrap & 1) ||   /* check if zlib header allowed */
     8864        (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
     8865        strm.msg = 'incorrect header check';
     8866        state.mode = BAD;
     8867        break;
     8868      }
     8869      if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
     8870        strm.msg = 'unknown compression method';
     8871        state.mode = BAD;
     8872        break;
     8873      }
     8874      //--- DROPBITS(4) ---//
     8875      hold >>>= 4;
     8876      bits -= 4;
     8877      //---//
     8878      len = (hold & 0x0f)/*BITS(4)*/ + 8;
     8879      if (state.wbits === 0) {
     8880        state.wbits = len;
     8881      }
     8882      else if (len > state.wbits) {
     8883        strm.msg = 'invalid window size';
     8884        state.mode = BAD;
     8885        break;
     8886      }
     8887      state.dmax = 1 << len;
     8888      //Tracev((stderr, "inflate:   zlib header ok\n"));
     8889      strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
     8890      state.mode = hold & 0x200 ? DICTID : TYPE;
     8891      //=== INITBITS();
     8892      hold = 0;
     8893      bits = 0;
     8894      //===//
     8895      break;
     8896    case FLAGS:
     8897      //=== NEEDBITS(16); */
     8898      while (bits < 16) {
     8899        if (have === 0) { break inf_leave; }
     8900        have--;
     8901        hold += input[next++] << bits;
     8902        bits += 8;
     8903      }
     8904      //===//
     8905      state.flags = hold;
     8906      if ((state.flags & 0xff) !== Z_DEFLATED) {
     8907        strm.msg = 'unknown compression method';
     8908        state.mode = BAD;
     8909        break;
     8910      }
     8911      if (state.flags & 0xe000) {
     8912        strm.msg = 'unknown header flags set';
     8913        state.mode = BAD;
     8914        break;
     8915      }
     8916      if (state.head) {
     8917        state.head.text = ((hold >> 8) & 1);
     8918      }
     8919      if (state.flags & 0x0200) {
     8920        //=== CRC2(state.check, hold);
     8921        hbuf[0] = hold & 0xff;
     8922        hbuf[1] = (hold >>> 8) & 0xff;
     8923        state.check = crc32(state.check, hbuf, 2, 0);
     8924        //===//
     8925      }
     8926      //=== INITBITS();
     8927      hold = 0;
     8928      bits = 0;
     8929      //===//
     8930      state.mode = TIME;
     8931      /* falls through */
     8932    case TIME:
     8933      //=== NEEDBITS(32); */
     8934      while (bits < 32) {
     8935        if (have === 0) { break inf_leave; }
     8936        have--;
     8937        hold += input[next++] << bits;
     8938        bits += 8;
     8939      }
     8940      //===//
     8941      if (state.head) {
     8942        state.head.time = hold;
     8943      }
     8944      if (state.flags & 0x0200) {
     8945        //=== CRC4(state.check, hold)
     8946        hbuf[0] = hold & 0xff;
     8947        hbuf[1] = (hold >>> 8) & 0xff;
     8948        hbuf[2] = (hold >>> 16) & 0xff;
     8949        hbuf[3] = (hold >>> 24) & 0xff;
     8950        state.check = crc32(state.check, hbuf, 4, 0);
     8951        //===
     8952      }
     8953      //=== INITBITS();
     8954      hold = 0;
     8955      bits = 0;
     8956      //===//
     8957      state.mode = OS;
     8958      /* falls through */
     8959    case OS:
     8960      //=== NEEDBITS(16); */
     8961      while (bits < 16) {
     8962        if (have === 0) { break inf_leave; }
     8963        have--;
     8964        hold += input[next++] << bits;
     8965        bits += 8;
     8966      }
     8967      //===//
     8968      if (state.head) {
     8969        state.head.xflags = (hold & 0xff);
     8970        state.head.os = (hold >> 8);
     8971      }
     8972      if (state.flags & 0x0200) {
     8973        //=== CRC2(state.check, hold);
     8974        hbuf[0] = hold & 0xff;
     8975        hbuf[1] = (hold >>> 8) & 0xff;
     8976        state.check = crc32(state.check, hbuf, 2, 0);
     8977        //===//
     8978      }
     8979      //=== INITBITS();
     8980      hold = 0;
     8981      bits = 0;
     8982      //===//
     8983      state.mode = EXLEN;
     8984      /* falls through */
     8985    case EXLEN:
     8986      if (state.flags & 0x0400) {
     8987        //=== NEEDBITS(16); */
     8988        while (bits < 16) {
     8989          if (have === 0) { break inf_leave; }
     8990          have--;
     8991          hold += input[next++] << bits;
     8992          bits += 8;
     8993        }
     8994        //===//
     8995        state.length = hold;
     8996        if (state.head) {
     8997          state.head.extra_len = hold;
     8998        }
     8999        if (state.flags & 0x0200) {
     9000          //=== CRC2(state.check, hold);
     9001          hbuf[0] = hold & 0xff;
     9002          hbuf[1] = (hold >>> 8) & 0xff;
     9003          state.check = crc32(state.check, hbuf, 2, 0);
     9004          //===//
     9005        }
     9006        //=== INITBITS();
     9007        hold = 0;
     9008        bits = 0;
     9009        //===//
     9010      }
     9011      else if (state.head) {
     9012        state.head.extra = null/*Z_NULL*/;
     9013      }
     9014      state.mode = EXTRA;
     9015      /* falls through */
     9016    case EXTRA:
     9017      if (state.flags & 0x0400) {
     9018        copy = state.length;
     9019        if (copy > have) { copy = have; }
     9020        if (copy) {
     9021          if (state.head) {
     9022            len = state.head.extra_len - state.length;
     9023            if (!state.head.extra) {
     9024              // Use untyped array for more conveniend processing later
     9025              state.head.extra = new Array(state.head.extra_len);
     9026            }
     9027            utils.arraySet(
     9028              state.head.extra,
     9029              input,
     9030              next,
     9031              // extra field is limited to 65536 bytes
     9032              // - no need for additional size check
     9033              copy,
     9034              /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
     9035              len
     9036            );
     9037            //zmemcpy(state.head.extra + len, next,
     9038            //        len + copy > state.head.extra_max ?
     9039            //        state.head.extra_max - len : copy);
     9040          }
     9041          if (state.flags & 0x0200) {
     9042            state.check = crc32(state.check, input, copy, next);
     9043          }
     9044          have -= copy;
     9045          next += copy;
     9046          state.length -= copy;
     9047        }
     9048        if (state.length) { break inf_leave; }
     9049      }
     9050      state.length = 0;
     9051      state.mode = NAME;
     9052      /* falls through */
     9053    case NAME:
     9054      if (state.flags & 0x0800) {
     9055        if (have === 0) { break inf_leave; }
     9056        copy = 0;
     9057        do {
     9058          // TODO: 2 or 1 bytes?
     9059          len = input[next + copy++];
     9060          /* use constant limit because in js we should not preallocate memory */
     9061          if (state.head && len &&
     9062              (state.length < 65536 /*state.head.name_max*/)) {
     9063            state.head.name += String.fromCharCode(len);
     9064          }
     9065        } while (len && copy < have);
     9066
     9067        if (state.flags & 0x0200) {
     9068          state.check = crc32(state.check, input, copy, next);
     9069        }
     9070        have -= copy;
     9071        next += copy;
     9072        if (len) { break inf_leave; }
     9073      }
     9074      else if (state.head) {
     9075        state.head.name = null;
     9076      }
     9077      state.length = 0;
     9078      state.mode = COMMENT;
     9079      /* falls through */
     9080    case COMMENT:
     9081      if (state.flags & 0x1000) {
     9082        if (have === 0) { break inf_leave; }
     9083        copy = 0;
     9084        do {
     9085          len = input[next + copy++];
     9086          /* use constant limit because in js we should not preallocate memory */
     9087          if (state.head && len &&
     9088              (state.length < 65536 /*state.head.comm_max*/)) {
     9089            state.head.comment += String.fromCharCode(len);
     9090          }
     9091        } while (len && copy < have);
     9092        if (state.flags & 0x0200) {
     9093          state.check = crc32(state.check, input, copy, next);
     9094        }
     9095        have -= copy;
     9096        next += copy;
     9097        if (len) { break inf_leave; }
     9098      }
     9099      else if (state.head) {
     9100        state.head.comment = null;
     9101      }
     9102      state.mode = HCRC;
     9103      /* falls through */
     9104    case HCRC:
     9105      if (state.flags & 0x0200) {
     9106        //=== NEEDBITS(16); */
     9107        while (bits < 16) {
     9108          if (have === 0) { break inf_leave; }
     9109          have--;
     9110          hold += input[next++] << bits;
     9111          bits += 8;
     9112        }
     9113        //===//
     9114        if (hold !== (state.check & 0xffff)) {
     9115          strm.msg = 'header crc mismatch';
     9116          state.mode = BAD;
     9117          break;
     9118        }
     9119        //=== INITBITS();
     9120        hold = 0;
     9121        bits = 0;
     9122        //===//
     9123      }
     9124      if (state.head) {
     9125        state.head.hcrc = ((state.flags >> 9) & 1);
     9126        state.head.done = true;
     9127      }
     9128      strm.adler = state.check = 0;
     9129      state.mode = TYPE;
     9130      break;
     9131    case DICTID:
     9132      //=== NEEDBITS(32); */
     9133      while (bits < 32) {
     9134        if (have === 0) { break inf_leave; }
     9135        have--;
     9136        hold += input[next++] << bits;
     9137        bits += 8;
     9138      }
     9139      //===//
     9140      strm.adler = state.check = zswap32(hold);
     9141      //=== INITBITS();
     9142      hold = 0;
     9143      bits = 0;
     9144      //===//
     9145      state.mode = DICT;
     9146      /* falls through */
     9147    case DICT:
     9148      if (state.havedict === 0) {
     9149        //--- RESTORE() ---
     9150        strm.next_out = put;
     9151        strm.avail_out = left;
     9152        strm.next_in = next;
     9153        strm.avail_in = have;
     9154        state.hold = hold;
     9155        state.bits = bits;
     9156        //---
     9157        return Z_NEED_DICT;
     9158      }
     9159      strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
     9160      state.mode = TYPE;
     9161      /* falls through */
     9162    case TYPE:
     9163      if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
     9164      /* falls through */
     9165    case TYPEDO:
     9166      if (state.last) {
     9167        //--- BYTEBITS() ---//
     9168        hold >>>= bits & 7;
     9169        bits -= bits & 7;
     9170        //---//
     9171        state.mode = CHECK;
     9172        break;
     9173      }
     9174      //=== NEEDBITS(3); */
     9175      while (bits < 3) {
     9176        if (have === 0) { break inf_leave; }
     9177        have--;
     9178        hold += input[next++] << bits;
     9179        bits += 8;
     9180      }
     9181      //===//
     9182      state.last = (hold & 0x01)/*BITS(1)*/;
     9183      //--- DROPBITS(1) ---//
     9184      hold >>>= 1;
     9185      bits -= 1;
     9186      //---//
     9187
     9188      switch ((hold & 0x03)/*BITS(2)*/) {
     9189      case 0:                             /* stored block */
     9190        //Tracev((stderr, "inflate:     stored block%s\n",
     9191        //        state.last ? " (last)" : ""));
     9192        state.mode = STORED;
     9193        break;
     9194      case 1:                             /* fixed block */
     9195        fixedtables(state);
     9196        //Tracev((stderr, "inflate:     fixed codes block%s\n",
     9197        //        state.last ? " (last)" : ""));
     9198        state.mode = LEN_;             /* decode codes */
     9199        if (flush === Z_TREES) {
     9200          //--- DROPBITS(2) ---//
     9201          hold >>>= 2;
     9202          bits -= 2;
     9203          //---//
     9204          break inf_leave;
     9205        }
     9206        break;
     9207      case 2:                             /* dynamic block */
     9208        //Tracev((stderr, "inflate:     dynamic codes block%s\n",
     9209        //        state.last ? " (last)" : ""));
     9210        state.mode = TABLE;
     9211        break;
     9212      case 3:
     9213        strm.msg = 'invalid block type';
     9214        state.mode = BAD;
     9215      }
     9216      //--- DROPBITS(2) ---//
     9217      hold >>>= 2;
     9218      bits -= 2;
     9219      //---//
     9220      break;
     9221    case STORED:
     9222      //--- BYTEBITS() ---// /* go to byte boundary */
     9223      hold >>>= bits & 7;
     9224      bits -= bits & 7;
     9225      //---//
     9226      //=== NEEDBITS(32); */
     9227      while (bits < 32) {
     9228        if (have === 0) { break inf_leave; }
     9229        have--;
     9230        hold += input[next++] << bits;
     9231        bits += 8;
     9232      }
     9233      //===//
     9234      if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
     9235        strm.msg = 'invalid stored block lengths';
     9236        state.mode = BAD;
     9237        break;
     9238      }
     9239      state.length = hold & 0xffff;
     9240      //Tracev((stderr, "inflate:       stored length %u\n",
     9241      //        state.length));
     9242      //=== INITBITS();
     9243      hold = 0;
     9244      bits = 0;
     9245      //===//
     9246      state.mode = COPY_;
     9247      if (flush === Z_TREES) { break inf_leave; }
     9248      /* falls through */
     9249    case COPY_:
     9250      state.mode = COPY;
     9251      /* falls through */
     9252    case COPY:
     9253      copy = state.length;
     9254      if (copy) {
     9255        if (copy > have) { copy = have; }
     9256        if (copy > left) { copy = left; }
     9257        if (copy === 0) { break inf_leave; }
     9258        //--- zmemcpy(put, next, copy); ---
     9259        utils.arraySet(output, input, next, copy, put);
     9260        //---//
     9261        have -= copy;
     9262        next += copy;
     9263        left -= copy;
     9264        put += copy;
     9265        state.length -= copy;
     9266        break;
     9267      }
     9268      //Tracev((stderr, "inflate:       stored end\n"));
     9269      state.mode = TYPE;
     9270      break;
     9271    case TABLE:
     9272      //=== NEEDBITS(14); */
     9273      while (bits < 14) {
     9274        if (have === 0) { break inf_leave; }
     9275        have--;
     9276        hold += input[next++] << bits;
     9277        bits += 8;
     9278      }
     9279      //===//
     9280      state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
     9281      //--- DROPBITS(5) ---//
     9282      hold >>>= 5;
     9283      bits -= 5;
     9284      //---//
     9285      state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
     9286      //--- DROPBITS(5) ---//
     9287      hold >>>= 5;
     9288      bits -= 5;
     9289      //---//
     9290      state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
     9291      //--- DROPBITS(4) ---//
     9292      hold >>>= 4;
     9293      bits -= 4;
     9294      //---//
     9295//#ifndef PKZIP_BUG_WORKAROUND
     9296      if (state.nlen > 286 || state.ndist > 30) {
     9297        strm.msg = 'too many length or distance symbols';
     9298        state.mode = BAD;
     9299        break;
     9300      }
     9301//#endif
     9302      //Tracev((stderr, "inflate:       table sizes ok\n"));
     9303      state.have = 0;
     9304      state.mode = LENLENS;
     9305      /* falls through */
     9306    case LENLENS:
     9307      while (state.have < state.ncode) {
     9308        //=== NEEDBITS(3);
     9309        while (bits < 3) {
     9310          if (have === 0) { break inf_leave; }
     9311          have--;
     9312          hold += input[next++] << bits;
     9313          bits += 8;
     9314        }
     9315        //===//
     9316        state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
     9317        //--- DROPBITS(3) ---//
     9318        hold >>>= 3;
     9319        bits -= 3;
     9320        //---//
     9321      }
     9322      while (state.have < 19) {
     9323        state.lens[order[state.have++]] = 0;
     9324      }
     9325      // We have separate tables & no pointers. 2 commented lines below not needed.
     9326      //state.next = state.codes;
     9327      //state.lencode = state.next;
     9328      // Switch to use dynamic table
     9329      state.lencode = state.lendyn;
     9330      state.lenbits = 7;
     9331
     9332      opts = { bits: state.lenbits };
     9333      ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
     9334      state.lenbits = opts.bits;
     9335
     9336      if (ret) {
     9337        strm.msg = 'invalid code lengths set';
     9338        state.mode = BAD;
     9339        break;
     9340      }
     9341      //Tracev((stderr, "inflate:       code lengths ok\n"));
     9342      state.have = 0;
     9343      state.mode = CODELENS;
     9344      /* falls through */
     9345    case CODELENS:
     9346      while (state.have < state.nlen + state.ndist) {
     9347        for (;;) {
     9348          here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
     9349          here_bits = here >>> 24;
     9350          here_op = (here >>> 16) & 0xff;
     9351          here_val = here & 0xffff;
     9352
     9353          if ((here_bits) <= bits) { break; }
     9354          //--- PULLBYTE() ---//
     9355          if (have === 0) { break inf_leave; }
     9356          have--;
     9357          hold += input[next++] << bits;
     9358          bits += 8;
     9359          //---//
     9360        }
     9361        if (here_val < 16) {
     9362          //--- DROPBITS(here.bits) ---//
     9363          hold >>>= here_bits;
     9364          bits -= here_bits;
     9365          //---//
     9366          state.lens[state.have++] = here_val;
     9367        }
     9368        else {
     9369          if (here_val === 16) {
     9370            //=== NEEDBITS(here.bits + 2);
     9371            n = here_bits + 2;
     9372            while (bits < n) {
     9373              if (have === 0) { break inf_leave; }
     9374              have--;
     9375              hold += input[next++] << bits;
     9376              bits += 8;
     9377            }
     9378            //===//
     9379            //--- DROPBITS(here.bits) ---//
     9380            hold >>>= here_bits;
     9381            bits -= here_bits;
     9382            //---//
     9383            if (state.have === 0) {
     9384              strm.msg = 'invalid bit length repeat';
     9385              state.mode = BAD;
     9386              break;
     9387            }
     9388            len = state.lens[state.have - 1];
     9389            copy = 3 + (hold & 0x03);//BITS(2);
     9390            //--- DROPBITS(2) ---//
     9391            hold >>>= 2;
     9392            bits -= 2;
     9393            //---//
     9394          }
     9395          else if (here_val === 17) {
     9396            //=== NEEDBITS(here.bits + 3);
     9397            n = here_bits + 3;
     9398            while (bits < n) {
     9399              if (have === 0) { break inf_leave; }
     9400              have--;
     9401              hold += input[next++] << bits;
     9402              bits += 8;
     9403            }
     9404            //===//
     9405            //--- DROPBITS(here.bits) ---//
     9406            hold >>>= here_bits;
     9407            bits -= here_bits;
     9408            //---//
     9409            len = 0;
     9410            copy = 3 + (hold & 0x07);//BITS(3);
     9411            //--- DROPBITS(3) ---//
     9412            hold >>>= 3;
     9413            bits -= 3;
     9414            //---//
     9415          }
     9416          else {
     9417            //=== NEEDBITS(here.bits + 7);
     9418            n = here_bits + 7;
     9419            while (bits < n) {
     9420              if (have === 0) { break inf_leave; }
     9421              have--;
     9422              hold += input[next++] << bits;
     9423              bits += 8;
     9424            }
     9425            //===//
     9426            //--- DROPBITS(here.bits) ---//
     9427            hold >>>= here_bits;
     9428            bits -= here_bits;
     9429            //---//
     9430            len = 0;
     9431            copy = 11 + (hold & 0x7f);//BITS(7);
     9432            //--- DROPBITS(7) ---//
     9433            hold >>>= 7;
     9434            bits -= 7;
     9435            //---//
     9436          }
     9437          if (state.have + copy > state.nlen + state.ndist) {
     9438            strm.msg = 'invalid bit length repeat';
     9439            state.mode = BAD;
     9440            break;
     9441          }
     9442          while (copy--) {
     9443            state.lens[state.have++] = len;
     9444          }
     9445        }
     9446      }
     9447
     9448      /* handle error breaks in while */
     9449      if (state.mode === BAD) { break; }
     9450
     9451      /* check for end-of-block code (better have one) */
     9452      if (state.lens[256] === 0) {
     9453        strm.msg = 'invalid code -- missing end-of-block';
     9454        state.mode = BAD;
     9455        break;
     9456      }
     9457
     9458      /* build code tables -- note: do not change the lenbits or distbits
     9459         values here (9 and 6) without reading the comments in inftrees.h
     9460         concerning the ENOUGH constants, which depend on those values */
     9461      state.lenbits = 9;
     9462
     9463      opts = { bits: state.lenbits };
     9464      ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
     9465      // We have separate tables & no pointers. 2 commented lines below not needed.
     9466      // state.next_index = opts.table_index;
     9467      state.lenbits = opts.bits;
     9468      // state.lencode = state.next;
     9469
     9470      if (ret) {
     9471        strm.msg = 'invalid literal/lengths set';
     9472        state.mode = BAD;
     9473        break;
     9474      }
     9475
     9476      state.distbits = 6;
     9477      //state.distcode.copy(state.codes);
     9478      // Switch to use dynamic table
     9479      state.distcode = state.distdyn;
     9480      opts = { bits: state.distbits };
     9481      ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
     9482      // We have separate tables & no pointers. 2 commented lines below not needed.
     9483      // state.next_index = opts.table_index;
     9484      state.distbits = opts.bits;
     9485      // state.distcode = state.next;
     9486
     9487      if (ret) {
     9488        strm.msg = 'invalid distances set';
     9489        state.mode = BAD;
     9490        break;
     9491      }
     9492      //Tracev((stderr, 'inflate:       codes ok\n'));
     9493      state.mode = LEN_;
     9494      if (flush === Z_TREES) { break inf_leave; }
     9495      /* falls through */
     9496    case LEN_:
     9497      state.mode = LEN;
     9498      /* falls through */
     9499    case LEN:
     9500      if (have >= 6 && left >= 258) {
     9501        //--- RESTORE() ---
     9502        strm.next_out = put;
     9503        strm.avail_out = left;
     9504        strm.next_in = next;
     9505        strm.avail_in = have;
     9506        state.hold = hold;
     9507        state.bits = bits;
     9508        //---
     9509        inflate_fast(strm, _out);
     9510        //--- LOAD() ---
     9511        put = strm.next_out;
     9512        output = strm.output;
     9513        left = strm.avail_out;
     9514        next = strm.next_in;
     9515        input = strm.input;
     9516        have = strm.avail_in;
     9517        hold = state.hold;
     9518        bits = state.bits;
     9519        //---
     9520
     9521        if (state.mode === TYPE) {
     9522          state.back = -1;
     9523        }
     9524        break;
     9525      }
     9526      state.back = 0;
     9527      for (;;) {
     9528        here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
     9529        here_bits = here >>> 24;
     9530        here_op = (here >>> 16) & 0xff;
     9531        here_val = here & 0xffff;
     9532
     9533        if (here_bits <= bits) { break; }
     9534        //--- PULLBYTE() ---//
     9535        if (have === 0) { break inf_leave; }
     9536        have--;
     9537        hold += input[next++] << bits;
     9538        bits += 8;
     9539        //---//
     9540      }
     9541      if (here_op && (here_op & 0xf0) === 0) {
     9542        last_bits = here_bits;
     9543        last_op = here_op;
     9544        last_val = here_val;
     9545        for (;;) {
     9546          here = state.lencode[last_val +
     9547                  ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
     9548          here_bits = here >>> 24;
     9549          here_op = (here >>> 16) & 0xff;
     9550          here_val = here & 0xffff;
     9551
     9552          if ((last_bits + here_bits) <= bits) { break; }
     9553          //--- PULLBYTE() ---//
     9554          if (have === 0) { break inf_leave; }
     9555          have--;
     9556          hold += input[next++] << bits;
     9557          bits += 8;
     9558          //---//
     9559        }
     9560        //--- DROPBITS(last.bits) ---//
     9561        hold >>>= last_bits;
     9562        bits -= last_bits;
     9563        //---//
     9564        state.back += last_bits;
     9565      }
     9566      //--- DROPBITS(here.bits) ---//
     9567      hold >>>= here_bits;
     9568      bits -= here_bits;
     9569      //---//
     9570      state.back += here_bits;
     9571      state.length = here_val;
     9572      if (here_op === 0) {
     9573        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
     9574        //        "inflate:         literal '%c'\n" :
     9575        //        "inflate:         literal 0x%02x\n", here.val));
     9576        state.mode = LIT;
     9577        break;
     9578      }
     9579      if (here_op & 32) {
     9580        //Tracevv((stderr, "inflate:         end of block\n"));
     9581        state.back = -1;
     9582        state.mode = TYPE;
     9583        break;
     9584      }
     9585      if (here_op & 64) {
     9586        strm.msg = 'invalid literal/length code';
     9587        state.mode = BAD;
     9588        break;
     9589      }
     9590      state.extra = here_op & 15;
     9591      state.mode = LENEXT;
     9592      /* falls through */
     9593    case LENEXT:
     9594      if (state.extra) {
     9595        //=== NEEDBITS(state.extra);
     9596        n = state.extra;
     9597        while (bits < n) {
     9598          if (have === 0) { break inf_leave; }
     9599          have--;
     9600          hold += input[next++] << bits;
     9601          bits += 8;
     9602        }
     9603        //===//
     9604        state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
     9605        //--- DROPBITS(state.extra) ---//
     9606        hold >>>= state.extra;
     9607        bits -= state.extra;
     9608        //---//
     9609        state.back += state.extra;
     9610      }
     9611      //Tracevv((stderr, "inflate:         length %u\n", state.length));
     9612      state.was = state.length;
     9613      state.mode = DIST;
     9614      /* falls through */
     9615    case DIST:
     9616      for (;;) {
     9617        here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
     9618        here_bits = here >>> 24;
     9619        here_op = (here >>> 16) & 0xff;
     9620        here_val = here & 0xffff;
     9621
     9622        if ((here_bits) <= bits) { break; }
     9623        //--- PULLBYTE() ---//
     9624        if (have === 0) { break inf_leave; }
     9625        have--;
     9626        hold += input[next++] << bits;
     9627        bits += 8;
     9628        //---//
     9629      }
     9630      if ((here_op & 0xf0) === 0) {
     9631        last_bits = here_bits;
     9632        last_op = here_op;
     9633        last_val = here_val;
     9634        for (;;) {
     9635          here = state.distcode[last_val +
     9636                  ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
     9637          here_bits = here >>> 24;
     9638          here_op = (here >>> 16) & 0xff;
     9639          here_val = here & 0xffff;
     9640
     9641          if ((last_bits + here_bits) <= bits) { break; }
     9642          //--- PULLBYTE() ---//
     9643          if (have === 0) { break inf_leave; }
     9644          have--;
     9645          hold += input[next++] << bits;
     9646          bits += 8;
     9647          //---//
     9648        }
     9649        //--- DROPBITS(last.bits) ---//
     9650        hold >>>= last_bits;
     9651        bits -= last_bits;
     9652        //---//
     9653        state.back += last_bits;
     9654      }
     9655      //--- DROPBITS(here.bits) ---//
     9656      hold >>>= here_bits;
     9657      bits -= here_bits;
     9658      //---//
     9659      state.back += here_bits;
     9660      if (here_op & 64) {
     9661        strm.msg = 'invalid distance code';
     9662        state.mode = BAD;
     9663        break;
     9664      }
     9665      state.offset = here_val;
     9666      state.extra = (here_op) & 15;
     9667      state.mode = DISTEXT;
     9668      /* falls through */
     9669    case DISTEXT:
     9670      if (state.extra) {
     9671        //=== NEEDBITS(state.extra);
     9672        n = state.extra;
     9673        while (bits < n) {
     9674          if (have === 0) { break inf_leave; }
     9675          have--;
     9676          hold += input[next++] << bits;
     9677          bits += 8;
     9678        }
     9679        //===//
     9680        state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
     9681        //--- DROPBITS(state.extra) ---//
     9682        hold >>>= state.extra;
     9683        bits -= state.extra;
     9684        //---//
     9685        state.back += state.extra;
     9686      }
     9687//#ifdef INFLATE_STRICT
     9688      if (state.offset > state.dmax) {
     9689        strm.msg = 'invalid distance too far back';
     9690        state.mode = BAD;
     9691        break;
     9692      }
     9693//#endif
     9694      //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
     9695      state.mode = MATCH;
     9696      /* falls through */
     9697    case MATCH:
     9698      if (left === 0) { break inf_leave; }
     9699      copy = _out - left;
     9700      if (state.offset > copy) {         /* copy from window */
     9701        copy = state.offset - copy;
     9702        if (copy > state.whave) {
     9703          if (state.sane) {
     9704            strm.msg = 'invalid distance too far back';
     9705            state.mode = BAD;
     9706            break;
     9707          }
     9708// (!) This block is disabled in zlib defailts,
     9709// don't enable it for binary compatibility
     9710//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
     9711//          Trace((stderr, "inflate.c too far\n"));
     9712//          copy -= state.whave;
     9713//          if (copy > state.length) { copy = state.length; }
     9714//          if (copy > left) { copy = left; }
     9715//          left -= copy;
     9716//          state.length -= copy;
     9717//          do {
     9718//            output[put++] = 0;
     9719//          } while (--copy);
     9720//          if (state.length === 0) { state.mode = LEN; }
     9721//          break;
     9722//#endif
     9723        }
     9724        if (copy > state.wnext) {
     9725          copy -= state.wnext;
     9726          from = state.wsize - copy;
     9727        }
     9728        else {
     9729          from = state.wnext - copy;
     9730        }
     9731        if (copy > state.length) { copy = state.length; }
     9732        from_source = state.window;
     9733      }
     9734      else {                              /* copy from output */
     9735        from_source = output;
     9736        from = put - state.offset;
     9737        copy = state.length;
     9738      }
     9739      if (copy > left) { copy = left; }
     9740      left -= copy;
     9741      state.length -= copy;
     9742      do {
     9743        output[put++] = from_source[from++];
     9744      } while (--copy);
     9745      if (state.length === 0) { state.mode = LEN; }
     9746      break;
     9747    case LIT:
     9748      if (left === 0) { break inf_leave; }
     9749      output[put++] = state.length;
     9750      left--;
     9751      state.mode = LEN;
     9752      break;
     9753    case CHECK:
     9754      if (state.wrap) {
     9755        //=== NEEDBITS(32);
     9756        while (bits < 32) {
     9757          if (have === 0) { break inf_leave; }
     9758          have--;
     9759          // Use '|' insdead of '+' to make sure that result is signed
     9760          hold |= input[next++] << bits;
     9761          bits += 8;
     9762        }
     9763        //===//
     9764        _out -= left;
     9765        strm.total_out += _out;
     9766        state.total += _out;
     9767        if (_out) {
     9768          strm.adler = state.check =
     9769              /*UPDATE(state.check, put - _out, _out);*/
     9770              (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
     9771
     9772        }
     9773        _out = left;
     9774        // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
     9775        if ((state.flags ? hold : zswap32(hold)) !== state.check) {
     9776          strm.msg = 'incorrect data check';
     9777          state.mode = BAD;
     9778          break;
     9779        }
     9780        //=== INITBITS();
     9781        hold = 0;
     9782        bits = 0;
     9783        //===//
     9784        //Tracev((stderr, "inflate:   check matches trailer\n"));
     9785      }
     9786      state.mode = LENGTH;
     9787      /* falls through */
     9788    case LENGTH:
     9789      if (state.wrap && state.flags) {
     9790        //=== NEEDBITS(32);
     9791        while (bits < 32) {
     9792          if (have === 0) { break inf_leave; }
     9793          have--;
     9794          hold += input[next++] << bits;
     9795          bits += 8;
     9796        }
     9797        //===//
     9798        if (hold !== (state.total & 0xffffffff)) {
     9799          strm.msg = 'incorrect length check';
     9800          state.mode = BAD;
     9801          break;
     9802        }
     9803        //=== INITBITS();
     9804        hold = 0;
     9805        bits = 0;
     9806        //===//
     9807        //Tracev((stderr, "inflate:   length matches trailer\n"));
     9808      }
     9809      state.mode = DONE;
     9810      /* falls through */
     9811    case DONE:
     9812      ret = Z_STREAM_END;
     9813      break inf_leave;
     9814    case BAD:
     9815      ret = Z_DATA_ERROR;
     9816      break inf_leave;
     9817    case MEM:
     9818      return Z_MEM_ERROR;
     9819    case SYNC:
     9820      /* falls through */
     9821    default:
     9822      return Z_STREAM_ERROR;
     9823    }
     9824  }
     9825
     9826  // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
     9827
     9828  /*
     9829     Return from inflate(), updating the total counts and the check value.
     9830     If there was no progress during the inflate() call, return a buffer
     9831     error.  Call updatewindow() to create and/or update the window state.
     9832     Note: a memory error from inflate() is non-recoverable.
     9833   */
     9834
     9835  //--- RESTORE() ---
     9836  strm.next_out = put;
     9837  strm.avail_out = left;
     9838  strm.next_in = next;
     9839  strm.avail_in = have;
     9840  state.hold = hold;
     9841  state.bits = bits;
     9842  //---
     9843
     9844  if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
     9845                      (state.mode < CHECK || flush !== Z_FINISH))) {
     9846    if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
     9847      state.mode = MEM;
     9848      return Z_MEM_ERROR;
     9849    }
     9850  }
     9851  _in -= strm.avail_in;
     9852  _out -= strm.avail_out;
     9853  strm.total_in += _in;
     9854  strm.total_out += _out;
     9855  state.total += _out;
     9856  if (state.wrap && _out) {
     9857    strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
     9858      (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
     9859  }
     9860  strm.data_type = state.bits + (state.last ? 64 : 0) +
     9861                    (state.mode === TYPE ? 128 : 0) +
     9862                    (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
     9863  if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
     9864    ret = Z_BUF_ERROR;
     9865  }
     9866  return ret;
     9867}
     9868
     9869function inflateEnd(strm) {
     9870
     9871  if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
     9872    return Z_STREAM_ERROR;
     9873  }
     9874
     9875  var state = strm.state;
     9876  if (state.window) {
     9877    state.window = null;
     9878  }
     9879  strm.state = null;
     9880  return Z_OK;
     9881}
     9882
     9883function inflateGetHeader(strm, head) {
     9884  var state;
     9885
     9886  /* check state */
     9887  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
     9888  state = strm.state;
     9889  if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
     9890
     9891  /* save header structure */
     9892  state.head = head;
     9893  head.done = false;
     9894  return Z_OK;
     9895}
     9896
     9897function inflateSetDictionary(strm, dictionary) {
     9898  var dictLength = dictionary.length;
     9899
     9900  var state;
     9901  var dictid;
     9902  var ret;
     9903
     9904  /* check state */
     9905  if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
     9906  state = strm.state;
     9907
     9908  if (state.wrap !== 0 && state.mode !== DICT) {
     9909    return Z_STREAM_ERROR;
     9910  }
     9911
     9912  /* check for correct dictionary identifier */
     9913  if (state.mode === DICT) {
     9914    dictid = 1; /* adler32(0, null, 0)*/
     9915    /* dictid = adler32(dictid, dictionary, dictLength); */
     9916    dictid = adler32(dictid, dictionary, dictLength, 0);
     9917    if (dictid !== state.check) {
     9918      return Z_DATA_ERROR;
     9919    }
     9920  }
     9921  /* copy dictionary to window using updatewindow(), which will amend the
     9922   existing dictionary if appropriate */
     9923  ret = updatewindow(strm, dictionary, dictLength, dictLength);
     9924  if (ret) {
     9925    state.mode = MEM;
     9926    return Z_MEM_ERROR;
     9927  }
     9928  state.havedict = 1;
     9929  // Tracev((stderr, "inflate:   dictionary set\n"));
     9930  return Z_OK;
     9931}
     9932
     9933exports.inflateReset = inflateReset;
     9934exports.inflateReset2 = inflateReset2;
     9935exports.inflateResetKeep = inflateResetKeep;
     9936exports.inflateInit = inflateInit;
     9937exports.inflateInit2 = inflateInit2;
     9938exports.inflate = inflate;
     9939exports.inflateEnd = inflateEnd;
     9940exports.inflateGetHeader = inflateGetHeader;
     9941exports.inflateSetDictionary = inflateSetDictionary;
     9942exports.inflateInfo = 'pako inflate (from Nodeca project)';
     9943
     9944/* Not implemented
     9945exports.inflateCopy = inflateCopy;
     9946exports.inflateGetDictionary = inflateGetDictionary;
     9947exports.inflateMark = inflateMark;
     9948exports.inflatePrime = inflatePrime;
     9949exports.inflateSync = inflateSync;
     9950exports.inflateSyncPoint = inflateSyncPoint;
     9951exports.inflateUndermine = inflateUndermine;
     9952*/
     9953
     9954},{"../utils/common":62,"./adler32":64,"./crc32":66,"./inffast":69,"./inftrees":71}],71:[function(require,module,exports){
     9955'use strict';
     9956
     9957// (C) 1995-2013 Jean-loup Gailly and Mark Adler
     9958// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
     9959//
     9960// This software is provided 'as-is', without any express or implied
     9961// warranty. In no event will the authors be held liable for any damages
     9962// arising from the use of this software.
     9963//
     9964// Permission is granted to anyone to use this software for any purpose,
     9965// including commercial applications, and to alter it and redistribute it
     9966// freely, subject to the following restrictions:
     9967//
     9968// 1. The origin of this software must not be misrepresented; you must not
     9969//   claim that you wrote the original software. If you use this software
     9970//   in a product, an acknowledgment in the product documentation would be
     9971//   appreciated but is not required.
     9972// 2. Altered source versions must be plainly marked as such, and must not be
     9973//   misrepresented as being the original software.
     9974// 3. This notice may not be removed or altered from any source distribution.
     9975
     9976var utils = require('../utils/common');
     9977
     9978var MAXBITS = 15;
     9979var ENOUGH_LENS = 852;
     9980var ENOUGH_DISTS = 592;
     9981//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
     9982
     9983var CODES = 0;
     9984var LENS = 1;
     9985var DISTS = 2;
     9986
     9987var lbase = [ /* Length codes 257..285 base */
     9988  3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
     9989  35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
     9990];
     9991
     9992var lext = [ /* Length codes 257..285 extra */
     9993  16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
     9994  19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
     9995];
     9996
     9997var dbase = [ /* Distance codes 0..29 base */
     9998  1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
     9999  257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
     10000  8193, 12289, 16385, 24577, 0, 0
     10001];
     10002
     10003var dext = [ /* Distance codes 0..29 extra */
     10004  16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
     10005  23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
     10006  28, 28, 29, 29, 64, 64
     10007];
     10008
     10009module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
     10010{
     10011  var bits = opts.bits;
     10012      //here = opts.here; /* table entry for duplication */
     10013
     10014  var len = 0;               /* a code's length in bits */
     10015  var sym = 0;               /* index of code symbols */
     10016  var min = 0, max = 0;          /* minimum and maximum code lengths */
     10017  var root = 0;              /* number of index bits for root table */
     10018  var curr = 0;              /* number of index bits for current table */
     10019  var drop = 0;              /* code bits to drop for sub-table */
     10020  var left = 0;                   /* number of prefix codes available */
     10021  var used = 0;              /* code entries in table used */
     10022  var huff = 0;              /* Huffman code */
     10023  var incr;              /* for incrementing code, index */
     10024  var fill;              /* index for replicating entries */
     10025  var low;               /* low bits for current root entry */
     10026  var mask;              /* mask for low root bits */
     10027  var next;             /* next available space in table */
     10028  var base = null;     /* base value table to use */
     10029  var base_index = 0;
     10030//  var shoextra;    /* extra bits table to use */
     10031  var end;                    /* use base and extra for symbol > end */
     10032  var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
     10033  var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
     10034  var extra = null;
     10035  var extra_index = 0;
     10036
     10037  var here_bits, here_op, here_val;
     10038
     10039  /*
     10040   Process a set of code lengths to create a canonical Huffman code.  The
     10041   code lengths are lens[0..codes-1].  Each length corresponds to the
     10042   symbols 0..codes-1.  The Huffman code is generated by first sorting the
     10043   symbols by length from short to long, and retaining the symbol order
     10044   for codes with equal lengths.  Then the code starts with all zero bits
     10045   for the first code of the shortest length, and the codes are integer
     10046   increments for the same length, and zeros are appended as the length
     10047   increases.  For the deflate format, these bits are stored backwards
     10048   from their more natural integer increment ordering, and so when the
     10049   decoding tables are built in the large loop below, the integer codes
     10050   are incremented backwards.
     10051
     10052   This routine assumes, but does not check, that all of the entries in
     10053   lens[] are in the range 0..MAXBITS.  The caller must assure this.
     10054   1..MAXBITS is interpreted as that code length.  zero means that that
     10055   symbol does not occur in this code.
     10056
     10057   The codes are sorted by computing a count of codes for each length,
     10058   creating from that a table of starting indices for each length in the
     10059   sorted table, and then entering the symbols in order in the sorted
     10060   table.  The sorted table is work[], with that space being provided by
     10061   the caller.
     10062
     10063   The length counts are used for other purposes as well, i.e. finding
     10064   the minimum and maximum length codes, determining if there are any
     10065   codes at all, checking for a valid set of lengths, and looking ahead
     10066   at length counts to determine sub-table sizes when building the
     10067   decoding tables.
     10068   */
     10069
     10070  /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
     10071  for (len = 0; len <= MAXBITS; len++) {
     10072    count[len] = 0;
     10073  }
     10074  for (sym = 0; sym < codes; sym++) {
     10075    count[lens[lens_index + sym]]++;
     10076  }
     10077
     10078  /* bound code lengths, force root to be within code lengths */
     10079  root = bits;
     10080  for (max = MAXBITS; max >= 1; max--) {
     10081    if (count[max] !== 0) { break; }
     10082  }
     10083  if (root > max) {
     10084    root = max;
     10085  }
     10086  if (max === 0) {                     /* no symbols to code at all */
     10087    //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
     10088    //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
     10089    //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
     10090    table[table_index++] = (1 << 24) | (64 << 16) | 0;
     10091
     10092
     10093    //table.op[opts.table_index] = 64;
     10094    //table.bits[opts.table_index] = 1;
     10095    //table.val[opts.table_index++] = 0;
     10096    table[table_index++] = (1 << 24) | (64 << 16) | 0;
     10097
     10098    opts.bits = 1;
     10099    return 0;     /* no symbols, but wait for decoding to report error */
     10100  }
     10101  for (min = 1; min < max; min++) {
     10102    if (count[min] !== 0) { break; }
     10103  }
     10104  if (root < min) {
     10105    root = min;
     10106  }
     10107
     10108  /* check for an over-subscribed or incomplete set of lengths */
     10109  left = 1;
     10110  for (len = 1; len <= MAXBITS; len++) {
     10111    left <<= 1;
     10112    left -= count[len];
     10113    if (left < 0) {
     10114      return -1;
     10115    }        /* over-subscribed */
     10116  }
     10117  if (left > 0 && (type === CODES || max !== 1)) {
     10118    return -1;                      /* incomplete set */
     10119  }
     10120
     10121  /* generate offsets into symbol table for each length for sorting */
     10122  offs[1] = 0;
     10123  for (len = 1; len < MAXBITS; len++) {
     10124    offs[len + 1] = offs[len] + count[len];
     10125  }
     10126
     10127  /* sort symbols by length, by symbol order within each length */
     10128  for (sym = 0; sym < codes; sym++) {
     10129    if (lens[lens_index + sym] !== 0) {
     10130      work[offs[lens[lens_index + sym]]++] = sym;
     10131    }
     10132  }
     10133
     10134  /*
     10135   Create and fill in decoding tables.  In this loop, the table being
     10136   filled is at next and has curr index bits.  The code being used is huff
     10137   with length len.  That code is converted to an index by dropping drop
     10138   bits off of the bottom.  For codes where len is less than drop + curr,
     10139   those top drop + curr - len bits are incremented through all values to
     10140   fill the table with replicated entries.
     10141
     10142   root is the number of index bits for the root table.  When len exceeds
     10143   root, sub-tables are created pointed to by the root entry with an index
     10144   of the low root bits of huff.  This is saved in low to check for when a
     10145   new sub-table should be started.  drop is zero when the root table is
     10146   being filled, and drop is root when sub-tables are being filled.
     10147
     10148   When a new sub-table is needed, it is necessary to look ahead in the
     10149   code lengths to determine what size sub-table is needed.  The length
     10150   counts are used for this, and so count[] is decremented as codes are
     10151   entered in the tables.
     10152
     10153   used keeps track of how many table entries have been allocated from the
     10154   provided *table space.  It is checked for LENS and DIST tables against
     10155   the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
     10156   the initial root table size constants.  See the comments in inftrees.h
     10157   for more information.
     10158
     10159   sym increments through all symbols, and the loop terminates when
     10160   all codes of length max, i.e. all codes, have been processed.  This
     10161   routine permits incomplete codes, so another loop after this one fills
     10162   in the rest of the decoding tables with invalid code markers.
     10163   */
     10164
     10165  /* set up for code type */
     10166  // poor man optimization - use if-else instead of switch,
     10167  // to avoid deopts in old v8
     10168  if (type === CODES) {
     10169    base = extra = work;    /* dummy value--not used */
     10170    end = 19;
     10171
     10172  } else if (type === LENS) {
     10173    base = lbase;
     10174    base_index -= 257;
     10175    extra = lext;
     10176    extra_index -= 257;
     10177    end = 256;
     10178
     10179  } else {                    /* DISTS */
     10180    base = dbase;
     10181    extra = dext;
     10182    end = -1;
     10183  }
     10184
     10185  /* initialize opts for loop */
     10186  huff = 0;                   /* starting code */
     10187  sym = 0;                    /* starting code symbol */
     10188  len = min;                  /* starting code length */
     10189  next = table_index;              /* current table to fill in */
     10190  curr = root;                /* current table index bits */
     10191  drop = 0;                   /* current bits to drop from code for index */
     10192  low = -1;                   /* trigger new sub-table when len > root */
     10193  used = 1 << root;          /* use root table entries */
     10194  mask = used - 1;            /* mask for comparing low */
     10195
     10196  /* check available table space */
     10197  if ((type === LENS && used > ENOUGH_LENS) ||
     10198    (type === DISTS && used > ENOUGH_DISTS)) {
     10199    return 1;
     10200  }
     10201
     10202  /* process all codes and make table entries */
     10203  for (;;) {
     10204    /* create table entry */
     10205    here_bits = len - drop;
     10206    if (work[sym] < end) {
     10207      here_op = 0;
     10208      here_val = work[sym];
     10209    }
     10210    else if (work[sym] > end) {
     10211      here_op = extra[extra_index + work[sym]];
     10212      here_val = base[base_index + work[sym]];
     10213    }
     10214    else {
     10215      here_op = 32 + 64;         /* end of block */
     10216      here_val = 0;
     10217    }
     10218
     10219    /* replicate for those indices with low len bits equal to huff */
     10220    incr = 1 << (len - drop);
     10221    fill = 1 << curr;
     10222    min = fill;                 /* save offset to next table */
     10223    do {
     10224      fill -= incr;
     10225      table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
     10226    } while (fill !== 0);
     10227
     10228    /* backwards increment the len-bit code huff */
     10229    incr = 1 << (len - 1);
     10230    while (huff & incr) {
     10231      incr >>= 1;
     10232    }
     10233    if (incr !== 0) {
     10234      huff &= incr - 1;
     10235      huff += incr;
     10236    } else {
     10237      huff = 0;
     10238    }
     10239
     10240    /* go to next symbol, update count, len */
     10241    sym++;
     10242    if (--count[len] === 0) {
     10243      if (len === max) { break; }
     10244      len = lens[lens_index + work[sym]];
     10245    }
     10246
     10247    /* create new sub-table if needed */
     10248    if (len > root && (huff & mask) !== low) {
     10249      /* if first time, transition to sub-tables */
     10250      if (drop === 0) {
     10251        drop = root;
     10252      }
     10253
     10254      /* increment past last table */
     10255      next += min;            /* here min is 1 << curr */
     10256
     10257      /* determine length of next table */
     10258      curr = len - drop;
     10259      left = 1 << curr;
     10260      while (curr + drop < max) {
     10261        left -= count[curr + drop];
     10262        if (left <= 0) { break; }
     10263        curr++;
     10264        left <<= 1;
     10265      }
     10266
     10267      /* check for enough space */
     10268      used += 1 << curr;
     10269      if ((type === LENS && used > ENOUGH_LENS) ||
     10270        (type === DISTS && used > ENOUGH_DISTS)) {
     10271        return 1;
     10272      }
     10273
     10274      /* point entry in root table to sub-table */
     10275      low = huff & mask;
     10276      /*table.op[low] = curr;
     10277      table.bits[low] = root;
     10278      table.val[low] = next - opts.table_index;*/
     10279      table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
     10280    }
     10281  }
     10282
     10283  /* fill in remaining table entry if code is incomplete (guaranteed to have
     10284   at most one remaining entry, since if the code is incomplete, the
     10285   maximum code length that was allowed to get this far is one bit) */
     10286  if (huff !== 0) {
     10287    //table.op[next + huff] = 64;            /* invalid code marker */
     10288    //table.bits[next + huff] = len - drop;
     10289    //table.val[next + huff] = 0;
     10290    table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
     10291  }
     10292
     10293  /* set return parameters */
     10294  //opts.table_index += used;
     10295  opts.bits = root;
     10296  return 0;
     10297};
     10298
     10299},{"../utils/common":62}],72:[function(require,module,exports){
     10300'use strict';
     10301
     10302// (C) 1995-2013 Jean-loup Gailly and Mark Adler
     10303// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
     10304//
     10305// This software is provided 'as-is', without any express or implied
     10306// warranty. In no event will the authors be held liable for any damages
     10307// arising from the use of this software.
     10308//
     10309// Permission is granted to anyone to use this software for any purpose,
     10310// including commercial applications, and to alter it and redistribute it
     10311// freely, subject to the following restrictions:
     10312//
     10313// 1. The origin of this software must not be misrepresented; you must not
     10314//   claim that you wrote the original software. If you use this software
     10315//   in a product, an acknowledgment in the product documentation would be
     10316//   appreciated but is not required.
     10317// 2. Altered source versions must be plainly marked as such, and must not be
     10318//   misrepresented as being the original software.
     10319// 3. This notice may not be removed or altered from any source distribution.
     10320
     10321module.exports = {
     10322  2:      'need dictionary',     /* Z_NEED_DICT       2  */
     10323  1:      'stream end',          /* Z_STREAM_END      1  */
     10324  0:      '',                    /* Z_OK              0  */
     10325  '-1':   'file error',          /* Z_ERRNO         (-1) */
     10326  '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
     10327  '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
     10328  '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
     10329  '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
     10330  '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
     10331};
     10332
     10333},{}],73:[function(require,module,exports){
     10334'use strict';
     10335
     10336// (C) 1995-2013 Jean-loup Gailly and Mark Adler
     10337// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
     10338//
     10339// This software is provided 'as-is', without any express or implied
     10340// warranty. In no event will the authors be held liable for any damages
     10341// arising from the use of this software.
     10342//
     10343// Permission is granted to anyone to use this software for any purpose,
     10344// including commercial applications, and to alter it and redistribute it
     10345// freely, subject to the following restrictions:
     10346//
     10347// 1. The origin of this software must not be misrepresented; you must not
     10348//   claim that you wrote the original software. If you use this software
     10349//   in a product, an acknowledgment in the product documentation would be
     10350//   appreciated but is not required.
     10351// 2. Altered source versions must be plainly marked as such, and must not be
     10352//   misrepresented as being the original software.
     10353// 3. This notice may not be removed or altered from any source distribution.
     10354
     10355var utils = require('../utils/common');
     10356
     10357/* Public constants ==========================================================*/
     10358/* ===========================================================================*/
     10359
     10360
     10361//var Z_FILTERED          = 1;
     10362//var Z_HUFFMAN_ONLY      = 2;
     10363//var Z_RLE               = 3;
     10364var Z_FIXED               = 4;
     10365//var Z_DEFAULT_STRATEGY  = 0;
     10366
     10367/* Possible values of the data_type field (though see inflate()) */
     10368var Z_BINARY              = 0;
     10369var Z_TEXT                = 1;
     10370//var Z_ASCII             = 1; // = Z_TEXT
     10371var Z_UNKNOWN             = 2;
     10372
     10373/*============================================================================*/
     10374
     10375
     10376function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
     10377
     10378// From zutil.h
     10379
     10380var STORED_BLOCK = 0;
     10381var STATIC_TREES = 1;
     10382var DYN_TREES    = 2;
     10383/* The three kinds of block type */
     10384
     10385var MIN_MATCH    = 3;
     10386var MAX_MATCH    = 258;
     10387/* The minimum and maximum match lengths */
     10388
     10389// From deflate.h
     10390/* ===========================================================================
     10391 * Internal compression state.
     10392 */
     10393
     10394var LENGTH_CODES  = 29;
     10395/* number of length codes, not counting the special END_BLOCK code */
     10396
     10397var LITERALS      = 256;
     10398/* number of literal bytes 0..255 */
     10399
     10400var L_CODES       = LITERALS + 1 + LENGTH_CODES;
     10401/* number of Literal or Length codes, including the END_BLOCK code */
     10402
     10403var D_CODES       = 30;
     10404/* number of distance codes */
     10405
     10406var BL_CODES      = 19;
     10407/* number of codes used to transfer the bit lengths */
     10408
     10409var HEAP_SIZE     = 2 * L_CODES + 1;
     10410/* maximum heap size */
     10411
     10412var MAX_BITS      = 15;
     10413/* All codes must not exceed MAX_BITS bits */
     10414
     10415var Buf_size      = 16;
     10416/* size of bit buffer in bi_buf */
     10417
     10418
     10419/* ===========================================================================
     10420 * Constants
     10421 */
     10422
     10423var MAX_BL_BITS = 7;
     10424/* Bit length codes must not exceed MAX_BL_BITS bits */
     10425
     10426var END_BLOCK   = 256;
     10427/* end of block literal code */
     10428
     10429var REP_3_6     = 16;
     10430/* repeat previous bit length 3-6 times (2 bits of repeat count) */
     10431
     10432var REPZ_3_10   = 17;
     10433/* repeat a zero length 3-10 times  (3 bits of repeat count) */
     10434
     10435var REPZ_11_138 = 18;
     10436/* repeat a zero length 11-138 times  (7 bits of repeat count) */
     10437
     10438/* eslint-disable comma-spacing,array-bracket-spacing */
     10439var extra_lbits =   /* extra bits for each length code */
     10440  [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];
     10441
     10442var extra_dbits =   /* extra bits for each distance code */
     10443  [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];
     10444
     10445var extra_blbits =  /* extra bits for each bit length code */
     10446  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
     10447
     10448var bl_order =
     10449  [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
     10450/* eslint-enable comma-spacing,array-bracket-spacing */
     10451
     10452/* The lengths of the bit length codes are sent in order of decreasing
     10453 * probability, to avoid transmitting the lengths for unused bit length codes.
     10454 */
     10455
     10456/* ===========================================================================
     10457 * Local data. These are initialized only once.
     10458 */
     10459
     10460// We pre-fill arrays with 0 to avoid uninitialized gaps
     10461
     10462var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
     10463
     10464// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
     10465var static_ltree  = new Array((L_CODES + 2) * 2);
     10466zero(static_ltree);
     10467/* The static literal tree. Since the bit lengths are imposed, there is no
     10468 * need for the L_CODES extra codes used during heap construction. However
     10469 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
     10470 * below).
     10471 */
     10472
     10473var static_dtree  = new Array(D_CODES * 2);
     10474zero(static_dtree);
     10475/* The static distance tree. (Actually a trivial tree since all codes use
     10476 * 5 bits.)
     10477 */
     10478
     10479var _dist_code    = new Array(DIST_CODE_LEN);
     10480zero(_dist_code);
     10481/* Distance codes. The first 256 values correspond to the distances
     10482 * 3 .. 258, the last 256 values correspond to the top 8 bits of
     10483 * the 15 bit distances.
     10484 */
     10485
     10486var _length_code  = new Array(MAX_MATCH - MIN_MATCH + 1);
     10487zero(_length_code);
     10488/* length code for each normalized match length (0 == MIN_MATCH) */
     10489
     10490var base_length   = new Array(LENGTH_CODES);
     10491zero(base_length);
     10492/* First normalized length for each code (0 = MIN_MATCH) */
     10493
     10494var base_dist     = new Array(D_CODES);
     10495zero(base_dist);
     10496/* First normalized distance for each code (0 = distance of 1) */
     10497
     10498
     10499function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
     10500
     10501  this.static_tree  = static_tree;  /* static tree or NULL */
     10502  this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
     10503  this.extra_base   = extra_base;   /* base index for extra_bits */
     10504  this.elems        = elems;        /* max number of elements in the tree */
     10505  this.max_length   = max_length;   /* max bit length for the codes */
     10506
     10507  // show if `static_tree` has data or dummy - needed for monomorphic objects
     10508  this.has_stree    = static_tree && static_tree.length;
     10509}
     10510
     10511
     10512var static_l_desc;
     10513var static_d_desc;
     10514var static_bl_desc;
     10515
     10516
     10517function TreeDesc(dyn_tree, stat_desc) {
     10518  this.dyn_tree = dyn_tree;     /* the dynamic tree */
     10519  this.max_code = 0;            /* largest code with non zero frequency */
     10520  this.stat_desc = stat_desc;   /* the corresponding static tree */
     10521}
     10522
     10523
     10524
     10525function d_code(dist) {
     10526  return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
     10527}
     10528
     10529
     10530/* ===========================================================================
     10531 * Output a short LSB first on the stream.
     10532 * IN assertion: there is enough room in pendingBuf.
     10533 */
     10534function put_short(s, w) {
     10535//    put_byte(s, (uch)((w) & 0xff));
     10536//    put_byte(s, (uch)((ush)(w) >> 8));
     10537  s.pending_buf[s.pending++] = (w) & 0xff;
     10538  s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
     10539}
     10540
     10541
     10542/* ===========================================================================
     10543 * Send a value on a given number of bits.
     10544 * IN assertion: length <= 16 and value fits in length bits.
     10545 */
     10546function send_bits(s, value, length) {
     10547  if (s.bi_valid > (Buf_size - length)) {
     10548    s.bi_buf |= (value << s.bi_valid) & 0xffff;
     10549    put_short(s, s.bi_buf);
     10550    s.bi_buf = value >> (Buf_size - s.bi_valid);
     10551    s.bi_valid += length - Buf_size;
     10552  } else {
     10553    s.bi_buf |= (value << s.bi_valid) & 0xffff;
     10554    s.bi_valid += length;
     10555  }
     10556}
     10557
     10558
     10559function send_code(s, c, tree) {
     10560  send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
     10561}
     10562
     10563
     10564/* ===========================================================================
     10565 * Reverse the first len bits of a code, using straightforward code (a faster
     10566 * method would use a table)
     10567 * IN assertion: 1 <= len <= 15
     10568 */
     10569function bi_reverse(code, len) {
     10570  var res = 0;
     10571  do {
     10572    res |= code & 1;
     10573    code >>>= 1;
     10574    res <<= 1;
     10575  } while (--len > 0);
     10576  return res >>> 1;
     10577}
     10578
     10579
     10580/* ===========================================================================
     10581 * Flush the bit buffer, keeping at most 7 bits in it.
     10582 */
     10583function bi_flush(s) {
     10584  if (s.bi_valid === 16) {
     10585    put_short(s, s.bi_buf);
     10586    s.bi_buf = 0;
     10587    s.bi_valid = 0;
     10588
     10589  } else if (s.bi_valid >= 8) {
     10590    s.pending_buf[s.pending++] = s.bi_buf & 0xff;
     10591    s.bi_buf >>= 8;
     10592    s.bi_valid -= 8;
     10593  }
     10594}
     10595
     10596
     10597/* ===========================================================================
     10598 * Compute the optimal bit lengths for a tree and update the total bit length
     10599 * for the current block.
     10600 * IN assertion: the fields freq and dad are set, heap[heap_max] and
     10601 *    above are the tree nodes sorted by increasing frequency.
     10602 * OUT assertions: the field len is set to the optimal bit length, the
     10603 *     array bl_count contains the frequencies for each bit length.
     10604 *     The length opt_len is updated; static_len is also updated if stree is
     10605 *     not null.
     10606 */
     10607function gen_bitlen(s, desc)
     10608//    deflate_state *s;
     10609//    tree_desc *desc;    /* the tree descriptor */
     10610{
     10611  var tree            = desc.dyn_tree;
     10612  var max_code        = desc.max_code;
     10613  var stree           = desc.stat_desc.static_tree;
     10614  var has_stree       = desc.stat_desc.has_stree;
     10615  var extra           = desc.stat_desc.extra_bits;
     10616  var base            = desc.stat_desc.extra_base;
     10617  var max_length      = desc.stat_desc.max_length;
     10618  var h;              /* heap index */
     10619  var n, m;           /* iterate over the tree elements */
     10620  var bits;           /* bit length */
     10621  var xbits;          /* extra bits */
     10622  var f;              /* frequency */
     10623  var overflow = 0;   /* number of elements with bit length too large */
     10624
     10625  for (bits = 0; bits <= MAX_BITS; bits++) {
     10626    s.bl_count[bits] = 0;
     10627  }
     10628
     10629  /* In a first pass, compute the optimal bit lengths (which may
     10630   * overflow in the case of the bit length tree).
     10631   */
     10632  tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
     10633
     10634  for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
     10635    n = s.heap[h];
     10636    bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
     10637    if (bits > max_length) {
     10638      bits = max_length;
     10639      overflow++;
     10640    }
     10641    tree[n * 2 + 1]/*.Len*/ = bits;
     10642    /* We overwrite tree[n].Dad which is no longer needed */
     10643
     10644    if (n > max_code) { continue; } /* not a leaf node */
     10645
     10646    s.bl_count[bits]++;
     10647    xbits = 0;
     10648    if (n >= base) {
     10649      xbits = extra[n - base];
     10650    }
     10651    f = tree[n * 2]/*.Freq*/;
     10652    s.opt_len += f * (bits + xbits);
     10653    if (has_stree) {
     10654      s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
     10655    }
     10656  }
     10657  if (overflow === 0) { return; }
     10658
     10659  // Trace((stderr,"\nbit length overflow\n"));
     10660  /* This happens for example on obj2 and pic of the Calgary corpus */
     10661
     10662  /* Find the first bit length which could increase: */
     10663  do {
     10664    bits = max_length - 1;
     10665    while (s.bl_count[bits] === 0) { bits--; }
     10666    s.bl_count[bits]--;      /* move one leaf down the tree */
     10667    s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
     10668    s.bl_count[max_length]--;
     10669    /* The brother of the overflow item also moves one step up,
     10670     * but this does not affect bl_count[max_length]
     10671     */
     10672    overflow -= 2;
     10673  } while (overflow > 0);
     10674
     10675  /* Now recompute all bit lengths, scanning in increasing frequency.
     10676   * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
     10677   * lengths instead of fixing only the wrong ones. This idea is taken
     10678   * from 'ar' written by Haruhiko Okumura.)
     10679   */
     10680  for (bits = max_length; bits !== 0; bits--) {
     10681    n = s.bl_count[bits];
     10682    while (n !== 0) {
     10683      m = s.heap[--h];
     10684      if (m > max_code) { continue; }
     10685      if (tree[m * 2 + 1]/*.Len*/ !== bits) {
     10686        // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
     10687        s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
     10688        tree[m * 2 + 1]/*.Len*/ = bits;
     10689      }
     10690      n--;
     10691    }
     10692  }
     10693}
     10694
     10695
     10696/* ===========================================================================
     10697 * Generate the codes for a given tree and bit counts (which need not be
     10698 * optimal).
     10699 * IN assertion: the array bl_count contains the bit length statistics for
     10700 * the given tree and the field len is set for all tree elements.
     10701 * OUT assertion: the field code is set for all tree elements of non
     10702 *     zero code length.
     10703 */
     10704function gen_codes(tree, max_code, bl_count)
     10705//    ct_data *tree;             /* the tree to decorate */
     10706//    int max_code;              /* largest code with non zero frequency */
     10707//    ushf *bl_count;            /* number of codes at each bit length */
     10708{
     10709  var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
     10710  var code = 0;              /* running code value */
     10711  var bits;                  /* bit index */
     10712  var n;                     /* code index */
     10713
     10714  /* The distribution counts are first used to generate the code values
     10715   * without bit reversal.
     10716   */
     10717  for (bits = 1; bits <= MAX_BITS; bits++) {
     10718    next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
     10719  }
     10720  /* Check that the bit counts in bl_count are consistent. The last code
     10721   * must be all ones.
     10722   */
     10723  //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
     10724  //        "inconsistent bit counts");
     10725  //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
     10726
     10727  for (n = 0;  n <= max_code; n++) {
     10728    var len = tree[n * 2 + 1]/*.Len*/;
     10729    if (len === 0) { continue; }
     10730    /* Now reverse the bits */
     10731    tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
     10732
     10733    //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
     10734    //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
     10735  }
     10736}
     10737
     10738
     10739/* ===========================================================================
     10740 * Initialize the various 'constant' tables.
     10741 */
     10742function tr_static_init() {
     10743  var n;        /* iterates over tree elements */
     10744  var bits;     /* bit counter */
     10745  var length;   /* length value */
     10746  var code;     /* code value */
     10747  var dist;     /* distance index */
     10748  var bl_count = new Array(MAX_BITS + 1);
     10749  /* number of codes at each bit length for an optimal tree */
     10750
     10751  // do check in _tr_init()
     10752  //if (static_init_done) return;
     10753
     10754  /* For some embedded targets, global variables are not initialized: */
     10755/*#ifdef NO_INIT_GLOBAL_POINTERS
     10756  static_l_desc.static_tree = static_ltree;
     10757  static_l_desc.extra_bits = extra_lbits;
     10758  static_d_desc.static_tree = static_dtree;
     10759  static_d_desc.extra_bits = extra_dbits;
     10760  static_bl_desc.extra_bits = extra_blbits;
     10761#endif*/
     10762
     10763  /* Initialize the mapping length (0..255) -> length code (0..28) */
     10764  length = 0;
     10765  for (code = 0; code < LENGTH_CODES - 1; code++) {
     10766    base_length[code] = length;
     10767    for (n = 0; n < (1 << extra_lbits[code]); n++) {
     10768      _length_code[length++] = code;
     10769    }
     10770  }
     10771  //Assert (length == 256, "tr_static_init: length != 256");
     10772  /* Note that the length 255 (match length 258) can be represented
     10773   * in two different ways: code 284 + 5 bits or code 285, so we
     10774   * overwrite length_code[255] to use the best encoding:
     10775   */
     10776  _length_code[length - 1] = code;
     10777
     10778  /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
     10779  dist = 0;
     10780  for (code = 0; code < 16; code++) {
     10781    base_dist[code] = dist;
     10782    for (n = 0; n < (1 << extra_dbits[code]); n++) {
     10783      _dist_code[dist++] = code;
     10784    }
     10785  }
     10786  //Assert (dist == 256, "tr_static_init: dist != 256");
     10787  dist >>= 7; /* from now on, all distances are divided by 128 */
     10788  for (; code < D_CODES; code++) {
     10789    base_dist[code] = dist << 7;
     10790    for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
     10791      _dist_code[256 + dist++] = code;
     10792    }
     10793  }
     10794  //Assert (dist == 256, "tr_static_init: 256+dist != 512");
     10795
     10796  /* Construct the codes of the static literal tree */
     10797  for (bits = 0; bits <= MAX_BITS; bits++) {
     10798    bl_count[bits] = 0;
     10799  }
     10800
     10801  n = 0;
     10802  while (n <= 143) {
     10803    static_ltree[n * 2 + 1]/*.Len*/ = 8;
     10804    n++;
     10805    bl_count[8]++;
     10806  }
     10807  while (n <= 255) {
     10808    static_ltree[n * 2 + 1]/*.Len*/ = 9;
     10809    n++;
     10810    bl_count[9]++;
     10811  }
     10812  while (n <= 279) {
     10813    static_ltree[n * 2 + 1]/*.Len*/ = 7;
     10814    n++;
     10815    bl_count[7]++;
     10816  }
     10817  while (n <= 287) {
     10818    static_ltree[n * 2 + 1]/*.Len*/ = 8;
     10819    n++;
     10820    bl_count[8]++;
     10821  }
     10822  /* Codes 286 and 287 do not exist, but we must include them in the
     10823   * tree construction to get a canonical Huffman tree (longest code
     10824   * all ones)
     10825   */
     10826  gen_codes(static_ltree, L_CODES + 1, bl_count);
     10827
     10828  /* The static distance tree is trivial: */
     10829  for (n = 0; n < D_CODES; n++) {
     10830    static_dtree[n * 2 + 1]/*.Len*/ = 5;
     10831    static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
     10832  }
     10833
     10834  // Now data ready and we can init static trees
     10835  static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
     10836  static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
     10837  static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);
     10838
     10839  //static_init_done = true;
     10840}
     10841
     10842
     10843/* ===========================================================================
     10844 * Initialize a new block.
     10845 */
     10846function init_block(s) {
     10847  var n; /* iterates over tree elements */
     10848
     10849  /* Initialize the trees. */
     10850  for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
     10851  for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
     10852  for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
     10853
     10854  s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
     10855  s.opt_len = s.static_len = 0;
     10856  s.last_lit = s.matches = 0;
     10857}
     10858
     10859
     10860/* ===========================================================================
     10861 * Flush the bit buffer and align the output on a byte boundary
     10862 */
     10863function bi_windup(s)
     10864{
     10865  if (s.bi_valid > 8) {
     10866    put_short(s, s.bi_buf);
     10867  } else if (s.bi_valid > 0) {
     10868    //put_byte(s, (Byte)s->bi_buf);
     10869    s.pending_buf[s.pending++] = s.bi_buf;
     10870  }
     10871  s.bi_buf = 0;
     10872  s.bi_valid = 0;
     10873}
     10874
     10875/* ===========================================================================
     10876 * Copy a stored block, storing first the length and its
     10877 * one's complement if requested.
     10878 */
     10879function copy_block(s, buf, len, header)
     10880//DeflateState *s;
     10881//charf    *buf;    /* the input data */
     10882//unsigned len;     /* its length */
     10883//int      header;  /* true if block header must be written */
     10884{
     10885  bi_windup(s);        /* align on byte boundary */
     10886
     10887  if (header) {
     10888    put_short(s, len);
     10889    put_short(s, ~len);
     10890  }
     10891//  while (len--) {
     10892//    put_byte(s, *buf++);
     10893//  }
     10894  utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
     10895  s.pending += len;
     10896}
     10897
     10898/* ===========================================================================
     10899 * Compares to subtrees, using the tree depth as tie breaker when
     10900 * the subtrees have equal frequency. This minimizes the worst case length.
     10901 */
     10902function smaller(tree, n, m, depth) {
     10903  var _n2 = n * 2;
     10904  var _m2 = m * 2;
     10905  return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
     10906         (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
     10907}
     10908
     10909/* ===========================================================================
     10910 * Restore the heap property by moving down the tree starting at node k,
     10911 * exchanging a node with the smallest of its two sons if necessary, stopping
     10912 * when the heap property is re-established (each father smaller than its
     10913 * two sons).
     10914 */
     10915function pqdownheap(s, tree, k)
     10916//    deflate_state *s;
     10917//    ct_data *tree;  /* the tree to restore */
     10918//    int k;               /* node to move down */
     10919{
     10920  var v = s.heap[k];
     10921  var j = k << 1;  /* left son of k */
     10922  while (j <= s.heap_len) {
     10923    /* Set j to the smallest of the two sons: */
     10924    if (j < s.heap_len &&
     10925      smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
     10926      j++;
     10927    }
     10928    /* Exit if v is smaller than both sons */
     10929    if (smaller(tree, v, s.heap[j], s.depth)) { break; }
     10930
     10931    /* Exchange v with the smallest son */
     10932    s.heap[k] = s.heap[j];
     10933    k = j;
     10934
     10935    /* And continue down the tree, setting j to the left son of k */
     10936    j <<= 1;
     10937  }
     10938  s.heap[k] = v;
     10939}
     10940
     10941
     10942// inlined manually
     10943// var SMALLEST = 1;
     10944
     10945/* ===========================================================================
     10946 * Send the block data compressed using the given Huffman trees
     10947 */
     10948function compress_block(s, ltree, dtree)
     10949//    deflate_state *s;
     10950//    const ct_data *ltree; /* literal tree */
     10951//    const ct_data *dtree; /* distance tree */
     10952{
     10953  var dist;           /* distance of matched string */
     10954  var lc;             /* match length or unmatched char (if dist == 0) */
     10955  var lx = 0;         /* running index in l_buf */
     10956  var code;           /* the code to send */
     10957  var extra;          /* number of extra bits to send */
     10958
     10959  if (s.last_lit !== 0) {
     10960    do {
     10961      dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
     10962      lc = s.pending_buf[s.l_buf + lx];
     10963      lx++;
     10964
     10965      if (dist === 0) {
     10966        send_code(s, lc, ltree); /* send a literal byte */
     10967        //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
     10968      } else {
     10969        /* Here, lc is the match length - MIN_MATCH */
     10970        code = _length_code[lc];
     10971        send_code(s, code + LITERALS + 1, ltree); /* send the length code */
     10972        extra = extra_lbits[code];
     10973        if (extra !== 0) {
     10974          lc -= base_length[code];
     10975          send_bits(s, lc, extra);       /* send the extra length bits */
     10976        }
     10977        dist--; /* dist is now the match distance - 1 */
     10978        code = d_code(dist);
     10979        //Assert (code < D_CODES, "bad d_code");
     10980
     10981        send_code(s, code, dtree);       /* send the distance code */
     10982        extra = extra_dbits[code];
     10983        if (extra !== 0) {
     10984          dist -= base_dist[code];
     10985          send_bits(s, dist, extra);   /* send the extra distance bits */
     10986        }
     10987      } /* literal or match pair ? */
     10988
     10989      /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
     10990      //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
     10991      //       "pendingBuf overflow");
     10992
     10993    } while (lx < s.last_lit);
     10994  }
     10995
     10996  send_code(s, END_BLOCK, ltree);
     10997}
     10998
     10999
     11000/* ===========================================================================
     11001 * Construct one Huffman tree and assigns the code bit strings and lengths.
     11002 * Update the total bit length for the current block.
     11003 * IN assertion: the field freq is set for all tree elements.
     11004 * OUT assertions: the fields len and code are set to the optimal bit length
     11005 *     and corresponding code. The length opt_len is updated; static_len is
     11006 *     also updated if stree is not null. The field max_code is set.
     11007 */
     11008function build_tree(s, desc)
     11009//    deflate_state *s;
     11010//    tree_desc *desc; /* the tree descriptor */
     11011{
     11012  var tree     = desc.dyn_tree;
     11013  var stree    = desc.stat_desc.static_tree;
     11014  var has_stree = desc.stat_desc.has_stree;
     11015  var elems    = desc.stat_desc.elems;
     11016  var n, m;          /* iterate over heap elements */
     11017  var max_code = -1; /* largest code with non zero frequency */
     11018  var node;          /* new node being created */
     11019
     11020  /* Construct the initial heap, with least frequent element in
     11021   * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
     11022   * heap[0] is not used.
     11023   */
     11024  s.heap_len = 0;
     11025  s.heap_max = HEAP_SIZE;
     11026
     11027  for (n = 0; n < elems; n++) {
     11028    if (tree[n * 2]/*.Freq*/ !== 0) {
     11029      s.heap[++s.heap_len] = max_code = n;
     11030      s.depth[n] = 0;
     11031
     11032    } else {
     11033      tree[n * 2 + 1]/*.Len*/ = 0;
     11034    }
     11035  }
     11036
     11037  /* The pkzip format requires that at least one distance code exists,
     11038   * and that at least one bit should be sent even if there is only one
     11039   * possible code. So to avoid special checks later on we force at least
     11040   * two codes of non zero frequency.
     11041   */
     11042  while (s.heap_len < 2) {
     11043    node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
     11044    tree[node * 2]/*.Freq*/ = 1;
     11045    s.depth[node] = 0;
     11046    s.opt_len--;
     11047
     11048    if (has_stree) {
     11049      s.static_len -= stree[node * 2 + 1]/*.Len*/;
     11050    }
     11051    /* node is 0 or 1 so it does not have extra bits */
     11052  }
     11053  desc.max_code = max_code;
     11054
     11055  /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
     11056   * establish sub-heaps of increasing lengths:
     11057   */
     11058  for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
     11059
     11060  /* Construct the Huffman tree by repeatedly combining the least two
     11061   * frequent nodes.
     11062   */
     11063  node = elems;              /* next internal node of the tree */
     11064  do {
     11065    //pqremove(s, tree, n);  /* n = node of least frequency */
     11066    /*** pqremove ***/
     11067    n = s.heap[1/*SMALLEST*/];
     11068    s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
     11069    pqdownheap(s, tree, 1/*SMALLEST*/);
     11070    /***/
     11071
     11072    m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
     11073
     11074    s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
     11075    s.heap[--s.heap_max] = m;
     11076
     11077    /* Create a new node father of n and m */
     11078    tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
     11079    s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
     11080    tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
     11081
     11082    /* and insert the new node in the heap */
     11083    s.heap[1/*SMALLEST*/] = node++;
     11084    pqdownheap(s, tree, 1/*SMALLEST*/);
     11085
     11086  } while (s.heap_len >= 2);
     11087
     11088  s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
     11089
     11090  /* At this point, the fields freq and dad are set. We can now
     11091   * generate the bit lengths.
     11092   */
     11093  gen_bitlen(s, desc);
     11094
     11095  /* The field len is now set, we can generate the bit codes */
     11096  gen_codes(tree, max_code, s.bl_count);
     11097}
     11098
     11099
     11100/* ===========================================================================
     11101 * Scan a literal or distance tree to determine the frequencies of the codes
     11102 * in the bit length tree.
     11103 */
     11104function scan_tree(s, tree, max_code)
     11105//    deflate_state *s;
     11106//    ct_data *tree;   /* the tree to be scanned */
     11107//    int max_code;    /* and its largest code of non zero frequency */
     11108{
     11109  var n;                     /* iterates over all tree elements */
     11110  var prevlen = -1;          /* last emitted length */
     11111  var curlen;                /* length of current code */
     11112
     11113  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
     11114
     11115  var count = 0;             /* repeat count of the current code */
     11116  var max_count = 7;         /* max repeat count */
     11117  var min_count = 4;         /* min repeat count */
     11118
     11119  if (nextlen === 0) {
     11120    max_count = 138;
     11121    min_count = 3;
     11122  }
     11123  tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
     11124
     11125  for (n = 0; n <= max_code; n++) {
     11126    curlen = nextlen;
     11127    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
     11128
     11129    if (++count < max_count && curlen === nextlen) {
     11130      continue;
     11131
     11132    } else if (count < min_count) {
     11133      s.bl_tree[curlen * 2]/*.Freq*/ += count;
     11134
     11135    } else if (curlen !== 0) {
     11136
     11137      if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
     11138      s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
     11139
     11140    } else if (count <= 10) {
     11141      s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
     11142
     11143    } else {
     11144      s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
     11145    }
     11146
     11147    count = 0;
     11148    prevlen = curlen;
     11149
     11150    if (nextlen === 0) {
     11151      max_count = 138;
     11152      min_count = 3;
     11153
     11154    } else if (curlen === nextlen) {
     11155      max_count = 6;
     11156      min_count = 3;
     11157
     11158    } else {
     11159      max_count = 7;
     11160      min_count = 4;
     11161    }
     11162  }
     11163}
     11164
     11165
     11166/* ===========================================================================
     11167 * Send a literal or distance tree in compressed form, using the codes in
     11168 * bl_tree.
     11169 */
     11170function send_tree(s, tree, max_code)
     11171//    deflate_state *s;
     11172//    ct_data *tree; /* the tree to be scanned */
     11173//    int max_code;       /* and its largest code of non zero frequency */
     11174{
     11175  var n;                     /* iterates over all tree elements */
     11176  var prevlen = -1;          /* last emitted length */
     11177  var curlen;                /* length of current code */
     11178
     11179  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
     11180
     11181  var count = 0;             /* repeat count of the current code */
     11182  var max_count = 7;         /* max repeat count */
     11183  var min_count = 4;         /* min repeat count */
     11184
     11185  /* tree[max_code+1].Len = -1; */  /* guard already set */
     11186  if (nextlen === 0) {
     11187    max_count = 138;
     11188    min_count = 3;
     11189  }
     11190
     11191  for (n = 0; n <= max_code; n++) {
     11192    curlen = nextlen;
     11193    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
     11194
     11195    if (++count < max_count && curlen === nextlen) {
     11196      continue;
     11197
     11198    } else if (count < min_count) {
     11199      do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
     11200
     11201    } else if (curlen !== 0) {
     11202      if (curlen !== prevlen) {
     11203        send_code(s, curlen, s.bl_tree);
     11204        count--;
     11205      }
     11206      //Assert(count >= 3 && count <= 6, " 3_6?");
     11207      send_code(s, REP_3_6, s.bl_tree);
     11208      send_bits(s, count - 3, 2);
     11209
     11210    } else if (count <= 10) {
     11211      send_code(s, REPZ_3_10, s.bl_tree);
     11212      send_bits(s, count - 3, 3);
     11213
     11214    } else {
     11215      send_code(s, REPZ_11_138, s.bl_tree);
     11216      send_bits(s, count - 11, 7);
     11217    }
     11218
     11219    count = 0;
     11220    prevlen = curlen;
     11221    if (nextlen === 0) {
     11222      max_count = 138;
     11223      min_count = 3;
     11224
     11225    } else if (curlen === nextlen) {
     11226      max_count = 6;
     11227      min_count = 3;
     11228
     11229    } else {
     11230      max_count = 7;
     11231      min_count = 4;
     11232    }
     11233  }
     11234}
     11235
     11236
     11237/* ===========================================================================
     11238 * Construct the Huffman tree for the bit lengths and return the index in
     11239 * bl_order of the last bit length code to send.
     11240 */
     11241function build_bl_tree(s) {
     11242  var max_blindex;  /* index of last bit length code of non zero freq */
     11243
     11244  /* Determine the bit length frequencies for literal and distance trees */
     11245  scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
     11246  scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
     11247
     11248  /* Build the bit length tree: */
     11249  build_tree(s, s.bl_desc);
     11250  /* opt_len now includes the length of the tree representations, except
     11251   * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
     11252   */
     11253
     11254  /* Determine the number of bit length codes to send. The pkzip format
     11255   * requires that at least 4 bit length codes be sent. (appnote.txt says
     11256   * 3 but the actual value used is 4.)
     11257   */
     11258  for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
     11259    if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
     11260      break;
     11261    }
     11262  }
     11263  /* Update opt_len to include the bit length tree and counts */
     11264  s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
     11265  //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
     11266  //        s->opt_len, s->static_len));
     11267
     11268  return max_blindex;
     11269}
     11270
     11271
     11272/* ===========================================================================
     11273 * Send the header for a block using dynamic Huffman trees: the counts, the
     11274 * lengths of the bit length codes, the literal tree and the distance tree.
     11275 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
     11276 */
     11277function send_all_trees(s, lcodes, dcodes, blcodes)
     11278//    deflate_state *s;
     11279//    int lcodes, dcodes, blcodes; /* number of codes for each tree */
     11280{
     11281  var rank;                    /* index in bl_order */
     11282
     11283  //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
     11284  //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
     11285  //        "too many codes");
     11286  //Tracev((stderr, "\nbl counts: "));
     11287  send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
     11288  send_bits(s, dcodes - 1,   5);
     11289  send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
     11290  for (rank = 0; rank < blcodes; rank++) {
     11291    //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
     11292    send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
     11293  }
     11294  //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
     11295
     11296  send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
     11297  //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
     11298
     11299  send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
     11300  //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
     11301}
     11302
     11303
     11304/* ===========================================================================
     11305 * Check if the data type is TEXT or BINARY, using the following algorithm:
     11306 * - TEXT if the two conditions below are satisfied:
     11307 *    a) There are no non-portable control characters belonging to the
     11308 *       "black list" (0..6, 14..25, 28..31).
     11309 *    b) There is at least one printable character belonging to the
     11310 *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
     11311 * - BINARY otherwise.
     11312 * - The following partially-portable control characters form a
     11313 *   "gray list" that is ignored in this detection algorithm:
     11314 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
     11315 * IN assertion: the fields Freq of dyn_ltree are set.
     11316 */
     11317function detect_data_type(s) {
     11318  /* black_mask is the bit mask of black-listed bytes
     11319   * set bits 0..6, 14..25, and 28..31
     11320   * 0xf3ffc07f = binary 11110011111111111100000001111111
     11321   */
     11322  var black_mask = 0xf3ffc07f;
     11323  var n;
     11324
     11325  /* Check for non-textual ("black-listed") bytes. */
     11326  for (n = 0; n <= 31; n++, black_mask >>>= 1) {
     11327    if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
     11328      return Z_BINARY;
     11329    }
     11330  }
     11331
     11332  /* Check for textual ("white-listed") bytes. */
     11333  if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
     11334      s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
     11335    return Z_TEXT;
     11336  }
     11337  for (n = 32; n < LITERALS; n++) {
     11338    if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
     11339      return Z_TEXT;
     11340    }
     11341  }
     11342
     11343  /* There are no "black-listed" or "white-listed" bytes:
     11344   * this stream either is empty or has tolerated ("gray-listed") bytes only.
     11345   */
     11346  return Z_BINARY;
     11347}
     11348
     11349
     11350var static_init_done = false;
     11351
     11352/* ===========================================================================
     11353 * Initialize the tree data structures for a new zlib stream.
     11354 */
     11355function _tr_init(s)
     11356{
     11357
     11358  if (!static_init_done) {
     11359    tr_static_init();
     11360    static_init_done = true;
     11361  }
     11362
     11363  s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
     11364  s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
     11365  s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
     11366
     11367  s.bi_buf = 0;
     11368  s.bi_valid = 0;
     11369
     11370  /* Initialize the first block of the first file: */
     11371  init_block(s);
     11372}
     11373
     11374
     11375/* ===========================================================================
     11376 * Send a stored block
     11377 */
     11378function _tr_stored_block(s, buf, stored_len, last)
     11379//DeflateState *s;
     11380//charf *buf;       /* input block */
     11381//ulg stored_len;   /* length of input block */
     11382//int last;         /* one if this is the last block for a file */
     11383{
     11384  send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
     11385  copy_block(s, buf, stored_len, true); /* with header */
     11386}
     11387
     11388
     11389/* ===========================================================================
     11390 * Send one empty static block to give enough lookahead for inflate.
     11391 * This takes 10 bits, of which 7 may remain in the bit buffer.
     11392 */
     11393function _tr_align(s) {
     11394  send_bits(s, STATIC_TREES << 1, 3);
     11395  send_code(s, END_BLOCK, static_ltree);
     11396  bi_flush(s);
     11397}
     11398
     11399
     11400/* ===========================================================================
     11401 * Determine the best encoding for the current block: dynamic trees, static
     11402 * trees or store, and output the encoded block to the zip file.
     11403 */
     11404function _tr_flush_block(s, buf, stored_len, last)
     11405//DeflateState *s;
     11406//charf *buf;       /* input block, or NULL if too old */
     11407//ulg stored_len;   /* length of input block */
     11408//int last;         /* one if this is the last block for a file */
     11409{
     11410  var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
     11411  var max_blindex = 0;        /* index of last bit length code of non zero freq */
     11412
     11413  /* Build the Huffman trees unless a stored block is forced */
     11414  if (s.level > 0) {
     11415
     11416    /* Check if the file is binary or text */
     11417    if (s.strm.data_type === Z_UNKNOWN) {
     11418      s.strm.data_type = detect_data_type(s);
     11419    }
     11420
     11421    /* Construct the literal and distance trees */
     11422    build_tree(s, s.l_desc);
     11423    // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
     11424    //        s->static_len));
     11425
     11426    build_tree(s, s.d_desc);
     11427    // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
     11428    //        s->static_len));
     11429    /* At this point, opt_len and static_len are the total bit lengths of
     11430     * the compressed block data, excluding the tree representations.
     11431     */
     11432
     11433    /* Build the bit length tree for the above two trees, and get the index
     11434     * in bl_order of the last bit length code to send.
     11435     */
     11436    max_blindex = build_bl_tree(s);
     11437
     11438    /* Determine the best encoding. Compute the block lengths in bytes. */
     11439    opt_lenb = (s.opt_len + 3 + 7) >>> 3;
     11440    static_lenb = (s.static_len + 3 + 7) >>> 3;
     11441
     11442    // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
     11443    //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
     11444    //        s->last_lit));
     11445
     11446    if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
     11447
     11448  } else {
     11449    // Assert(buf != (char*)0, "lost buf");
     11450    opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
     11451  }
     11452
     11453  if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
     11454    /* 4: two words for the lengths */
     11455
     11456    /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
     11457     * Otherwise we can't have processed more than WSIZE input bytes since
     11458     * the last block flush, because compression would have been
     11459     * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
     11460     * transform a block into a stored block.
     11461     */
     11462    _tr_stored_block(s, buf, stored_len, last);
     11463
     11464  } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
     11465
     11466    send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
     11467    compress_block(s, static_ltree, static_dtree);
     11468
     11469  } else {
     11470    send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
     11471    send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
     11472    compress_block(s, s.dyn_ltree, s.dyn_dtree);
     11473  }
     11474  // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
     11475  /* The above check is made mod 2^32, for files larger than 512 MB
     11476   * and uLong implemented on 32 bits.
     11477   */
     11478  init_block(s);
     11479
     11480  if (last) {
     11481    bi_windup(s);
     11482  }
     11483  // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
     11484  //       s->compressed_len-7*last));
     11485}
     11486
     11487/* ===========================================================================
     11488 * Save the match info and tally the frequency counts. Return true if
     11489 * the current block must be flushed.
     11490 */
     11491function _tr_tally(s, dist, lc)
     11492//    deflate_state *s;
     11493//    unsigned dist;  /* distance of matched string */
     11494//    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
     11495{
     11496  //var out_length, in_length, dcode;
     11497
     11498  s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
     11499  s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
     11500
     11501  s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
     11502  s.last_lit++;
     11503
     11504  if (dist === 0) {
     11505    /* lc is the unmatched char */
     11506    s.dyn_ltree[lc * 2]/*.Freq*/++;
     11507  } else {
     11508    s.matches++;
     11509    /* Here, lc is the match length - MIN_MATCH */
     11510    dist--;             /* dist = match distance - 1 */
     11511    //Assert((ush)dist < (ush)MAX_DIST(s) &&
     11512    //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
     11513    //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
     11514
     11515    s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
     11516    s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
     11517  }
     11518
     11519// (!) This block is disabled in zlib defailts,
     11520// don't enable it for binary compatibility
     11521
     11522//#ifdef TRUNCATE_BLOCK
     11523//  /* Try to guess if it is profitable to stop the current block here */
     11524//  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
     11525//    /* Compute an upper bound for the compressed length */
     11526//    out_length = s.last_lit*8;
     11527//    in_length = s.strstart - s.block_start;
     11528//
     11529//    for (dcode = 0; dcode < D_CODES; dcode++) {
     11530//      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
     11531//    }
     11532//    out_length >>>= 3;
     11533//    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
     11534//    //       s->last_lit, in_length, out_length,
     11535//    //       100L - out_length*100L/in_length));
     11536//    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
     11537//      return true;
     11538//    }
     11539//  }
     11540//#endif
     11541
     11542  return (s.last_lit === s.lit_bufsize - 1);
     11543  /* We avoid equality with lit_bufsize because of wraparound at 64K
     11544   * on 16 bit machines and because stored blocks are restricted to
     11545   * 64K-1 bytes.
     11546   */
     11547}
     11548
     11549exports._tr_init  = _tr_init;
     11550exports._tr_stored_block = _tr_stored_block;
     11551exports._tr_flush_block  = _tr_flush_block;
     11552exports._tr_tally = _tr_tally;
     11553exports._tr_align = _tr_align;
     11554
     11555},{"../utils/common":62}],74:[function(require,module,exports){
     11556'use strict';
     11557
     11558// (C) 1995-2013 Jean-loup Gailly and Mark Adler
     11559// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
     11560//
     11561// This software is provided 'as-is', without any express or implied
     11562// warranty. In no event will the authors be held liable for any damages
     11563// arising from the use of this software.
     11564//
     11565// Permission is granted to anyone to use this software for any purpose,
     11566// including commercial applications, and to alter it and redistribute it
     11567// freely, subject to the following restrictions:
     11568//
     11569// 1. The origin of this software must not be misrepresented; you must not
     11570//   claim that you wrote the original software. If you use this software
     11571//   in a product, an acknowledgment in the product documentation would be
     11572//   appreciated but is not required.
     11573// 2. Altered source versions must be plainly marked as such, and must not be
     11574//   misrepresented as being the original software.
     11575// 3. This notice may not be removed or altered from any source distribution.
     11576
     11577function ZStream() {
     11578  /* next input byte */
     11579  this.input = null; // JS specific, because we have no pointers
     11580  this.next_in = 0;
     11581  /* number of bytes available at input */
     11582  this.avail_in = 0;
     11583  /* total number of input bytes read so far */
     11584  this.total_in = 0;
     11585  /* next output byte should be put there */
     11586  this.output = null; // JS specific, because we have no pointers
     11587  this.next_out = 0;
     11588  /* remaining free space at output */
     11589  this.avail_out = 0;
     11590  /* total number of bytes output so far */
     11591  this.total_out = 0;
     11592  /* last error message, NULL if no error */
     11593  this.msg = ''/*Z_NULL*/;
     11594  /* not visible by applications */
     11595  this.state = null;
     11596  /* best guess about the data type: binary or text */
     11597  this.data_type = 2/*Z_UNKNOWN*/;
     11598  /* adler32 value of the uncompressed data */
     11599  this.adler = 0;
     11600}
     11601
     11602module.exports = ZStream;
     11603
     11604},{}]},{},[10])(10)
     11605});
     11606 No newline at end of file
  • src/wp-includes/rest-api.php

    diff --git src/wp-includes/rest-api.php src/wp-includes/rest-api.php
    index 697a7cc..656362b 100644
    function create_initial_rest_routes() { 
    233233        // Settings.
    234234        $controller = new WP_REST_Settings_Controller;
    235235        $controller->register_routes();
     236
     237        // Plugins.
     238        $controller = new WP_REST_Plugins_Controller;
     239        $controller->register_routes();
    236240}
    237241
    238242/**
  • src/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php

    diff --git src/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php src/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php
    index e69de29..183b8be 100644
     
     1<?php
     2/**
     3 * REST API: WP_REST_Plugins_Controller class
     4 *
     5 * @package WordPress
     6 * @subpackage REST_API
     7 * @since 5.0.0
     8 */
     9
     10/**
     11 * Core class used to get a site's plugins via the REST API.
     12 *
     13 * @since 5.0.0
     14 *
     15 * @see WP_REST_Controller
     16 */
     17class WP_REST_Plugins_Controller extends WP_REST_Controller {
     18        /**
     19         * List of installed plugins.
     20         *
     21         * @var array
     22         */
     23        protected $plugins;
     24
     25        /**
     26         * Constructor.
     27         *
     28         * @since 5.0.0
     29         */
     30        public function __construct() {
     31                $this->namespace = 'wp/v2';
     32                $this->rest_base = 'plugins';
     33        }
     34
     35        /**
     36         * Registers the routes for the objects of the controller.
     37         *
     38         * @since 5.0.0
     39         *
     40         * @see register_rest_route()
     41         */
     42        public function register_routes() {
     43
     44                register_rest_route( $this->namespace, '/' . $this->rest_base, array(
     45                        array(
     46                                'methods'             => WP_REST_Server::READABLE,
     47                                'callback'            => array( $this, 'get_items' ),
     48                                'args'                => array(),
     49                                'permission_callback' => array( $this, 'get_items_permissions_check' ),
     50                        ),
     51                        'schema' => array( $this, 'get_public_item_schema' ),
     52                ) );
     53
     54                register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<slug>[\w-]+)', array(
     55                        'args' => array(
     56                                'slug' => array(
     57                                        'description' => __( 'An alphanumeric identifier for the slug of the plugin.' ),
     58                                        'type'        => 'string',
     59                                ),
     60                        ),
     61                        array(
     62                                'methods'             => WP_REST_Server::READABLE,
     63                                'callback'            => array( $this, 'get_item' ),
     64                                'permission_callback' => array( $this, 'get_item_permissions_check' ),
     65                                'args'                => array(
     66                                        'context' => $this->get_context_param( array( 'default' => 'view' ) ),
     67                                ),
     68                        ),
     69                        'schema' => array( $this, 'get_public_item_schema' ),
     70                ) );
     71        }
     72
     73        /**
     74         * Checks if a given request has access to read plugins.
     75         *
     76         * @since 5.0.0
     77         *
     78         * @param WP_REST_Request $request Full details about the request.
     79         * @return bool True if the request has read access for the item, otherwise false.
     80         */
     81        public function get_items_permissions_check( $request ) {
     82                return current_user_can( 'update_plugins' );
     83        }
     84
     85        /**
     86         * Retrieves the collection of plugins.
     87         *
     88         * @since 5.0.0
     89         *
     90         * @param WP_REST_Request $request Full details about the request.
     91         * @return WP_REST_Response Response object.
     92         */
     93        public function get_items( $request ) {
     94                $plugins  = $this->get_installed_plugins();
     95                $response = array();
     96
     97                foreach ( $plugins as $id => $plugin ) {
     98                        $response[]  = $this->prepare_item_for_response( $plugin, $request );
     99                }
     100
     101                return rest_ensure_response( $response );
     102        }
     103
     104        /**
     105         * Checks if a given request has access to read the plugin.
     106         *
     107         * @since 5.0.0
     108         *
     109         * @param WP_REST_Request $request Full details about the request.
     110         * @return bool True if the request has read access for the item, otherwise false.
     111         */
     112        public function get_item_permissions_check( $request ) {
     113                return current_user_can( 'update_plugins' );
     114        }
     115
     116        /**
     117         * Retrieves the requested plugin.
     118         *
     119         * @since 5.0.0
     120         *
     121         * @param WP_REST_Request $request Full details about the request.
     122         * @return array|WP_Error Array on success, or WP_Error object on failure.
     123         * @return WP_REST_Response Response object.
     124         */
     125        public function get_item( $request ) {
     126                $plugins = $this->get_installed_plugins();
     127                $error   = new WP_Error( 'rest_plugin_not_found', __( 'The plugin is not installed' ), array( 'status' => 404 ) );
     128
     129                $slug = $request->get_param( 'slug' );
     130
     131                if ( ! $slug ) {
     132                        return $error;
     133                }
     134
     135                $plugin = wp_list_filter( $plugins, array( 'slug' => $slug ) );
     136
     137                if ( ! $plugin ) {
     138                        return $error;
     139                }
     140
     141                $response = $this->prepare_item_for_response( $plugin, $request );
     142
     143                return rest_ensure_response( $response );
     144        }
     145
     146        /**
     147         * Prepares a single plugin output for response.
     148         *
     149         * @since 5.0.0
     150         *
     151         * @param array           $plugin  Array of Plugin header tags.
     152         * @param WP_REST_Request $request Request object.
     153         * @return array Array of plugin header tags.
     154         */
     155        public function prepare_item_for_response( $plugin, $request ) {
     156                if ( ! is_array( $plugin ) ) {
     157                        return array();
     158                }
     159
     160                if ( 'id' !== key( $plugin ) ) {
     161                        $plugin = reset( $plugin );
     162                }
     163
     164                $schema     = $this->get_item_schema();
     165                $properties = wp_list_filter( $schema['properties'], array( 'type' => 'string' ) );
     166                $data       = array();
     167                $attributes = array();
     168
     169                // Set plugin data to translate.
     170                foreach ( $properties as $property => $params ) {
     171                        if ( 'id' === $property || 'slug' === $property ) {
     172                                continue;
     173                        }
     174
     175                        $data[ $params['description'] ] = $plugin[ $property ];
     176                        $attributes[ $property ]        = $params['description'];
     177                }
     178
     179                $data = _get_plugin_data_markup_translate( $plugin['id'], $data, false, true );
     180                $data = array_map( 'strip_tags', $data );
     181
     182                // Update plugin with translated attributes
     183                foreach ( $attributes as $p => $t ) {
     184                        if ( ! isset( $data[ $t ] ) ) {
     185                                continue;
     186                        }
     187
     188                        $plugin[ $p ] = $data[ $t ];
     189                }
     190
     191                $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
     192                $plugin = $this->filter_response_by_context( $plugin, $context );
     193
     194                return $plugin;
     195        }
     196
     197        /**
     198         * Retrieves all of the installed plugins or the Rest additionnal shema.
     199         *
     200         * @since 5.0.0
     201         *
     202         * @param  boolean $schema True to get the additionnal schema.
     203         * @return array Array of registered options.
     204         */
     205        protected function get_installed_plugins( $schema = false ) {
     206                $rest_plugins = array();
     207
     208                if ( ! $this->plugins ) {
     209                        require_once ABSPATH . 'wp-admin/includes/plugin.php';
     210
     211                        $this->plugins = get_plugins();
     212                }
     213
     214                foreach ( $this->plugins as $id => $args ) {
     215                        if ( $schema ) {
     216                                $rest_args = array();
     217
     218                                $default_schema = array(
     219                                        'type'        => 'string',
     220                                        'description' => '',
     221                                        'context'     => array( 'view', 'edit', 'embed' ),
     222                                );
     223
     224                        } else {
     225                                $rest_args = array( 'id' => $id );
     226                                $slug      = dirname( $id );
     227
     228                                if ( ! $slug ) {
     229                                        continue;
     230                                }
     231
     232                                if ( '.' === $slug ) {
     233                                        $slug = wp_basename( $id, '.php' );
     234                                }
     235
     236                                $rest_args['slug'] = $slug;
     237                        }
     238
     239                        $header_keys = array_keys( $args );
     240
     241                        foreach ( array_map( 'sanitize_key', $header_keys ) as $tag_id => $header_tag ) {
     242                                if ( $schema && ! isset( $rest_plugins[ $header_tag ] ) ) {
     243                                        $rest_args['id']     = $header_tag;
     244                                        $rest_args['schema'] = wp_parse_args( array(
     245                                                'description' => $header_keys[ $tag_id ],
     246                                                'type'        => is_bool( $args[ $header_keys[ $tag_id ] ] ) ? 'boolean' : 'string',
     247                                        ), $default_schema );
     248
     249                                        $rest_plugins[ $rest_args['id'] ] = $rest_args;
     250
     251                                } else {
     252                                        $rest_args[ $header_tag ] = $args[ $header_keys[ $tag_id ] ];
     253                                }
     254                        }
     255
     256                        if ( ! $schema ) {
     257                                $rest_plugins[ $rest_args['id'] ] = $rest_args;
     258                        }
     259                }
     260
     261                return $rest_plugins;
     262        }
     263
     264        /**
     265         * Retrieves the plugins schema, conforming to JSON Schema.
     266         *
     267         * @since 5.0.0
     268         *
     269         * @return array Item schema data.
     270         */
     271        public function get_item_schema() {
     272                $plugins = $this->get_installed_plugins( true );
     273
     274                $schema = array(
     275                        '$schema'    => 'http://json-schema.org/draft-04/schema#',
     276                        'title'      => 'plugins',
     277                        'type'       => 'object',
     278                        'properties' => array(
     279                                'id'            => array(
     280                                        'description' => __( 'An alphanumeric identifier for the object unique to its directory and main php file.' ),
     281                                        'type'        => 'string',
     282                                        'context'     => array( 'view', 'edit', 'embed' ),
     283                                ),
     284                                'slug'            => array(
     285                                        'description' => __( 'An alphanumeric identifier for the object unique to its slug.' ),
     286                                        'type'        => 'string',
     287                                        'context'     => array( 'view', 'edit', 'embed' ),
     288                                ),
     289                        ),
     290                );
     291
     292                foreach ( $plugins as $property_name => $property ) {
     293                        $schema['properties'][ $property_name ] = $property['schema'];
     294                }
     295
     296                return $this->add_additional_fields_schema( $schema );
     297        }
     298}
  • src/wp-includes/script-loader.php

    diff --git src/wp-includes/script-loader.php src/wp-includes/script-loader.php
    index e6a9ef1..6b99e0b 100644
    function wp_default_scripts( &$scripts ) { 
    625625        $scripts->add( 'mce-view', "/wp-includes/js/mce-view$suffix.js", array( 'shortcode', 'jquery', 'media-views', 'media-audiovideo' ), false, 1 );
    626626
    627627        $scripts->add( 'wp-api', "/wp-includes/js/wp-api$suffix.js", array( 'jquery', 'backbone', 'underscore', 'wp-api-request' ), false, 1 );
     628        $scripts->add( 'jszip', "/wp-includes/js/jszip$suffix.js", array(), '3.1.3', 1 );
    628629
    629630        if ( is_admin() ) {
    630631                $scripts->add( 'admin-tags', "/wp-admin/js/tags$suffix.js", array( 'jquery', 'wp-ajax-response' ), false, 1 );
    function wp_default_scripts( &$scripts ) { 
    832833                        ),
    833834                ) );
    834835
     836                $scripts->add( 'plugin-upload', "/wp-admin/js/plugin-upload$suffix.js", array( 'wp-util', 'wp-api-request', 'jszip' ), false, 1 );
     837                did_action( 'init' ) && $scripts->localize( 'plugin-upload', 'pluginUploadL10n', array(
     838                        'warnOverwrite'      => __( "You are about to replace an existing plugin.\nThis action cannot be undone.\nPress 'Cancel' to stop or 'Install' to confirm." ),
     839                        'cancel'             => __( 'Cancel' ),
     840                        'pluginDetailsIntro' => __( 'About the existing plugin:' ),
     841                ) );
     842
    835843                $scripts->add( 'farbtastic', '/wp-admin/js/farbtastic.js', array('jquery'), '1.2' );
    836844
    837845                $scripts->add( 'iris', '/wp-admin/js/iris.min.js', array( 'jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch' ), '1.0.7', 1 );
  • src/wp-settings.php

    diff --git src/wp-settings.php src/wp-settings.php
    index bacf4cf..73c9cbc 100644
    require( ABSPATH . WPINC . '/rest-api/endpoints/class-wp-rest-terms-controller.p 
    234234require( ABSPATH . WPINC . '/rest-api/endpoints/class-wp-rest-users-controller.php' );
    235235require( ABSPATH . WPINC . '/rest-api/endpoints/class-wp-rest-comments-controller.php' );
    236236require( ABSPATH . WPINC . '/rest-api/endpoints/class-wp-rest-settings-controller.php' );
     237require( ABSPATH . WPINC . '/rest-api/endpoints/class-wp-rest-plugins-controller.php' );
    237238require( ABSPATH . WPINC . '/rest-api/fields/class-wp-rest-meta-fields.php' );
    238239require( ABSPATH . WPINC . '/rest-api/fields/class-wp-rest-comment-meta-fields.php' );
    239240require( ABSPATH . WPINC . '/rest-api/fields/class-wp-rest-post-meta-fields.php' );