Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. 'use strict';
  2. var zlib_inflate = require('./zlib/inflate');
  3. var utils = require('./utils/common');
  4. var strings = require('./utils/strings');
  5. var c = require('./zlib/constants');
  6. var msg = require('./zlib/messages');
  7. var ZStream = require('./zlib/zstream');
  8. var GZheader = require('./zlib/gzheader');
  9. var toString = Object.prototype.toString;
  10. /**
  11. * class Inflate
  12. *
  13. * Generic JS-style wrapper for zlib calls. If you don't need
  14. * streaming behaviour - use more simple functions: [[inflate]]
  15. * and [[inflateRaw]].
  16. **/
  17. /* internal
  18. * inflate.chunks -> Array
  19. *
  20. * Chunks of output data, if [[Inflate#onData]] not overridden.
  21. **/
  22. /**
  23. * Inflate.result -> Uint8Array|Array|String
  24. *
  25. * Uncompressed result, generated by default [[Inflate#onData]]
  26. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  27. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  28. * push a chunk with explicit flush (call [[Inflate#push]] with
  29. * `Z_SYNC_FLUSH` param).
  30. **/
  31. /**
  32. * Inflate.err -> Number
  33. *
  34. * Error code after inflate finished. 0 (Z_OK) on success.
  35. * Should be checked if broken data possible.
  36. **/
  37. /**
  38. * Inflate.msg -> String
  39. *
  40. * Error message, if [[Inflate.err]] != 0
  41. **/
  42. /**
  43. * new Inflate(options)
  44. * - options (Object): zlib inflate options.
  45. *
  46. * Creates new inflator instance with specified params. Throws exception
  47. * on bad params. Supported options:
  48. *
  49. * - `windowBits`
  50. * - `dictionary`
  51. *
  52. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  53. * for more information on these.
  54. *
  55. * Additional options, for internal needs:
  56. *
  57. * - `chunkSize` - size of generated data chunks (16K by default)
  58. * - `raw` (Boolean) - do raw inflate
  59. * - `to` (String) - if equal to 'string', then result will be converted
  60. * from utf8 to utf16 (javascript) string. When string output requested,
  61. * chunk length can differ from `chunkSize`, depending on content.
  62. *
  63. * By default, when no options set, autodetect deflate/gzip data format via
  64. * wrapper header.
  65. *
  66. * ##### Example:
  67. *
  68. * ```javascript
  69. * var pako = require('pako')
  70. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  71. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  72. *
  73. * var inflate = new pako.Inflate({ level: 3});
  74. *
  75. * inflate.push(chunk1, false);
  76. * inflate.push(chunk2, true); // true -> last chunk
  77. *
  78. * if (inflate.err) { throw new Error(inflate.err); }
  79. *
  80. * console.log(inflate.result);
  81. * ```
  82. **/
  83. function Inflate(options) {
  84. if (!(this instanceof Inflate)) return new Inflate(options);
  85. this.options = utils.assign({
  86. chunkSize: 16384,
  87. windowBits: 0,
  88. to: ''
  89. }, options || {});
  90. var opt = this.options;
  91. // Force window size for `raw` data, if not set directly,
  92. // because we have no header for autodetect.
  93. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  94. opt.windowBits = -opt.windowBits;
  95. if (opt.windowBits === 0) { opt.windowBits = -15; }
  96. }
  97. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  98. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  99. !(options && options.windowBits)) {
  100. opt.windowBits += 32;
  101. }
  102. // Gzip header has no info about windows size, we can do autodetect only
  103. // for deflate. So, if window size not set, force it to max when gzip possible
  104. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  105. // bit 3 (16) -> gzipped data
  106. // bit 4 (32) -> autodetect gzip/deflate
  107. if ((opt.windowBits & 15) === 0) {
  108. opt.windowBits |= 15;
  109. }
  110. }
  111. this.err = 0; // error code, if happens (0 = Z_OK)
  112. this.msg = ''; // error message
  113. this.ended = false; // used to avoid multiple onEnd() calls
  114. this.chunks = []; // chunks of compressed data
  115. this.strm = new ZStream();
  116. this.strm.avail_out = 0;
  117. var status = zlib_inflate.inflateInit2(
  118. this.strm,
  119. opt.windowBits
  120. );
  121. if (status !== c.Z_OK) {
  122. throw new Error(msg[status]);
  123. }
  124. this.header = new GZheader();
  125. zlib_inflate.inflateGetHeader(this.strm, this.header);
  126. // Setup dictionary
  127. if (opt.dictionary) {
  128. // Convert data if needed
  129. if (typeof opt.dictionary === 'string') {
  130. opt.dictionary = strings.string2buf(opt.dictionary);
  131. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  132. opt.dictionary = new Uint8Array(opt.dictionary);
  133. }
  134. if (opt.raw) { //In raw mode we need to set the dictionary early
  135. status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);
  136. if (status !== c.Z_OK) {
  137. throw new Error(msg[status]);
  138. }
  139. }
  140. }
  141. }
  142. /**
  143. * Inflate#push(data[, mode]) -> Boolean
  144. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  145. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  146. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  147. *
  148. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  149. * new output chunks. Returns `true` on success. The last data block must have
  150. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  151. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  152. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  153. *
  154. * On fail call [[Inflate#onEnd]] with error code and return false.
  155. *
  156. * We strongly recommend to use `Uint8Array` on input for best speed (output
  157. * format is detected automatically). Also, don't skip last param and always
  158. * use the same type in your code (boolean or number). That will improve JS speed.
  159. *
  160. * For regular `Array`-s make sure all elements are [0..255].
  161. *
  162. * ##### Example
  163. *
  164. * ```javascript
  165. * push(chunk, false); // push one of data chunks
  166. * ...
  167. * push(chunk, true); // push last chunk
  168. * ```
  169. **/
  170. Inflate.prototype.push = function (data, mode) {
  171. var strm = this.strm;
  172. var chunkSize = this.options.chunkSize;
  173. var dictionary = this.options.dictionary;
  174. var status, _mode;
  175. var next_out_utf8, tail, utf8str;
  176. // Flag to properly process Z_BUF_ERROR on testing inflate call
  177. // when we check that all output data was flushed.
  178. var allowBufError = false;
  179. if (this.ended) { return false; }
  180. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  181. // Convert data if needed
  182. if (typeof data === 'string') {
  183. // Only binary strings can be decompressed on practice
  184. strm.input = strings.binstring2buf(data);
  185. } else if (toString.call(data) === '[object ArrayBuffer]') {
  186. strm.input = new Uint8Array(data);
  187. } else {
  188. strm.input = data;
  189. }
  190. strm.next_in = 0;
  191. strm.avail_in = strm.input.length;
  192. do {
  193. if (strm.avail_out === 0) {
  194. strm.output = new utils.Buf8(chunkSize);
  195. strm.next_out = 0;
  196. strm.avail_out = chunkSize;
  197. }
  198. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  199. if (status === c.Z_NEED_DICT && dictionary) {
  200. status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);
  201. }
  202. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  203. status = c.Z_OK;
  204. allowBufError = false;
  205. }
  206. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  207. this.onEnd(status);
  208. this.ended = true;
  209. return false;
  210. }
  211. if (strm.next_out) {
  212. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  213. if (this.options.to === 'string') {
  214. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  215. tail = strm.next_out - next_out_utf8;
  216. utf8str = strings.buf2string(strm.output, next_out_utf8);
  217. // move tail
  218. strm.next_out = tail;
  219. strm.avail_out = chunkSize - tail;
  220. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  221. this.onData(utf8str);
  222. } else {
  223. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  224. }
  225. }
  226. }
  227. // When no more input data, we should check that internal inflate buffers
  228. // are flushed. The only way to do it when avail_out = 0 - run one more
  229. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  230. // Here we set flag to process this error properly.
  231. //
  232. // NOTE. Deflate does not return error in this case and does not needs such
  233. // logic.
  234. if (strm.avail_in === 0 && strm.avail_out === 0) {
  235. allowBufError = true;
  236. }
  237. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  238. if (status === c.Z_STREAM_END) {
  239. _mode = c.Z_FINISH;
  240. }
  241. // Finalize on the last chunk.
  242. if (_mode === c.Z_FINISH) {
  243. status = zlib_inflate.inflateEnd(this.strm);
  244. this.onEnd(status);
  245. this.ended = true;
  246. return status === c.Z_OK;
  247. }
  248. // callback interim results if Z_SYNC_FLUSH.
  249. if (_mode === c.Z_SYNC_FLUSH) {
  250. this.onEnd(c.Z_OK);
  251. strm.avail_out = 0;
  252. return true;
  253. }
  254. return true;
  255. };
  256. /**
  257. * Inflate#onData(chunk) -> Void
  258. * - chunk (Uint8Array|Array|String): output data. Type of array depends
  259. * on js engine support. When string output requested, each chunk
  260. * will be string.
  261. *
  262. * By default, stores data blocks in `chunks[]` property and glue
  263. * those in `onEnd`. Override this handler, if you need another behaviour.
  264. **/
  265. Inflate.prototype.onData = function (chunk) {
  266. this.chunks.push(chunk);
  267. };
  268. /**
  269. * Inflate#onEnd(status) -> Void
  270. * - status (Number): inflate status. 0 (Z_OK) on success,
  271. * other if not.
  272. *
  273. * Called either after you tell inflate that the input stream is
  274. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  275. * or if an error happened. By default - join collected chunks,
  276. * free memory and fill `results` / `err` properties.
  277. **/
  278. Inflate.prototype.onEnd = function (status) {
  279. // On success - join
  280. if (status === c.Z_OK) {
  281. if (this.options.to === 'string') {
  282. // Glue & convert here, until we teach pako to send
  283. // utf8 aligned strings to onData
  284. this.result = this.chunks.join('');
  285. } else {
  286. this.result = utils.flattenChunks(this.chunks);
  287. }
  288. }
  289. this.chunks = [];
  290. this.err = status;
  291. this.msg = this.strm.msg;
  292. };
  293. /**
  294. * inflate(data[, options]) -> Uint8Array|Array|String
  295. * - data (Uint8Array|Array|String): input data to decompress.
  296. * - options (Object): zlib inflate options.
  297. *
  298. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  299. * format via wrapper header by default. That's why we don't provide
  300. * separate `ungzip` method.
  301. *
  302. * Supported options are:
  303. *
  304. * - windowBits
  305. *
  306. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  307. * for more information.
  308. *
  309. * Sugar (options):
  310. *
  311. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  312. * negative windowBits implicitly.
  313. * - `to` (String) - if equal to 'string', then result will be converted
  314. * from utf8 to utf16 (javascript) string. When string output requested,
  315. * chunk length can differ from `chunkSize`, depending on content.
  316. *
  317. *
  318. * ##### Example:
  319. *
  320. * ```javascript
  321. * var pako = require('pako')
  322. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  323. * , output;
  324. *
  325. * try {
  326. * output = pako.inflate(input);
  327. * } catch (err)
  328. * console.log(err);
  329. * }
  330. * ```
  331. **/
  332. function inflate(input, options) {
  333. var inflator = new Inflate(options);
  334. inflator.push(input, true);
  335. // That will never happens, if you don't cheat with options :)
  336. if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
  337. return inflator.result;
  338. }
  339. /**
  340. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  341. * - data (Uint8Array|Array|String): input data to decompress.
  342. * - options (Object): zlib inflate options.
  343. *
  344. * The same as [[inflate]], but creates raw data, without wrapper
  345. * (header and adler32 crc).
  346. **/
  347. function inflateRaw(input, options) {
  348. options = options || {};
  349. options.raw = true;
  350. return inflate(input, options);
  351. }
  352. /**
  353. * ungzip(data[, options]) -> Uint8Array|Array|String
  354. * - data (Uint8Array|Array|String): input data to decompress.
  355. * - options (Object): zlib inflate options.
  356. *
  357. * Just shortcut to [[inflate]], because it autodetects format
  358. * by header.content. Done for convenience.
  359. **/
  360. exports.Inflate = Inflate;
  361. exports.inflate = inflate;
  362. exports.inflateRaw = inflateRaw;
  363. exports.ungzip = inflate;