You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3978 lines
130 KiB

1 year ago
  1. /*! pako 2.0.4 https://github.com/nodeca/pako @license (MIT AND Zlib) */
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.pako = {}));
  6. }(this, (function (exports) { 'use strict';
  7. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9. //
  10. // This software is provided 'as-is', without any express or implied
  11. // warranty. In no event will the authors be held liable for any damages
  12. // arising from the use of this software.
  13. //
  14. // Permission is granted to anyone to use this software for any purpose,
  15. // including commercial applications, and to alter it and redistribute it
  16. // freely, subject to the following restrictions:
  17. //
  18. // 1. The origin of this software must not be misrepresented; you must not
  19. // claim that you wrote the original software. If you use this software
  20. // in a product, an acknowledgment in the product documentation would be
  21. // appreciated but is not required.
  22. // 2. Altered source versions must be plainly marked as such, and must not be
  23. // misrepresented as being the original software.
  24. // 3. This notice may not be removed or altered from any source distribution.
  25. /* eslint-disable space-unary-ops */
  26. /* Public constants ==========================================================*/
  27. /* ===========================================================================*/
  28. //const Z_FILTERED = 1;
  29. //const Z_HUFFMAN_ONLY = 2;
  30. //const Z_RLE = 3;
  31. const Z_FIXED$1 = 4;
  32. //const Z_DEFAULT_STRATEGY = 0;
  33. /* Possible values of the data_type field (though see inflate()) */
  34. const Z_BINARY = 0;
  35. const Z_TEXT = 1;
  36. //const Z_ASCII = 1; // = Z_TEXT
  37. const Z_UNKNOWN$1 = 2;
  38. /*============================================================================*/
  39. function zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  40. // From zutil.h
  41. const STORED_BLOCK = 0;
  42. const STATIC_TREES = 1;
  43. const DYN_TREES = 2;
  44. /* The three kinds of block type */
  45. const MIN_MATCH$1 = 3;
  46. const MAX_MATCH$1 = 258;
  47. /* The minimum and maximum match lengths */
  48. // From deflate.h
  49. /* ===========================================================================
  50. * Internal compression state.
  51. */
  52. const LENGTH_CODES$1 = 29;
  53. /* number of length codes, not counting the special END_BLOCK code */
  54. const LITERALS$1 = 256;
  55. /* number of literal bytes 0..255 */
  56. const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
  57. /* number of Literal or Length codes, including the END_BLOCK code */
  58. const D_CODES$1 = 30;
  59. /* number of distance codes */
  60. const BL_CODES$1 = 19;
  61. /* number of codes used to transfer the bit lengths */
  62. const HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
  63. /* maximum heap size */
  64. const MAX_BITS$1 = 15;
  65. /* All codes must not exceed MAX_BITS bits */
  66. const Buf_size = 16;
  67. /* size of bit buffer in bi_buf */
  68. /* ===========================================================================
  69. * Constants
  70. */
  71. const MAX_BL_BITS = 7;
  72. /* Bit length codes must not exceed MAX_BL_BITS bits */
  73. const END_BLOCK = 256;
  74. /* end of block literal code */
  75. const REP_3_6 = 16;
  76. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  77. const REPZ_3_10 = 17;
  78. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  79. const REPZ_11_138 = 18;
  80. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  81. /* eslint-disable comma-spacing,array-bracket-spacing */
  82. const extra_lbits = /* extra bits for each length code */
  83. new Uint8Array([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]);
  84. const extra_dbits = /* extra bits for each distance code */
  85. new Uint8Array([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]);
  86. const extra_blbits = /* extra bits for each bit length code */
  87. new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);
  88. const bl_order =
  89. new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);
  90. /* eslint-enable comma-spacing,array-bracket-spacing */
  91. /* The lengths of the bit length codes are sent in order of decreasing
  92. * probability, to avoid transmitting the lengths for unused bit length codes.
  93. */
  94. /* ===========================================================================
  95. * Local data. These are initialized only once.
  96. */
  97. // We pre-fill arrays with 0 to avoid uninitialized gaps
  98. const DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  99. // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  100. const static_ltree = new Array((L_CODES$1 + 2) * 2);
  101. zero$1(static_ltree);
  102. /* The static literal tree. Since the bit lengths are imposed, there is no
  103. * need for the L_CODES extra codes used during heap construction. However
  104. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  105. * below).
  106. */
  107. const static_dtree = new Array(D_CODES$1 * 2);
  108. zero$1(static_dtree);
  109. /* The static distance tree. (Actually a trivial tree since all codes use
  110. * 5 bits.)
  111. */
  112. const _dist_code = new Array(DIST_CODE_LEN);
  113. zero$1(_dist_code);
  114. /* Distance codes. The first 256 values correspond to the distances
  115. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  116. * the 15 bit distances.
  117. */
  118. const _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);
  119. zero$1(_length_code);
  120. /* length code for each normalized match length (0 == MIN_MATCH) */
  121. const base_length = new Array(LENGTH_CODES$1);
  122. zero$1(base_length);
  123. /* First normalized length for each code (0 = MIN_MATCH) */
  124. const base_dist = new Array(D_CODES$1);
  125. zero$1(base_dist);
  126. /* First normalized distance for each code (0 = distance of 1) */
  127. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  128. this.static_tree = static_tree; /* static tree or NULL */
  129. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  130. this.extra_base = extra_base; /* base index for extra_bits */
  131. this.elems = elems; /* max number of elements in the tree */
  132. this.max_length = max_length; /* max bit length for the codes */
  133. // show if `static_tree` has data or dummy - needed for monomorphic objects
  134. this.has_stree = static_tree && static_tree.length;
  135. }
  136. let static_l_desc;
  137. let static_d_desc;
  138. let static_bl_desc;
  139. function TreeDesc(dyn_tree, stat_desc) {
  140. this.dyn_tree = dyn_tree; /* the dynamic tree */
  141. this.max_code = 0; /* largest code with non zero frequency */
  142. this.stat_desc = stat_desc; /* the corresponding static tree */
  143. }
  144. const d_code = (dist) => {
  145. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  146. };
  147. /* ===========================================================================
  148. * Output a short LSB first on the stream.
  149. * IN assertion: there is enough room in pendingBuf.
  150. */
  151. const put_short = (s, w) => {
  152. // put_byte(s, (uch)((w) & 0xff));
  153. // put_byte(s, (uch)((ush)(w) >> 8));
  154. s.pending_buf[s.pending++] = (w) & 0xff;
  155. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  156. };
  157. /* ===========================================================================
  158. * Send a value on a given number of bits.
  159. * IN assertion: length <= 16 and value fits in length bits.
  160. */
  161. const send_bits = (s, value, length) => {
  162. if (s.bi_valid > (Buf_size - length)) {
  163. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  164. put_short(s, s.bi_buf);
  165. s.bi_buf = value >> (Buf_size - s.bi_valid);
  166. s.bi_valid += length - Buf_size;
  167. } else {
  168. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  169. s.bi_valid += length;
  170. }
  171. };
  172. const send_code = (s, c, tree) => {
  173. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  174. };
  175. /* ===========================================================================
  176. * Reverse the first len bits of a code, using straightforward code (a faster
  177. * method would use a table)
  178. * IN assertion: 1 <= len <= 15
  179. */
  180. const bi_reverse = (code, len) => {
  181. let res = 0;
  182. do {
  183. res |= code & 1;
  184. code >>>= 1;
  185. res <<= 1;
  186. } while (--len > 0);
  187. return res >>> 1;
  188. };
  189. /* ===========================================================================
  190. * Flush the bit buffer, keeping at most 7 bits in it.
  191. */
  192. const bi_flush = (s) => {
  193. if (s.bi_valid === 16) {
  194. put_short(s, s.bi_buf);
  195. s.bi_buf = 0;
  196. s.bi_valid = 0;
  197. } else if (s.bi_valid >= 8) {
  198. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  199. s.bi_buf >>= 8;
  200. s.bi_valid -= 8;
  201. }
  202. };
  203. /* ===========================================================================
  204. * Compute the optimal bit lengths for a tree and update the total bit length
  205. * for the current block.
  206. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  207. * above are the tree nodes sorted by increasing frequency.
  208. * OUT assertions: the field len is set to the optimal bit length, the
  209. * array bl_count contains the frequencies for each bit length.
  210. * The length opt_len is updated; static_len is also updated if stree is
  211. * not null.
  212. */
  213. const gen_bitlen = (s, desc) =>
  214. // deflate_state *s;
  215. // tree_desc *desc; /* the tree descriptor */
  216. {
  217. const tree = desc.dyn_tree;
  218. const max_code = desc.max_code;
  219. const stree = desc.stat_desc.static_tree;
  220. const has_stree = desc.stat_desc.has_stree;
  221. const extra = desc.stat_desc.extra_bits;
  222. const base = desc.stat_desc.extra_base;
  223. const max_length = desc.stat_desc.max_length;
  224. let h; /* heap index */
  225. let n, m; /* iterate over the tree elements */
  226. let bits; /* bit length */
  227. let xbits; /* extra bits */
  228. let f; /* frequency */
  229. let overflow = 0; /* number of elements with bit length too large */
  230. for (bits = 0; bits <= MAX_BITS$1; bits++) {
  231. s.bl_count[bits] = 0;
  232. }
  233. /* In a first pass, compute the optimal bit lengths (which may
  234. * overflow in the case of the bit length tree).
  235. */
  236. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  237. for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {
  238. n = s.heap[h];
  239. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  240. if (bits > max_length) {
  241. bits = max_length;
  242. overflow++;
  243. }
  244. tree[n * 2 + 1]/*.Len*/ = bits;
  245. /* We overwrite tree[n].Dad which is no longer needed */
  246. if (n > max_code) { continue; } /* not a leaf node */
  247. s.bl_count[bits]++;
  248. xbits = 0;
  249. if (n >= base) {
  250. xbits = extra[n - base];
  251. }
  252. f = tree[n * 2]/*.Freq*/;
  253. s.opt_len += f * (bits + xbits);
  254. if (has_stree) {
  255. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  256. }
  257. }
  258. if (overflow === 0) { return; }
  259. // Trace((stderr,"\nbit length overflow\n"));
  260. /* This happens for example on obj2 and pic of the Calgary corpus */
  261. /* Find the first bit length which could increase: */
  262. do {
  263. bits = max_length - 1;
  264. while (s.bl_count[bits] === 0) { bits--; }
  265. s.bl_count[bits]--; /* move one leaf down the tree */
  266. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  267. s.bl_count[max_length]--;
  268. /* The brother of the overflow item also moves one step up,
  269. * but this does not affect bl_count[max_length]
  270. */
  271. overflow -= 2;
  272. } while (overflow > 0);
  273. /* Now recompute all bit lengths, scanning in increasing frequency.
  274. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  275. * lengths instead of fixing only the wrong ones. This idea is taken
  276. * from 'ar' written by Haruhiko Okumura.)
  277. */
  278. for (bits = max_length; bits !== 0; bits--) {
  279. n = s.bl_count[bits];
  280. while (n !== 0) {
  281. m = s.heap[--h];
  282. if (m > max_code) { continue; }
  283. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  284. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  285. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  286. tree[m * 2 + 1]/*.Len*/ = bits;
  287. }
  288. n--;
  289. }
  290. }
  291. };
  292. /* ===========================================================================
  293. * Generate the codes for a given tree and bit counts (which need not be
  294. * optimal).
  295. * IN assertion: the array bl_count contains the bit length statistics for
  296. * the given tree and the field len is set for all tree elements.
  297. * OUT assertion: the field code is set for all tree elements of non
  298. * zero code length.
  299. */
  300. const gen_codes = (tree, max_code, bl_count) =>
  301. // ct_data *tree; /* the tree to decorate */
  302. // int max_code; /* largest code with non zero frequency */
  303. // ushf *bl_count; /* number of codes at each bit length */
  304. {
  305. const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */
  306. let code = 0; /* running code value */
  307. let bits; /* bit index */
  308. let n; /* code index */
  309. /* The distribution counts are first used to generate the code values
  310. * without bit reversal.
  311. */
  312. for (bits = 1; bits <= MAX_BITS$1; bits++) {
  313. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  314. }
  315. /* Check that the bit counts in bl_count are consistent. The last code
  316. * must be all ones.
  317. */
  318. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  319. // "inconsistent bit counts");
  320. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  321. for (n = 0; n <= max_code; n++) {
  322. let len = tree[n * 2 + 1]/*.Len*/;
  323. if (len === 0) { continue; }
  324. /* Now reverse the bits */
  325. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  326. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  327. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  328. }
  329. };
  330. /* ===========================================================================
  331. * Initialize the various 'constant' tables.
  332. */
  333. const tr_static_init = () => {
  334. let n; /* iterates over tree elements */
  335. let bits; /* bit counter */
  336. let length; /* length value */
  337. let code; /* code value */
  338. let dist; /* distance index */
  339. const bl_count = new Array(MAX_BITS$1 + 1);
  340. /* number of codes at each bit length for an optimal tree */
  341. // do check in _tr_init()
  342. //if (static_init_done) return;
  343. /* For some embedded targets, global variables are not initialized: */
  344. /*#ifdef NO_INIT_GLOBAL_POINTERS
  345. static_l_desc.static_tree = static_ltree;
  346. static_l_desc.extra_bits = extra_lbits;
  347. static_d_desc.static_tree = static_dtree;
  348. static_d_desc.extra_bits = extra_dbits;
  349. static_bl_desc.extra_bits = extra_blbits;
  350. #endif*/
  351. /* Initialize the mapping length (0..255) -> length code (0..28) */
  352. length = 0;
  353. for (code = 0; code < LENGTH_CODES$1 - 1; code++) {
  354. base_length[code] = length;
  355. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  356. _length_code[length++] = code;
  357. }
  358. }
  359. //Assert (length == 256, "tr_static_init: length != 256");
  360. /* Note that the length 255 (match length 258) can be represented
  361. * in two different ways: code 284 + 5 bits or code 285, so we
  362. * overwrite length_code[255] to use the best encoding:
  363. */
  364. _length_code[length - 1] = code;
  365. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  366. dist = 0;
  367. for (code = 0; code < 16; code++) {
  368. base_dist[code] = dist;
  369. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  370. _dist_code[dist++] = code;
  371. }
  372. }
  373. //Assert (dist == 256, "tr_static_init: dist != 256");
  374. dist >>= 7; /* from now on, all distances are divided by 128 */
  375. for (; code < D_CODES$1; code++) {
  376. base_dist[code] = dist << 7;
  377. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  378. _dist_code[256 + dist++] = code;
  379. }
  380. }
  381. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  382. /* Construct the codes of the static literal tree */
  383. for (bits = 0; bits <= MAX_BITS$1; bits++) {
  384. bl_count[bits] = 0;
  385. }
  386. n = 0;
  387. while (n <= 143) {
  388. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  389. n++;
  390. bl_count[8]++;
  391. }
  392. while (n <= 255) {
  393. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  394. n++;
  395. bl_count[9]++;
  396. }
  397. while (n <= 279) {
  398. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  399. n++;
  400. bl_count[7]++;
  401. }
  402. while (n <= 287) {
  403. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  404. n++;
  405. bl_count[8]++;
  406. }
  407. /* Codes 286 and 287 do not exist, but we must include them in the
  408. * tree construction to get a canonical Huffman tree (longest code
  409. * all ones)
  410. */
  411. gen_codes(static_ltree, L_CODES$1 + 1, bl_count);
  412. /* The static distance tree is trivial: */
  413. for (n = 0; n < D_CODES$1; n++) {
  414. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  415. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  416. }
  417. // Now data ready and we can init static trees
  418. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);
  419. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1);
  420. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS);
  421. //static_init_done = true;
  422. };
  423. /* ===========================================================================
  424. * Initialize a new block.
  425. */
  426. const init_block = (s) => {
  427. let n; /* iterates over tree elements */
  428. /* Initialize the trees. */
  429. for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  430. for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  431. for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  432. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  433. s.opt_len = s.static_len = 0;
  434. s.last_lit = s.matches = 0;
  435. };
  436. /* ===========================================================================
  437. * Flush the bit buffer and align the output on a byte boundary
  438. */
  439. const bi_windup = (s) =>
  440. {
  441. if (s.bi_valid > 8) {
  442. put_short(s, s.bi_buf);
  443. } else if (s.bi_valid > 0) {
  444. //put_byte(s, (Byte)s->bi_buf);
  445. s.pending_buf[s.pending++] = s.bi_buf;
  446. }
  447. s.bi_buf = 0;
  448. s.bi_valid = 0;
  449. };
  450. /* ===========================================================================
  451. * Copy a stored block, storing first the length and its
  452. * one's complement if requested.
  453. */
  454. const copy_block = (s, buf, len, header) =>
  455. //DeflateState *s;
  456. //charf *buf; /* the input data */
  457. //unsigned len; /* its length */
  458. //int header; /* true if block header must be written */
  459. {
  460. bi_windup(s); /* align on byte boundary */
  461. if (header) {
  462. put_short(s, len);
  463. put_short(s, ~len);
  464. }
  465. // while (len--) {
  466. // put_byte(s, *buf++);
  467. // }
  468. s.pending_buf.set(s.window.subarray(buf, buf + len), s.pending);
  469. s.pending += len;
  470. };
  471. /* ===========================================================================
  472. * Compares to subtrees, using the tree depth as tie breaker when
  473. * the subtrees have equal frequency. This minimizes the worst case length.
  474. */
  475. const smaller = (tree, n, m, depth) => {
  476. const _n2 = n * 2;
  477. const _m2 = m * 2;
  478. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  479. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  480. };
  481. /* ===========================================================================
  482. * Restore the heap property by moving down the tree starting at node k,
  483. * exchanging a node with the smallest of its two sons if necessary, stopping
  484. * when the heap property is re-established (each father smaller than its
  485. * two sons).
  486. */
  487. const pqdownheap = (s, tree, k) =>
  488. // deflate_state *s;
  489. // ct_data *tree; /* the tree to restore */
  490. // int k; /* node to move down */
  491. {
  492. const v = s.heap[k];
  493. let j = k << 1; /* left son of k */
  494. while (j <= s.heap_len) {
  495. /* Set j to the smallest of the two sons: */
  496. if (j < s.heap_len &&
  497. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  498. j++;
  499. }
  500. /* Exit if v is smaller than both sons */
  501. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  502. /* Exchange v with the smallest son */
  503. s.heap[k] = s.heap[j];
  504. k = j;
  505. /* And continue down the tree, setting j to the left son of k */
  506. j <<= 1;
  507. }
  508. s.heap[k] = v;
  509. };
  510. // inlined manually
  511. // const SMALLEST = 1;
  512. /* ===========================================================================
  513. * Send the block data compressed using the given Huffman trees
  514. */
  515. const compress_block = (s, ltree, dtree) =>
  516. // deflate_state *s;
  517. // const ct_data *ltree; /* literal tree */
  518. // const ct_data *dtree; /* distance tree */
  519. {
  520. let dist; /* distance of matched string */
  521. let lc; /* match length or unmatched char (if dist == 0) */
  522. let lx = 0; /* running index in l_buf */
  523. let code; /* the code to send */
  524. let extra; /* number of extra bits to send */
  525. if (s.last_lit !== 0) {
  526. do {
  527. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  528. lc = s.pending_buf[s.l_buf + lx];
  529. lx++;
  530. if (dist === 0) {
  531. send_code(s, lc, ltree); /* send a literal byte */
  532. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  533. } else {
  534. /* Here, lc is the match length - MIN_MATCH */
  535. code = _length_code[lc];
  536. send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */
  537. extra = extra_lbits[code];
  538. if (extra !== 0) {
  539. lc -= base_length[code];
  540. send_bits(s, lc, extra); /* send the extra length bits */
  541. }
  542. dist--; /* dist is now the match distance - 1 */
  543. code = d_code(dist);
  544. //Assert (code < D_CODES, "bad d_code");
  545. send_code(s, code, dtree); /* send the distance code */
  546. extra = extra_dbits[code];
  547. if (extra !== 0) {
  548. dist -= base_dist[code];
  549. send_bits(s, dist, extra); /* send the extra distance bits */
  550. }
  551. } /* literal or match pair ? */
  552. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  553. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  554. // "pendingBuf overflow");
  555. } while (lx < s.last_lit);
  556. }
  557. send_code(s, END_BLOCK, ltree);
  558. };
  559. /* ===========================================================================
  560. * Construct one Huffman tree and assigns the code bit strings and lengths.
  561. * Update the total bit length for the current block.
  562. * IN assertion: the field freq is set for all tree elements.
  563. * OUT assertions: the fields len and code are set to the optimal bit length
  564. * and corresponding code. The length opt_len is updated; static_len is
  565. * also updated if stree is not null. The field max_code is set.
  566. */
  567. const build_tree = (s, desc) =>
  568. // deflate_state *s;
  569. // tree_desc *desc; /* the tree descriptor */
  570. {
  571. const tree = desc.dyn_tree;
  572. const stree = desc.stat_desc.static_tree;
  573. const has_stree = desc.stat_desc.has_stree;
  574. const elems = desc.stat_desc.elems;
  575. let n, m; /* iterate over heap elements */
  576. let max_code = -1; /* largest code with non zero frequency */
  577. let node; /* new node being created */
  578. /* Construct the initial heap, with least frequent element in
  579. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  580. * heap[0] is not used.
  581. */
  582. s.heap_len = 0;
  583. s.heap_max = HEAP_SIZE$1;
  584. for (n = 0; n < elems; n++) {
  585. if (tree[n * 2]/*.Freq*/ !== 0) {
  586. s.heap[++s.heap_len] = max_code = n;
  587. s.depth[n] = 0;
  588. } else {
  589. tree[n * 2 + 1]/*.Len*/ = 0;
  590. }
  591. }
  592. /* The pkzip format requires that at least one distance code exists,
  593. * and that at least one bit should be sent even if there is only one
  594. * possible code. So to avoid special checks later on we force at least
  595. * two codes of non zero frequency.
  596. */
  597. while (s.heap_len < 2) {
  598. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  599. tree[node * 2]/*.Freq*/ = 1;
  600. s.depth[node] = 0;
  601. s.opt_len--;
  602. if (has_stree) {
  603. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  604. }
  605. /* node is 0 or 1 so it does not have extra bits */
  606. }
  607. desc.max_code = max_code;
  608. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  609. * establish sub-heaps of increasing lengths:
  610. */
  611. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  612. /* Construct the Huffman tree by repeatedly combining the least two
  613. * frequent nodes.
  614. */
  615. node = elems; /* next internal node of the tree */
  616. do {
  617. //pqremove(s, tree, n); /* n = node of least frequency */
  618. /*** pqremove ***/
  619. n = s.heap[1/*SMALLEST*/];
  620. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  621. pqdownheap(s, tree, 1/*SMALLEST*/);
  622. /***/
  623. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  624. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  625. s.heap[--s.heap_max] = m;
  626. /* Create a new node father of n and m */
  627. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  628. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  629. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  630. /* and insert the new node in the heap */
  631. s.heap[1/*SMALLEST*/] = node++;
  632. pqdownheap(s, tree, 1/*SMALLEST*/);
  633. } while (s.heap_len >= 2);
  634. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  635. /* At this point, the fields freq and dad are set. We can now
  636. * generate the bit lengths.
  637. */
  638. gen_bitlen(s, desc);
  639. /* The field len is now set, we can generate the bit codes */
  640. gen_codes(tree, max_code, s.bl_count);
  641. };
  642. /* ===========================================================================
  643. * Scan a literal or distance tree to determine the frequencies of the codes
  644. * in the bit length tree.
  645. */
  646. const scan_tree = (s, tree, max_code) =>
  647. // deflate_state *s;
  648. // ct_data *tree; /* the tree to be scanned */
  649. // int max_code; /* and its largest code of non zero frequency */
  650. {
  651. let n; /* iterates over all tree elements */
  652. let prevlen = -1; /* last emitted length */
  653. let curlen; /* length of current code */
  654. let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  655. let count = 0; /* repeat count of the current code */
  656. let max_count = 7; /* max repeat count */
  657. let min_count = 4; /* min repeat count */
  658. if (nextlen === 0) {
  659. max_count = 138;
  660. min_count = 3;
  661. }
  662. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  663. for (n = 0; n <= max_code; n++) {
  664. curlen = nextlen;
  665. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  666. if (++count < max_count && curlen === nextlen) {
  667. continue;
  668. } else if (count < min_count) {
  669. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  670. } else if (curlen !== 0) {
  671. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  672. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  673. } else if (count <= 10) {
  674. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  675. } else {
  676. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  677. }
  678. count = 0;
  679. prevlen = curlen;
  680. if (nextlen === 0) {
  681. max_count = 138;
  682. min_count = 3;
  683. } else if (curlen === nextlen) {
  684. max_count = 6;
  685. min_count = 3;
  686. } else {
  687. max_count = 7;
  688. min_count = 4;
  689. }
  690. }
  691. };
  692. /* ===========================================================================
  693. * Send a literal or distance tree in compressed form, using the codes in
  694. * bl_tree.
  695. */
  696. const send_tree = (s, tree, max_code) =>
  697. // deflate_state *s;
  698. // ct_data *tree; /* the tree to be scanned */
  699. // int max_code; /* and its largest code of non zero frequency */
  700. {
  701. let n; /* iterates over all tree elements */
  702. let prevlen = -1; /* last emitted length */
  703. let curlen; /* length of current code */
  704. let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  705. let count = 0; /* repeat count of the current code */
  706. let max_count = 7; /* max repeat count */
  707. let min_count = 4; /* min repeat count */
  708. /* tree[max_code+1].Len = -1; */ /* guard already set */
  709. if (nextlen === 0) {
  710. max_count = 138;
  711. min_count = 3;
  712. }
  713. for (n = 0; n <= max_code; n++) {
  714. curlen = nextlen;
  715. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  716. if (++count < max_count && curlen === nextlen) {
  717. continue;
  718. } else if (count < min_count) {
  719. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  720. } else if (curlen !== 0) {
  721. if (curlen !== prevlen) {
  722. send_code(s, curlen, s.bl_tree);
  723. count--;
  724. }
  725. //Assert(count >= 3 && count <= 6, " 3_6?");
  726. send_code(s, REP_3_6, s.bl_tree);
  727. send_bits(s, count - 3, 2);
  728. } else if (count <= 10) {
  729. send_code(s, REPZ_3_10, s.bl_tree);
  730. send_bits(s, count - 3, 3);
  731. } else {
  732. send_code(s, REPZ_11_138, s.bl_tree);
  733. send_bits(s, count - 11, 7);
  734. }
  735. count = 0;
  736. prevlen = curlen;
  737. if (nextlen === 0) {
  738. max_count = 138;
  739. min_count = 3;
  740. } else if (curlen === nextlen) {
  741. max_count = 6;
  742. min_count = 3;
  743. } else {
  744. max_count = 7;
  745. min_count = 4;
  746. }
  747. }
  748. };
  749. /* ===========================================================================
  750. * Construct the Huffman tree for the bit lengths and return the index in
  751. * bl_order of the last bit length code to send.
  752. */
  753. const build_bl_tree = (s) => {
  754. let max_blindex; /* index of last bit length code of non zero freq */
  755. /* Determine the bit length frequencies for literal and distance trees */
  756. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  757. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  758. /* Build the bit length tree: */
  759. build_tree(s, s.bl_desc);
  760. /* opt_len now includes the length of the tree representations, except
  761. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  762. */
  763. /* Determine the number of bit length codes to send. The pkzip format
  764. * requires that at least 4 bit length codes be sent. (appnote.txt says
  765. * 3 but the actual value used is 4.)
  766. */
  767. for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {
  768. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  769. break;
  770. }
  771. }
  772. /* Update opt_len to include the bit length tree and counts */
  773. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  774. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  775. // s->opt_len, s->static_len));
  776. return max_blindex;
  777. };
  778. /* ===========================================================================
  779. * Send the header for a block using dynamic Huffman trees: the counts, the
  780. * lengths of the bit length codes, the literal tree and the distance tree.
  781. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  782. */
  783. const send_all_trees = (s, lcodes, dcodes, blcodes) =>
  784. // deflate_state *s;
  785. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  786. {
  787. let rank; /* index in bl_order */
  788. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  789. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  790. // "too many codes");
  791. //Tracev((stderr, "\nbl counts: "));
  792. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  793. send_bits(s, dcodes - 1, 5);
  794. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  795. for (rank = 0; rank < blcodes; rank++) {
  796. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  797. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  798. }
  799. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  800. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  801. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  802. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  803. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  804. };
  805. /* ===========================================================================
  806. * Check if the data type is TEXT or BINARY, using the following algorithm:
  807. * - TEXT if the two conditions below are satisfied:
  808. * a) There are no non-portable control characters belonging to the
  809. * "black list" (0..6, 14..25, 28..31).
  810. * b) There is at least one printable character belonging to the
  811. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  812. * - BINARY otherwise.
  813. * - The following partially-portable control characters form a
  814. * "gray list" that is ignored in this detection algorithm:
  815. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  816. * IN assertion: the fields Freq of dyn_ltree are set.
  817. */
  818. const detect_data_type = (s) => {
  819. /* black_mask is the bit mask of black-listed bytes
  820. * set bits 0..6, 14..25, and 28..31
  821. * 0xf3ffc07f = binary 11110011111111111100000001111111
  822. */
  823. let black_mask = 0xf3ffc07f;
  824. let n;
  825. /* Check for non-textual ("black-listed") bytes. */
  826. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  827. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  828. return Z_BINARY;
  829. }
  830. }
  831. /* Check for textual ("white-listed") bytes. */
  832. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  833. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  834. return Z_TEXT;
  835. }
  836. for (n = 32; n < LITERALS$1; n++) {
  837. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  838. return Z_TEXT;
  839. }
  840. }
  841. /* There are no "black-listed" or "white-listed" bytes:
  842. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  843. */
  844. return Z_BINARY;
  845. };
  846. let static_init_done = false;
  847. /* ===========================================================================
  848. * Initialize the tree data structures for a new zlib stream.
  849. */
  850. const _tr_init$1 = (s) =>
  851. {
  852. if (!static_init_done) {
  853. tr_static_init();
  854. static_init_done = true;
  855. }
  856. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  857. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  858. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  859. s.bi_buf = 0;
  860. s.bi_valid = 0;
  861. /* Initialize the first block of the first file: */
  862. init_block(s);
  863. };
  864. /* ===========================================================================
  865. * Send a stored block
  866. */
  867. const _tr_stored_block$1 = (s, buf, stored_len, last) =>
  868. //DeflateState *s;
  869. //charf *buf; /* input block */
  870. //ulg stored_len; /* length of input block */
  871. //int last; /* one if this is the last block for a file */
  872. {
  873. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  874. copy_block(s, buf, stored_len, true); /* with header */
  875. };
  876. /* ===========================================================================
  877. * Send one empty static block to give enough lookahead for inflate.
  878. * This takes 10 bits, of which 7 may remain in the bit buffer.
  879. */
  880. const _tr_align$1 = (s) => {
  881. send_bits(s, STATIC_TREES << 1, 3);
  882. send_code(s, END_BLOCK, static_ltree);
  883. bi_flush(s);
  884. };
  885. /* ===========================================================================
  886. * Determine the best encoding for the current block: dynamic trees, static
  887. * trees or store, and output the encoded block to the zip file.
  888. */
  889. const _tr_flush_block$1 = (s, buf, stored_len, last) =>
  890. //DeflateState *s;
  891. //charf *buf; /* input block, or NULL if too old */
  892. //ulg stored_len; /* length of input block */
  893. //int last; /* one if this is the last block for a file */
  894. {
  895. let opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  896. let max_blindex = 0; /* index of last bit length code of non zero freq */
  897. /* Build the Huffman trees unless a stored block is forced */
  898. if (s.level > 0) {
  899. /* Check if the file is binary or text */
  900. if (s.strm.data_type === Z_UNKNOWN$1) {
  901. s.strm.data_type = detect_data_type(s);
  902. }
  903. /* Construct the literal and distance trees */
  904. build_tree(s, s.l_desc);
  905. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  906. // s->static_len));
  907. build_tree(s, s.d_desc);
  908. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  909. // s->static_len));
  910. /* At this point, opt_len and static_len are the total bit lengths of
  911. * the compressed block data, excluding the tree representations.
  912. */
  913. /* Build the bit length tree for the above two trees, and get the index
  914. * in bl_order of the last bit length code to send.
  915. */
  916. max_blindex = build_bl_tree(s);
  917. /* Determine the best encoding. Compute the block lengths in bytes. */
  918. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  919. static_lenb = (s.static_len + 3 + 7) >>> 3;
  920. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  921. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  922. // s->last_lit));
  923. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  924. } else {
  925. // Assert(buf != (char*)0, "lost buf");
  926. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  927. }
  928. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  929. /* 4: two words for the lengths */
  930. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  931. * Otherwise we can't have processed more than WSIZE input bytes since
  932. * the last block flush, because compression would have been
  933. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  934. * transform a block into a stored block.
  935. */
  936. _tr_stored_block$1(s, buf, stored_len, last);
  937. } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {
  938. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  939. compress_block(s, static_ltree, static_dtree);
  940. } else {
  941. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  942. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  943. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  944. }
  945. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  946. /* The above check is made mod 2^32, for files larger than 512 MB
  947. * and uLong implemented on 32 bits.
  948. */
  949. init_block(s);
  950. if (last) {
  951. bi_windup(s);
  952. }
  953. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  954. // s->compressed_len-7*last));
  955. };
  956. /* ===========================================================================
  957. * Save the match info and tally the frequency counts. Return true if
  958. * the current block must be flushed.
  959. */
  960. const _tr_tally$1 = (s, dist, lc) =>
  961. // deflate_state *s;
  962. // unsigned dist; /* distance of matched string */
  963. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  964. {
  965. //let out_length, in_length, dcode;
  966. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  967. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  968. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  969. s.last_lit++;
  970. if (dist === 0) {
  971. /* lc is the unmatched char */
  972. s.dyn_ltree[lc * 2]/*.Freq*/++;
  973. } else {
  974. s.matches++;
  975. /* Here, lc is the match length - MIN_MATCH */
  976. dist--; /* dist = match distance - 1 */
  977. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  978. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  979. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  980. s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;
  981. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  982. }
  983. // (!) This block is disabled in zlib defaults,
  984. // don't enable it for binary compatibility
  985. //#ifdef TRUNCATE_BLOCK
  986. // /* Try to guess if it is profitable to stop the current block here */
  987. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  988. // /* Compute an upper bound for the compressed length */
  989. // out_length = s.last_lit*8;
  990. // in_length = s.strstart - s.block_start;
  991. //
  992. // for (dcode = 0; dcode < D_CODES; dcode++) {
  993. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  994. // }
  995. // out_length >>>= 3;
  996. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  997. // // s->last_lit, in_length, out_length,
  998. // // 100L - out_length*100L/in_length));
  999. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  1000. // return true;
  1001. // }
  1002. // }
  1003. //#endif
  1004. return (s.last_lit === s.lit_bufsize - 1);
  1005. /* We avoid equality with lit_bufsize because of wraparound at 64K
  1006. * on 16 bit machines and because stored blocks are restricted to
  1007. * 64K-1 bytes.
  1008. */
  1009. };
  1010. var _tr_init_1 = _tr_init$1;
  1011. var _tr_stored_block_1 = _tr_stored_block$1;
  1012. var _tr_flush_block_1 = _tr_flush_block$1;
  1013. var _tr_tally_1 = _tr_tally$1;
  1014. var _tr_align_1 = _tr_align$1;
  1015. var trees = {
  1016. _tr_init: _tr_init_1,
  1017. _tr_stored_block: _tr_stored_block_1,
  1018. _tr_flush_block: _tr_flush_block_1,
  1019. _tr_tally: _tr_tally_1,
  1020. _tr_align: _tr_align_1
  1021. };
  1022. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  1023. // It isn't worth it to make additional optimizations as in original.
  1024. // Small size is preferable.
  1025. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  1026. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  1027. //
  1028. // This software is provided 'as-is', without any express or implied
  1029. // warranty. In no event will the authors be held liable for any damages
  1030. // arising from the use of this software.
  1031. //
  1032. // Permission is granted to anyone to use this software for any purpose,
  1033. // including commercial applications, and to alter it and redistribute it
  1034. // freely, subject to the following restrictions:
  1035. //
  1036. // 1. The origin of this software must not be misrepresented; you must not
  1037. // claim that you wrote the original software. If you use this software
  1038. // in a product, an acknowledgment in the product documentation would be
  1039. // appreciated but is not required.
  1040. // 2. Altered source versions must be plainly marked as such, and must not be
  1041. // misrepresented as being the original software.
  1042. // 3. This notice may not be removed or altered from any source distribution.
  1043. const adler32 = (adler, buf, len, pos) => {
  1044. let s1 = (adler & 0xffff) |0,
  1045. s2 = ((adler >>> 16) & 0xffff) |0,
  1046. n = 0;
  1047. while (len !== 0) {
  1048. // Set limit ~ twice less than 5552, to keep
  1049. // s2 in 31-bits, because we force signed ints.
  1050. // in other case %= will fail.
  1051. n = len > 2000 ? 2000 : len;
  1052. len -= n;
  1053. do {
  1054. s1 = (s1 + buf[pos++]) |0;
  1055. s2 = (s2 + s1) |0;
  1056. } while (--n);
  1057. s1 %= 65521;
  1058. s2 %= 65521;
  1059. }
  1060. return (s1 | (s2 << 16)) |0;
  1061. };
  1062. var adler32_1 = adler32;
  1063. // Note: we can't get significant speed boost here.
  1064. // So write code to minimize size - no pregenerated tables
  1065. // and array tools dependencies.
  1066. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  1067. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  1068. //
  1069. // This software is provided 'as-is', without any express or implied
  1070. // warranty. In no event will the authors be held liable for any damages
  1071. // arising from the use of this software.
  1072. //
  1073. // Permission is granted to anyone to use this software for any purpose,
  1074. // including commercial applications, and to alter it and redistribute it
  1075. // freely, subject to the following restrictions:
  1076. //
  1077. // 1. The origin of this software must not be misrepresented; you must not
  1078. // claim that you wrote the original software. If you use this software
  1079. // in a product, an acknowledgment in the product documentation would be
  1080. // appreciated but is not required.
  1081. // 2. Altered source versions must be plainly marked as such, and must not be
  1082. // misrepresented as being the original software.
  1083. // 3. This notice may not be removed or altered from any source distribution.
  1084. // Use ordinary array, since untyped makes no boost here
  1085. const makeTable = () => {
  1086. let c, table = [];
  1087. for (var n = 0; n < 256; n++) {
  1088. c = n;
  1089. for (var k = 0; k < 8; k++) {
  1090. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  1091. }
  1092. table[n] = c;
  1093. }
  1094. return table;
  1095. };
  1096. // Create table on load. Just 255 signed longs. Not a problem.
  1097. const crcTable = new Uint32Array(makeTable());
  1098. const crc32 = (crc, buf, len, pos) => {
  1099. const t = crcTable;
  1100. const end = pos + len;
  1101. crc ^= -1;
  1102. for (let i = pos; i < end; i++) {
  1103. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  1104. }
  1105. return (crc ^ (-1)); // >>> 0;
  1106. };
  1107. var crc32_1 = crc32;
  1108. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  1109. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  1110. //
  1111. // This software is provided 'as-is', without any express or implied
  1112. // warranty. In no event will the authors be held liable for any damages
  1113. // arising from the use of this software.
  1114. //
  1115. // Permission is granted to anyone to use this software for any purpose,
  1116. // including commercial applications, and to alter it and redistribute it
  1117. // freely, subject to the following restrictions:
  1118. //
  1119. // 1. The origin of this software must not be misrepresented; you must not
  1120. // claim that you wrote the original software. If you use this software
  1121. // in a product, an acknowledgment in the product documentation would be
  1122. // appreciated but is not required.
  1123. // 2. Altered source versions must be plainly marked as such, and must not be
  1124. // misrepresented as being the original software.
  1125. // 3. This notice may not be removed or altered from any source distribution.
  1126. var messages = {
  1127. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  1128. 1: 'stream end', /* Z_STREAM_END 1 */
  1129. 0: '', /* Z_OK 0 */
  1130. '-1': 'file error', /* Z_ERRNO (-1) */
  1131. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  1132. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  1133. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  1134. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  1135. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  1136. };
  1137. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  1138. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  1139. //
  1140. // This software is provided 'as-is', without any express or implied
  1141. // warranty. In no event will the authors be held liable for any damages
  1142. // arising from the use of this software.
  1143. //
  1144. // Permission is granted to anyone to use this software for any purpose,
  1145. // including commercial applications, and to alter it and redistribute it
  1146. // freely, subject to the following restrictions:
  1147. //
  1148. // 1. The origin of this software must not be misrepresented; you must not
  1149. // claim that you wrote the original software. If you use this software
  1150. // in a product, an acknowledgment in the product documentation would be
  1151. // appreciated but is not required.
  1152. // 2. Altered source versions must be plainly marked as such, and must not be
  1153. // misrepresented as being the original software.
  1154. // 3. This notice may not be removed or altered from any source distribution.
  1155. var constants$1 = {
  1156. /* Allowed flush values; see deflate() and inflate() below for details */
  1157. Z_NO_FLUSH: 0,
  1158. Z_PARTIAL_FLUSH: 1,
  1159. Z_SYNC_FLUSH: 2,
  1160. Z_FULL_FLUSH: 3,
  1161. Z_FINISH: 4,
  1162. Z_BLOCK: 5,
  1163. Z_TREES: 6,
  1164. /* Return codes for the compression/decompression functions. Negative values
  1165. * are errors, positive values are used for special but normal events.
  1166. */
  1167. Z_OK: 0,
  1168. Z_STREAM_END: 1,
  1169. Z_NEED_DICT: 2,
  1170. Z_ERRNO: -1,
  1171. Z_STREAM_ERROR: -2,
  1172. Z_DATA_ERROR: -3,
  1173. Z_MEM_ERROR: -4,
  1174. Z_BUF_ERROR: -5,
  1175. //Z_VERSION_ERROR: -6,
  1176. /* compression levels */
  1177. Z_NO_COMPRESSION: 0,
  1178. Z_BEST_SPEED: 1,
  1179. Z_BEST_COMPRESSION: 9,
  1180. Z_DEFAULT_COMPRESSION: -1,
  1181. Z_FILTERED: 1,
  1182. Z_HUFFMAN_ONLY: 2,
  1183. Z_RLE: 3,
  1184. Z_FIXED: 4,
  1185. Z_DEFAULT_STRATEGY: 0,
  1186. /* Possible values of the data_type field (though see inflate()) */
  1187. Z_BINARY: 0,
  1188. Z_TEXT: 1,
  1189. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  1190. Z_UNKNOWN: 2,
  1191. /* The deflate compression method */
  1192. Z_DEFLATED: 8
  1193. //Z_NULL: null // Use -1 or null inline, depending on var type
  1194. };
  1195. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  1196. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  1197. //
  1198. // This software is provided 'as-is', without any express or implied
  1199. // warranty. In no event will the authors be held liable for any damages
  1200. // arising from the use of this software.
  1201. //
  1202. // Permission is granted to anyone to use this software for any purpose,
  1203. // including commercial applications, and to alter it and redistribute it
  1204. // freely, subject to the following restrictions:
  1205. //
  1206. // 1. The origin of this software must not be misrepresented; you must not
  1207. // claim that you wrote the original software. If you use this software
  1208. // in a product, an acknowledgment in the product documentation would be
  1209. // appreciated but is not required.
  1210. // 2. Altered source versions must be plainly marked as such, and must not be
  1211. // misrepresented as being the original software.
  1212. // 3. This notice may not be removed or altered from any source distribution.
  1213. const { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;
  1214. /* Public constants ==========================================================*/
  1215. /* ===========================================================================*/
  1216. const {
  1217. Z_NO_FLUSH: Z_NO_FLUSH$1, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$1, Z_BLOCK,
  1218. Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_STREAM_ERROR, Z_DATA_ERROR, Z_BUF_ERROR,
  1219. Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,
  1220. Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,
  1221. Z_UNKNOWN,
  1222. Z_DEFLATED: Z_DEFLATED$1
  1223. } = constants$1;
  1224. /*============================================================================*/
  1225. const MAX_MEM_LEVEL = 9;
  1226. /* Maximum value for memLevel in deflateInit2 */
  1227. const MAX_WBITS = 15;
  1228. /* 32K LZ77 window */
  1229. const DEF_MEM_LEVEL = 8;
  1230. const LENGTH_CODES = 29;
  1231. /* number of length codes, not counting the special END_BLOCK code */
  1232. const LITERALS = 256;
  1233. /* number of literal bytes 0..255 */
  1234. const L_CODES = LITERALS + 1 + LENGTH_CODES;
  1235. /* number of Literal or Length codes, including the END_BLOCK code */
  1236. const D_CODES = 30;
  1237. /* number of distance codes */
  1238. const BL_CODES = 19;
  1239. /* number of codes used to transfer the bit lengths */
  1240. const HEAP_SIZE = 2 * L_CODES + 1;
  1241. /* maximum heap size */
  1242. const MAX_BITS = 15;
  1243. /* All codes must not exceed MAX_BITS bits */
  1244. const MIN_MATCH = 3;
  1245. const MAX_MATCH = 258;
  1246. const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  1247. const PRESET_DICT = 0x20;
  1248. const INIT_STATE = 42;
  1249. const EXTRA_STATE = 69;
  1250. const NAME_STATE = 73;
  1251. const COMMENT_STATE = 91;
  1252. const HCRC_STATE = 103;
  1253. const BUSY_STATE = 113;
  1254. const FINISH_STATE = 666;
  1255. const BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  1256. const BS_BLOCK_DONE = 2; /* block flush performed */
  1257. const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  1258. const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  1259. const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  1260. const err = (strm, errorCode) => {
  1261. strm.msg = messages[errorCode];
  1262. return errorCode;
  1263. };
  1264. const rank = (f) => {
  1265. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  1266. };
  1267. const zero = (buf) => {
  1268. let len = buf.length; while (--len >= 0) { buf[len] = 0; }
  1269. };
  1270. /* eslint-disable new-cap */
  1271. let HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;
  1272. // This hash causes less collisions, https://github.com/nodeca/pako/issues/135
  1273. // But breaks binary compatibility
  1274. //let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;
  1275. let HASH = HASH_ZLIB;
  1276. /* =========================================================================
  1277. * Flush as much pending output as possible. All deflate() output goes
  1278. * through this function so some applications may wish to modify it
  1279. * to avoid allocating a large strm->output buffer and copying into it.
  1280. * (See also read_buf()).
  1281. */
  1282. const flush_pending = (strm) => {
  1283. const s = strm.state;
  1284. //_tr_flush_bits(s);
  1285. let len = s.pending;
  1286. if (len > strm.avail_out) {
  1287. len = strm.avail_out;
  1288. }
  1289. if (len === 0) { return; }
  1290. strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);
  1291. strm.next_out += len;
  1292. s.pending_out += len;
  1293. strm.total_out += len;
  1294. strm.avail_out -= len;
  1295. s.pending -= len;
  1296. if (s.pending === 0) {
  1297. s.pending_out = 0;
  1298. }
  1299. };
  1300. const flush_block_only = (s, last) => {
  1301. _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  1302. s.block_start = s.strstart;
  1303. flush_pending(s.strm);
  1304. };
  1305. const put_byte = (s, b) => {
  1306. s.pending_buf[s.pending++] = b;
  1307. };
  1308. /* =========================================================================
  1309. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  1310. * IN assertion: the stream state is correct and there is enough room in
  1311. * pending_buf.
  1312. */
  1313. const putShortMSB = (s, b) => {
  1314. // put_byte(s, (Byte)(b >> 8));
  1315. // put_byte(s, (Byte)(b & 0xff));
  1316. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  1317. s.pending_buf[s.pending++] = b & 0xff;
  1318. };
  1319. /* ===========================================================================
  1320. * Read a new buffer from the current input stream, update the adler32
  1321. * and total number of bytes read. All deflate() input goes through
  1322. * this function so some applications may wish to modify it to avoid
  1323. * allocating a large strm->input buffer and copying from it.
  1324. * (See also flush_pending()).
  1325. */
  1326. const read_buf = (strm, buf, start, size) => {
  1327. let len = strm.avail_in;
  1328. if (len > size) { len = size; }
  1329. if (len === 0) { return 0; }
  1330. strm.avail_in -= len;
  1331. // zmemcpy(buf, strm->next_in, len);
  1332. buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);
  1333. if (strm.state.wrap === 1) {
  1334. strm.adler = adler32_1(strm.adler, buf, len, start);
  1335. }
  1336. else if (strm.state.wrap === 2) {
  1337. strm.adler = crc32_1(strm.adler, buf, len, start);
  1338. }
  1339. strm.next_in += len;
  1340. strm.total_in += len;
  1341. return len;
  1342. };
  1343. /* ===========================================================================
  1344. * Set match_start to the longest match starting at the given string and
  1345. * return its length. Matches shorter or equal to prev_length are discarded,
  1346. * in which case the result is equal to prev_length and match_start is
  1347. * garbage.
  1348. * IN assertions: cur_match is the head of the hash chain for the current
  1349. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  1350. * OUT assertion: the match length is not greater than s->lookahead.
  1351. */
  1352. const longest_match = (s, cur_match) => {
  1353. let chain_length = s.max_chain_length; /* max hash chain length */
  1354. let scan = s.strstart; /* current string */
  1355. let match; /* matched string */
  1356. let len; /* length of current match */
  1357. let best_len = s.prev_length; /* best match length so far */
  1358. let nice_match = s.nice_match; /* stop if match long enough */
  1359. const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  1360. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  1361. const _win = s.window; // shortcut
  1362. const wmask = s.w_mask;
  1363. const prev = s.prev;
  1364. /* Stop when cur_match becomes <= limit. To simplify the code,
  1365. * we prevent matches with the string of window index 0.
  1366. */
  1367. const strend = s.strstart + MAX_MATCH;
  1368. let scan_end1 = _win[scan + best_len - 1];
  1369. let scan_end = _win[scan + best_len];
  1370. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1371. * It is easy to get rid of this optimization if necessary.
  1372. */
  1373. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  1374. /* Do not waste too much time if we already have a good match: */
  1375. if (s.prev_length >= s.good_match) {
  1376. chain_length >>= 2;
  1377. }
  1378. /* Do not look for matches beyond the end of the input. This is necessary
  1379. * to make deflate deterministic.
  1380. */
  1381. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  1382. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  1383. do {
  1384. // Assert(cur_match < s->strstart, "no future");
  1385. match = cur_match;
  1386. /* Skip to next match if the match length cannot increase
  1387. * or if the match length is less than 2. Note that the checks below
  1388. * for insufficient lookahead only occur occasionally for performance
  1389. * reasons. Therefore uninitialized memory will be accessed, and
  1390. * conditional jumps will be made that depend on those values.
  1391. * However the length of the match is limited to the lookahead, so
  1392. * the output of deflate is not affected by the uninitialized values.
  1393. */
  1394. if (_win[match + best_len] !== scan_end ||
  1395. _win[match + best_len - 1] !== scan_end1 ||
  1396. _win[match] !== _win[scan] ||
  1397. _win[++match] !== _win[scan + 1]) {
  1398. continue;
  1399. }
  1400. /* The check at best_len-1 can be removed because it will be made
  1401. * again later. (This heuristic is not always a win.)
  1402. * It is not necessary to compare scan[2] and match[2] since they
  1403. * are always equal when the other bytes match, given that
  1404. * the hash keys are equal and that HASH_BITS >= 8.
  1405. */
  1406. scan += 2;
  1407. match++;
  1408. // Assert(*scan == *match, "match[2]?");
  1409. /* We check for insufficient lookahead only every 8th comparison;
  1410. * the 256th check will be made at strstart+258.
  1411. */
  1412. do {
  1413. /*jshint noempty:false*/
  1414. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  1415. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  1416. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  1417. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  1418. scan < strend);
  1419. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1420. len = MAX_MATCH - (strend - scan);
  1421. scan = strend - MAX_MATCH;
  1422. if (len > best_len) {
  1423. s.match_start = cur_match;
  1424. best_len = len;
  1425. if (len >= nice_match) {
  1426. break;
  1427. }
  1428. scan_end1 = _win[scan + best_len - 1];
  1429. scan_end = _win[scan + best_len];
  1430. }
  1431. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  1432. if (best_len <= s.lookahead) {
  1433. return best_len;
  1434. }
  1435. return s.lookahead;
  1436. };
  1437. /* ===========================================================================
  1438. * Fill the window when the lookahead becomes insufficient.
  1439. * Updates strstart and lookahead.
  1440. *
  1441. * IN assertion: lookahead < MIN_LOOKAHEAD
  1442. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  1443. * At least one byte has been read, or avail_in == 0; reads are
  1444. * performed for at least two bytes (required for the zip translate_eol
  1445. * option -- not supported here).
  1446. */
  1447. const fill_window = (s) => {
  1448. const _w_size = s.w_size;
  1449. let p, n, m, more, str;
  1450. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  1451. do {
  1452. more = s.window_size - s.lookahead - s.strstart;
  1453. // JS ints have 32 bit, block below not needed
  1454. /* Deal with !@#$% 64K limit: */
  1455. //if (sizeof(int) <= 2) {
  1456. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  1457. // more = wsize;
  1458. //
  1459. // } else if (more == (unsigned)(-1)) {
  1460. // /* Very unlikely, but possible on 16 bit machine if
  1461. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  1462. // */
  1463. // more--;
  1464. // }
  1465. //}
  1466. /* If the window is almost full and there is insufficient lookahead,
  1467. * move the upper half to the lower one to make room in the upper half.
  1468. */
  1469. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  1470. s.window.set(s.window.subarray(_w_size, _w_size + _w_size), 0);
  1471. s.match_start -= _w_size;
  1472. s.strstart -= _w_size;
  1473. /* we now have strstart >= MAX_DIST */
  1474. s.block_start -= _w_size;
  1475. /* Slide the hash table (could be avoided with 32 bit values
  1476. at the expense of memory usage). We slide even when level == 0
  1477. to keep the hash table consistent if we switch back to level > 0
  1478. later. (Using level 0 permanently is not an optimal usage of
  1479. zlib, so we don't care about this pathological case.)
  1480. */
  1481. n = s.hash_size;
  1482. p = n;
  1483. do {
  1484. m = s.head[--p];
  1485. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  1486. } while (--n);
  1487. n = _w_size;
  1488. p = n;
  1489. do {
  1490. m = s.prev[--p];
  1491. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  1492. /* If n is not on any hash chain, prev[n] is garbage but
  1493. * its value will never be used.
  1494. */
  1495. } while (--n);
  1496. more += _w_size;
  1497. }
  1498. if (s.strm.avail_in === 0) {
  1499. break;
  1500. }
  1501. /* If there was no sliding:
  1502. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1503. * more == window_size - lookahead - strstart
  1504. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1505. * => more >= window_size - 2*WSIZE + 2
  1506. * In the BIG_MEM or MMAP case (not yet supported),
  1507. * window_size == input_size + MIN_LOOKAHEAD &&
  1508. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1509. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1510. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  1511. */
  1512. //Assert(more >= 2, "more < 2");
  1513. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  1514. s.lookahead += n;
  1515. /* Initialize the hash value now that we have some input: */
  1516. if (s.lookahead + s.insert >= MIN_MATCH) {
  1517. str = s.strstart - s.insert;
  1518. s.ins_h = s.window[str];
  1519. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  1520. s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);
  1521. //#if MIN_MATCH != 3
  1522. // Call update_hash() MIN_MATCH-3 more times
  1523. //#endif
  1524. while (s.insert) {
  1525. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  1526. s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
  1527. s.prev[str & s.w_mask] = s.head[s.ins_h];
  1528. s.head[s.ins_h] = str;
  1529. str++;
  1530. s.insert--;
  1531. if (s.lookahead + s.insert < MIN_MATCH) {
  1532. break;
  1533. }
  1534. }
  1535. }
  1536. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  1537. * but this is not important since only literal bytes will be emitted.
  1538. */
  1539. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  1540. /* If the WIN_INIT bytes after the end of the current data have never been
  1541. * written, then zero those bytes in order to avoid memory check reports of
  1542. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  1543. * the longest match routines. Update the high water mark for the next
  1544. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  1545. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  1546. */
  1547. // if (s.high_water < s.window_size) {
  1548. // const curr = s.strstart + s.lookahead;
  1549. // let init = 0;
  1550. //
  1551. // if (s.high_water < curr) {
  1552. // /* Previous high water mark below current data -- zero WIN_INIT
  1553. // * bytes or up to end of window, whichever is less.
  1554. // */
  1555. // init = s.window_size - curr;
  1556. // if (init > WIN_INIT)
  1557. // init = WIN_INIT;
  1558. // zmemzero(s->window + curr, (unsigned)init);
  1559. // s->high_water = curr + init;
  1560. // }
  1561. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  1562. // /* High water mark at or above current data, but below current data
  1563. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  1564. // * to end of window, whichever is less.
  1565. // */
  1566. // init = (ulg)curr + WIN_INIT - s->high_water;
  1567. // if (init > s->window_size - s->high_water)
  1568. // init = s->window_size - s->high_water;
  1569. // zmemzero(s->window + s->high_water, (unsigned)init);
  1570. // s->high_water += init;
  1571. // }
  1572. // }
  1573. //
  1574. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  1575. // "not enough room for search");
  1576. };
  1577. /* ===========================================================================
  1578. * Copy without compression as much as possible from the input stream, return
  1579. * the current block state.
  1580. * This function does not insert new strings in the dictionary since
  1581. * uncompressible data is probably not useful. This function is used
  1582. * only for the level=0 compression option.
  1583. * NOTE: this function should be optimized to avoid extra copying from
  1584. * window to pending_buf.
  1585. */
  1586. const deflate_stored = (s, flush) => {
  1587. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  1588. * to pending_buf_size, and each stored block has a 5 byte header:
  1589. */
  1590. let max_block_size = 0xffff;
  1591. if (max_block_size > s.pending_buf_size - 5) {
  1592. max_block_size = s.pending_buf_size - 5;
  1593. }
  1594. /* Copy as much as possible from input to output: */
  1595. for (;;) {
  1596. /* Fill the window as much as possible: */
  1597. if (s.lookahead <= 1) {
  1598. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  1599. // s->block_start >= (long)s->w_size, "slide too late");
  1600. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  1601. // s.block_start >= s.w_size)) {
  1602. // throw new Error("slide too late");
  1603. // }
  1604. fill_window(s);
  1605. if (s.lookahead === 0 && flush === Z_NO_FLUSH$1) {
  1606. return BS_NEED_MORE;
  1607. }
  1608. if (s.lookahead === 0) {
  1609. break;
  1610. }
  1611. /* flush the current block */
  1612. }
  1613. //Assert(s->block_start >= 0L, "block gone");
  1614. // if (s.block_start < 0) throw new Error("block gone");
  1615. s.strstart += s.lookahead;
  1616. s.lookahead = 0;
  1617. /* Emit a stored block if pending_buf will be full: */
  1618. const max_start = s.block_start + max_block_size;
  1619. if (s.strstart === 0 || s.strstart >= max_start) {
  1620. /* strstart == 0 is possible when wraparound on 16-bit machine */
  1621. s.lookahead = s.strstart - max_start;
  1622. s.strstart = max_start;
  1623. /*** FLUSH_BLOCK(s, 0); ***/
  1624. flush_block_only(s, false);
  1625. if (s.strm.avail_out === 0) {
  1626. return BS_NEED_MORE;
  1627. }
  1628. /***/
  1629. }
  1630. /* Flush if we may have to slide, otherwise block_start may become
  1631. * negative and the data will be gone:
  1632. */
  1633. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  1634. /*** FLUSH_BLOCK(s, 0); ***/
  1635. flush_block_only(s, false);
  1636. if (s.strm.avail_out === 0) {
  1637. return BS_NEED_MORE;
  1638. }
  1639. /***/
  1640. }
  1641. }
  1642. s.insert = 0;
  1643. if (flush === Z_FINISH$1) {
  1644. /*** FLUSH_BLOCK(s, 1); ***/
  1645. flush_block_only(s, true);
  1646. if (s.strm.avail_out === 0) {
  1647. return BS_FINISH_STARTED;
  1648. }
  1649. /***/
  1650. return BS_FINISH_DONE;
  1651. }
  1652. if (s.strstart > s.block_start) {
  1653. /*** FLUSH_BLOCK(s, 0); ***/
  1654. flush_block_only(s, false);
  1655. if (s.strm.avail_out === 0) {
  1656. return BS_NEED_MORE;
  1657. }
  1658. /***/
  1659. }
  1660. return BS_NEED_MORE;
  1661. };
  1662. /* ===========================================================================
  1663. * Compress as much as possible from the input stream, return the current
  1664. * block state.
  1665. * This function does not perform lazy evaluation of matches and inserts
  1666. * new strings in the dictionary only for unmatched strings or for short
  1667. * matches. It is used only for the fast compression options.
  1668. */
  1669. const deflate_fast = (s, flush) => {
  1670. let hash_head; /* head of the hash chain */
  1671. let bflush; /* set if current block must be flushed */
  1672. for (;;) {
  1673. /* Make sure that we always have enough lookahead, except
  1674. * at the end of the input file. We need MAX_MATCH bytes
  1675. * for the next match, plus MIN_MATCH bytes to insert the
  1676. * string following the next match.
  1677. */
  1678. if (s.lookahead < MIN_LOOKAHEAD) {
  1679. fill_window(s);
  1680. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$1) {
  1681. return BS_NEED_MORE;
  1682. }
  1683. if (s.lookahead === 0) {
  1684. break; /* flush the current block */
  1685. }
  1686. }
  1687. /* Insert the string window[strstart .. strstart+2] in the
  1688. * dictionary, and set hash_head to the head of the hash chain:
  1689. */
  1690. hash_head = 0/*NIL*/;
  1691. if (s.lookahead >= MIN_MATCH) {
  1692. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  1693. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  1694. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  1695. s.head[s.ins_h] = s.strstart;
  1696. /***/
  1697. }
  1698. /* Find the longest match, discarding those <= prev_length.
  1699. * At this point we have always match_length < MIN_MATCH
  1700. */
  1701. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  1702. /* To simplify the code, we prevent matches with the string
  1703. * of window index 0 (in particular we have to avoid a match
  1704. * of the string with itself at the start of the input file).
  1705. */
  1706. s.match_length = longest_match(s, hash_head);
  1707. /* longest_match() sets match_start */
  1708. }
  1709. if (s.match_length >= MIN_MATCH) {
  1710. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  1711. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  1712. s.match_length - MIN_MATCH, bflush); ***/
  1713. bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  1714. s.lookahead -= s.match_length;
  1715. /* Insert new strings in the hash table only if the match length
  1716. * is not too large. This saves time but degrades compression.
  1717. */
  1718. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  1719. s.match_length--; /* string at strstart already in table */
  1720. do {
  1721. s.strstart++;
  1722. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  1723. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  1724. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  1725. s.head[s.ins_h] = s.strstart;
  1726. /***/
  1727. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1728. * always MIN_MATCH bytes ahead.
  1729. */
  1730. } while (--s.match_length !== 0);
  1731. s.strstart++;
  1732. } else
  1733. {
  1734. s.strstart += s.match_length;
  1735. s.match_length = 0;
  1736. s.ins_h = s.window[s.strstart];
  1737. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  1738. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);
  1739. //#if MIN_MATCH != 3
  1740. // Call UPDATE_HASH() MIN_MATCH-3 more times
  1741. //#endif
  1742. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1743. * matter since it will be recomputed at next deflate call.
  1744. */
  1745. }
  1746. } else {
  1747. /* No match, output a literal byte */
  1748. //Tracevv((stderr,"%c", s.window[s.strstart]));
  1749. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  1750. bflush = _tr_tally(s, 0, s.window[s.strstart]);
  1751. s.lookahead--;
  1752. s.strstart++;
  1753. }
  1754. if (bflush) {
  1755. /*** FLUSH_BLOCK(s, 0); ***/
  1756. flush_block_only(s, false);
  1757. if (s.strm.avail_out === 0) {
  1758. return BS_NEED_MORE;
  1759. }
  1760. /***/
  1761. }
  1762. }
  1763. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  1764. if (flush === Z_FINISH$1) {
  1765. /*** FLUSH_BLOCK(s, 1); ***/
  1766. flush_block_only(s, true);
  1767. if (s.strm.avail_out === 0) {
  1768. return BS_FINISH_STARTED;
  1769. }
  1770. /***/
  1771. return BS_FINISH_DONE;
  1772. }
  1773. if (s.last_lit) {
  1774. /*** FLUSH_BLOCK(s, 0); ***/
  1775. flush_block_only(s, false);
  1776. if (s.strm.avail_out === 0) {
  1777. return BS_NEED_MORE;
  1778. }
  1779. /***/
  1780. }
  1781. return BS_BLOCK_DONE;
  1782. };
  1783. /* ===========================================================================
  1784. * Same as above, but achieves better compression. We use a lazy
  1785. * evaluation for matches: a match is finally adopted only if there is
  1786. * no better match at the next window position.
  1787. */
  1788. const deflate_slow = (s, flush) => {
  1789. let hash_head; /* head of hash chain */
  1790. let bflush; /* set if current block must be flushed */
  1791. let max_insert;
  1792. /* Process the input block. */
  1793. for (;;) {
  1794. /* Make sure that we always have enough lookahead, except
  1795. * at the end of the input file. We need MAX_MATCH bytes
  1796. * for the next match, plus MIN_MATCH bytes to insert the
  1797. * string following the next match.
  1798. */
  1799. if (s.lookahead < MIN_LOOKAHEAD) {
  1800. fill_window(s);
  1801. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$1) {
  1802. return BS_NEED_MORE;
  1803. }
  1804. if (s.lookahead === 0) { break; } /* flush the current block */
  1805. }
  1806. /* Insert the string window[strstart .. strstart+2] in the
  1807. * dictionary, and set hash_head to the head of the hash chain:
  1808. */
  1809. hash_head = 0/*NIL*/;
  1810. if (s.lookahead >= MIN_MATCH) {
  1811. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  1812. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  1813. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  1814. s.head[s.ins_h] = s.strstart;
  1815. /***/
  1816. }
  1817. /* Find the longest match, discarding those <= prev_length.
  1818. */
  1819. s.prev_length = s.match_length;
  1820. s.prev_match = s.match_start;
  1821. s.match_length = MIN_MATCH - 1;
  1822. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  1823. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  1824. /* To simplify the code, we prevent matches with the string
  1825. * of window index 0 (in particular we have to avoid a match
  1826. * of the string with itself at the start of the input file).
  1827. */
  1828. s.match_length = longest_match(s, hash_head);
  1829. /* longest_match() sets match_start */
  1830. if (s.match_length <= 5 &&
  1831. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  1832. /* If prev_match is also MIN_MATCH, match_start is garbage
  1833. * but we will ignore the current match anyway.
  1834. */
  1835. s.match_length = MIN_MATCH - 1;
  1836. }
  1837. }
  1838. /* If there was a match at the previous step and the current
  1839. * match is not better, output the previous match:
  1840. */
  1841. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  1842. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  1843. /* Do not insert strings in hash table beyond this. */
  1844. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  1845. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  1846. s.prev_length - MIN_MATCH, bflush);***/
  1847. bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  1848. /* Insert in hash table all strings up to the end of the match.
  1849. * strstart-1 and strstart are already inserted. If there is not
  1850. * enough lookahead, the last two strings are not inserted in
  1851. * the hash table.
  1852. */
  1853. s.lookahead -= s.prev_length - 1;
  1854. s.prev_length -= 2;
  1855. do {
  1856. if (++s.strstart <= max_insert) {
  1857. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  1858. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  1859. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  1860. s.head[s.ins_h] = s.strstart;
  1861. /***/
  1862. }
  1863. } while (--s.prev_length !== 0);
  1864. s.match_available = 0;
  1865. s.match_length = MIN_MATCH - 1;
  1866. s.strstart++;
  1867. if (bflush) {
  1868. /*** FLUSH_BLOCK(s, 0); ***/
  1869. flush_block_only(s, false);
  1870. if (s.strm.avail_out === 0) {
  1871. return BS_NEED_MORE;
  1872. }
  1873. /***/
  1874. }
  1875. } else if (s.match_available) {
  1876. /* If there was no match at the previous position, output a
  1877. * single literal. If there was a match but the current match
  1878. * is longer, truncate the previous match to a single literal.
  1879. */
  1880. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1881. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  1882. bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
  1883. if (bflush) {
  1884. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  1885. flush_block_only(s, false);
  1886. /***/
  1887. }
  1888. s.strstart++;
  1889. s.lookahead--;
  1890. if (s.strm.avail_out === 0) {
  1891. return BS_NEED_MORE;
  1892. }
  1893. } else {
  1894. /* There is no previous match to compare with, wait for
  1895. * the next step to decide.
  1896. */
  1897. s.match_available = 1;
  1898. s.strstart++;
  1899. s.lookahead--;
  1900. }
  1901. }
  1902. //Assert (flush != Z_NO_FLUSH, "no flush?");
  1903. if (s.match_available) {
  1904. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1905. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  1906. bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
  1907. s.match_available = 0;
  1908. }
  1909. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  1910. if (flush === Z_FINISH$1) {
  1911. /*** FLUSH_BLOCK(s, 1); ***/
  1912. flush_block_only(s, true);
  1913. if (s.strm.avail_out === 0) {
  1914. return BS_FINISH_STARTED;
  1915. }
  1916. /***/
  1917. return BS_FINISH_DONE;
  1918. }
  1919. if (s.last_lit) {
  1920. /*** FLUSH_BLOCK(s, 0); ***/
  1921. flush_block_only(s, false);
  1922. if (s.strm.avail_out === 0) {
  1923. return BS_NEED_MORE;
  1924. }
  1925. /***/
  1926. }
  1927. return BS_BLOCK_DONE;
  1928. };
  1929. /* ===========================================================================
  1930. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  1931. * one. Do not maintain a hash table. (It will be regenerated if this run of
  1932. * deflate switches away from Z_RLE.)
  1933. */
  1934. const deflate_rle = (s, flush) => {
  1935. let bflush; /* set if current block must be flushed */
  1936. let prev; /* byte at distance one to match */
  1937. let scan, strend; /* scan goes up to strend for length of run */
  1938. const _win = s.window;
  1939. for (;;) {
  1940. /* Make sure that we always have enough lookahead, except
  1941. * at the end of the input file. We need MAX_MATCH bytes
  1942. * for the longest run, plus one for the unrolled loop.
  1943. */
  1944. if (s.lookahead <= MAX_MATCH) {
  1945. fill_window(s);
  1946. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$1) {
  1947. return BS_NEED_MORE;
  1948. }
  1949. if (s.lookahead === 0) { break; } /* flush the current block */
  1950. }
  1951. /* See how many times the previous byte repeats */
  1952. s.match_length = 0;
  1953. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  1954. scan = s.strstart - 1;
  1955. prev = _win[scan];
  1956. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  1957. strend = s.strstart + MAX_MATCH;
  1958. do {
  1959. /*jshint noempty:false*/
  1960. } while (prev === _win[++scan] && prev === _win[++scan] &&
  1961. prev === _win[++scan] && prev === _win[++scan] &&
  1962. prev === _win[++scan] && prev === _win[++scan] &&
  1963. prev === _win[++scan] && prev === _win[++scan] &&
  1964. scan < strend);
  1965. s.match_length = MAX_MATCH - (strend - scan);
  1966. if (s.match_length > s.lookahead) {
  1967. s.match_length = s.lookahead;
  1968. }
  1969. }
  1970. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  1971. }
  1972. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  1973. if (s.match_length >= MIN_MATCH) {
  1974. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  1975. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  1976. bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);
  1977. s.lookahead -= s.match_length;
  1978. s.strstart += s.match_length;
  1979. s.match_length = 0;
  1980. } else {
  1981. /* No match, output a literal byte */
  1982. //Tracevv((stderr,"%c", s->window[s->strstart]));
  1983. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  1984. bflush = _tr_tally(s, 0, s.window[s.strstart]);
  1985. s.lookahead--;
  1986. s.strstart++;
  1987. }
  1988. if (bflush) {
  1989. /*** FLUSH_BLOCK(s, 0); ***/
  1990. flush_block_only(s, false);
  1991. if (s.strm.avail_out === 0) {
  1992. return BS_NEED_MORE;
  1993. }
  1994. /***/
  1995. }
  1996. }
  1997. s.insert = 0;
  1998. if (flush === Z_FINISH$1) {
  1999. /*** FLUSH_BLOCK(s, 1); ***/
  2000. flush_block_only(s, true);
  2001. if (s.strm.avail_out === 0) {
  2002. return BS_FINISH_STARTED;
  2003. }
  2004. /***/
  2005. return BS_FINISH_DONE;
  2006. }
  2007. if (s.last_lit) {
  2008. /*** FLUSH_BLOCK(s, 0); ***/
  2009. flush_block_only(s, false);
  2010. if (s.strm.avail_out === 0) {
  2011. return BS_NEED_MORE;
  2012. }
  2013. /***/
  2014. }
  2015. return BS_BLOCK_DONE;
  2016. };
  2017. /* ===========================================================================
  2018. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  2019. * (It will be regenerated if this run of deflate switches away from Huffman.)
  2020. */
  2021. const deflate_huff = (s, flush) => {
  2022. let bflush; /* set if current block must be flushed */
  2023. for (;;) {
  2024. /* Make sure that we have a literal to write. */
  2025. if (s.lookahead === 0) {
  2026. fill_window(s);
  2027. if (s.lookahead === 0) {
  2028. if (flush === Z_NO_FLUSH$1) {
  2029. return BS_NEED_MORE;
  2030. }
  2031. break; /* flush the current block */
  2032. }
  2033. }
  2034. /* Output a literal byte */
  2035. s.match_length = 0;
  2036. //Tracevv((stderr,"%c", s->window[s->strstart]));
  2037. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  2038. bflush = _tr_tally(s, 0, s.window[s.strstart]);
  2039. s.lookahead--;
  2040. s.strstart++;
  2041. if (bflush) {
  2042. /*** FLUSH_BLOCK(s, 0); ***/
  2043. flush_block_only(s, false);
  2044. if (s.strm.avail_out === 0) {
  2045. return BS_NEED_MORE;
  2046. }
  2047. /***/
  2048. }
  2049. }
  2050. s.insert = 0;
  2051. if (flush === Z_FINISH$1) {
  2052. /*** FLUSH_BLOCK(s, 1); ***/
  2053. flush_block_only(s, true);
  2054. if (s.strm.avail_out === 0) {
  2055. return BS_FINISH_STARTED;
  2056. }
  2057. /***/
  2058. return BS_FINISH_DONE;
  2059. }
  2060. if (s.last_lit) {
  2061. /*** FLUSH_BLOCK(s, 0); ***/
  2062. flush_block_only(s, false);
  2063. if (s.strm.avail_out === 0) {
  2064. return BS_NEED_MORE;
  2065. }
  2066. /***/
  2067. }
  2068. return BS_BLOCK_DONE;
  2069. };
  2070. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  2071. * the desired pack level (0..9). The values given below have been tuned to
  2072. * exclude worst case performance for pathological files. Better values may be
  2073. * found for specific files.
  2074. */
  2075. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  2076. this.good_length = good_length;
  2077. this.max_lazy = max_lazy;
  2078. this.nice_length = nice_length;
  2079. this.max_chain = max_chain;
  2080. this.func = func;
  2081. }
  2082. const configuration_table = [
  2083. /* good lazy nice chain */
  2084. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  2085. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  2086. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  2087. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  2088. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  2089. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  2090. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  2091. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  2092. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  2093. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  2094. ];
  2095. /* ===========================================================================
  2096. * Initialize the "longest match" routines for a new zlib stream
  2097. */
  2098. const lm_init = (s) => {
  2099. s.window_size = 2 * s.w_size;
  2100. /*** CLEAR_HASH(s); ***/
  2101. zero(s.head); // Fill with NIL (= 0);
  2102. /* Set the default configuration parameters:
  2103. */
  2104. s.max_lazy_match = configuration_table[s.level].max_lazy;
  2105. s.good_match = configuration_table[s.level].good_length;
  2106. s.nice_match = configuration_table[s.level].nice_length;
  2107. s.max_chain_length = configuration_table[s.level].max_chain;
  2108. s.strstart = 0;
  2109. s.block_start = 0;
  2110. s.lookahead = 0;
  2111. s.insert = 0;
  2112. s.match_length = s.prev_length = MIN_MATCH - 1;
  2113. s.match_available = 0;
  2114. s.ins_h = 0;
  2115. };
  2116. function DeflateState() {
  2117. this.strm = null; /* pointer back to this zlib stream */
  2118. this.status = 0; /* as the name implies */
  2119. this.pending_buf = null; /* output still pending */
  2120. this.pending_buf_size = 0; /* size of pending_buf */
  2121. this.pending_out = 0; /* next pending byte to output to the stream */
  2122. this.pending = 0; /* nb of bytes in the pending buffer */
  2123. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  2124. this.gzhead = null; /* gzip header information to write */
  2125. this.gzindex = 0; /* where in extra, name, or comment */
  2126. this.method = Z_DEFLATED$1; /* can only be DEFLATED */
  2127. this.last_flush = -1; /* value of flush param for previous deflate call */
  2128. this.w_size = 0; /* LZ77 window size (32K by default) */
  2129. this.w_bits = 0; /* log2(w_size) (8..16) */
  2130. this.w_mask = 0; /* w_size - 1 */
  2131. this.window = null;
  2132. /* Sliding window. Input bytes are read into the second half of the window,
  2133. * and move to the first half later to keep a dictionary of at least wSize
  2134. * bytes. With this organization, matches are limited to a distance of
  2135. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  2136. * performed with a length multiple of the block size.
  2137. */
  2138. this.window_size = 0;
  2139. /* Actual size of window: 2*wSize, except when the user input buffer
  2140. * is directly used as sliding window.
  2141. */
  2142. this.prev = null;
  2143. /* Link to older string with same hash index. To limit the size of this
  2144. * array to 64K, this link is maintained only for the last 32K strings.
  2145. * An index in this array is thus a window index modulo 32K.
  2146. */
  2147. this.head = null; /* Heads of the hash chains or NIL. */
  2148. this.ins_h = 0; /* hash index of string to be inserted */
  2149. this.hash_size = 0; /* number of elements in hash table */
  2150. this.hash_bits = 0; /* log2(hash_size) */
  2151. this.hash_mask = 0; /* hash_size-1 */
  2152. this.hash_shift = 0;
  2153. /* Number of bits by which ins_h must be shifted at each input
  2154. * step. It must be such that after MIN_MATCH steps, the oldest
  2155. * byte no longer takes part in the hash key, that is:
  2156. * hash_shift * MIN_MATCH >= hash_bits
  2157. */
  2158. this.block_start = 0;
  2159. /* Window position at the beginning of the current output block. Gets
  2160. * negative when the window is moved backwards.
  2161. */
  2162. this.match_length = 0; /* length of best match */
  2163. this.prev_match = 0; /* previous match */
  2164. this.match_available = 0; /* set if previous match exists */
  2165. this.strstart = 0; /* start of string to insert */
  2166. this.match_start = 0; /* start of matching string */
  2167. this.lookahead = 0; /* number of valid bytes ahead in window */
  2168. this.prev_length = 0;
  2169. /* Length of the best match at previous step. Matches not greater than this
  2170. * are discarded. This is used in the lazy match evaluation.
  2171. */
  2172. this.max_chain_length = 0;
  2173. /* To speed up deflation, hash chains are never searched beyond this
  2174. * length. A higher limit improves compression ratio but degrades the
  2175. * speed.
  2176. */
  2177. this.max_lazy_match = 0;
  2178. /* Attempt to find a better match only when the current match is strictly
  2179. * smaller than this value. This mechanism is used only for compression
  2180. * levels >= 4.
  2181. */
  2182. // That's alias to max_lazy_match, don't use directly
  2183. //this.max_insert_length = 0;
  2184. /* Insert new strings in the hash table only if the match length is not
  2185. * greater than this length. This saves time but degrades compression.
  2186. * max_insert_length is used only for compression levels <= 3.
  2187. */
  2188. this.level = 0; /* compression level (1..9) */
  2189. this.strategy = 0; /* favor or force Huffman coding*/
  2190. this.good_match = 0;
  2191. /* Use a faster search when the previous match is longer than this */
  2192. this.nice_match = 0; /* Stop searching when current match exceeds this */
  2193. /* used by trees.c: */
  2194. /* Didn't use ct_data typedef below to suppress compiler warning */
  2195. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  2196. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  2197. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  2198. // Use flat array of DOUBLE size, with interleaved fata,
  2199. // because JS does not support effective
  2200. this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2);
  2201. this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);
  2202. this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2);
  2203. zero(this.dyn_ltree);
  2204. zero(this.dyn_dtree);
  2205. zero(this.bl_tree);
  2206. this.l_desc = null; /* desc. for literal tree */
  2207. this.d_desc = null; /* desc. for distance tree */
  2208. this.bl_desc = null; /* desc. for bit length tree */
  2209. //ush bl_count[MAX_BITS+1];
  2210. this.bl_count = new Uint16Array(MAX_BITS + 1);
  2211. /* number of codes at each bit length for an optimal tree */
  2212. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  2213. this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  2214. zero(this.heap);
  2215. this.heap_len = 0; /* number of elements in the heap */
  2216. this.heap_max = 0; /* element of largest frequency */
  2217. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  2218. * The same heap array is used to build all trees.
  2219. */
  2220. this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  2221. zero(this.depth);
  2222. /* Depth of each subtree used as tie breaker for trees of equal frequency
  2223. */
  2224. this.l_buf = 0; /* buffer index for literals or lengths */
  2225. this.lit_bufsize = 0;
  2226. /* Size of match buffer for literals/lengths. There are 4 reasons for
  2227. * limiting lit_bufsize to 64K:
  2228. * - frequencies can be kept in 16 bit counters
  2229. * - if compression is not successful for the first block, all input
  2230. * data is still in the window so we can still emit a stored block even
  2231. * when input comes from standard input. (This can also be done for
  2232. * all blocks if lit_bufsize is not greater than 32K.)
  2233. * - if compression is not successful for a file smaller than 64K, we can
  2234. * even emit a stored file instead of a stored block (saving 5 bytes).
  2235. * This is applicable only for zip (not gzip or zlib).
  2236. * - creating new Huffman trees less frequently may not provide fast
  2237. * adaptation to changes in the input data statistics. (Take for
  2238. * example a binary file with poorly compressible code followed by
  2239. * a highly compressible string table.) Smaller buffer sizes give
  2240. * fast adaptation but have of course the overhead of transmitting
  2241. * trees more frequently.
  2242. * - I can't count above 4
  2243. */
  2244. this.last_lit = 0; /* running index in l_buf */
  2245. this.d_buf = 0;
  2246. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  2247. * the same number of elements. To use different lengths, an extra flag
  2248. * array would be necessary.
  2249. */
  2250. this.opt_len = 0; /* bit length of current block with optimal trees */
  2251. this.static_len = 0; /* bit length of current block with static trees */
  2252. this.matches = 0; /* number of string matches in current block */
  2253. this.insert = 0; /* bytes at end of window left to insert */
  2254. this.bi_buf = 0;
  2255. /* Output buffer. bits are inserted starting at the bottom (least
  2256. * significant bits).
  2257. */
  2258. this.bi_valid = 0;
  2259. /* Number of valid bits in bi_buf. All bits above the last valid bit
  2260. * are always zero.
  2261. */
  2262. // Used for window memory init. We safely ignore it for JS. That makes
  2263. // sense only for pointers and memory check tools.
  2264. //this.high_water = 0;
  2265. /* High water mark offset in window for initialized bytes -- bytes above
  2266. * this are set to zero in order to avoid memory check warnings when
  2267. * longest match routines access bytes past the input. This is then
  2268. * updated to the new high water mark.
  2269. */
  2270. }
  2271. const deflateResetKeep = (strm) => {
  2272. if (!strm || !strm.state) {
  2273. return err(strm, Z_STREAM_ERROR);
  2274. }
  2275. strm.total_in = strm.total_out = 0;
  2276. strm.data_type = Z_UNKNOWN;
  2277. const s = strm.state;
  2278. s.pending = 0;
  2279. s.pending_out = 0;
  2280. if (s.wrap < 0) {
  2281. s.wrap = -s.wrap;
  2282. /* was made negative by deflate(..., Z_FINISH); */
  2283. }
  2284. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  2285. strm.adler = (s.wrap === 2) ?
  2286. 0 // crc32(0, Z_NULL, 0)
  2287. :
  2288. 1; // adler32(0, Z_NULL, 0)
  2289. s.last_flush = Z_NO_FLUSH$1;
  2290. _tr_init(s);
  2291. return Z_OK$1;
  2292. };
  2293. const deflateReset = (strm) => {
  2294. const ret = deflateResetKeep(strm);
  2295. if (ret === Z_OK$1) {
  2296. lm_init(strm.state);
  2297. }
  2298. return ret;
  2299. };
  2300. const deflateSetHeader = (strm, head) => {
  2301. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  2302. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  2303. strm.state.gzhead = head;
  2304. return Z_OK$1;
  2305. };
  2306. const deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {
  2307. if (!strm) { // === Z_NULL
  2308. return Z_STREAM_ERROR;
  2309. }
  2310. let wrap = 1;
  2311. if (level === Z_DEFAULT_COMPRESSION$1) {
  2312. level = 6;
  2313. }
  2314. if (windowBits < 0) { /* suppress zlib wrapper */
  2315. wrap = 0;
  2316. windowBits = -windowBits;
  2317. }
  2318. else if (windowBits > 15) {
  2319. wrap = 2; /* write gzip wrapper instead */
  2320. windowBits -= 16;
  2321. }
  2322. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$1 ||
  2323. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  2324. strategy < 0 || strategy > Z_FIXED) {
  2325. return err(strm, Z_STREAM_ERROR);
  2326. }
  2327. if (windowBits === 8) {
  2328. windowBits = 9;
  2329. }
  2330. /* until 256-byte window bug fixed */
  2331. const s = new DeflateState();
  2332. strm.state = s;
  2333. s.strm = strm;
  2334. s.wrap = wrap;
  2335. s.gzhead = null;
  2336. s.w_bits = windowBits;
  2337. s.w_size = 1 << s.w_bits;
  2338. s.w_mask = s.w_size - 1;
  2339. s.hash_bits = memLevel + 7;
  2340. s.hash_size = 1 << s.hash_bits;
  2341. s.hash_mask = s.hash_size - 1;
  2342. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  2343. s.window = new Uint8Array(s.w_size * 2);
  2344. s.head = new Uint16Array(s.hash_size);
  2345. s.prev = new Uint16Array(s.w_size);
  2346. // Don't need mem init magic for JS.
  2347. //s.high_water = 0; /* nothing written to s->window yet */
  2348. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  2349. s.pending_buf_size = s.lit_bufsize * 4;
  2350. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  2351. //s->pending_buf = (uchf *) overlay;
  2352. s.pending_buf = new Uint8Array(s.pending_buf_size);
  2353. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  2354. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  2355. s.d_buf = 1 * s.lit_bufsize;
  2356. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  2357. s.l_buf = (1 + 2) * s.lit_bufsize;
  2358. s.level = level;
  2359. s.strategy = strategy;
  2360. s.method = method;
  2361. return deflateReset(strm);
  2362. };
  2363. const deflateInit = (strm, level) => {
  2364. return deflateInit2(strm, level, Z_DEFLATED$1, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);
  2365. };
  2366. const deflate$1 = (strm, flush) => {
  2367. let beg, val; // for gzip header write only
  2368. if (!strm || !strm.state ||
  2369. flush > Z_BLOCK || flush < 0) {
  2370. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  2371. }
  2372. const s = strm.state;
  2373. if (!strm.output ||
  2374. (!strm.input && strm.avail_in !== 0) ||
  2375. (s.status === FINISH_STATE && flush !== Z_FINISH$1)) {
  2376. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  2377. }
  2378. s.strm = strm; /* just in case */
  2379. const old_flush = s.last_flush;
  2380. s.last_flush = flush;
  2381. /* Write the header */
  2382. if (s.status === INIT_STATE) {
  2383. if (s.wrap === 2) { // GZIP header
  2384. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  2385. put_byte(s, 31);
  2386. put_byte(s, 139);
  2387. put_byte(s, 8);
  2388. if (!s.gzhead) { // s->gzhead == Z_NULL
  2389. put_byte(s, 0);
  2390. put_byte(s, 0);
  2391. put_byte(s, 0);
  2392. put_byte(s, 0);
  2393. put_byte(s, 0);
  2394. put_byte(s, s.level === 9 ? 2 :
  2395. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  2396. 4 : 0));
  2397. put_byte(s, OS_CODE);
  2398. s.status = BUSY_STATE;
  2399. }
  2400. else {
  2401. put_byte(s, (s.gzhead.text ? 1 : 0) +
  2402. (s.gzhead.hcrc ? 2 : 0) +
  2403. (!s.gzhead.extra ? 0 : 4) +
  2404. (!s.gzhead.name ? 0 : 8) +
  2405. (!s.gzhead.comment ? 0 : 16)
  2406. );
  2407. put_byte(s, s.gzhead.time & 0xff);
  2408. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  2409. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  2410. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  2411. put_byte(s, s.level === 9 ? 2 :
  2412. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  2413. 4 : 0));
  2414. put_byte(s, s.gzhead.os & 0xff);
  2415. if (s.gzhead.extra && s.gzhead.extra.length) {
  2416. put_byte(s, s.gzhead.extra.length & 0xff);
  2417. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  2418. }
  2419. if (s.gzhead.hcrc) {
  2420. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);
  2421. }
  2422. s.gzindex = 0;
  2423. s.status = EXTRA_STATE;
  2424. }
  2425. }
  2426. else // DEFLATE header
  2427. {
  2428. let header = (Z_DEFLATED$1 + ((s.w_bits - 8) << 4)) << 8;
  2429. let level_flags = -1;
  2430. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  2431. level_flags = 0;
  2432. } else if (s.level < 6) {
  2433. level_flags = 1;
  2434. } else if (s.level === 6) {
  2435. level_flags = 2;
  2436. } else {
  2437. level_flags = 3;
  2438. }
  2439. header |= (level_flags << 6);
  2440. if (s.strstart !== 0) { header |= PRESET_DICT; }
  2441. header += 31 - (header % 31);
  2442. s.status = BUSY_STATE;
  2443. putShortMSB(s, header);
  2444. /* Save the adler32 of the preset dictionary: */
  2445. if (s.strstart !== 0) {
  2446. putShortMSB(s, strm.adler >>> 16);
  2447. putShortMSB(s, strm.adler & 0xffff);
  2448. }
  2449. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  2450. }
  2451. }
  2452. //#ifdef GZIP
  2453. if (s.status === EXTRA_STATE) {
  2454. if (s.gzhead.extra/* != Z_NULL*/) {
  2455. beg = s.pending; /* start of bytes to update crc */
  2456. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  2457. if (s.pending === s.pending_buf_size) {
  2458. if (s.gzhead.hcrc && s.pending > beg) {
  2459. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2460. }
  2461. flush_pending(strm);
  2462. beg = s.pending;
  2463. if (s.pending === s.pending_buf_size) {
  2464. break;
  2465. }
  2466. }
  2467. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  2468. s.gzindex++;
  2469. }
  2470. if (s.gzhead.hcrc && s.pending > beg) {
  2471. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2472. }
  2473. if (s.gzindex === s.gzhead.extra.length) {
  2474. s.gzindex = 0;
  2475. s.status = NAME_STATE;
  2476. }
  2477. }
  2478. else {
  2479. s.status = NAME_STATE;
  2480. }
  2481. }
  2482. if (s.status === NAME_STATE) {
  2483. if (s.gzhead.name/* != Z_NULL*/) {
  2484. beg = s.pending; /* start of bytes to update crc */
  2485. //int val;
  2486. do {
  2487. if (s.pending === s.pending_buf_size) {
  2488. if (s.gzhead.hcrc && s.pending > beg) {
  2489. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2490. }
  2491. flush_pending(strm);
  2492. beg = s.pending;
  2493. if (s.pending === s.pending_buf_size) {
  2494. val = 1;
  2495. break;
  2496. }
  2497. }
  2498. // JS specific: little magic to add zero terminator to end of string
  2499. if (s.gzindex < s.gzhead.name.length) {
  2500. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  2501. } else {
  2502. val = 0;
  2503. }
  2504. put_byte(s, val);
  2505. } while (val !== 0);
  2506. if (s.gzhead.hcrc && s.pending > beg) {
  2507. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2508. }
  2509. if (val === 0) {
  2510. s.gzindex = 0;
  2511. s.status = COMMENT_STATE;
  2512. }
  2513. }
  2514. else {
  2515. s.status = COMMENT_STATE;
  2516. }
  2517. }
  2518. if (s.status === COMMENT_STATE) {
  2519. if (s.gzhead.comment/* != Z_NULL*/) {
  2520. beg = s.pending; /* start of bytes to update crc */
  2521. //int val;
  2522. do {
  2523. if (s.pending === s.pending_buf_size) {
  2524. if (s.gzhead.hcrc && s.pending > beg) {
  2525. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2526. }
  2527. flush_pending(strm);
  2528. beg = s.pending;
  2529. if (s.pending === s.pending_buf_size) {
  2530. val = 1;
  2531. break;
  2532. }
  2533. }
  2534. // JS specific: little magic to add zero terminator to end of string
  2535. if (s.gzindex < s.gzhead.comment.length) {
  2536. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  2537. } else {
  2538. val = 0;
  2539. }
  2540. put_byte(s, val);
  2541. } while (val !== 0);
  2542. if (s.gzhead.hcrc && s.pending > beg) {
  2543. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2544. }
  2545. if (val === 0) {
  2546. s.status = HCRC_STATE;
  2547. }
  2548. }
  2549. else {
  2550. s.status = HCRC_STATE;
  2551. }
  2552. }
  2553. if (s.status === HCRC_STATE) {
  2554. if (s.gzhead.hcrc) {
  2555. if (s.pending + 2 > s.pending_buf_size) {
  2556. flush_pending(strm);
  2557. }
  2558. if (s.pending + 2 <= s.pending_buf_size) {
  2559. put_byte(s, strm.adler & 0xff);
  2560. put_byte(s, (strm.adler >> 8) & 0xff);
  2561. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  2562. s.status = BUSY_STATE;
  2563. }
  2564. }
  2565. else {
  2566. s.status = BUSY_STATE;
  2567. }
  2568. }
  2569. //#endif
  2570. /* Flush as much pending output as possible */
  2571. if (s.pending !== 0) {
  2572. flush_pending(strm);
  2573. if (strm.avail_out === 0) {
  2574. /* Since avail_out is 0, deflate will be called again with
  2575. * more output space, but possibly with both pending and
  2576. * avail_in equal to zero. There won't be anything to do,
  2577. * but this is not an error situation so make sure we
  2578. * return OK instead of BUF_ERROR at next call of deflate:
  2579. */
  2580. s.last_flush = -1;
  2581. return Z_OK$1;
  2582. }
  2583. /* Make sure there is something to do and avoid duplicate consecutive
  2584. * flushes. For repeated and useless calls with Z_FINISH, we keep
  2585. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  2586. */
  2587. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  2588. flush !== Z_FINISH$1) {
  2589. return err(strm, Z_BUF_ERROR);
  2590. }
  2591. /* User must not provide more input after the first FINISH: */
  2592. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  2593. return err(strm, Z_BUF_ERROR);
  2594. }
  2595. /* Start a new block or continue the current one.
  2596. */
  2597. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  2598. (flush !== Z_NO_FLUSH$1 && s.status !== FINISH_STATE)) {
  2599. let bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  2600. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  2601. configuration_table[s.level].func(s, flush));
  2602. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  2603. s.status = FINISH_STATE;
  2604. }
  2605. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  2606. if (strm.avail_out === 0) {
  2607. s.last_flush = -1;
  2608. /* avoid BUF_ERROR next call, see above */
  2609. }
  2610. return Z_OK$1;
  2611. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  2612. * of deflate should use the same flush parameter to make sure
  2613. * that the flush is complete. So we don't have to output an
  2614. * empty block here, this will be done at next call. This also
  2615. * ensures that for a very small output buffer, we emit at most
  2616. * one empty block.
  2617. */
  2618. }
  2619. if (bstate === BS_BLOCK_DONE) {
  2620. if (flush === Z_PARTIAL_FLUSH) {
  2621. _tr_align(s);
  2622. }
  2623. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  2624. _tr_stored_block(s, 0, 0, false);
  2625. /* For a full flush, this empty block will be recognized
  2626. * as a special marker by inflate_sync().
  2627. */
  2628. if (flush === Z_FULL_FLUSH$1) {
  2629. /*** CLEAR_HASH(s); ***/ /* forget history */
  2630. zero(s.head); // Fill with NIL (= 0);
  2631. if (s.lookahead === 0) {
  2632. s.strstart = 0;
  2633. s.block_start = 0;
  2634. s.insert = 0;
  2635. }
  2636. }
  2637. }
  2638. flush_pending(strm);
  2639. if (strm.avail_out === 0) {
  2640. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  2641. return Z_OK$1;
  2642. }
  2643. }
  2644. }
  2645. //Assert(strm->avail_out > 0, "bug2");
  2646. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  2647. if (flush !== Z_FINISH$1) { return Z_OK$1; }
  2648. if (s.wrap <= 0) { return Z_STREAM_END$1; }
  2649. /* Write the trailer */
  2650. if (s.wrap === 2) {
  2651. put_byte(s, strm.adler & 0xff);
  2652. put_byte(s, (strm.adler >> 8) & 0xff);
  2653. put_byte(s, (strm.adler >> 16) & 0xff);
  2654. put_byte(s, (strm.adler >> 24) & 0xff);
  2655. put_byte(s, strm.total_in & 0xff);
  2656. put_byte(s, (strm.total_in >> 8) & 0xff);
  2657. put_byte(s, (strm.total_in >> 16) & 0xff);
  2658. put_byte(s, (strm.total_in >> 24) & 0xff);
  2659. }
  2660. else
  2661. {
  2662. putShortMSB(s, strm.adler >>> 16);
  2663. putShortMSB(s, strm.adler & 0xffff);
  2664. }
  2665. flush_pending(strm);
  2666. /* If avail_out is zero, the application will call deflate again
  2667. * to flush the rest.
  2668. */
  2669. if (s.wrap > 0) { s.wrap = -s.wrap; }
  2670. /* write the trailer only once! */
  2671. return s.pending !== 0 ? Z_OK$1 : Z_STREAM_END$1;
  2672. };
  2673. const deflateEnd = (strm) => {
  2674. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  2675. return Z_STREAM_ERROR;
  2676. }
  2677. const status = strm.state.status;
  2678. if (status !== INIT_STATE &&
  2679. status !== EXTRA_STATE &&
  2680. status !== NAME_STATE &&
  2681. status !== COMMENT_STATE &&
  2682. status !== HCRC_STATE &&
  2683. status !== BUSY_STATE &&
  2684. status !== FINISH_STATE
  2685. ) {
  2686. return err(strm, Z_STREAM_ERROR);
  2687. }
  2688. strm.state = null;
  2689. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK$1;
  2690. };
  2691. /* =========================================================================
  2692. * Initializes the compression dictionary from the given byte
  2693. * sequence without producing any compressed output.
  2694. */
  2695. const deflateSetDictionary = (strm, dictionary) => {
  2696. let dictLength = dictionary.length;
  2697. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  2698. return Z_STREAM_ERROR;
  2699. }
  2700. const s = strm.state;
  2701. const wrap = s.wrap;
  2702. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  2703. return Z_STREAM_ERROR;
  2704. }
  2705. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  2706. if (wrap === 1) {
  2707. /* adler32(strm->adler, dictionary, dictLength); */
  2708. strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);
  2709. }
  2710. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  2711. /* if dictionary would fill window, just replace the history */
  2712. if (dictLength >= s.w_size) {
  2713. if (wrap === 0) { /* already empty otherwise */
  2714. /*** CLEAR_HASH(s); ***/
  2715. zero(s.head); // Fill with NIL (= 0);
  2716. s.strstart = 0;
  2717. s.block_start = 0;
  2718. s.insert = 0;
  2719. }
  2720. /* use the tail */
  2721. // dictionary = dictionary.slice(dictLength - s.w_size);
  2722. let tmpDict = new Uint8Array(s.w_size);
  2723. tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);
  2724. dictionary = tmpDict;
  2725. dictLength = s.w_size;
  2726. }
  2727. /* insert dictionary into window and hash */
  2728. const avail = strm.avail_in;
  2729. const next = strm.next_in;
  2730. const input = strm.input;
  2731. strm.avail_in = dictLength;
  2732. strm.next_in = 0;
  2733. strm.input = dictionary;
  2734. fill_window(s);
  2735. while (s.lookahead >= MIN_MATCH) {
  2736. let str = s.strstart;
  2737. let n = s.lookahead - (MIN_MATCH - 1);
  2738. do {
  2739. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  2740. s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
  2741. s.prev[str & s.w_mask] = s.head[s.ins_h];
  2742. s.head[s.ins_h] = str;
  2743. str++;
  2744. } while (--n);
  2745. s.strstart = str;
  2746. s.lookahead = MIN_MATCH - 1;
  2747. fill_window(s);
  2748. }
  2749. s.strstart += s.lookahead;
  2750. s.block_start = s.strstart;
  2751. s.insert = s.lookahead;
  2752. s.lookahead = 0;
  2753. s.match_length = s.prev_length = MIN_MATCH - 1;
  2754. s.match_available = 0;
  2755. strm.next_in = next;
  2756. strm.input = input;
  2757. strm.avail_in = avail;
  2758. s.wrap = wrap;
  2759. return Z_OK$1;
  2760. };
  2761. var deflateInit_1 = deflateInit;
  2762. var deflateInit2_1 = deflateInit2;
  2763. var deflateReset_1 = deflateReset;
  2764. var deflateResetKeep_1 = deflateResetKeep;
  2765. var deflateSetHeader_1 = deflateSetHeader;
  2766. var deflate_2$1 = deflate$1;
  2767. var deflateEnd_1 = deflateEnd;
  2768. var deflateSetDictionary_1 = deflateSetDictionary;
  2769. var deflateInfo = 'pako deflate (from Nodeca project)';
  2770. /* Not implemented
  2771. module.exports.deflateBound = deflateBound;
  2772. module.exports.deflateCopy = deflateCopy;
  2773. module.exports.deflateParams = deflateParams;
  2774. module.exports.deflatePending = deflatePending;
  2775. module.exports.deflatePrime = deflatePrime;
  2776. module.exports.deflateTune = deflateTune;
  2777. */
  2778. var deflate_1$1 = {
  2779. deflateInit: deflateInit_1,
  2780. deflateInit2: deflateInit2_1,
  2781. deflateReset: deflateReset_1,
  2782. deflateResetKeep: deflateResetKeep_1,
  2783. deflateSetHeader: deflateSetHeader_1,
  2784. deflate: deflate_2$1,
  2785. deflateEnd: deflateEnd_1,
  2786. deflateSetDictionary: deflateSetDictionary_1,
  2787. deflateInfo: deflateInfo
  2788. };
  2789. const _has = (obj, key) => {
  2790. return Object.prototype.hasOwnProperty.call(obj, key);
  2791. };
  2792. var assign = function (obj /*from1, from2, from3, ...*/) {
  2793. const sources = Array.prototype.slice.call(arguments, 1);
  2794. while (sources.length) {
  2795. const source = sources.shift();
  2796. if (!source) { continue; }
  2797. if (typeof source !== 'object') {
  2798. throw new TypeError(source + 'must be non-object');
  2799. }
  2800. for (const p in source) {
  2801. if (_has(source, p)) {
  2802. obj[p] = source[p];
  2803. }
  2804. }
  2805. }
  2806. return obj;
  2807. };
  2808. // Join array of chunks to single array.
  2809. var flattenChunks = (chunks) => {
  2810. // calculate data length
  2811. let len = 0;
  2812. for (let i = 0, l = chunks.length; i < l; i++) {
  2813. len += chunks[i].length;
  2814. }
  2815. // join chunks
  2816. const result = new Uint8Array(len);
  2817. for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {
  2818. let chunk = chunks[i];
  2819. result.set(chunk, pos);
  2820. pos += chunk.length;
  2821. }
  2822. return result;
  2823. };
  2824. var common = {
  2825. assign: assign,
  2826. flattenChunks: flattenChunks
  2827. };
  2828. // String encode/decode helpers
  2829. // Quick check if we can use fast array to bin string conversion
  2830. //
  2831. // - apply(Array) can fail on Android 2.2
  2832. // - apply(Uint8Array) can fail on iOS 5.1 Safari
  2833. //
  2834. let STR_APPLY_UIA_OK = true;
  2835. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  2836. // Table with utf8 lengths (calculated by first byte of sequence)
  2837. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  2838. // because max possible codepoint is 0x10ffff
  2839. const _utf8len = new Uint8Array(256);
  2840. for (let q = 0; q < 256; q++) {
  2841. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  2842. }
  2843. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  2844. // convert string to array (typed, when possible)
  2845. var string2buf = (str) => {
  2846. if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {
  2847. return new TextEncoder().encode(str);
  2848. }
  2849. let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  2850. // count binary size
  2851. for (m_pos = 0; m_pos < str_len; m_pos++) {
  2852. c = str.charCodeAt(m_pos);
  2853. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  2854. c2 = str.charCodeAt(m_pos + 1);
  2855. if ((c2 & 0xfc00) === 0xdc00) {
  2856. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2857. m_pos++;
  2858. }
  2859. }
  2860. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  2861. }
  2862. // allocate buffer
  2863. buf = new Uint8Array(buf_len);
  2864. // convert
  2865. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  2866. c = str.charCodeAt(m_pos);
  2867. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  2868. c2 = str.charCodeAt(m_pos + 1);
  2869. if ((c2 & 0xfc00) === 0xdc00) {
  2870. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2871. m_pos++;
  2872. }
  2873. }
  2874. if (c < 0x80) {
  2875. /* one byte */
  2876. buf[i++] = c;
  2877. } else if (c < 0x800) {
  2878. /* two bytes */
  2879. buf[i++] = 0xC0 | (c >>> 6);
  2880. buf[i++] = 0x80 | (c & 0x3f);
  2881. } else if (c < 0x10000) {
  2882. /* three bytes */
  2883. buf[i++] = 0xE0 | (c >>> 12);
  2884. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2885. buf[i++] = 0x80 | (c & 0x3f);
  2886. } else {
  2887. /* four bytes */
  2888. buf[i++] = 0xf0 | (c >>> 18);
  2889. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  2890. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2891. buf[i++] = 0x80 | (c & 0x3f);
  2892. }
  2893. }
  2894. return buf;
  2895. };
  2896. // Helper
  2897. const buf2binstring = (buf, len) => {
  2898. // On Chrome, the arguments in a function call that are allowed is `65534`.
  2899. // If the length of the buffer is smaller than that, we can use this optimization,
  2900. // otherwise we will take a slower path.
  2901. if (len < 65534) {
  2902. if (buf.subarray && STR_APPLY_UIA_OK) {
  2903. return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));
  2904. }
  2905. }
  2906. let result = '';
  2907. for (let i = 0; i < len; i++) {
  2908. result += String.fromCharCode(buf[i]);
  2909. }
  2910. return result;
  2911. };
  2912. // convert array to string
  2913. var buf2string = (buf, max) => {
  2914. const len = max || buf.length;
  2915. if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {
  2916. return new TextDecoder().decode(buf.subarray(0, max));
  2917. }
  2918. let i, out;
  2919. // Reserve max possible length (2 words per char)
  2920. // NB: by unknown reasons, Array is significantly faster for
  2921. // String.fromCharCode.apply than Uint16Array.
  2922. const utf16buf = new Array(len * 2);
  2923. for (out = 0, i = 0; i < len;) {
  2924. let c = buf[i++];
  2925. // quick process ascii
  2926. if (c < 0x80) { utf16buf[out++] = c; continue; }
  2927. let c_len = _utf8len[c];
  2928. // skip 5 & 6 byte codes
  2929. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  2930. // apply mask on first byte
  2931. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  2932. // join the rest
  2933. while (c_len > 1 && i < len) {
  2934. c = (c << 6) | (buf[i++] & 0x3f);
  2935. c_len--;
  2936. }
  2937. // terminated by end of string?
  2938. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  2939. if (c < 0x10000) {
  2940. utf16buf[out++] = c;
  2941. } else {
  2942. c -= 0x10000;
  2943. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  2944. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  2945. }
  2946. }
  2947. return buf2binstring(utf16buf, out);
  2948. };
  2949. // Calculate max possible position in utf8 buffer,
  2950. // that will not break sequence. If that's not possible
  2951. // - (very small limits) return max size as is.
  2952. //
  2953. // buf[] - utf8 bytes array
  2954. // max - length limit (mandatory);
  2955. var utf8border = (buf, max) => {
  2956. max = max || buf.length;
  2957. if (max > buf.length) { max = buf.length; }
  2958. // go back from last position, until start of sequence found
  2959. let pos = max - 1;
  2960. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  2961. // Very small and broken sequence,
  2962. // return max, because we should return something anyway.
  2963. if (pos < 0) { return max; }
  2964. // If we came to start of buffer - that means buffer is too small,
  2965. // return max too.
  2966. if (pos === 0) { return max; }
  2967. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  2968. };
  2969. var strings = {
  2970. string2buf: string2buf,
  2971. buf2string: buf2string,
  2972. utf8border: utf8border
  2973. };
  2974. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  2975. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  2976. //
  2977. // This software is provided 'as-is', without any express or implied
  2978. // warranty. In no event will the authors be held liable for any damages
  2979. // arising from the use of this software.
  2980. //
  2981. // Permission is granted to anyone to use this software for any purpose,
  2982. // including commercial applications, and to alter it and redistribute it
  2983. // freely, subject to the following restrictions:
  2984. //
  2985. // 1. The origin of this software must not be misrepresented; you must not
  2986. // claim that you wrote the original software. If you use this software
  2987. // in a product, an acknowledgment in the product documentation would be
  2988. // appreciated but is not required.
  2989. // 2. Altered source versions must be plainly marked as such, and must not be
  2990. // misrepresented as being the original software.
  2991. // 3. This notice may not be removed or altered from any source distribution.
  2992. function ZStream() {
  2993. /* next input byte */
  2994. this.input = null; // JS specific, because we have no pointers
  2995. this.next_in = 0;
  2996. /* number of bytes available at input */
  2997. this.avail_in = 0;
  2998. /* total number of input bytes read so far */
  2999. this.total_in = 0;
  3000. /* next output byte should be put there */
  3001. this.output = null; // JS specific, because we have no pointers
  3002. this.next_out = 0;
  3003. /* remaining free space at output */
  3004. this.avail_out = 0;
  3005. /* total number of bytes output so far */
  3006. this.total_out = 0;
  3007. /* last error message, NULL if no error */
  3008. this.msg = ''/*Z_NULL*/;
  3009. /* not visible by applications */
  3010. this.state = null;
  3011. /* best guess about the data type: binary or text */
  3012. this.data_type = 2/*Z_UNKNOWN*/;
  3013. /* adler32 value of the uncompressed data */
  3014. this.adler = 0;
  3015. }
  3016. var zstream = ZStream;
  3017. const toString = Object.prototype.toString;
  3018. /* Public constants ==========================================================*/
  3019. /* ===========================================================================*/
  3020. const {
  3021. Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH,
  3022. Z_OK, Z_STREAM_END,
  3023. Z_DEFAULT_COMPRESSION,
  3024. Z_DEFAULT_STRATEGY,
  3025. Z_DEFLATED
  3026. } = constants$1;
  3027. /* ===========================================================================*/
  3028. /**
  3029. * class Deflate
  3030. *
  3031. * Generic JS-style wrapper for zlib calls. If you don't need
  3032. * streaming behaviour - use more simple functions: [[deflate]],
  3033. * [[deflateRaw]] and [[gzip]].
  3034. **/
  3035. /* internal
  3036. * Deflate.chunks -> Array
  3037. *
  3038. * Chunks of output data, if [[Deflate#onData]] not overridden.
  3039. **/
  3040. /**
  3041. * Deflate.result -> Uint8Array
  3042. *
  3043. * Compressed result, generated by default [[Deflate#onData]]
  3044. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  3045. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  3046. **/
  3047. /**
  3048. * Deflate.err -> Number
  3049. *
  3050. * Error code after deflate finished. 0 (Z_OK) on success.
  3051. * You will not need it in real life, because deflate errors
  3052. * are possible only on wrong options or bad `onData` / `onEnd`
  3053. * custom handlers.
  3054. **/
  3055. /**
  3056. * Deflate.msg -> String
  3057. *
  3058. * Error message, if [[Deflate.err]] != 0
  3059. **/
  3060. /**
  3061. * new Deflate(options)
  3062. * - options (Object): zlib deflate options.
  3063. *
  3064. * Creates new deflator instance with specified params. Throws exception
  3065. * on bad params. Supported options:
  3066. *
  3067. * - `level`
  3068. * - `windowBits`
  3069. * - `memLevel`
  3070. * - `strategy`
  3071. * - `dictionary`
  3072. *
  3073. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3074. * for more information on these.
  3075. *
  3076. * Additional options, for internal needs:
  3077. *
  3078. * - `chunkSize` - size of generated data chunks (16K by default)
  3079. * - `raw` (Boolean) - do raw deflate
  3080. * - `gzip` (Boolean) - create gzip wrapper
  3081. * - `header` (Object) - custom header for gzip
  3082. * - `text` (Boolean) - true if compressed data believed to be text
  3083. * - `time` (Number) - modification time, unix timestamp
  3084. * - `os` (Number) - operation system code
  3085. * - `extra` (Array) - array of bytes with extra data (max 65536)
  3086. * - `name` (String) - file name (binary string)
  3087. * - `comment` (String) - comment (binary string)
  3088. * - `hcrc` (Boolean) - true if header crc should be added
  3089. *
  3090. * ##### Example:
  3091. *
  3092. * ```javascript
  3093. * const pako = require('pako')
  3094. * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
  3095. * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  3096. *
  3097. * const deflate = new pako.Deflate({ level: 3});
  3098. *
  3099. * deflate.push(chunk1, false);
  3100. * deflate.push(chunk2, true); // true -> last chunk
  3101. *
  3102. * if (deflate.err) { throw new Error(deflate.err); }
  3103. *
  3104. * console.log(deflate.result);
  3105. * ```
  3106. **/
  3107. function Deflate(options) {
  3108. this.options = common.assign({
  3109. level: Z_DEFAULT_COMPRESSION,
  3110. method: Z_DEFLATED,
  3111. chunkSize: 16384,
  3112. windowBits: 15,
  3113. memLevel: 8,
  3114. strategy: Z_DEFAULT_STRATEGY
  3115. }, options || {});
  3116. let opt = this.options;
  3117. if (opt.raw && (opt.windowBits > 0)) {
  3118. opt.windowBits = -opt.windowBits;
  3119. }
  3120. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  3121. opt.windowBits += 16;
  3122. }
  3123. this.err = 0; // error code, if happens (0 = Z_OK)
  3124. this.msg = ''; // error message
  3125. this.ended = false; // used to avoid multiple onEnd() calls
  3126. this.chunks = []; // chunks of compressed data
  3127. this.strm = new zstream();
  3128. this.strm.avail_out = 0;
  3129. let status = deflate_1$1.deflateInit2(
  3130. this.strm,
  3131. opt.level,
  3132. opt.method,
  3133. opt.windowBits,
  3134. opt.memLevel,
  3135. opt.strategy
  3136. );
  3137. if (status !== Z_OK) {
  3138. throw new Error(messages[status]);
  3139. }
  3140. if (opt.header) {
  3141. deflate_1$1.deflateSetHeader(this.strm, opt.header);
  3142. }
  3143. if (opt.dictionary) {
  3144. let dict;
  3145. // Convert data if needed
  3146. if (typeof opt.dictionary === 'string') {
  3147. // If we need to compress text, change encoding to utf8.
  3148. dict = strings.string2buf(opt.dictionary);
  3149. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  3150. dict = new Uint8Array(opt.dictionary);
  3151. } else {
  3152. dict = opt.dictionary;
  3153. }
  3154. status = deflate_1$1.deflateSetDictionary(this.strm, dict);
  3155. if (status !== Z_OK) {
  3156. throw new Error(messages[status]);
  3157. }
  3158. this._dict_set = true;
  3159. }
  3160. }
  3161. /**
  3162. * Deflate#push(data[, flush_mode]) -> Boolean
  3163. * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be
  3164. * converted to utf8 byte sequence.
  3165. * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  3166. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  3167. *
  3168. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  3169. * new compressed chunks. Returns `true` on success. The last data block must
  3170. * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending
  3171. * buffers and call [[Deflate#onEnd]].
  3172. *
  3173. * On fail call [[Deflate#onEnd]] with error code and return false.
  3174. *
  3175. * ##### Example
  3176. *
  3177. * ```javascript
  3178. * push(chunk, false); // push one of data chunks
  3179. * ...
  3180. * push(chunk, true); // push last chunk
  3181. * ```
  3182. **/
  3183. Deflate.prototype.push = function (data, flush_mode) {
  3184. const strm = this.strm;
  3185. const chunkSize = this.options.chunkSize;
  3186. let status, _flush_mode;
  3187. if (this.ended) { return false; }
  3188. if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;
  3189. else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;
  3190. // Convert data if needed
  3191. if (typeof data === 'string') {
  3192. // If we need to compress text, change encoding to utf8.
  3193. strm.input = strings.string2buf(data);
  3194. } else if (toString.call(data) === '[object ArrayBuffer]') {
  3195. strm.input = new Uint8Array(data);
  3196. } else {
  3197. strm.input = data;
  3198. }
  3199. strm.next_in = 0;
  3200. strm.avail_in = strm.input.length;
  3201. for (;;) {
  3202. if (strm.avail_out === 0) {
  3203. strm.output = new Uint8Array(chunkSize);
  3204. strm.next_out = 0;
  3205. strm.avail_out = chunkSize;
  3206. }
  3207. // Make sure avail_out > 6 to avoid repeating markers
  3208. if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {
  3209. this.onData(strm.output.subarray(0, strm.next_out));
  3210. strm.avail_out = 0;
  3211. continue;
  3212. }
  3213. status = deflate_1$1.deflate(strm, _flush_mode);
  3214. // Ended => flush and finish
  3215. if (status === Z_STREAM_END) {
  3216. if (strm.next_out > 0) {
  3217. this.onData(strm.output.subarray(0, strm.next_out));
  3218. }
  3219. status = deflate_1$1.deflateEnd(this.strm);
  3220. this.onEnd(status);
  3221. this.ended = true;
  3222. return status === Z_OK;
  3223. }
  3224. // Flush if out buffer full
  3225. if (strm.avail_out === 0) {
  3226. this.onData(strm.output);
  3227. continue;
  3228. }
  3229. // Flush if requested and has data
  3230. if (_flush_mode > 0 && strm.next_out > 0) {
  3231. this.onData(strm.output.subarray(0, strm.next_out));
  3232. strm.avail_out = 0;
  3233. continue;
  3234. }
  3235. if (strm.avail_in === 0) break;
  3236. }
  3237. return true;
  3238. };
  3239. /**
  3240. * Deflate#onData(chunk) -> Void
  3241. * - chunk (Uint8Array): output data.
  3242. *
  3243. * By default, stores data blocks in `chunks[]` property and glue
  3244. * those in `onEnd`. Override this handler, if you need another behaviour.
  3245. **/
  3246. Deflate.prototype.onData = function (chunk) {
  3247. this.chunks.push(chunk);
  3248. };
  3249. /**
  3250. * Deflate#onEnd(status) -> Void
  3251. * - status (Number): deflate status. 0 (Z_OK) on success,
  3252. * other if not.
  3253. *
  3254. * Called once after you tell deflate that the input stream is
  3255. * complete (Z_FINISH). By default - join collected chunks,
  3256. * free memory and fill `results` / `err` properties.
  3257. **/
  3258. Deflate.prototype.onEnd = function (status) {
  3259. // On success - join
  3260. if (status === Z_OK) {
  3261. this.result = common.flattenChunks(this.chunks);
  3262. }
  3263. this.chunks = [];
  3264. this.err = status;
  3265. this.msg = this.strm.msg;
  3266. };
  3267. /**
  3268. * deflate(data[, options]) -> Uint8Array
  3269. * - data (Uint8Array|String): input data to compress.
  3270. * - options (Object): zlib deflate options.
  3271. *
  3272. * Compress `data` with deflate algorithm and `options`.
  3273. *
  3274. * Supported options are:
  3275. *
  3276. * - level
  3277. * - windowBits
  3278. * - memLevel
  3279. * - strategy
  3280. * - dictionary
  3281. *
  3282. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3283. * for more information on these.
  3284. *
  3285. * Sugar (options):
  3286. *
  3287. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  3288. * negative windowBits implicitly.
  3289. *
  3290. * ##### Example:
  3291. *
  3292. * ```javascript
  3293. * const pako = require('pako')
  3294. * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);
  3295. *
  3296. * console.log(pako.deflate(data));
  3297. * ```
  3298. **/
  3299. function deflate(input, options) {
  3300. const deflator = new Deflate(options);
  3301. deflator.push(input, true);
  3302. // That will never happens, if you don't cheat with options :)
  3303. if (deflator.err) { throw deflator.msg || messages[deflator.err]; }
  3304. return deflator.result;
  3305. }
  3306. /**
  3307. * deflateRaw(data[, options]) -> Uint8Array
  3308. * - data (Uint8Array|String): input data to compress.
  3309. * - options (Object): zlib deflate options.
  3310. *
  3311. * The same as [[deflate]], but creates raw data, without wrapper
  3312. * (header and adler32 crc).
  3313. **/
  3314. function deflateRaw(input, options) {
  3315. options = options || {};
  3316. options.raw = true;
  3317. return deflate(input, options);
  3318. }
  3319. /**
  3320. * gzip(data[, options]) -> Uint8Array
  3321. * - data (Uint8Array|String): input data to compress.
  3322. * - options (Object): zlib deflate options.
  3323. *
  3324. * The same as [[deflate]], but create gzip wrapper instead of
  3325. * deflate one.
  3326. **/
  3327. function gzip(input, options) {
  3328. options = options || {};
  3329. options.gzip = true;
  3330. return deflate(input, options);
  3331. }
  3332. var Deflate_1 = Deflate;
  3333. var deflate_2 = deflate;
  3334. var deflateRaw_1 = deflateRaw;
  3335. var gzip_1 = gzip;
  3336. var constants = constants$1;
  3337. var deflate_1 = {
  3338. Deflate: Deflate_1,
  3339. deflate: deflate_2,
  3340. deflateRaw: deflateRaw_1,
  3341. gzip: gzip_1,
  3342. constants: constants
  3343. };
  3344. exports.Deflate = Deflate_1;
  3345. exports.constants = constants;
  3346. exports['default'] = deflate_1;
  3347. exports.deflate = deflate_2;
  3348. exports.deflateRaw = deflateRaw_1;
  3349. exports.gzip = gzip_1;
  3350. Object.defineProperty(exports, '__esModule', { value: true });
  3351. })));