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.

380 lines
9.8 KiB

1 year ago
  1. 'use strict';
  2. const zlib_deflate = require('./zlib/deflate');
  3. const utils = require('./utils/common');
  4. const strings = require('./utils/strings');
  5. const msg = require('./zlib/messages');
  6. const ZStream = require('./zlib/zstream');
  7. const toString = Object.prototype.toString;
  8. /* Public constants ==========================================================*/
  9. /* ===========================================================================*/
  10. const {
  11. Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH,
  12. Z_OK, Z_STREAM_END,
  13. Z_DEFAULT_COMPRESSION,
  14. Z_DEFAULT_STRATEGY,
  15. Z_DEFLATED
  16. } = require('./zlib/constants');
  17. /* ===========================================================================*/
  18. /**
  19. * class Deflate
  20. *
  21. * Generic JS-style wrapper for zlib calls. If you don't need
  22. * streaming behaviour - use more simple functions: [[deflate]],
  23. * [[deflateRaw]] and [[gzip]].
  24. **/
  25. /* internal
  26. * Deflate.chunks -> Array
  27. *
  28. * Chunks of output data, if [[Deflate#onData]] not overridden.
  29. **/
  30. /**
  31. * Deflate.result -> Uint8Array
  32. *
  33. * Compressed result, generated by default [[Deflate#onData]]
  34. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  35. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  36. **/
  37. /**
  38. * Deflate.err -> Number
  39. *
  40. * Error code after deflate finished. 0 (Z_OK) on success.
  41. * You will not need it in real life, because deflate errors
  42. * are possible only on wrong options or bad `onData` / `onEnd`
  43. * custom handlers.
  44. **/
  45. /**
  46. * Deflate.msg -> String
  47. *
  48. * Error message, if [[Deflate.err]] != 0
  49. **/
  50. /**
  51. * new Deflate(options)
  52. * - options (Object): zlib deflate options.
  53. *
  54. * Creates new deflator instance with specified params. Throws exception
  55. * on bad params. Supported options:
  56. *
  57. * - `level`
  58. * - `windowBits`
  59. * - `memLevel`
  60. * - `strategy`
  61. * - `dictionary`
  62. *
  63. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  64. * for more information on these.
  65. *
  66. * Additional options, for internal needs:
  67. *
  68. * - `chunkSize` - size of generated data chunks (16K by default)
  69. * - `raw` (Boolean) - do raw deflate
  70. * - `gzip` (Boolean) - create gzip wrapper
  71. * - `header` (Object) - custom header for gzip
  72. * - `text` (Boolean) - true if compressed data believed to be text
  73. * - `time` (Number) - modification time, unix timestamp
  74. * - `os` (Number) - operation system code
  75. * - `extra` (Array) - array of bytes with extra data (max 65536)
  76. * - `name` (String) - file name (binary string)
  77. * - `comment` (String) - comment (binary string)
  78. * - `hcrc` (Boolean) - true if header crc should be added
  79. *
  80. * ##### Example:
  81. *
  82. * ```javascript
  83. * const pako = require('pako')
  84. * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
  85. * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  86. *
  87. * const deflate = new pako.Deflate({ level: 3});
  88. *
  89. * deflate.push(chunk1, false);
  90. * deflate.push(chunk2, true); // true -> last chunk
  91. *
  92. * if (deflate.err) { throw new Error(deflate.err); }
  93. *
  94. * console.log(deflate.result);
  95. * ```
  96. **/
  97. function Deflate(options) {
  98. this.options = utils.assign({
  99. level: Z_DEFAULT_COMPRESSION,
  100. method: Z_DEFLATED,
  101. chunkSize: 16384,
  102. windowBits: 15,
  103. memLevel: 8,
  104. strategy: Z_DEFAULT_STRATEGY
  105. }, options || {});
  106. let opt = this.options;
  107. if (opt.raw && (opt.windowBits > 0)) {
  108. opt.windowBits = -opt.windowBits;
  109. }
  110. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  111. opt.windowBits += 16;
  112. }
  113. this.err = 0; // error code, if happens (0 = Z_OK)
  114. this.msg = ''; // error message
  115. this.ended = false; // used to avoid multiple onEnd() calls
  116. this.chunks = []; // chunks of compressed data
  117. this.strm = new ZStream();
  118. this.strm.avail_out = 0;
  119. let status = zlib_deflate.deflateInit2(
  120. this.strm,
  121. opt.level,
  122. opt.method,
  123. opt.windowBits,
  124. opt.memLevel,
  125. opt.strategy
  126. );
  127. if (status !== Z_OK) {
  128. throw new Error(msg[status]);
  129. }
  130. if (opt.header) {
  131. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  132. }
  133. if (opt.dictionary) {
  134. let dict;
  135. // Convert data if needed
  136. if (typeof opt.dictionary === 'string') {
  137. // If we need to compress text, change encoding to utf8.
  138. dict = strings.string2buf(opt.dictionary);
  139. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  140. dict = new Uint8Array(opt.dictionary);
  141. } else {
  142. dict = opt.dictionary;
  143. }
  144. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  145. if (status !== Z_OK) {
  146. throw new Error(msg[status]);
  147. }
  148. this._dict_set = true;
  149. }
  150. }
  151. /**
  152. * Deflate#push(data[, flush_mode]) -> Boolean
  153. * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be
  154. * converted to utf8 byte sequence.
  155. * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  156. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  157. *
  158. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  159. * new compressed chunks. Returns `true` on success. The last data block must
  160. * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending
  161. * buffers and call [[Deflate#onEnd]].
  162. *
  163. * On fail call [[Deflate#onEnd]] with error code and return false.
  164. *
  165. * ##### Example
  166. *
  167. * ```javascript
  168. * push(chunk, false); // push one of data chunks
  169. * ...
  170. * push(chunk, true); // push last chunk
  171. * ```
  172. **/
  173. Deflate.prototype.push = function (data, flush_mode) {
  174. const strm = this.strm;
  175. const chunkSize = this.options.chunkSize;
  176. let status, _flush_mode;
  177. if (this.ended) { return false; }
  178. if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;
  179. else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;
  180. // Convert data if needed
  181. if (typeof data === 'string') {
  182. // If we need to compress text, change encoding to utf8.
  183. strm.input = strings.string2buf(data);
  184. } else if (toString.call(data) === '[object ArrayBuffer]') {
  185. strm.input = new Uint8Array(data);
  186. } else {
  187. strm.input = data;
  188. }
  189. strm.next_in = 0;
  190. strm.avail_in = strm.input.length;
  191. for (;;) {
  192. if (strm.avail_out === 0) {
  193. strm.output = new Uint8Array(chunkSize);
  194. strm.next_out = 0;
  195. strm.avail_out = chunkSize;
  196. }
  197. // Make sure avail_out > 6 to avoid repeating markers
  198. if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {
  199. this.onData(strm.output.subarray(0, strm.next_out));
  200. strm.avail_out = 0;
  201. continue;
  202. }
  203. status = zlib_deflate.deflate(strm, _flush_mode);
  204. // Ended => flush and finish
  205. if (status === Z_STREAM_END) {
  206. if (strm.next_out > 0) {
  207. this.onData(strm.output.subarray(0, strm.next_out));
  208. }
  209. status = zlib_deflate.deflateEnd(this.strm);
  210. this.onEnd(status);
  211. this.ended = true;
  212. return status === Z_OK;
  213. }
  214. // Flush if out buffer full
  215. if (strm.avail_out === 0) {
  216. this.onData(strm.output);
  217. continue;
  218. }
  219. // Flush if requested and has data
  220. if (_flush_mode > 0 && strm.next_out > 0) {
  221. this.onData(strm.output.subarray(0, strm.next_out));
  222. strm.avail_out = 0;
  223. continue;
  224. }
  225. if (strm.avail_in === 0) break;
  226. }
  227. return true;
  228. };
  229. /**
  230. * Deflate#onData(chunk) -> Void
  231. * - chunk (Uint8Array): output data.
  232. *
  233. * By default, stores data blocks in `chunks[]` property and glue
  234. * those in `onEnd`. Override this handler, if you need another behaviour.
  235. **/
  236. Deflate.prototype.onData = function (chunk) {
  237. this.chunks.push(chunk);
  238. };
  239. /**
  240. * Deflate#onEnd(status) -> Void
  241. * - status (Number): deflate status. 0 (Z_OK) on success,
  242. * other if not.
  243. *
  244. * Called once after you tell deflate that the input stream is
  245. * complete (Z_FINISH). By default - join collected chunks,
  246. * free memory and fill `results` / `err` properties.
  247. **/
  248. Deflate.prototype.onEnd = function (status) {
  249. // On success - join
  250. if (status === Z_OK) {
  251. this.result = utils.flattenChunks(this.chunks);
  252. }
  253. this.chunks = [];
  254. this.err = status;
  255. this.msg = this.strm.msg;
  256. };
  257. /**
  258. * deflate(data[, options]) -> Uint8Array
  259. * - data (Uint8Array|String): input data to compress.
  260. * - options (Object): zlib deflate options.
  261. *
  262. * Compress `data` with deflate algorithm and `options`.
  263. *
  264. * Supported options are:
  265. *
  266. * - level
  267. * - windowBits
  268. * - memLevel
  269. * - strategy
  270. * - dictionary
  271. *
  272. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  273. * for more information on these.
  274. *
  275. * Sugar (options):
  276. *
  277. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  278. * negative windowBits implicitly.
  279. *
  280. * ##### Example:
  281. *
  282. * ```javascript
  283. * const pako = require('pako')
  284. * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);
  285. *
  286. * console.log(pako.deflate(data));
  287. * ```
  288. **/
  289. function deflate(input, options) {
  290. const deflator = new Deflate(options);
  291. deflator.push(input, true);
  292. // That will never happens, if you don't cheat with options :)
  293. if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
  294. return deflator.result;
  295. }
  296. /**
  297. * deflateRaw(data[, options]) -> Uint8Array
  298. * - data (Uint8Array|String): input data to compress.
  299. * - options (Object): zlib deflate options.
  300. *
  301. * The same as [[deflate]], but creates raw data, without wrapper
  302. * (header and adler32 crc).
  303. **/
  304. function deflateRaw(input, options) {
  305. options = options || {};
  306. options.raw = true;
  307. return deflate(input, options);
  308. }
  309. /**
  310. * gzip(data[, options]) -> Uint8Array
  311. * - data (Uint8Array|String): input data to compress.
  312. * - options (Object): zlib deflate options.
  313. *
  314. * The same as [[deflate]], but create gzip wrapper instead of
  315. * deflate one.
  316. **/
  317. function gzip(input, options) {
  318. options = options || {};
  319. options.gzip = true;
  320. return deflate(input, options);
  321. }
  322. module.exports.Deflate = Deflate;
  323. module.exports.deflate = deflate;
  324. module.exports.deflateRaw = deflateRaw;
  325. module.exports.gzip = gzip;
  326. module.exports.constants = require('./zlib/constants');