├── popup.js
├── background.js
├── icon.gif
├── fonts
├── Dosis-Book.eot
├── Dosis-Book.ttf
├── Dosis-Book.woff
├── styles.css
└── preview.html
├── devtool.js
├── devtool.html
├── manifest.json
├── content.html
├── popup.html
├── zip
├── z-worker.js
├── zip.js
├── inflate.js
└── deflate.js
├── styles.css
└── content.js
/popup.js:
--------------------------------------------------------------------------------
1 | //console.log('Hello from -> Popup');
--------------------------------------------------------------------------------
/background.js:
--------------------------------------------------------------------------------
1 | //console.log('Hello from -> background');
--------------------------------------------------------------------------------
/icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jxdingx/chrome-SaveAllResources/HEAD/icon.gif
--------------------------------------------------------------------------------
/fonts/Dosis-Book.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jxdingx/chrome-SaveAllResources/HEAD/fonts/Dosis-Book.eot
--------------------------------------------------------------------------------
/fonts/Dosis-Book.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jxdingx/chrome-SaveAllResources/HEAD/fonts/Dosis-Book.ttf
--------------------------------------------------------------------------------
/fonts/Dosis-Book.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jxdingx/chrome-SaveAllResources/HEAD/fonts/Dosis-Book.woff
--------------------------------------------------------------------------------
/devtool.js:
--------------------------------------------------------------------------------
1 | //console.log('Hello from -> Devtool');
2 | chrome.devtools.panels.create(
3 | "ResourcesSaver",
4 | "icon.gif",
5 | "content.html",
6 | function(panel) {
7 | console.log("Content is loaded to panel");
8 | }
9 | );
--------------------------------------------------------------------------------
/fonts/styles.css:
--------------------------------------------------------------------------------
1 |
2 | @font-face {
3 | font-family: 'Dosis-Book';
4 | src: url('Dosis-Book.eot?#iefix') format('embedded-opentype'), url('Dosis-Book.woff') format('woff'), url('Dosis-Book.ttf') format('truetype'), url('Dosis-Book.svg#Dosis-Book') format('svg');
5 | font-weight: normal;
6 | font-style: normal;
7 | }
8 |
--------------------------------------------------------------------------------
/devtool.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Getting Started Extension's Popup
5 |
6 |
7 |
8 |
9 | Hello World - Devtool Here
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "update_url": "https://clients2.google.com/service/update2/crx",
3 |
4 | "name": "Save All Resources",
5 | "version": "0.0.9",
6 | "description": "UP - Save all resources files with retaining folder structure.",
7 | "icons": {
8 | "128": "icon.gif"
9 | },
10 | "browser_action": {
11 | "default_icon": "icon.gif",
12 | "default_title": "UP",
13 | "default_popup": "popup.html"
14 | },
15 | "background": {
16 | "scripts": [
17 | "background.js"
18 | ]
19 | },
20 | "permissions": [
21 | "tabs",
22 | "http://*/",
23 | "https://*/",
24 | "*://*/*",
25 | "downloads",
26 | "downloads.shelf"
27 | ],
28 | "devtools_page": "devtool.html",
29 | "manifest_version": 2
30 | }
31 |
--------------------------------------------------------------------------------
/content.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Popup
5 |
6 |
7 |
8 |
9 |
10 |
Resources Saver
11 | Save All Resources
12 |
13 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/popup.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Popup
6 |
7 |
8 |
9 |
10 |
11 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/zip/z-worker.js:
--------------------------------------------------------------------------------
1 | /* jshint worker:true */
2 | (function main(global) {
3 | "use strict";
4 |
5 | if (global.zWorkerInitialized)
6 | throw new Error('z-worker.js should be run only once');
7 | global.zWorkerInitialized = true;
8 |
9 | addEventListener("message", function(event) {
10 | var message = event.data, type = message.type, sn = message.sn;
11 | var handler = handlers[type];
12 | if (handler) {
13 | try {
14 | handler(message);
15 | } catch (e) {
16 | onError(type, sn, e);
17 | }
18 | }
19 | //for debug
20 | //postMessage({type: 'echo', originalType: type, sn: sn});
21 | });
22 |
23 | var handlers = {
24 | importScripts: doImportScripts,
25 | newTask: newTask,
26 | append: processData,
27 | flush: processData,
28 | };
29 |
30 | // deflater/inflater tasks indexed by serial numbers
31 | var tasks = {};
32 |
33 | function doImportScripts(msg) {
34 | if (msg.scripts && msg.scripts.length > 0)
35 | importScripts.apply(undefined, msg.scripts);
36 | postMessage({type: 'importScripts'});
37 | }
38 |
39 | function newTask(msg) {
40 | var CodecClass = global[msg.codecClass];
41 | var sn = msg.sn;
42 | if (tasks[sn])
43 | throw Error('duplicated sn');
44 | tasks[sn] = {
45 | codec: new CodecClass(msg.options),
46 | crcInput: msg.crcType === 'input',
47 | crcOutput: msg.crcType === 'output',
48 | crc: new Crc32(),
49 | };
50 | postMessage({type: 'newTask', sn: sn});
51 | }
52 |
53 | // performance may not be supported
54 | var now = global.performance ? global.performance.now.bind(global.performance) : Date.now;
55 |
56 | function processData(msg) {
57 | var sn = msg.sn, type = msg.type, input = msg.data;
58 | var task = tasks[sn];
59 | // allow creating codec on first append
60 | if (!task && msg.codecClass) {
61 | newTask(msg);
62 | task = tasks[sn];
63 | }
64 | var isAppend = type === 'append';
65 | var start = now();
66 | var output;
67 | if (isAppend) {
68 | try {
69 | output = task.codec.append(input, function onprogress(loaded) {
70 | postMessage({type: 'progress', sn: sn, loaded: loaded});
71 | });
72 | } catch (e) {
73 | delete tasks[sn];
74 | throw e;
75 | }
76 | } else {
77 | delete tasks[sn];
78 | output = task.codec.flush();
79 | }
80 | var codecTime = now() - start;
81 |
82 | start = now();
83 | if (input && task.crcInput)
84 | task.crc.append(input);
85 | if (output && task.crcOutput)
86 | task.crc.append(output);
87 | var crcTime = now() - start;
88 |
89 | var rmsg = {type: type, sn: sn, codecTime: codecTime, crcTime: crcTime};
90 | var transferables = [];
91 | if (output) {
92 | rmsg.data = output;
93 | transferables.push(output.buffer);
94 | }
95 | if (!isAppend && (task.crcInput || task.crcOutput))
96 | rmsg.crc = task.crc.get();
97 | postMessage(rmsg, transferables);
98 | }
99 |
100 | function onError(type, sn, e) {
101 | var msg = {
102 | type: type,
103 | sn: sn,
104 | error: formatError(e)
105 | };
106 | postMessage(msg);
107 | }
108 |
109 | function formatError(e) {
110 | return { message: e.message, stack: e.stack };
111 | }
112 |
113 | // Crc32 code copied from file zip.js
114 | function Crc32() {
115 | this.crc = -1;
116 | }
117 | Crc32.prototype.append = function append(data) {
118 | var crc = this.crc | 0, table = this.table;
119 | for (var offset = 0, len = data.length | 0; offset < len; offset++)
120 | crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xFF];
121 | this.crc = crc;
122 | };
123 | Crc32.prototype.get = function get() {
124 | return ~this.crc;
125 | };
126 | Crc32.prototype.table = (function() {
127 | var i, j, t, table = []; // Uint32Array is actually slower than []
128 | for (i = 0; i < 256; i++) {
129 | t = i;
130 | for (j = 0; j < 8; j++)
131 | if (t & 1)
132 | t = (t >>> 1) ^ 0xEDB88320;
133 | else
134 | t = t >>> 1;
135 | table[i] = t;
136 | }
137 | return table;
138 | })();
139 |
140 | // "no-op" codec
141 | function NOOP() {}
142 | global.NOOP = NOOP;
143 | NOOP.prototype.append = function append(bytes, onprogress) {
144 | return bytes;
145 | };
146 | NOOP.prototype.flush = function flush() {};
147 | })(this);
148 |
--------------------------------------------------------------------------------
/fonts/preview.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Dosis-Book
6 | - Web font preview
7 |
8 |
24 |
25 |
26 |
27 |
How to Install
28 |
Step 1
29 |
30 | Upload contents of the zip file to your web server's public directory. For example:
31 | www.yourdomain.com/css/webfont/
32 |
33 |
Step 2
34 |
35 | Add contents of
36 | styles.css
37 | to your site's style sheet.
38 |
39 |
Step 3
40 |
41 | Make sure you adjust the paths in code from
42 | styles.css
43 | to reflect the relative path on your server.
44 |
45 |
46 | For this example you need to prepend
47 | /css/webfont/
48 | to all
49 | src url
50 | definitions. Like this:
51 |
52 |
53 | @font-face {
54 | font-family: 'Dosis-Book';
55 | src: url('/css/webfont/Dosis-Book.eot?#iefix') format('embedded-opentype'), url('/css/webfont/Dosis-Book.woff') format('woff'), url('/css/webfont/Dosis-Book.ttf') format('truetype'), url('/css/webfont/Dosis-Book.svg#Dosis-Book') format('svg');
56 | font-weight: normal;
57 | font-style: normal;
58 | }
59 |
60 |
61 |
62 |
63 | H1
64 | Dosis-Book
65 |
66 |
67 | H2
68 | Donec lacinia, felis nec sagittis feugiat
69 |
70 |
71 | H3
72 | Sed ullamcorper tincidunt libero, sed tempus sem rhoncus non.
73 |
74 |
75 | H4
76 | Etiam in nulla eros, quis laoreet orci. Morbi ullamcorper tempor nunc sed ullamcorper.
77 |
78 |
79 | DEFAULT
80 | In hac habitasse platea dictumst. Sed hendrerit scelerisque pellentesque. Suspendisse id eros quis sem tristique varius sed eget velit. Phasellus pellentesque ipsum non quam vulputate euismod. Nullam eget viverra lorem. Ut eu tortor metus. Mauris eget quam nulla, eu suscipit magna. Nullam vitae lectus quam, a consequat tortor. Ut sed arcu arcu. Aliquam aliquet lacinia lorem, id tristique nunc pulvinar eget.
81 |
82 |
83 | SMALL
84 |
85 | Proin volutpat, magna at vehicula blandit, massa lectus aliquam dolor, ut porta magna odio eu nunc. Nam nisi diam, commodo vitae hendrerit non, consequat sed est. Proin fringilla, nunc non vulputate hendrerit, turpis purus vestibulum diam, a venenatis nunc lectus nec quam. Quisque euismod fermentum mauris, at accumsan mi pulvinar in. Fusce libero lectus, fringilla non congue vel, cursus nec metus. Nunc ac ante quam.
86 |
87 |
88 |
89 | BIG
90 |
91 | Curabitur auctor orci vel felis sodales porttitor. Aenean non neque auctor tellus suscipit vulputate ut quis nunc. Integer tellus purus, venenatis a cursus nec, vestibulum eget turpis. Nulla pulvinar dictum elit, vulputate sodales nunc laoreet eget. Aliquam vitae urna ac risus scelerisque iaculis.
92 |
93 |
94 |
95 |
96 |
97 |
98 | H1
99 | Dosis-Book
100 |
101 |
102 | H2
103 | Donec lacinia, felis nec sagittis feugiat
104 |
105 |
106 | H3
107 | Sed ullamcorper tincidunt libero, sed tempus sem rhoncus non.
108 |
109 |
110 | H4
111 | Etiam in nulla eros, quis laoreet orci. Morbi ullamcorper tempor nunc sed ullamcorper.
112 |
113 |
114 | DEFAULT
115 | In hac habitasse platea dictumst. Sed hendrerit scelerisque pellentesque. Suspendisse id eros quis sem tristique varius sed eget velit. Phasellus pellentesque ipsum non quam vulputate euismod. Nullam eget viverra lorem. Ut eu tortor metus. Mauris eget quam nulla, eu suscipit magna. Nullam vitae lectus quam, a consequat tortor. Ut sed arcu arcu. Aliquam aliquet lacinia lorem, id tristique nunc pulvinar eget.
116 |
117 |
118 | SMALL
119 |
120 | Proin volutpat, magna at vehicula blandit, massa lectus aliquam dolor, ut porta magna odio eu nunc. Nam nisi diam, commodo vitae hendrerit non, consequat sed est. Proin fringilla, nunc non vulputate hendrerit, turpis purus vestibulum diam, a venenatis nunc lectus nec quam. Quisque euismod fermentum mauris, at accumsan mi pulvinar in. Fusce libero lectus, fringilla non congue vel, cursus nec metus. Nunc ac ante quam.
121 |
122 |
123 |
124 | BIG
125 |
126 | Curabitur auctor orci vel felis sodales porttitor. Aenean non neque auctor tellus suscipit vulputate ut quis nunc. Integer tellus purus, venenatis a cursus nec, vestibulum eget turpis. Nulla pulvinar dictum elit, vulputate sodales nunc laoreet eget. Aliquam vitae urna ac risus scelerisque iaculis.
127 |
128 |
129 |
130 |
131 |
132 |
133 |
--------------------------------------------------------------------------------
/styles.css:
--------------------------------------------------------------------------------
1 | @import url("https://fonts.googleapis.com/css?family=Dosis:400,600");
2 | @keyframes fadeInDown {
3 | from {
4 | opacity: 0;
5 | transform: translate3d(0, -100px, 0);
6 | }
7 | to {
8 | opacity: 1;
9 | transform: translate3d(0, 0, 0);
10 | }
11 | }
12 | @keyframes fadeInLeft {
13 | from {
14 | opacity: 0;
15 | transform: translate3d(-100px, 0, 0);
16 | }
17 | to {
18 | opacity: 1;
19 | transform: translate3d(0, 0, 0);
20 | }
21 | }
22 | html, body {
23 | font-family: 'Dosis', Helvetica, Tahoma, sans-serif;
24 | font-weight: 400;
25 | font-size: 14px;
26 | letter-spacing: 0.25px;
27 | }
28 |
29 | * {
30 | margin: 0;
31 | padding: 0;
32 | outline: 0;
33 | }
34 |
35 | ul {
36 | margin: 0;
37 | padding: 10px 10px;
38 | }
39 | ul li {
40 | list-style: none;
41 | margin: 0;
42 | padding: 0 0 10px 0;
43 | }
44 |
45 | input[type=checkbox] {
46 | width: 15px;
47 | height: 15px;
48 | cursor: pointer;
49 | }
50 |
51 | label, button {
52 | cursor: pointer;
53 | }
54 |
55 | a {
56 | outline: none;
57 | text-decoration: none;
58 | transition: all .3s ease-out;
59 | color: green;
60 | }
61 | a:visited {
62 | color: green;
63 | }
64 | a:hover {
65 | color: #1aff1a;
66 | }
67 |
68 | #options {
69 | padding: 10px 0px;
70 | }
71 |
72 | .popup-body {
73 | background-color: #EEE;
74 | }
75 |
76 | .up-popup {
77 | width: 300px;
78 | padding: 15px 25px 15px 15px;
79 | border-radius: 3px;
80 | margin: 5px;
81 | box-shadow: #EEE 0px 0px 0px 5px;
82 | background-color: white;
83 | animation: fadeInDown 1s both cubic-bezier(0.1, 0.71, 0.28, 1.14) 0s 1;
84 | }
85 | .up-popup .heading {
86 | padding: 10px 0;
87 | animation: fadeInDown 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14) 0s 1;
88 | position: relative;
89 | }
90 | .up-popup .heading::after {
91 | width: 100%;
92 | height: 2px;
93 | background-color: #EEE;
94 | position: absolute;
95 | content: '';
96 | bottom: 0;
97 | left: 0;
98 | animation: fadeInDown 0.5s both cubic-bezier(0.1, 0.71, 0.28, 1.14) 0.1s 1;
99 | }
100 | .up-popup a {
101 | animation: fadeInLeft 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14) 0.2s 1;
102 | }
103 | .up-popup ul li:nth-child(1) {
104 | animation: fadeInDown 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14);
105 | animation-delay: 0.2s;
106 | }
107 | .up-popup ul li:nth-child(2) {
108 | animation: fadeInDown 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14);
109 | animation-delay: 0.3s;
110 | }
111 | .up-popup ul li:nth-child(3) {
112 | animation: fadeInDown 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14);
113 | animation-delay: 0.4s;
114 | }
115 | .up-popup ul li:nth-child(4) {
116 | animation: fadeInDown 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14);
117 | animation-delay: 0.5s;
118 | }
119 | .up-popup ul li:nth-child(5) {
120 | animation: fadeInDown 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14);
121 | animation-delay: 0.6s;
122 | }
123 | .up-popup ul li:nth-child(6) {
124 | animation: fadeInDown 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14);
125 | animation-delay: 0.7s;
126 | }
127 | .up-popup ul li:nth-child(7) {
128 | animation: fadeInDown 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14);
129 | animation-delay: 0.8s;
130 | }
131 | .up-popup ul li:nth-child(8) {
132 | animation: fadeInDown 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14);
133 | animation-delay: 0.9s;
134 | }
135 | .up-popup ul li:nth-child(9) {
136 | animation: fadeInDown 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14);
137 | animation-delay: 1s;
138 | }
139 | .up-popup ul li:nth-child(10) {
140 | animation: fadeInDown 0.75s both cubic-bezier(0.1, 0.71, 0.28, 1.14);
141 | animation-delay: 1.1s;
142 | }
143 |
144 | .sub-title {
145 | color: #999;
146 | font-size: 12px;
147 | font-weight: 600;
148 | display: block;
149 | text-align: right;
150 | }
151 |
152 | .up-content {
153 | padding: 30px;
154 | text-align: left;
155 | }
156 | .up-content h1 {
157 | padding: 10px 0;
158 | border-bottom: 1px solid #EEE;
159 | }
160 | .up-content h1 button {
161 | margin-left: 10px;
162 | padding: 5px 30px;
163 | height: 30px;
164 | background-color: cornflowerblue;
165 | vertical-align: text-bottom;
166 | }
167 | .up-content button {
168 | display: inline-block;
169 | vertical-align: text-top;
170 | border: 0;
171 | background-color: #2aa32a;
172 | color: white;
173 | padding: 3px 5px;
174 | transition: all .3s ease-out;
175 | animation: fadeInLeft 1s both cubic-bezier(0.1, 0.71, 0.28, 1.14) 0s 1;
176 | }
177 | .up-content button:hover {
178 | background-color: #185bd3;
179 | }
180 | .up-content button[disabled] {
181 | background-color: #222222;
182 | }
183 | .up-content #debug p {
184 | background-color: #EEE;
185 | padding: 15px;
186 | transition: all 0.5s cubic-bezier(0.1, 0.71, 0.28, 1.14);
187 | border-bottom: 2px solid #FFF;
188 | animation: fadeInDown 1s both cubic-bezier(0.1, 0.71, 0.28, 1.14) 0s 1;
189 | }
190 | .up-content #debug p.all-done {
191 | background-color: #e0f2de;
192 | }
193 | .up-content #debug ul {
194 | transition: all 0.5s cubic-bezier(0.1, 0.71, 0.28, 1.14);
195 | display: flex;
196 | flex-flow: row nowrap;
197 | padding: 0;
198 | animation: fadeInLeft 1s both cubic-bezier(0.1, 0.71, 0.28, 1.14) 0s 1;
199 | }
200 | .up-content #debug ul.each-done {
201 | border-bottom: 1px solid rgba(0, 128, 0, 0.5);
202 | }
203 | .up-content #debug ul.each-failed {
204 | border-bottom: 1px solid rgba(255, 0, 0, 0.5);
205 | }
206 | .up-content #debug ul li {
207 | padding: 15px;
208 | animation: fadeInLeft 1s both cubic-bezier(0.1, 0.71, 0.28, 1.14) 0.05s 1;
209 | }
210 | .up-content #debug ul li:nth-child(1) {
211 | flex: 0 0 50px;
212 | background-color: rgba(255, 236, 186, 0.5);
213 | text-align: right;
214 | animation: fadeInLeft 1s both cubic-bezier(0.1, 0.71, 0.28, 1.14) 0.1s 1;
215 | }
216 | .up-content #debug ul li:nth-child(2) {
217 | flex: 0 0 70px;
218 | background-color: rgba(255, 243, 214, 0.5);
219 | animation: fadeInLeft 1s both cubic-bezier(0.1, 0.71, 0.28, 1.14) 0.15s 1;
220 | }
221 | .up-content #debug ul li:nth-child(3) {
222 | flex: 1;
223 | word-break: break-all;
224 | background-color: rgba(255, 251, 242, 0.5);
225 | animation: fadeInLeft 1s both cubic-bezier(0.1, 0.71, 0.28, 1.14) 0.2s 1;
226 | }
227 |
228 | #status {
229 | margin-bottom: 10px;
230 | }
231 |
232 | .success {
233 | color: green;
234 | }
235 |
236 | .failed {
237 | color: red;
238 | }
239 |
--------------------------------------------------------------------------------
/content.js:
--------------------------------------------------------------------------------
1 | document.addEventListener('DOMContentLoaded', function () {
2 | // chrome.devtools.network.getHAR(function(logInfo){
3 | // console.log(logInfo);
4 | // });
5 | // reqs = []
6 | chrome.devtools.network.onRequestFinished.addListener(function (req) {
7 | // req.getContent(function (body) {
8 | // reqs.push(Object.assign({},{body: body,url: req.request.url}));
9 | // console.log(reqs[reqs.length-1],reqs.length);
10 | // setResourceCount();
11 | // })
12 | // var resolvedURL = resolveURLToPath(req.request.url).path;
13 | // if (!reqs.includes(req.request.url)) {
14 | // reqs.push(req.request.url);
15 | // }
16 | setResourceCount();
17 | });
18 |
19 | var setResourceCount = debounce(function () {
20 | if (document.getElementById('check-xhr').checked) {
21 | chrome.devtools.network.getHAR(function (logInfo) {
22 | document.getElementById('status').innerHTML = 'All requests count: ' + logInfo.entries.length;
23 | });
24 | } else {
25 | chrome.devtools.inspectedWindow.getResources(function (resources) {
26 | document.getElementById('status').innerHTML = 'Static resources count: ' + resources.length;
27 | })
28 | }
29 | }, 500);
30 |
31 |
32 | document.getElementById('up-save').addEventListener('click', saveAllResources);
33 |
34 | document.getElementById('check-xhr').addEventListener('change', function (e) {
35 | e.target.checked = !e.target.checked;
36 | if (!e.target.checked) {
37 | e.target.checked = false;
38 | document.getElementById('label-xhr').innerHTML = 'Reloading page for collecting XHR requests ...'; //Include all assets by XHR requests
39 | document.getElementById('up-save').innerHTML = 'Waiting for reload';
40 | document.getElementById('up-save').disabled = true;
41 | // Add listener, only when the check box is from unchecked to checked
42 | chrome.tabs.onUpdated.addListener(tabCompleteHandler);
43 | chrome.tabs.reload(chrome.devtools.inspectedWindow.tabId, null, function () {
44 | e.target.disabled = true;
45 | });
46 | } else {
47 | e.target.checked = false;
48 | }
49 | setResourceCount();
50 | });
51 |
52 | chrome.devtools.inspectedWindow.getResources(function (resources) {
53 | document.getElementById('status').innerHTML = 'Static resources count: ' + resources.length;
54 | })
55 |
56 | //This can be used for identifying when ever a download is done (state from in_processing to complete)
57 | // chrome.downloads.onChanged.addListener(function(downloadItem){
58 | // console.log('Download Updated': downloadItem);
59 | // });
60 |
61 | //This can be used for identifying when ever a new resource is added
62 | chrome.devtools.inspectedWindow.onResourceAdded.addListener(function (resource) {
63 | if (resource.url.indexOf('http') === 0) {
64 | // alert("resources added -> " + resource.url);
65 | // alert("resources content added " + resource.content);
66 | // console.log('Resource Added: ', resource.url);
67 | // document.getElementById('debug').innerHTML += resource.url + '\n';
68 | }
69 | });
70 |
71 | //This can be used to detect when ever a resource code is changed/updated
72 | chrome.devtools.inspectedWindow.onResourceContentCommitted.addListener(function (resource, content) {
73 | // alert("Resource Changed");
74 | // alert("New Content " + content);
75 | // alert("New Resource Object is " + resource);
76 | // console.log('Resource Commited: ', resource.url);
77 | });
78 | });
79 |
80 | function tabCompleteHandler(tabId, changeInfo) {
81 | if (tabId === chrome.devtools.inspectedWindow.tabId && changeInfo.status === 'complete') {
82 | document.getElementById('check-xhr').checked = true;
83 | document.getElementById('check-xhr').disabled = false;
84 | document.getElementById('label-xhr').innerHTML = 'Include all assets by XHR requests (require page reload).'
85 | document.getElementById('up-save').innerHTML = 'Save All Resources';
86 | document.getElementById('up-save').disabled = false;
87 | // Remove listener from further same event
88 | chrome.tabs.onUpdated.removeListener(tabCompleteHandler);
89 | }
90 | }
91 |
92 | function getXHRs(callback) {
93 | var xhrResources = [];
94 | if (document.getElementById('check-xhr').checked) {
95 | chrome.devtools.network.getHAR(function (logInfo) {
96 | logInfo.entries.map(function (entry) {
97 | xhrResources.push(Object.assign({}, entry.request, {
98 | getContent: entry.getContent
99 | }));
100 | })
101 | callback(xhrResources);
102 | });
103 | } else {
104 | callback(xhrResources);
105 | }
106 | }
107 |
108 | function saveAllResources(e) {
109 | var toDownload = [];
110 | var downloadThread = 5;
111 |
112 | // Reset Report Table
113 | document.getElementById('debug').innerHTML = '';
114 |
115 | getXHRs(function (xhrResources) {
116 | // Disable download notification
117 | chrome.downloads.setShelfEnabled(false);
118 |
119 | chrome.tabs.get(chrome.devtools.inspectedWindow.tabId, function (tab) {
120 | console.log('Save content from: ', tab.url);
121 | var domain = tab.url.split('://')[1].substring(0, tab.url.split('://')[1].indexOf('/'));
122 | //Fetching all available resources and filtering using name of script snippet added
123 | chrome.devtools.inspectedWindow.getResources(function (resources) {
124 | // resources.map(function (item) {
125 | // console.log(item);
126 | // })
127 | // alert(resources);
128 | // This function returns array of resources available in the current window
129 |
130 | // Disable button
131 | e.target.innerHTML = 'Starting Download';
132 | e.target.disabled = true;
133 |
134 | var combineResources = xhrResources.concat(resources);
135 |
136 | // Filter Resource here
137 | if (document.getElementById('check-all').checked) {
138 | for (i = 0; i < combineResources.length; i++) {
139 | // Make sure unique URL
140 | if (toDownload.findIndex(function (item) {
141 | return item.url === combineResources[i].url
142 | }) === -1) {
143 | toDownload.push(combineResources[i]);
144 | }
145 | }
146 | } else {
147 | for (i = 0; i < combineResources.length; i++) {
148 | // Matching with current snippet URL
149 | if (combineResources[i].url.indexOf('://' + domain) >= 0) {
150 | // Make sure unique URL
151 | if (toDownload.findIndex(function (item) {
152 | return item.url === combineResources[i].url
153 | }) === -1) {
154 | toDownload.push(combineResources[i]);
155 | }
156 | }
157 | }
158 | }
159 |
160 | console.log('Combine Resource: ', combineResources);
161 | console.log('Download List: ', toDownload)
162 |
163 | if (document.getElementById('check-zip').checked) {
164 | // No need to turn off notification for only one zip file
165 | chrome.downloads.setShelfEnabled(true);
166 |
167 | downloadZipFile(toDownload, allDone);
168 | } else {
169 | downloadListWithThread(toDownload, downloadThread, allDone);
170 | }
171 |
172 | });
173 | })
174 | });
175 | }
176 |
177 | function allDone(isSuccess) {
178 | // Default value
179 | if (typeof isSuccess === 'undefined') {
180 | isSuccess = true;
181 | }
182 |
183 | // Re-enable Download notification
184 | chrome.downloads.setShelfEnabled(true);
185 | var endStatus = document.createElement('p');
186 |
187 | // Report in the end
188 | if (isSuccess) {
189 | endStatus.className = 'all-done';
190 | endStatus.innerHTML = 'Downloaded All Files !!!';
191 | document.getElementById('debug').insertBefore(endStatus, document.getElementById('debug').childNodes[0]);
192 |
193 | var openDownload = document.createElement('button');
194 | openDownload.innerHTML = 'Open';
195 | openDownload.addEventListener('click', function () {
196 | chrome.downloads.showDefaultFolder();
197 | });
198 | } else {
199 | endStatus.className = 'all-done';
200 | endStatus.innerHTML = 'Something wrong, please try again or contact me for the issue.';
201 | document.getElementById('debug').insertBefore(endStatus, document.getElementById('debug').childNodes[0]);
202 | }
203 |
204 | // Restore/Change button state
205 | document.getElementById('status').innerHTML = 'Resources Folder: ';
206 | document.getElementById('status').appendChild(openDownload);
207 |
208 | document.getElementById('up-save').innerHTML = 'Re-Download?';
209 | document.getElementById('up-save').disabled = false;
210 | }
211 |
212 | function downloadListWithThread(toDownload, threadCount, callback) {
213 | document.getElementById('status').innerHTML = 'Files to download: ' + toDownload.length;
214 | var currentList = toDownload.slice(0, threadCount);
215 | var restList = toDownload.slice(threadCount);
216 | downloadURLs(currentList, function () {
217 | if (currentList.length > 0 && restList.length > 0) {
218 | downloadListWithThread(restList, threadCount, callback);
219 | } else {
220 | callback();
221 | }
222 | });
223 | }
224 |
225 | function resolveURLToPath(cUrl) {
226 | var filepath, filename, isDataURI;
227 | var foundIndex = cUrl.search(/\:\/\//);
228 | // Check the url whether it is a link or a string of text data
229 | if ((foundIndex === -1) || (foundIndex >= 10)) {
230 | isDataURI = true;
231 | console.log('Data URI Detected!!!!!');
232 |
233 | if (cUrl.indexOf('data:') === 0) {
234 | var dataURIInfo = cUrl.split(';')[0].split(',')[0].substring(0, 30).replace(/[^A-Za-z0-9]/g, '.');
235 | // console.log('=====> ',dataURIInfo);
236 | filename = dataURIInfo + '.' + Math.random().toString(16).substring(2) + '.txt';
237 | } else {
238 | filename = 'data.' + Math.random().toString(16).substring(2) + '.txt';
239 | }
240 |
241 | filepath = '_DataURI/' + filename;
242 | } else {
243 | isDataURI = false;
244 | filepath = cUrl.split('://')[1].split('?')[0];
245 | if (filepath.charAt(filepath.length - 1) === '/') {
246 | filepath = filepath + 'index.html';
247 | }
248 | filename = filepath.substring(filepath.lastIndexOf('/') + 1);
249 | }
250 |
251 | // Get Rid of QueryString after ;
252 | filepath = filepath.substring(0, filepath.lastIndexOf('/') + 1) + filename.split(';')[0];
253 |
254 | // Add default extension to non extension filename
255 | if (filename.search(/\./) === -1) {
256 | filepath = filepath + '.html';
257 | }
258 |
259 | filepath = filepath
260 | .replace(/\:|\\|\/\/|\=|\*|\.$|\"|\'|\?|\~|\||\<|\>/g, '')
261 | .replace(/(\s|\.)\//g, '/')
262 | .replace(/\/(\s|\.)/g, '/');
263 |
264 | // console.log('Save to: ', filepath);
265 | // console.log('File name: ',filename);
266 |
267 | return {
268 | path: filepath,
269 | name: filename,
270 | dataURI: isDataURI && cUrl
271 | }
272 | }
273 |
274 | function downloadURLs(urls, callback) {
275 | var currentDownloadQueue = [];
276 | urls.forEach(function (currentURL, index) {
277 | console.log('Current request: ', currentURL);
278 | var cUrl = currentURL.url;
279 | var resolvedURL = resolveURLToPath(cUrl);
280 |
281 | var filepath = resolvedURL.path;
282 | var filename = resolvedURL.name;
283 |
284 | console.log('Save to: ', filepath);
285 |
286 | currentDownloadQueue.push({
287 | index: index,
288 | url: cUrl,
289 | resolved: false
290 | });
291 |
292 | if (document.getElementById('check-cache').checked && currentURL.getContent) {
293 | currentURL.getContent(function (content, encoding) {
294 | var currentEnconding = encoding;
295 | if (filename.search(/\.(png|jpg|jpeg|gif|ico|svg)/) !== -1) {
296 | currentEnconding = 'base64';
297 | }
298 |
299 | var currentContent, finalURI;
300 |
301 | if (resolvedURL.dataURI) {
302 | currentContent = content;
303 | finalURI = 'data:text/plain;charset=UTF-8,' + encodeURIComponent(resolvedURL.dataURI);
304 | } else {
305 | currentContent = currentEnconding ? content : (function () {
306 | try {
307 | return btoa(content);
308 | } catch (err) {
309 | console.log('utoa fallback: ', currentURL.url);
310 | return btoa(unescape(encodeURIComponent(content)));
311 | }
312 | })(); //btoa(unescape(encodeURIComponent(content)))
313 |
314 | finalURI = 'data:text/plain;base64,' + currentContent;
315 | }
316 |
317 | try {
318 | chrome.downloads.download({
319 | url: finalURI, //currentURL.url
320 | filename: 'All Resources/' + filepath,
321 | saveAs: false
322 | },
323 | function (downloadId) {
324 | var currentIndex = currentDownloadQueue.findIndex(function (item) {
325 | return item.index === index
326 | });
327 | if (chrome.runtime.lastError) {
328 | console.log('URI ERR: ', chrome.runtime.lastError, filepath); // , filepath, finalURI
329 | // document.getElementById('status').innerHTML = 'Files to download: ERR occured';
330 | currentDownloadQueue[currentIndex].resolved = true;
331 | resolveCurrentDownload();
332 | } else {
333 | currentDownloadQueue[currentIndex].id = downloadId;
334 | currentDownloadQueue[currentIndex].order = currentIndex;
335 | //console.log('Create: ', JSON.stringify(currentDownloadQueue));
336 | //console.log(currentDownloadQueue);
337 | //chrome.downloads.search({
338 | // id: downloadId
339 | //}, function (item) {
340 | // //console.log(item[0].state);
341 | //})
342 | }
343 | }
344 | );
345 | } catch (runTimeErr) {
346 | console.log(runTimeErr)
347 | }
348 | });
349 | } else {
350 | try {
351 | chrome.downloads.download({
352 | url: currentURL.url,
353 | filename: 'All Resources/' + filepath,
354 | saveAs: false
355 | },
356 | function (downloadId) {
357 | var currentIndex = currentDownloadQueue.findIndex(function (item) {
358 | return item.index === index
359 | });
360 | if (chrome.runtime.lastError) {
361 | console.log('URL ERR: ', chrome.runtime.lastError, filepath); // , filepath, finalURI
362 | // document.getElementById('status').innerHTML = 'Files to download: ERR occured';
363 | currentDownloadQueue[currentIndex].resolved = true;
364 | resolveCurrentDownload();
365 | } else {
366 | currentDownloadQueue[currentIndex].id = downloadId;
367 | currentDownloadQueue[currentIndex].order = currentIndex;
368 | //console.log('Create: ', JSON.stringify(currentDownloadQueue));
369 | //console.log(currentDownloadQueue);
370 | //chrome.downloads.search({
371 | // id: downloadId
372 | //}, function (item) {
373 | // //console.log(item[0].state);
374 | //})
375 | }
376 | }
377 | );
378 | } catch (runTimeErr) {
379 | console.log(runTimeErr);
380 | }
381 | }
382 |
383 | });
384 |
385 | function resolveCurrentDownload() {
386 | var count = currentDownloadQueue.filter(function (item) {
387 | return item.resolved === true
388 | }).length;
389 | //console.log('Count: ', count, '---', urls.length);
390 | if (count === urls.length) {
391 | //console.log('Callback');
392 | currentDownloadQueue = [];
393 | callback();
394 | }
395 | };
396 |
397 | chrome.downloads.onChanged.addListener(function (downloadItem) {
398 | var index = currentDownloadQueue.findIndex(function (item) {
399 | return item.id === downloadItem.id
400 | });
401 | if (index >= 0 && downloadItem.state) {
402 | //console.log(downloadItem.state.current);
403 | if (downloadItem.state.current === 'complete') {
404 | chrome.downloads.search({
405 | id: downloadItem.id
406 | }, function (item) {
407 | chrome.downloads.erase({
408 | id: downloadItem.id
409 | }, function () {
410 | var newListUrl = currentDownloadQueue.find(function (item) {
411 | return item.id === downloadItem.id
412 | }).url;
413 |
414 | if (newListUrl.indexOf('data:') === 0) {
415 | newListUrl = 'DATA URI CONTENT';
416 | }
417 |
418 | var newList = document.createElement('ul');
419 | newList.className = 'each-done';
420 | newList.innerHTML = '' + item[0].id + ' Success ' + newListUrl + ' ';
421 | document.getElementById('debug').insertBefore(newList, document.getElementById('debug').childNodes[0]);
422 | currentDownloadQueue[index].resolved = true;
423 | resolveCurrentDownload();
424 | });
425 | });
426 | } else if (downloadItem.state.current === 'interrupted') {
427 | chrome.downloads.search({
428 | id: downloadItem.id
429 | }, function (item) {
430 | chrome.downloads.erase({
431 | id: downloadItem.id
432 | }, function () {
433 | var newList = document.createElement('ul');
434 | newList.className = 'each-failed';
435 | newList.innerHTML = '' + item[0].id + ' Failed ' + item[0].url + ' ';
436 | document.getElementById('debug').insertBefore(newList, document.getElementById('debug').childNodes[0]);
437 | currentDownloadQueue[index].resolved = true;
438 | resolveCurrentDownload();
439 | });
440 | });
441 | }
442 | }
443 | });
444 | }
445 |
446 | function downloadZipFile(toDownload, callback) {
447 | if (zip) {
448 | zip.workerScriptsPath = "zip/";
449 | getAllToDownloadContent(toDownload, function (result) {
450 | console.log(result);
451 | zip.createWriter(new zip.BlobWriter(), function (blobWriter) {
452 | addItemsToZipWriter(blobWriter, result, downloadCompleteZip.bind(this, blobWriter, callback));
453 | }, function (err) {
454 | console.log('ERROR: ', err, currentRest);
455 | // Continue on Error, error might lead to corrupted zip, so might need to escape here
456 | callback(false);
457 | });
458 | });
459 | } else {
460 | callback(false);
461 | }
462 | };
463 |
464 | function getAllToDownloadContent(toDownload, callback) {
465 | // Prepare the file list for adding into zip
466 | var result = [];
467 | var pendingDownloads = toDownload.length;
468 |
469 | // window.toDownload = toDownload;
470 |
471 | toDownload.forEach(function (item, index) {
472 | if (item.getContent) {
473 | item.getContent(function (body, encode) {
474 |
475 | if (chrome.runtime.lastError) {
476 | console.log(chrome.runtime.lastError);
477 | }
478 | // console.log(index,': ',encode,'---->',body ? body.substring(0,20) : null);
479 | var resolvedItem = resolveURLToPath(item.url);
480 | var newURL = resolvedItem.path;
481 | var filename = resolvedItem.name;
482 | var currentEnconding = encode || null;
483 |
484 | if (filename.search(/\.(png|jpg|jpeg|gif|ico|svg)/) !== -1) {
485 | currentEnconding = 'base64';
486 | }
487 |
488 | if (resolvedItem.dataURI) {
489 | currentEnconding = null;
490 | }
491 |
492 | // Make sure the file is unique, otherwise exclude
493 | var foundIndex = result.findIndex(function (currentItem) {
494 | return currentItem.url === newURL;
495 | });
496 |
497 | // Only add to result when the url is unique
498 | if (foundIndex === -1) {
499 | result.push({
500 | originalUrl: item.url,
501 | url: newURL,
502 | content: resolvedItem.dataURI || body,
503 | encoding: currentEnconding
504 | });
505 | }
506 |
507 | // Update status bar
508 | document.getElementById('status').innerHTML = 'Fetched: ' + resolvedItem.path;
509 |
510 | // Callback when all done
511 | pendingDownloads--;
512 | if (pendingDownloads === 0) {
513 | callback(result);
514 | }
515 | });
516 | } else {
517 | pendingDownloads--;
518 | }
519 | });
520 | }
521 |
522 | function addItemsToZipWriter(blobWriter, items, callback) {
523 | var item = items[0];
524 | var rest = items.slice(1);
525 |
526 | // if item exist so add it to zip
527 | if (item) {
528 | // Check whether base64 encoding is valid
529 | if (item.encoding === 'base64') {
530 | // Try to decode first
531 | try {
532 | var tryAtob = atob(item.content);
533 | } catch (err) {
534 | console.log(item.url, ' is not base64 encoding, fallback to plain text');
535 | item.encoding = null;
536 | }
537 | }
538 |
539 | // Create a reader of the content for zip
540 | var resolvedContent = (item.encoding === 'base64') ?
541 | new zip.Data64URIReader(item.content || '') :
542 | new zip.TextReader(item.content || 'No Content: ' + item.originalUrl);
543 |
544 | // Create a Row of Report Table
545 | var newList = document.createElement('ul');
546 |
547 | // Make sure the file has some byte otherwise no import to avoid corrupted zip
548 | resolvedContent.init(function () {
549 | if (resolvedContent.size > 0) {
550 | console.log(resolvedContent.size, item.encoding || 'No Encoding', item.url);
551 | blobWriter.add(item.url, resolvedContent,
552 | function () {
553 | // On Success, to the next item
554 | addItemsToZipWriter(blobWriter, rest, callback);
555 |
556 | // Update Status
557 | document.getElementById('status').innerHTML = 'Compressed: ' + item.url;
558 |
559 | // Update Report Table
560 | newList.className = 'each-done';
561 | newList.innerHTML = 'Added Success ' + item.url + ' ';
562 | document.getElementById('debug').insertBefore(newList, document.getElementById('debug').childNodes[0]);
563 | },
564 | function () {
565 | // On Progress
566 | }
567 | );
568 | } else {
569 | // If no size, exclude the item
570 | console.log('EXCLUDED: ', item.url);
571 |
572 | // Update Status
573 | document.getElementById('status').innerHTML = 'Excluded: ' + item.url;
574 |
575 | // Update Report Table
576 | newList.className = 'each-failed';
577 | newList.innerHTML = 'Excluded Failed ' + item.url + ' ';
578 | document.getElementById('debug').insertBefore(newList, document.getElementById('debug').childNodes[0]);
579 |
580 | // To the next item
581 | addItemsToZipWriter(blobWriter, rest, callback);
582 | }
583 | });
584 |
585 | } else {
586 | // Callback when all done
587 | callback();
588 | }
589 | return rest;
590 | }
591 |
592 | function downloadCompleteZip(blobWriter, callback) {
593 | // Close the writer and save it by dataURI
594 | blobWriter.close(function (blob) {
595 | chrome.downloads.download({
596 | url: URL.createObjectURL(blob),
597 | filename: 'All Resources/all.zip',
598 | saveAs: false
599 | }, function () {
600 | if (chrome.runtime.lastError) {
601 | callback(false);
602 | } else {
603 | callback(true);
604 | }
605 | });
606 | });
607 | }
608 |
609 | // Returns a function, that, as long as it continues to be invoked, will not
610 | // be triggered. The function will be called after it stops being called for
611 | // N milliseconds. If `immediate` is passed, trigger the function on the
612 | // leading edge, instead of the trailing.
613 | function debounce(func, wait, immediate) {
614 | var timeout;
615 | return function () {
616 | var context = this,
617 | args = arguments;
618 | var later = function () {
619 | timeout = null;
620 | if (!immediate) func.apply(context, args);
621 | };
622 | var callNow = immediate && !timeout;
623 | clearTimeout(timeout);
624 | timeout = setTimeout(later, wait);
625 | if (callNow) func.apply(context, args);
626 | };
627 | };
628 |
629 | // console.log('Hello from -> Content');
630 |
631 | // Communication between tab and extension
632 | // Inject a message sending from an active tab
633 | //setTimeout(function(){
634 | // chrome.tabs.executeScript(chrome.devtools.inspectedWindow.tabId, {
635 | // code: 'window.addEventListener("load", function(){chrome.runtime.sendMessage({type: "RELOADED"})}, false);'
636 | // });
637 | //},3000);
638 |
639 | // Communication between tab and extension
640 | // Function when this extension get an message event and react that
641 | //chrome.runtime.onMessage.addListener(
642 | // function(request, sender, sendResponse) {
643 | // // console.log(request.type,sender.tab.id,chrome.devtools.inspectedWindow.tabId)
644 | // if (request.type === 'RELOADED' && sender.tab.id === chrome.devtools.inspectedWindow.tabId) {
645 | // document.getElementById('check-xhr').checked = true;
646 | // document.getElementById('check-xhr').disabled = false;
647 | // document.getElementById('label-xhr').innerHTML = 'Include all assets by XHR requests'
648 | // document.getElementById('up-save').innerHTML = 'Save All Resources';
649 | // document.getElementById('up-save').disabled = false;
650 | // }
651 | // }
652 | //);
653 |
654 | // resources[i].getContent(function (content, encoding) {
655 | // alert("encoding is " + encoding);
656 | // alert("content is " + content);
657 | // document.getElementById('debug').innerHTML += ''+ cUrl +'
';
658 | // });
--------------------------------------------------------------------------------
/zip/zip.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2013 Gildas Lormeau. All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without
5 | modification, are permitted provided that the following conditions are met:
6 |
7 | 1. Redistributions of source code must retain the above copyright notice,
8 | this list of conditions and the following disclaimer.
9 |
10 | 2. Redistributions in binary form must reproduce the above copyright
11 | notice, this list of conditions and the following disclaimer in
12 | the documentation and/or other materials provided with the distribution.
13 |
14 | 3. The names of the authors may not be used to endorse or promote products
15 | derived from this software without specific prior written permission.
16 |
17 | THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
18 | INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
19 | FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
20 | INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
21 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 | OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
26 | EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 | */
28 |
29 | (function(obj) {
30 | "use strict";
31 |
32 | var ERR_BAD_FORMAT = "File format is not recognized.";
33 | var ERR_CRC = "CRC failed.";
34 | var ERR_ENCRYPTED = "File contains encrypted entry.";
35 | var ERR_ZIP64 = "File is using Zip64 (4gb+ file size).";
36 | var ERR_READ = "Error while reading zip file.";
37 | var ERR_WRITE = "Error while writing zip file.";
38 | var ERR_WRITE_DATA = "Error while writing file data.";
39 | var ERR_READ_DATA = "Error while reading file data.";
40 | var ERR_DUPLICATED_NAME = "File already exists.";
41 | var CHUNK_SIZE = 512 * 1024;
42 |
43 | var TEXT_PLAIN = "text/plain";
44 |
45 | var appendABViewSupported;
46 | try {
47 | appendABViewSupported = new Blob([ new DataView(new ArrayBuffer(0)) ]).size === 0;
48 | } catch (e) {
49 | }
50 |
51 | function Crc32() {
52 | this.crc = -1;
53 | }
54 | Crc32.prototype.append = function append(data) {
55 | var crc = this.crc | 0, table = this.table;
56 | for (var offset = 0, len = data.length | 0; offset < len; offset++)
57 | crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xFF];
58 | this.crc = crc;
59 | };
60 | Crc32.prototype.get = function get() {
61 | return ~this.crc;
62 | };
63 | Crc32.prototype.table = (function() {
64 | var i, j, t, table = []; // Uint32Array is actually slower than []
65 | for (i = 0; i < 256; i++) {
66 | t = i;
67 | for (j = 0; j < 8; j++)
68 | if (t & 1)
69 | t = (t >>> 1) ^ 0xEDB88320;
70 | else
71 | t = t >>> 1;
72 | table[i] = t;
73 | }
74 | return table;
75 | })();
76 |
77 | // "no-op" codec
78 | function NOOP() {}
79 | NOOP.prototype.append = function append(bytes, onprogress) {
80 | return bytes;
81 | };
82 | NOOP.prototype.flush = function flush() {};
83 |
84 | function blobSlice(blob, index, length) {
85 | if (index < 0 || length < 0 || index + length > blob.size)
86 | throw new RangeError('offset:' + index + ', length:' + length + ', size:' + blob.size);
87 | if (blob.slice)
88 | return blob.slice(index, index + length);
89 | else if (blob.webkitSlice)
90 | return blob.webkitSlice(index, index + length);
91 | else if (blob.mozSlice)
92 | return blob.mozSlice(index, index + length);
93 | else if (blob.msSlice)
94 | return blob.msSlice(index, index + length);
95 | }
96 |
97 | function getDataHelper(byteLength, bytes) {
98 | var dataBuffer, dataArray;
99 | dataBuffer = new ArrayBuffer(byteLength);
100 | dataArray = new Uint8Array(dataBuffer);
101 | if (bytes)
102 | dataArray.set(bytes, 0);
103 | return {
104 | buffer : dataBuffer,
105 | array : dataArray,
106 | view : new DataView(dataBuffer)
107 | };
108 | }
109 |
110 | // Readers
111 | function Reader() {
112 | }
113 |
114 | function TextReader(text) {
115 | var that = this, blobReader;
116 |
117 | function init(callback, onerror) {
118 | var blob = new Blob([ text ], {
119 | type : TEXT_PLAIN
120 | });
121 | blobReader = new BlobReader(blob);
122 | blobReader.init(function() {
123 | that.size = blobReader.size;
124 | callback();
125 | }, onerror);
126 | }
127 |
128 | function readUint8Array(index, length, callback, onerror) {
129 | blobReader.readUint8Array(index, length, callback, onerror);
130 | }
131 |
132 | that.size = 0;
133 | that.init = init;
134 | that.readUint8Array = readUint8Array;
135 | }
136 | TextReader.prototype = new Reader();
137 | TextReader.prototype.constructor = TextReader;
138 |
139 | function Data64URIReader(dataURI) {
140 | var that = this, dataStart;
141 |
142 | function init(callback) {
143 | var dataEnd = dataURI.length;
144 | while (dataURI.charAt(dataEnd - 1) == "=")
145 | dataEnd--;
146 | dataStart = dataURI.indexOf(",") + 1;
147 | that.size = Math.floor((dataEnd - dataStart) * 0.75);
148 | callback();
149 | }
150 |
151 | function readUint8Array(index, length, callback) {
152 | var i, data = getDataHelper(length);
153 | var start = Math.floor(index / 3) * 4;
154 | var end = Math.ceil((index + length) / 3) * 4;
155 | var bytes = obj.atob(dataURI.substring(start + dataStart, end + dataStart));
156 | var delta = index - Math.floor(start / 4) * 3;
157 | for (i = delta; i < delta + length; i++)
158 | data.array[i - delta] = bytes.charCodeAt(i);
159 | callback(data.array);
160 | }
161 |
162 | that.size = 0;
163 | that.init = init;
164 | that.readUint8Array = readUint8Array;
165 | }
166 |
167 | Data64URIReader.prototype = new Reader();
168 | Data64URIReader.prototype.constructor = Data64URIReader;
169 |
170 | function BlobReader(blob) {
171 | var that = this;
172 |
173 | function init(callback) {
174 | that.size = blob.size;
175 | callback();
176 | }
177 |
178 | function readUint8Array(index, length, callback, onerror) {
179 | var reader = new FileReader();
180 | reader.onload = function(e) {
181 | callback(new Uint8Array(e.target.result));
182 | };
183 | reader.onerror = onerror;
184 | try {
185 | reader.readAsArrayBuffer(blobSlice(blob, index, length));
186 | } catch (e) {
187 | onerror(e);
188 | }
189 | }
190 |
191 | that.size = 0;
192 | that.init = init;
193 | that.readUint8Array = readUint8Array;
194 | }
195 | BlobReader.prototype = new Reader();
196 | BlobReader.prototype.constructor = BlobReader;
197 |
198 | // Writers
199 |
200 | function Writer() {
201 | }
202 | Writer.prototype.getData = function(callback) {
203 | callback(this.data);
204 | };
205 |
206 | function TextWriter(encoding) {
207 | var that = this, blob;
208 |
209 | function init(callback) {
210 | blob = new Blob([], {
211 | type : TEXT_PLAIN
212 | });
213 | callback();
214 | }
215 |
216 | function writeUint8Array(array, callback) {
217 | blob = new Blob([ blob, appendABViewSupported ? array : array.buffer ], {
218 | type : TEXT_PLAIN
219 | });
220 | callback();
221 | }
222 |
223 | function getData(callback, onerror) {
224 | var reader = new FileReader();
225 | reader.onload = function(e) {
226 | callback(e.target.result);
227 | };
228 | reader.onerror = onerror;
229 | reader.readAsText(blob, encoding);
230 | }
231 |
232 | that.init = init;
233 | that.writeUint8Array = writeUint8Array;
234 | that.getData = getData;
235 | }
236 | TextWriter.prototype = new Writer();
237 | TextWriter.prototype.constructor = TextWriter;
238 |
239 | function Data64URIWriter(contentType) {
240 | var that = this, data = "", pending = "";
241 |
242 | function init(callback) {
243 | data += "data:" + (contentType || "") + ";base64,";
244 | callback();
245 | }
246 |
247 | function writeUint8Array(array, callback) {
248 | var i, delta = pending.length, dataString = pending;
249 | pending = "";
250 | for (i = 0; i < (Math.floor((delta + array.length) / 3) * 3) - delta; i++)
251 | dataString += String.fromCharCode(array[i]);
252 | for (; i < array.length; i++)
253 | pending += String.fromCharCode(array[i]);
254 | if (dataString.length > 2)
255 | data += obj.btoa(dataString);
256 | else
257 | pending = dataString;
258 | callback();
259 | }
260 |
261 | function getData(callback) {
262 | callback(data + obj.btoa(pending));
263 | }
264 |
265 | that.init = init;
266 | that.writeUint8Array = writeUint8Array;
267 | that.getData = getData;
268 | }
269 | Data64URIWriter.prototype = new Writer();
270 | Data64URIWriter.prototype.constructor = Data64URIWriter;
271 |
272 | function BlobWriter(contentType) {
273 | var blob, that = this;
274 |
275 | function init(callback) {
276 | blob = new Blob([], {
277 | type : contentType
278 | });
279 | callback();
280 | }
281 |
282 | function writeUint8Array(array, callback) {
283 | blob = new Blob([ blob, appendABViewSupported ? array : array.buffer ], {
284 | type : contentType
285 | });
286 | callback();
287 | }
288 |
289 | function getData(callback) {
290 | callback(blob);
291 | }
292 |
293 | that.init = init;
294 | that.writeUint8Array = writeUint8Array;
295 | that.getData = getData;
296 | }
297 | BlobWriter.prototype = new Writer();
298 | BlobWriter.prototype.constructor = BlobWriter;
299 |
300 | /**
301 | * inflate/deflate core functions
302 | * @param worker {Worker} web worker for the task.
303 | * @param initialMessage {Object} initial message to be sent to the worker. should contain
304 | * sn(serial number for distinguishing multiple tasks sent to the worker), and codecClass.
305 | * This function may add more properties before sending.
306 | */
307 | function launchWorkerProcess(worker, initialMessage, reader, writer, offset, size, onprogress, onend, onreaderror, onwriteerror) {
308 | var chunkIndex = 0, index, outputSize, sn = initialMessage.sn, crc;
309 |
310 | function onflush() {
311 | worker.removeEventListener('message', onmessage, false);
312 | onend(outputSize, crc);
313 | }
314 |
315 | function onmessage(event) {
316 | var message = event.data, data = message.data, err = message.error;
317 | if (err) {
318 | err.toString = function () { return 'Error: ' + this.message; };
319 | onreaderror(err);
320 | return;
321 | }
322 | if (message.sn !== sn)
323 | return;
324 | if (typeof message.codecTime === 'number')
325 | worker.codecTime += message.codecTime; // should be before onflush()
326 | if (typeof message.crcTime === 'number')
327 | worker.crcTime += message.crcTime;
328 |
329 | switch (message.type) {
330 | case 'append':
331 | if (data) {
332 | outputSize += data.length;
333 | writer.writeUint8Array(data, function() {
334 | step();
335 | }, onwriteerror);
336 | } else
337 | step();
338 | break;
339 | case 'flush':
340 | crc = message.crc;
341 | if (data) {
342 | outputSize += data.length;
343 | writer.writeUint8Array(data, function() {
344 | onflush();
345 | }, onwriteerror);
346 | } else
347 | onflush();
348 | break;
349 | case 'progress':
350 | if (onprogress)
351 | onprogress(index + message.loaded, size);
352 | break;
353 | case 'importScripts': //no need to handle here
354 | case 'newTask':
355 | case 'echo':
356 | break;
357 | default:
358 | console.warn('zip.js:launchWorkerProcess: unknown message: ', message);
359 | }
360 | }
361 |
362 | function step() {
363 | index = chunkIndex * CHUNK_SIZE;
364 | if (index < size) {
365 | reader.readUint8Array(offset + index, Math.min(CHUNK_SIZE, size - index), function(array) {
366 | if (onprogress)
367 | onprogress(index, size);
368 | var msg = index === 0 ? initialMessage : {sn : sn};
369 | msg.type = 'append';
370 | msg.data = array;
371 | worker.postMessage(msg, [array.buffer]);
372 | chunkIndex++;
373 | }, onreaderror);
374 | } else {
375 | worker.postMessage({
376 | sn: sn,
377 | type: 'flush'
378 | });
379 | }
380 | }
381 |
382 | outputSize = 0;
383 | worker.addEventListener('message', onmessage, false);
384 | step();
385 | }
386 |
387 | function launchProcess(process, reader, writer, offset, size, crcType, onprogress, onend, onreaderror, onwriteerror) {
388 | var chunkIndex = 0, index, outputSize = 0,
389 | crcInput = crcType === 'input',
390 | crcOutput = crcType === 'output',
391 | crc = new Crc32();
392 | function step() {
393 | var outputData;
394 | index = chunkIndex * CHUNK_SIZE;
395 | if (index < size)
396 | reader.readUint8Array(offset + index, Math.min(CHUNK_SIZE, size - index), function(inputData) {
397 | var outputData;
398 | try {
399 | outputData = process.append(inputData, function(loaded) {
400 | if (onprogress)
401 | onprogress(index + loaded, size);
402 | });
403 | } catch (e) {
404 | onreaderror(e);
405 | return;
406 | }
407 | if (outputData) {
408 | outputSize += outputData.length;
409 | writer.writeUint8Array(outputData, function() {
410 | chunkIndex++;
411 | setTimeout(step, 1);
412 | }, onwriteerror);
413 | if (crcOutput)
414 | crc.append(outputData);
415 | } else {
416 | chunkIndex++;
417 | setTimeout(step, 1);
418 | }
419 | if (crcInput)
420 | crc.append(inputData);
421 | if (onprogress)
422 | onprogress(index, size);
423 | }, onreaderror);
424 | else {
425 | try {
426 | outputData = process.flush();
427 | } catch (e) {
428 | onreaderror(e);
429 | return;
430 | }
431 | if (outputData) {
432 | if (crcOutput)
433 | crc.append(outputData);
434 | outputSize += outputData.length;
435 | writer.writeUint8Array(outputData, function() {
436 | onend(outputSize, crc.get());
437 | }, onwriteerror);
438 | } else
439 | onend(outputSize, crc.get());
440 | }
441 | }
442 |
443 | step();
444 | }
445 |
446 | function inflate(worker, sn, reader, writer, offset, size, computeCrc32, onend, onprogress, onreaderror, onwriteerror) {
447 | var crcType = computeCrc32 ? 'output' : 'none';
448 | if (obj.zip.useWebWorkers) {
449 | var initialMessage = {
450 | sn: sn,
451 | codecClass: 'Inflater',
452 | crcType: crcType,
453 | };
454 | launchWorkerProcess(worker, initialMessage, reader, writer, offset, size, onprogress, onend, onreaderror, onwriteerror);
455 | } else
456 | launchProcess(new obj.zip.Inflater(), reader, writer, offset, size, crcType, onprogress, onend, onreaderror, onwriteerror);
457 | }
458 |
459 | function deflate(worker, sn, reader, writer, level, onend, onprogress, onreaderror, onwriteerror) {
460 | var crcType = 'input';
461 | if (obj.zip.useWebWorkers) {
462 | var initialMessage = {
463 | sn: sn,
464 | options: {level: level},
465 | codecClass: 'Deflater',
466 | crcType: crcType,
467 | };
468 | launchWorkerProcess(worker, initialMessage, reader, writer, 0, reader.size, onprogress, onend, onreaderror, onwriteerror);
469 | } else
470 | launchProcess(new obj.zip.Deflater(), reader, writer, 0, reader.size, crcType, onprogress, onend, onreaderror, onwriteerror);
471 | }
472 |
473 | function copy(worker, sn, reader, writer, offset, size, computeCrc32, onend, onprogress, onreaderror, onwriteerror) {
474 | var crcType = 'input';
475 | if (obj.zip.useWebWorkers && computeCrc32) {
476 | var initialMessage = {
477 | sn: sn,
478 | codecClass: 'NOOP',
479 | crcType: crcType,
480 | };
481 | launchWorkerProcess(worker, initialMessage, reader, writer, offset, size, onprogress, onend, onreaderror, onwriteerror);
482 | } else
483 | launchProcess(new NOOP(), reader, writer, offset, size, crcType, onprogress, onend, onreaderror, onwriteerror);
484 | }
485 |
486 | // ZipReader
487 |
488 | function decodeASCII(str) {
489 | var i, out = "", charCode, extendedASCII = [ '\u00C7', '\u00FC', '\u00E9', '\u00E2', '\u00E4', '\u00E0', '\u00E5', '\u00E7', '\u00EA', '\u00EB',
490 | '\u00E8', '\u00EF', '\u00EE', '\u00EC', '\u00C4', '\u00C5', '\u00C9', '\u00E6', '\u00C6', '\u00F4', '\u00F6', '\u00F2', '\u00FB', '\u00F9',
491 | '\u00FF', '\u00D6', '\u00DC', '\u00F8', '\u00A3', '\u00D8', '\u00D7', '\u0192', '\u00E1', '\u00ED', '\u00F3', '\u00FA', '\u00F1', '\u00D1',
492 | '\u00AA', '\u00BA', '\u00BF', '\u00AE', '\u00AC', '\u00BD', '\u00BC', '\u00A1', '\u00AB', '\u00BB', '_', '_', '_', '\u00A6', '\u00A6',
493 | '\u00C1', '\u00C2', '\u00C0', '\u00A9', '\u00A6', '\u00A6', '+', '+', '\u00A2', '\u00A5', '+', '+', '-', '-', '+', '-', '+', '\u00E3',
494 | '\u00C3', '+', '+', '-', '-', '\u00A6', '-', '+', '\u00A4', '\u00F0', '\u00D0', '\u00CA', '\u00CB', '\u00C8', 'i', '\u00CD', '\u00CE',
495 | '\u00CF', '+', '+', '_', '_', '\u00A6', '\u00CC', '_', '\u00D3', '\u00DF', '\u00D4', '\u00D2', '\u00F5', '\u00D5', '\u00B5', '\u00FE',
496 | '\u00DE', '\u00DA', '\u00DB', '\u00D9', '\u00FD', '\u00DD', '\u00AF', '\u00B4', '\u00AD', '\u00B1', '_', '\u00BE', '\u00B6', '\u00A7',
497 | '\u00F7', '\u00B8', '\u00B0', '\u00A8', '\u00B7', '\u00B9', '\u00B3', '\u00B2', '_', ' ' ];
498 | for (i = 0; i < str.length; i++) {
499 | charCode = str.charCodeAt(i) & 0xFF;
500 | if (charCode > 127)
501 | out += extendedASCII[charCode - 128];
502 | else
503 | out += String.fromCharCode(charCode);
504 | }
505 | return out;
506 | }
507 |
508 | function decodeUTF8(string) {
509 | return decodeURIComponent(escape(string));
510 | }
511 |
512 | function getString(bytes) {
513 | var i, str = "";
514 | for (i = 0; i < bytes.length; i++)
515 | str += String.fromCharCode(bytes[i]);
516 | return str;
517 | }
518 |
519 | function getDate(timeRaw) {
520 | var date = (timeRaw & 0xffff0000) >> 16, time = timeRaw & 0x0000ffff;
521 | try {
522 | return new Date(1980 + ((date & 0xFE00) >> 9), ((date & 0x01E0) >> 5) - 1, date & 0x001F, (time & 0xF800) >> 11, (time & 0x07E0) >> 5,
523 | (time & 0x001F) * 2, 0);
524 | } catch (e) {
525 | }
526 | }
527 |
528 | function readCommonHeader(entry, data, index, centralDirectory, onerror) {
529 | entry.version = data.view.getUint16(index, true);
530 | entry.bitFlag = data.view.getUint16(index + 2, true);
531 | entry.compressionMethod = data.view.getUint16(index + 4, true);
532 | entry.lastModDateRaw = data.view.getUint32(index + 6, true);
533 | entry.lastModDate = getDate(entry.lastModDateRaw);
534 | if ((entry.bitFlag & 0x01) === 0x01) {
535 | onerror(ERR_ENCRYPTED);
536 | return;
537 | }
538 | if (centralDirectory || (entry.bitFlag & 0x0008) != 0x0008) {
539 | entry.crc32 = data.view.getUint32(index + 10, true);
540 | entry.compressedSize = data.view.getUint32(index + 14, true);
541 | entry.uncompressedSize = data.view.getUint32(index + 18, true);
542 | }
543 | if (entry.compressedSize === 0xFFFFFFFF || entry.uncompressedSize === 0xFFFFFFFF) {
544 | onerror(ERR_ZIP64);
545 | return;
546 | }
547 | entry.filenameLength = data.view.getUint16(index + 22, true);
548 | entry.extraFieldLength = data.view.getUint16(index + 24, true);
549 | }
550 |
551 | function createZipReader(reader, callback, onerror) {
552 | var inflateSN = 0;
553 |
554 | function Entry() {
555 | }
556 |
557 | Entry.prototype.getData = function(writer, onend, onprogress, checkCrc32) {
558 | var that = this;
559 |
560 | function testCrc32(crc32) {
561 | var dataCrc32 = getDataHelper(4);
562 | dataCrc32.view.setUint32(0, crc32);
563 | return that.crc32 == dataCrc32.view.getUint32(0);
564 | }
565 |
566 | function getWriterData(uncompressedSize, crc32) {
567 | if (checkCrc32 && !testCrc32(crc32))
568 | onerror(ERR_CRC);
569 | else
570 | writer.getData(function(data) {
571 | onend(data);
572 | });
573 | }
574 |
575 | function onreaderror(err) {
576 | onerror(err || ERR_READ_DATA);
577 | }
578 |
579 | function onwriteerror(err) {
580 | onerror(err || ERR_WRITE_DATA);
581 | }
582 |
583 | reader.readUint8Array(that.offset, 30, function(bytes) {
584 | var data = getDataHelper(bytes.length, bytes), dataOffset;
585 | if (data.view.getUint32(0) != 0x504b0304) {
586 | onerror(ERR_BAD_FORMAT);
587 | return;
588 | }
589 | readCommonHeader(that, data, 4, false, onerror);
590 | dataOffset = that.offset + 30 + that.filenameLength + that.extraFieldLength;
591 | writer.init(function() {
592 | if (that.compressionMethod === 0)
593 | copy(that._worker, inflateSN++, reader, writer, dataOffset, that.compressedSize, checkCrc32, getWriterData, onprogress, onreaderror, onwriteerror);
594 | else
595 | inflate(that._worker, inflateSN++, reader, writer, dataOffset, that.compressedSize, checkCrc32, getWriterData, onprogress, onreaderror, onwriteerror);
596 | }, onwriteerror);
597 | }, onreaderror);
598 | };
599 |
600 | function seekEOCDR(eocdrCallback) {
601 | // "End of central directory record" is the last part of a zip archive, and is at least 22 bytes long.
602 | // Zip file comment is the last part of EOCDR and has max length of 64KB,
603 | // so we only have to search the last 64K + 22 bytes of a archive for EOCDR signature (0x06054b50).
604 | var EOCDR_MIN = 22;
605 | if (reader.size < EOCDR_MIN) {
606 | onerror(ERR_BAD_FORMAT);
607 | return;
608 | }
609 | var ZIP_COMMENT_MAX = 256 * 256, EOCDR_MAX = EOCDR_MIN + ZIP_COMMENT_MAX;
610 |
611 | // In most cases, the EOCDR is EOCDR_MIN bytes long
612 | doSeek(EOCDR_MIN, function() {
613 | // If not found, try within EOCDR_MAX bytes
614 | doSeek(Math.min(EOCDR_MAX, reader.size), function() {
615 | onerror(ERR_BAD_FORMAT);
616 | });
617 | });
618 |
619 | // seek last length bytes of file for EOCDR
620 | function doSeek(length, eocdrNotFoundCallback) {
621 | reader.readUint8Array(reader.size - length, length, function(bytes) {
622 | for (var i = bytes.length - EOCDR_MIN; i >= 0; i--) {
623 | if (bytes[i] === 0x50 && bytes[i + 1] === 0x4b && bytes[i + 2] === 0x05 && bytes[i + 3] === 0x06) {
624 | eocdrCallback(new DataView(bytes.buffer, i, EOCDR_MIN));
625 | return;
626 | }
627 | }
628 | eocdrNotFoundCallback();
629 | }, function() {
630 | onerror(ERR_READ);
631 | });
632 | }
633 | }
634 |
635 | var zipReader = {
636 | getEntries : function(callback) {
637 | var worker = this._worker;
638 | // look for End of central directory record
639 | seekEOCDR(function(dataView) {
640 | var datalength, fileslength;
641 | datalength = dataView.getUint32(16, true);
642 | fileslength = dataView.getUint16(8, true);
643 | if (datalength < 0 || datalength >= reader.size) {
644 | onerror(ERR_BAD_FORMAT);
645 | return;
646 | }
647 | reader.readUint8Array(datalength, reader.size - datalength, function(bytes) {
648 | var i, index = 0, entries = [], entry, filename, comment, data = getDataHelper(bytes.length, bytes);
649 | for (i = 0; i < fileslength; i++) {
650 | entry = new Entry();
651 | entry._worker = worker;
652 | if (data.view.getUint32(index) != 0x504b0102) {
653 | onerror(ERR_BAD_FORMAT);
654 | return;
655 | }
656 | readCommonHeader(entry, data, index + 6, true, onerror);
657 | entry.commentLength = data.view.getUint16(index + 32, true);
658 | entry.directory = ((data.view.getUint8(index + 38) & 0x10) == 0x10);
659 | entry.offset = data.view.getUint32(index + 42, true);
660 | filename = getString(data.array.subarray(index + 46, index + 46 + entry.filenameLength));
661 | entry.filename = ((entry.bitFlag & 0x0800) === 0x0800) ? decodeUTF8(filename) : decodeASCII(filename);
662 | if (!entry.directory && entry.filename.charAt(entry.filename.length - 1) == "/")
663 | entry.directory = true;
664 | comment = getString(data.array.subarray(index + 46 + entry.filenameLength + entry.extraFieldLength, index + 46
665 | + entry.filenameLength + entry.extraFieldLength + entry.commentLength));
666 | entry.comment = ((entry.bitFlag & 0x0800) === 0x0800) ? decodeUTF8(comment) : decodeASCII(comment);
667 | entries.push(entry);
668 | index += 46 + entry.filenameLength + entry.extraFieldLength + entry.commentLength;
669 | }
670 | callback(entries);
671 | }, function() {
672 | onerror(ERR_READ);
673 | });
674 | });
675 | },
676 | close : function(callback) {
677 | if (this._worker) {
678 | this._worker.terminate();
679 | this._worker = null;
680 | }
681 | if (callback)
682 | callback();
683 | },
684 | _worker: null
685 | };
686 |
687 | if (!obj.zip.useWebWorkers)
688 | callback(zipReader);
689 | else {
690 | createWorker('inflater',
691 | function(worker) {
692 | zipReader._worker = worker;
693 | callback(zipReader);
694 | },
695 | function(err) {
696 | onerror(err);
697 | }
698 | );
699 | }
700 | }
701 |
702 | // ZipWriter
703 |
704 | function encodeUTF8(string) {
705 | return unescape(encodeURIComponent(string));
706 | }
707 |
708 | function getBytes(str) {
709 | var i, array = [];
710 | for (i = 0; i < str.length; i++)
711 | array.push(str.charCodeAt(i));
712 | return array;
713 | }
714 |
715 | function createZipWriter(writer, callback, onerror, dontDeflate) {
716 | var files = {}, filenames = [], datalength = 0;
717 | var deflateSN = 0;
718 |
719 | function onwriteerror(err) {
720 | onerror(err || ERR_WRITE);
721 | }
722 |
723 | function onreaderror(err) {
724 | onerror(err || ERR_READ_DATA);
725 | }
726 |
727 | var zipWriter = {
728 | add : function(name, reader, onend, onprogress, options) {
729 | var header, filename, date;
730 | var worker = this._worker;
731 |
732 | function writeHeader(callback) {
733 | var data;
734 | date = options.lastModDate || new Date();
735 | header = getDataHelper(26);
736 | files[name] = {
737 | headerArray : header.array,
738 | directory : options.directory,
739 | filename : filename,
740 | offset : datalength,
741 | comment : getBytes(encodeUTF8(options.comment || ""))
742 | };
743 | header.view.setUint32(0, 0x14000808);
744 | if (options.version)
745 | header.view.setUint8(0, options.version);
746 | if (!dontDeflate && options.level !== 0 && !options.directory)
747 | header.view.setUint16(4, 0x0800);
748 | header.view.setUint16(6, (((date.getHours() << 6) | date.getMinutes()) << 5) | date.getSeconds() / 2, true);
749 | header.view.setUint16(8, ((((date.getFullYear() - 1980) << 4) | (date.getMonth() + 1)) << 5) | date.getDate(), true);
750 | header.view.setUint16(22, filename.length, true);
751 | data = getDataHelper(30 + filename.length);
752 | data.view.setUint32(0, 0x504b0304);
753 | data.array.set(header.array, 4);
754 | data.array.set(filename, 30);
755 | datalength += data.array.length;
756 | writer.writeUint8Array(data.array, callback, onwriteerror);
757 | }
758 |
759 | function writeFooter(compressedLength, crc32) {
760 | var footer = getDataHelper(16);
761 | datalength += compressedLength || 0;
762 | footer.view.setUint32(0, 0x504b0708);
763 | if (typeof crc32 != "undefined") {
764 | header.view.setUint32(10, crc32, true);
765 | footer.view.setUint32(4, crc32, true);
766 | }
767 | if (reader) {
768 | footer.view.setUint32(8, compressedLength, true);
769 | header.view.setUint32(14, compressedLength, true);
770 | footer.view.setUint32(12, reader.size, true);
771 | header.view.setUint32(18, reader.size, true);
772 | }
773 | writer.writeUint8Array(footer.array, function() {
774 | datalength += 16;
775 | onend();
776 | }, onwriteerror);
777 | }
778 |
779 | function writeFile() {
780 | options = options || {};
781 | name = name.trim();
782 | if (options.directory && name.charAt(name.length - 1) != "/")
783 | name += "/";
784 | if (files.hasOwnProperty(name)) {
785 | onerror(ERR_DUPLICATED_NAME);
786 | return;
787 | }
788 | filename = getBytes(encodeUTF8(name));
789 | filenames.push(name);
790 | writeHeader(function() {
791 | if (reader)
792 | if (dontDeflate || options.level === 0)
793 | copy(worker, deflateSN++, reader, writer, 0, reader.size, true, writeFooter, onprogress, onreaderror, onwriteerror);
794 | else
795 | deflate(worker, deflateSN++, reader, writer, options.level, writeFooter, onprogress, onreaderror, onwriteerror);
796 | else
797 | writeFooter();
798 | }, onwriteerror);
799 | }
800 |
801 | if (reader)
802 | reader.init(writeFile, onreaderror);
803 | else
804 | writeFile();
805 | },
806 | close : function(callback) {
807 | if (this._worker) {
808 | this._worker.terminate();
809 | this._worker = null;
810 | }
811 |
812 | var data, length = 0, index = 0, indexFilename, file;
813 | for (indexFilename = 0; indexFilename < filenames.length; indexFilename++) {
814 | file = files[filenames[indexFilename]];
815 | length += 46 + file.filename.length + file.comment.length;
816 | }
817 | data = getDataHelper(length + 22);
818 | for (indexFilename = 0; indexFilename < filenames.length; indexFilename++) {
819 | file = files[filenames[indexFilename]];
820 | data.view.setUint32(index, 0x504b0102);
821 | data.view.setUint16(index + 4, 0x1400);
822 | data.array.set(file.headerArray, index + 6);
823 | data.view.setUint16(index + 32, file.comment.length, true);
824 | if (file.directory)
825 | data.view.setUint8(index + 38, 0x10);
826 | data.view.setUint32(index + 42, file.offset, true);
827 | data.array.set(file.filename, index + 46);
828 | data.array.set(file.comment, index + 46 + file.filename.length);
829 | index += 46 + file.filename.length + file.comment.length;
830 | }
831 | data.view.setUint32(index, 0x504b0506);
832 | data.view.setUint16(index + 8, filenames.length, true);
833 | data.view.setUint16(index + 10, filenames.length, true);
834 | data.view.setUint32(index + 12, length, true);
835 | data.view.setUint32(index + 16, datalength, true);
836 | writer.writeUint8Array(data.array, function() {
837 | writer.getData(callback);
838 | }, onwriteerror);
839 | },
840 | _worker: null
841 | };
842 |
843 | if (!obj.zip.useWebWorkers)
844 | callback(zipWriter);
845 | else {
846 | createWorker('deflater',
847 | function(worker) {
848 | zipWriter._worker = worker;
849 | callback(zipWriter);
850 | },
851 | function(err) {
852 | onerror(err);
853 | }
854 | );
855 | }
856 | }
857 |
858 | function resolveURLs(urls) {
859 | var a = document.createElement('a');
860 | return urls.map(function(url) {
861 | a.href = url;
862 | return a.href;
863 | });
864 | }
865 |
866 | var DEFAULT_WORKER_SCRIPTS = {
867 | deflater: ['z-worker.js', 'deflate.js'],
868 | inflater: ['z-worker.js', 'inflate.js']
869 | };
870 | function createWorker(type, callback, onerror) {
871 | if (obj.zip.workerScripts !== null && obj.zip.workerScriptsPath !== null) {
872 | onerror(new Error('Either zip.workerScripts or zip.workerScriptsPath may be set, not both.'));
873 | return;
874 | }
875 | var scripts;
876 | if (obj.zip.workerScripts) {
877 | scripts = obj.zip.workerScripts[type];
878 | if (!Array.isArray(scripts)) {
879 | onerror(new Error('zip.workerScripts.' + type + ' is not an array!'));
880 | return;
881 | }
882 | scripts = resolveURLs(scripts);
883 | } else {
884 | scripts = DEFAULT_WORKER_SCRIPTS[type].slice(0);
885 | scripts[0] = (obj.zip.workerScriptsPath || '') + scripts[0];
886 | }
887 | var worker = new Worker(scripts[0]);
888 | // record total consumed time by inflater/deflater/crc32 in this worker
889 | worker.codecTime = worker.crcTime = 0;
890 | worker.postMessage({ type: 'importScripts', scripts: scripts.slice(1) });
891 | worker.addEventListener('message', onmessage);
892 | function onmessage(ev) {
893 | var msg = ev.data;
894 | if (msg.error) {
895 | worker.terminate(); // should before onerror(), because onerror() may throw.
896 | onerror(msg.error);
897 | return;
898 | }
899 | if (msg.type === 'importScripts') {
900 | worker.removeEventListener('message', onmessage);
901 | worker.removeEventListener('error', errorHandler);
902 | callback(worker);
903 | }
904 | }
905 | // catch entry script loading error and other unhandled errors
906 | worker.addEventListener('error', errorHandler);
907 | function errorHandler(err) {
908 | worker.terminate();
909 | onerror(err);
910 | }
911 | }
912 |
913 | function onerror_default(error) {
914 | console.error(error);
915 | }
916 | obj.zip = {
917 | Reader : Reader,
918 | Writer : Writer,
919 | BlobReader : BlobReader,
920 | Data64URIReader : Data64URIReader,
921 | TextReader : TextReader,
922 | BlobWriter : BlobWriter,
923 | Data64URIWriter : Data64URIWriter,
924 | TextWriter : TextWriter,
925 | createReader : function(reader, callback, onerror) {
926 | onerror = onerror || onerror_default;
927 |
928 | reader.init(function() {
929 | createZipReader(reader, callback, onerror);
930 | }, onerror);
931 | },
932 | createWriter : function(writer, callback, onerror, dontDeflate) {
933 | onerror = onerror || onerror_default;
934 | dontDeflate = !!dontDeflate;
935 |
936 | writer.init(function() {
937 | createZipWriter(writer, callback, onerror, dontDeflate);
938 | }, onerror);
939 | },
940 | useWebWorkers : true,
941 | /**
942 | * Directory containing the default worker scripts (z-worker.js, deflate.js, and inflate.js), relative to current base url.
943 | * E.g.: zip.workerScripts = './';
944 | */
945 | workerScriptsPath : null,
946 | /**
947 | * Advanced option to control which scripts are loaded in the Web worker. If this option is specified, then workerScriptsPath must not be set.
948 | * workerScripts.deflater/workerScripts.inflater should be arrays of urls to scripts for deflater/inflater, respectively.
949 | * Scripts in the array are executed in order, and the first one should be z-worker.js, which is used to start the worker.
950 | * All urls are relative to current base url.
951 | * E.g.:
952 | * zip.workerScripts = {
953 | * deflater: ['z-worker.js', 'deflate.js'],
954 | * inflater: ['z-worker.js', 'inflate.js']
955 | * };
956 | */
957 | workerScripts : null,
958 | };
959 |
960 | })(this);
--------------------------------------------------------------------------------
/zip/inflate.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2013 Gildas Lormeau. All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without
5 | modification, are permitted provided that the following conditions are met:
6 |
7 | 1. Redistributions of source code must retain the above copyright notice,
8 | this list of conditions and the following disclaimer.
9 |
10 | 2. Redistributions in binary form must reproduce the above copyright
11 | notice, this list of conditions and the following disclaimer in
12 | the documentation and/or other materials provided with the distribution.
13 |
14 | 3. The names of the authors may not be used to endorse or promote products
15 | derived from this software without specific prior written permission.
16 |
17 | THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
18 | INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
19 | FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
20 | INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
21 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 | OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
26 | EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 | */
28 |
29 | /*
30 | * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
31 | * JZlib is based on zlib-1.1.3, so all credit should go authors
32 | * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
33 | * and contributors of zlib.
34 | */
35 |
36 | (function(global) {
37 | "use strict";
38 |
39 | // Global
40 | var MAX_BITS = 15;
41 |
42 | var Z_OK = 0;
43 | var Z_STREAM_END = 1;
44 | var Z_NEED_DICT = 2;
45 | var Z_STREAM_ERROR = -2;
46 | var Z_DATA_ERROR = -3;
47 | var Z_MEM_ERROR = -4;
48 | var Z_BUF_ERROR = -5;
49 |
50 | var inflate_mask = [ 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff,
51 | 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff ];
52 |
53 | var MANY = 1440;
54 |
55 | // JZlib version : "1.0.2"
56 | var Z_NO_FLUSH = 0;
57 | var Z_FINISH = 4;
58 |
59 | // InfTree
60 | var fixed_bl = 9;
61 | var fixed_bd = 5;
62 |
63 | var fixed_tl = [ 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 160, 0, 8, 0,
64 | 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40,
65 | 0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13,
66 | 0, 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0, 8, 60,
67 | 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7,
68 | 35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8,
69 | 26, 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80,
70 | 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0,
71 | 8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0,
72 | 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 194, 80, 7, 10, 0, 8, 97,
73 | 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210,
74 | 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117,
75 | 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154,
76 | 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83,
77 | 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230,
78 | 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139,
79 | 0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174,
80 | 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8, 111,
81 | 0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9,
82 | 193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8,
83 | 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8,
84 | 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8,
85 | 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9,
86 | 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8,
87 | 130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9,
88 | 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8,
89 | 102, 0, 8, 38, 0, 9, 173, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9,
90 | 221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0,
91 | 8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9,
92 | 147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 243, 80, 7, 4, 0, 8,
93 | 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9,
94 | 235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8,
95 | 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9,
96 | 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8,
97 | 107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9,
98 | 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8,
99 | 127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 255 ];
100 | var fixed_td = [ 80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33, 92, 5,
101 | 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80, 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, 1537, 85, 5, 97, 93, 5,
102 | 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92, 5, 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577 ];
103 |
104 | // Tables for deflate from PKZIP's appnote.txt.
105 | var cplens = [ // Copy lengths for literal codes 257..285
106 | 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ];
107 |
108 | // see note #13 above about 258
109 | var cplext = [ // Extra bits for literal codes 257..285
110 | 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, 112, 112 // 112==invalid
111 | ];
112 |
113 | var cpdist = [ // Copy offsets for distance codes 0..29
114 | 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 ];
115 |
116 | var cpdext = [ // Extra bits for distance codes
117 | 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 ];
118 |
119 | // If BMAX needs to be larger than 16, then h and x[] should be uLong.
120 | var BMAX = 15; // maximum bit length of any code
121 |
122 | function InfTree() {
123 | var that = this;
124 |
125 | var hn; // hufts used in space
126 | var v; // work area for huft_build
127 | var c; // bit length count table
128 | var r; // table entry for structure assignment
129 | var u; // table stack
130 | var x; // bit offsets, then code stack
131 |
132 | function huft_build(b, // code lengths in bits (all assumed <=
133 | // BMAX)
134 | bindex, n, // number of codes (assumed <= 288)
135 | s, // number of simple-valued codes (0..s-1)
136 | d, // list of base values for non-simple codes
137 | e, // list of extra bits for non-simple codes
138 | t, // result: starting table
139 | m, // maximum lookup bits, returns actual
140 | hp,// space for trees
141 | hn,// hufts used in space
142 | v // working area: values in order of bit length
143 | ) {
144 | // Given a list of code lengths and a maximum table size, make a set of
145 | // tables to decode that set of codes. Return Z_OK on success,
146 | // Z_BUF_ERROR
147 | // if the given code set is incomplete (the tables are still built in
148 | // this
149 | // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set
150 | // of
151 | // lengths), or Z_MEM_ERROR if not enough memory.
152 |
153 | var a; // counter for codes of length k
154 | var f; // i repeats in table every f entries
155 | var g; // maximum code length
156 | var h; // table level
157 | var i; // counter, current code
158 | var j; // counter
159 | var k; // number of bits in current code
160 | var l; // bits per table (returned in m)
161 | var mask; // (1 << w) - 1, to avoid cc -O bug on HP
162 | var p; // pointer into c[], b[], or v[]
163 | var q; // points to current table
164 | var w; // bits before this table == (l * h)
165 | var xp; // pointer into x
166 | var y; // number of dummy codes added
167 | var z; // number of entries in current table
168 |
169 | // Generate counts for each bit length
170 |
171 | p = 0;
172 | i = n;
173 | do {
174 | c[b[bindex + p]]++;
175 | p++;
176 | i--; // assume all entries <= BMAX
177 | } while (i !== 0);
178 |
179 | if (c[0] == n) { // null input--all zero length codes
180 | t[0] = -1;
181 | m[0] = 0;
182 | return Z_OK;
183 | }
184 |
185 | // Find minimum and maximum length, bound *m by those
186 | l = m[0];
187 | for (j = 1; j <= BMAX; j++)
188 | if (c[j] !== 0)
189 | break;
190 | k = j; // minimum code length
191 | if (l < j) {
192 | l = j;
193 | }
194 | for (i = BMAX; i !== 0; i--) {
195 | if (c[i] !== 0)
196 | break;
197 | }
198 | g = i; // maximum code length
199 | if (l > i) {
200 | l = i;
201 | }
202 | m[0] = l;
203 |
204 | // Adjust last length count to fill out codes, if needed
205 | for (y = 1 << j; j < i; j++, y <<= 1) {
206 | if ((y -= c[j]) < 0) {
207 | return Z_DATA_ERROR;
208 | }
209 | }
210 | if ((y -= c[i]) < 0) {
211 | return Z_DATA_ERROR;
212 | }
213 | c[i] += y;
214 |
215 | // Generate starting offsets into the value table for each length
216 | x[1] = j = 0;
217 | p = 1;
218 | xp = 2;
219 | while (--i !== 0) { // note that i == g from above
220 | x[xp] = (j += c[p]);
221 | xp++;
222 | p++;
223 | }
224 |
225 | // Make a table of values in order of bit lengths
226 | i = 0;
227 | p = 0;
228 | do {
229 | if ((j = b[bindex + p]) !== 0) {
230 | v[x[j]++] = i;
231 | }
232 | p++;
233 | } while (++i < n);
234 | n = x[g]; // set n to length of v
235 |
236 | // Generate the Huffman codes and for each, make the table entries
237 | x[0] = i = 0; // first Huffman code is zero
238 | p = 0; // grab values in bit order
239 | h = -1; // no tables yet--level -1
240 | w = -l; // bits decoded == (l * h)
241 | u[0] = 0; // just to keep compilers happy
242 | q = 0; // ditto
243 | z = 0; // ditto
244 |
245 | // go through the bit lengths (k already is bits in shortest code)
246 | for (; k <= g; k++) {
247 | a = c[k];
248 | while (a-- !== 0) {
249 | // here i is the Huffman code of length k bits for value *p
250 | // make tables up to required level
251 | while (k > w + l) {
252 | h++;
253 | w += l; // previous table always l bits
254 | // compute minimum size table less than or equal to l bits
255 | z = g - w;
256 | z = (z > l) ? l : z; // table size upper limit
257 | if ((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table
258 | // too few codes for
259 | // k-w bit table
260 | f -= a + 1; // deduct codes from patterns left
261 | xp = k;
262 | if (j < z) {
263 | while (++j < z) { // try smaller tables up to z bits
264 | if ((f <<= 1) <= c[++xp])
265 | break; // enough codes to use up j bits
266 | f -= c[xp]; // else deduct codes from patterns
267 | }
268 | }
269 | }
270 | z = 1 << j; // table entries for j-bit table
271 |
272 | // allocate new table
273 | if (hn[0] + z > MANY) { // (note: doesn't matter for fixed)
274 | return Z_DATA_ERROR; // overflow of MANY
275 | }
276 | u[h] = q = /* hp+ */hn[0]; // DEBUG
277 | hn[0] += z;
278 |
279 | // connect to last table, if there is one
280 | if (h !== 0) {
281 | x[h] = i; // save pattern for backing up
282 | r[0] = /* (byte) */j; // bits in this table
283 | r[1] = /* (byte) */l; // bits to dump before this table
284 | j = i >>> (w - l);
285 | r[2] = /* (int) */(q - u[h - 1] - j); // offset to this table
286 | hp.set(r, (u[h - 1] + j) * 3);
287 | // to
288 | // last
289 | // table
290 | } else {
291 | t[0] = q; // first table is returned result
292 | }
293 | }
294 |
295 | // set up table entry in r
296 | r[1] = /* (byte) */(k - w);
297 | if (p >= n) {
298 | r[0] = 128 + 64; // out of values--invalid code
299 | } else if (v[p] < s) {
300 | r[0] = /* (byte) */(v[p] < 256 ? 0 : 32 + 64); // 256 is
301 | // end-of-block
302 | r[2] = v[p++]; // simple code is just the value
303 | } else {
304 | r[0] = /* (byte) */(e[v[p] - s] + 16 + 64); // non-simple--look
305 | // up in lists
306 | r[2] = d[v[p++] - s];
307 | }
308 |
309 | // fill code-like entries with r
310 | f = 1 << (k - w);
311 | for (j = i >>> w; j < z; j += f) {
312 | hp.set(r, (q + j) * 3);
313 | }
314 |
315 | // backwards increment the k-bit code i
316 | for (j = 1 << (k - 1); (i & j) !== 0; j >>>= 1) {
317 | i ^= j;
318 | }
319 | i ^= j;
320 |
321 | // backup over finished tables
322 | mask = (1 << w) - 1; // needed on HP, cc -O bug
323 | while ((i & mask) != x[h]) {
324 | h--; // don't need to update q
325 | w -= l;
326 | mask = (1 << w) - 1;
327 | }
328 | }
329 | }
330 | // Return Z_BUF_ERROR if we were given an incomplete table
331 | return y !== 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
332 | }
333 |
334 | function initWorkArea(vsize) {
335 | var i;
336 | if (!hn) {
337 | hn = []; // []; //new Array(1);
338 | v = []; // new Array(vsize);
339 | c = new Int32Array(BMAX + 1); // new Array(BMAX + 1);
340 | r = []; // new Array(3);
341 | u = new Int32Array(BMAX); // new Array(BMAX);
342 | x = new Int32Array(BMAX + 1); // new Array(BMAX + 1);
343 | }
344 | if (v.length < vsize) {
345 | v = []; // new Array(vsize);
346 | }
347 | for (i = 0; i < vsize; i++) {
348 | v[i] = 0;
349 | }
350 | for (i = 0; i < BMAX + 1; i++) {
351 | c[i] = 0;
352 | }
353 | for (i = 0; i < 3; i++) {
354 | r[i] = 0;
355 | }
356 | // for(int i=0; i 257)) {
413 | if (result == Z_DATA_ERROR) {
414 | z.msg = "oversubscribed distance tree";
415 | } else if (result == Z_BUF_ERROR) {
416 | z.msg = "incomplete distance tree";
417 | result = Z_DATA_ERROR;
418 | } else if (result != Z_MEM_ERROR) {
419 | z.msg = "empty distance tree with lengths";
420 | result = Z_DATA_ERROR;
421 | }
422 | return result;
423 | }
424 |
425 | return Z_OK;
426 | };
427 |
428 | }
429 |
430 | InfTree.inflate_trees_fixed = function(bl, // literal desired/actual bit depth
431 | bd, // distance desired/actual bit depth
432 | tl,// literal/length tree result
433 | td// distance tree result
434 | ) {
435 | bl[0] = fixed_bl;
436 | bd[0] = fixed_bd;
437 | tl[0] = fixed_tl;
438 | td[0] = fixed_td;
439 | return Z_OK;
440 | };
441 |
442 | // InfCodes
443 |
444 | // waiting for "i:"=input,
445 | // "o:"=output,
446 | // "x:"=nothing
447 | var START = 0; // x: set up for LEN
448 | var LEN = 1; // i: get length/literal/eob next
449 | var LENEXT = 2; // i: getting length extra (have base)
450 | var DIST = 3; // i: get distance next
451 | var DISTEXT = 4;// i: getting distance extra
452 | var COPY = 5; // o: copying bytes in window, waiting
453 | // for space
454 | var LIT = 6; // o: got literal, waiting for output
455 | // space
456 | var WASH = 7; // o: got eob, possibly still output
457 | // waiting
458 | var END = 8; // x: got eob and all data flushed
459 | var BADCODE = 9;// x: got error
460 |
461 | function InfCodes() {
462 | var that = this;
463 |
464 | var mode; // current inflate_codes mode
465 |
466 | // mode dependent information
467 | var len = 0;
468 |
469 | var tree; // pointer into tree
470 | var tree_index = 0;
471 | var need = 0; // bits needed
472 |
473 | var lit = 0;
474 |
475 | // if EXT or COPY, where and how much
476 | var get = 0; // bits to get for extra
477 | var dist = 0; // distance back to copy from
478 |
479 | var lbits = 0; // ltree bits decoded per branch
480 | var dbits = 0; // dtree bits decoder per branch
481 | var ltree; // literal/length/eob tree
482 | var ltree_index = 0; // literal/length/eob tree
483 | var dtree; // distance tree
484 | var dtree_index = 0; // distance tree
485 |
486 | // Called with number of bytes left to write in window at least 258
487 | // (the maximum string length) and number of input bytes available
488 | // at least ten. The ten bytes are six bytes for the longest length/
489 | // distance pair plus four bytes for overloading the bit buffer.
490 |
491 | function inflate_fast(bl, bd, tl, tl_index, td, td_index, s, z) {
492 | var t; // temporary pointer
493 | var tp; // temporary pointer
494 | var tp_index; // temporary pointer
495 | var e; // extra bits or operation
496 | var b; // bit buffer
497 | var k; // bits in bit buffer
498 | var p; // input data pointer
499 | var n; // bytes available there
500 | var q; // output window write pointer
501 | var m; // bytes to end of window or read pointer
502 | var ml; // mask for literal/length tree
503 | var md; // mask for distance tree
504 | var c; // bytes to copy
505 | var d; // distance back to copy from
506 | var r; // copy source pointer
507 |
508 | var tp_index_t_3; // (tp_index+t)*3
509 |
510 | // load input, output, bit values
511 | p = z.next_in_index;
512 | n = z.avail_in;
513 | b = s.bitb;
514 | k = s.bitk;
515 | q = s.write;
516 | m = q < s.read ? s.read - q - 1 : s.end - q;
517 |
518 | // initialize masks
519 | ml = inflate_mask[bl];
520 | md = inflate_mask[bd];
521 |
522 | // do until not enough input or output space for fast loop
523 | do { // assume called with m >= 258 && n >= 10
524 | // get literal/length code
525 | while (k < (20)) { // max bits for literal/length code
526 | n--;
527 | b |= (z.read_byte(p++) & 0xff) << k;
528 | k += 8;
529 | }
530 |
531 | t = b & ml;
532 | tp = tl;
533 | tp_index = tl_index;
534 | tp_index_t_3 = (tp_index + t) * 3;
535 | if ((e = tp[tp_index_t_3]) === 0) {
536 | b >>= (tp[tp_index_t_3 + 1]);
537 | k -= (tp[tp_index_t_3 + 1]);
538 |
539 | s.window[q++] = /* (byte) */tp[tp_index_t_3 + 2];
540 | m--;
541 | continue;
542 | }
543 | do {
544 |
545 | b >>= (tp[tp_index_t_3 + 1]);
546 | k -= (tp[tp_index_t_3 + 1]);
547 |
548 | if ((e & 16) !== 0) {
549 | e &= 15;
550 | c = tp[tp_index_t_3 + 2] + (/* (int) */b & inflate_mask[e]);
551 |
552 | b >>= e;
553 | k -= e;
554 |
555 | // decode distance base of block to copy
556 | while (k < (15)) { // max bits for distance code
557 | n--;
558 | b |= (z.read_byte(p++) & 0xff) << k;
559 | k += 8;
560 | }
561 |
562 | t = b & md;
563 | tp = td;
564 | tp_index = td_index;
565 | tp_index_t_3 = (tp_index + t) * 3;
566 | e = tp[tp_index_t_3];
567 |
568 | do {
569 |
570 | b >>= (tp[tp_index_t_3 + 1]);
571 | k -= (tp[tp_index_t_3 + 1]);
572 |
573 | if ((e & 16) !== 0) {
574 | // get extra bits to add to distance base
575 | e &= 15;
576 | while (k < (e)) { // get extra bits (up to 13)
577 | n--;
578 | b |= (z.read_byte(p++) & 0xff) << k;
579 | k += 8;
580 | }
581 |
582 | d = tp[tp_index_t_3 + 2] + (b & inflate_mask[e]);
583 |
584 | b >>= (e);
585 | k -= (e);
586 |
587 | // do the copy
588 | m -= c;
589 | if (q >= d) { // offset before dest
590 | // just copy
591 | r = q - d;
592 | if (q - r > 0 && 2 > (q - r)) {
593 | s.window[q++] = s.window[r++]; // minimum
594 | // count is
595 | // three,
596 | s.window[q++] = s.window[r++]; // so unroll
597 | // loop a
598 | // little
599 | c -= 2;
600 | } else {
601 | s.window.set(s.window.subarray(r, r + 2), q);
602 | q += 2;
603 | r += 2;
604 | c -= 2;
605 | }
606 | } else { // else offset after destination
607 | r = q - d;
608 | do {
609 | r += s.end; // force pointer in window
610 | } while (r < 0); // covers invalid distances
611 | e = s.end - r;
612 | if (c > e) { // if source crosses,
613 | c -= e; // wrapped copy
614 | if (q - r > 0 && e > (q - r)) {
615 | do {
616 | s.window[q++] = s.window[r++];
617 | } while (--e !== 0);
618 | } else {
619 | s.window.set(s.window.subarray(r, r + e), q);
620 | q += e;
621 | r += e;
622 | e = 0;
623 | }
624 | r = 0; // copy rest from start of window
625 | }
626 |
627 | }
628 |
629 | // copy all or what's left
630 | if (q - r > 0 && c > (q - r)) {
631 | do {
632 | s.window[q++] = s.window[r++];
633 | } while (--c !== 0);
634 | } else {
635 | s.window.set(s.window.subarray(r, r + c), q);
636 | q += c;
637 | r += c;
638 | c = 0;
639 | }
640 | break;
641 | } else if ((e & 64) === 0) {
642 | t += tp[tp_index_t_3 + 2];
643 | t += (b & inflate_mask[e]);
644 | tp_index_t_3 = (tp_index + t) * 3;
645 | e = tp[tp_index_t_3];
646 | } else {
647 | z.msg = "invalid distance code";
648 |
649 | c = z.avail_in - n;
650 | c = (k >> 3) < c ? k >> 3 : c;
651 | n += c;
652 | p -= c;
653 | k -= c << 3;
654 |
655 | s.bitb = b;
656 | s.bitk = k;
657 | z.avail_in = n;
658 | z.total_in += p - z.next_in_index;
659 | z.next_in_index = p;
660 | s.write = q;
661 |
662 | return Z_DATA_ERROR;
663 | }
664 | } while (true);
665 | break;
666 | }
667 |
668 | if ((e & 64) === 0) {
669 | t += tp[tp_index_t_3 + 2];
670 | t += (b & inflate_mask[e]);
671 | tp_index_t_3 = (tp_index + t) * 3;
672 | if ((e = tp[tp_index_t_3]) === 0) {
673 |
674 | b >>= (tp[tp_index_t_3 + 1]);
675 | k -= (tp[tp_index_t_3 + 1]);
676 |
677 | s.window[q++] = /* (byte) */tp[tp_index_t_3 + 2];
678 | m--;
679 | break;
680 | }
681 | } else if ((e & 32) !== 0) {
682 |
683 | c = z.avail_in - n;
684 | c = (k >> 3) < c ? k >> 3 : c;
685 | n += c;
686 | p -= c;
687 | k -= c << 3;
688 |
689 | s.bitb = b;
690 | s.bitk = k;
691 | z.avail_in = n;
692 | z.total_in += p - z.next_in_index;
693 | z.next_in_index = p;
694 | s.write = q;
695 |
696 | return Z_STREAM_END;
697 | } else {
698 | z.msg = "invalid literal/length code";
699 |
700 | c = z.avail_in - n;
701 | c = (k >> 3) < c ? k >> 3 : c;
702 | n += c;
703 | p -= c;
704 | k -= c << 3;
705 |
706 | s.bitb = b;
707 | s.bitk = k;
708 | z.avail_in = n;
709 | z.total_in += p - z.next_in_index;
710 | z.next_in_index = p;
711 | s.write = q;
712 |
713 | return Z_DATA_ERROR;
714 | }
715 | } while (true);
716 | } while (m >= 258 && n >= 10);
717 |
718 | // not enough input or output--restore pointers and return
719 | c = z.avail_in - n;
720 | c = (k >> 3) < c ? k >> 3 : c;
721 | n += c;
722 | p -= c;
723 | k -= c << 3;
724 |
725 | s.bitb = b;
726 | s.bitk = k;
727 | z.avail_in = n;
728 | z.total_in += p - z.next_in_index;
729 | z.next_in_index = p;
730 | s.write = q;
731 |
732 | return Z_OK;
733 | }
734 |
735 | that.init = function(bl, bd, tl, tl_index, td, td_index) {
736 | mode = START;
737 | lbits = /* (byte) */bl;
738 | dbits = /* (byte) */bd;
739 | ltree = tl;
740 | ltree_index = tl_index;
741 | dtree = td;
742 | dtree_index = td_index;
743 | tree = null;
744 | };
745 |
746 | that.proc = function(s, z, r) {
747 | var j; // temporary storage
748 | var tindex; // temporary pointer
749 | var e; // extra bits or operation
750 | var b = 0; // bit buffer
751 | var k = 0; // bits in bit buffer
752 | var p = 0; // input data pointer
753 | var n; // bytes available there
754 | var q; // output window write pointer
755 | var m; // bytes to end of window or read pointer
756 | var f; // pointer to copy strings from
757 |
758 | // copy input/output information to locals (UPDATE macro restores)
759 | p = z.next_in_index;
760 | n = z.avail_in;
761 | b = s.bitb;
762 | k = s.bitk;
763 | q = s.write;
764 | m = q < s.read ? s.read - q - 1 : s.end - q;
765 |
766 | // process input and output based on current state
767 | while (true) {
768 | switch (mode) {
769 | // waiting for "i:"=input, "o:"=output, "x:"=nothing
770 | case START: // x: set up for LEN
771 | if (m >= 258 && n >= 10) {
772 |
773 | s.bitb = b;
774 | s.bitk = k;
775 | z.avail_in = n;
776 | z.total_in += p - z.next_in_index;
777 | z.next_in_index = p;
778 | s.write = q;
779 | r = inflate_fast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, s, z);
780 |
781 | p = z.next_in_index;
782 | n = z.avail_in;
783 | b = s.bitb;
784 | k = s.bitk;
785 | q = s.write;
786 | m = q < s.read ? s.read - q - 1 : s.end - q;
787 |
788 | if (r != Z_OK) {
789 | mode = r == Z_STREAM_END ? WASH : BADCODE;
790 | break;
791 | }
792 | }
793 | need = lbits;
794 | tree = ltree;
795 | tree_index = ltree_index;
796 |
797 | mode = LEN;
798 | /* falls through */
799 | case LEN: // i: get length/literal/eob next
800 | j = need;
801 |
802 | while (k < (j)) {
803 | if (n !== 0)
804 | r = Z_OK;
805 | else {
806 |
807 | s.bitb = b;
808 | s.bitk = k;
809 | z.avail_in = n;
810 | z.total_in += p - z.next_in_index;
811 | z.next_in_index = p;
812 | s.write = q;
813 | return s.inflate_flush(z, r);
814 | }
815 | n--;
816 | b |= (z.read_byte(p++) & 0xff) << k;
817 | k += 8;
818 | }
819 |
820 | tindex = (tree_index + (b & inflate_mask[j])) * 3;
821 |
822 | b >>>= (tree[tindex + 1]);
823 | k -= (tree[tindex + 1]);
824 |
825 | e = tree[tindex];
826 |
827 | if (e === 0) { // literal
828 | lit = tree[tindex + 2];
829 | mode = LIT;
830 | break;
831 | }
832 | if ((e & 16) !== 0) { // length
833 | get = e & 15;
834 | len = tree[tindex + 2];
835 | mode = LENEXT;
836 | break;
837 | }
838 | if ((e & 64) === 0) { // next table
839 | need = e;
840 | tree_index = tindex / 3 + tree[tindex + 2];
841 | break;
842 | }
843 | if ((e & 32) !== 0) { // end of block
844 | mode = WASH;
845 | break;
846 | }
847 | mode = BADCODE; // invalid code
848 | z.msg = "invalid literal/length code";
849 | r = Z_DATA_ERROR;
850 |
851 | s.bitb = b;
852 | s.bitk = k;
853 | z.avail_in = n;
854 | z.total_in += p - z.next_in_index;
855 | z.next_in_index = p;
856 | s.write = q;
857 | return s.inflate_flush(z, r);
858 |
859 | case LENEXT: // i: getting length extra (have base)
860 | j = get;
861 |
862 | while (k < (j)) {
863 | if (n !== 0)
864 | r = Z_OK;
865 | else {
866 |
867 | s.bitb = b;
868 | s.bitk = k;
869 | z.avail_in = n;
870 | z.total_in += p - z.next_in_index;
871 | z.next_in_index = p;
872 | s.write = q;
873 | return s.inflate_flush(z, r);
874 | }
875 | n--;
876 | b |= (z.read_byte(p++) & 0xff) << k;
877 | k += 8;
878 | }
879 |
880 | len += (b & inflate_mask[j]);
881 |
882 | b >>= j;
883 | k -= j;
884 |
885 | need = dbits;
886 | tree = dtree;
887 | tree_index = dtree_index;
888 | mode = DIST;
889 | /* falls through */
890 | case DIST: // i: get distance next
891 | j = need;
892 |
893 | while (k < (j)) {
894 | if (n !== 0)
895 | r = Z_OK;
896 | else {
897 |
898 | s.bitb = b;
899 | s.bitk = k;
900 | z.avail_in = n;
901 | z.total_in += p - z.next_in_index;
902 | z.next_in_index = p;
903 | s.write = q;
904 | return s.inflate_flush(z, r);
905 | }
906 | n--;
907 | b |= (z.read_byte(p++) & 0xff) << k;
908 | k += 8;
909 | }
910 |
911 | tindex = (tree_index + (b & inflate_mask[j])) * 3;
912 |
913 | b >>= tree[tindex + 1];
914 | k -= tree[tindex + 1];
915 |
916 | e = (tree[tindex]);
917 | if ((e & 16) !== 0) { // distance
918 | get = e & 15;
919 | dist = tree[tindex + 2];
920 | mode = DISTEXT;
921 | break;
922 | }
923 | if ((e & 64) === 0) { // next table
924 | need = e;
925 | tree_index = tindex / 3 + tree[tindex + 2];
926 | break;
927 | }
928 | mode = BADCODE; // invalid code
929 | z.msg = "invalid distance code";
930 | r = Z_DATA_ERROR;
931 |
932 | s.bitb = b;
933 | s.bitk = k;
934 | z.avail_in = n;
935 | z.total_in += p - z.next_in_index;
936 | z.next_in_index = p;
937 | s.write = q;
938 | return s.inflate_flush(z, r);
939 |
940 | case DISTEXT: // i: getting distance extra
941 | j = get;
942 |
943 | while (k < (j)) {
944 | if (n !== 0)
945 | r = Z_OK;
946 | else {
947 |
948 | s.bitb = b;
949 | s.bitk = k;
950 | z.avail_in = n;
951 | z.total_in += p - z.next_in_index;
952 | z.next_in_index = p;
953 | s.write = q;
954 | return s.inflate_flush(z, r);
955 | }
956 | n--;
957 | b |= (z.read_byte(p++) & 0xff) << k;
958 | k += 8;
959 | }
960 |
961 | dist += (b & inflate_mask[j]);
962 |
963 | b >>= j;
964 | k -= j;
965 |
966 | mode = COPY;
967 | /* falls through */
968 | case COPY: // o: copying bytes in window, waiting for space
969 | f = q - dist;
970 | while (f < 0) { // modulo window size-"while" instead
971 | f += s.end; // of "if" handles invalid distances
972 | }
973 | while (len !== 0) {
974 |
975 | if (m === 0) {
976 | if (q == s.end && s.read !== 0) {
977 | q = 0;
978 | m = q < s.read ? s.read - q - 1 : s.end - q;
979 | }
980 | if (m === 0) {
981 | s.write = q;
982 | r = s.inflate_flush(z, r);
983 | q = s.write;
984 | m = q < s.read ? s.read - q - 1 : s.end - q;
985 |
986 | if (q == s.end && s.read !== 0) {
987 | q = 0;
988 | m = q < s.read ? s.read - q - 1 : s.end - q;
989 | }
990 |
991 | if (m === 0) {
992 | s.bitb = b;
993 | s.bitk = k;
994 | z.avail_in = n;
995 | z.total_in += p - z.next_in_index;
996 | z.next_in_index = p;
997 | s.write = q;
998 | return s.inflate_flush(z, r);
999 | }
1000 | }
1001 | }
1002 |
1003 | s.window[q++] = s.window[f++];
1004 | m--;
1005 |
1006 | if (f == s.end)
1007 | f = 0;
1008 | len--;
1009 | }
1010 | mode = START;
1011 | break;
1012 | case LIT: // o: got literal, waiting for output space
1013 | if (m === 0) {
1014 | if (q == s.end && s.read !== 0) {
1015 | q = 0;
1016 | m = q < s.read ? s.read - q - 1 : s.end - q;
1017 | }
1018 | if (m === 0) {
1019 | s.write = q;
1020 | r = s.inflate_flush(z, r);
1021 | q = s.write;
1022 | m = q < s.read ? s.read - q - 1 : s.end - q;
1023 |
1024 | if (q == s.end && s.read !== 0) {
1025 | q = 0;
1026 | m = q < s.read ? s.read - q - 1 : s.end - q;
1027 | }
1028 | if (m === 0) {
1029 | s.bitb = b;
1030 | s.bitk = k;
1031 | z.avail_in = n;
1032 | z.total_in += p - z.next_in_index;
1033 | z.next_in_index = p;
1034 | s.write = q;
1035 | return s.inflate_flush(z, r);
1036 | }
1037 | }
1038 | }
1039 | r = Z_OK;
1040 |
1041 | s.window[q++] = /* (byte) */lit;
1042 | m--;
1043 |
1044 | mode = START;
1045 | break;
1046 | case WASH: // o: got eob, possibly more output
1047 | if (k > 7) { // return unused byte, if any
1048 | k -= 8;
1049 | n++;
1050 | p--; // can always return one
1051 | }
1052 |
1053 | s.write = q;
1054 | r = s.inflate_flush(z, r);
1055 | q = s.write;
1056 | m = q < s.read ? s.read - q - 1 : s.end - q;
1057 |
1058 | if (s.read != s.write) {
1059 | s.bitb = b;
1060 | s.bitk = k;
1061 | z.avail_in = n;
1062 | z.total_in += p - z.next_in_index;
1063 | z.next_in_index = p;
1064 | s.write = q;
1065 | return s.inflate_flush(z, r);
1066 | }
1067 | mode = END;
1068 | /* falls through */
1069 | case END:
1070 | r = Z_STREAM_END;
1071 | s.bitb = b;
1072 | s.bitk = k;
1073 | z.avail_in = n;
1074 | z.total_in += p - z.next_in_index;
1075 | z.next_in_index = p;
1076 | s.write = q;
1077 | return s.inflate_flush(z, r);
1078 |
1079 | case BADCODE: // x: got error
1080 |
1081 | r = Z_DATA_ERROR;
1082 |
1083 | s.bitb = b;
1084 | s.bitk = k;
1085 | z.avail_in = n;
1086 | z.total_in += p - z.next_in_index;
1087 | z.next_in_index = p;
1088 | s.write = q;
1089 | return s.inflate_flush(z, r);
1090 |
1091 | default:
1092 | r = Z_STREAM_ERROR;
1093 |
1094 | s.bitb = b;
1095 | s.bitk = k;
1096 | z.avail_in = n;
1097 | z.total_in += p - z.next_in_index;
1098 | z.next_in_index = p;
1099 | s.write = q;
1100 | return s.inflate_flush(z, r);
1101 | }
1102 | }
1103 | };
1104 |
1105 | that.free = function() {
1106 | // ZFREE(z, c);
1107 | };
1108 |
1109 | }
1110 |
1111 | // InfBlocks
1112 |
1113 | // Table for deflate from PKZIP's appnote.txt.
1114 | var border = [ // Order of the bit length code lengths
1115 | 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
1116 |
1117 | var TYPE = 0; // get type bits (3, including end bit)
1118 | var LENS = 1; // get lengths for stored
1119 | var STORED = 2;// processing stored block
1120 | var TABLE = 3; // get table lengths
1121 | var BTREE = 4; // get bit lengths tree for a dynamic
1122 | // block
1123 | var DTREE = 5; // get length, distance trees for a
1124 | // dynamic block
1125 | var CODES = 6; // processing fixed or dynamic block
1126 | var DRY = 7; // output remaining window bytes
1127 | var DONELOCKS = 8; // finished last block, done
1128 | var BADBLOCKS = 9; // ot a data error--stuck here
1129 |
1130 | function InfBlocks(z, w) {
1131 | var that = this;
1132 |
1133 | var mode = TYPE; // current inflate_block mode
1134 |
1135 | var left = 0; // if STORED, bytes left to copy
1136 |
1137 | var table = 0; // table lengths (14 bits)
1138 | var index = 0; // index into blens (or border)
1139 | var blens; // bit lengths of codes
1140 | var bb = [ 0 ]; // bit length tree depth
1141 | var tb = [ 0 ]; // bit length decoding tree
1142 |
1143 | var codes = new InfCodes(); // if CODES, current state
1144 |
1145 | var last = 0; // true if this block is the last block
1146 |
1147 | var hufts = new Int32Array(MANY * 3); // single malloc for tree space
1148 | var check = 0; // check on output
1149 | var inftree = new InfTree();
1150 |
1151 | that.bitk = 0; // bits in bit buffer
1152 | that.bitb = 0; // bit buffer
1153 | that.window = new Uint8Array(w); // sliding window
1154 | that.end = w; // one byte after sliding window
1155 | that.read = 0; // window read pointer
1156 | that.write = 0; // window write pointer
1157 |
1158 | that.reset = function(z, c) {
1159 | if (c)
1160 | c[0] = check;
1161 | // if (mode == BTREE || mode == DTREE) {
1162 | // }
1163 | if (mode == CODES) {
1164 | codes.free(z);
1165 | }
1166 | mode = TYPE;
1167 | that.bitk = 0;
1168 | that.bitb = 0;
1169 | that.read = that.write = 0;
1170 | };
1171 |
1172 | that.reset(z, null);
1173 |
1174 | // copy as much as possible from the sliding window to the output area
1175 | that.inflate_flush = function(z, r) {
1176 | var n;
1177 | var p;
1178 | var q;
1179 |
1180 | // local copies of source and destination pointers
1181 | p = z.next_out_index;
1182 | q = that.read;
1183 |
1184 | // compute number of bytes to copy as far as end of window
1185 | n = /* (int) */((q <= that.write ? that.write : that.end) - q);
1186 | if (n > z.avail_out)
1187 | n = z.avail_out;
1188 | if (n !== 0 && r == Z_BUF_ERROR)
1189 | r = Z_OK;
1190 |
1191 | // update counters
1192 | z.avail_out -= n;
1193 | z.total_out += n;
1194 |
1195 | // copy as far as end of window
1196 | z.next_out.set(that.window.subarray(q, q + n), p);
1197 | p += n;
1198 | q += n;
1199 |
1200 | // see if more to copy at beginning of window
1201 | if (q == that.end) {
1202 | // wrap pointers
1203 | q = 0;
1204 | if (that.write == that.end)
1205 | that.write = 0;
1206 |
1207 | // compute bytes to copy
1208 | n = that.write - q;
1209 | if (n > z.avail_out)
1210 | n = z.avail_out;
1211 | if (n !== 0 && r == Z_BUF_ERROR)
1212 | r = Z_OK;
1213 |
1214 | // update counters
1215 | z.avail_out -= n;
1216 | z.total_out += n;
1217 |
1218 | // copy
1219 | z.next_out.set(that.window.subarray(q, q + n), p);
1220 | p += n;
1221 | q += n;
1222 | }
1223 |
1224 | // update pointers
1225 | z.next_out_index = p;
1226 | that.read = q;
1227 |
1228 | // done
1229 | return r;
1230 | };
1231 |
1232 | that.proc = function(z, r) {
1233 | var t; // temporary storage
1234 | var b; // bit buffer
1235 | var k; // bits in bit buffer
1236 | var p; // input data pointer
1237 | var n; // bytes available there
1238 | var q; // output window write pointer
1239 | var m; // bytes to end of window or read pointer
1240 |
1241 | var i;
1242 |
1243 | // copy input/output information to locals (UPDATE macro restores)
1244 | // {
1245 | p = z.next_in_index;
1246 | n = z.avail_in;
1247 | b = that.bitb;
1248 | k = that.bitk;
1249 | // }
1250 | // {
1251 | q = that.write;
1252 | m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
1253 | // }
1254 |
1255 | // process input based on current state
1256 | // DEBUG dtree
1257 | while (true) {
1258 | switch (mode) {
1259 | case TYPE:
1260 |
1261 | while (k < (3)) {
1262 | if (n !== 0) {
1263 | r = Z_OK;
1264 | } else {
1265 | that.bitb = b;
1266 | that.bitk = k;
1267 | z.avail_in = n;
1268 | z.total_in += p - z.next_in_index;
1269 | z.next_in_index = p;
1270 | that.write = q;
1271 | return that.inflate_flush(z, r);
1272 | }
1273 | n--;
1274 | b |= (z.read_byte(p++) & 0xff) << k;
1275 | k += 8;
1276 | }
1277 | t = /* (int) */(b & 7);
1278 | last = t & 1;
1279 |
1280 | switch (t >>> 1) {
1281 | case 0: // stored
1282 | // {
1283 | b >>>= (3);
1284 | k -= (3);
1285 | // }
1286 | t = k & 7; // go to byte boundary
1287 |
1288 | // {
1289 | b >>>= (t);
1290 | k -= (t);
1291 | // }
1292 | mode = LENS; // get length of stored block
1293 | break;
1294 | case 1: // fixed
1295 | // {
1296 | var bl = []; // new Array(1);
1297 | var bd = []; // new Array(1);
1298 | var tl = [ [] ]; // new Array(1);
1299 | var td = [ [] ]; // new Array(1);
1300 |
1301 | InfTree.inflate_trees_fixed(bl, bd, tl, td);
1302 | codes.init(bl[0], bd[0], tl[0], 0, td[0], 0);
1303 | // }
1304 |
1305 | // {
1306 | b >>>= (3);
1307 | k -= (3);
1308 | // }
1309 |
1310 | mode = CODES;
1311 | break;
1312 | case 2: // dynamic
1313 |
1314 | // {
1315 | b >>>= (3);
1316 | k -= (3);
1317 | // }
1318 |
1319 | mode = TABLE;
1320 | break;
1321 | case 3: // illegal
1322 |
1323 | // {
1324 | b >>>= (3);
1325 | k -= (3);
1326 | // }
1327 | mode = BADBLOCKS;
1328 | z.msg = "invalid block type";
1329 | r = Z_DATA_ERROR;
1330 |
1331 | that.bitb = b;
1332 | that.bitk = k;
1333 | z.avail_in = n;
1334 | z.total_in += p - z.next_in_index;
1335 | z.next_in_index = p;
1336 | that.write = q;
1337 | return that.inflate_flush(z, r);
1338 | }
1339 | break;
1340 | case LENS:
1341 |
1342 | while (k < (32)) {
1343 | if (n !== 0) {
1344 | r = Z_OK;
1345 | } else {
1346 | that.bitb = b;
1347 | that.bitk = k;
1348 | z.avail_in = n;
1349 | z.total_in += p - z.next_in_index;
1350 | z.next_in_index = p;
1351 | that.write = q;
1352 | return that.inflate_flush(z, r);
1353 | }
1354 | n--;
1355 | b |= (z.read_byte(p++) & 0xff) << k;
1356 | k += 8;
1357 | }
1358 |
1359 | if ((((~b) >>> 16) & 0xffff) != (b & 0xffff)) {
1360 | mode = BADBLOCKS;
1361 | z.msg = "invalid stored block lengths";
1362 | r = Z_DATA_ERROR;
1363 |
1364 | that.bitb = b;
1365 | that.bitk = k;
1366 | z.avail_in = n;
1367 | z.total_in += p - z.next_in_index;
1368 | z.next_in_index = p;
1369 | that.write = q;
1370 | return that.inflate_flush(z, r);
1371 | }
1372 | left = (b & 0xffff);
1373 | b = k = 0; // dump bits
1374 | mode = left !== 0 ? STORED : (last !== 0 ? DRY : TYPE);
1375 | break;
1376 | case STORED:
1377 | if (n === 0) {
1378 | that.bitb = b;
1379 | that.bitk = k;
1380 | z.avail_in = n;
1381 | z.total_in += p - z.next_in_index;
1382 | z.next_in_index = p;
1383 | that.write = q;
1384 | return that.inflate_flush(z, r);
1385 | }
1386 |
1387 | if (m === 0) {
1388 | if (q == that.end && that.read !== 0) {
1389 | q = 0;
1390 | m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
1391 | }
1392 | if (m === 0) {
1393 | that.write = q;
1394 | r = that.inflate_flush(z, r);
1395 | q = that.write;
1396 | m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
1397 | if (q == that.end && that.read !== 0) {
1398 | q = 0;
1399 | m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
1400 | }
1401 | if (m === 0) {
1402 | that.bitb = b;
1403 | that.bitk = k;
1404 | z.avail_in = n;
1405 | z.total_in += p - z.next_in_index;
1406 | z.next_in_index = p;
1407 | that.write = q;
1408 | return that.inflate_flush(z, r);
1409 | }
1410 | }
1411 | }
1412 | r = Z_OK;
1413 |
1414 | t = left;
1415 | if (t > n)
1416 | t = n;
1417 | if (t > m)
1418 | t = m;
1419 | that.window.set(z.read_buf(p, t), q);
1420 | p += t;
1421 | n -= t;
1422 | q += t;
1423 | m -= t;
1424 | if ((left -= t) !== 0)
1425 | break;
1426 | mode = last !== 0 ? DRY : TYPE;
1427 | break;
1428 | case TABLE:
1429 |
1430 | while (k < (14)) {
1431 | if (n !== 0) {
1432 | r = Z_OK;
1433 | } else {
1434 | that.bitb = b;
1435 | that.bitk = k;
1436 | z.avail_in = n;
1437 | z.total_in += p - z.next_in_index;
1438 | z.next_in_index = p;
1439 | that.write = q;
1440 | return that.inflate_flush(z, r);
1441 | }
1442 |
1443 | n--;
1444 | b |= (z.read_byte(p++) & 0xff) << k;
1445 | k += 8;
1446 | }
1447 |
1448 | table = t = (b & 0x3fff);
1449 | if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) {
1450 | mode = BADBLOCKS;
1451 | z.msg = "too many length or distance symbols";
1452 | r = Z_DATA_ERROR;
1453 |
1454 | that.bitb = b;
1455 | that.bitk = k;
1456 | z.avail_in = n;
1457 | z.total_in += p - z.next_in_index;
1458 | z.next_in_index = p;
1459 | that.write = q;
1460 | return that.inflate_flush(z, r);
1461 | }
1462 | t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
1463 | if (!blens || blens.length < t) {
1464 | blens = []; // new Array(t);
1465 | } else {
1466 | for (i = 0; i < t; i++) {
1467 | blens[i] = 0;
1468 | }
1469 | }
1470 |
1471 | // {
1472 | b >>>= (14);
1473 | k -= (14);
1474 | // }
1475 |
1476 | index = 0;
1477 | mode = BTREE;
1478 | /* falls through */
1479 | case BTREE:
1480 | while (index < 4 + (table >>> 10)) {
1481 | while (k < (3)) {
1482 | if (n !== 0) {
1483 | r = Z_OK;
1484 | } else {
1485 | that.bitb = b;
1486 | that.bitk = k;
1487 | z.avail_in = n;
1488 | z.total_in += p - z.next_in_index;
1489 | z.next_in_index = p;
1490 | that.write = q;
1491 | return that.inflate_flush(z, r);
1492 | }
1493 | n--;
1494 | b |= (z.read_byte(p++) & 0xff) << k;
1495 | k += 8;
1496 | }
1497 |
1498 | blens[border[index++]] = b & 7;
1499 |
1500 | // {
1501 | b >>>= (3);
1502 | k -= (3);
1503 | // }
1504 | }
1505 |
1506 | while (index < 19) {
1507 | blens[border[index++]] = 0;
1508 | }
1509 |
1510 | bb[0] = 7;
1511 | t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z);
1512 | if (t != Z_OK) {
1513 | r = t;
1514 | if (r == Z_DATA_ERROR) {
1515 | blens = null;
1516 | mode = BADBLOCKS;
1517 | }
1518 |
1519 | that.bitb = b;
1520 | that.bitk = k;
1521 | z.avail_in = n;
1522 | z.total_in += p - z.next_in_index;
1523 | z.next_in_index = p;
1524 | that.write = q;
1525 | return that.inflate_flush(z, r);
1526 | }
1527 |
1528 | index = 0;
1529 | mode = DTREE;
1530 | /* falls through */
1531 | case DTREE:
1532 | while (true) {
1533 | t = table;
1534 | if (index >= 258 + (t & 0x1f) + ((t >> 5) & 0x1f)) {
1535 | break;
1536 | }
1537 |
1538 | var j, c;
1539 |
1540 | t = bb[0];
1541 |
1542 | while (k < (t)) {
1543 | if (n !== 0) {
1544 | r = Z_OK;
1545 | } else {
1546 | that.bitb = b;
1547 | that.bitk = k;
1548 | z.avail_in = n;
1549 | z.total_in += p - z.next_in_index;
1550 | z.next_in_index = p;
1551 | that.write = q;
1552 | return that.inflate_flush(z, r);
1553 | }
1554 | n--;
1555 | b |= (z.read_byte(p++) & 0xff) << k;
1556 | k += 8;
1557 | }
1558 |
1559 | // if (tb[0] == -1) {
1560 | // System.err.println("null...");
1561 | // }
1562 |
1563 | t = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 1];
1564 | c = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 2];
1565 |
1566 | if (c < 16) {
1567 | b >>>= (t);
1568 | k -= (t);
1569 | blens[index++] = c;
1570 | } else { // c == 16..18
1571 | i = c == 18 ? 7 : c - 14;
1572 | j = c == 18 ? 11 : 3;
1573 |
1574 | while (k < (t + i)) {
1575 | if (n !== 0) {
1576 | r = Z_OK;
1577 | } else {
1578 | that.bitb = b;
1579 | that.bitk = k;
1580 | z.avail_in = n;
1581 | z.total_in += p - z.next_in_index;
1582 | z.next_in_index = p;
1583 | that.write = q;
1584 | return that.inflate_flush(z, r);
1585 | }
1586 | n--;
1587 | b |= (z.read_byte(p++) & 0xff) << k;
1588 | k += 8;
1589 | }
1590 |
1591 | b >>>= (t);
1592 | k -= (t);
1593 |
1594 | j += (b & inflate_mask[i]);
1595 |
1596 | b >>>= (i);
1597 | k -= (i);
1598 |
1599 | i = index;
1600 | t = table;
1601 | if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) {
1602 | blens = null;
1603 | mode = BADBLOCKS;
1604 | z.msg = "invalid bit length repeat";
1605 | r = Z_DATA_ERROR;
1606 |
1607 | that.bitb = b;
1608 | that.bitk = k;
1609 | z.avail_in = n;
1610 | z.total_in += p - z.next_in_index;
1611 | z.next_in_index = p;
1612 | that.write = q;
1613 | return that.inflate_flush(z, r);
1614 | }
1615 |
1616 | c = c == 16 ? blens[i - 1] : 0;
1617 | do {
1618 | blens[i++] = c;
1619 | } while (--j !== 0);
1620 | index = i;
1621 | }
1622 | }
1623 |
1624 | tb[0] = -1;
1625 | // {
1626 | var bl_ = []; // new Array(1);
1627 | var bd_ = []; // new Array(1);
1628 | var tl_ = []; // new Array(1);
1629 | var td_ = []; // new Array(1);
1630 | bl_[0] = 9; // must be <= 9 for lookahead assumptions
1631 | bd_[0] = 6; // must be <= 9 for lookahead assumptions
1632 |
1633 | t = table;
1634 | t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl_, bd_, tl_, td_, hufts, z);
1635 |
1636 | if (t != Z_OK) {
1637 | if (t == Z_DATA_ERROR) {
1638 | blens = null;
1639 | mode = BADBLOCKS;
1640 | }
1641 | r = t;
1642 |
1643 | that.bitb = b;
1644 | that.bitk = k;
1645 | z.avail_in = n;
1646 | z.total_in += p - z.next_in_index;
1647 | z.next_in_index = p;
1648 | that.write = q;
1649 | return that.inflate_flush(z, r);
1650 | }
1651 | codes.init(bl_[0], bd_[0], hufts, tl_[0], hufts, td_[0]);
1652 | // }
1653 | mode = CODES;
1654 | /* falls through */
1655 | case CODES:
1656 | that.bitb = b;
1657 | that.bitk = k;
1658 | z.avail_in = n;
1659 | z.total_in += p - z.next_in_index;
1660 | z.next_in_index = p;
1661 | that.write = q;
1662 |
1663 | if ((r = codes.proc(that, z, r)) != Z_STREAM_END) {
1664 | return that.inflate_flush(z, r);
1665 | }
1666 | r = Z_OK;
1667 | codes.free(z);
1668 |
1669 | p = z.next_in_index;
1670 | n = z.avail_in;
1671 | b = that.bitb;
1672 | k = that.bitk;
1673 | q = that.write;
1674 | m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
1675 |
1676 | if (last === 0) {
1677 | mode = TYPE;
1678 | break;
1679 | }
1680 | mode = DRY;
1681 | /* falls through */
1682 | case DRY:
1683 | that.write = q;
1684 | r = that.inflate_flush(z, r);
1685 | q = that.write;
1686 | m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
1687 | if (that.read != that.write) {
1688 | that.bitb = b;
1689 | that.bitk = k;
1690 | z.avail_in = n;
1691 | z.total_in += p - z.next_in_index;
1692 | z.next_in_index = p;
1693 | that.write = q;
1694 | return that.inflate_flush(z, r);
1695 | }
1696 | mode = DONELOCKS;
1697 | /* falls through */
1698 | case DONELOCKS:
1699 | r = Z_STREAM_END;
1700 |
1701 | that.bitb = b;
1702 | that.bitk = k;
1703 | z.avail_in = n;
1704 | z.total_in += p - z.next_in_index;
1705 | z.next_in_index = p;
1706 | that.write = q;
1707 | return that.inflate_flush(z, r);
1708 | case BADBLOCKS:
1709 | r = Z_DATA_ERROR;
1710 |
1711 | that.bitb = b;
1712 | that.bitk = k;
1713 | z.avail_in = n;
1714 | z.total_in += p - z.next_in_index;
1715 | z.next_in_index = p;
1716 | that.write = q;
1717 | return that.inflate_flush(z, r);
1718 |
1719 | default:
1720 | r = Z_STREAM_ERROR;
1721 |
1722 | that.bitb = b;
1723 | that.bitk = k;
1724 | z.avail_in = n;
1725 | z.total_in += p - z.next_in_index;
1726 | z.next_in_index = p;
1727 | that.write = q;
1728 | return that.inflate_flush(z, r);
1729 | }
1730 | }
1731 | };
1732 |
1733 | that.free = function(z) {
1734 | that.reset(z, null);
1735 | that.window = null;
1736 | hufts = null;
1737 | // ZFREE(z, s);
1738 | };
1739 |
1740 | that.set_dictionary = function(d, start, n) {
1741 | that.window.set(d.subarray(start, start + n), 0);
1742 | that.read = that.write = n;
1743 | };
1744 |
1745 | // Returns true if inflate is currently at the end of a block generated
1746 | // by Z_SYNC_FLUSH or Z_FULL_FLUSH.
1747 | that.sync_point = function() {
1748 | return mode == LENS ? 1 : 0;
1749 | };
1750 |
1751 | }
1752 |
1753 | // Inflate
1754 |
1755 | // preset dictionary flag in zlib header
1756 | var PRESET_DICT = 0x20;
1757 |
1758 | var Z_DEFLATED = 8;
1759 |
1760 | var METHOD = 0; // waiting for method byte
1761 | var FLAG = 1; // waiting for flag byte
1762 | var DICT4 = 2; // four dictionary check bytes to go
1763 | var DICT3 = 3; // three dictionary check bytes to go
1764 | var DICT2 = 4; // two dictionary check bytes to go
1765 | var DICT1 = 5; // one dictionary check byte to go
1766 | var DICT0 = 6; // waiting for inflateSetDictionary
1767 | var BLOCKS = 7; // decompressing blocks
1768 | var DONE = 12; // finished check, done
1769 | var BAD = 13; // got an error--stay here
1770 |
1771 | var mark = [ 0, 0, 0xff, 0xff ];
1772 |
1773 | function Inflate() {
1774 | var that = this;
1775 |
1776 | that.mode = 0; // current inflate mode
1777 |
1778 | // mode dependent information
1779 | that.method = 0; // if FLAGS, method byte
1780 |
1781 | // if CHECK, check values to compare
1782 | that.was = [ 0 ]; // new Array(1); // computed check value
1783 | that.need = 0; // stream check value
1784 |
1785 | // if BAD, inflateSync's marker bytes count
1786 | that.marker = 0;
1787 |
1788 | // mode independent information
1789 | that.wbits = 0; // log2(window size) (8..15, defaults to 15)
1790 |
1791 | // this.blocks; // current inflate_blocks state
1792 |
1793 | function inflateReset(z) {
1794 | if (!z || !z.istate)
1795 | return Z_STREAM_ERROR;
1796 |
1797 | z.total_in = z.total_out = 0;
1798 | z.msg = null;
1799 | z.istate.mode = BLOCKS;
1800 | z.istate.blocks.reset(z, null);
1801 | return Z_OK;
1802 | }
1803 |
1804 | that.inflateEnd = function(z) {
1805 | if (that.blocks)
1806 | that.blocks.free(z);
1807 | that.blocks = null;
1808 | // ZFREE(z, z->state);
1809 | return Z_OK;
1810 | };
1811 |
1812 | that.inflateInit = function(z, w) {
1813 | z.msg = null;
1814 | that.blocks = null;
1815 |
1816 | // set window size
1817 | if (w < 8 || w > 15) {
1818 | that.inflateEnd(z);
1819 | return Z_STREAM_ERROR;
1820 | }
1821 | that.wbits = w;
1822 |
1823 | z.istate.blocks = new InfBlocks(z, 1 << w);
1824 |
1825 | // reset state
1826 | inflateReset(z);
1827 | return Z_OK;
1828 | };
1829 |
1830 | that.inflate = function(z, f) {
1831 | var r;
1832 | var b;
1833 |
1834 | if (!z || !z.istate || !z.next_in)
1835 | return Z_STREAM_ERROR;
1836 | f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
1837 | r = Z_BUF_ERROR;
1838 | while (true) {
1839 | // System.out.println("mode: "+z.istate.mode);
1840 | switch (z.istate.mode) {
1841 | case METHOD:
1842 |
1843 | if (z.avail_in === 0)
1844 | return r;
1845 | r = f;
1846 |
1847 | z.avail_in--;
1848 | z.total_in++;
1849 | if (((z.istate.method = z.read_byte(z.next_in_index++)) & 0xf) != Z_DEFLATED) {
1850 | z.istate.mode = BAD;
1851 | z.msg = "unknown compression method";
1852 | z.istate.marker = 5; // can't try inflateSync
1853 | break;
1854 | }
1855 | if ((z.istate.method >> 4) + 8 > z.istate.wbits) {
1856 | z.istate.mode = BAD;
1857 | z.msg = "invalid window size";
1858 | z.istate.marker = 5; // can't try inflateSync
1859 | break;
1860 | }
1861 | z.istate.mode = FLAG;
1862 | /* falls through */
1863 | case FLAG:
1864 |
1865 | if (z.avail_in === 0)
1866 | return r;
1867 | r = f;
1868 |
1869 | z.avail_in--;
1870 | z.total_in++;
1871 | b = (z.read_byte(z.next_in_index++)) & 0xff;
1872 |
1873 | if ((((z.istate.method << 8) + b) % 31) !== 0) {
1874 | z.istate.mode = BAD;
1875 | z.msg = "incorrect header check";
1876 | z.istate.marker = 5; // can't try inflateSync
1877 | break;
1878 | }
1879 |
1880 | if ((b & PRESET_DICT) === 0) {
1881 | z.istate.mode = BLOCKS;
1882 | break;
1883 | }
1884 | z.istate.mode = DICT4;
1885 | /* falls through */
1886 | case DICT4:
1887 |
1888 | if (z.avail_in === 0)
1889 | return r;
1890 | r = f;
1891 |
1892 | z.avail_in--;
1893 | z.total_in++;
1894 | z.istate.need = ((z.read_byte(z.next_in_index++) & 0xff) << 24) & 0xff000000;
1895 | z.istate.mode = DICT3;
1896 | /* falls through */
1897 | case DICT3:
1898 |
1899 | if (z.avail_in === 0)
1900 | return r;
1901 | r = f;
1902 |
1903 | z.avail_in--;
1904 | z.total_in++;
1905 | z.istate.need += ((z.read_byte(z.next_in_index++) & 0xff) << 16) & 0xff0000;
1906 | z.istate.mode = DICT2;
1907 | /* falls through */
1908 | case DICT2:
1909 |
1910 | if (z.avail_in === 0)
1911 | return r;
1912 | r = f;
1913 |
1914 | z.avail_in--;
1915 | z.total_in++;
1916 | z.istate.need += ((z.read_byte(z.next_in_index++) & 0xff) << 8) & 0xff00;
1917 | z.istate.mode = DICT1;
1918 | /* falls through */
1919 | case DICT1:
1920 |
1921 | if (z.avail_in === 0)
1922 | return r;
1923 | r = f;
1924 |
1925 | z.avail_in--;
1926 | z.total_in++;
1927 | z.istate.need += (z.read_byte(z.next_in_index++) & 0xff);
1928 | z.istate.mode = DICT0;
1929 | return Z_NEED_DICT;
1930 | case DICT0:
1931 | z.istate.mode = BAD;
1932 | z.msg = "need dictionary";
1933 | z.istate.marker = 0; // can try inflateSync
1934 | return Z_STREAM_ERROR;
1935 | case BLOCKS:
1936 |
1937 | r = z.istate.blocks.proc(z, r);
1938 | if (r == Z_DATA_ERROR) {
1939 | z.istate.mode = BAD;
1940 | z.istate.marker = 0; // can try inflateSync
1941 | break;
1942 | }
1943 | if (r == Z_OK) {
1944 | r = f;
1945 | }
1946 | if (r != Z_STREAM_END) {
1947 | return r;
1948 | }
1949 | r = f;
1950 | z.istate.blocks.reset(z, z.istate.was);
1951 | z.istate.mode = DONE;
1952 | /* falls through */
1953 | case DONE:
1954 | return Z_STREAM_END;
1955 | case BAD:
1956 | return Z_DATA_ERROR;
1957 | default:
1958 | return Z_STREAM_ERROR;
1959 | }
1960 | }
1961 | };
1962 |
1963 | that.inflateSetDictionary = function(z, dictionary, dictLength) {
1964 | var index = 0;
1965 | var length = dictLength;
1966 | if (!z || !z.istate || z.istate.mode != DICT0)
1967 | return Z_STREAM_ERROR;
1968 |
1969 | if (length >= (1 << z.istate.wbits)) {
1970 | length = (1 << z.istate.wbits) - 1;
1971 | index = dictLength - length;
1972 | }
1973 | z.istate.blocks.set_dictionary(dictionary, index, length);
1974 | z.istate.mode = BLOCKS;
1975 | return Z_OK;
1976 | };
1977 |
1978 | that.inflateSync = function(z) {
1979 | var n; // number of bytes to look at
1980 | var p; // pointer to bytes
1981 | var m; // number of marker bytes found in a row
1982 | var r, w; // temporaries to save total_in and total_out
1983 |
1984 | // set up
1985 | if (!z || !z.istate)
1986 | return Z_STREAM_ERROR;
1987 | if (z.istate.mode != BAD) {
1988 | z.istate.mode = BAD;
1989 | z.istate.marker = 0;
1990 | }
1991 | if ((n = z.avail_in) === 0)
1992 | return Z_BUF_ERROR;
1993 | p = z.next_in_index;
1994 | m = z.istate.marker;
1995 |
1996 | // search
1997 | while (n !== 0 && m < 4) {
1998 | if (z.read_byte(p) == mark[m]) {
1999 | m++;
2000 | } else if (z.read_byte(p) !== 0) {
2001 | m = 0;
2002 | } else {
2003 | m = 4 - m;
2004 | }
2005 | p++;
2006 | n--;
2007 | }
2008 |
2009 | // restore
2010 | z.total_in += p - z.next_in_index;
2011 | z.next_in_index = p;
2012 | z.avail_in = n;
2013 | z.istate.marker = m;
2014 |
2015 | // return no joy or set up to restart on a new block
2016 | if (m != 4) {
2017 | return Z_DATA_ERROR;
2018 | }
2019 | r = z.total_in;
2020 | w = z.total_out;
2021 | inflateReset(z);
2022 | z.total_in = r;
2023 | z.total_out = w;
2024 | z.istate.mode = BLOCKS;
2025 | return Z_OK;
2026 | };
2027 |
2028 | // Returns true if inflate is currently at the end of a block generated
2029 | // by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
2030 | // implementation to provide an additional safety check. PPP uses
2031 | // Z_SYNC_FLUSH
2032 | // but removes the length bytes of the resulting empty stored block. When
2033 | // decompressing, PPP checks that at the end of input packet, inflate is
2034 | // waiting for these length bytes.
2035 | that.inflateSyncPoint = function(z) {
2036 | if (!z || !z.istate || !z.istate.blocks)
2037 | return Z_STREAM_ERROR;
2038 | return z.istate.blocks.sync_point();
2039 | };
2040 | }
2041 |
2042 | // ZStream
2043 |
2044 | function ZStream() {
2045 | }
2046 |
2047 | ZStream.prototype = {
2048 | inflateInit : function(bits) {
2049 | var that = this;
2050 | that.istate = new Inflate();
2051 | if (!bits)
2052 | bits = MAX_BITS;
2053 | return that.istate.inflateInit(that, bits);
2054 | },
2055 |
2056 | inflate : function(f) {
2057 | var that = this;
2058 | if (!that.istate)
2059 | return Z_STREAM_ERROR;
2060 | return that.istate.inflate(that, f);
2061 | },
2062 |
2063 | inflateEnd : function() {
2064 | var that = this;
2065 | if (!that.istate)
2066 | return Z_STREAM_ERROR;
2067 | var ret = that.istate.inflateEnd(that);
2068 | that.istate = null;
2069 | return ret;
2070 | },
2071 |
2072 | inflateSync : function() {
2073 | var that = this;
2074 | if (!that.istate)
2075 | return Z_STREAM_ERROR;
2076 | return that.istate.inflateSync(that);
2077 | },
2078 | inflateSetDictionary : function(dictionary, dictLength) {
2079 | var that = this;
2080 | if (!that.istate)
2081 | return Z_STREAM_ERROR;
2082 | return that.istate.inflateSetDictionary(that, dictionary, dictLength);
2083 | },
2084 | read_byte : function(start) {
2085 | var that = this;
2086 | return that.next_in.subarray(start, start + 1)[0];
2087 | },
2088 | read_buf : function(start, size) {
2089 | var that = this;
2090 | return that.next_in.subarray(start, start + size);
2091 | }
2092 | };
2093 |
2094 | // Inflater
2095 |
2096 | function Inflater() {
2097 | var that = this;
2098 | var z = new ZStream();
2099 | var bufsize = 512;
2100 | var flush = Z_NO_FLUSH;
2101 | var buf = new Uint8Array(bufsize);
2102 | var nomoreinput = false;
2103 |
2104 | z.inflateInit();
2105 | z.next_out = buf;
2106 |
2107 | that.append = function(data, onprogress) {
2108 | var err, buffers = [], lastIndex = 0, bufferIndex = 0, bufferSize = 0, array;
2109 | if (data.length === 0)
2110 | return;
2111 | z.next_in_index = 0;
2112 | z.next_in = data;
2113 | z.avail_in = data.length;
2114 | do {
2115 | z.next_out_index = 0;
2116 | z.avail_out = bufsize;
2117 | if ((z.avail_in === 0) && (!nomoreinput)) { // if buffer is empty and more input is available, refill it
2118 | z.next_in_index = 0;
2119 | nomoreinput = true;
2120 | }
2121 | err = z.inflate(flush);
2122 | if (nomoreinput && (err === Z_BUF_ERROR)) {
2123 | if (z.avail_in !== 0)
2124 | throw new Error("inflating: bad input");
2125 | } else if (err !== Z_OK && err !== Z_STREAM_END)
2126 | throw new Error("inflating: " + z.msg);
2127 | if ((nomoreinput || err === Z_STREAM_END) && (z.avail_in === data.length))
2128 | throw new Error("inflating: bad input");
2129 | if (z.next_out_index)
2130 | if (z.next_out_index === bufsize)
2131 | buffers.push(new Uint8Array(buf));
2132 | else
2133 | buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
2134 | bufferSize += z.next_out_index;
2135 | if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
2136 | onprogress(z.next_in_index);
2137 | lastIndex = z.next_in_index;
2138 | }
2139 | } while (z.avail_in > 0 || z.avail_out === 0);
2140 | array = new Uint8Array(bufferSize);
2141 | buffers.forEach(function(chunk) {
2142 | array.set(chunk, bufferIndex);
2143 | bufferIndex += chunk.length;
2144 | });
2145 | return array;
2146 | };
2147 | that.flush = function() {
2148 | z.inflateEnd();
2149 | };
2150 | }
2151 |
2152 | // 'zip' may not be defined in z-worker and some tests
2153 | var env = global.zip || global;
2154 | env.Inflater = env._jzlib_Inflater = Inflater;
2155 | })(this);
--------------------------------------------------------------------------------
/zip/deflate.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2013 Gildas Lormeau. All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without
5 | modification, are permitted provided that the following conditions are met:
6 |
7 | 1. Redistributions of source code must retain the above copyright notice,
8 | this list of conditions and the following disclaimer.
9 |
10 | 2. Redistributions in binary form must reproduce the above copyright
11 | notice, this list of conditions and the following disclaimer in
12 | the documentation and/or other materials provided with the distribution.
13 |
14 | 3. The names of the authors may not be used to endorse or promote products
15 | derived from this software without specific prior written permission.
16 |
17 | THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
18 | INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
19 | FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
20 | INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
21 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 | OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
26 | EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 | */
28 |
29 | /*
30 | * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
31 | * JZlib is based on zlib-1.1.3, so all credit should go authors
32 | * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
33 | * and contributors of zlib.
34 | */
35 |
36 | (function(global) {
37 | "use strict";
38 |
39 | // Global
40 |
41 | var MAX_BITS = 15;
42 | var D_CODES = 30;
43 | var BL_CODES = 19;
44 |
45 | var LENGTH_CODES = 29;
46 | var LITERALS = 256;
47 | var L_CODES = (LITERALS + 1 + LENGTH_CODES);
48 | var HEAP_SIZE = (2 * L_CODES + 1);
49 |
50 | var END_BLOCK = 256;
51 |
52 | // Bit length codes must not exceed MAX_BL_BITS bits
53 | var MAX_BL_BITS = 7;
54 |
55 | // repeat previous bit length 3-6 times (2 bits of repeat count)
56 | var REP_3_6 = 16;
57 |
58 | // repeat a zero length 3-10 times (3 bits of repeat count)
59 | var REPZ_3_10 = 17;
60 |
61 | // repeat a zero length 11-138 times (7 bits of repeat count)
62 | var REPZ_11_138 = 18;
63 |
64 | // The lengths of the bit length codes are sent in order of decreasing
65 | // probability, to avoid transmitting the lengths for unused bit
66 | // length codes.
67 |
68 | var Buf_size = 8 * 2;
69 |
70 | // JZlib version : "1.0.2"
71 | var Z_DEFAULT_COMPRESSION = -1;
72 |
73 | // compression strategy
74 | var Z_FILTERED = 1;
75 | var Z_HUFFMAN_ONLY = 2;
76 | var Z_DEFAULT_STRATEGY = 0;
77 |
78 | var Z_NO_FLUSH = 0;
79 | var Z_PARTIAL_FLUSH = 1;
80 | var Z_FULL_FLUSH = 3;
81 | var Z_FINISH = 4;
82 |
83 | var Z_OK = 0;
84 | var Z_STREAM_END = 1;
85 | var Z_NEED_DICT = 2;
86 | var Z_STREAM_ERROR = -2;
87 | var Z_DATA_ERROR = -3;
88 | var Z_BUF_ERROR = -5;
89 |
90 | // Tree
91 |
92 | // see definition of array dist_code below
93 | var _dist_code = [ 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
94 | 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
95 | 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
96 | 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
97 | 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
98 | 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
99 | 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19,
100 | 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
101 | 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
102 | 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
103 | 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
104 | 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29,
105 | 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
106 | 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 ];
107 |
108 | function Tree() {
109 | var that = this;
110 |
111 | // dyn_tree; // the dynamic tree
112 | // max_code; // largest code with non zero frequency
113 | // stat_desc; // the corresponding static tree
114 |
115 | // Compute the optimal bit lengths for a tree and update the total bit
116 | // length
117 | // for the current block.
118 | // IN assertion: the fields freq and dad are set, heap[heap_max] and
119 | // above are the tree nodes sorted by increasing frequency.
120 | // OUT assertions: the field len is set to the optimal bit length, the
121 | // array bl_count contains the frequencies for each bit length.
122 | // The length opt_len is updated; static_len is also updated if stree is
123 | // not null.
124 | function gen_bitlen(s) {
125 | var tree = that.dyn_tree;
126 | var stree = that.stat_desc.static_tree;
127 | var extra = that.stat_desc.extra_bits;
128 | var base = that.stat_desc.extra_base;
129 | var max_length = that.stat_desc.max_length;
130 | var h; // heap index
131 | var n, m; // iterate over the tree elements
132 | var bits; // bit length
133 | var xbits; // extra bits
134 | var f; // frequency
135 | var overflow = 0; // number of elements with bit length too large
136 |
137 | for (bits = 0; bits <= MAX_BITS; bits++)
138 | s.bl_count[bits] = 0;
139 |
140 | // In a first pass, compute the optimal bit lengths (which may
141 | // overflow in the case of the bit length tree).
142 | tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
143 |
144 | for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
145 | n = s.heap[h];
146 | bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
147 | if (bits > max_length) {
148 | bits = max_length;
149 | overflow++;
150 | }
151 | tree[n * 2 + 1] = bits;
152 | // We overwrite tree[n*2+1] which is no longer needed
153 |
154 | if (n > that.max_code)
155 | continue; // not a leaf node
156 |
157 | s.bl_count[bits]++;
158 | xbits = 0;
159 | if (n >= base)
160 | xbits = extra[n - base];
161 | f = tree[n * 2];
162 | s.opt_len += f * (bits + xbits);
163 | if (stree)
164 | s.static_len += f * (stree[n * 2 + 1] + xbits);
165 | }
166 | if (overflow === 0)
167 | return;
168 |
169 | // This happens for example on obj2 and pic of the Calgary corpus
170 | // Find the first bit length which could increase:
171 | do {
172 | bits = max_length - 1;
173 | while (s.bl_count[bits] === 0)
174 | bits--;
175 | s.bl_count[bits]--; // move one leaf down the tree
176 | s.bl_count[bits + 1] += 2; // move one overflow item as its brother
177 | s.bl_count[max_length]--;
178 | // The brother of the overflow item also moves one step up,
179 | // but this does not affect bl_count[max_length]
180 | overflow -= 2;
181 | } while (overflow > 0);
182 |
183 | for (bits = max_length; bits !== 0; bits--) {
184 | n = s.bl_count[bits];
185 | while (n !== 0) {
186 | m = s.heap[--h];
187 | if (m > that.max_code)
188 | continue;
189 | if (tree[m * 2 + 1] != bits) {
190 | s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
191 | tree[m * 2 + 1] = bits;
192 | }
193 | n--;
194 | }
195 | }
196 | }
197 |
198 | // Reverse the first len bits of a code, using straightforward code (a
199 | // faster
200 | // method would use a table)
201 | // IN assertion: 1 <= len <= 15
202 | function bi_reverse(code, // the value to invert
203 | len // its bit length
204 | ) {
205 | var res = 0;
206 | do {
207 | res |= code & 1;
208 | code >>>= 1;
209 | res <<= 1;
210 | } while (--len > 0);
211 | return res >>> 1;
212 | }
213 |
214 | // Generate the codes for a given tree and bit counts (which need not be
215 | // optimal).
216 | // IN assertion: the array bl_count contains the bit length statistics for
217 | // the given tree and the field len is set for all tree elements.
218 | // OUT assertion: the field code is set for all tree elements of non
219 | // zero code length.
220 | function gen_codes(tree, // the tree to decorate
221 | max_code, // largest code with non zero frequency
222 | bl_count // number of codes at each bit length
223 | ) {
224 | var next_code = []; // next code value for each
225 | // bit length
226 | var code = 0; // running code value
227 | var bits; // bit index
228 | var n; // code index
229 | var len;
230 |
231 | // The distribution counts are first used to generate the code values
232 | // without bit reversal.
233 | for (bits = 1; bits <= MAX_BITS; bits++) {
234 | next_code[bits] = code = ((code + bl_count[bits - 1]) << 1);
235 | }
236 |
237 | // Check that the bit counts in bl_count are consistent. The last code
238 | // must be all ones.
239 | // Assert (code + bl_count[MAX_BITS]-1 == (1<= 1; n--)
300 | s.pqdownheap(tree, n);
301 |
302 | // Construct the Huffman tree by repeatedly combining the least two
303 | // frequent nodes.
304 |
305 | node = elems; // next internal node of the tree
306 | do {
307 | // n = node of least frequency
308 | n = s.heap[1];
309 | s.heap[1] = s.heap[s.heap_len--];
310 | s.pqdownheap(tree, 1);
311 | m = s.heap[1]; // m = node of next least frequency
312 |
313 | s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
314 | s.heap[--s.heap_max] = m;
315 |
316 | // Create a new node father of n and m
317 | tree[node * 2] = (tree[n * 2] + tree[m * 2]);
318 | s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
319 | tree[n * 2 + 1] = tree[m * 2 + 1] = node;
320 |
321 | // and insert the new node in the heap
322 | s.heap[1] = node++;
323 | s.pqdownheap(tree, 1);
324 | } while (s.heap_len >= 2);
325 |
326 | s.heap[--s.heap_max] = s.heap[1];
327 |
328 | // At this point, the fields freq and dad are set. We can now
329 | // generate the bit lengths.
330 |
331 | gen_bitlen(s);
332 |
333 | // The field len is now set, we can generate the bit codes
334 | gen_codes(tree, that.max_code, s.bl_count);
335 | };
336 |
337 | }
338 |
339 | Tree._length_code = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16,
340 | 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20,
341 | 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
342 | 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
343 | 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
344 | 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
345 | 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 ];
346 |
347 | Tree.base_length = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 ];
348 |
349 | Tree.base_dist = [ 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384,
350 | 24576 ];
351 |
352 | // Mapping from a distance to a distance code. dist is the distance - 1 and
353 | // must not have side effects. _dist_code[256] and _dist_code[257] are never
354 | // used.
355 | Tree.d_code = function(dist) {
356 | return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]);
357 | };
358 |
359 | // extra bits for each length code
360 | Tree.extra_lbits = [ 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 ];
361 |
362 | // extra bits for each distance code
363 | Tree.extra_dbits = [ 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 ];
364 |
365 | // extra bits for each bit length code
366 | Tree.extra_blbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 ];
367 |
368 | Tree.bl_order = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
369 |
370 | // StaticTree
371 |
372 | function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
373 | var that = this;
374 | that.static_tree = static_tree;
375 | that.extra_bits = extra_bits;
376 | that.extra_base = extra_base;
377 | that.elems = elems;
378 | that.max_length = max_length;
379 | }
380 |
381 | StaticTree.static_ltree = [ 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8,
382 | 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42,
383 | 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8,
384 | 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8,
385 | 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113,
386 | 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8,
387 | 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8,
388 | 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9,
389 | 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9,
390 | 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379,
391 | 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23,
392 | 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9,
393 | 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9,
394 | 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7,
395 | 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8,
396 | 99, 8, 227, 8 ];
397 |
398 | StaticTree.static_dtree = [ 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5,
399 | 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 ];
400 |
401 | StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
402 |
403 | StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
404 |
405 | StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
406 |
407 | // Deflate
408 |
409 | var MAX_MEM_LEVEL = 9;
410 | var DEF_MEM_LEVEL = 8;
411 |
412 | function Config(good_length, max_lazy, nice_length, max_chain, func) {
413 | var that = this;
414 | that.good_length = good_length;
415 | that.max_lazy = max_lazy;
416 | that.nice_length = nice_length;
417 | that.max_chain = max_chain;
418 | that.func = func;
419 | }
420 |
421 | var STORED = 0;
422 | var FAST = 1;
423 | var SLOW = 2;
424 | var config_table = [ new Config(0, 0, 0, 0, STORED), new Config(4, 4, 8, 4, FAST), new Config(4, 5, 16, 8, FAST), new Config(4, 6, 32, 32, FAST),
425 | new Config(4, 4, 16, 16, SLOW), new Config(8, 16, 32, 32, SLOW), new Config(8, 16, 128, 128, SLOW), new Config(8, 32, 128, 256, SLOW),
426 | new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW) ];
427 |
428 | var z_errmsg = [ "need dictionary", // Z_NEED_DICT
429 | // 2
430 | "stream end", // Z_STREAM_END 1
431 | "", // Z_OK 0
432 | "", // Z_ERRNO (-1)
433 | "stream error", // Z_STREAM_ERROR (-2)
434 | "data error", // Z_DATA_ERROR (-3)
435 | "", // Z_MEM_ERROR (-4)
436 | "buffer error", // Z_BUF_ERROR (-5)
437 | "",// Z_VERSION_ERROR (-6)
438 | "" ];
439 |
440 | // block not completed, need more input or more output
441 | var NeedMore = 0;
442 |
443 | // block flush performed
444 | var BlockDone = 1;
445 |
446 | // finish started, need only more output at next deflate
447 | var FinishStarted = 2;
448 |
449 | // finish done, accept no more input or output
450 | var FinishDone = 3;
451 |
452 | // preset dictionary flag in zlib header
453 | var PRESET_DICT = 0x20;
454 |
455 | var INIT_STATE = 42;
456 | var BUSY_STATE = 113;
457 | var FINISH_STATE = 666;
458 |
459 | // The deflate compression method
460 | var Z_DEFLATED = 8;
461 |
462 | var STORED_BLOCK = 0;
463 | var STATIC_TREES = 1;
464 | var DYN_TREES = 2;
465 |
466 | var MIN_MATCH = 3;
467 | var MAX_MATCH = 258;
468 | var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
469 |
470 | function smaller(tree, n, m, depth) {
471 | var tn2 = tree[n * 2];
472 | var tm2 = tree[m * 2];
473 | return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
474 | }
475 |
476 | function Deflate() {
477 |
478 | var that = this;
479 | var strm; // pointer back to this zlib stream
480 | var status; // as the name implies
481 | // pending_buf; // output still pending
482 | var pending_buf_size; // size of pending_buf
483 | // pending_out; // next pending byte to output to the stream
484 | // pending; // nb of bytes in the pending buffer
485 | var method; // STORED (for zip only) or DEFLATED
486 | var last_flush; // value of flush param for previous deflate call
487 |
488 | var w_size; // LZ77 window size (32K by default)
489 | var w_bits; // log2(w_size) (8..16)
490 | var w_mask; // w_size - 1
491 |
492 | var window;
493 | // Sliding window. Input bytes are read into the second half of the window,
494 | // and move to the first half later to keep a dictionary of at least wSize
495 | // bytes. With this organization, matches are limited to a distance of
496 | // wSize-MAX_MATCH bytes, but this ensures that IO is always
497 | // performed with a length multiple of the block size. Also, it limits
498 | // the window size to 64K, which is quite useful on MSDOS.
499 | // To do: use the user input buffer as sliding window.
500 |
501 | var window_size;
502 | // Actual size of window: 2*wSize, except when the user input buffer
503 | // is directly used as sliding window.
504 |
505 | var prev;
506 | // Link to older string with same hash index. To limit the size of this
507 | // array to 64K, this link is maintained only for the last 32K strings.
508 | // An index in this array is thus a window index modulo 32K.
509 |
510 | var head; // Heads of the hash chains or NIL.
511 |
512 | var ins_h; // hash index of string to be inserted
513 | var hash_size; // number of elements in hash table
514 | var hash_bits; // log2(hash_size)
515 | var hash_mask; // hash_size-1
516 |
517 | // Number of bits by which ins_h must be shifted at each input
518 | // step. It must be such that after MIN_MATCH steps, the oldest
519 | // byte no longer takes part in the hash key, that is:
520 | // hash_shift * MIN_MATCH >= hash_bits
521 | var hash_shift;
522 |
523 | // Window position at the beginning of the current output block. Gets
524 | // negative when the window is moved backwards.
525 |
526 | var block_start;
527 |
528 | var match_length; // length of best match
529 | var prev_match; // previous match
530 | var match_available; // set if previous match exists
531 | var strstart; // start of string to insert
532 | var match_start; // start of matching string
533 | var lookahead; // number of valid bytes ahead in window
534 |
535 | // Length of the best match at previous step. Matches not greater than this
536 | // are discarded. This is used in the lazy match evaluation.
537 | var prev_length;
538 |
539 | // To speed up deflation, hash chains are never searched beyond this
540 | // length. A higher limit improves compression ratio but degrades the speed.
541 | var max_chain_length;
542 |
543 | // Attempt to find a better match only when the current match is strictly
544 | // smaller than this value. This mechanism is used only for compression
545 | // levels >= 4.
546 | var max_lazy_match;
547 |
548 | // Insert new strings in the hash table only if the match length is not
549 | // greater than this length. This saves time but degrades compression.
550 | // max_insert_length is used only for compression levels <= 3.
551 |
552 | var level; // compression level (1..9)
553 | var strategy; // favor or force Huffman coding
554 |
555 | // Use a faster search when the previous match is longer than this
556 | var good_match;
557 |
558 | // Stop searching when current match exceeds this
559 | var nice_match;
560 |
561 | var dyn_ltree; // literal and length tree
562 | var dyn_dtree; // distance tree
563 | var bl_tree; // Huffman tree for bit lengths
564 |
565 | var l_desc = new Tree(); // desc for literal tree
566 | var d_desc = new Tree(); // desc for distance tree
567 | var bl_desc = new Tree(); // desc for bit length tree
568 |
569 | // that.heap_len; // number of elements in the heap
570 | // that.heap_max; // element of largest frequency
571 | // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
572 | // The same heap array is used to build all trees.
573 |
574 | // Depth of each subtree used as tie breaker for trees of equal frequency
575 | that.depth = [];
576 |
577 | var l_buf; // index for literals or lengths */
578 |
579 | // Size of match buffer for literals/lengths. There are 4 reasons for
580 | // limiting lit_bufsize to 64K:
581 | // - frequencies can be kept in 16 bit counters
582 | // - if compression is not successful for the first block, all input
583 | // data is still in the window so we can still emit a stored block even
584 | // when input comes from standard input. (This can also be done for
585 | // all blocks if lit_bufsize is not greater than 32K.)
586 | // - if compression is not successful for a file smaller than 64K, we can
587 | // even emit a stored file instead of a stored block (saving 5 bytes).
588 | // This is applicable only for zip (not gzip or zlib).
589 | // - creating new Huffman trees less frequently may not provide fast
590 | // adaptation to changes in the input data statistics. (Take for
591 | // example a binary file with poorly compressible code followed by
592 | // a highly compressible string table.) Smaller buffer sizes give
593 | // fast adaptation but have of course the overhead of transmitting
594 | // trees more frequently.
595 | // - I can't count above 4
596 | var lit_bufsize;
597 |
598 | var last_lit; // running index in l_buf
599 |
600 | // Buffer for distances. To simplify the code, d_buf and l_buf have
601 | // the same number of elements. To use different lengths, an extra flag
602 | // array would be necessary.
603 |
604 | var d_buf; // index of pendig_buf
605 |
606 | // that.opt_len; // bit length of current block with optimal trees
607 | // that.static_len; // bit length of current block with static trees
608 | var matches; // number of string matches in current block
609 | var last_eob_len; // bit length of EOB code for last block
610 |
611 | // Output buffer. bits are inserted starting at the bottom (least
612 | // significant bits).
613 | var bi_buf;
614 |
615 | // Number of valid bits in bi_buf. All bits above the last valid bit
616 | // are always zero.
617 | var bi_valid;
618 |
619 | // number of codes at each bit length for an optimal tree
620 | that.bl_count = [];
621 |
622 | // heap used to build the Huffman trees
623 | that.heap = [];
624 |
625 | dyn_ltree = [];
626 | dyn_dtree = [];
627 | bl_tree = [];
628 |
629 | function lm_init() {
630 | var i;
631 | window_size = 2 * w_size;
632 |
633 | head[hash_size - 1] = 0;
634 | for (i = 0; i < hash_size - 1; i++) {
635 | head[i] = 0;
636 | }
637 |
638 | // Set the default configuration parameters:
639 | max_lazy_match = config_table[level].max_lazy;
640 | good_match = config_table[level].good_length;
641 | nice_match = config_table[level].nice_length;
642 | max_chain_length = config_table[level].max_chain;
643 |
644 | strstart = 0;
645 | block_start = 0;
646 | lookahead = 0;
647 | match_length = prev_length = MIN_MATCH - 1;
648 | match_available = 0;
649 | ins_h = 0;
650 | }
651 |
652 | function init_block() {
653 | var i;
654 | // Initialize the trees.
655 | for (i = 0; i < L_CODES; i++)
656 | dyn_ltree[i * 2] = 0;
657 | for (i = 0; i < D_CODES; i++)
658 | dyn_dtree[i * 2] = 0;
659 | for (i = 0; i < BL_CODES; i++)
660 | bl_tree[i * 2] = 0;
661 |
662 | dyn_ltree[END_BLOCK * 2] = 1;
663 | that.opt_len = that.static_len = 0;
664 | last_lit = matches = 0;
665 | }
666 |
667 | // Initialize the tree data structures for a new zlib stream.
668 | function tr_init() {
669 |
670 | l_desc.dyn_tree = dyn_ltree;
671 | l_desc.stat_desc = StaticTree.static_l_desc;
672 |
673 | d_desc.dyn_tree = dyn_dtree;
674 | d_desc.stat_desc = StaticTree.static_d_desc;
675 |
676 | bl_desc.dyn_tree = bl_tree;
677 | bl_desc.stat_desc = StaticTree.static_bl_desc;
678 |
679 | bi_buf = 0;
680 | bi_valid = 0;
681 | last_eob_len = 8; // enough lookahead for inflate
682 |
683 | // Initialize the first block of the first file:
684 | init_block();
685 | }
686 |
687 | // Restore the heap property by moving down the tree starting at node k,
688 | // exchanging a node with the smallest of its two sons if necessary,
689 | // stopping
690 | // when the heap property is re-established (each father smaller than its
691 | // two sons).
692 | that.pqdownheap = function(tree, // the tree to restore
693 | k // node to move down
694 | ) {
695 | var heap = that.heap;
696 | var v = heap[k];
697 | var j = k << 1; // left son of k
698 | while (j <= that.heap_len) {
699 | // Set j to the smallest of the two sons:
700 | if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
701 | j++;
702 | }
703 | // Exit if v is smaller than both sons
704 | if (smaller(tree, v, heap[j], that.depth))
705 | break;
706 |
707 | // Exchange v with the smallest son
708 | heap[k] = heap[j];
709 | k = j;
710 | // And continue down the tree, setting j to the left son of k
711 | j <<= 1;
712 | }
713 | heap[k] = v;
714 | };
715 |
716 | // Scan a literal or distance tree to determine the frequencies of the codes
717 | // in the bit length tree.
718 | function scan_tree(tree,// the tree to be scanned
719 | max_code // and its largest code of non zero frequency
720 | ) {
721 | var n; // iterates over all tree elements
722 | var prevlen = -1; // last emitted length
723 | var curlen; // length of current code
724 | var nextlen = tree[0 * 2 + 1]; // length of next code
725 | var count = 0; // repeat count of the current code
726 | var max_count = 7; // max repeat count
727 | var min_count = 4; // min repeat count
728 |
729 | if (nextlen === 0) {
730 | max_count = 138;
731 | min_count = 3;
732 | }
733 | tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
734 |
735 | for (n = 0; n <= max_code; n++) {
736 | curlen = nextlen;
737 | nextlen = tree[(n + 1) * 2 + 1];
738 | if (++count < max_count && curlen == nextlen) {
739 | continue;
740 | } else if (count < min_count) {
741 | bl_tree[curlen * 2] += count;
742 | } else if (curlen !== 0) {
743 | if (curlen != prevlen)
744 | bl_tree[curlen * 2]++;
745 | bl_tree[REP_3_6 * 2]++;
746 | } else if (count <= 10) {
747 | bl_tree[REPZ_3_10 * 2]++;
748 | } else {
749 | bl_tree[REPZ_11_138 * 2]++;
750 | }
751 | count = 0;
752 | prevlen = curlen;
753 | if (nextlen === 0) {
754 | max_count = 138;
755 | min_count = 3;
756 | } else if (curlen == nextlen) {
757 | max_count = 6;
758 | min_count = 3;
759 | } else {
760 | max_count = 7;
761 | min_count = 4;
762 | }
763 | }
764 | }
765 |
766 | // Construct the Huffman tree for the bit lengths and return the index in
767 | // bl_order of the last bit length code to send.
768 | function build_bl_tree() {
769 | var max_blindex; // index of last bit length code of non zero freq
770 |
771 | // Determine the bit length frequencies for literal and distance trees
772 | scan_tree(dyn_ltree, l_desc.max_code);
773 | scan_tree(dyn_dtree, d_desc.max_code);
774 |
775 | // Build the bit length tree:
776 | bl_desc.build_tree(that);
777 | // opt_len now includes the length of the tree representations, except
778 | // the lengths of the bit lengths codes and the 5+5+4 bits for the
779 | // counts.
780 |
781 | // Determine the number of bit length codes to send. The pkzip format
782 | // requires that at least 4 bit length codes be sent. (appnote.txt says
783 | // 3 but the actual value used is 4.)
784 | for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
785 | if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
786 | break;
787 | }
788 | // Update opt_len to include the bit length tree and counts
789 | that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
790 |
791 | return max_blindex;
792 | }
793 |
794 | // Output a byte on the stream.
795 | // IN assertion: there is enough room in pending_buf.
796 | function put_byte(p) {
797 | that.pending_buf[that.pending++] = p;
798 | }
799 |
800 | function put_short(w) {
801 | put_byte(w & 0xff);
802 | put_byte((w >>> 8) & 0xff);
803 | }
804 |
805 | function putShortMSB(b) {
806 | put_byte((b >> 8) & 0xff);
807 | put_byte((b & 0xff) & 0xff);
808 | }
809 |
810 | function send_bits(value, length) {
811 | var val, len = length;
812 | if (bi_valid > Buf_size - len) {
813 | val = value;
814 | // bi_buf |= (val << bi_valid);
815 | bi_buf |= ((val << bi_valid) & 0xffff);
816 | put_short(bi_buf);
817 | bi_buf = val >>> (Buf_size - bi_valid);
818 | bi_valid += len - Buf_size;
819 | } else {
820 | // bi_buf |= (value) << bi_valid;
821 | bi_buf |= (((value) << bi_valid) & 0xffff);
822 | bi_valid += len;
823 | }
824 | }
825 |
826 | function send_code(c, tree) {
827 | var c2 = c * 2;
828 | send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
829 | }
830 |
831 | // Send a literal or distance tree in compressed form, using the codes in
832 | // bl_tree.
833 | function send_tree(tree,// the tree to be sent
834 | max_code // and its largest code of non zero frequency
835 | ) {
836 | var n; // iterates over all tree elements
837 | var prevlen = -1; // last emitted length
838 | var curlen; // length of current code
839 | var nextlen = tree[0 * 2 + 1]; // length of next code
840 | var count = 0; // repeat count of the current code
841 | var max_count = 7; // max repeat count
842 | var min_count = 4; // min repeat count
843 |
844 | if (nextlen === 0) {
845 | max_count = 138;
846 | min_count = 3;
847 | }
848 |
849 | for (n = 0; n <= max_code; n++) {
850 | curlen = nextlen;
851 | nextlen = tree[(n + 1) * 2 + 1];
852 | if (++count < max_count && curlen == nextlen) {
853 | continue;
854 | } else if (count < min_count) {
855 | do {
856 | send_code(curlen, bl_tree);
857 | } while (--count !== 0);
858 | } else if (curlen !== 0) {
859 | if (curlen != prevlen) {
860 | send_code(curlen, bl_tree);
861 | count--;
862 | }
863 | send_code(REP_3_6, bl_tree);
864 | send_bits(count - 3, 2);
865 | } else if (count <= 10) {
866 | send_code(REPZ_3_10, bl_tree);
867 | send_bits(count - 3, 3);
868 | } else {
869 | send_code(REPZ_11_138, bl_tree);
870 | send_bits(count - 11, 7);
871 | }
872 | count = 0;
873 | prevlen = curlen;
874 | if (nextlen === 0) {
875 | max_count = 138;
876 | min_count = 3;
877 | } else if (curlen == nextlen) {
878 | max_count = 6;
879 | min_count = 3;
880 | } else {
881 | max_count = 7;
882 | min_count = 4;
883 | }
884 | }
885 | }
886 |
887 | // Send the header for a block using dynamic Huffman trees: the counts, the
888 | // lengths of the bit length codes, the literal tree and the distance tree.
889 | // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
890 | function send_all_trees(lcodes, dcodes, blcodes) {
891 | var rank; // index in bl_order
892 |
893 | send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
894 | send_bits(dcodes - 1, 5);
895 | send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
896 | for (rank = 0; rank < blcodes; rank++) {
897 | send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
898 | }
899 | send_tree(dyn_ltree, lcodes - 1); // literal tree
900 | send_tree(dyn_dtree, dcodes - 1); // distance tree
901 | }
902 |
903 | // Flush the bit buffer, keeping at most 7 bits in it.
904 | function bi_flush() {
905 | if (bi_valid == 16) {
906 | put_short(bi_buf);
907 | bi_buf = 0;
908 | bi_valid = 0;
909 | } else if (bi_valid >= 8) {
910 | put_byte(bi_buf & 0xff);
911 | bi_buf >>>= 8;
912 | bi_valid -= 8;
913 | }
914 | }
915 |
916 | // Send one empty static block to give enough lookahead for inflate.
917 | // This takes 10 bits, of which 7 may remain in the bit buffer.
918 | // The current inflate code requires 9 bits of lookahead. If the
919 | // last two codes for the previous block (real code plus EOB) were coded
920 | // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
921 | // the last real code. In this case we send two empty static blocks instead
922 | // of one. (There are no problems if the previous block is stored or fixed.)
923 | // To simplify the code, we assume the worst case of last real code encoded
924 | // on one bit only.
925 | function _tr_align() {
926 | send_bits(STATIC_TREES << 1, 3);
927 | send_code(END_BLOCK, StaticTree.static_ltree);
928 |
929 | bi_flush();
930 |
931 | // Of the 10 bits for the empty block, we have already sent
932 | // (10 - bi_valid) bits. The lookahead for the last real code (before
933 | // the EOB of the previous block) was thus at least one plus the length
934 | // of the EOB plus what we have just sent of the empty static block.
935 | if (1 + last_eob_len + 10 - bi_valid < 9) {
936 | send_bits(STATIC_TREES << 1, 3);
937 | send_code(END_BLOCK, StaticTree.static_ltree);
938 | bi_flush();
939 | }
940 | last_eob_len = 7;
941 | }
942 |
943 | // Save the match info and tally the frequency counts. Return true if
944 | // the current block must be flushed.
945 | function _tr_tally(dist, // distance of matched string
946 | lc // match length-MIN_MATCH or unmatched char (if dist==0)
947 | ) {
948 | var out_length, in_length, dcode;
949 | that.pending_buf[d_buf + last_lit * 2] = (dist >>> 8) & 0xff;
950 | that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff;
951 |
952 | that.pending_buf[l_buf + last_lit] = lc & 0xff;
953 | last_lit++;
954 |
955 | if (dist === 0) {
956 | // lc is the unmatched char
957 | dyn_ltree[lc * 2]++;
958 | } else {
959 | matches++;
960 | // Here, lc is the match length - MIN_MATCH
961 | dist--; // dist = match distance - 1
962 | dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
963 | dyn_dtree[Tree.d_code(dist) * 2]++;
964 | }
965 |
966 | if ((last_lit & 0x1fff) === 0 && level > 2) {
967 | // Compute an upper bound for the compressed length
968 | out_length = last_lit * 8;
969 | in_length = strstart - block_start;
970 | for (dcode = 0; dcode < D_CODES; dcode++) {
971 | out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
972 | }
973 | out_length >>>= 3;
974 | if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2))
975 | return true;
976 | }
977 |
978 | return (last_lit == lit_bufsize - 1);
979 | // We avoid equality with lit_bufsize because of wraparound at 64K
980 | // on 16 bit machines and because stored blocks are restricted to
981 | // 64K-1 bytes.
982 | }
983 |
984 | // Send the block data compressed using the given Huffman trees
985 | function compress_block(ltree, dtree) {
986 | var dist; // distance of matched string
987 | var lc; // match length or unmatched char (if dist === 0)
988 | var lx = 0; // running index in l_buf
989 | var code; // the code to send
990 | var extra; // number of extra bits to send
991 |
992 | if (last_lit !== 0) {
993 | do {
994 | dist = ((that.pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (that.pending_buf[d_buf + lx * 2 + 1] & 0xff);
995 | lc = (that.pending_buf[l_buf + lx]) & 0xff;
996 | lx++;
997 |
998 | if (dist === 0) {
999 | send_code(lc, ltree); // send a literal byte
1000 | } else {
1001 | // Here, lc is the match length - MIN_MATCH
1002 | code = Tree._length_code[lc];
1003 |
1004 | send_code(code + LITERALS + 1, ltree); // send the length
1005 | // code
1006 | extra = Tree.extra_lbits[code];
1007 | if (extra !== 0) {
1008 | lc -= Tree.base_length[code];
1009 | send_bits(lc, extra); // send the extra length bits
1010 | }
1011 | dist--; // dist is now the match distance - 1
1012 | code = Tree.d_code(dist);
1013 |
1014 | send_code(code, dtree); // send the distance code
1015 | extra = Tree.extra_dbits[code];
1016 | if (extra !== 0) {
1017 | dist -= Tree.base_dist[code];
1018 | send_bits(dist, extra); // send the extra distance bits
1019 | }
1020 | } // literal or match pair ?
1021 |
1022 | // Check that the overlay between pending_buf and d_buf+l_buf is
1023 | // ok:
1024 | } while (lx < last_lit);
1025 | }
1026 |
1027 | send_code(END_BLOCK, ltree);
1028 | last_eob_len = ltree[END_BLOCK * 2 + 1];
1029 | }
1030 |
1031 | // Flush the bit buffer and align the output on a byte boundary
1032 | function bi_windup() {
1033 | if (bi_valid > 8) {
1034 | put_short(bi_buf);
1035 | } else if (bi_valid > 0) {
1036 | put_byte(bi_buf & 0xff);
1037 | }
1038 | bi_buf = 0;
1039 | bi_valid = 0;
1040 | }
1041 |
1042 | // Copy a stored block, storing first the length and its
1043 | // one's complement if requested.
1044 | function copy_block(buf, // the input data
1045 | len, // its length
1046 | header // true if block header must be written
1047 | ) {
1048 | bi_windup(); // align on byte boundary
1049 | last_eob_len = 8; // enough lookahead for inflate
1050 |
1051 | if (header) {
1052 | put_short(len);
1053 | put_short(~len);
1054 | }
1055 |
1056 | that.pending_buf.set(window.subarray(buf, buf + len), that.pending);
1057 | that.pending += len;
1058 | }
1059 |
1060 | // Send a stored block
1061 | function _tr_stored_block(buf, // input block
1062 | stored_len, // length of input block
1063 | eof // true if this is the last block for a file
1064 | ) {
1065 | send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
1066 | copy_block(buf, stored_len, true); // with header
1067 | }
1068 |
1069 | // Determine the best encoding for the current block: dynamic trees, static
1070 | // trees or store, and output the encoded block to the zip file.
1071 | function _tr_flush_block(buf, // input block, or NULL if too old
1072 | stored_len, // length of input block
1073 | eof // true if this is the last block for a file
1074 | ) {
1075 | var opt_lenb, static_lenb;// opt_len and static_len in bytes
1076 | var max_blindex = 0; // index of last bit length code of non zero freq
1077 |
1078 | // Build the Huffman trees unless a stored block is forced
1079 | if (level > 0) {
1080 | // Construct the literal and distance trees
1081 | l_desc.build_tree(that);
1082 |
1083 | d_desc.build_tree(that);
1084 |
1085 | // At this point, opt_len and static_len are the total bit lengths
1086 | // of
1087 | // the compressed block data, excluding the tree representations.
1088 |
1089 | // Build the bit length tree for the above two trees, and get the
1090 | // index
1091 | // in bl_order of the last bit length code to send.
1092 | max_blindex = build_bl_tree();
1093 |
1094 | // Determine the best encoding. Compute first the block length in
1095 | // bytes
1096 | opt_lenb = (that.opt_len + 3 + 7) >>> 3;
1097 | static_lenb = (that.static_len + 3 + 7) >>> 3;
1098 |
1099 | if (static_lenb <= opt_lenb)
1100 | opt_lenb = static_lenb;
1101 | } else {
1102 | opt_lenb = static_lenb = stored_len + 5; // force a stored block
1103 | }
1104 |
1105 | if ((stored_len + 4 <= opt_lenb) && buf != -1) {
1106 | // 4: two words for the lengths
1107 | // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
1108 | // Otherwise we can't have processed more than WSIZE input bytes
1109 | // since
1110 | // the last block flush, because compression would have been
1111 | // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
1112 | // transform a block into a stored block.
1113 | _tr_stored_block(buf, stored_len, eof);
1114 | } else if (static_lenb == opt_lenb) {
1115 | send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
1116 | compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
1117 | } else {
1118 | send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
1119 | send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
1120 | compress_block(dyn_ltree, dyn_dtree);
1121 | }
1122 |
1123 | // The above check is made mod 2^32, for files larger than 512 MB
1124 | // and uLong implemented on 32 bits.
1125 |
1126 | init_block();
1127 |
1128 | if (eof) {
1129 | bi_windup();
1130 | }
1131 | }
1132 |
1133 | function flush_block_only(eof) {
1134 | _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
1135 | block_start = strstart;
1136 | strm.flush_pending();
1137 | }
1138 |
1139 | // Fill the window when the lookahead becomes insufficient.
1140 | // Updates strstart and lookahead.
1141 | //
1142 | // IN assertion: lookahead < MIN_LOOKAHEAD
1143 | // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1144 | // At least one byte has been read, or avail_in === 0; reads are
1145 | // performed for at least two bytes (required for the zip translate_eol
1146 | // option -- not supported here).
1147 | function fill_window() {
1148 | var n, m;
1149 | var p;
1150 | var more; // Amount of free space at the end of the window.
1151 |
1152 | do {
1153 | more = (window_size - lookahead - strstart);
1154 |
1155 | // Deal with !@#$% 64K limit:
1156 | if (more === 0 && strstart === 0 && lookahead === 0) {
1157 | more = w_size;
1158 | } else if (more == -1) {
1159 | // Very unlikely, but possible on 16 bit machine if strstart ==
1160 | // 0
1161 | // and lookahead == 1 (input done one byte at time)
1162 | more--;
1163 |
1164 | // If the window is almost full and there is insufficient
1165 | // lookahead,
1166 | // move the upper half to the lower one to make room in the
1167 | // upper half.
1168 | } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
1169 | window.set(window.subarray(w_size, w_size + w_size), 0);
1170 |
1171 | match_start -= w_size;
1172 | strstart -= w_size; // we now have strstart >= MAX_DIST
1173 | block_start -= w_size;
1174 |
1175 | // Slide the hash table (could be avoided with 32 bit values
1176 | // at the expense of memory usage). We slide even when level ==
1177 | // 0
1178 | // to keep the hash table consistent if we switch back to level
1179 | // > 0
1180 | // later. (Using level 0 permanently is not an optimal usage of
1181 | // zlib, so we don't care about this pathological case.)
1182 |
1183 | n = hash_size;
1184 | p = n;
1185 | do {
1186 | m = (head[--p] & 0xffff);
1187 | head[p] = (m >= w_size ? m - w_size : 0);
1188 | } while (--n !== 0);
1189 |
1190 | n = w_size;
1191 | p = n;
1192 | do {
1193 | m = (prev[--p] & 0xffff);
1194 | prev[p] = (m >= w_size ? m - w_size : 0);
1195 | // If n is not on any hash chain, prev[n] is garbage but
1196 | // its value will never be used.
1197 | } while (--n !== 0);
1198 | more += w_size;
1199 | }
1200 |
1201 | if (strm.avail_in === 0)
1202 | return;
1203 |
1204 | // If there was no sliding:
1205 | // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1206 | // more == window_size - lookahead - strstart
1207 | // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1208 | // => more >= window_size - 2*WSIZE + 2
1209 | // In the BIG_MEM or MMAP case (not yet supported),
1210 | // window_size == input_size + MIN_LOOKAHEAD &&
1211 | // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1212 | // Otherwise, window_size == 2*WSIZE so more >= 2.
1213 | // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1214 |
1215 | n = strm.read_buf(window, strstart + lookahead, more);
1216 | lookahead += n;
1217 |
1218 | // Initialize the hash value now that we have some input:
1219 | if (lookahead >= MIN_MATCH) {
1220 | ins_h = window[strstart] & 0xff;
1221 | ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
1222 | }
1223 | // If the whole input has less than MIN_MATCH bytes, ins_h is
1224 | // garbage,
1225 | // but this is not important since only literal bytes will be
1226 | // emitted.
1227 | } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
1228 | }
1229 |
1230 | // Copy without compression as much as possible from the input stream,
1231 | // return
1232 | // the current block state.
1233 | // This function does not insert new strings in the dictionary since
1234 | // uncompressible data is probably not useful. This function is used
1235 | // only for the level=0 compression option.
1236 | // NOTE: this function should be optimized to avoid extra copying from
1237 | // window to pending_buf.
1238 | function deflate_stored(flush) {
1239 | // Stored blocks are limited to 0xffff bytes, pending_buf is limited
1240 | // to pending_buf_size, and each stored block has a 5 byte header:
1241 |
1242 | var max_block_size = 0xffff;
1243 | var max_start;
1244 |
1245 | if (max_block_size > pending_buf_size - 5) {
1246 | max_block_size = pending_buf_size - 5;
1247 | }
1248 |
1249 | // Copy as much as possible from input to output:
1250 | while (true) {
1251 | // Fill the window as much as possible:
1252 | if (lookahead <= 1) {
1253 | fill_window();
1254 | if (lookahead === 0 && flush == Z_NO_FLUSH)
1255 | return NeedMore;
1256 | if (lookahead === 0)
1257 | break; // flush the current block
1258 | }
1259 |
1260 | strstart += lookahead;
1261 | lookahead = 0;
1262 |
1263 | // Emit a stored block if pending_buf will be full:
1264 | max_start = block_start + max_block_size;
1265 | if (strstart === 0 || strstart >= max_start) {
1266 | // strstart === 0 is possible when wraparound on 16-bit machine
1267 | lookahead = (strstart - max_start);
1268 | strstart = max_start;
1269 |
1270 | flush_block_only(false);
1271 | if (strm.avail_out === 0)
1272 | return NeedMore;
1273 |
1274 | }
1275 |
1276 | // Flush if we may have to slide, otherwise block_start may become
1277 | // negative and the data will be gone:
1278 | if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
1279 | flush_block_only(false);
1280 | if (strm.avail_out === 0)
1281 | return NeedMore;
1282 | }
1283 | }
1284 |
1285 | flush_block_only(flush == Z_FINISH);
1286 | if (strm.avail_out === 0)
1287 | return (flush == Z_FINISH) ? FinishStarted : NeedMore;
1288 |
1289 | return flush == Z_FINISH ? FinishDone : BlockDone;
1290 | }
1291 |
1292 | function longest_match(cur_match) {
1293 | var chain_length = max_chain_length; // max hash chain length
1294 | var scan = strstart; // current string
1295 | var match; // matched string
1296 | var len; // length of current match
1297 | var best_len = prev_length; // best match length so far
1298 | var limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
1299 | var _nice_match = nice_match;
1300 |
1301 | // Stop when cur_match becomes <= limit. To simplify the code,
1302 | // we prevent matches with the string of window index 0.
1303 |
1304 | var wmask = w_mask;
1305 |
1306 | var strend = strstart + MAX_MATCH;
1307 | var scan_end1 = window[scan + best_len - 1];
1308 | var scan_end = window[scan + best_len];
1309 |
1310 | // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
1311 | // 16.
1312 | // It is easy to get rid of this optimization if necessary.
1313 |
1314 | // Do not waste too much time if we already have a good match:
1315 | if (prev_length >= good_match) {
1316 | chain_length >>= 2;
1317 | }
1318 |
1319 | // Do not look for matches beyond the end of the input. This is
1320 | // necessary
1321 | // to make deflate deterministic.
1322 | if (_nice_match > lookahead)
1323 | _nice_match = lookahead;
1324 |
1325 | do {
1326 | match = cur_match;
1327 |
1328 | // Skip to next match if the match length cannot increase
1329 | // or if the match length is less than 2:
1330 | if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan]
1331 | || window[++match] != window[scan + 1])
1332 | continue;
1333 |
1334 | // The check at best_len-1 can be removed because it will be made
1335 | // again later. (This heuristic is not always a win.)
1336 | // It is not necessary to compare scan[2] and match[2] since they
1337 | // are always equal when the other bytes match, given that
1338 | // the hash keys are equal and that HASH_BITS >= 8.
1339 | scan += 2;
1340 | match++;
1341 |
1342 | // We check for insufficient lookahead only every 8th comparison;
1343 | // the 256th check will be made at strstart+258.
1344 | do {
1345 | } while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
1346 | && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
1347 | && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
1348 |
1349 | len = MAX_MATCH - (strend - scan);
1350 | scan = strend - MAX_MATCH;
1351 |
1352 | if (len > best_len) {
1353 | match_start = cur_match;
1354 | best_len = len;
1355 | if (len >= _nice_match)
1356 | break;
1357 | scan_end1 = window[scan + best_len - 1];
1358 | scan_end = window[scan + best_len];
1359 | }
1360 |
1361 | } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0);
1362 |
1363 | if (best_len <= lookahead)
1364 | return best_len;
1365 | return lookahead;
1366 | }
1367 |
1368 | // Compress as much as possible from the input stream, return the current
1369 | // block state.
1370 | // This function does not perform lazy evaluation of matches and inserts
1371 | // new strings in the dictionary only for unmatched strings or for short
1372 | // matches. It is used only for the fast compression options.
1373 | function deflate_fast(flush) {
1374 | // short hash_head = 0; // head of the hash chain
1375 | var hash_head = 0; // head of the hash chain
1376 | var bflush; // set if current block must be flushed
1377 |
1378 | while (true) {
1379 | // Make sure that we always have enough lookahead, except
1380 | // at the end of the input file. We need MAX_MATCH bytes
1381 | // for the next match, plus MIN_MATCH bytes to insert the
1382 | // string following the next match.
1383 | if (lookahead < MIN_LOOKAHEAD) {
1384 | fill_window();
1385 | if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1386 | return NeedMore;
1387 | }
1388 | if (lookahead === 0)
1389 | break; // flush the current block
1390 | }
1391 |
1392 | // Insert the string window[strstart .. strstart+2] in the
1393 | // dictionary, and set hash_head to the head of the hash chain:
1394 | if (lookahead >= MIN_MATCH) {
1395 | ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
1396 |
1397 | // prev[strstart&w_mask]=hash_head=head[ins_h];
1398 | hash_head = (head[ins_h] & 0xffff);
1399 | prev[strstart & w_mask] = head[ins_h];
1400 | head[ins_h] = strstart;
1401 | }
1402 |
1403 | // Find the longest match, discarding those <= prev_length.
1404 | // At this point we have always match_length < MIN_MATCH
1405 |
1406 | if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
1407 | // To simplify the code, we prevent matches with the string
1408 | // of window index 0 (in particular we have to avoid a match
1409 | // of the string with itself at the start of the input file).
1410 | if (strategy != Z_HUFFMAN_ONLY) {
1411 | match_length = longest_match(hash_head);
1412 | }
1413 | // longest_match() sets match_start
1414 | }
1415 | if (match_length >= MIN_MATCH) {
1416 | // check_match(strstart, match_start, match_length);
1417 |
1418 | bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
1419 |
1420 | lookahead -= match_length;
1421 |
1422 | // Insert new strings in the hash table only if the match length
1423 | // is not too large. This saves time but degrades compression.
1424 | if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
1425 | match_length--; // string at strstart already in hash table
1426 | do {
1427 | strstart++;
1428 |
1429 | ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
1430 | // prev[strstart&w_mask]=hash_head=head[ins_h];
1431 | hash_head = (head[ins_h] & 0xffff);
1432 | prev[strstart & w_mask] = head[ins_h];
1433 | head[ins_h] = strstart;
1434 |
1435 | // strstart never exceeds WSIZE-MAX_MATCH, so there are
1436 | // always MIN_MATCH bytes ahead.
1437 | } while (--match_length !== 0);
1438 | strstart++;
1439 | } else {
1440 | strstart += match_length;
1441 | match_length = 0;
1442 | ins_h = window[strstart] & 0xff;
1443 |
1444 | ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
1445 | // If lookahead < MIN_MATCH, ins_h is garbage, but it does
1446 | // not
1447 | // matter since it will be recomputed at next deflate call.
1448 | }
1449 | } else {
1450 | // No match, output a literal byte
1451 |
1452 | bflush = _tr_tally(0, window[strstart] & 0xff);
1453 | lookahead--;
1454 | strstart++;
1455 | }
1456 | if (bflush) {
1457 |
1458 | flush_block_only(false);
1459 | if (strm.avail_out === 0)
1460 | return NeedMore;
1461 | }
1462 | }
1463 |
1464 | flush_block_only(flush == Z_FINISH);
1465 | if (strm.avail_out === 0) {
1466 | if (flush == Z_FINISH)
1467 | return FinishStarted;
1468 | else
1469 | return NeedMore;
1470 | }
1471 | return flush == Z_FINISH ? FinishDone : BlockDone;
1472 | }
1473 |
1474 | // Same as above, but achieves better compression. We use a lazy
1475 | // evaluation for matches: a match is finally adopted only if there is
1476 | // no better match at the next window position.
1477 | function deflate_slow(flush) {
1478 | // short hash_head = 0; // head of hash chain
1479 | var hash_head = 0; // head of hash chain
1480 | var bflush; // set if current block must be flushed
1481 | var max_insert;
1482 |
1483 | // Process the input block.
1484 | while (true) {
1485 | // Make sure that we always have enough lookahead, except
1486 | // at the end of the input file. We need MAX_MATCH bytes
1487 | // for the next match, plus MIN_MATCH bytes to insert the
1488 | // string following the next match.
1489 |
1490 | if (lookahead < MIN_LOOKAHEAD) {
1491 | fill_window();
1492 | if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1493 | return NeedMore;
1494 | }
1495 | if (lookahead === 0)
1496 | break; // flush the current block
1497 | }
1498 |
1499 | // Insert the string window[strstart .. strstart+2] in the
1500 | // dictionary, and set hash_head to the head of the hash chain:
1501 |
1502 | if (lookahead >= MIN_MATCH) {
1503 | ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
1504 | // prev[strstart&w_mask]=hash_head=head[ins_h];
1505 | hash_head = (head[ins_h] & 0xffff);
1506 | prev[strstart & w_mask] = head[ins_h];
1507 | head[ins_h] = strstart;
1508 | }
1509 |
1510 | // Find the longest match, discarding those <= prev_length.
1511 | prev_length = match_length;
1512 | prev_match = match_start;
1513 | match_length = MIN_MATCH - 1;
1514 |
1515 | if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
1516 | // To simplify the code, we prevent matches with the string
1517 | // of window index 0 (in particular we have to avoid a match
1518 | // of the string with itself at the start of the input file).
1519 |
1520 | if (strategy != Z_HUFFMAN_ONLY) {
1521 | match_length = longest_match(hash_head);
1522 | }
1523 | // longest_match() sets match_start
1524 |
1525 | if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {
1526 |
1527 | // If prev_match is also MIN_MATCH, match_start is garbage
1528 | // but we will ignore the current match anyway.
1529 | match_length = MIN_MATCH - 1;
1530 | }
1531 | }
1532 |
1533 | // If there was a match at the previous step and the current
1534 | // match is not better, output the previous match:
1535 | if (prev_length >= MIN_MATCH && match_length <= prev_length) {
1536 | max_insert = strstart + lookahead - MIN_MATCH;
1537 | // Do not insert strings in hash table beyond this.
1538 |
1539 | // check_match(strstart-1, prev_match, prev_length);
1540 |
1541 | bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
1542 |
1543 | // Insert in hash table all strings up to the end of the match.
1544 | // strstart-1 and strstart are already inserted. If there is not
1545 | // enough lookahead, the last two strings are not inserted in
1546 | // the hash table.
1547 | lookahead -= prev_length - 1;
1548 | prev_length -= 2;
1549 | do {
1550 | if (++strstart <= max_insert) {
1551 | ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
1552 | // prev[strstart&w_mask]=hash_head=head[ins_h];
1553 | hash_head = (head[ins_h] & 0xffff);
1554 | prev[strstart & w_mask] = head[ins_h];
1555 | head[ins_h] = strstart;
1556 | }
1557 | } while (--prev_length !== 0);
1558 | match_available = 0;
1559 | match_length = MIN_MATCH - 1;
1560 | strstart++;
1561 |
1562 | if (bflush) {
1563 | flush_block_only(false);
1564 | if (strm.avail_out === 0)
1565 | return NeedMore;
1566 | }
1567 | } else if (match_available !== 0) {
1568 |
1569 | // If there was no match at the previous position, output a
1570 | // single literal. If there was a match but the current match
1571 | // is longer, truncate the previous match to a single literal.
1572 |
1573 | bflush = _tr_tally(0, window[strstart - 1] & 0xff);
1574 |
1575 | if (bflush) {
1576 | flush_block_only(false);
1577 | }
1578 | strstart++;
1579 | lookahead--;
1580 | if (strm.avail_out === 0)
1581 | return NeedMore;
1582 | } else {
1583 | // There is no previous match to compare with, wait for
1584 | // the next step to decide.
1585 |
1586 | match_available = 1;
1587 | strstart++;
1588 | lookahead--;
1589 | }
1590 | }
1591 |
1592 | if (match_available !== 0) {
1593 | bflush = _tr_tally(0, window[strstart - 1] & 0xff);
1594 | match_available = 0;
1595 | }
1596 | flush_block_only(flush == Z_FINISH);
1597 |
1598 | if (strm.avail_out === 0) {
1599 | if (flush == Z_FINISH)
1600 | return FinishStarted;
1601 | else
1602 | return NeedMore;
1603 | }
1604 |
1605 | return flush == Z_FINISH ? FinishDone : BlockDone;
1606 | }
1607 |
1608 | function deflateReset(strm) {
1609 | strm.total_in = strm.total_out = 0;
1610 | strm.msg = null; //
1611 |
1612 | that.pending = 0;
1613 | that.pending_out = 0;
1614 |
1615 | status = BUSY_STATE;
1616 |
1617 | last_flush = Z_NO_FLUSH;
1618 |
1619 | tr_init();
1620 | lm_init();
1621 | return Z_OK;
1622 | }
1623 |
1624 | that.deflateInit = function(strm, _level, bits, _method, memLevel, _strategy) {
1625 | if (!_method)
1626 | _method = Z_DEFLATED;
1627 | if (!memLevel)
1628 | memLevel = DEF_MEM_LEVEL;
1629 | if (!_strategy)
1630 | _strategy = Z_DEFAULT_STRATEGY;
1631 |
1632 | // byte[] my_version=ZLIB_VERSION;
1633 |
1634 | //
1635 | // if (!version || version[0] != my_version[0]
1636 | // || stream_size != sizeof(z_stream)) {
1637 | // return Z_VERSION_ERROR;
1638 | // }
1639 |
1640 | strm.msg = null;
1641 |
1642 | if (_level == Z_DEFAULT_COMPRESSION)
1643 | _level = 6;
1644 |
1645 | if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0
1646 | || _strategy > Z_HUFFMAN_ONLY) {
1647 | return Z_STREAM_ERROR;
1648 | }
1649 |
1650 | strm.dstate = that;
1651 |
1652 | w_bits = bits;
1653 | w_size = 1 << w_bits;
1654 | w_mask = w_size - 1;
1655 |
1656 | hash_bits = memLevel + 7;
1657 | hash_size = 1 << hash_bits;
1658 | hash_mask = hash_size - 1;
1659 | hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
1660 |
1661 | window = new Uint8Array(w_size * 2);
1662 | prev = [];
1663 | head = [];
1664 |
1665 | lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
1666 |
1667 | // We overlay pending_buf and d_buf+l_buf. This works since the average
1668 | // output size for (length,distance) codes is <= 24 bits.
1669 | that.pending_buf = new Uint8Array(lit_bufsize * 4);
1670 | pending_buf_size = lit_bufsize * 4;
1671 |
1672 | d_buf = Math.floor(lit_bufsize / 2);
1673 | l_buf = (1 + 2) * lit_bufsize;
1674 |
1675 | level = _level;
1676 |
1677 | strategy = _strategy;
1678 | method = _method & 0xff;
1679 |
1680 | return deflateReset(strm);
1681 | };
1682 |
1683 | that.deflateEnd = function() {
1684 | if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
1685 | return Z_STREAM_ERROR;
1686 | }
1687 | // Deallocate in reverse order of allocations:
1688 | that.pending_buf = null;
1689 | head = null;
1690 | prev = null;
1691 | window = null;
1692 | // free
1693 | that.dstate = null;
1694 | return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1695 | };
1696 |
1697 | that.deflateParams = function(strm, _level, _strategy) {
1698 | var err = Z_OK;
1699 |
1700 | if (_level == Z_DEFAULT_COMPRESSION) {
1701 | _level = 6;
1702 | }
1703 | if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
1704 | return Z_STREAM_ERROR;
1705 | }
1706 |
1707 | if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
1708 | // Flush the last buffer:
1709 | err = strm.deflate(Z_PARTIAL_FLUSH);
1710 | }
1711 |
1712 | if (level != _level) {
1713 | level = _level;
1714 | max_lazy_match = config_table[level].max_lazy;
1715 | good_match = config_table[level].good_length;
1716 | nice_match = config_table[level].nice_length;
1717 | max_chain_length = config_table[level].max_chain;
1718 | }
1719 | strategy = _strategy;
1720 | return err;
1721 | };
1722 |
1723 | that.deflateSetDictionary = function(strm, dictionary, dictLength) {
1724 | var length = dictLength;
1725 | var n, index = 0;
1726 |
1727 | if (!dictionary || status != INIT_STATE)
1728 | return Z_STREAM_ERROR;
1729 |
1730 | if (length < MIN_MATCH)
1731 | return Z_OK;
1732 | if (length > w_size - MIN_LOOKAHEAD) {
1733 | length = w_size - MIN_LOOKAHEAD;
1734 | index = dictLength - length; // use the tail of the dictionary
1735 | }
1736 | window.set(dictionary.subarray(index, index + length), 0);
1737 |
1738 | strstart = length;
1739 | block_start = length;
1740 |
1741 | // Insert all strings in the hash table (except for the last two bytes).
1742 | // s->lookahead stays null, so s->ins_h will be recomputed at the next
1743 | // call of fill_window.
1744 |
1745 | ins_h = window[0] & 0xff;
1746 | ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
1747 |
1748 | for (n = 0; n <= length - MIN_MATCH; n++) {
1749 | ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
1750 | prev[n & w_mask] = head[ins_h];
1751 | head[ins_h] = n;
1752 | }
1753 | return Z_OK;
1754 | };
1755 |
1756 | that.deflate = function(_strm, flush) {
1757 | var i, header, level_flags, old_flush, bstate;
1758 |
1759 | if (flush > Z_FINISH || flush < 0) {
1760 | return Z_STREAM_ERROR;
1761 | }
1762 |
1763 | if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH)) {
1764 | _strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
1765 | return Z_STREAM_ERROR;
1766 | }
1767 | if (_strm.avail_out === 0) {
1768 | _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
1769 | return Z_BUF_ERROR;
1770 | }
1771 |
1772 | strm = _strm; // just in case
1773 | old_flush = last_flush;
1774 | last_flush = flush;
1775 |
1776 | // Write the zlib header
1777 | if (status == INIT_STATE) {
1778 | header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
1779 | level_flags = ((level - 1) & 0xff) >> 1;
1780 |
1781 | if (level_flags > 3)
1782 | level_flags = 3;
1783 | header |= (level_flags << 6);
1784 | if (strstart !== 0)
1785 | header |= PRESET_DICT;
1786 | header += 31 - (header % 31);
1787 |
1788 | status = BUSY_STATE;
1789 | putShortMSB(header);
1790 | }
1791 |
1792 | // Flush as much pending output as possible
1793 | if (that.pending !== 0) {
1794 | strm.flush_pending();
1795 | if (strm.avail_out === 0) {
1796 | // console.log(" avail_out==0");
1797 | // Since avail_out is 0, deflate will be called again with
1798 | // more output space, but possibly with both pending and
1799 | // avail_in equal to zero. There won't be anything to do,
1800 | // but this is not an error situation so make sure we
1801 | // return OK instead of BUF_ERROR at next call of deflate:
1802 | last_flush = -1;
1803 | return Z_OK;
1804 | }
1805 |
1806 | // Make sure there is something to do and avoid duplicate
1807 | // consecutive
1808 | // flushes. For repeated and useless calls with Z_FINISH, we keep
1809 | // returning Z_STREAM_END instead of Z_BUFF_ERROR.
1810 | } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
1811 | strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
1812 | return Z_BUF_ERROR;
1813 | }
1814 |
1815 | // User must not provide more input after the first FINISH:
1816 | if (status == FINISH_STATE && strm.avail_in !== 0) {
1817 | _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
1818 | return Z_BUF_ERROR;
1819 | }
1820 |
1821 | // Start a new block or continue the current one.
1822 | if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
1823 | bstate = -1;
1824 | switch (config_table[level].func) {
1825 | case STORED:
1826 | bstate = deflate_stored(flush);
1827 | break;
1828 | case FAST:
1829 | bstate = deflate_fast(flush);
1830 | break;
1831 | case SLOW:
1832 | bstate = deflate_slow(flush);
1833 | break;
1834 | default:
1835 | }
1836 |
1837 | if (bstate == FinishStarted || bstate == FinishDone) {
1838 | status = FINISH_STATE;
1839 | }
1840 | if (bstate == NeedMore || bstate == FinishStarted) {
1841 | if (strm.avail_out === 0) {
1842 | last_flush = -1; // avoid BUF_ERROR next call, see above
1843 | }
1844 | return Z_OK;
1845 | // If flush != Z_NO_FLUSH && avail_out === 0, the next call
1846 | // of deflate should use the same flush parameter to make sure
1847 | // that the flush is complete. So we don't have to output an
1848 | // empty block here, this will be done at next call. This also
1849 | // ensures that for a very small output buffer, we emit at most
1850 | // one empty block.
1851 | }
1852 |
1853 | if (bstate == BlockDone) {
1854 | if (flush == Z_PARTIAL_FLUSH) {
1855 | _tr_align();
1856 | } else { // FULL_FLUSH or SYNC_FLUSH
1857 | _tr_stored_block(0, 0, false);
1858 | // For a full flush, this empty block will be recognized
1859 | // as a special marker by inflate_sync().
1860 | if (flush == Z_FULL_FLUSH) {
1861 | // state.head[s.hash_size-1]=0;
1862 | for (i = 0; i < hash_size/*-1*/; i++)
1863 | // forget history
1864 | head[i] = 0;
1865 | }
1866 | }
1867 | strm.flush_pending();
1868 | if (strm.avail_out === 0) {
1869 | last_flush = -1; // avoid BUF_ERROR at next call, see above
1870 | return Z_OK;
1871 | }
1872 | }
1873 | }
1874 |
1875 | if (flush != Z_FINISH)
1876 | return Z_OK;
1877 | return Z_STREAM_END;
1878 | };
1879 | }
1880 |
1881 | // ZStream
1882 |
1883 | function ZStream() {
1884 | var that = this;
1885 | that.next_in_index = 0;
1886 | that.next_out_index = 0;
1887 | // that.next_in; // next input byte
1888 | that.avail_in = 0; // number of bytes available at next_in
1889 | that.total_in = 0; // total nb of input bytes read so far
1890 | // that.next_out; // next output byte should be put there
1891 | that.avail_out = 0; // remaining free space at next_out
1892 | that.total_out = 0; // total nb of bytes output so far
1893 | // that.msg;
1894 | // that.dstate;
1895 | }
1896 |
1897 | ZStream.prototype = {
1898 | deflateInit : function(level, bits) {
1899 | var that = this;
1900 | that.dstate = new Deflate();
1901 | if (!bits)
1902 | bits = MAX_BITS;
1903 | return that.dstate.deflateInit(that, level, bits);
1904 | },
1905 |
1906 | deflate : function(flush) {
1907 | var that = this;
1908 | if (!that.dstate) {
1909 | return Z_STREAM_ERROR;
1910 | }
1911 | return that.dstate.deflate(that, flush);
1912 | },
1913 |
1914 | deflateEnd : function() {
1915 | var that = this;
1916 | if (!that.dstate)
1917 | return Z_STREAM_ERROR;
1918 | var ret = that.dstate.deflateEnd();
1919 | that.dstate = null;
1920 | return ret;
1921 | },
1922 |
1923 | deflateParams : function(level, strategy) {
1924 | var that = this;
1925 | if (!that.dstate)
1926 | return Z_STREAM_ERROR;
1927 | return that.dstate.deflateParams(that, level, strategy);
1928 | },
1929 |
1930 | deflateSetDictionary : function(dictionary, dictLength) {
1931 | var that = this;
1932 | if (!that.dstate)
1933 | return Z_STREAM_ERROR;
1934 | return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
1935 | },
1936 |
1937 | // Read a new buffer from the current input stream, update the
1938 | // total number of bytes read. All deflate() input goes through
1939 | // this function so some applications may wish to modify it to avoid
1940 | // allocating a large strm->next_in buffer and copying from it.
1941 | // (See also flush_pending()).
1942 | read_buf : function(buf, start, size) {
1943 | var that = this;
1944 | var len = that.avail_in;
1945 | if (len > size)
1946 | len = size;
1947 | if (len === 0)
1948 | return 0;
1949 | that.avail_in -= len;
1950 | buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
1951 | that.next_in_index += len;
1952 | that.total_in += len;
1953 | return len;
1954 | },
1955 |
1956 | // Flush as much pending output as possible. All deflate() output goes
1957 | // through this function so some applications may wish to modify it
1958 | // to avoid allocating a large strm->next_out buffer and copying into it.
1959 | // (See also read_buf()).
1960 | flush_pending : function() {
1961 | var that = this;
1962 | var len = that.dstate.pending;
1963 |
1964 | if (len > that.avail_out)
1965 | len = that.avail_out;
1966 | if (len === 0)
1967 | return;
1968 |
1969 | // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
1970 | // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
1971 | // len)) {
1972 | // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
1973 | // that.next_out_index + ", " + len);
1974 | // console.log("avail_out=" + that.avail_out);
1975 | // }
1976 |
1977 | that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
1978 |
1979 | that.next_out_index += len;
1980 | that.dstate.pending_out += len;
1981 | that.total_out += len;
1982 | that.avail_out -= len;
1983 | that.dstate.pending -= len;
1984 | if (that.dstate.pending === 0) {
1985 | that.dstate.pending_out = 0;
1986 | }
1987 | }
1988 | };
1989 |
1990 | // Deflater
1991 |
1992 | function Deflater(options) {
1993 | var that = this;
1994 | var z = new ZStream();
1995 | var bufsize = 512;
1996 | var flush = Z_NO_FLUSH;
1997 | var buf = new Uint8Array(bufsize);
1998 | var level = options ? options.level : Z_DEFAULT_COMPRESSION;
1999 | if (typeof level == "undefined")
2000 | level = Z_DEFAULT_COMPRESSION;
2001 | z.deflateInit(level);
2002 | z.next_out = buf;
2003 |
2004 | that.append = function(data, onprogress) {
2005 | var err, buffers = [], lastIndex = 0, bufferIndex = 0, bufferSize = 0, array;
2006 | if (!data.length)
2007 | return;
2008 | z.next_in_index = 0;
2009 | z.next_in = data;
2010 | z.avail_in = data.length;
2011 | do {
2012 | z.next_out_index = 0;
2013 | z.avail_out = bufsize;
2014 | err = z.deflate(flush);
2015 | if (err != Z_OK)
2016 | throw new Error("deflating: " + z.msg);
2017 | if (z.next_out_index)
2018 | if (z.next_out_index == bufsize)
2019 | buffers.push(new Uint8Array(buf));
2020 | else
2021 | buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
2022 | bufferSize += z.next_out_index;
2023 | if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
2024 | onprogress(z.next_in_index);
2025 | lastIndex = z.next_in_index;
2026 | }
2027 | } while (z.avail_in > 0 || z.avail_out === 0);
2028 | array = new Uint8Array(bufferSize);
2029 | buffers.forEach(function(chunk) {
2030 | array.set(chunk, bufferIndex);
2031 | bufferIndex += chunk.length;
2032 | });
2033 | return array;
2034 | };
2035 | that.flush = function() {
2036 | var err, buffers = [], bufferIndex = 0, bufferSize = 0, array;
2037 | do {
2038 | z.next_out_index = 0;
2039 | z.avail_out = bufsize;
2040 | err = z.deflate(Z_FINISH);
2041 | if (err != Z_STREAM_END && err != Z_OK)
2042 | throw new Error("deflating: " + z.msg);
2043 | if (bufsize - z.avail_out > 0)
2044 | buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
2045 | bufferSize += z.next_out_index;
2046 | } while (z.avail_in > 0 || z.avail_out === 0);
2047 | z.deflateEnd();
2048 | array = new Uint8Array(bufferSize);
2049 | buffers.forEach(function(chunk) {
2050 | array.set(chunk, bufferIndex);
2051 | bufferIndex += chunk.length;
2052 | });
2053 | return array;
2054 | };
2055 | }
2056 |
2057 | // 'zip' may not be defined in z-worker and some tests
2058 | var env = global.zip || global;
2059 | env.Deflater = env._jzlib_Deflater = Deflater;
2060 | })(this);
2061 |
--------------------------------------------------------------------------------