main.js (1063625B)
1 // ==UserScript== 2 // @name musescore-downloader 3 // @namespace https://www.xmader.com/ 4 // @homepageURL https://github.com/Xmader/musescore-downloader/ 5 // @supportURL https://github.com/Xmader/musescore-downloader/issues 6 // @version 0.6.3 7 // @description download sheet music from musescore.com for free, no login or Musescore Pro required | 免登录、免 Musescore Pro,免费下载 musescore.com 上的曲谱 8 // @author Xmader 9 // @match https://musescore.com/*/* 10 // @license MIT 11 // @copyright Copyright (c) 2019-2020 Xmader 12 // @grant none 13 // ==/UserScript== 14 15 (function () { 16 'use strict'; 17 18 function __awaiter(thisArg, _arguments, P, generator) { 19 return new (P || (P = Promise))(function (resolve, reject) { 20 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 21 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 22 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } 23 step((generator = generator.apply(thisArg, _arguments || [])).next()); 24 }); 25 } 26 27 const waitForDocumentLoaded = () => { 28 if (document.readyState !== "complete") { 29 return new Promise(resolve => { 30 document.addEventListener("readystatechange", () => { 31 if (document.readyState == "complete") { 32 resolve(); 33 } 34 }, { once: true }); 35 }); 36 } 37 else { 38 return Promise.resolve(); 39 } 40 }; 41 42 /** 43 * the site key for Google reCAPTCHA v3 44 */ 45 const SITE_KEY = "6Ldxtt8UAAAAALvcRqWTlVOVIB7MmEWwN-zw_9fM"; 46 let gr; 47 /** 48 * load reCAPTCHA 49 */ 50 const load = () => { 51 // load script 52 const script = document.createElement("script"); 53 script.src = `https://www.recaptcha.net/recaptcha/api.js?render=${SITE_KEY}`; 54 script.async = true; 55 document.body.appendChild(script); 56 // add css 57 const style = document.createElement("style"); 58 style.innerHTML = ".grecaptcha-badge { display: none !important; }"; 59 document.head.appendChild(style); 60 return new Promise((resolve) => { 61 script.onload = () => { 62 const grecaptcha = window["grecaptcha"]; 63 grecaptcha.ready(() => resolve(grecaptcha)); 64 }; 65 }); 66 }; 67 const init = () => { 68 if (!gr) { 69 gr = load(); 70 } 71 return gr; 72 }; 73 const execute = () => __awaiter(void 0, void 0, void 0, function* () { 74 const captcha = yield init(); 75 return captcha.execute(SITE_KEY, { action: "downloadmscz" }); 76 }); 77 78 var global$1 = (typeof global !== "undefined" ? global : 79 typeof self !== "undefined" ? self : 80 typeof window !== "undefined" ? window : {}); 81 82 const PDFWorker = function () { 83 (function () { 84 85 function __awaiter(thisArg, _arguments, P, generator) { 86 return new (P || (P = Promise))(function (resolve, reject) { 87 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 88 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 89 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } 90 step((generator = generator.apply(thisArg, _arguments || [])).next()); 91 }); 92 } 93 94 var global$1$1 = (typeof global$1 !== "undefined" ? global$1 : 95 typeof self !== "undefined" ? self : 96 typeof window !== "undefined" ? window : {}); 97 98 var lookup = []; 99 var revLookup = []; 100 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; 101 var inited = false; 102 function init () { 103 inited = true; 104 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; 105 for (var i = 0, len = code.length; i < len; ++i) { 106 lookup[i] = code[i]; 107 revLookup[code.charCodeAt(i)] = i; 108 } 109 110 revLookup['-'.charCodeAt(0)] = 62; 111 revLookup['_'.charCodeAt(0)] = 63; 112 } 113 114 function toByteArray (b64) { 115 if (!inited) { 116 init(); 117 } 118 var i, j, l, tmp, placeHolders, arr; 119 var len = b64.length; 120 121 if (len % 4 > 0) { 122 throw new Error('Invalid string. Length must be a multiple of 4') 123 } 124 125 // the number of equal signs (place holders) 126 // if there are two placeholders, than the two characters before it 127 // represent one byte 128 // if there is only one, then the three characters before it represent 2 bytes 129 // this is just a cheap hack to not do indexOf twice 130 placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; 131 132 // base64 is 4/3 + up to two characters of the original data 133 arr = new Arr(len * 3 / 4 - placeHolders); 134 135 // if there are placeholders, only get up to the last complete 4 chars 136 l = placeHolders > 0 ? len - 4 : len; 137 138 var L = 0; 139 140 for (i = 0, j = 0; i < l; i += 4, j += 3) { 141 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; 142 arr[L++] = (tmp >> 16) & 0xFF; 143 arr[L++] = (tmp >> 8) & 0xFF; 144 arr[L++] = tmp & 0xFF; 145 } 146 147 if (placeHolders === 2) { 148 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); 149 arr[L++] = tmp & 0xFF; 150 } else if (placeHolders === 1) { 151 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); 152 arr[L++] = (tmp >> 8) & 0xFF; 153 arr[L++] = tmp & 0xFF; 154 } 155 156 return arr 157 } 158 159 function tripletToBase64 (num) { 160 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] 161 } 162 163 function encodeChunk (uint8, start, end) { 164 var tmp; 165 var output = []; 166 for (var i = start; i < end; i += 3) { 167 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); 168 output.push(tripletToBase64(tmp)); 169 } 170 return output.join('') 171 } 172 173 function fromByteArray (uint8) { 174 if (!inited) { 175 init(); 176 } 177 var tmp; 178 var len = uint8.length; 179 var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes 180 var output = ''; 181 var parts = []; 182 var maxChunkLength = 16383; // must be multiple of 3 183 184 // go through the array every three bytes, we'll deal with trailing stuff later 185 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { 186 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); 187 } 188 189 // pad the end with zeros, but make sure to not forget the extra bytes 190 if (extraBytes === 1) { 191 tmp = uint8[len - 1]; 192 output += lookup[tmp >> 2]; 193 output += lookup[(tmp << 4) & 0x3F]; 194 output += '=='; 195 } else if (extraBytes === 2) { 196 tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); 197 output += lookup[tmp >> 10]; 198 output += lookup[(tmp >> 4) & 0x3F]; 199 output += lookup[(tmp << 2) & 0x3F]; 200 output += '='; 201 } 202 203 parts.push(output); 204 205 return parts.join('') 206 } 207 208 function read (buffer, offset, isLE, mLen, nBytes) { 209 var e, m; 210 var eLen = nBytes * 8 - mLen - 1; 211 var eMax = (1 << eLen) - 1; 212 var eBias = eMax >> 1; 213 var nBits = -7; 214 var i = isLE ? (nBytes - 1) : 0; 215 var d = isLE ? -1 : 1; 216 var s = buffer[offset + i]; 217 218 i += d; 219 220 e = s & ((1 << (-nBits)) - 1); 221 s >>= (-nBits); 222 nBits += eLen; 223 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} 224 225 m = e & ((1 << (-nBits)) - 1); 226 e >>= (-nBits); 227 nBits += mLen; 228 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} 229 230 if (e === 0) { 231 e = 1 - eBias; 232 } else if (e === eMax) { 233 return m ? NaN : ((s ? -1 : 1) * Infinity) 234 } else { 235 m = m + Math.pow(2, mLen); 236 e = e - eBias; 237 } 238 return (s ? -1 : 1) * m * Math.pow(2, e - mLen) 239 } 240 241 function write (buffer, value, offset, isLE, mLen, nBytes) { 242 var e, m, c; 243 var eLen = nBytes * 8 - mLen - 1; 244 var eMax = (1 << eLen) - 1; 245 var eBias = eMax >> 1; 246 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); 247 var i = isLE ? 0 : (nBytes - 1); 248 var d = isLE ? 1 : -1; 249 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; 250 251 value = Math.abs(value); 252 253 if (isNaN(value) || value === Infinity) { 254 m = isNaN(value) ? 1 : 0; 255 e = eMax; 256 } else { 257 e = Math.floor(Math.log(value) / Math.LN2); 258 if (value * (c = Math.pow(2, -e)) < 1) { 259 e--; 260 c *= 2; 261 } 262 if (e + eBias >= 1) { 263 value += rt / c; 264 } else { 265 value += rt * Math.pow(2, 1 - eBias); 266 } 267 if (value * c >= 2) { 268 e++; 269 c /= 2; 270 } 271 272 if (e + eBias >= eMax) { 273 m = 0; 274 e = eMax; 275 } else if (e + eBias >= 1) { 276 m = (value * c - 1) * Math.pow(2, mLen); 277 e = e + eBias; 278 } else { 279 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); 280 e = 0; 281 } 282 } 283 284 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} 285 286 e = (e << mLen) | m; 287 eLen += mLen; 288 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} 289 290 buffer[offset + i - d] |= s * 128; 291 } 292 293 var toString = {}.toString; 294 295 var isArray = Array.isArray || function (arr) { 296 return toString.call(arr) == '[object Array]'; 297 }; 298 299 var INSPECT_MAX_BYTES = 50; 300 301 /** 302 * If `Buffer.TYPED_ARRAY_SUPPORT`: 303 * === true Use Uint8Array implementation (fastest) 304 * === false Use Object implementation (most compatible, even IE6) 305 * 306 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, 307 * Opera 11.6+, iOS 4.2+. 308 * 309 * Due to various browser bugs, sometimes the Object implementation will be used even 310 * when the browser supports typed arrays. 311 * 312 * Note: 313 * 314 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, 315 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. 316 * 317 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. 318 * 319 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of 320 * incorrect length in some situations. 321 322 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they 323 * get the Object implementation, which is slower but behaves correctly. 324 */ 325 Buffer.TYPED_ARRAY_SUPPORT = global$1$1.TYPED_ARRAY_SUPPORT !== undefined 326 ? global$1$1.TYPED_ARRAY_SUPPORT 327 : true; 328 329 function kMaxLength () { 330 return Buffer.TYPED_ARRAY_SUPPORT 331 ? 0x7fffffff 332 : 0x3fffffff 333 } 334 335 function createBuffer (that, length) { 336 if (kMaxLength() < length) { 337 throw new RangeError('Invalid typed array length') 338 } 339 if (Buffer.TYPED_ARRAY_SUPPORT) { 340 // Return an augmented `Uint8Array` instance, for best performance 341 that = new Uint8Array(length); 342 that.__proto__ = Buffer.prototype; 343 } else { 344 // Fallback: Return an object instance of the Buffer class 345 if (that === null) { 346 that = new Buffer(length); 347 } 348 that.length = length; 349 } 350 351 return that 352 } 353 354 /** 355 * The Buffer constructor returns instances of `Uint8Array` that have their 356 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of 357 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods 358 * and the `Uint8Array` methods. Square bracket notation works as expected -- it 359 * returns a single octet. 360 * 361 * The `Uint8Array` prototype remains unmodified. 362 */ 363 364 function Buffer (arg, encodingOrOffset, length) { 365 if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { 366 return new Buffer(arg, encodingOrOffset, length) 367 } 368 369 // Common case. 370 if (typeof arg === 'number') { 371 if (typeof encodingOrOffset === 'string') { 372 throw new Error( 373 'If encoding is specified then the first argument must be a string' 374 ) 375 } 376 return allocUnsafe(this, arg) 377 } 378 return from(this, arg, encodingOrOffset, length) 379 } 380 381 Buffer.poolSize = 8192; // not used by this implementation 382 383 // TODO: Legacy, not needed anymore. Remove in next major version. 384 Buffer._augment = function (arr) { 385 arr.__proto__ = Buffer.prototype; 386 return arr 387 }; 388 389 function from (that, value, encodingOrOffset, length) { 390 if (typeof value === 'number') { 391 throw new TypeError('"value" argument must not be a number') 392 } 393 394 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { 395 return fromArrayBuffer(that, value, encodingOrOffset, length) 396 } 397 398 if (typeof value === 'string') { 399 return fromString(that, value, encodingOrOffset) 400 } 401 402 return fromObject(that, value) 403 } 404 405 /** 406 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError 407 * if value is a number. 408 * Buffer.from(str[, encoding]) 409 * Buffer.from(array) 410 * Buffer.from(buffer) 411 * Buffer.from(arrayBuffer[, byteOffset[, length]]) 412 **/ 413 Buffer.from = function (value, encodingOrOffset, length) { 414 return from(null, value, encodingOrOffset, length) 415 }; 416 417 if (Buffer.TYPED_ARRAY_SUPPORT) { 418 Buffer.prototype.__proto__ = Uint8Array.prototype; 419 Buffer.__proto__ = Uint8Array; 420 } 421 422 function assertSize (size) { 423 if (typeof size !== 'number') { 424 throw new TypeError('"size" argument must be a number') 425 } else if (size < 0) { 426 throw new RangeError('"size" argument must not be negative') 427 } 428 } 429 430 function alloc (that, size, fill, encoding) { 431 assertSize(size); 432 if (size <= 0) { 433 return createBuffer(that, size) 434 } 435 if (fill !== undefined) { 436 // Only pay attention to encoding if it's a string. This 437 // prevents accidentally sending in a number that would 438 // be interpretted as a start offset. 439 return typeof encoding === 'string' 440 ? createBuffer(that, size).fill(fill, encoding) 441 : createBuffer(that, size).fill(fill) 442 } 443 return createBuffer(that, size) 444 } 445 446 /** 447 * Creates a new filled Buffer instance. 448 * alloc(size[, fill[, encoding]]) 449 **/ 450 Buffer.alloc = function (size, fill, encoding) { 451 return alloc(null, size, fill, encoding) 452 }; 453 454 function allocUnsafe (that, size) { 455 assertSize(size); 456 that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); 457 if (!Buffer.TYPED_ARRAY_SUPPORT) { 458 for (var i = 0; i < size; ++i) { 459 that[i] = 0; 460 } 461 } 462 return that 463 } 464 465 /** 466 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. 467 * */ 468 Buffer.allocUnsafe = function (size) { 469 return allocUnsafe(null, size) 470 }; 471 /** 472 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. 473 */ 474 Buffer.allocUnsafeSlow = function (size) { 475 return allocUnsafe(null, size) 476 }; 477 478 function fromString (that, string, encoding) { 479 if (typeof encoding !== 'string' || encoding === '') { 480 encoding = 'utf8'; 481 } 482 483 if (!Buffer.isEncoding(encoding)) { 484 throw new TypeError('"encoding" must be a valid string encoding') 485 } 486 487 var length = byteLength(string, encoding) | 0; 488 that = createBuffer(that, length); 489 490 var actual = that.write(string, encoding); 491 492 if (actual !== length) { 493 // Writing a hex string, for example, that contains invalid characters will 494 // cause everything after the first invalid character to be ignored. (e.g. 495 // 'abxxcd' will be treated as 'ab') 496 that = that.slice(0, actual); 497 } 498 499 return that 500 } 501 502 function fromArrayLike (that, array) { 503 var length = array.length < 0 ? 0 : checked(array.length) | 0; 504 that = createBuffer(that, length); 505 for (var i = 0; i < length; i += 1) { 506 that[i] = array[i] & 255; 507 } 508 return that 509 } 510 511 function fromArrayBuffer (that, array, byteOffset, length) { 512 array.byteLength; // this throws if `array` is not a valid ArrayBuffer 513 514 if (byteOffset < 0 || array.byteLength < byteOffset) { 515 throw new RangeError('\'offset\' is out of bounds') 516 } 517 518 if (array.byteLength < byteOffset + (length || 0)) { 519 throw new RangeError('\'length\' is out of bounds') 520 } 521 522 if (byteOffset === undefined && length === undefined) { 523 array = new Uint8Array(array); 524 } else if (length === undefined) { 525 array = new Uint8Array(array, byteOffset); 526 } else { 527 array = new Uint8Array(array, byteOffset, length); 528 } 529 530 if (Buffer.TYPED_ARRAY_SUPPORT) { 531 // Return an augmented `Uint8Array` instance, for best performance 532 that = array; 533 that.__proto__ = Buffer.prototype; 534 } else { 535 // Fallback: Return an object instance of the Buffer class 536 that = fromArrayLike(that, array); 537 } 538 return that 539 } 540 541 function fromObject (that, obj) { 542 if (internalIsBuffer(obj)) { 543 var len = checked(obj.length) | 0; 544 that = createBuffer(that, len); 545 546 if (that.length === 0) { 547 return that 548 } 549 550 obj.copy(that, 0, 0, len); 551 return that 552 } 553 554 if (obj) { 555 if ((typeof ArrayBuffer !== 'undefined' && 556 obj.buffer instanceof ArrayBuffer) || 'length' in obj) { 557 if (typeof obj.length !== 'number' || isnan(obj.length)) { 558 return createBuffer(that, 0) 559 } 560 return fromArrayLike(that, obj) 561 } 562 563 if (obj.type === 'Buffer' && isArray(obj.data)) { 564 return fromArrayLike(that, obj.data) 565 } 566 } 567 568 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') 569 } 570 571 function checked (length) { 572 // Note: cannot use `length < kMaxLength()` here because that fails when 573 // length is NaN (which is otherwise coerced to zero.) 574 if (length >= kMaxLength()) { 575 throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 576 'size: 0x' + kMaxLength().toString(16) + ' bytes') 577 } 578 return length | 0 579 } 580 Buffer.isBuffer = isBuffer; 581 function internalIsBuffer (b) { 582 return !!(b != null && b._isBuffer) 583 } 584 585 Buffer.compare = function compare (a, b) { 586 if (!internalIsBuffer(a) || !internalIsBuffer(b)) { 587 throw new TypeError('Arguments must be Buffers') 588 } 589 590 if (a === b) return 0 591 592 var x = a.length; 593 var y = b.length; 594 595 for (var i = 0, len = Math.min(x, y); i < len; ++i) { 596 if (a[i] !== b[i]) { 597 x = a[i]; 598 y = b[i]; 599 break 600 } 601 } 602 603 if (x < y) return -1 604 if (y < x) return 1 605 return 0 606 }; 607 608 Buffer.isEncoding = function isEncoding (encoding) { 609 switch (String(encoding).toLowerCase()) { 610 case 'hex': 611 case 'utf8': 612 case 'utf-8': 613 case 'ascii': 614 case 'latin1': 615 case 'binary': 616 case 'base64': 617 case 'ucs2': 618 case 'ucs-2': 619 case 'utf16le': 620 case 'utf-16le': 621 return true 622 default: 623 return false 624 } 625 }; 626 627 Buffer.concat = function concat (list, length) { 628 if (!isArray(list)) { 629 throw new TypeError('"list" argument must be an Array of Buffers') 630 } 631 632 if (list.length === 0) { 633 return Buffer.alloc(0) 634 } 635 636 var i; 637 if (length === undefined) { 638 length = 0; 639 for (i = 0; i < list.length; ++i) { 640 length += list[i].length; 641 } 642 } 643 644 var buffer = Buffer.allocUnsafe(length); 645 var pos = 0; 646 for (i = 0; i < list.length; ++i) { 647 var buf = list[i]; 648 if (!internalIsBuffer(buf)) { 649 throw new TypeError('"list" argument must be an Array of Buffers') 650 } 651 buf.copy(buffer, pos); 652 pos += buf.length; 653 } 654 return buffer 655 }; 656 657 function byteLength (string, encoding) { 658 if (internalIsBuffer(string)) { 659 return string.length 660 } 661 if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && 662 (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { 663 return string.byteLength 664 } 665 if (typeof string !== 'string') { 666 string = '' + string; 667 } 668 669 var len = string.length; 670 if (len === 0) return 0 671 672 // Use a for loop to avoid recursion 673 var loweredCase = false; 674 for (;;) { 675 switch (encoding) { 676 case 'ascii': 677 case 'latin1': 678 case 'binary': 679 return len 680 case 'utf8': 681 case 'utf-8': 682 case undefined: 683 return utf8ToBytes(string).length 684 case 'ucs2': 685 case 'ucs-2': 686 case 'utf16le': 687 case 'utf-16le': 688 return len * 2 689 case 'hex': 690 return len >>> 1 691 case 'base64': 692 return base64ToBytes(string).length 693 default: 694 if (loweredCase) return utf8ToBytes(string).length // assume utf8 695 encoding = ('' + encoding).toLowerCase(); 696 loweredCase = true; 697 } 698 } 699 } 700 Buffer.byteLength = byteLength; 701 702 function slowToString (encoding, start, end) { 703 var loweredCase = false; 704 705 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only 706 // property of a typed array. 707 708 // This behaves neither like String nor Uint8Array in that we set start/end 709 // to their upper/lower bounds if the value passed is out of range. 710 // undefined is handled specially as per ECMA-262 6th Edition, 711 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. 712 if (start === undefined || start < 0) { 713 start = 0; 714 } 715 // Return early if start > this.length. Done here to prevent potential uint32 716 // coercion fail below. 717 if (start > this.length) { 718 return '' 719 } 720 721 if (end === undefined || end > this.length) { 722 end = this.length; 723 } 724 725 if (end <= 0) { 726 return '' 727 } 728 729 // Force coersion to uint32. This will also coerce falsey/NaN values to 0. 730 end >>>= 0; 731 start >>>= 0; 732 733 if (end <= start) { 734 return '' 735 } 736 737 if (!encoding) encoding = 'utf8'; 738 739 while (true) { 740 switch (encoding) { 741 case 'hex': 742 return hexSlice(this, start, end) 743 744 case 'utf8': 745 case 'utf-8': 746 return utf8Slice(this, start, end) 747 748 case 'ascii': 749 return asciiSlice(this, start, end) 750 751 case 'latin1': 752 case 'binary': 753 return latin1Slice(this, start, end) 754 755 case 'base64': 756 return base64Slice(this, start, end) 757 758 case 'ucs2': 759 case 'ucs-2': 760 case 'utf16le': 761 case 'utf-16le': 762 return utf16leSlice(this, start, end) 763 764 default: 765 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) 766 encoding = (encoding + '').toLowerCase(); 767 loweredCase = true; 768 } 769 } 770 } 771 772 // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect 773 // Buffer instances. 774 Buffer.prototype._isBuffer = true; 775 776 function swap (b, n, m) { 777 var i = b[n]; 778 b[n] = b[m]; 779 b[m] = i; 780 } 781 782 Buffer.prototype.swap16 = function swap16 () { 783 var len = this.length; 784 if (len % 2 !== 0) { 785 throw new RangeError('Buffer size must be a multiple of 16-bits') 786 } 787 for (var i = 0; i < len; i += 2) { 788 swap(this, i, i + 1); 789 } 790 return this 791 }; 792 793 Buffer.prototype.swap32 = function swap32 () { 794 var len = this.length; 795 if (len % 4 !== 0) { 796 throw new RangeError('Buffer size must be a multiple of 32-bits') 797 } 798 for (var i = 0; i < len; i += 4) { 799 swap(this, i, i + 3); 800 swap(this, i + 1, i + 2); 801 } 802 return this 803 }; 804 805 Buffer.prototype.swap64 = function swap64 () { 806 var len = this.length; 807 if (len % 8 !== 0) { 808 throw new RangeError('Buffer size must be a multiple of 64-bits') 809 } 810 for (var i = 0; i < len; i += 8) { 811 swap(this, i, i + 7); 812 swap(this, i + 1, i + 6); 813 swap(this, i + 2, i + 5); 814 swap(this, i + 3, i + 4); 815 } 816 return this 817 }; 818 819 Buffer.prototype.toString = function toString () { 820 var length = this.length | 0; 821 if (length === 0) return '' 822 if (arguments.length === 0) return utf8Slice(this, 0, length) 823 return slowToString.apply(this, arguments) 824 }; 825 826 Buffer.prototype.equals = function equals (b) { 827 if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') 828 if (this === b) return true 829 return Buffer.compare(this, b) === 0 830 }; 831 832 Buffer.prototype.inspect = function inspect () { 833 var str = ''; 834 var max = INSPECT_MAX_BYTES; 835 if (this.length > 0) { 836 str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); 837 if (this.length > max) str += ' ... '; 838 } 839 return '<Buffer ' + str + '>' 840 }; 841 842 Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { 843 if (!internalIsBuffer(target)) { 844 throw new TypeError('Argument must be a Buffer') 845 } 846 847 if (start === undefined) { 848 start = 0; 849 } 850 if (end === undefined) { 851 end = target ? target.length : 0; 852 } 853 if (thisStart === undefined) { 854 thisStart = 0; 855 } 856 if (thisEnd === undefined) { 857 thisEnd = this.length; 858 } 859 860 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { 861 throw new RangeError('out of range index') 862 } 863 864 if (thisStart >= thisEnd && start >= end) { 865 return 0 866 } 867 if (thisStart >= thisEnd) { 868 return -1 869 } 870 if (start >= end) { 871 return 1 872 } 873 874 start >>>= 0; 875 end >>>= 0; 876 thisStart >>>= 0; 877 thisEnd >>>= 0; 878 879 if (this === target) return 0 880 881 var x = thisEnd - thisStart; 882 var y = end - start; 883 var len = Math.min(x, y); 884 885 var thisCopy = this.slice(thisStart, thisEnd); 886 var targetCopy = target.slice(start, end); 887 888 for (var i = 0; i < len; ++i) { 889 if (thisCopy[i] !== targetCopy[i]) { 890 x = thisCopy[i]; 891 y = targetCopy[i]; 892 break 893 } 894 } 895 896 if (x < y) return -1 897 if (y < x) return 1 898 return 0 899 }; 900 901 // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, 902 // OR the last index of `val` in `buffer` at offset <= `byteOffset`. 903 // 904 // Arguments: 905 // - buffer - a Buffer to search 906 // - val - a string, Buffer, or number 907 // - byteOffset - an index into `buffer`; will be clamped to an int32 908 // - encoding - an optional encoding, relevant is val is a string 909 // - dir - true for indexOf, false for lastIndexOf 910 function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { 911 // Empty buffer means no match 912 if (buffer.length === 0) return -1 913 914 // Normalize byteOffset 915 if (typeof byteOffset === 'string') { 916 encoding = byteOffset; 917 byteOffset = 0; 918 } else if (byteOffset > 0x7fffffff) { 919 byteOffset = 0x7fffffff; 920 } else if (byteOffset < -0x80000000) { 921 byteOffset = -0x80000000; 922 } 923 byteOffset = +byteOffset; // Coerce to Number. 924 if (isNaN(byteOffset)) { 925 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer 926 byteOffset = dir ? 0 : (buffer.length - 1); 927 } 928 929 // Normalize byteOffset: negative offsets start from the end of the buffer 930 if (byteOffset < 0) byteOffset = buffer.length + byteOffset; 931 if (byteOffset >= buffer.length) { 932 if (dir) return -1 933 else byteOffset = buffer.length - 1; 934 } else if (byteOffset < 0) { 935 if (dir) byteOffset = 0; 936 else return -1 937 } 938 939 // Normalize val 940 if (typeof val === 'string') { 941 val = Buffer.from(val, encoding); 942 } 943 944 // Finally, search either indexOf (if dir is true) or lastIndexOf 945 if (internalIsBuffer(val)) { 946 // Special case: looking for empty string/buffer always fails 947 if (val.length === 0) { 948 return -1 949 } 950 return arrayIndexOf(buffer, val, byteOffset, encoding, dir) 951 } else if (typeof val === 'number') { 952 val = val & 0xFF; // Search for a byte value [0-255] 953 if (Buffer.TYPED_ARRAY_SUPPORT && 954 typeof Uint8Array.prototype.indexOf === 'function') { 955 if (dir) { 956 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) 957 } else { 958 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) 959 } 960 } 961 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) 962 } 963 964 throw new TypeError('val must be string, number or Buffer') 965 } 966 967 function arrayIndexOf (arr, val, byteOffset, encoding, dir) { 968 var indexSize = 1; 969 var arrLength = arr.length; 970 var valLength = val.length; 971 972 if (encoding !== undefined) { 973 encoding = String(encoding).toLowerCase(); 974 if (encoding === 'ucs2' || encoding === 'ucs-2' || 975 encoding === 'utf16le' || encoding === 'utf-16le') { 976 if (arr.length < 2 || val.length < 2) { 977 return -1 978 } 979 indexSize = 2; 980 arrLength /= 2; 981 valLength /= 2; 982 byteOffset /= 2; 983 } 984 } 985 986 function read (buf, i) { 987 if (indexSize === 1) { 988 return buf[i] 989 } else { 990 return buf.readUInt16BE(i * indexSize) 991 } 992 } 993 994 var i; 995 if (dir) { 996 var foundIndex = -1; 997 for (i = byteOffset; i < arrLength; i++) { 998 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { 999 if (foundIndex === -1) foundIndex = i; 1000 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize 1001 } else { 1002 if (foundIndex !== -1) i -= i - foundIndex; 1003 foundIndex = -1; 1004 } 1005 } 1006 } else { 1007 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; 1008 for (i = byteOffset; i >= 0; i--) { 1009 var found = true; 1010 for (var j = 0; j < valLength; j++) { 1011 if (read(arr, i + j) !== read(val, j)) { 1012 found = false; 1013 break 1014 } 1015 } 1016 if (found) return i 1017 } 1018 } 1019 1020 return -1 1021 } 1022 1023 Buffer.prototype.includes = function includes (val, byteOffset, encoding) { 1024 return this.indexOf(val, byteOffset, encoding) !== -1 1025 }; 1026 1027 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { 1028 return bidirectionalIndexOf(this, val, byteOffset, encoding, true) 1029 }; 1030 1031 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { 1032 return bidirectionalIndexOf(this, val, byteOffset, encoding, false) 1033 }; 1034 1035 function hexWrite (buf, string, offset, length) { 1036 offset = Number(offset) || 0; 1037 var remaining = buf.length - offset; 1038 if (!length) { 1039 length = remaining; 1040 } else { 1041 length = Number(length); 1042 if (length > remaining) { 1043 length = remaining; 1044 } 1045 } 1046 1047 // must be an even number of digits 1048 var strLen = string.length; 1049 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') 1050 1051 if (length > strLen / 2) { 1052 length = strLen / 2; 1053 } 1054 for (var i = 0; i < length; ++i) { 1055 var parsed = parseInt(string.substr(i * 2, 2), 16); 1056 if (isNaN(parsed)) return i 1057 buf[offset + i] = parsed; 1058 } 1059 return i 1060 } 1061 1062 function utf8Write (buf, string, offset, length) { 1063 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) 1064 } 1065 1066 function asciiWrite (buf, string, offset, length) { 1067 return blitBuffer(asciiToBytes(string), buf, offset, length) 1068 } 1069 1070 function latin1Write (buf, string, offset, length) { 1071 return asciiWrite(buf, string, offset, length) 1072 } 1073 1074 function base64Write (buf, string, offset, length) { 1075 return blitBuffer(base64ToBytes(string), buf, offset, length) 1076 } 1077 1078 function ucs2Write (buf, string, offset, length) { 1079 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) 1080 } 1081 1082 Buffer.prototype.write = function write (string, offset, length, encoding) { 1083 // Buffer#write(string) 1084 if (offset === undefined) { 1085 encoding = 'utf8'; 1086 length = this.length; 1087 offset = 0; 1088 // Buffer#write(string, encoding) 1089 } else if (length === undefined && typeof offset === 'string') { 1090 encoding = offset; 1091 length = this.length; 1092 offset = 0; 1093 // Buffer#write(string, offset[, length][, encoding]) 1094 } else if (isFinite(offset)) { 1095 offset = offset | 0; 1096 if (isFinite(length)) { 1097 length = length | 0; 1098 if (encoding === undefined) encoding = 'utf8'; 1099 } else { 1100 encoding = length; 1101 length = undefined; 1102 } 1103 // legacy write(string, encoding, offset, length) - remove in v0.13 1104 } else { 1105 throw new Error( 1106 'Buffer.write(string, encoding, offset[, length]) is no longer supported' 1107 ) 1108 } 1109 1110 var remaining = this.length - offset; 1111 if (length === undefined || length > remaining) length = remaining; 1112 1113 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { 1114 throw new RangeError('Attempt to write outside buffer bounds') 1115 } 1116 1117 if (!encoding) encoding = 'utf8'; 1118 1119 var loweredCase = false; 1120 for (;;) { 1121 switch (encoding) { 1122 case 'hex': 1123 return hexWrite(this, string, offset, length) 1124 1125 case 'utf8': 1126 case 'utf-8': 1127 return utf8Write(this, string, offset, length) 1128 1129 case 'ascii': 1130 return asciiWrite(this, string, offset, length) 1131 1132 case 'latin1': 1133 case 'binary': 1134 return latin1Write(this, string, offset, length) 1135 1136 case 'base64': 1137 // Warning: maxLength not taken into account in base64Write 1138 return base64Write(this, string, offset, length) 1139 1140 case 'ucs2': 1141 case 'ucs-2': 1142 case 'utf16le': 1143 case 'utf-16le': 1144 return ucs2Write(this, string, offset, length) 1145 1146 default: 1147 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) 1148 encoding = ('' + encoding).toLowerCase(); 1149 loweredCase = true; 1150 } 1151 } 1152 }; 1153 1154 Buffer.prototype.toJSON = function toJSON () { 1155 return { 1156 type: 'Buffer', 1157 data: Array.prototype.slice.call(this._arr || this, 0) 1158 } 1159 }; 1160 1161 function base64Slice (buf, start, end) { 1162 if (start === 0 && end === buf.length) { 1163 return fromByteArray(buf) 1164 } else { 1165 return fromByteArray(buf.slice(start, end)) 1166 } 1167 } 1168 1169 function utf8Slice (buf, start, end) { 1170 end = Math.min(buf.length, end); 1171 var res = []; 1172 1173 var i = start; 1174 while (i < end) { 1175 var firstByte = buf[i]; 1176 var codePoint = null; 1177 var bytesPerSequence = (firstByte > 0xEF) ? 4 1178 : (firstByte > 0xDF) ? 3 1179 : (firstByte > 0xBF) ? 2 1180 : 1; 1181 1182 if (i + bytesPerSequence <= end) { 1183 var secondByte, thirdByte, fourthByte, tempCodePoint; 1184 1185 switch (bytesPerSequence) { 1186 case 1: 1187 if (firstByte < 0x80) { 1188 codePoint = firstByte; 1189 } 1190 break 1191 case 2: 1192 secondByte = buf[i + 1]; 1193 if ((secondByte & 0xC0) === 0x80) { 1194 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); 1195 if (tempCodePoint > 0x7F) { 1196 codePoint = tempCodePoint; 1197 } 1198 } 1199 break 1200 case 3: 1201 secondByte = buf[i + 1]; 1202 thirdByte = buf[i + 2]; 1203 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { 1204 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); 1205 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { 1206 codePoint = tempCodePoint; 1207 } 1208 } 1209 break 1210 case 4: 1211 secondByte = buf[i + 1]; 1212 thirdByte = buf[i + 2]; 1213 fourthByte = buf[i + 3]; 1214 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { 1215 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); 1216 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { 1217 codePoint = tempCodePoint; 1218 } 1219 } 1220 } 1221 } 1222 1223 if (codePoint === null) { 1224 // we did not generate a valid codePoint so insert a 1225 // replacement char (U+FFFD) and advance only 1 byte 1226 codePoint = 0xFFFD; 1227 bytesPerSequence = 1; 1228 } else if (codePoint > 0xFFFF) { 1229 // encode to utf16 (surrogate pair dance) 1230 codePoint -= 0x10000; 1231 res.push(codePoint >>> 10 & 0x3FF | 0xD800); 1232 codePoint = 0xDC00 | codePoint & 0x3FF; 1233 } 1234 1235 res.push(codePoint); 1236 i += bytesPerSequence; 1237 } 1238 1239 return decodeCodePointsArray(res) 1240 } 1241 1242 // Based on http://stackoverflow.com/a/22747272/680742, the browser with 1243 // the lowest limit is Chrome, with 0x10000 args. 1244 // We go 1 magnitude less, for safety 1245 var MAX_ARGUMENTS_LENGTH = 0x1000; 1246 1247 function decodeCodePointsArray (codePoints) { 1248 var len = codePoints.length; 1249 if (len <= MAX_ARGUMENTS_LENGTH) { 1250 return String.fromCharCode.apply(String, codePoints) // avoid extra slice() 1251 } 1252 1253 // Decode in chunks to avoid "call stack size exceeded". 1254 var res = ''; 1255 var i = 0; 1256 while (i < len) { 1257 res += String.fromCharCode.apply( 1258 String, 1259 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) 1260 ); 1261 } 1262 return res 1263 } 1264 1265 function asciiSlice (buf, start, end) { 1266 var ret = ''; 1267 end = Math.min(buf.length, end); 1268 1269 for (var i = start; i < end; ++i) { 1270 ret += String.fromCharCode(buf[i] & 0x7F); 1271 } 1272 return ret 1273 } 1274 1275 function latin1Slice (buf, start, end) { 1276 var ret = ''; 1277 end = Math.min(buf.length, end); 1278 1279 for (var i = start; i < end; ++i) { 1280 ret += String.fromCharCode(buf[i]); 1281 } 1282 return ret 1283 } 1284 1285 function hexSlice (buf, start, end) { 1286 var len = buf.length; 1287 1288 if (!start || start < 0) start = 0; 1289 if (!end || end < 0 || end > len) end = len; 1290 1291 var out = ''; 1292 for (var i = start; i < end; ++i) { 1293 out += toHex(buf[i]); 1294 } 1295 return out 1296 } 1297 1298 function utf16leSlice (buf, start, end) { 1299 var bytes = buf.slice(start, end); 1300 var res = ''; 1301 for (var i = 0; i < bytes.length; i += 2) { 1302 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); 1303 } 1304 return res 1305 } 1306 1307 Buffer.prototype.slice = function slice (start, end) { 1308 var len = this.length; 1309 start = ~~start; 1310 end = end === undefined ? len : ~~end; 1311 1312 if (start < 0) { 1313 start += len; 1314 if (start < 0) start = 0; 1315 } else if (start > len) { 1316 start = len; 1317 } 1318 1319 if (end < 0) { 1320 end += len; 1321 if (end < 0) end = 0; 1322 } else if (end > len) { 1323 end = len; 1324 } 1325 1326 if (end < start) end = start; 1327 1328 var newBuf; 1329 if (Buffer.TYPED_ARRAY_SUPPORT) { 1330 newBuf = this.subarray(start, end); 1331 newBuf.__proto__ = Buffer.prototype; 1332 } else { 1333 var sliceLen = end - start; 1334 newBuf = new Buffer(sliceLen, undefined); 1335 for (var i = 0; i < sliceLen; ++i) { 1336 newBuf[i] = this[i + start]; 1337 } 1338 } 1339 1340 return newBuf 1341 }; 1342 1343 /* 1344 * Need to make sure that buffer isn't trying to write out of bounds. 1345 */ 1346 function checkOffset (offset, ext, length) { 1347 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') 1348 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') 1349 } 1350 1351 Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { 1352 offset = offset | 0; 1353 byteLength = byteLength | 0; 1354 if (!noAssert) checkOffset(offset, byteLength, this.length); 1355 1356 var val = this[offset]; 1357 var mul = 1; 1358 var i = 0; 1359 while (++i < byteLength && (mul *= 0x100)) { 1360 val += this[offset + i] * mul; 1361 } 1362 1363 return val 1364 }; 1365 1366 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { 1367 offset = offset | 0; 1368 byteLength = byteLength | 0; 1369 if (!noAssert) { 1370 checkOffset(offset, byteLength, this.length); 1371 } 1372 1373 var val = this[offset + --byteLength]; 1374 var mul = 1; 1375 while (byteLength > 0 && (mul *= 0x100)) { 1376 val += this[offset + --byteLength] * mul; 1377 } 1378 1379 return val 1380 }; 1381 1382 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { 1383 if (!noAssert) checkOffset(offset, 1, this.length); 1384 return this[offset] 1385 }; 1386 1387 Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { 1388 if (!noAssert) checkOffset(offset, 2, this.length); 1389 return this[offset] | (this[offset + 1] << 8) 1390 }; 1391 1392 Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { 1393 if (!noAssert) checkOffset(offset, 2, this.length); 1394 return (this[offset] << 8) | this[offset + 1] 1395 }; 1396 1397 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { 1398 if (!noAssert) checkOffset(offset, 4, this.length); 1399 1400 return ((this[offset]) | 1401 (this[offset + 1] << 8) | 1402 (this[offset + 2] << 16)) + 1403 (this[offset + 3] * 0x1000000) 1404 }; 1405 1406 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { 1407 if (!noAssert) checkOffset(offset, 4, this.length); 1408 1409 return (this[offset] * 0x1000000) + 1410 ((this[offset + 1] << 16) | 1411 (this[offset + 2] << 8) | 1412 this[offset + 3]) 1413 }; 1414 1415 Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { 1416 offset = offset | 0; 1417 byteLength = byteLength | 0; 1418 if (!noAssert) checkOffset(offset, byteLength, this.length); 1419 1420 var val = this[offset]; 1421 var mul = 1; 1422 var i = 0; 1423 while (++i < byteLength && (mul *= 0x100)) { 1424 val += this[offset + i] * mul; 1425 } 1426 mul *= 0x80; 1427 1428 if (val >= mul) val -= Math.pow(2, 8 * byteLength); 1429 1430 return val 1431 }; 1432 1433 Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { 1434 offset = offset | 0; 1435 byteLength = byteLength | 0; 1436 if (!noAssert) checkOffset(offset, byteLength, this.length); 1437 1438 var i = byteLength; 1439 var mul = 1; 1440 var val = this[offset + --i]; 1441 while (i > 0 && (mul *= 0x100)) { 1442 val += this[offset + --i] * mul; 1443 } 1444 mul *= 0x80; 1445 1446 if (val >= mul) val -= Math.pow(2, 8 * byteLength); 1447 1448 return val 1449 }; 1450 1451 Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { 1452 if (!noAssert) checkOffset(offset, 1, this.length); 1453 if (!(this[offset] & 0x80)) return (this[offset]) 1454 return ((0xff - this[offset] + 1) * -1) 1455 }; 1456 1457 Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { 1458 if (!noAssert) checkOffset(offset, 2, this.length); 1459 var val = this[offset] | (this[offset + 1] << 8); 1460 return (val & 0x8000) ? val | 0xFFFF0000 : val 1461 }; 1462 1463 Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { 1464 if (!noAssert) checkOffset(offset, 2, this.length); 1465 var val = this[offset + 1] | (this[offset] << 8); 1466 return (val & 0x8000) ? val | 0xFFFF0000 : val 1467 }; 1468 1469 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { 1470 if (!noAssert) checkOffset(offset, 4, this.length); 1471 1472 return (this[offset]) | 1473 (this[offset + 1] << 8) | 1474 (this[offset + 2] << 16) | 1475 (this[offset + 3] << 24) 1476 }; 1477 1478 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { 1479 if (!noAssert) checkOffset(offset, 4, this.length); 1480 1481 return (this[offset] << 24) | 1482 (this[offset + 1] << 16) | 1483 (this[offset + 2] << 8) | 1484 (this[offset + 3]) 1485 }; 1486 1487 Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { 1488 if (!noAssert) checkOffset(offset, 4, this.length); 1489 return read(this, offset, true, 23, 4) 1490 }; 1491 1492 Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { 1493 if (!noAssert) checkOffset(offset, 4, this.length); 1494 return read(this, offset, false, 23, 4) 1495 }; 1496 1497 Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { 1498 if (!noAssert) checkOffset(offset, 8, this.length); 1499 return read(this, offset, true, 52, 8) 1500 }; 1501 1502 Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { 1503 if (!noAssert) checkOffset(offset, 8, this.length); 1504 return read(this, offset, false, 52, 8) 1505 }; 1506 1507 function checkInt (buf, value, offset, ext, max, min) { 1508 if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') 1509 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') 1510 if (offset + ext > buf.length) throw new RangeError('Index out of range') 1511 } 1512 1513 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { 1514 value = +value; 1515 offset = offset | 0; 1516 byteLength = byteLength | 0; 1517 if (!noAssert) { 1518 var maxBytes = Math.pow(2, 8 * byteLength) - 1; 1519 checkInt(this, value, offset, byteLength, maxBytes, 0); 1520 } 1521 1522 var mul = 1; 1523 var i = 0; 1524 this[offset] = value & 0xFF; 1525 while (++i < byteLength && (mul *= 0x100)) { 1526 this[offset + i] = (value / mul) & 0xFF; 1527 } 1528 1529 return offset + byteLength 1530 }; 1531 1532 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { 1533 value = +value; 1534 offset = offset | 0; 1535 byteLength = byteLength | 0; 1536 if (!noAssert) { 1537 var maxBytes = Math.pow(2, 8 * byteLength) - 1; 1538 checkInt(this, value, offset, byteLength, maxBytes, 0); 1539 } 1540 1541 var i = byteLength - 1; 1542 var mul = 1; 1543 this[offset + i] = value & 0xFF; 1544 while (--i >= 0 && (mul *= 0x100)) { 1545 this[offset + i] = (value / mul) & 0xFF; 1546 } 1547 1548 return offset + byteLength 1549 }; 1550 1551 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { 1552 value = +value; 1553 offset = offset | 0; 1554 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); 1555 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); 1556 this[offset] = (value & 0xff); 1557 return offset + 1 1558 }; 1559 1560 function objectWriteUInt16 (buf, value, offset, littleEndian) { 1561 if (value < 0) value = 0xffff + value + 1; 1562 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { 1563 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> 1564 (littleEndian ? i : 1 - i) * 8; 1565 } 1566 } 1567 1568 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { 1569 value = +value; 1570 offset = offset | 0; 1571 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); 1572 if (Buffer.TYPED_ARRAY_SUPPORT) { 1573 this[offset] = (value & 0xff); 1574 this[offset + 1] = (value >>> 8); 1575 } else { 1576 objectWriteUInt16(this, value, offset, true); 1577 } 1578 return offset + 2 1579 }; 1580 1581 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { 1582 value = +value; 1583 offset = offset | 0; 1584 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); 1585 if (Buffer.TYPED_ARRAY_SUPPORT) { 1586 this[offset] = (value >>> 8); 1587 this[offset + 1] = (value & 0xff); 1588 } else { 1589 objectWriteUInt16(this, value, offset, false); 1590 } 1591 return offset + 2 1592 }; 1593 1594 function objectWriteUInt32 (buf, value, offset, littleEndian) { 1595 if (value < 0) value = 0xffffffff + value + 1; 1596 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { 1597 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; 1598 } 1599 } 1600 1601 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { 1602 value = +value; 1603 offset = offset | 0; 1604 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); 1605 if (Buffer.TYPED_ARRAY_SUPPORT) { 1606 this[offset + 3] = (value >>> 24); 1607 this[offset + 2] = (value >>> 16); 1608 this[offset + 1] = (value >>> 8); 1609 this[offset] = (value & 0xff); 1610 } else { 1611 objectWriteUInt32(this, value, offset, true); 1612 } 1613 return offset + 4 1614 }; 1615 1616 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { 1617 value = +value; 1618 offset = offset | 0; 1619 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); 1620 if (Buffer.TYPED_ARRAY_SUPPORT) { 1621 this[offset] = (value >>> 24); 1622 this[offset + 1] = (value >>> 16); 1623 this[offset + 2] = (value >>> 8); 1624 this[offset + 3] = (value & 0xff); 1625 } else { 1626 objectWriteUInt32(this, value, offset, false); 1627 } 1628 return offset + 4 1629 }; 1630 1631 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { 1632 value = +value; 1633 offset = offset | 0; 1634 if (!noAssert) { 1635 var limit = Math.pow(2, 8 * byteLength - 1); 1636 1637 checkInt(this, value, offset, byteLength, limit - 1, -limit); 1638 } 1639 1640 var i = 0; 1641 var mul = 1; 1642 var sub = 0; 1643 this[offset] = value & 0xFF; 1644 while (++i < byteLength && (mul *= 0x100)) { 1645 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { 1646 sub = 1; 1647 } 1648 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; 1649 } 1650 1651 return offset + byteLength 1652 }; 1653 1654 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { 1655 value = +value; 1656 offset = offset | 0; 1657 if (!noAssert) { 1658 var limit = Math.pow(2, 8 * byteLength - 1); 1659 1660 checkInt(this, value, offset, byteLength, limit - 1, -limit); 1661 } 1662 1663 var i = byteLength - 1; 1664 var mul = 1; 1665 var sub = 0; 1666 this[offset + i] = value & 0xFF; 1667 while (--i >= 0 && (mul *= 0x100)) { 1668 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { 1669 sub = 1; 1670 } 1671 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; 1672 } 1673 1674 return offset + byteLength 1675 }; 1676 1677 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { 1678 value = +value; 1679 offset = offset | 0; 1680 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); 1681 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); 1682 if (value < 0) value = 0xff + value + 1; 1683 this[offset] = (value & 0xff); 1684 return offset + 1 1685 }; 1686 1687 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { 1688 value = +value; 1689 offset = offset | 0; 1690 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); 1691 if (Buffer.TYPED_ARRAY_SUPPORT) { 1692 this[offset] = (value & 0xff); 1693 this[offset + 1] = (value >>> 8); 1694 } else { 1695 objectWriteUInt16(this, value, offset, true); 1696 } 1697 return offset + 2 1698 }; 1699 1700 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { 1701 value = +value; 1702 offset = offset | 0; 1703 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); 1704 if (Buffer.TYPED_ARRAY_SUPPORT) { 1705 this[offset] = (value >>> 8); 1706 this[offset + 1] = (value & 0xff); 1707 } else { 1708 objectWriteUInt16(this, value, offset, false); 1709 } 1710 return offset + 2 1711 }; 1712 1713 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { 1714 value = +value; 1715 offset = offset | 0; 1716 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); 1717 if (Buffer.TYPED_ARRAY_SUPPORT) { 1718 this[offset] = (value & 0xff); 1719 this[offset + 1] = (value >>> 8); 1720 this[offset + 2] = (value >>> 16); 1721 this[offset + 3] = (value >>> 24); 1722 } else { 1723 objectWriteUInt32(this, value, offset, true); 1724 } 1725 return offset + 4 1726 }; 1727 1728 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { 1729 value = +value; 1730 offset = offset | 0; 1731 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); 1732 if (value < 0) value = 0xffffffff + value + 1; 1733 if (Buffer.TYPED_ARRAY_SUPPORT) { 1734 this[offset] = (value >>> 24); 1735 this[offset + 1] = (value >>> 16); 1736 this[offset + 2] = (value >>> 8); 1737 this[offset + 3] = (value & 0xff); 1738 } else { 1739 objectWriteUInt32(this, value, offset, false); 1740 } 1741 return offset + 4 1742 }; 1743 1744 function checkIEEE754 (buf, value, offset, ext, max, min) { 1745 if (offset + ext > buf.length) throw new RangeError('Index out of range') 1746 if (offset < 0) throw new RangeError('Index out of range') 1747 } 1748 1749 function writeFloat (buf, value, offset, littleEndian, noAssert) { 1750 if (!noAssert) { 1751 checkIEEE754(buf, value, offset, 4); 1752 } 1753 write(buf, value, offset, littleEndian, 23, 4); 1754 return offset + 4 1755 } 1756 1757 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { 1758 return writeFloat(this, value, offset, true, noAssert) 1759 }; 1760 1761 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { 1762 return writeFloat(this, value, offset, false, noAssert) 1763 }; 1764 1765 function writeDouble (buf, value, offset, littleEndian, noAssert) { 1766 if (!noAssert) { 1767 checkIEEE754(buf, value, offset, 8); 1768 } 1769 write(buf, value, offset, littleEndian, 52, 8); 1770 return offset + 8 1771 } 1772 1773 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { 1774 return writeDouble(this, value, offset, true, noAssert) 1775 }; 1776 1777 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { 1778 return writeDouble(this, value, offset, false, noAssert) 1779 }; 1780 1781 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) 1782 Buffer.prototype.copy = function copy (target, targetStart, start, end) { 1783 if (!start) start = 0; 1784 if (!end && end !== 0) end = this.length; 1785 if (targetStart >= target.length) targetStart = target.length; 1786 if (!targetStart) targetStart = 0; 1787 if (end > 0 && end < start) end = start; 1788 1789 // Copy 0 bytes; we're done 1790 if (end === start) return 0 1791 if (target.length === 0 || this.length === 0) return 0 1792 1793 // Fatal error conditions 1794 if (targetStart < 0) { 1795 throw new RangeError('targetStart out of bounds') 1796 } 1797 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') 1798 if (end < 0) throw new RangeError('sourceEnd out of bounds') 1799 1800 // Are we oob? 1801 if (end > this.length) end = this.length; 1802 if (target.length - targetStart < end - start) { 1803 end = target.length - targetStart + start; 1804 } 1805 1806 var len = end - start; 1807 var i; 1808 1809 if (this === target && start < targetStart && targetStart < end) { 1810 // descending copy from end 1811 for (i = len - 1; i >= 0; --i) { 1812 target[i + targetStart] = this[i + start]; 1813 } 1814 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { 1815 // ascending copy from start 1816 for (i = 0; i < len; ++i) { 1817 target[i + targetStart] = this[i + start]; 1818 } 1819 } else { 1820 Uint8Array.prototype.set.call( 1821 target, 1822 this.subarray(start, start + len), 1823 targetStart 1824 ); 1825 } 1826 1827 return len 1828 }; 1829 1830 // Usage: 1831 // buffer.fill(number[, offset[, end]]) 1832 // buffer.fill(buffer[, offset[, end]]) 1833 // buffer.fill(string[, offset[, end]][, encoding]) 1834 Buffer.prototype.fill = function fill (val, start, end, encoding) { 1835 // Handle string cases: 1836 if (typeof val === 'string') { 1837 if (typeof start === 'string') { 1838 encoding = start; 1839 start = 0; 1840 end = this.length; 1841 } else if (typeof end === 'string') { 1842 encoding = end; 1843 end = this.length; 1844 } 1845 if (val.length === 1) { 1846 var code = val.charCodeAt(0); 1847 if (code < 256) { 1848 val = code; 1849 } 1850 } 1851 if (encoding !== undefined && typeof encoding !== 'string') { 1852 throw new TypeError('encoding must be a string') 1853 } 1854 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { 1855 throw new TypeError('Unknown encoding: ' + encoding) 1856 } 1857 } else if (typeof val === 'number') { 1858 val = val & 255; 1859 } 1860 1861 // Invalid ranges are not set to a default, so can range check early. 1862 if (start < 0 || this.length < start || this.length < end) { 1863 throw new RangeError('Out of range index') 1864 } 1865 1866 if (end <= start) { 1867 return this 1868 } 1869 1870 start = start >>> 0; 1871 end = end === undefined ? this.length : end >>> 0; 1872 1873 if (!val) val = 0; 1874 1875 var i; 1876 if (typeof val === 'number') { 1877 for (i = start; i < end; ++i) { 1878 this[i] = val; 1879 } 1880 } else { 1881 var bytes = internalIsBuffer(val) 1882 ? val 1883 : utf8ToBytes(new Buffer(val, encoding).toString()); 1884 var len = bytes.length; 1885 for (i = 0; i < end - start; ++i) { 1886 this[i + start] = bytes[i % len]; 1887 } 1888 } 1889 1890 return this 1891 }; 1892 1893 // HELPER FUNCTIONS 1894 // ================ 1895 1896 var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; 1897 1898 function base64clean (str) { 1899 // Node strips out invalid characters like \n and \t from the string, base64-js does not 1900 str = stringtrim(str).replace(INVALID_BASE64_RE, ''); 1901 // Node converts strings with length < 2 to '' 1902 if (str.length < 2) return '' 1903 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not 1904 while (str.length % 4 !== 0) { 1905 str = str + '='; 1906 } 1907 return str 1908 } 1909 1910 function stringtrim (str) { 1911 if (str.trim) return str.trim() 1912 return str.replace(/^\s+|\s+$/g, '') 1913 } 1914 1915 function toHex (n) { 1916 if (n < 16) return '0' + n.toString(16) 1917 return n.toString(16) 1918 } 1919 1920 function utf8ToBytes (string, units) { 1921 units = units || Infinity; 1922 var codePoint; 1923 var length = string.length; 1924 var leadSurrogate = null; 1925 var bytes = []; 1926 1927 for (var i = 0; i < length; ++i) { 1928 codePoint = string.charCodeAt(i); 1929 1930 // is surrogate component 1931 if (codePoint > 0xD7FF && codePoint < 0xE000) { 1932 // last char was a lead 1933 if (!leadSurrogate) { 1934 // no lead yet 1935 if (codePoint > 0xDBFF) { 1936 // unexpected trail 1937 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 1938 continue 1939 } else if (i + 1 === length) { 1940 // unpaired lead 1941 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 1942 continue 1943 } 1944 1945 // valid lead 1946 leadSurrogate = codePoint; 1947 1948 continue 1949 } 1950 1951 // 2 leads in a row 1952 if (codePoint < 0xDC00) { 1953 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 1954 leadSurrogate = codePoint; 1955 continue 1956 } 1957 1958 // valid surrogate pair 1959 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; 1960 } else if (leadSurrogate) { 1961 // valid bmp char, but last char was a lead 1962 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 1963 } 1964 1965 leadSurrogate = null; 1966 1967 // encode utf8 1968 if (codePoint < 0x80) { 1969 if ((units -= 1) < 0) break 1970 bytes.push(codePoint); 1971 } else if (codePoint < 0x800) { 1972 if ((units -= 2) < 0) break 1973 bytes.push( 1974 codePoint >> 0x6 | 0xC0, 1975 codePoint & 0x3F | 0x80 1976 ); 1977 } else if (codePoint < 0x10000) { 1978 if ((units -= 3) < 0) break 1979 bytes.push( 1980 codePoint >> 0xC | 0xE0, 1981 codePoint >> 0x6 & 0x3F | 0x80, 1982 codePoint & 0x3F | 0x80 1983 ); 1984 } else if (codePoint < 0x110000) { 1985 if ((units -= 4) < 0) break 1986 bytes.push( 1987 codePoint >> 0x12 | 0xF0, 1988 codePoint >> 0xC & 0x3F | 0x80, 1989 codePoint >> 0x6 & 0x3F | 0x80, 1990 codePoint & 0x3F | 0x80 1991 ); 1992 } else { 1993 throw new Error('Invalid code point') 1994 } 1995 } 1996 1997 return bytes 1998 } 1999 2000 function asciiToBytes (str) { 2001 var byteArray = []; 2002 for (var i = 0; i < str.length; ++i) { 2003 // Node's code seems to be doing this and not & 0x7F.. 2004 byteArray.push(str.charCodeAt(i) & 0xFF); 2005 } 2006 return byteArray 2007 } 2008 2009 function utf16leToBytes (str, units) { 2010 var c, hi, lo; 2011 var byteArray = []; 2012 for (var i = 0; i < str.length; ++i) { 2013 if ((units -= 2) < 0) break 2014 2015 c = str.charCodeAt(i); 2016 hi = c >> 8; 2017 lo = c % 256; 2018 byteArray.push(lo); 2019 byteArray.push(hi); 2020 } 2021 2022 return byteArray 2023 } 2024 2025 2026 function base64ToBytes (str) { 2027 return toByteArray(base64clean(str)) 2028 } 2029 2030 function blitBuffer (src, dst, offset, length) { 2031 for (var i = 0; i < length; ++i) { 2032 if ((i + offset >= dst.length) || (i >= src.length)) break 2033 dst[i + offset] = src[i]; 2034 } 2035 return i 2036 } 2037 2038 function isnan (val) { 2039 return val !== val // eslint-disable-line no-self-compare 2040 } 2041 2042 2043 // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence 2044 // The _isBuffer check is for Safari 5-7 support, because it's missing 2045 // Object.prototype.constructor. Remove this eventually 2046 function isBuffer(obj) { 2047 return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) 2048 } 2049 2050 function isFastBuffer (obj) { 2051 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) 2052 } 2053 2054 // For Node v0.10 support. Remove this eventually. 2055 function isSlowBuffer (obj) { 2056 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) 2057 } 2058 2059 var domain; 2060 2061 // This constructor is used to store event handlers. Instantiating this is 2062 // faster than explicitly calling `Object.create(null)` to get a "clean" empty 2063 // object (tested with v8 v4.9). 2064 function EventHandlers() {} 2065 EventHandlers.prototype = Object.create(null); 2066 2067 function EventEmitter() { 2068 EventEmitter.init.call(this); 2069 } 2070 2071 // nodejs oddity 2072 // require('events') === require('events').EventEmitter 2073 EventEmitter.EventEmitter = EventEmitter; 2074 2075 EventEmitter.usingDomains = false; 2076 2077 EventEmitter.prototype.domain = undefined; 2078 EventEmitter.prototype._events = undefined; 2079 EventEmitter.prototype._maxListeners = undefined; 2080 2081 // By default EventEmitters will print a warning if more than 10 listeners are 2082 // added to it. This is a useful default which helps finding memory leaks. 2083 EventEmitter.defaultMaxListeners = 10; 2084 2085 EventEmitter.init = function() { 2086 this.domain = null; 2087 if (EventEmitter.usingDomains) { 2088 // if there is an active domain, then attach to it. 2089 if (domain.active && !(this instanceof domain.Domain)) ; 2090 } 2091 2092 if (!this._events || this._events === Object.getPrototypeOf(this)._events) { 2093 this._events = new EventHandlers(); 2094 this._eventsCount = 0; 2095 } 2096 2097 this._maxListeners = this._maxListeners || undefined; 2098 }; 2099 2100 // Obviously not all Emitters should be limited to 10. This function allows 2101 // that to be increased. Set to zero for unlimited. 2102 EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { 2103 if (typeof n !== 'number' || n < 0 || isNaN(n)) 2104 throw new TypeError('"n" argument must be a positive number'); 2105 this._maxListeners = n; 2106 return this; 2107 }; 2108 2109 function $getMaxListeners(that) { 2110 if (that._maxListeners === undefined) 2111 return EventEmitter.defaultMaxListeners; 2112 return that._maxListeners; 2113 } 2114 2115 EventEmitter.prototype.getMaxListeners = function getMaxListeners() { 2116 return $getMaxListeners(this); 2117 }; 2118 2119 // These standalone emit* functions are used to optimize calling of event 2120 // handlers for fast cases because emit() itself often has a variable number of 2121 // arguments and can be deoptimized because of that. These functions always have 2122 // the same number of arguments and thus do not get deoptimized, so the code 2123 // inside them can execute faster. 2124 function emitNone(handler, isFn, self) { 2125 if (isFn) 2126 handler.call(self); 2127 else { 2128 var len = handler.length; 2129 var listeners = arrayClone(handler, len); 2130 for (var i = 0; i < len; ++i) 2131 listeners[i].call(self); 2132 } 2133 } 2134 function emitOne(handler, isFn, self, arg1) { 2135 if (isFn) 2136 handler.call(self, arg1); 2137 else { 2138 var len = handler.length; 2139 var listeners = arrayClone(handler, len); 2140 for (var i = 0; i < len; ++i) 2141 listeners[i].call(self, arg1); 2142 } 2143 } 2144 function emitTwo(handler, isFn, self, arg1, arg2) { 2145 if (isFn) 2146 handler.call(self, arg1, arg2); 2147 else { 2148 var len = handler.length; 2149 var listeners = arrayClone(handler, len); 2150 for (var i = 0; i < len; ++i) 2151 listeners[i].call(self, arg1, arg2); 2152 } 2153 } 2154 function emitThree(handler, isFn, self, arg1, arg2, arg3) { 2155 if (isFn) 2156 handler.call(self, arg1, arg2, arg3); 2157 else { 2158 var len = handler.length; 2159 var listeners = arrayClone(handler, len); 2160 for (var i = 0; i < len; ++i) 2161 listeners[i].call(self, arg1, arg2, arg3); 2162 } 2163 } 2164 2165 function emitMany(handler, isFn, self, args) { 2166 if (isFn) 2167 handler.apply(self, args); 2168 else { 2169 var len = handler.length; 2170 var listeners = arrayClone(handler, len); 2171 for (var i = 0; i < len; ++i) 2172 listeners[i].apply(self, args); 2173 } 2174 } 2175 2176 EventEmitter.prototype.emit = function emit(type) { 2177 var er, handler, len, args, i, events, domain; 2178 var doError = (type === 'error'); 2179 2180 events = this._events; 2181 if (events) 2182 doError = (doError && events.error == null); 2183 else if (!doError) 2184 return false; 2185 2186 domain = this.domain; 2187 2188 // If there is no 'error' event listener then throw. 2189 if (doError) { 2190 er = arguments[1]; 2191 if (domain) { 2192 if (!er) 2193 er = new Error('Uncaught, unspecified "error" event'); 2194 er.domainEmitter = this; 2195 er.domain = domain; 2196 er.domainThrown = false; 2197 domain.emit('error', er); 2198 } else if (er instanceof Error) { 2199 throw er; // Unhandled 'error' event 2200 } else { 2201 // At least give some kind of context to the user 2202 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); 2203 err.context = er; 2204 throw err; 2205 } 2206 return false; 2207 } 2208 2209 handler = events[type]; 2210 2211 if (!handler) 2212 return false; 2213 2214 var isFn = typeof handler === 'function'; 2215 len = arguments.length; 2216 switch (len) { 2217 // fast cases 2218 case 1: 2219 emitNone(handler, isFn, this); 2220 break; 2221 case 2: 2222 emitOne(handler, isFn, this, arguments[1]); 2223 break; 2224 case 3: 2225 emitTwo(handler, isFn, this, arguments[1], arguments[2]); 2226 break; 2227 case 4: 2228 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); 2229 break; 2230 // slower 2231 default: 2232 args = new Array(len - 1); 2233 for (i = 1; i < len; i++) 2234 args[i - 1] = arguments[i]; 2235 emitMany(handler, isFn, this, args); 2236 } 2237 2238 return true; 2239 }; 2240 2241 function _addListener(target, type, listener, prepend) { 2242 var m; 2243 var events; 2244 var existing; 2245 2246 if (typeof listener !== 'function') 2247 throw new TypeError('"listener" argument must be a function'); 2248 2249 events = target._events; 2250 if (!events) { 2251 events = target._events = new EventHandlers(); 2252 target._eventsCount = 0; 2253 } else { 2254 // To avoid recursion in the case that type === "newListener"! Before 2255 // adding it to the listeners, first emit "newListener". 2256 if (events.newListener) { 2257 target.emit('newListener', type, 2258 listener.listener ? listener.listener : listener); 2259 2260 // Re-assign `events` because a newListener handler could have caused the 2261 // this._events to be assigned to a new object 2262 events = target._events; 2263 } 2264 existing = events[type]; 2265 } 2266 2267 if (!existing) { 2268 // Optimize the case of one listener. Don't need the extra array object. 2269 existing = events[type] = listener; 2270 ++target._eventsCount; 2271 } else { 2272 if (typeof existing === 'function') { 2273 // Adding the second element, need to change to array. 2274 existing = events[type] = prepend ? [listener, existing] : 2275 [existing, listener]; 2276 } else { 2277 // If we've already got an array, just append. 2278 if (prepend) { 2279 existing.unshift(listener); 2280 } else { 2281 existing.push(listener); 2282 } 2283 } 2284 2285 // Check for listener leak 2286 if (!existing.warned) { 2287 m = $getMaxListeners(target); 2288 if (m && m > 0 && existing.length > m) { 2289 existing.warned = true; 2290 var w = new Error('Possible EventEmitter memory leak detected. ' + 2291 existing.length + ' ' + type + ' listeners added. ' + 2292 'Use emitter.setMaxListeners() to increase limit'); 2293 w.name = 'MaxListenersExceededWarning'; 2294 w.emitter = target; 2295 w.type = type; 2296 w.count = existing.length; 2297 emitWarning(w); 2298 } 2299 } 2300 } 2301 2302 return target; 2303 } 2304 function emitWarning(e) { 2305 typeof console.warn === 'function' ? console.warn(e) : console.log(e); 2306 } 2307 EventEmitter.prototype.addListener = function addListener(type, listener) { 2308 return _addListener(this, type, listener, false); 2309 }; 2310 2311 EventEmitter.prototype.on = EventEmitter.prototype.addListener; 2312 2313 EventEmitter.prototype.prependListener = 2314 function prependListener(type, listener) { 2315 return _addListener(this, type, listener, true); 2316 }; 2317 2318 function _onceWrap(target, type, listener) { 2319 var fired = false; 2320 function g() { 2321 target.removeListener(type, g); 2322 if (!fired) { 2323 fired = true; 2324 listener.apply(target, arguments); 2325 } 2326 } 2327 g.listener = listener; 2328 return g; 2329 } 2330 2331 EventEmitter.prototype.once = function once(type, listener) { 2332 if (typeof listener !== 'function') 2333 throw new TypeError('"listener" argument must be a function'); 2334 this.on(type, _onceWrap(this, type, listener)); 2335 return this; 2336 }; 2337 2338 EventEmitter.prototype.prependOnceListener = 2339 function prependOnceListener(type, listener) { 2340 if (typeof listener !== 'function') 2341 throw new TypeError('"listener" argument must be a function'); 2342 this.prependListener(type, _onceWrap(this, type, listener)); 2343 return this; 2344 }; 2345 2346 // emits a 'removeListener' event iff the listener was removed 2347 EventEmitter.prototype.removeListener = 2348 function removeListener(type, listener) { 2349 var list, events, position, i, originalListener; 2350 2351 if (typeof listener !== 'function') 2352 throw new TypeError('"listener" argument must be a function'); 2353 2354 events = this._events; 2355 if (!events) 2356 return this; 2357 2358 list = events[type]; 2359 if (!list) 2360 return this; 2361 2362 if (list === listener || (list.listener && list.listener === listener)) { 2363 if (--this._eventsCount === 0) 2364 this._events = new EventHandlers(); 2365 else { 2366 delete events[type]; 2367 if (events.removeListener) 2368 this.emit('removeListener', type, list.listener || listener); 2369 } 2370 } else if (typeof list !== 'function') { 2371 position = -1; 2372 2373 for (i = list.length; i-- > 0;) { 2374 if (list[i] === listener || 2375 (list[i].listener && list[i].listener === listener)) { 2376 originalListener = list[i].listener; 2377 position = i; 2378 break; 2379 } 2380 } 2381 2382 if (position < 0) 2383 return this; 2384 2385 if (list.length === 1) { 2386 list[0] = undefined; 2387 if (--this._eventsCount === 0) { 2388 this._events = new EventHandlers(); 2389 return this; 2390 } else { 2391 delete events[type]; 2392 } 2393 } else { 2394 spliceOne(list, position); 2395 } 2396 2397 if (events.removeListener) 2398 this.emit('removeListener', type, originalListener || listener); 2399 } 2400 2401 return this; 2402 }; 2403 2404 EventEmitter.prototype.removeAllListeners = 2405 function removeAllListeners(type) { 2406 var listeners, events; 2407 2408 events = this._events; 2409 if (!events) 2410 return this; 2411 2412 // not listening for removeListener, no need to emit 2413 if (!events.removeListener) { 2414 if (arguments.length === 0) { 2415 this._events = new EventHandlers(); 2416 this._eventsCount = 0; 2417 } else if (events[type]) { 2418 if (--this._eventsCount === 0) 2419 this._events = new EventHandlers(); 2420 else 2421 delete events[type]; 2422 } 2423 return this; 2424 } 2425 2426 // emit removeListener for all listeners on all events 2427 if (arguments.length === 0) { 2428 var keys = Object.keys(events); 2429 for (var i = 0, key; i < keys.length; ++i) { 2430 key = keys[i]; 2431 if (key === 'removeListener') continue; 2432 this.removeAllListeners(key); 2433 } 2434 this.removeAllListeners('removeListener'); 2435 this._events = new EventHandlers(); 2436 this._eventsCount = 0; 2437 return this; 2438 } 2439 2440 listeners = events[type]; 2441 2442 if (typeof listeners === 'function') { 2443 this.removeListener(type, listeners); 2444 } else if (listeners) { 2445 // LIFO order 2446 do { 2447 this.removeListener(type, listeners[listeners.length - 1]); 2448 } while (listeners[0]); 2449 } 2450 2451 return this; 2452 }; 2453 2454 EventEmitter.prototype.listeners = function listeners(type) { 2455 var evlistener; 2456 var ret; 2457 var events = this._events; 2458 2459 if (!events) 2460 ret = []; 2461 else { 2462 evlistener = events[type]; 2463 if (!evlistener) 2464 ret = []; 2465 else if (typeof evlistener === 'function') 2466 ret = [evlistener.listener || evlistener]; 2467 else 2468 ret = unwrapListeners(evlistener); 2469 } 2470 2471 return ret; 2472 }; 2473 2474 EventEmitter.listenerCount = function(emitter, type) { 2475 if (typeof emitter.listenerCount === 'function') { 2476 return emitter.listenerCount(type); 2477 } else { 2478 return listenerCount.call(emitter, type); 2479 } 2480 }; 2481 2482 EventEmitter.prototype.listenerCount = listenerCount; 2483 function listenerCount(type) { 2484 var events = this._events; 2485 2486 if (events) { 2487 var evlistener = events[type]; 2488 2489 if (typeof evlistener === 'function') { 2490 return 1; 2491 } else if (evlistener) { 2492 return evlistener.length; 2493 } 2494 } 2495 2496 return 0; 2497 } 2498 2499 EventEmitter.prototype.eventNames = function eventNames() { 2500 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; 2501 }; 2502 2503 // About 1.5x faster than the two-arg version of Array#splice(). 2504 function spliceOne(list, index) { 2505 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) 2506 list[i] = list[k]; 2507 list.pop(); 2508 } 2509 2510 function arrayClone(arr, i) { 2511 var copy = new Array(i); 2512 while (i--) 2513 copy[i] = arr[i]; 2514 return copy; 2515 } 2516 2517 function unwrapListeners(arr) { 2518 var ret = new Array(arr.length); 2519 for (var i = 0; i < ret.length; ++i) { 2520 ret[i] = arr[i].listener || arr[i]; 2521 } 2522 return ret; 2523 } 2524 2525 // shim for using process in browser 2526 // based off https://github.com/defunctzombie/node-process/blob/master/browser.js 2527 2528 function defaultSetTimout() { 2529 throw new Error('setTimeout has not been defined'); 2530 } 2531 function defaultClearTimeout () { 2532 throw new Error('clearTimeout has not been defined'); 2533 } 2534 var cachedSetTimeout = defaultSetTimout; 2535 var cachedClearTimeout = defaultClearTimeout; 2536 if (typeof global$1$1.setTimeout === 'function') { 2537 cachedSetTimeout = setTimeout; 2538 } 2539 if (typeof global$1$1.clearTimeout === 'function') { 2540 cachedClearTimeout = clearTimeout; 2541 } 2542 2543 function runTimeout(fun) { 2544 if (cachedSetTimeout === setTimeout) { 2545 //normal enviroments in sane situations 2546 return setTimeout(fun, 0); 2547 } 2548 // if setTimeout wasn't available but was latter defined 2549 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { 2550 cachedSetTimeout = setTimeout; 2551 return setTimeout(fun, 0); 2552 } 2553 try { 2554 // when when somebody has screwed with setTimeout but no I.E. maddness 2555 return cachedSetTimeout(fun, 0); 2556 } catch(e){ 2557 try { 2558 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally 2559 return cachedSetTimeout.call(null, fun, 0); 2560 } catch(e){ 2561 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error 2562 return cachedSetTimeout.call(this, fun, 0); 2563 } 2564 } 2565 2566 2567 } 2568 function runClearTimeout(marker) { 2569 if (cachedClearTimeout === clearTimeout) { 2570 //normal enviroments in sane situations 2571 return clearTimeout(marker); 2572 } 2573 // if clearTimeout wasn't available but was latter defined 2574 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { 2575 cachedClearTimeout = clearTimeout; 2576 return clearTimeout(marker); 2577 } 2578 try { 2579 // when when somebody has screwed with setTimeout but no I.E. maddness 2580 return cachedClearTimeout(marker); 2581 } catch (e){ 2582 try { 2583 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally 2584 return cachedClearTimeout.call(null, marker); 2585 } catch (e){ 2586 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. 2587 // Some versions of I.E. have different rules for clearTimeout vs setTimeout 2588 return cachedClearTimeout.call(this, marker); 2589 } 2590 } 2591 2592 2593 2594 } 2595 var queue = []; 2596 var draining = false; 2597 var currentQueue; 2598 var queueIndex = -1; 2599 2600 function cleanUpNextTick() { 2601 if (!draining || !currentQueue) { 2602 return; 2603 } 2604 draining = false; 2605 if (currentQueue.length) { 2606 queue = currentQueue.concat(queue); 2607 } else { 2608 queueIndex = -1; 2609 } 2610 if (queue.length) { 2611 drainQueue(); 2612 } 2613 } 2614 2615 function drainQueue() { 2616 if (draining) { 2617 return; 2618 } 2619 var timeout = runTimeout(cleanUpNextTick); 2620 draining = true; 2621 2622 var len = queue.length; 2623 while(len) { 2624 currentQueue = queue; 2625 queue = []; 2626 while (++queueIndex < len) { 2627 if (currentQueue) { 2628 currentQueue[queueIndex].run(); 2629 } 2630 } 2631 queueIndex = -1; 2632 len = queue.length; 2633 } 2634 currentQueue = null; 2635 draining = false; 2636 runClearTimeout(timeout); 2637 } 2638 function nextTick(fun) { 2639 var args = new Array(arguments.length - 1); 2640 if (arguments.length > 1) { 2641 for (var i = 1; i < arguments.length; i++) { 2642 args[i - 1] = arguments[i]; 2643 } 2644 } 2645 queue.push(new Item(fun, args)); 2646 if (queue.length === 1 && !draining) { 2647 runTimeout(drainQueue); 2648 } 2649 } 2650 // v8 likes predictible objects 2651 function Item(fun, array) { 2652 this.fun = fun; 2653 this.array = array; 2654 } 2655 Item.prototype.run = function () { 2656 this.fun.apply(null, this.array); 2657 }; 2658 2659 // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js 2660 var performance = global$1$1.performance || {}; 2661 var performanceNow = 2662 performance.now || 2663 performance.mozNow || 2664 performance.msNow || 2665 performance.oNow || 2666 performance.webkitNow || 2667 function(){ return (new Date()).getTime() }; 2668 2669 var inherits; 2670 if (typeof Object.create === 'function'){ 2671 inherits = function inherits(ctor, superCtor) { 2672 // implementation from standard node.js 'util' module 2673 ctor.super_ = superCtor; 2674 ctor.prototype = Object.create(superCtor.prototype, { 2675 constructor: { 2676 value: ctor, 2677 enumerable: false, 2678 writable: true, 2679 configurable: true 2680 } 2681 }); 2682 }; 2683 } else { 2684 inherits = function inherits(ctor, superCtor) { 2685 ctor.super_ = superCtor; 2686 var TempCtor = function () {}; 2687 TempCtor.prototype = superCtor.prototype; 2688 ctor.prototype = new TempCtor(); 2689 ctor.prototype.constructor = ctor; 2690 }; 2691 } 2692 var inherits$1 = inherits; 2693 2694 var formatRegExp = /%[sdj%]/g; 2695 function format(f) { 2696 if (!isString(f)) { 2697 var objects = []; 2698 for (var i = 0; i < arguments.length; i++) { 2699 objects.push(inspect(arguments[i])); 2700 } 2701 return objects.join(' '); 2702 } 2703 2704 var i = 1; 2705 var args = arguments; 2706 var len = args.length; 2707 var str = String(f).replace(formatRegExp, function(x) { 2708 if (x === '%%') return '%'; 2709 if (i >= len) return x; 2710 switch (x) { 2711 case '%s': return String(args[i++]); 2712 case '%d': return Number(args[i++]); 2713 case '%j': 2714 try { 2715 return JSON.stringify(args[i++]); 2716 } catch (_) { 2717 return '[Circular]'; 2718 } 2719 default: 2720 return x; 2721 } 2722 }); 2723 for (var x = args[i]; i < len; x = args[++i]) { 2724 if (isNull(x) || !isObject(x)) { 2725 str += ' ' + x; 2726 } else { 2727 str += ' ' + inspect(x); 2728 } 2729 } 2730 return str; 2731 } 2732 2733 // Mark that a method should not be used. 2734 // Returns a modified function which warns once by default. 2735 // If --no-deprecation is set, then it is a no-op. 2736 function deprecate(fn, msg) { 2737 // Allow for deprecating things in the process of starting up. 2738 if (isUndefined(global$1$1.process)) { 2739 return function() { 2740 return deprecate(fn, msg).apply(this, arguments); 2741 }; 2742 } 2743 2744 var warned = false; 2745 function deprecated() { 2746 if (!warned) { 2747 { 2748 console.error(msg); 2749 } 2750 warned = true; 2751 } 2752 return fn.apply(this, arguments); 2753 } 2754 2755 return deprecated; 2756 } 2757 2758 var debugs = {}; 2759 var debugEnviron; 2760 function debuglog(set) { 2761 if (isUndefined(debugEnviron)) 2762 debugEnviron = ''; 2763 set = set.toUpperCase(); 2764 if (!debugs[set]) { 2765 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { 2766 var pid = 0; 2767 debugs[set] = function() { 2768 var msg = format.apply(null, arguments); 2769 console.error('%s %d: %s', set, pid, msg); 2770 }; 2771 } else { 2772 debugs[set] = function() {}; 2773 } 2774 } 2775 return debugs[set]; 2776 } 2777 2778 /** 2779 * Echos the value of a value. Trys to print the value out 2780 * in the best way possible given the different types. 2781 * 2782 * @param {Object} obj The object to print out. 2783 * @param {Object} opts Optional options object that alters the output. 2784 */ 2785 /* legacy: obj, showHidden, depth, colors*/ 2786 function inspect(obj, opts) { 2787 // default options 2788 var ctx = { 2789 seen: [], 2790 stylize: stylizeNoColor 2791 }; 2792 // legacy... 2793 if (arguments.length >= 3) ctx.depth = arguments[2]; 2794 if (arguments.length >= 4) ctx.colors = arguments[3]; 2795 if (isBoolean(opts)) { 2796 // legacy... 2797 ctx.showHidden = opts; 2798 } else if (opts) { 2799 // got an "options" object 2800 _extend(ctx, opts); 2801 } 2802 // set default options 2803 if (isUndefined(ctx.showHidden)) ctx.showHidden = false; 2804 if (isUndefined(ctx.depth)) ctx.depth = 2; 2805 if (isUndefined(ctx.colors)) ctx.colors = false; 2806 if (isUndefined(ctx.customInspect)) ctx.customInspect = true; 2807 if (ctx.colors) ctx.stylize = stylizeWithColor; 2808 return formatValue(ctx, obj, ctx.depth); 2809 } 2810 2811 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics 2812 inspect.colors = { 2813 'bold' : [1, 22], 2814 'italic' : [3, 23], 2815 'underline' : [4, 24], 2816 'inverse' : [7, 27], 2817 'white' : [37, 39], 2818 'grey' : [90, 39], 2819 'black' : [30, 39], 2820 'blue' : [34, 39], 2821 'cyan' : [36, 39], 2822 'green' : [32, 39], 2823 'magenta' : [35, 39], 2824 'red' : [31, 39], 2825 'yellow' : [33, 39] 2826 }; 2827 2828 // Don't use 'blue' not visible on cmd.exe 2829 inspect.styles = { 2830 'special': 'cyan', 2831 'number': 'yellow', 2832 'boolean': 'yellow', 2833 'undefined': 'grey', 2834 'null': 'bold', 2835 'string': 'green', 2836 'date': 'magenta', 2837 // "name": intentionally not styling 2838 'regexp': 'red' 2839 }; 2840 2841 2842 function stylizeWithColor(str, styleType) { 2843 var style = inspect.styles[styleType]; 2844 2845 if (style) { 2846 return '\u001b[' + inspect.colors[style][0] + 'm' + str + 2847 '\u001b[' + inspect.colors[style][1] + 'm'; 2848 } else { 2849 return str; 2850 } 2851 } 2852 2853 2854 function stylizeNoColor(str, styleType) { 2855 return str; 2856 } 2857 2858 2859 function arrayToHash(array) { 2860 var hash = {}; 2861 2862 array.forEach(function(val, idx) { 2863 hash[val] = true; 2864 }); 2865 2866 return hash; 2867 } 2868 2869 2870 function formatValue(ctx, value, recurseTimes) { 2871 // Provide a hook for user-specified inspect functions. 2872 // Check that value is an object with an inspect function on it 2873 if (ctx.customInspect && 2874 value && 2875 isFunction(value.inspect) && 2876 // Filter out the util module, it's inspect function is special 2877 value.inspect !== inspect && 2878 // Also filter out any prototype objects using the circular check. 2879 !(value.constructor && value.constructor.prototype === value)) { 2880 var ret = value.inspect(recurseTimes, ctx); 2881 if (!isString(ret)) { 2882 ret = formatValue(ctx, ret, recurseTimes); 2883 } 2884 return ret; 2885 } 2886 2887 // Primitive types cannot have properties 2888 var primitive = formatPrimitive(ctx, value); 2889 if (primitive) { 2890 return primitive; 2891 } 2892 2893 // Look up the keys of the object. 2894 var keys = Object.keys(value); 2895 var visibleKeys = arrayToHash(keys); 2896 2897 if (ctx.showHidden) { 2898 keys = Object.getOwnPropertyNames(value); 2899 } 2900 2901 // IE doesn't make error fields non-enumerable 2902 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx 2903 if (isError(value) 2904 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { 2905 return formatError(value); 2906 } 2907 2908 // Some type of object without properties can be shortcutted. 2909 if (keys.length === 0) { 2910 if (isFunction(value)) { 2911 var name = value.name ? ': ' + value.name : ''; 2912 return ctx.stylize('[Function' + name + ']', 'special'); 2913 } 2914 if (isRegExp(value)) { 2915 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); 2916 } 2917 if (isDate(value)) { 2918 return ctx.stylize(Date.prototype.toString.call(value), 'date'); 2919 } 2920 if (isError(value)) { 2921 return formatError(value); 2922 } 2923 } 2924 2925 var base = '', array = false, braces = ['{', '}']; 2926 2927 // Make Array say that they are Array 2928 if (isArray$1(value)) { 2929 array = true; 2930 braces = ['[', ']']; 2931 } 2932 2933 // Make functions say that they are functions 2934 if (isFunction(value)) { 2935 var n = value.name ? ': ' + value.name : ''; 2936 base = ' [Function' + n + ']'; 2937 } 2938 2939 // Make RegExps say that they are RegExps 2940 if (isRegExp(value)) { 2941 base = ' ' + RegExp.prototype.toString.call(value); 2942 } 2943 2944 // Make dates with properties first say the date 2945 if (isDate(value)) { 2946 base = ' ' + Date.prototype.toUTCString.call(value); 2947 } 2948 2949 // Make error with message first say the error 2950 if (isError(value)) { 2951 base = ' ' + formatError(value); 2952 } 2953 2954 if (keys.length === 0 && (!array || value.length == 0)) { 2955 return braces[0] + base + braces[1]; 2956 } 2957 2958 if (recurseTimes < 0) { 2959 if (isRegExp(value)) { 2960 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); 2961 } else { 2962 return ctx.stylize('[Object]', 'special'); 2963 } 2964 } 2965 2966 ctx.seen.push(value); 2967 2968 var output; 2969 if (array) { 2970 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); 2971 } else { 2972 output = keys.map(function(key) { 2973 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); 2974 }); 2975 } 2976 2977 ctx.seen.pop(); 2978 2979 return reduceToSingleString(output, base, braces); 2980 } 2981 2982 2983 function formatPrimitive(ctx, value) { 2984 if (isUndefined(value)) 2985 return ctx.stylize('undefined', 'undefined'); 2986 if (isString(value)) { 2987 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') 2988 .replace(/'/g, "\\'") 2989 .replace(/\\"/g, '"') + '\''; 2990 return ctx.stylize(simple, 'string'); 2991 } 2992 if (isNumber(value)) 2993 return ctx.stylize('' + value, 'number'); 2994 if (isBoolean(value)) 2995 return ctx.stylize('' + value, 'boolean'); 2996 // For some reason typeof null is "object", so special case here. 2997 if (isNull(value)) 2998 return ctx.stylize('null', 'null'); 2999 } 3000 3001 3002 function formatError(value) { 3003 return '[' + Error.prototype.toString.call(value) + ']'; 3004 } 3005 3006 3007 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { 3008 var output = []; 3009 for (var i = 0, l = value.length; i < l; ++i) { 3010 if (hasOwnProperty(value, String(i))) { 3011 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, 3012 String(i), true)); 3013 } else { 3014 output.push(''); 3015 } 3016 } 3017 keys.forEach(function(key) { 3018 if (!key.match(/^\d+$/)) { 3019 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, 3020 key, true)); 3021 } 3022 }); 3023 return output; 3024 } 3025 3026 3027 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { 3028 var name, str, desc; 3029 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; 3030 if (desc.get) { 3031 if (desc.set) { 3032 str = ctx.stylize('[Getter/Setter]', 'special'); 3033 } else { 3034 str = ctx.stylize('[Getter]', 'special'); 3035 } 3036 } else { 3037 if (desc.set) { 3038 str = ctx.stylize('[Setter]', 'special'); 3039 } 3040 } 3041 if (!hasOwnProperty(visibleKeys, key)) { 3042 name = '[' + key + ']'; 3043 } 3044 if (!str) { 3045 if (ctx.seen.indexOf(desc.value) < 0) { 3046 if (isNull(recurseTimes)) { 3047 str = formatValue(ctx, desc.value, null); 3048 } else { 3049 str = formatValue(ctx, desc.value, recurseTimes - 1); 3050 } 3051 if (str.indexOf('\n') > -1) { 3052 if (array) { 3053 str = str.split('\n').map(function(line) { 3054 return ' ' + line; 3055 }).join('\n').substr(2); 3056 } else { 3057 str = '\n' + str.split('\n').map(function(line) { 3058 return ' ' + line; 3059 }).join('\n'); 3060 } 3061 } 3062 } else { 3063 str = ctx.stylize('[Circular]', 'special'); 3064 } 3065 } 3066 if (isUndefined(name)) { 3067 if (array && key.match(/^\d+$/)) { 3068 return str; 3069 } 3070 name = JSON.stringify('' + key); 3071 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { 3072 name = name.substr(1, name.length - 2); 3073 name = ctx.stylize(name, 'name'); 3074 } else { 3075 name = name.replace(/'/g, "\\'") 3076 .replace(/\\"/g, '"') 3077 .replace(/(^"|"$)/g, "'"); 3078 name = ctx.stylize(name, 'string'); 3079 } 3080 } 3081 3082 return name + ': ' + str; 3083 } 3084 3085 3086 function reduceToSingleString(output, base, braces) { 3087 var length = output.reduce(function(prev, cur) { 3088 if (cur.indexOf('\n') >= 0) ; 3089 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; 3090 }, 0); 3091 3092 if (length > 60) { 3093 return braces[0] + 3094 (base === '' ? '' : base + '\n ') + 3095 ' ' + 3096 output.join(',\n ') + 3097 ' ' + 3098 braces[1]; 3099 } 3100 3101 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; 3102 } 3103 3104 3105 // NOTE: These type checking functions intentionally don't use `instanceof` 3106 // because it is fragile and can be easily faked with `Object.create()`. 3107 function isArray$1(ar) { 3108 return Array.isArray(ar); 3109 } 3110 3111 function isBoolean(arg) { 3112 return typeof arg === 'boolean'; 3113 } 3114 3115 function isNull(arg) { 3116 return arg === null; 3117 } 3118 3119 function isNumber(arg) { 3120 return typeof arg === 'number'; 3121 } 3122 3123 function isString(arg) { 3124 return typeof arg === 'string'; 3125 } 3126 3127 function isUndefined(arg) { 3128 return arg === void 0; 3129 } 3130 3131 function isRegExp(re) { 3132 return isObject(re) && objectToString(re) === '[object RegExp]'; 3133 } 3134 3135 function isObject(arg) { 3136 return typeof arg === 'object' && arg !== null; 3137 } 3138 3139 function isDate(d) { 3140 return isObject(d) && objectToString(d) === '[object Date]'; 3141 } 3142 3143 function isError(e) { 3144 return isObject(e) && 3145 (objectToString(e) === '[object Error]' || e instanceof Error); 3146 } 3147 3148 function isFunction(arg) { 3149 return typeof arg === 'function'; 3150 } 3151 3152 function objectToString(o) { 3153 return Object.prototype.toString.call(o); 3154 } 3155 3156 function _extend(origin, add) { 3157 // Don't do anything if add isn't an object 3158 if (!add || !isObject(add)) return origin; 3159 3160 var keys = Object.keys(add); 3161 var i = keys.length; 3162 while (i--) { 3163 origin[keys[i]] = add[keys[i]]; 3164 } 3165 return origin; 3166 } 3167 function hasOwnProperty(obj, prop) { 3168 return Object.prototype.hasOwnProperty.call(obj, prop); 3169 } 3170 3171 var INSPECT_MAX_BYTES$1 = 50; 3172 3173 /** 3174 * If `Buffer.TYPED_ARRAY_SUPPORT`: 3175 * === true Use Uint8Array implementation (fastest) 3176 * === false Use Object implementation (most compatible, even IE6) 3177 * 3178 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, 3179 * Opera 11.6+, iOS 4.2+. 3180 * 3181 * Due to various browser bugs, sometimes the Object implementation will be used even 3182 * when the browser supports typed arrays. 3183 * 3184 * Note: 3185 * 3186 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, 3187 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. 3188 * 3189 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. 3190 * 3191 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of 3192 * incorrect length in some situations. 3193 3194 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they 3195 * get the Object implementation, which is slower but behaves correctly. 3196 */ 3197 Buffer$1.TYPED_ARRAY_SUPPORT = global$1$1.TYPED_ARRAY_SUPPORT !== undefined 3198 ? global$1$1.TYPED_ARRAY_SUPPORT 3199 : true; 3200 3201 function kMaxLength$1 () { 3202 return Buffer$1.TYPED_ARRAY_SUPPORT 3203 ? 0x7fffffff 3204 : 0x3fffffff 3205 } 3206 3207 function createBuffer$1 (that, length) { 3208 if (kMaxLength$1() < length) { 3209 throw new RangeError('Invalid typed array length') 3210 } 3211 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 3212 // Return an augmented `Uint8Array` instance, for best performance 3213 that = new Uint8Array(length); 3214 that.__proto__ = Buffer$1.prototype; 3215 } else { 3216 // Fallback: Return an object instance of the Buffer class 3217 if (that === null) { 3218 that = new Buffer$1(length); 3219 } 3220 that.length = length; 3221 } 3222 3223 return that 3224 } 3225 3226 /** 3227 * The Buffer constructor returns instances of `Uint8Array` that have their 3228 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of 3229 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods 3230 * and the `Uint8Array` methods. Square bracket notation works as expected -- it 3231 * returns a single octet. 3232 * 3233 * The `Uint8Array` prototype remains unmodified. 3234 */ 3235 3236 function Buffer$1 (arg, encodingOrOffset, length) { 3237 if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { 3238 return new Buffer$1(arg, encodingOrOffset, length) 3239 } 3240 3241 // Common case. 3242 if (typeof arg === 'number') { 3243 if (typeof encodingOrOffset === 'string') { 3244 throw new Error( 3245 'If encoding is specified then the first argument must be a string' 3246 ) 3247 } 3248 return allocUnsafe$1(this, arg) 3249 } 3250 return from$1(this, arg, encodingOrOffset, length) 3251 } 3252 3253 Buffer$1.poolSize = 8192; // not used by this implementation 3254 3255 // TODO: Legacy, not needed anymore. Remove in next major version. 3256 Buffer$1._augment = function (arr) { 3257 arr.__proto__ = Buffer$1.prototype; 3258 return arr 3259 }; 3260 3261 function from$1 (that, value, encodingOrOffset, length) { 3262 if (typeof value === 'number') { 3263 throw new TypeError('"value" argument must not be a number') 3264 } 3265 3266 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { 3267 return fromArrayBuffer$1(that, value, encodingOrOffset, length) 3268 } 3269 3270 if (typeof value === 'string') { 3271 return fromString$1(that, value, encodingOrOffset) 3272 } 3273 3274 return fromObject$1(that, value) 3275 } 3276 3277 /** 3278 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError 3279 * if value is a number. 3280 * Buffer.from(str[, encoding]) 3281 * Buffer.from(array) 3282 * Buffer.from(buffer) 3283 * Buffer.from(arrayBuffer[, byteOffset[, length]]) 3284 **/ 3285 Buffer$1.from = function (value, encodingOrOffset, length) { 3286 return from$1(null, value, encodingOrOffset, length) 3287 }; 3288 3289 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 3290 Buffer$1.prototype.__proto__ = Uint8Array.prototype; 3291 Buffer$1.__proto__ = Uint8Array; 3292 } 3293 3294 function assertSize$1 (size) { 3295 if (typeof size !== 'number') { 3296 throw new TypeError('"size" argument must be a number') 3297 } else if (size < 0) { 3298 throw new RangeError('"size" argument must not be negative') 3299 } 3300 } 3301 3302 function alloc$1 (that, size, fill, encoding) { 3303 assertSize$1(size); 3304 if (size <= 0) { 3305 return createBuffer$1(that, size) 3306 } 3307 if (fill !== undefined) { 3308 // Only pay attention to encoding if it's a string. This 3309 // prevents accidentally sending in a number that would 3310 // be interpretted as a start offset. 3311 return typeof encoding === 'string' 3312 ? createBuffer$1(that, size).fill(fill, encoding) 3313 : createBuffer$1(that, size).fill(fill) 3314 } 3315 return createBuffer$1(that, size) 3316 } 3317 3318 /** 3319 * Creates a new filled Buffer instance. 3320 * alloc(size[, fill[, encoding]]) 3321 **/ 3322 Buffer$1.alloc = function (size, fill, encoding) { 3323 return alloc$1(null, size, fill, encoding) 3324 }; 3325 3326 function allocUnsafe$1 (that, size) { 3327 assertSize$1(size); 3328 that = createBuffer$1(that, size < 0 ? 0 : checked$1(size) | 0); 3329 if (!Buffer$1.TYPED_ARRAY_SUPPORT) { 3330 for (var i = 0; i < size; ++i) { 3331 that[i] = 0; 3332 } 3333 } 3334 return that 3335 } 3336 3337 /** 3338 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. 3339 * */ 3340 Buffer$1.allocUnsafe = function (size) { 3341 return allocUnsafe$1(null, size) 3342 }; 3343 /** 3344 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. 3345 */ 3346 Buffer$1.allocUnsafeSlow = function (size) { 3347 return allocUnsafe$1(null, size) 3348 }; 3349 3350 function fromString$1 (that, string, encoding) { 3351 if (typeof encoding !== 'string' || encoding === '') { 3352 encoding = 'utf8'; 3353 } 3354 3355 if (!Buffer$1.isEncoding(encoding)) { 3356 throw new TypeError('"encoding" must be a valid string encoding') 3357 } 3358 3359 var length = byteLength$1(string, encoding) | 0; 3360 that = createBuffer$1(that, length); 3361 3362 var actual = that.write(string, encoding); 3363 3364 if (actual !== length) { 3365 // Writing a hex string, for example, that contains invalid characters will 3366 // cause everything after the first invalid character to be ignored. (e.g. 3367 // 'abxxcd' will be treated as 'ab') 3368 that = that.slice(0, actual); 3369 } 3370 3371 return that 3372 } 3373 3374 function fromArrayLike$1 (that, array) { 3375 var length = array.length < 0 ? 0 : checked$1(array.length) | 0; 3376 that = createBuffer$1(that, length); 3377 for (var i = 0; i < length; i += 1) { 3378 that[i] = array[i] & 255; 3379 } 3380 return that 3381 } 3382 3383 function fromArrayBuffer$1 (that, array, byteOffset, length) { 3384 array.byteLength; // this throws if `array` is not a valid ArrayBuffer 3385 3386 if (byteOffset < 0 || array.byteLength < byteOffset) { 3387 throw new RangeError('\'offset\' is out of bounds') 3388 } 3389 3390 if (array.byteLength < byteOffset + (length || 0)) { 3391 throw new RangeError('\'length\' is out of bounds') 3392 } 3393 3394 if (byteOffset === undefined && length === undefined) { 3395 array = new Uint8Array(array); 3396 } else if (length === undefined) { 3397 array = new Uint8Array(array, byteOffset); 3398 } else { 3399 array = new Uint8Array(array, byteOffset, length); 3400 } 3401 3402 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 3403 // Return an augmented `Uint8Array` instance, for best performance 3404 that = array; 3405 that.__proto__ = Buffer$1.prototype; 3406 } else { 3407 // Fallback: Return an object instance of the Buffer class 3408 that = fromArrayLike$1(that, array); 3409 } 3410 return that 3411 } 3412 3413 function fromObject$1 (that, obj) { 3414 if (internalIsBuffer$1(obj)) { 3415 var len = checked$1(obj.length) | 0; 3416 that = createBuffer$1(that, len); 3417 3418 if (that.length === 0) { 3419 return that 3420 } 3421 3422 obj.copy(that, 0, 0, len); 3423 return that 3424 } 3425 3426 if (obj) { 3427 if ((typeof ArrayBuffer !== 'undefined' && 3428 obj.buffer instanceof ArrayBuffer) || 'length' in obj) { 3429 if (typeof obj.length !== 'number' || isnan$1(obj.length)) { 3430 return createBuffer$1(that, 0) 3431 } 3432 return fromArrayLike$1(that, obj) 3433 } 3434 3435 if (obj.type === 'Buffer' && isArray(obj.data)) { 3436 return fromArrayLike$1(that, obj.data) 3437 } 3438 } 3439 3440 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') 3441 } 3442 3443 function checked$1 (length) { 3444 // Note: cannot use `length < kMaxLength()` here because that fails when 3445 // length is NaN (which is otherwise coerced to zero.) 3446 if (length >= kMaxLength$1()) { 3447 throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 3448 'size: 0x' + kMaxLength$1().toString(16) + ' bytes') 3449 } 3450 return length | 0 3451 } 3452 Buffer$1.isBuffer = isBuffer$1; 3453 function internalIsBuffer$1 (b) { 3454 return !!(b != null && b._isBuffer) 3455 } 3456 3457 Buffer$1.compare = function compare (a, b) { 3458 if (!internalIsBuffer$1(a) || !internalIsBuffer$1(b)) { 3459 throw new TypeError('Arguments must be Buffers') 3460 } 3461 3462 if (a === b) return 0 3463 3464 var x = a.length; 3465 var y = b.length; 3466 3467 for (var i = 0, len = Math.min(x, y); i < len; ++i) { 3468 if (a[i] !== b[i]) { 3469 x = a[i]; 3470 y = b[i]; 3471 break 3472 } 3473 } 3474 3475 if (x < y) return -1 3476 if (y < x) return 1 3477 return 0 3478 }; 3479 3480 Buffer$1.isEncoding = function isEncoding (encoding) { 3481 switch (String(encoding).toLowerCase()) { 3482 case 'hex': 3483 case 'utf8': 3484 case 'utf-8': 3485 case 'ascii': 3486 case 'latin1': 3487 case 'binary': 3488 case 'base64': 3489 case 'ucs2': 3490 case 'ucs-2': 3491 case 'utf16le': 3492 case 'utf-16le': 3493 return true 3494 default: 3495 return false 3496 } 3497 }; 3498 3499 Buffer$1.concat = function concat (list, length) { 3500 if (!isArray(list)) { 3501 throw new TypeError('"list" argument must be an Array of Buffers') 3502 } 3503 3504 if (list.length === 0) { 3505 return Buffer$1.alloc(0) 3506 } 3507 3508 var i; 3509 if (length === undefined) { 3510 length = 0; 3511 for (i = 0; i < list.length; ++i) { 3512 length += list[i].length; 3513 } 3514 } 3515 3516 var buffer = Buffer$1.allocUnsafe(length); 3517 var pos = 0; 3518 for (i = 0; i < list.length; ++i) { 3519 var buf = list[i]; 3520 if (!internalIsBuffer$1(buf)) { 3521 throw new TypeError('"list" argument must be an Array of Buffers') 3522 } 3523 buf.copy(buffer, pos); 3524 pos += buf.length; 3525 } 3526 return buffer 3527 }; 3528 3529 function byteLength$1 (string, encoding) { 3530 if (internalIsBuffer$1(string)) { 3531 return string.length 3532 } 3533 if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && 3534 (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { 3535 return string.byteLength 3536 } 3537 if (typeof string !== 'string') { 3538 string = '' + string; 3539 } 3540 3541 var len = string.length; 3542 if (len === 0) return 0 3543 3544 // Use a for loop to avoid recursion 3545 var loweredCase = false; 3546 for (;;) { 3547 switch (encoding) { 3548 case 'ascii': 3549 case 'latin1': 3550 case 'binary': 3551 return len 3552 case 'utf8': 3553 case 'utf-8': 3554 case undefined: 3555 return utf8ToBytes$1(string).length 3556 case 'ucs2': 3557 case 'ucs-2': 3558 case 'utf16le': 3559 case 'utf-16le': 3560 return len * 2 3561 case 'hex': 3562 return len >>> 1 3563 case 'base64': 3564 return base64ToBytes$1(string).length 3565 default: 3566 if (loweredCase) return utf8ToBytes$1(string).length // assume utf8 3567 encoding = ('' + encoding).toLowerCase(); 3568 loweredCase = true; 3569 } 3570 } 3571 } 3572 Buffer$1.byteLength = byteLength$1; 3573 3574 function slowToString$1 (encoding, start, end) { 3575 var loweredCase = false; 3576 3577 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only 3578 // property of a typed array. 3579 3580 // This behaves neither like String nor Uint8Array in that we set start/end 3581 // to their upper/lower bounds if the value passed is out of range. 3582 // undefined is handled specially as per ECMA-262 6th Edition, 3583 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. 3584 if (start === undefined || start < 0) { 3585 start = 0; 3586 } 3587 // Return early if start > this.length. Done here to prevent potential uint32 3588 // coercion fail below. 3589 if (start > this.length) { 3590 return '' 3591 } 3592 3593 if (end === undefined || end > this.length) { 3594 end = this.length; 3595 } 3596 3597 if (end <= 0) { 3598 return '' 3599 } 3600 3601 // Force coersion to uint32. This will also coerce falsey/NaN values to 0. 3602 end >>>= 0; 3603 start >>>= 0; 3604 3605 if (end <= start) { 3606 return '' 3607 } 3608 3609 if (!encoding) encoding = 'utf8'; 3610 3611 while (true) { 3612 switch (encoding) { 3613 case 'hex': 3614 return hexSlice$1(this, start, end) 3615 3616 case 'utf8': 3617 case 'utf-8': 3618 return utf8Slice$1(this, start, end) 3619 3620 case 'ascii': 3621 return asciiSlice$1(this, start, end) 3622 3623 case 'latin1': 3624 case 'binary': 3625 return latin1Slice$1(this, start, end) 3626 3627 case 'base64': 3628 return base64Slice$1(this, start, end) 3629 3630 case 'ucs2': 3631 case 'ucs-2': 3632 case 'utf16le': 3633 case 'utf-16le': 3634 return utf16leSlice$1(this, start, end) 3635 3636 default: 3637 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) 3638 encoding = (encoding + '').toLowerCase(); 3639 loweredCase = true; 3640 } 3641 } 3642 } 3643 3644 // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect 3645 // Buffer instances. 3646 Buffer$1.prototype._isBuffer = true; 3647 3648 function swap$1 (b, n, m) { 3649 var i = b[n]; 3650 b[n] = b[m]; 3651 b[m] = i; 3652 } 3653 3654 Buffer$1.prototype.swap16 = function swap16 () { 3655 var len = this.length; 3656 if (len % 2 !== 0) { 3657 throw new RangeError('Buffer size must be a multiple of 16-bits') 3658 } 3659 for (var i = 0; i < len; i += 2) { 3660 swap$1(this, i, i + 1); 3661 } 3662 return this 3663 }; 3664 3665 Buffer$1.prototype.swap32 = function swap32 () { 3666 var len = this.length; 3667 if (len % 4 !== 0) { 3668 throw new RangeError('Buffer size must be a multiple of 32-bits') 3669 } 3670 for (var i = 0; i < len; i += 4) { 3671 swap$1(this, i, i + 3); 3672 swap$1(this, i + 1, i + 2); 3673 } 3674 return this 3675 }; 3676 3677 Buffer$1.prototype.swap64 = function swap64 () { 3678 var len = this.length; 3679 if (len % 8 !== 0) { 3680 throw new RangeError('Buffer size must be a multiple of 64-bits') 3681 } 3682 for (var i = 0; i < len; i += 8) { 3683 swap$1(this, i, i + 7); 3684 swap$1(this, i + 1, i + 6); 3685 swap$1(this, i + 2, i + 5); 3686 swap$1(this, i + 3, i + 4); 3687 } 3688 return this 3689 }; 3690 3691 Buffer$1.prototype.toString = function toString () { 3692 var length = this.length | 0; 3693 if (length === 0) return '' 3694 if (arguments.length === 0) return utf8Slice$1(this, 0, length) 3695 return slowToString$1.apply(this, arguments) 3696 }; 3697 3698 Buffer$1.prototype.equals = function equals (b) { 3699 if (!internalIsBuffer$1(b)) throw new TypeError('Argument must be a Buffer') 3700 if (this === b) return true 3701 return Buffer$1.compare(this, b) === 0 3702 }; 3703 3704 Buffer$1.prototype.inspect = function inspect () { 3705 var str = ''; 3706 var max = INSPECT_MAX_BYTES$1; 3707 if (this.length > 0) { 3708 str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); 3709 if (this.length > max) str += ' ... '; 3710 } 3711 return '<Buffer ' + str + '>' 3712 }; 3713 3714 Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { 3715 if (!internalIsBuffer$1(target)) { 3716 throw new TypeError('Argument must be a Buffer') 3717 } 3718 3719 if (start === undefined) { 3720 start = 0; 3721 } 3722 if (end === undefined) { 3723 end = target ? target.length : 0; 3724 } 3725 if (thisStart === undefined) { 3726 thisStart = 0; 3727 } 3728 if (thisEnd === undefined) { 3729 thisEnd = this.length; 3730 } 3731 3732 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { 3733 throw new RangeError('out of range index') 3734 } 3735 3736 if (thisStart >= thisEnd && start >= end) { 3737 return 0 3738 } 3739 if (thisStart >= thisEnd) { 3740 return -1 3741 } 3742 if (start >= end) { 3743 return 1 3744 } 3745 3746 start >>>= 0; 3747 end >>>= 0; 3748 thisStart >>>= 0; 3749 thisEnd >>>= 0; 3750 3751 if (this === target) return 0 3752 3753 var x = thisEnd - thisStart; 3754 var y = end - start; 3755 var len = Math.min(x, y); 3756 3757 var thisCopy = this.slice(thisStart, thisEnd); 3758 var targetCopy = target.slice(start, end); 3759 3760 for (var i = 0; i < len; ++i) { 3761 if (thisCopy[i] !== targetCopy[i]) { 3762 x = thisCopy[i]; 3763 y = targetCopy[i]; 3764 break 3765 } 3766 } 3767 3768 if (x < y) return -1 3769 if (y < x) return 1 3770 return 0 3771 }; 3772 3773 // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, 3774 // OR the last index of `val` in `buffer` at offset <= `byteOffset`. 3775 // 3776 // Arguments: 3777 // - buffer - a Buffer to search 3778 // - val - a string, Buffer, or number 3779 // - byteOffset - an index into `buffer`; will be clamped to an int32 3780 // - encoding - an optional encoding, relevant is val is a string 3781 // - dir - true for indexOf, false for lastIndexOf 3782 function bidirectionalIndexOf$1 (buffer, val, byteOffset, encoding, dir) { 3783 // Empty buffer means no match 3784 if (buffer.length === 0) return -1 3785 3786 // Normalize byteOffset 3787 if (typeof byteOffset === 'string') { 3788 encoding = byteOffset; 3789 byteOffset = 0; 3790 } else if (byteOffset > 0x7fffffff) { 3791 byteOffset = 0x7fffffff; 3792 } else if (byteOffset < -0x80000000) { 3793 byteOffset = -0x80000000; 3794 } 3795 byteOffset = +byteOffset; // Coerce to Number. 3796 if (isNaN(byteOffset)) { 3797 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer 3798 byteOffset = dir ? 0 : (buffer.length - 1); 3799 } 3800 3801 // Normalize byteOffset: negative offsets start from the end of the buffer 3802 if (byteOffset < 0) byteOffset = buffer.length + byteOffset; 3803 if (byteOffset >= buffer.length) { 3804 if (dir) return -1 3805 else byteOffset = buffer.length - 1; 3806 } else if (byteOffset < 0) { 3807 if (dir) byteOffset = 0; 3808 else return -1 3809 } 3810 3811 // Normalize val 3812 if (typeof val === 'string') { 3813 val = Buffer$1.from(val, encoding); 3814 } 3815 3816 // Finally, search either indexOf (if dir is true) or lastIndexOf 3817 if (internalIsBuffer$1(val)) { 3818 // Special case: looking for empty string/buffer always fails 3819 if (val.length === 0) { 3820 return -1 3821 } 3822 return arrayIndexOf$1(buffer, val, byteOffset, encoding, dir) 3823 } else if (typeof val === 'number') { 3824 val = val & 0xFF; // Search for a byte value [0-255] 3825 if (Buffer$1.TYPED_ARRAY_SUPPORT && 3826 typeof Uint8Array.prototype.indexOf === 'function') { 3827 if (dir) { 3828 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) 3829 } else { 3830 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) 3831 } 3832 } 3833 return arrayIndexOf$1(buffer, [ val ], byteOffset, encoding, dir) 3834 } 3835 3836 throw new TypeError('val must be string, number or Buffer') 3837 } 3838 3839 function arrayIndexOf$1 (arr, val, byteOffset, encoding, dir) { 3840 var indexSize = 1; 3841 var arrLength = arr.length; 3842 var valLength = val.length; 3843 3844 if (encoding !== undefined) { 3845 encoding = String(encoding).toLowerCase(); 3846 if (encoding === 'ucs2' || encoding === 'ucs-2' || 3847 encoding === 'utf16le' || encoding === 'utf-16le') { 3848 if (arr.length < 2 || val.length < 2) { 3849 return -1 3850 } 3851 indexSize = 2; 3852 arrLength /= 2; 3853 valLength /= 2; 3854 byteOffset /= 2; 3855 } 3856 } 3857 3858 function read (buf, i) { 3859 if (indexSize === 1) { 3860 return buf[i] 3861 } else { 3862 return buf.readUInt16BE(i * indexSize) 3863 } 3864 } 3865 3866 var i; 3867 if (dir) { 3868 var foundIndex = -1; 3869 for (i = byteOffset; i < arrLength; i++) { 3870 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { 3871 if (foundIndex === -1) foundIndex = i; 3872 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize 3873 } else { 3874 if (foundIndex !== -1) i -= i - foundIndex; 3875 foundIndex = -1; 3876 } 3877 } 3878 } else { 3879 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; 3880 for (i = byteOffset; i >= 0; i--) { 3881 var found = true; 3882 for (var j = 0; j < valLength; j++) { 3883 if (read(arr, i + j) !== read(val, j)) { 3884 found = false; 3885 break 3886 } 3887 } 3888 if (found) return i 3889 } 3890 } 3891 3892 return -1 3893 } 3894 3895 Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { 3896 return this.indexOf(val, byteOffset, encoding) !== -1 3897 }; 3898 3899 Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { 3900 return bidirectionalIndexOf$1(this, val, byteOffset, encoding, true) 3901 }; 3902 3903 Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { 3904 return bidirectionalIndexOf$1(this, val, byteOffset, encoding, false) 3905 }; 3906 3907 function hexWrite$1 (buf, string, offset, length) { 3908 offset = Number(offset) || 0; 3909 var remaining = buf.length - offset; 3910 if (!length) { 3911 length = remaining; 3912 } else { 3913 length = Number(length); 3914 if (length > remaining) { 3915 length = remaining; 3916 } 3917 } 3918 3919 // must be an even number of digits 3920 var strLen = string.length; 3921 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') 3922 3923 if (length > strLen / 2) { 3924 length = strLen / 2; 3925 } 3926 for (var i = 0; i < length; ++i) { 3927 var parsed = parseInt(string.substr(i * 2, 2), 16); 3928 if (isNaN(parsed)) return i 3929 buf[offset + i] = parsed; 3930 } 3931 return i 3932 } 3933 3934 function utf8Write$1 (buf, string, offset, length) { 3935 return blitBuffer$1(utf8ToBytes$1(string, buf.length - offset), buf, offset, length) 3936 } 3937 3938 function asciiWrite$1 (buf, string, offset, length) { 3939 return blitBuffer$1(asciiToBytes$1(string), buf, offset, length) 3940 } 3941 3942 function latin1Write$1 (buf, string, offset, length) { 3943 return asciiWrite$1(buf, string, offset, length) 3944 } 3945 3946 function base64Write$1 (buf, string, offset, length) { 3947 return blitBuffer$1(base64ToBytes$1(string), buf, offset, length) 3948 } 3949 3950 function ucs2Write$1 (buf, string, offset, length) { 3951 return blitBuffer$1(utf16leToBytes$1(string, buf.length - offset), buf, offset, length) 3952 } 3953 3954 Buffer$1.prototype.write = function write (string, offset, length, encoding) { 3955 // Buffer#write(string) 3956 if (offset === undefined) { 3957 encoding = 'utf8'; 3958 length = this.length; 3959 offset = 0; 3960 // Buffer#write(string, encoding) 3961 } else if (length === undefined && typeof offset === 'string') { 3962 encoding = offset; 3963 length = this.length; 3964 offset = 0; 3965 // Buffer#write(string, offset[, length][, encoding]) 3966 } else if (isFinite(offset)) { 3967 offset = offset | 0; 3968 if (isFinite(length)) { 3969 length = length | 0; 3970 if (encoding === undefined) encoding = 'utf8'; 3971 } else { 3972 encoding = length; 3973 length = undefined; 3974 } 3975 // legacy write(string, encoding, offset, length) - remove in v0.13 3976 } else { 3977 throw new Error( 3978 'Buffer.write(string, encoding, offset[, length]) is no longer supported' 3979 ) 3980 } 3981 3982 var remaining = this.length - offset; 3983 if (length === undefined || length > remaining) length = remaining; 3984 3985 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { 3986 throw new RangeError('Attempt to write outside buffer bounds') 3987 } 3988 3989 if (!encoding) encoding = 'utf8'; 3990 3991 var loweredCase = false; 3992 for (;;) { 3993 switch (encoding) { 3994 case 'hex': 3995 return hexWrite$1(this, string, offset, length) 3996 3997 case 'utf8': 3998 case 'utf-8': 3999 return utf8Write$1(this, string, offset, length) 4000 4001 case 'ascii': 4002 return asciiWrite$1(this, string, offset, length) 4003 4004 case 'latin1': 4005 case 'binary': 4006 return latin1Write$1(this, string, offset, length) 4007 4008 case 'base64': 4009 // Warning: maxLength not taken into account in base64Write 4010 return base64Write$1(this, string, offset, length) 4011 4012 case 'ucs2': 4013 case 'ucs-2': 4014 case 'utf16le': 4015 case 'utf-16le': 4016 return ucs2Write$1(this, string, offset, length) 4017 4018 default: 4019 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) 4020 encoding = ('' + encoding).toLowerCase(); 4021 loweredCase = true; 4022 } 4023 } 4024 }; 4025 4026 Buffer$1.prototype.toJSON = function toJSON () { 4027 return { 4028 type: 'Buffer', 4029 data: Array.prototype.slice.call(this._arr || this, 0) 4030 } 4031 }; 4032 4033 function base64Slice$1 (buf, start, end) { 4034 if (start === 0 && end === buf.length) { 4035 return fromByteArray(buf) 4036 } else { 4037 return fromByteArray(buf.slice(start, end)) 4038 } 4039 } 4040 4041 function utf8Slice$1 (buf, start, end) { 4042 end = Math.min(buf.length, end); 4043 var res = []; 4044 4045 var i = start; 4046 while (i < end) { 4047 var firstByte = buf[i]; 4048 var codePoint = null; 4049 var bytesPerSequence = (firstByte > 0xEF) ? 4 4050 : (firstByte > 0xDF) ? 3 4051 : (firstByte > 0xBF) ? 2 4052 : 1; 4053 4054 if (i + bytesPerSequence <= end) { 4055 var secondByte, thirdByte, fourthByte, tempCodePoint; 4056 4057 switch (bytesPerSequence) { 4058 case 1: 4059 if (firstByte < 0x80) { 4060 codePoint = firstByte; 4061 } 4062 break 4063 case 2: 4064 secondByte = buf[i + 1]; 4065 if ((secondByte & 0xC0) === 0x80) { 4066 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); 4067 if (tempCodePoint > 0x7F) { 4068 codePoint = tempCodePoint; 4069 } 4070 } 4071 break 4072 case 3: 4073 secondByte = buf[i + 1]; 4074 thirdByte = buf[i + 2]; 4075 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { 4076 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); 4077 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { 4078 codePoint = tempCodePoint; 4079 } 4080 } 4081 break 4082 case 4: 4083 secondByte = buf[i + 1]; 4084 thirdByte = buf[i + 2]; 4085 fourthByte = buf[i + 3]; 4086 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { 4087 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); 4088 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { 4089 codePoint = tempCodePoint; 4090 } 4091 } 4092 } 4093 } 4094 4095 if (codePoint === null) { 4096 // we did not generate a valid codePoint so insert a 4097 // replacement char (U+FFFD) and advance only 1 byte 4098 codePoint = 0xFFFD; 4099 bytesPerSequence = 1; 4100 } else if (codePoint > 0xFFFF) { 4101 // encode to utf16 (surrogate pair dance) 4102 codePoint -= 0x10000; 4103 res.push(codePoint >>> 10 & 0x3FF | 0xD800); 4104 codePoint = 0xDC00 | codePoint & 0x3FF; 4105 } 4106 4107 res.push(codePoint); 4108 i += bytesPerSequence; 4109 } 4110 4111 return decodeCodePointsArray$1(res) 4112 } 4113 4114 // Based on http://stackoverflow.com/a/22747272/680742, the browser with 4115 // the lowest limit is Chrome, with 0x10000 args. 4116 // We go 1 magnitude less, for safety 4117 var MAX_ARGUMENTS_LENGTH$1 = 0x1000; 4118 4119 function decodeCodePointsArray$1 (codePoints) { 4120 var len = codePoints.length; 4121 if (len <= MAX_ARGUMENTS_LENGTH$1) { 4122 return String.fromCharCode.apply(String, codePoints) // avoid extra slice() 4123 } 4124 4125 // Decode in chunks to avoid "call stack size exceeded". 4126 var res = ''; 4127 var i = 0; 4128 while (i < len) { 4129 res += String.fromCharCode.apply( 4130 String, 4131 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH$1) 4132 ); 4133 } 4134 return res 4135 } 4136 4137 function asciiSlice$1 (buf, start, end) { 4138 var ret = ''; 4139 end = Math.min(buf.length, end); 4140 4141 for (var i = start; i < end; ++i) { 4142 ret += String.fromCharCode(buf[i] & 0x7F); 4143 } 4144 return ret 4145 } 4146 4147 function latin1Slice$1 (buf, start, end) { 4148 var ret = ''; 4149 end = Math.min(buf.length, end); 4150 4151 for (var i = start; i < end; ++i) { 4152 ret += String.fromCharCode(buf[i]); 4153 } 4154 return ret 4155 } 4156 4157 function hexSlice$1 (buf, start, end) { 4158 var len = buf.length; 4159 4160 if (!start || start < 0) start = 0; 4161 if (!end || end < 0 || end > len) end = len; 4162 4163 var out = ''; 4164 for (var i = start; i < end; ++i) { 4165 out += toHex$1(buf[i]); 4166 } 4167 return out 4168 } 4169 4170 function utf16leSlice$1 (buf, start, end) { 4171 var bytes = buf.slice(start, end); 4172 var res = ''; 4173 for (var i = 0; i < bytes.length; i += 2) { 4174 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); 4175 } 4176 return res 4177 } 4178 4179 Buffer$1.prototype.slice = function slice (start, end) { 4180 var len = this.length; 4181 start = ~~start; 4182 end = end === undefined ? len : ~~end; 4183 4184 if (start < 0) { 4185 start += len; 4186 if (start < 0) start = 0; 4187 } else if (start > len) { 4188 start = len; 4189 } 4190 4191 if (end < 0) { 4192 end += len; 4193 if (end < 0) end = 0; 4194 } else if (end > len) { 4195 end = len; 4196 } 4197 4198 if (end < start) end = start; 4199 4200 var newBuf; 4201 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 4202 newBuf = this.subarray(start, end); 4203 newBuf.__proto__ = Buffer$1.prototype; 4204 } else { 4205 var sliceLen = end - start; 4206 newBuf = new Buffer$1(sliceLen, undefined); 4207 for (var i = 0; i < sliceLen; ++i) { 4208 newBuf[i] = this[i + start]; 4209 } 4210 } 4211 4212 return newBuf 4213 }; 4214 4215 /* 4216 * Need to make sure that buffer isn't trying to write out of bounds. 4217 */ 4218 function checkOffset$1 (offset, ext, length) { 4219 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') 4220 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') 4221 } 4222 4223 Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { 4224 offset = offset | 0; 4225 byteLength = byteLength | 0; 4226 if (!noAssert) checkOffset$1(offset, byteLength, this.length); 4227 4228 var val = this[offset]; 4229 var mul = 1; 4230 var i = 0; 4231 while (++i < byteLength && (mul *= 0x100)) { 4232 val += this[offset + i] * mul; 4233 } 4234 4235 return val 4236 }; 4237 4238 Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { 4239 offset = offset | 0; 4240 byteLength = byteLength | 0; 4241 if (!noAssert) { 4242 checkOffset$1(offset, byteLength, this.length); 4243 } 4244 4245 var val = this[offset + --byteLength]; 4246 var mul = 1; 4247 while (byteLength > 0 && (mul *= 0x100)) { 4248 val += this[offset + --byteLength] * mul; 4249 } 4250 4251 return val 4252 }; 4253 4254 Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { 4255 if (!noAssert) checkOffset$1(offset, 1, this.length); 4256 return this[offset] 4257 }; 4258 4259 Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { 4260 if (!noAssert) checkOffset$1(offset, 2, this.length); 4261 return this[offset] | (this[offset + 1] << 8) 4262 }; 4263 4264 Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { 4265 if (!noAssert) checkOffset$1(offset, 2, this.length); 4266 return (this[offset] << 8) | this[offset + 1] 4267 }; 4268 4269 Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { 4270 if (!noAssert) checkOffset$1(offset, 4, this.length); 4271 4272 return ((this[offset]) | 4273 (this[offset + 1] << 8) | 4274 (this[offset + 2] << 16)) + 4275 (this[offset + 3] * 0x1000000) 4276 }; 4277 4278 Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { 4279 if (!noAssert) checkOffset$1(offset, 4, this.length); 4280 4281 return (this[offset] * 0x1000000) + 4282 ((this[offset + 1] << 16) | 4283 (this[offset + 2] << 8) | 4284 this[offset + 3]) 4285 }; 4286 4287 Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { 4288 offset = offset | 0; 4289 byteLength = byteLength | 0; 4290 if (!noAssert) checkOffset$1(offset, byteLength, this.length); 4291 4292 var val = this[offset]; 4293 var mul = 1; 4294 var i = 0; 4295 while (++i < byteLength && (mul *= 0x100)) { 4296 val += this[offset + i] * mul; 4297 } 4298 mul *= 0x80; 4299 4300 if (val >= mul) val -= Math.pow(2, 8 * byteLength); 4301 4302 return val 4303 }; 4304 4305 Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { 4306 offset = offset | 0; 4307 byteLength = byteLength | 0; 4308 if (!noAssert) checkOffset$1(offset, byteLength, this.length); 4309 4310 var i = byteLength; 4311 var mul = 1; 4312 var val = this[offset + --i]; 4313 while (i > 0 && (mul *= 0x100)) { 4314 val += this[offset + --i] * mul; 4315 } 4316 mul *= 0x80; 4317 4318 if (val >= mul) val -= Math.pow(2, 8 * byteLength); 4319 4320 return val 4321 }; 4322 4323 Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { 4324 if (!noAssert) checkOffset$1(offset, 1, this.length); 4325 if (!(this[offset] & 0x80)) return (this[offset]) 4326 return ((0xff - this[offset] + 1) * -1) 4327 }; 4328 4329 Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { 4330 if (!noAssert) checkOffset$1(offset, 2, this.length); 4331 var val = this[offset] | (this[offset + 1] << 8); 4332 return (val & 0x8000) ? val | 0xFFFF0000 : val 4333 }; 4334 4335 Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { 4336 if (!noAssert) checkOffset$1(offset, 2, this.length); 4337 var val = this[offset + 1] | (this[offset] << 8); 4338 return (val & 0x8000) ? val | 0xFFFF0000 : val 4339 }; 4340 4341 Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { 4342 if (!noAssert) checkOffset$1(offset, 4, this.length); 4343 4344 return (this[offset]) | 4345 (this[offset + 1] << 8) | 4346 (this[offset + 2] << 16) | 4347 (this[offset + 3] << 24) 4348 }; 4349 4350 Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { 4351 if (!noAssert) checkOffset$1(offset, 4, this.length); 4352 4353 return (this[offset] << 24) | 4354 (this[offset + 1] << 16) | 4355 (this[offset + 2] << 8) | 4356 (this[offset + 3]) 4357 }; 4358 4359 Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { 4360 if (!noAssert) checkOffset$1(offset, 4, this.length); 4361 return read(this, offset, true, 23, 4) 4362 }; 4363 4364 Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { 4365 if (!noAssert) checkOffset$1(offset, 4, this.length); 4366 return read(this, offset, false, 23, 4) 4367 }; 4368 4369 Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { 4370 if (!noAssert) checkOffset$1(offset, 8, this.length); 4371 return read(this, offset, true, 52, 8) 4372 }; 4373 4374 Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { 4375 if (!noAssert) checkOffset$1(offset, 8, this.length); 4376 return read(this, offset, false, 52, 8) 4377 }; 4378 4379 function checkInt$1 (buf, value, offset, ext, max, min) { 4380 if (!internalIsBuffer$1(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') 4381 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') 4382 if (offset + ext > buf.length) throw new RangeError('Index out of range') 4383 } 4384 4385 Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { 4386 value = +value; 4387 offset = offset | 0; 4388 byteLength = byteLength | 0; 4389 if (!noAssert) { 4390 var maxBytes = Math.pow(2, 8 * byteLength) - 1; 4391 checkInt$1(this, value, offset, byteLength, maxBytes, 0); 4392 } 4393 4394 var mul = 1; 4395 var i = 0; 4396 this[offset] = value & 0xFF; 4397 while (++i < byteLength && (mul *= 0x100)) { 4398 this[offset + i] = (value / mul) & 0xFF; 4399 } 4400 4401 return offset + byteLength 4402 }; 4403 4404 Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { 4405 value = +value; 4406 offset = offset | 0; 4407 byteLength = byteLength | 0; 4408 if (!noAssert) { 4409 var maxBytes = Math.pow(2, 8 * byteLength) - 1; 4410 checkInt$1(this, value, offset, byteLength, maxBytes, 0); 4411 } 4412 4413 var i = byteLength - 1; 4414 var mul = 1; 4415 this[offset + i] = value & 0xFF; 4416 while (--i >= 0 && (mul *= 0x100)) { 4417 this[offset + i] = (value / mul) & 0xFF; 4418 } 4419 4420 return offset + byteLength 4421 }; 4422 4423 Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { 4424 value = +value; 4425 offset = offset | 0; 4426 if (!noAssert) checkInt$1(this, value, offset, 1, 0xff, 0); 4427 if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); 4428 this[offset] = (value & 0xff); 4429 return offset + 1 4430 }; 4431 4432 function objectWriteUInt16$1 (buf, value, offset, littleEndian) { 4433 if (value < 0) value = 0xffff + value + 1; 4434 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { 4435 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> 4436 (littleEndian ? i : 1 - i) * 8; 4437 } 4438 } 4439 4440 Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { 4441 value = +value; 4442 offset = offset | 0; 4443 if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0); 4444 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 4445 this[offset] = (value & 0xff); 4446 this[offset + 1] = (value >>> 8); 4447 } else { 4448 objectWriteUInt16$1(this, value, offset, true); 4449 } 4450 return offset + 2 4451 }; 4452 4453 Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { 4454 value = +value; 4455 offset = offset | 0; 4456 if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0); 4457 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 4458 this[offset] = (value >>> 8); 4459 this[offset + 1] = (value & 0xff); 4460 } else { 4461 objectWriteUInt16$1(this, value, offset, false); 4462 } 4463 return offset + 2 4464 }; 4465 4466 function objectWriteUInt32$1 (buf, value, offset, littleEndian) { 4467 if (value < 0) value = 0xffffffff + value + 1; 4468 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { 4469 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; 4470 } 4471 } 4472 4473 Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { 4474 value = +value; 4475 offset = offset | 0; 4476 if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0); 4477 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 4478 this[offset + 3] = (value >>> 24); 4479 this[offset + 2] = (value >>> 16); 4480 this[offset + 1] = (value >>> 8); 4481 this[offset] = (value & 0xff); 4482 } else { 4483 objectWriteUInt32$1(this, value, offset, true); 4484 } 4485 return offset + 4 4486 }; 4487 4488 Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { 4489 value = +value; 4490 offset = offset | 0; 4491 if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0); 4492 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 4493 this[offset] = (value >>> 24); 4494 this[offset + 1] = (value >>> 16); 4495 this[offset + 2] = (value >>> 8); 4496 this[offset + 3] = (value & 0xff); 4497 } else { 4498 objectWriteUInt32$1(this, value, offset, false); 4499 } 4500 return offset + 4 4501 }; 4502 4503 Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { 4504 value = +value; 4505 offset = offset | 0; 4506 if (!noAssert) { 4507 var limit = Math.pow(2, 8 * byteLength - 1); 4508 4509 checkInt$1(this, value, offset, byteLength, limit - 1, -limit); 4510 } 4511 4512 var i = 0; 4513 var mul = 1; 4514 var sub = 0; 4515 this[offset] = value & 0xFF; 4516 while (++i < byteLength && (mul *= 0x100)) { 4517 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { 4518 sub = 1; 4519 } 4520 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; 4521 } 4522 4523 return offset + byteLength 4524 }; 4525 4526 Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { 4527 value = +value; 4528 offset = offset | 0; 4529 if (!noAssert) { 4530 var limit = Math.pow(2, 8 * byteLength - 1); 4531 4532 checkInt$1(this, value, offset, byteLength, limit - 1, -limit); 4533 } 4534 4535 var i = byteLength - 1; 4536 var mul = 1; 4537 var sub = 0; 4538 this[offset + i] = value & 0xFF; 4539 while (--i >= 0 && (mul *= 0x100)) { 4540 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { 4541 sub = 1; 4542 } 4543 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; 4544 } 4545 4546 return offset + byteLength 4547 }; 4548 4549 Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { 4550 value = +value; 4551 offset = offset | 0; 4552 if (!noAssert) checkInt$1(this, value, offset, 1, 0x7f, -0x80); 4553 if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); 4554 if (value < 0) value = 0xff + value + 1; 4555 this[offset] = (value & 0xff); 4556 return offset + 1 4557 }; 4558 4559 Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { 4560 value = +value; 4561 offset = offset | 0; 4562 if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000); 4563 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 4564 this[offset] = (value & 0xff); 4565 this[offset + 1] = (value >>> 8); 4566 } else { 4567 objectWriteUInt16$1(this, value, offset, true); 4568 } 4569 return offset + 2 4570 }; 4571 4572 Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { 4573 value = +value; 4574 offset = offset | 0; 4575 if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000); 4576 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 4577 this[offset] = (value >>> 8); 4578 this[offset + 1] = (value & 0xff); 4579 } else { 4580 objectWriteUInt16$1(this, value, offset, false); 4581 } 4582 return offset + 2 4583 }; 4584 4585 Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { 4586 value = +value; 4587 offset = offset | 0; 4588 if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000); 4589 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 4590 this[offset] = (value & 0xff); 4591 this[offset + 1] = (value >>> 8); 4592 this[offset + 2] = (value >>> 16); 4593 this[offset + 3] = (value >>> 24); 4594 } else { 4595 objectWriteUInt32$1(this, value, offset, true); 4596 } 4597 return offset + 4 4598 }; 4599 4600 Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { 4601 value = +value; 4602 offset = offset | 0; 4603 if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000); 4604 if (value < 0) value = 0xffffffff + value + 1; 4605 if (Buffer$1.TYPED_ARRAY_SUPPORT) { 4606 this[offset] = (value >>> 24); 4607 this[offset + 1] = (value >>> 16); 4608 this[offset + 2] = (value >>> 8); 4609 this[offset + 3] = (value & 0xff); 4610 } else { 4611 objectWriteUInt32$1(this, value, offset, false); 4612 } 4613 return offset + 4 4614 }; 4615 4616 function checkIEEE754$1 (buf, value, offset, ext, max, min) { 4617 if (offset + ext > buf.length) throw new RangeError('Index out of range') 4618 if (offset < 0) throw new RangeError('Index out of range') 4619 } 4620 4621 function writeFloat$1 (buf, value, offset, littleEndian, noAssert) { 4622 if (!noAssert) { 4623 checkIEEE754$1(buf, value, offset, 4); 4624 } 4625 write(buf, value, offset, littleEndian, 23, 4); 4626 return offset + 4 4627 } 4628 4629 Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { 4630 return writeFloat$1(this, value, offset, true, noAssert) 4631 }; 4632 4633 Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { 4634 return writeFloat$1(this, value, offset, false, noAssert) 4635 }; 4636 4637 function writeDouble$1 (buf, value, offset, littleEndian, noAssert) { 4638 if (!noAssert) { 4639 checkIEEE754$1(buf, value, offset, 8); 4640 } 4641 write(buf, value, offset, littleEndian, 52, 8); 4642 return offset + 8 4643 } 4644 4645 Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { 4646 return writeDouble$1(this, value, offset, true, noAssert) 4647 }; 4648 4649 Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { 4650 return writeDouble$1(this, value, offset, false, noAssert) 4651 }; 4652 4653 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) 4654 Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { 4655 if (!start) start = 0; 4656 if (!end && end !== 0) end = this.length; 4657 if (targetStart >= target.length) targetStart = target.length; 4658 if (!targetStart) targetStart = 0; 4659 if (end > 0 && end < start) end = start; 4660 4661 // Copy 0 bytes; we're done 4662 if (end === start) return 0 4663 if (target.length === 0 || this.length === 0) return 0 4664 4665 // Fatal error conditions 4666 if (targetStart < 0) { 4667 throw new RangeError('targetStart out of bounds') 4668 } 4669 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') 4670 if (end < 0) throw new RangeError('sourceEnd out of bounds') 4671 4672 // Are we oob? 4673 if (end > this.length) end = this.length; 4674 if (target.length - targetStart < end - start) { 4675 end = target.length - targetStart + start; 4676 } 4677 4678 var len = end - start; 4679 var i; 4680 4681 if (this === target && start < targetStart && targetStart < end) { 4682 // descending copy from end 4683 for (i = len - 1; i >= 0; --i) { 4684 target[i + targetStart] = this[i + start]; 4685 } 4686 } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { 4687 // ascending copy from start 4688 for (i = 0; i < len; ++i) { 4689 target[i + targetStart] = this[i + start]; 4690 } 4691 } else { 4692 Uint8Array.prototype.set.call( 4693 target, 4694 this.subarray(start, start + len), 4695 targetStart 4696 ); 4697 } 4698 4699 return len 4700 }; 4701 4702 // Usage: 4703 // buffer.fill(number[, offset[, end]]) 4704 // buffer.fill(buffer[, offset[, end]]) 4705 // buffer.fill(string[, offset[, end]][, encoding]) 4706 Buffer$1.prototype.fill = function fill (val, start, end, encoding) { 4707 // Handle string cases: 4708 if (typeof val === 'string') { 4709 if (typeof start === 'string') { 4710 encoding = start; 4711 start = 0; 4712 end = this.length; 4713 } else if (typeof end === 'string') { 4714 encoding = end; 4715 end = this.length; 4716 } 4717 if (val.length === 1) { 4718 var code = val.charCodeAt(0); 4719 if (code < 256) { 4720 val = code; 4721 } 4722 } 4723 if (encoding !== undefined && typeof encoding !== 'string') { 4724 throw new TypeError('encoding must be a string') 4725 } 4726 if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { 4727 throw new TypeError('Unknown encoding: ' + encoding) 4728 } 4729 } else if (typeof val === 'number') { 4730 val = val & 255; 4731 } 4732 4733 // Invalid ranges are not set to a default, so can range check early. 4734 if (start < 0 || this.length < start || this.length < end) { 4735 throw new RangeError('Out of range index') 4736 } 4737 4738 if (end <= start) { 4739 return this 4740 } 4741 4742 start = start >>> 0; 4743 end = end === undefined ? this.length : end >>> 0; 4744 4745 if (!val) val = 0; 4746 4747 var i; 4748 if (typeof val === 'number') { 4749 for (i = start; i < end; ++i) { 4750 this[i] = val; 4751 } 4752 } else { 4753 var bytes = internalIsBuffer$1(val) 4754 ? val 4755 : utf8ToBytes$1(new Buffer$1(val, encoding).toString()); 4756 var len = bytes.length; 4757 for (i = 0; i < end - start; ++i) { 4758 this[i + start] = bytes[i % len]; 4759 } 4760 } 4761 4762 return this 4763 }; 4764 4765 // HELPER FUNCTIONS 4766 // ================ 4767 4768 var INVALID_BASE64_RE$1 = /[^+\/0-9A-Za-z-_]/g; 4769 4770 function base64clean$1 (str) { 4771 // Node strips out invalid characters like \n and \t from the string, base64-js does not 4772 str = stringtrim$1(str).replace(INVALID_BASE64_RE$1, ''); 4773 // Node converts strings with length < 2 to '' 4774 if (str.length < 2) return '' 4775 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not 4776 while (str.length % 4 !== 0) { 4777 str = str + '='; 4778 } 4779 return str 4780 } 4781 4782 function stringtrim$1 (str) { 4783 if (str.trim) return str.trim() 4784 return str.replace(/^\s+|\s+$/g, '') 4785 } 4786 4787 function toHex$1 (n) { 4788 if (n < 16) return '0' + n.toString(16) 4789 return n.toString(16) 4790 } 4791 4792 function utf8ToBytes$1 (string, units) { 4793 units = units || Infinity; 4794 var codePoint; 4795 var length = string.length; 4796 var leadSurrogate = null; 4797 var bytes = []; 4798 4799 for (var i = 0; i < length; ++i) { 4800 codePoint = string.charCodeAt(i); 4801 4802 // is surrogate component 4803 if (codePoint > 0xD7FF && codePoint < 0xE000) { 4804 // last char was a lead 4805 if (!leadSurrogate) { 4806 // no lead yet 4807 if (codePoint > 0xDBFF) { 4808 // unexpected trail 4809 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 4810 continue 4811 } else if (i + 1 === length) { 4812 // unpaired lead 4813 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 4814 continue 4815 } 4816 4817 // valid lead 4818 leadSurrogate = codePoint; 4819 4820 continue 4821 } 4822 4823 // 2 leads in a row 4824 if (codePoint < 0xDC00) { 4825 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 4826 leadSurrogate = codePoint; 4827 continue 4828 } 4829 4830 // valid surrogate pair 4831 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; 4832 } else if (leadSurrogate) { 4833 // valid bmp char, but last char was a lead 4834 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 4835 } 4836 4837 leadSurrogate = null; 4838 4839 // encode utf8 4840 if (codePoint < 0x80) { 4841 if ((units -= 1) < 0) break 4842 bytes.push(codePoint); 4843 } else if (codePoint < 0x800) { 4844 if ((units -= 2) < 0) break 4845 bytes.push( 4846 codePoint >> 0x6 | 0xC0, 4847 codePoint & 0x3F | 0x80 4848 ); 4849 } else if (codePoint < 0x10000) { 4850 if ((units -= 3) < 0) break 4851 bytes.push( 4852 codePoint >> 0xC | 0xE0, 4853 codePoint >> 0x6 & 0x3F | 0x80, 4854 codePoint & 0x3F | 0x80 4855 ); 4856 } else if (codePoint < 0x110000) { 4857 if ((units -= 4) < 0) break 4858 bytes.push( 4859 codePoint >> 0x12 | 0xF0, 4860 codePoint >> 0xC & 0x3F | 0x80, 4861 codePoint >> 0x6 & 0x3F | 0x80, 4862 codePoint & 0x3F | 0x80 4863 ); 4864 } else { 4865 throw new Error('Invalid code point') 4866 } 4867 } 4868 4869 return bytes 4870 } 4871 4872 function asciiToBytes$1 (str) { 4873 var byteArray = []; 4874 for (var i = 0; i < str.length; ++i) { 4875 // Node's code seems to be doing this and not & 0x7F.. 4876 byteArray.push(str.charCodeAt(i) & 0xFF); 4877 } 4878 return byteArray 4879 } 4880 4881 function utf16leToBytes$1 (str, units) { 4882 var c, hi, lo; 4883 var byteArray = []; 4884 for (var i = 0; i < str.length; ++i) { 4885 if ((units -= 2) < 0) break 4886 4887 c = str.charCodeAt(i); 4888 hi = c >> 8; 4889 lo = c % 256; 4890 byteArray.push(lo); 4891 byteArray.push(hi); 4892 } 4893 4894 return byteArray 4895 } 4896 4897 4898 function base64ToBytes$1 (str) { 4899 return toByteArray(base64clean$1(str)) 4900 } 4901 4902 function blitBuffer$1 (src, dst, offset, length) { 4903 for (var i = 0; i < length; ++i) { 4904 if ((i + offset >= dst.length) || (i >= src.length)) break 4905 dst[i + offset] = src[i]; 4906 } 4907 return i 4908 } 4909 4910 function isnan$1 (val) { 4911 return val !== val // eslint-disable-line no-self-compare 4912 } 4913 4914 4915 // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence 4916 // The _isBuffer check is for Safari 5-7 support, because it's missing 4917 // Object.prototype.constructor. Remove this eventually 4918 function isBuffer$1(obj) { 4919 return obj != null && (!!obj._isBuffer || isFastBuffer$1(obj) || isSlowBuffer$1(obj)) 4920 } 4921 4922 function isFastBuffer$1 (obj) { 4923 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) 4924 } 4925 4926 // For Node v0.10 support. Remove this eventually. 4927 function isSlowBuffer$1 (obj) { 4928 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer$1(obj.slice(0, 0)) 4929 } 4930 4931 function BufferList() { 4932 this.head = null; 4933 this.tail = null; 4934 this.length = 0; 4935 } 4936 4937 BufferList.prototype.push = function (v) { 4938 var entry = { data: v, next: null }; 4939 if (this.length > 0) this.tail.next = entry;else this.head = entry; 4940 this.tail = entry; 4941 ++this.length; 4942 }; 4943 4944 BufferList.prototype.unshift = function (v) { 4945 var entry = { data: v, next: this.head }; 4946 if (this.length === 0) this.tail = entry; 4947 this.head = entry; 4948 ++this.length; 4949 }; 4950 4951 BufferList.prototype.shift = function () { 4952 if (this.length === 0) return; 4953 var ret = this.head.data; 4954 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; 4955 --this.length; 4956 return ret; 4957 }; 4958 4959 BufferList.prototype.clear = function () { 4960 this.head = this.tail = null; 4961 this.length = 0; 4962 }; 4963 4964 BufferList.prototype.join = function (s) { 4965 if (this.length === 0) return ''; 4966 var p = this.head; 4967 var ret = '' + p.data; 4968 while (p = p.next) { 4969 ret += s + p.data; 4970 }return ret; 4971 }; 4972 4973 BufferList.prototype.concat = function (n) { 4974 if (this.length === 0) return Buffer$1.alloc(0); 4975 if (this.length === 1) return this.head.data; 4976 var ret = Buffer$1.allocUnsafe(n >>> 0); 4977 var p = this.head; 4978 var i = 0; 4979 while (p) { 4980 p.data.copy(ret, i); 4981 i += p.data.length; 4982 p = p.next; 4983 } 4984 return ret; 4985 }; 4986 4987 // Copyright Joyent, Inc. and other Node contributors. 4988 var isBufferEncoding = Buffer$1.isEncoding 4989 || function(encoding) { 4990 switch (encoding && encoding.toLowerCase()) { 4991 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; 4992 default: return false; 4993 } 4994 }; 4995 4996 4997 function assertEncoding(encoding) { 4998 if (encoding && !isBufferEncoding(encoding)) { 4999 throw new Error('Unknown encoding: ' + encoding); 5000 } 5001 } 5002 5003 // StringDecoder provides an interface for efficiently splitting a series of 5004 // buffers into a series of JS strings without breaking apart multi-byte 5005 // characters. CESU-8 is handled as part of the UTF-8 encoding. 5006 // 5007 // @TODO Handling all encodings inside a single object makes it very difficult 5008 // to reason about this code, so it should be split up in the future. 5009 // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code 5010 // points as used by CESU-8. 5011 function StringDecoder(encoding) { 5012 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); 5013 assertEncoding(encoding); 5014 switch (this.encoding) { 5015 case 'utf8': 5016 // CESU-8 represents each of Surrogate Pair by 3-bytes 5017 this.surrogateSize = 3; 5018 break; 5019 case 'ucs2': 5020 case 'utf16le': 5021 // UTF-16 represents each of Surrogate Pair by 2-bytes 5022 this.surrogateSize = 2; 5023 this.detectIncompleteChar = utf16DetectIncompleteChar; 5024 break; 5025 case 'base64': 5026 // Base-64 stores 3 bytes in 4 chars, and pads the remainder. 5027 this.surrogateSize = 3; 5028 this.detectIncompleteChar = base64DetectIncompleteChar; 5029 break; 5030 default: 5031 this.write = passThroughWrite; 5032 return; 5033 } 5034 5035 // Enough space to store all bytes of a single character. UTF-8 needs 4 5036 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). 5037 this.charBuffer = new Buffer$1(6); 5038 // Number of bytes received for the current incomplete multi-byte character. 5039 this.charReceived = 0; 5040 // Number of bytes expected for the current incomplete multi-byte character. 5041 this.charLength = 0; 5042 } 5043 5044 // write decodes the given buffer and returns it as JS string that is 5045 // guaranteed to not contain any partial multi-byte characters. Any partial 5046 // character found at the end of the buffer is buffered up, and will be 5047 // returned when calling write again with the remaining bytes. 5048 // 5049 // Note: Converting a Buffer containing an orphan surrogate to a String 5050 // currently works, but converting a String to a Buffer (via `new Buffer`, or 5051 // Buffer#write) will replace incomplete surrogates with the unicode 5052 // replacement character. See https://codereview.chromium.org/121173009/ . 5053 StringDecoder.prototype.write = function(buffer) { 5054 var charStr = ''; 5055 // if our last write ended with an incomplete multibyte character 5056 while (this.charLength) { 5057 // determine how many remaining bytes this buffer has to offer for this char 5058 var available = (buffer.length >= this.charLength - this.charReceived) ? 5059 this.charLength - this.charReceived : 5060 buffer.length; 5061 5062 // add the new bytes to the char buffer 5063 buffer.copy(this.charBuffer, this.charReceived, 0, available); 5064 this.charReceived += available; 5065 5066 if (this.charReceived < this.charLength) { 5067 // still not enough chars in this buffer? wait for more ... 5068 return ''; 5069 } 5070 5071 // remove bytes belonging to the current character from the buffer 5072 buffer = buffer.slice(available, buffer.length); 5073 5074 // get the character that was split 5075 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); 5076 5077 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character 5078 var charCode = charStr.charCodeAt(charStr.length - 1); 5079 if (charCode >= 0xD800 && charCode <= 0xDBFF) { 5080 this.charLength += this.surrogateSize; 5081 charStr = ''; 5082 continue; 5083 } 5084 this.charReceived = this.charLength = 0; 5085 5086 // if there are no more bytes in this buffer, just emit our char 5087 if (buffer.length === 0) { 5088 return charStr; 5089 } 5090 break; 5091 } 5092 5093 // determine and set charLength / charReceived 5094 this.detectIncompleteChar(buffer); 5095 5096 var end = buffer.length; 5097 if (this.charLength) { 5098 // buffer the incomplete character bytes we got 5099 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); 5100 end -= this.charReceived; 5101 } 5102 5103 charStr += buffer.toString(this.encoding, 0, end); 5104 5105 var end = charStr.length - 1; 5106 var charCode = charStr.charCodeAt(end); 5107 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character 5108 if (charCode >= 0xD800 && charCode <= 0xDBFF) { 5109 var size = this.surrogateSize; 5110 this.charLength += size; 5111 this.charReceived += size; 5112 this.charBuffer.copy(this.charBuffer, size, 0, size); 5113 buffer.copy(this.charBuffer, 0, 0, size); 5114 return charStr.substring(0, end); 5115 } 5116 5117 // or just emit the charStr 5118 return charStr; 5119 }; 5120 5121 // detectIncompleteChar determines if there is an incomplete UTF-8 character at 5122 // the end of the given buffer. If so, it sets this.charLength to the byte 5123 // length that character, and sets this.charReceived to the number of bytes 5124 // that are available for this character. 5125 StringDecoder.prototype.detectIncompleteChar = function(buffer) { 5126 // determine how many bytes we have to check at the end of this buffer 5127 var i = (buffer.length >= 3) ? 3 : buffer.length; 5128 5129 // Figure out if one of the last i bytes of our buffer announces an 5130 // incomplete char. 5131 for (; i > 0; i--) { 5132 var c = buffer[buffer.length - i]; 5133 5134 // See http://en.wikipedia.org/wiki/UTF-8#Description 5135 5136 // 110XXXXX 5137 if (i == 1 && c >> 5 == 0x06) { 5138 this.charLength = 2; 5139 break; 5140 } 5141 5142 // 1110XXXX 5143 if (i <= 2 && c >> 4 == 0x0E) { 5144 this.charLength = 3; 5145 break; 5146 } 5147 5148 // 11110XXX 5149 if (i <= 3 && c >> 3 == 0x1E) { 5150 this.charLength = 4; 5151 break; 5152 } 5153 } 5154 this.charReceived = i; 5155 }; 5156 5157 StringDecoder.prototype.end = function(buffer) { 5158 var res = ''; 5159 if (buffer && buffer.length) 5160 res = this.write(buffer); 5161 5162 if (this.charReceived) { 5163 var cr = this.charReceived; 5164 var buf = this.charBuffer; 5165 var enc = this.encoding; 5166 res += buf.slice(0, cr).toString(enc); 5167 } 5168 5169 return res; 5170 }; 5171 5172 function passThroughWrite(buffer) { 5173 return buffer.toString(this.encoding); 5174 } 5175 5176 function utf16DetectIncompleteChar(buffer) { 5177 this.charReceived = buffer.length % 2; 5178 this.charLength = this.charReceived ? 2 : 0; 5179 } 5180 5181 function base64DetectIncompleteChar(buffer) { 5182 this.charReceived = buffer.length % 3; 5183 this.charLength = this.charReceived ? 3 : 0; 5184 } 5185 5186 Readable.ReadableState = ReadableState; 5187 5188 var debug = debuglog('stream'); 5189 inherits$1(Readable, EventEmitter); 5190 5191 function prependListener(emitter, event, fn) { 5192 // Sadly this is not cacheable as some libraries bundle their own 5193 // event emitter implementation with them. 5194 if (typeof emitter.prependListener === 'function') { 5195 return emitter.prependListener(event, fn); 5196 } else { 5197 // This is a hack to make sure that our error handler is attached before any 5198 // userland ones. NEVER DO THIS. This is here only because this code needs 5199 // to continue to work with older versions of Node.js that do not include 5200 // the prependListener() method. The goal is to eventually remove this hack. 5201 if (!emitter._events || !emitter._events[event]) 5202 emitter.on(event, fn); 5203 else if (Array.isArray(emitter._events[event])) 5204 emitter._events[event].unshift(fn); 5205 else 5206 emitter._events[event] = [fn, emitter._events[event]]; 5207 } 5208 } 5209 function listenerCount$1 (emitter, type) { 5210 return emitter.listeners(type).length; 5211 } 5212 function ReadableState(options, stream) { 5213 5214 options = options || {}; 5215 5216 // object stream flag. Used to make read(n) ignore n and to 5217 // make all the buffer merging and length checks go away 5218 this.objectMode = !!options.objectMode; 5219 5220 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; 5221 5222 // the point at which it stops calling _read() to fill the buffer 5223 // Note: 0 is a valid value, means "don't call _read preemptively ever" 5224 var hwm = options.highWaterMark; 5225 var defaultHwm = this.objectMode ? 16 : 16 * 1024; 5226 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; 5227 5228 // cast to ints. 5229 this.highWaterMark = ~ ~this.highWaterMark; 5230 5231 // A linked list is used to store data chunks instead of an array because the 5232 // linked list can remove elements from the beginning faster than 5233 // array.shift() 5234 this.buffer = new BufferList(); 5235 this.length = 0; 5236 this.pipes = null; 5237 this.pipesCount = 0; 5238 this.flowing = null; 5239 this.ended = false; 5240 this.endEmitted = false; 5241 this.reading = false; 5242 5243 // a flag to be able to tell if the onwrite cb is called immediately, 5244 // or on a later tick. We set this to true at first, because any 5245 // actions that shouldn't happen until "later" should generally also 5246 // not happen before the first write call. 5247 this.sync = true; 5248 5249 // whenever we return null, then we set a flag to say 5250 // that we're awaiting a 'readable' event emission. 5251 this.needReadable = false; 5252 this.emittedReadable = false; 5253 this.readableListening = false; 5254 this.resumeScheduled = false; 5255 5256 // Crypto is kind of old and crusty. Historically, its default string 5257 // encoding is 'binary' so we have to make this configurable. 5258 // Everything else in the universe uses 'utf8', though. 5259 this.defaultEncoding = options.defaultEncoding || 'utf8'; 5260 5261 // when piping, we only care about 'readable' events that happen 5262 // after read()ing all the bytes and not getting any pushback. 5263 this.ranOut = false; 5264 5265 // the number of writers that are awaiting a drain event in .pipe()s 5266 this.awaitDrain = 0; 5267 5268 // if true, a maybeReadMore has been scheduled 5269 this.readingMore = false; 5270 5271 this.decoder = null; 5272 this.encoding = null; 5273 if (options.encoding) { 5274 this.decoder = new StringDecoder(options.encoding); 5275 this.encoding = options.encoding; 5276 } 5277 } 5278 function Readable(options) { 5279 5280 if (!(this instanceof Readable)) return new Readable(options); 5281 5282 this._readableState = new ReadableState(options, this); 5283 5284 // legacy 5285 this.readable = true; 5286 5287 if (options && typeof options.read === 'function') this._read = options.read; 5288 5289 EventEmitter.call(this); 5290 } 5291 5292 // Manually shove something into the read() buffer. 5293 // This returns true if the highWaterMark has not been hit yet, 5294 // similar to how Writable.write() returns true if you should 5295 // write() some more. 5296 Readable.prototype.push = function (chunk, encoding) { 5297 var state = this._readableState; 5298 5299 if (!state.objectMode && typeof chunk === 'string') { 5300 encoding = encoding || state.defaultEncoding; 5301 if (encoding !== state.encoding) { 5302 chunk = Buffer.from(chunk, encoding); 5303 encoding = ''; 5304 } 5305 } 5306 5307 return readableAddChunk(this, state, chunk, encoding, false); 5308 }; 5309 5310 // Unshift should *always* be something directly out of read() 5311 Readable.prototype.unshift = function (chunk) { 5312 var state = this._readableState; 5313 return readableAddChunk(this, state, chunk, '', true); 5314 }; 5315 5316 Readable.prototype.isPaused = function () { 5317 return this._readableState.flowing === false; 5318 }; 5319 5320 function readableAddChunk(stream, state, chunk, encoding, addToFront) { 5321 var er = chunkInvalid(state, chunk); 5322 if (er) { 5323 stream.emit('error', er); 5324 } else if (chunk === null) { 5325 state.reading = false; 5326 onEofChunk(stream, state); 5327 } else if (state.objectMode || chunk && chunk.length > 0) { 5328 if (state.ended && !addToFront) { 5329 var e = new Error('stream.push() after EOF'); 5330 stream.emit('error', e); 5331 } else if (state.endEmitted && addToFront) { 5332 var _e = new Error('stream.unshift() after end event'); 5333 stream.emit('error', _e); 5334 } else { 5335 var skipAdd; 5336 if (state.decoder && !addToFront && !encoding) { 5337 chunk = state.decoder.write(chunk); 5338 skipAdd = !state.objectMode && chunk.length === 0; 5339 } 5340 5341 if (!addToFront) state.reading = false; 5342 5343 // Don't add to the buffer if we've decoded to an empty string chunk and 5344 // we're not in object mode 5345 if (!skipAdd) { 5346 // if we want the data now, just emit it. 5347 if (state.flowing && state.length === 0 && !state.sync) { 5348 stream.emit('data', chunk); 5349 stream.read(0); 5350 } else { 5351 // update the buffer info. 5352 state.length += state.objectMode ? 1 : chunk.length; 5353 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); 5354 5355 if (state.needReadable) emitReadable(stream); 5356 } 5357 } 5358 5359 maybeReadMore(stream, state); 5360 } 5361 } else if (!addToFront) { 5362 state.reading = false; 5363 } 5364 5365 return needMoreData(state); 5366 } 5367 5368 // if it's past the high water mark, we can push in some more. 5369 // Also, if we have no data yet, we can stand some 5370 // more bytes. This is to work around cases where hwm=0, 5371 // such as the repl. Also, if the push() triggered a 5372 // readable event, and the user called read(largeNumber) such that 5373 // needReadable was set, then we ought to push more, so that another 5374 // 'readable' event will be triggered. 5375 function needMoreData(state) { 5376 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); 5377 } 5378 5379 // backwards compatibility. 5380 Readable.prototype.setEncoding = function (enc) { 5381 this._readableState.decoder = new StringDecoder(enc); 5382 this._readableState.encoding = enc; 5383 return this; 5384 }; 5385 5386 // Don't raise the hwm > 8MB 5387 var MAX_HWM = 0x800000; 5388 function computeNewHighWaterMark(n) { 5389 if (n >= MAX_HWM) { 5390 n = MAX_HWM; 5391 } else { 5392 // Get the next highest power of 2 to prevent increasing hwm excessively in 5393 // tiny amounts 5394 n--; 5395 n |= n >>> 1; 5396 n |= n >>> 2; 5397 n |= n >>> 4; 5398 n |= n >>> 8; 5399 n |= n >>> 16; 5400 n++; 5401 } 5402 return n; 5403 } 5404 5405 // This function is designed to be inlinable, so please take care when making 5406 // changes to the function body. 5407 function howMuchToRead(n, state) { 5408 if (n <= 0 || state.length === 0 && state.ended) return 0; 5409 if (state.objectMode) return 1; 5410 if (n !== n) { 5411 // Only flow one buffer at a time 5412 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; 5413 } 5414 // If we're asking for more than the current hwm, then raise the hwm. 5415 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); 5416 if (n <= state.length) return n; 5417 // Don't have enough 5418 if (!state.ended) { 5419 state.needReadable = true; 5420 return 0; 5421 } 5422 return state.length; 5423 } 5424 5425 // you can override either this method, or the async _read(n) below. 5426 Readable.prototype.read = function (n) { 5427 debug('read', n); 5428 n = parseInt(n, 10); 5429 var state = this._readableState; 5430 var nOrig = n; 5431 5432 if (n !== 0) state.emittedReadable = false; 5433 5434 // if we're doing read(0) to trigger a readable event, but we 5435 // already have a bunch of data in the buffer, then just trigger 5436 // the 'readable' event and move on. 5437 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { 5438 debug('read: emitReadable', state.length, state.ended); 5439 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); 5440 return null; 5441 } 5442 5443 n = howMuchToRead(n, state); 5444 5445 // if we've ended, and we're now clear, then finish it up. 5446 if (n === 0 && state.ended) { 5447 if (state.length === 0) endReadable(this); 5448 return null; 5449 } 5450 5451 // All the actual chunk generation logic needs to be 5452 // *below* the call to _read. The reason is that in certain 5453 // synthetic stream cases, such as passthrough streams, _read 5454 // may be a completely synchronous operation which may change 5455 // the state of the read buffer, providing enough data when 5456 // before there was *not* enough. 5457 // 5458 // So, the steps are: 5459 // 1. Figure out what the state of things will be after we do 5460 // a read from the buffer. 5461 // 5462 // 2. If that resulting state will trigger a _read, then call _read. 5463 // Note that this may be asynchronous, or synchronous. Yes, it is 5464 // deeply ugly to write APIs this way, but that still doesn't mean 5465 // that the Readable class should behave improperly, as streams are 5466 // designed to be sync/async agnostic. 5467 // Take note if the _read call is sync or async (ie, if the read call 5468 // has returned yet), so that we know whether or not it's safe to emit 5469 // 'readable' etc. 5470 // 5471 // 3. Actually pull the requested chunks out of the buffer and return. 5472 5473 // if we need a readable event, then we need to do some reading. 5474 var doRead = state.needReadable; 5475 debug('need readable', doRead); 5476 5477 // if we currently have less than the highWaterMark, then also read some 5478 if (state.length === 0 || state.length - n < state.highWaterMark) { 5479 doRead = true; 5480 debug('length less than watermark', doRead); 5481 } 5482 5483 // however, if we've ended, then there's no point, and if we're already 5484 // reading, then it's unnecessary. 5485 if (state.ended || state.reading) { 5486 doRead = false; 5487 debug('reading or ended', doRead); 5488 } else if (doRead) { 5489 debug('do read'); 5490 state.reading = true; 5491 state.sync = true; 5492 // if the length is currently zero, then we *need* a readable event. 5493 if (state.length === 0) state.needReadable = true; 5494 // call internal read method 5495 this._read(state.highWaterMark); 5496 state.sync = false; 5497 // If _read pushed data synchronously, then `reading` will be false, 5498 // and we need to re-evaluate how much data we can return to the user. 5499 if (!state.reading) n = howMuchToRead(nOrig, state); 5500 } 5501 5502 var ret; 5503 if (n > 0) ret = fromList(n, state);else ret = null; 5504 5505 if (ret === null) { 5506 state.needReadable = true; 5507 n = 0; 5508 } else { 5509 state.length -= n; 5510 } 5511 5512 if (state.length === 0) { 5513 // If we have nothing in the buffer, then we want to know 5514 // as soon as we *do* get something into the buffer. 5515 if (!state.ended) state.needReadable = true; 5516 5517 // If we tried to read() past the EOF, then emit end on the next tick. 5518 if (nOrig !== n && state.ended) endReadable(this); 5519 } 5520 5521 if (ret !== null) this.emit('data', ret); 5522 5523 return ret; 5524 }; 5525 5526 function chunkInvalid(state, chunk) { 5527 var er = null; 5528 if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { 5529 er = new TypeError('Invalid non-string/buffer chunk'); 5530 } 5531 return er; 5532 } 5533 5534 function onEofChunk(stream, state) { 5535 if (state.ended) return; 5536 if (state.decoder) { 5537 var chunk = state.decoder.end(); 5538 if (chunk && chunk.length) { 5539 state.buffer.push(chunk); 5540 state.length += state.objectMode ? 1 : chunk.length; 5541 } 5542 } 5543 state.ended = true; 5544 5545 // emit 'readable' now to make sure it gets picked up. 5546 emitReadable(stream); 5547 } 5548 5549 // Don't emit readable right away in sync mode, because this can trigger 5550 // another read() call => stack overflow. This way, it might trigger 5551 // a nextTick recursion warning, but that's not so bad. 5552 function emitReadable(stream) { 5553 var state = stream._readableState; 5554 state.needReadable = false; 5555 if (!state.emittedReadable) { 5556 debug('emitReadable', state.flowing); 5557 state.emittedReadable = true; 5558 if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); 5559 } 5560 } 5561 5562 function emitReadable_(stream) { 5563 debug('emit readable'); 5564 stream.emit('readable'); 5565 flow(stream); 5566 } 5567 5568 // at this point, the user has presumably seen the 'readable' event, 5569 // and called read() to consume some data. that may have triggered 5570 // in turn another _read(n) call, in which case reading = true if 5571 // it's in progress. 5572 // However, if we're not ended, or reading, and the length < hwm, 5573 // then go ahead and try to read some more preemptively. 5574 function maybeReadMore(stream, state) { 5575 if (!state.readingMore) { 5576 state.readingMore = true; 5577 nextTick(maybeReadMore_, stream, state); 5578 } 5579 } 5580 5581 function maybeReadMore_(stream, state) { 5582 var len = state.length; 5583 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { 5584 debug('maybeReadMore read 0'); 5585 stream.read(0); 5586 if (len === state.length) 5587 // didn't get any data, stop spinning. 5588 break;else len = state.length; 5589 } 5590 state.readingMore = false; 5591 } 5592 5593 // abstract method. to be overridden in specific implementation classes. 5594 // call cb(er, data) where data is <= n in length. 5595 // for virtual (non-string, non-buffer) streams, "length" is somewhat 5596 // arbitrary, and perhaps not very meaningful. 5597 Readable.prototype._read = function (n) { 5598 this.emit('error', new Error('not implemented')); 5599 }; 5600 5601 Readable.prototype.pipe = function (dest, pipeOpts) { 5602 var src = this; 5603 var state = this._readableState; 5604 5605 switch (state.pipesCount) { 5606 case 0: 5607 state.pipes = dest; 5608 break; 5609 case 1: 5610 state.pipes = [state.pipes, dest]; 5611 break; 5612 default: 5613 state.pipes.push(dest); 5614 break; 5615 } 5616 state.pipesCount += 1; 5617 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); 5618 5619 var doEnd = (!pipeOpts || pipeOpts.end !== false); 5620 5621 var endFn = doEnd ? onend : cleanup; 5622 if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); 5623 5624 dest.on('unpipe', onunpipe); 5625 function onunpipe(readable) { 5626 debug('onunpipe'); 5627 if (readable === src) { 5628 cleanup(); 5629 } 5630 } 5631 5632 function onend() { 5633 debug('onend'); 5634 dest.end(); 5635 } 5636 5637 // when the dest drains, it reduces the awaitDrain counter 5638 // on the source. This would be more elegant with a .once() 5639 // handler in flow(), but adding and removing repeatedly is 5640 // too slow. 5641 var ondrain = pipeOnDrain(src); 5642 dest.on('drain', ondrain); 5643 5644 var cleanedUp = false; 5645 function cleanup() { 5646 debug('cleanup'); 5647 // cleanup event handlers once the pipe is broken 5648 dest.removeListener('close', onclose); 5649 dest.removeListener('finish', onfinish); 5650 dest.removeListener('drain', ondrain); 5651 dest.removeListener('error', onerror); 5652 dest.removeListener('unpipe', onunpipe); 5653 src.removeListener('end', onend); 5654 src.removeListener('end', cleanup); 5655 src.removeListener('data', ondata); 5656 5657 cleanedUp = true; 5658 5659 // if the reader is waiting for a drain event from this 5660 // specific writer, then it would cause it to never start 5661 // flowing again. 5662 // So, if this is awaiting a drain, then we just call it now. 5663 // If we don't know, then assume that we are waiting for one. 5664 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); 5665 } 5666 5667 // If the user pushes more data while we're writing to dest then we'll end up 5668 // in ondata again. However, we only want to increase awaitDrain once because 5669 // dest will only emit one 'drain' event for the multiple writes. 5670 // => Introduce a guard on increasing awaitDrain. 5671 var increasedAwaitDrain = false; 5672 src.on('data', ondata); 5673 function ondata(chunk) { 5674 debug('ondata'); 5675 increasedAwaitDrain = false; 5676 var ret = dest.write(chunk); 5677 if (false === ret && !increasedAwaitDrain) { 5678 // If the user unpiped during `dest.write()`, it is possible 5679 // to get stuck in a permanently paused state if that write 5680 // also returned false. 5681 // => Check whether `dest` is still a piping destination. 5682 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { 5683 debug('false write response, pause', src._readableState.awaitDrain); 5684 src._readableState.awaitDrain++; 5685 increasedAwaitDrain = true; 5686 } 5687 src.pause(); 5688 } 5689 } 5690 5691 // if the dest has an error, then stop piping into it. 5692 // however, don't suppress the throwing behavior for this. 5693 function onerror(er) { 5694 debug('onerror', er); 5695 unpipe(); 5696 dest.removeListener('error', onerror); 5697 if (listenerCount$1(dest, 'error') === 0) dest.emit('error', er); 5698 } 5699 5700 // Make sure our error handler is attached before userland ones. 5701 prependListener(dest, 'error', onerror); 5702 5703 // Both close and finish should trigger unpipe, but only once. 5704 function onclose() { 5705 dest.removeListener('finish', onfinish); 5706 unpipe(); 5707 } 5708 dest.once('close', onclose); 5709 function onfinish() { 5710 debug('onfinish'); 5711 dest.removeListener('close', onclose); 5712 unpipe(); 5713 } 5714 dest.once('finish', onfinish); 5715 5716 function unpipe() { 5717 debug('unpipe'); 5718 src.unpipe(dest); 5719 } 5720 5721 // tell the dest that it's being piped to 5722 dest.emit('pipe', src); 5723 5724 // start the flow if it hasn't been started already. 5725 if (!state.flowing) { 5726 debug('pipe resume'); 5727 src.resume(); 5728 } 5729 5730 return dest; 5731 }; 5732 5733 function pipeOnDrain(src) { 5734 return function () { 5735 var state = src._readableState; 5736 debug('pipeOnDrain', state.awaitDrain); 5737 if (state.awaitDrain) state.awaitDrain--; 5738 if (state.awaitDrain === 0 && src.listeners('data').length) { 5739 state.flowing = true; 5740 flow(src); 5741 } 5742 }; 5743 } 5744 5745 Readable.prototype.unpipe = function (dest) { 5746 var state = this._readableState; 5747 5748 // if we're not piping anywhere, then do nothing. 5749 if (state.pipesCount === 0) return this; 5750 5751 // just one destination. most common case. 5752 if (state.pipesCount === 1) { 5753 // passed in one, but it's not the right one. 5754 if (dest && dest !== state.pipes) return this; 5755 5756 if (!dest) dest = state.pipes; 5757 5758 // got a match. 5759 state.pipes = null; 5760 state.pipesCount = 0; 5761 state.flowing = false; 5762 if (dest) dest.emit('unpipe', this); 5763 return this; 5764 } 5765 5766 // slow case. multiple pipe destinations. 5767 5768 if (!dest) { 5769 // remove all. 5770 var dests = state.pipes; 5771 var len = state.pipesCount; 5772 state.pipes = null; 5773 state.pipesCount = 0; 5774 state.flowing = false; 5775 5776 for (var _i = 0; _i < len; _i++) { 5777 dests[_i].emit('unpipe', this); 5778 }return this; 5779 } 5780 5781 // try to find the right one. 5782 var i = indexOf(state.pipes, dest); 5783 if (i === -1) return this; 5784 5785 state.pipes.splice(i, 1); 5786 state.pipesCount -= 1; 5787 if (state.pipesCount === 1) state.pipes = state.pipes[0]; 5788 5789 dest.emit('unpipe', this); 5790 5791 return this; 5792 }; 5793 5794 // set up data events if they are asked for 5795 // Ensure readable listeners eventually get something 5796 Readable.prototype.on = function (ev, fn) { 5797 var res = EventEmitter.prototype.on.call(this, ev, fn); 5798 5799 if (ev === 'data') { 5800 // Start flowing on next tick if stream isn't explicitly paused 5801 if (this._readableState.flowing !== false) this.resume(); 5802 } else if (ev === 'readable') { 5803 var state = this._readableState; 5804 if (!state.endEmitted && !state.readableListening) { 5805 state.readableListening = state.needReadable = true; 5806 state.emittedReadable = false; 5807 if (!state.reading) { 5808 nextTick(nReadingNextTick, this); 5809 } else if (state.length) { 5810 emitReadable(this); 5811 } 5812 } 5813 } 5814 5815 return res; 5816 }; 5817 Readable.prototype.addListener = Readable.prototype.on; 5818 5819 function nReadingNextTick(self) { 5820 debug('readable nexttick read 0'); 5821 self.read(0); 5822 } 5823 5824 // pause() and resume() are remnants of the legacy readable stream API 5825 // If the user uses them, then switch into old mode. 5826 Readable.prototype.resume = function () { 5827 var state = this._readableState; 5828 if (!state.flowing) { 5829 debug('resume'); 5830 state.flowing = true; 5831 resume(this, state); 5832 } 5833 return this; 5834 }; 5835 5836 function resume(stream, state) { 5837 if (!state.resumeScheduled) { 5838 state.resumeScheduled = true; 5839 nextTick(resume_, stream, state); 5840 } 5841 } 5842 5843 function resume_(stream, state) { 5844 if (!state.reading) { 5845 debug('resume read 0'); 5846 stream.read(0); 5847 } 5848 5849 state.resumeScheduled = false; 5850 state.awaitDrain = 0; 5851 stream.emit('resume'); 5852 flow(stream); 5853 if (state.flowing && !state.reading) stream.read(0); 5854 } 5855 5856 Readable.prototype.pause = function () { 5857 debug('call pause flowing=%j', this._readableState.flowing); 5858 if (false !== this._readableState.flowing) { 5859 debug('pause'); 5860 this._readableState.flowing = false; 5861 this.emit('pause'); 5862 } 5863 return this; 5864 }; 5865 5866 function flow(stream) { 5867 var state = stream._readableState; 5868 debug('flow', state.flowing); 5869 while (state.flowing && stream.read() !== null) {} 5870 } 5871 5872 // wrap an old-style stream as the async data source. 5873 // This is *not* part of the readable stream interface. 5874 // It is an ugly unfortunate mess of history. 5875 Readable.prototype.wrap = function (stream) { 5876 var state = this._readableState; 5877 var paused = false; 5878 5879 var self = this; 5880 stream.on('end', function () { 5881 debug('wrapped end'); 5882 if (state.decoder && !state.ended) { 5883 var chunk = state.decoder.end(); 5884 if (chunk && chunk.length) self.push(chunk); 5885 } 5886 5887 self.push(null); 5888 }); 5889 5890 stream.on('data', function (chunk) { 5891 debug('wrapped data'); 5892 if (state.decoder) chunk = state.decoder.write(chunk); 5893 5894 // don't skip over falsy values in objectMode 5895 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; 5896 5897 var ret = self.push(chunk); 5898 if (!ret) { 5899 paused = true; 5900 stream.pause(); 5901 } 5902 }); 5903 5904 // proxy all the other methods. 5905 // important when wrapping filters and duplexes. 5906 for (var i in stream) { 5907 if (this[i] === undefined && typeof stream[i] === 'function') { 5908 this[i] = function (method) { 5909 return function () { 5910 return stream[method].apply(stream, arguments); 5911 }; 5912 }(i); 5913 } 5914 } 5915 5916 // proxy certain important events. 5917 var events = ['error', 'close', 'destroy', 'pause', 'resume']; 5918 forEach(events, function (ev) { 5919 stream.on(ev, self.emit.bind(self, ev)); 5920 }); 5921 5922 // when we try to consume some more bytes, simply unpause the 5923 // underlying stream. 5924 self._read = function (n) { 5925 debug('wrapped _read', n); 5926 if (paused) { 5927 paused = false; 5928 stream.resume(); 5929 } 5930 }; 5931 5932 return self; 5933 }; 5934 5935 // exposed for testing purposes only. 5936 Readable._fromList = fromList; 5937 5938 // Pluck off n bytes from an array of buffers. 5939 // Length is the combined lengths of all the buffers in the list. 5940 // This function is designed to be inlinable, so please take care when making 5941 // changes to the function body. 5942 function fromList(n, state) { 5943 // nothing buffered 5944 if (state.length === 0) return null; 5945 5946 var ret; 5947 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { 5948 // read it all, truncate the list 5949 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); 5950 state.buffer.clear(); 5951 } else { 5952 // read part of list 5953 ret = fromListPartial(n, state.buffer, state.decoder); 5954 } 5955 5956 return ret; 5957 } 5958 5959 // Extracts only enough buffered data to satisfy the amount requested. 5960 // This function is designed to be inlinable, so please take care when making 5961 // changes to the function body. 5962 function fromListPartial(n, list, hasStrings) { 5963 var ret; 5964 if (n < list.head.data.length) { 5965 // slice is the same for buffers and strings 5966 ret = list.head.data.slice(0, n); 5967 list.head.data = list.head.data.slice(n); 5968 } else if (n === list.head.data.length) { 5969 // first chunk is a perfect match 5970 ret = list.shift(); 5971 } else { 5972 // result spans more than one buffer 5973 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); 5974 } 5975 return ret; 5976 } 5977 5978 // Copies a specified amount of characters from the list of buffered data 5979 // chunks. 5980 // This function is designed to be inlinable, so please take care when making 5981 // changes to the function body. 5982 function copyFromBufferString(n, list) { 5983 var p = list.head; 5984 var c = 1; 5985 var ret = p.data; 5986 n -= ret.length; 5987 while (p = p.next) { 5988 var str = p.data; 5989 var nb = n > str.length ? str.length : n; 5990 if (nb === str.length) ret += str;else ret += str.slice(0, n); 5991 n -= nb; 5992 if (n === 0) { 5993 if (nb === str.length) { 5994 ++c; 5995 if (p.next) list.head = p.next;else list.head = list.tail = null; 5996 } else { 5997 list.head = p; 5998 p.data = str.slice(nb); 5999 } 6000 break; 6001 } 6002 ++c; 6003 } 6004 list.length -= c; 6005 return ret; 6006 } 6007 6008 // Copies a specified amount of bytes from the list of buffered data chunks. 6009 // This function is designed to be inlinable, so please take care when making 6010 // changes to the function body. 6011 function copyFromBuffer(n, list) { 6012 var ret = Buffer.allocUnsafe(n); 6013 var p = list.head; 6014 var c = 1; 6015 p.data.copy(ret); 6016 n -= p.data.length; 6017 while (p = p.next) { 6018 var buf = p.data; 6019 var nb = n > buf.length ? buf.length : n; 6020 buf.copy(ret, ret.length - n, 0, nb); 6021 n -= nb; 6022 if (n === 0) { 6023 if (nb === buf.length) { 6024 ++c; 6025 if (p.next) list.head = p.next;else list.head = list.tail = null; 6026 } else { 6027 list.head = p; 6028 p.data = buf.slice(nb); 6029 } 6030 break; 6031 } 6032 ++c; 6033 } 6034 list.length -= c; 6035 return ret; 6036 } 6037 6038 function endReadable(stream) { 6039 var state = stream._readableState; 6040 6041 // If we get here before consuming all the bytes, then that is a 6042 // bug in node. Should never happen. 6043 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); 6044 6045 if (!state.endEmitted) { 6046 state.ended = true; 6047 nextTick(endReadableNT, state, stream); 6048 } 6049 } 6050 6051 function endReadableNT(state, stream) { 6052 // Check that we didn't get one last unshift. 6053 if (!state.endEmitted && state.length === 0) { 6054 state.endEmitted = true; 6055 stream.readable = false; 6056 stream.emit('end'); 6057 } 6058 } 6059 6060 function forEach(xs, f) { 6061 for (var i = 0, l = xs.length; i < l; i++) { 6062 f(xs[i], i); 6063 } 6064 } 6065 6066 function indexOf(xs, x) { 6067 for (var i = 0, l = xs.length; i < l; i++) { 6068 if (xs[i] === x) return i; 6069 } 6070 return -1; 6071 } 6072 6073 // A bit simpler than readable streams. 6074 Writable.WritableState = WritableState; 6075 inherits$1(Writable, EventEmitter); 6076 6077 function nop() {} 6078 6079 function WriteReq(chunk, encoding, cb) { 6080 this.chunk = chunk; 6081 this.encoding = encoding; 6082 this.callback = cb; 6083 this.next = null; 6084 } 6085 6086 function WritableState(options, stream) { 6087 Object.defineProperty(this, 'buffer', { 6088 get: deprecate(function () { 6089 return this.getBuffer(); 6090 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') 6091 }); 6092 options = options || {}; 6093 6094 // object stream flag to indicate whether or not this stream 6095 // contains buffers or objects. 6096 this.objectMode = !!options.objectMode; 6097 6098 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; 6099 6100 // the point at which write() starts returning false 6101 // Note: 0 is a valid value, means that we always return false if 6102 // the entire buffer is not flushed immediately on write() 6103 var hwm = options.highWaterMark; 6104 var defaultHwm = this.objectMode ? 16 : 16 * 1024; 6105 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; 6106 6107 // cast to ints. 6108 this.highWaterMark = ~ ~this.highWaterMark; 6109 6110 this.needDrain = false; 6111 // at the start of calling end() 6112 this.ending = false; 6113 // when end() has been called, and returned 6114 this.ended = false; 6115 // when 'finish' is emitted 6116 this.finished = false; 6117 6118 // should we decode strings into buffers before passing to _write? 6119 // this is here so that some node-core streams can optimize string 6120 // handling at a lower level. 6121 var noDecode = options.decodeStrings === false; 6122 this.decodeStrings = !noDecode; 6123 6124 // Crypto is kind of old and crusty. Historically, its default string 6125 // encoding is 'binary' so we have to make this configurable. 6126 // Everything else in the universe uses 'utf8', though. 6127 this.defaultEncoding = options.defaultEncoding || 'utf8'; 6128 6129 // not an actual buffer we keep track of, but a measurement 6130 // of how much we're waiting to get pushed to some underlying 6131 // socket or file. 6132 this.length = 0; 6133 6134 // a flag to see when we're in the middle of a write. 6135 this.writing = false; 6136 6137 // when true all writes will be buffered until .uncork() call 6138 this.corked = 0; 6139 6140 // a flag to be able to tell if the onwrite cb is called immediately, 6141 // or on a later tick. We set this to true at first, because any 6142 // actions that shouldn't happen until "later" should generally also 6143 // not happen before the first write call. 6144 this.sync = true; 6145 6146 // a flag to know if we're processing previously buffered items, which 6147 // may call the _write() callback in the same tick, so that we don't 6148 // end up in an overlapped onwrite situation. 6149 this.bufferProcessing = false; 6150 6151 // the callback that's passed to _write(chunk,cb) 6152 this.onwrite = function (er) { 6153 onwrite(stream, er); 6154 }; 6155 6156 // the callback that the user supplies to write(chunk,encoding,cb) 6157 this.writecb = null; 6158 6159 // the amount that is being written when _write is called. 6160 this.writelen = 0; 6161 6162 this.bufferedRequest = null; 6163 this.lastBufferedRequest = null; 6164 6165 // number of pending user-supplied write callbacks 6166 // this must be 0 before 'finish' can be emitted 6167 this.pendingcb = 0; 6168 6169 // emit prefinish if the only thing we're waiting for is _write cbs 6170 // This is relevant for synchronous Transform streams 6171 this.prefinished = false; 6172 6173 // True if the error was already emitted and should not be thrown again 6174 this.errorEmitted = false; 6175 6176 // count buffered requests 6177 this.bufferedRequestCount = 0; 6178 6179 // allocate the first CorkedRequest, there is always 6180 // one allocated and free to use, and we maintain at most two 6181 this.corkedRequestsFree = new CorkedRequest(this); 6182 } 6183 6184 WritableState.prototype.getBuffer = function writableStateGetBuffer() { 6185 var current = this.bufferedRequest; 6186 var out = []; 6187 while (current) { 6188 out.push(current); 6189 current = current.next; 6190 } 6191 return out; 6192 }; 6193 function Writable(options) { 6194 6195 // Writable ctor is applied to Duplexes, though they're not 6196 // instanceof Writable, they're instanceof Readable. 6197 if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); 6198 6199 this._writableState = new WritableState(options, this); 6200 6201 // legacy. 6202 this.writable = true; 6203 6204 if (options) { 6205 if (typeof options.write === 'function') this._write = options.write; 6206 6207 if (typeof options.writev === 'function') this._writev = options.writev; 6208 } 6209 6210 EventEmitter.call(this); 6211 } 6212 6213 // Otherwise people can pipe Writable streams, which is just wrong. 6214 Writable.prototype.pipe = function () { 6215 this.emit('error', new Error('Cannot pipe, not readable')); 6216 }; 6217 6218 function writeAfterEnd(stream, cb) { 6219 var er = new Error('write after end'); 6220 // TODO: defer error events consistently everywhere, not just the cb 6221 stream.emit('error', er); 6222 nextTick(cb, er); 6223 } 6224 6225 // If we get something that is not a buffer, string, null, or undefined, 6226 // and we're not in objectMode, then that's an error. 6227 // Otherwise stream chunks are all considered to be of length=1, and the 6228 // watermarks determine how many objects to keep in the buffer, rather than 6229 // how many bytes or characters. 6230 function validChunk(stream, state, chunk, cb) { 6231 var valid = true; 6232 var er = false; 6233 // Always throw error if a null is written 6234 // if we are not in object mode then throw 6235 // if it is not a buffer, string, or undefined. 6236 if (chunk === null) { 6237 er = new TypeError('May not write null values to stream'); 6238 } else if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { 6239 er = new TypeError('Invalid non-string/buffer chunk'); 6240 } 6241 if (er) { 6242 stream.emit('error', er); 6243 nextTick(cb, er); 6244 valid = false; 6245 } 6246 return valid; 6247 } 6248 6249 Writable.prototype.write = function (chunk, encoding, cb) { 6250 var state = this._writableState; 6251 var ret = false; 6252 6253 if (typeof encoding === 'function') { 6254 cb = encoding; 6255 encoding = null; 6256 } 6257 6258 if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; 6259 6260 if (typeof cb !== 'function') cb = nop; 6261 6262 if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { 6263 state.pendingcb++; 6264 ret = writeOrBuffer(this, state, chunk, encoding, cb); 6265 } 6266 6267 return ret; 6268 }; 6269 6270 Writable.prototype.cork = function () { 6271 var state = this._writableState; 6272 6273 state.corked++; 6274 }; 6275 6276 Writable.prototype.uncork = function () { 6277 var state = this._writableState; 6278 6279 if (state.corked) { 6280 state.corked--; 6281 6282 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); 6283 } 6284 }; 6285 6286 Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { 6287 // node::ParseEncoding() requires lower case. 6288 if (typeof encoding === 'string') encoding = encoding.toLowerCase(); 6289 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); 6290 this._writableState.defaultEncoding = encoding; 6291 return this; 6292 }; 6293 6294 function decodeChunk(state, chunk, encoding) { 6295 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { 6296 chunk = Buffer$1.from(chunk, encoding); 6297 } 6298 return chunk; 6299 } 6300 6301 // if we're already writing something, then just put this 6302 // in the queue, and wait our turn. Otherwise, call _write 6303 // If we return false, then we need a drain event, so set that flag. 6304 function writeOrBuffer(stream, state, chunk, encoding, cb) { 6305 chunk = decodeChunk(state, chunk, encoding); 6306 6307 if (Buffer$1.isBuffer(chunk)) encoding = 'buffer'; 6308 var len = state.objectMode ? 1 : chunk.length; 6309 6310 state.length += len; 6311 6312 var ret = state.length < state.highWaterMark; 6313 // we must ensure that previous needDrain will not be reset to false. 6314 if (!ret) state.needDrain = true; 6315 6316 if (state.writing || state.corked) { 6317 var last = state.lastBufferedRequest; 6318 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); 6319 if (last) { 6320 last.next = state.lastBufferedRequest; 6321 } else { 6322 state.bufferedRequest = state.lastBufferedRequest; 6323 } 6324 state.bufferedRequestCount += 1; 6325 } else { 6326 doWrite(stream, state, false, len, chunk, encoding, cb); 6327 } 6328 6329 return ret; 6330 } 6331 6332 function doWrite(stream, state, writev, len, chunk, encoding, cb) { 6333 state.writelen = len; 6334 state.writecb = cb; 6335 state.writing = true; 6336 state.sync = true; 6337 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); 6338 state.sync = false; 6339 } 6340 6341 function onwriteError(stream, state, sync, er, cb) { 6342 --state.pendingcb; 6343 if (sync) nextTick(cb, er);else cb(er); 6344 6345 stream._writableState.errorEmitted = true; 6346 stream.emit('error', er); 6347 } 6348 6349 function onwriteStateUpdate(state) { 6350 state.writing = false; 6351 state.writecb = null; 6352 state.length -= state.writelen; 6353 state.writelen = 0; 6354 } 6355 6356 function onwrite(stream, er) { 6357 var state = stream._writableState; 6358 var sync = state.sync; 6359 var cb = state.writecb; 6360 6361 onwriteStateUpdate(state); 6362 6363 if (er) onwriteError(stream, state, sync, er, cb);else { 6364 // Check if we're actually ready to finish, but don't emit yet 6365 var finished = needFinish(state); 6366 6367 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { 6368 clearBuffer(stream, state); 6369 } 6370 6371 if (sync) { 6372 /*<replacement>*/ 6373 nextTick(afterWrite, stream, state, finished, cb); 6374 /*</replacement>*/ 6375 } else { 6376 afterWrite(stream, state, finished, cb); 6377 } 6378 } 6379 } 6380 6381 function afterWrite(stream, state, finished, cb) { 6382 if (!finished) onwriteDrain(stream, state); 6383 state.pendingcb--; 6384 cb(); 6385 finishMaybe(stream, state); 6386 } 6387 6388 // Must force callback to be called on nextTick, so that we don't 6389 // emit 'drain' before the write() consumer gets the 'false' return 6390 // value, and has a chance to attach a 'drain' listener. 6391 function onwriteDrain(stream, state) { 6392 if (state.length === 0 && state.needDrain) { 6393 state.needDrain = false; 6394 stream.emit('drain'); 6395 } 6396 } 6397 6398 // if there's something in the buffer waiting, then process it 6399 function clearBuffer(stream, state) { 6400 state.bufferProcessing = true; 6401 var entry = state.bufferedRequest; 6402 6403 if (stream._writev && entry && entry.next) { 6404 // Fast case, write everything using _writev() 6405 var l = state.bufferedRequestCount; 6406 var buffer = new Array(l); 6407 var holder = state.corkedRequestsFree; 6408 holder.entry = entry; 6409 6410 var count = 0; 6411 while (entry) { 6412 buffer[count] = entry; 6413 entry = entry.next; 6414 count += 1; 6415 } 6416 6417 doWrite(stream, state, true, state.length, buffer, '', holder.finish); 6418 6419 // doWrite is almost always async, defer these to save a bit of time 6420 // as the hot path ends with doWrite 6421 state.pendingcb++; 6422 state.lastBufferedRequest = null; 6423 if (holder.next) { 6424 state.corkedRequestsFree = holder.next; 6425 holder.next = null; 6426 } else { 6427 state.corkedRequestsFree = new CorkedRequest(state); 6428 } 6429 } else { 6430 // Slow case, write chunks one-by-one 6431 while (entry) { 6432 var chunk = entry.chunk; 6433 var encoding = entry.encoding; 6434 var cb = entry.callback; 6435 var len = state.objectMode ? 1 : chunk.length; 6436 6437 doWrite(stream, state, false, len, chunk, encoding, cb); 6438 entry = entry.next; 6439 // if we didn't call the onwrite immediately, then 6440 // it means that we need to wait until it does. 6441 // also, that means that the chunk and cb are currently 6442 // being processed, so move the buffer counter past them. 6443 if (state.writing) { 6444 break; 6445 } 6446 } 6447 6448 if (entry === null) state.lastBufferedRequest = null; 6449 } 6450 6451 state.bufferedRequestCount = 0; 6452 state.bufferedRequest = entry; 6453 state.bufferProcessing = false; 6454 } 6455 6456 Writable.prototype._write = function (chunk, encoding, cb) { 6457 cb(new Error('not implemented')); 6458 }; 6459 6460 Writable.prototype._writev = null; 6461 6462 Writable.prototype.end = function (chunk, encoding, cb) { 6463 var state = this._writableState; 6464 6465 if (typeof chunk === 'function') { 6466 cb = chunk; 6467 chunk = null; 6468 encoding = null; 6469 } else if (typeof encoding === 'function') { 6470 cb = encoding; 6471 encoding = null; 6472 } 6473 6474 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); 6475 6476 // .end() fully uncorks 6477 if (state.corked) { 6478 state.corked = 1; 6479 this.uncork(); 6480 } 6481 6482 // ignore unnecessary end() calls. 6483 if (!state.ending && !state.finished) endWritable(this, state, cb); 6484 }; 6485 6486 function needFinish(state) { 6487 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; 6488 } 6489 6490 function prefinish(stream, state) { 6491 if (!state.prefinished) { 6492 state.prefinished = true; 6493 stream.emit('prefinish'); 6494 } 6495 } 6496 6497 function finishMaybe(stream, state) { 6498 var need = needFinish(state); 6499 if (need) { 6500 if (state.pendingcb === 0) { 6501 prefinish(stream, state); 6502 state.finished = true; 6503 stream.emit('finish'); 6504 } else { 6505 prefinish(stream, state); 6506 } 6507 } 6508 return need; 6509 } 6510 6511 function endWritable(stream, state, cb) { 6512 state.ending = true; 6513 finishMaybe(stream, state); 6514 if (cb) { 6515 if (state.finished) nextTick(cb);else stream.once('finish', cb); 6516 } 6517 state.ended = true; 6518 stream.writable = false; 6519 } 6520 6521 // It seems a linked list but it is not 6522 // there will be only 2 of these for each stream 6523 function CorkedRequest(state) { 6524 var _this = this; 6525 6526 this.next = null; 6527 this.entry = null; 6528 6529 this.finish = function (err) { 6530 var entry = _this.entry; 6531 _this.entry = null; 6532 while (entry) { 6533 var cb = entry.callback; 6534 state.pendingcb--; 6535 cb(err); 6536 entry = entry.next; 6537 } 6538 if (state.corkedRequestsFree) { 6539 state.corkedRequestsFree.next = _this; 6540 } else { 6541 state.corkedRequestsFree = _this; 6542 } 6543 }; 6544 } 6545 6546 inherits$1(Duplex, Readable); 6547 6548 var keys = Object.keys(Writable.prototype); 6549 for (var v = 0; v < keys.length; v++) { 6550 var method = keys[v]; 6551 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; 6552 } 6553 function Duplex(options) { 6554 if (!(this instanceof Duplex)) return new Duplex(options); 6555 6556 Readable.call(this, options); 6557 Writable.call(this, options); 6558 6559 if (options && options.readable === false) this.readable = false; 6560 6561 if (options && options.writable === false) this.writable = false; 6562 6563 this.allowHalfOpen = true; 6564 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; 6565 6566 this.once('end', onend); 6567 } 6568 6569 // the no-half-open enforcer 6570 function onend() { 6571 // if we allow half-open state, or if the writable side ended, 6572 // then we're ok. 6573 if (this.allowHalfOpen || this._writableState.ended) return; 6574 6575 // no more data can be written. 6576 // But allow more writes to happen in this tick. 6577 nextTick(onEndNT, this); 6578 } 6579 6580 function onEndNT(self) { 6581 self.end(); 6582 } 6583 6584 // a transform stream is a readable/writable stream where you do 6585 inherits$1(Transform, Duplex); 6586 6587 function TransformState(stream) { 6588 this.afterTransform = function (er, data) { 6589 return afterTransform(stream, er, data); 6590 }; 6591 6592 this.needTransform = false; 6593 this.transforming = false; 6594 this.writecb = null; 6595 this.writechunk = null; 6596 this.writeencoding = null; 6597 } 6598 6599 function afterTransform(stream, er, data) { 6600 var ts = stream._transformState; 6601 ts.transforming = false; 6602 6603 var cb = ts.writecb; 6604 6605 if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); 6606 6607 ts.writechunk = null; 6608 ts.writecb = null; 6609 6610 if (data !== null && data !== undefined) stream.push(data); 6611 6612 cb(er); 6613 6614 var rs = stream._readableState; 6615 rs.reading = false; 6616 if (rs.needReadable || rs.length < rs.highWaterMark) { 6617 stream._read(rs.highWaterMark); 6618 } 6619 } 6620 function Transform(options) { 6621 if (!(this instanceof Transform)) return new Transform(options); 6622 6623 Duplex.call(this, options); 6624 6625 this._transformState = new TransformState(this); 6626 6627 // when the writable side finishes, then flush out anything remaining. 6628 var stream = this; 6629 6630 // start out asking for a readable event once data is transformed. 6631 this._readableState.needReadable = true; 6632 6633 // we have implemented the _read method, and done the other things 6634 // that Readable wants before the first _read call, so unset the 6635 // sync guard flag. 6636 this._readableState.sync = false; 6637 6638 if (options) { 6639 if (typeof options.transform === 'function') this._transform = options.transform; 6640 6641 if (typeof options.flush === 'function') this._flush = options.flush; 6642 } 6643 6644 this.once('prefinish', function () { 6645 if (typeof this._flush === 'function') this._flush(function (er) { 6646 done(stream, er); 6647 });else done(stream); 6648 }); 6649 } 6650 6651 Transform.prototype.push = function (chunk, encoding) { 6652 this._transformState.needTransform = false; 6653 return Duplex.prototype.push.call(this, chunk, encoding); 6654 }; 6655 6656 // This is the part where you do stuff! 6657 // override this function in implementation classes. 6658 // 'chunk' is an input chunk. 6659 // 6660 // Call `push(newChunk)` to pass along transformed output 6661 // to the readable side. You may call 'push' zero or more times. 6662 // 6663 // Call `cb(err)` when you are done with this chunk. If you pass 6664 // an error, then that'll put the hurt on the whole operation. If you 6665 // never call cb(), then you'll never get another chunk. 6666 Transform.prototype._transform = function (chunk, encoding, cb) { 6667 throw new Error('Not implemented'); 6668 }; 6669 6670 Transform.prototype._write = function (chunk, encoding, cb) { 6671 var ts = this._transformState; 6672 ts.writecb = cb; 6673 ts.writechunk = chunk; 6674 ts.writeencoding = encoding; 6675 if (!ts.transforming) { 6676 var rs = this._readableState; 6677 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); 6678 } 6679 }; 6680 6681 // Doesn't matter what the args are here. 6682 // _transform does all the work. 6683 // That we got here means that the readable side wants more data. 6684 Transform.prototype._read = function (n) { 6685 var ts = this._transformState; 6686 6687 if (ts.writechunk !== null && ts.writecb && !ts.transforming) { 6688 ts.transforming = true; 6689 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); 6690 } else { 6691 // mark that we need a transform, so that any data that comes in 6692 // will get processed, now that we've asked for it. 6693 ts.needTransform = true; 6694 } 6695 }; 6696 6697 function done(stream, er) { 6698 if (er) return stream.emit('error', er); 6699 6700 // if there's nothing in the write buffer, then that means 6701 // that nothing more will ever be provided 6702 var ws = stream._writableState; 6703 var ts = stream._transformState; 6704 6705 if (ws.length) throw new Error('Calling transform done when ws.length != 0'); 6706 6707 if (ts.transforming) throw new Error('Calling transform done when still transforming'); 6708 6709 return stream.push(null); 6710 } 6711 6712 inherits$1(PassThrough, Transform); 6713 function PassThrough(options) { 6714 if (!(this instanceof PassThrough)) return new PassThrough(options); 6715 6716 Transform.call(this, options); 6717 } 6718 6719 PassThrough.prototype._transform = function (chunk, encoding, cb) { 6720 cb(null, chunk); 6721 }; 6722 6723 inherits$1(Stream, EventEmitter); 6724 Stream.Readable = Readable; 6725 Stream.Writable = Writable; 6726 Stream.Duplex = Duplex; 6727 Stream.Transform = Transform; 6728 Stream.PassThrough = PassThrough; 6729 6730 // Backwards-compat with node 0.4.x 6731 Stream.Stream = Stream; 6732 6733 // old-style streams. Note that the pipe method (the only relevant 6734 // part of this class) is overridden in the Readable class. 6735 6736 function Stream() { 6737 EventEmitter.call(this); 6738 } 6739 6740 Stream.prototype.pipe = function(dest, options) { 6741 var source = this; 6742 6743 function ondata(chunk) { 6744 if (dest.writable) { 6745 if (false === dest.write(chunk) && source.pause) { 6746 source.pause(); 6747 } 6748 } 6749 } 6750 6751 source.on('data', ondata); 6752 6753 function ondrain() { 6754 if (source.readable && source.resume) { 6755 source.resume(); 6756 } 6757 } 6758 6759 dest.on('drain', ondrain); 6760 6761 // If the 'end' option is not supplied, dest.end() will be called when 6762 // source gets the 'end' or 'close' events. Only dest.end() once. 6763 if (!dest._isStdio && (!options || options.end !== false)) { 6764 source.on('end', onend); 6765 source.on('close', onclose); 6766 } 6767 6768 var didOnEnd = false; 6769 function onend() { 6770 if (didOnEnd) return; 6771 didOnEnd = true; 6772 6773 dest.end(); 6774 } 6775 6776 6777 function onclose() { 6778 if (didOnEnd) return; 6779 didOnEnd = true; 6780 6781 if (typeof dest.destroy === 'function') dest.destroy(); 6782 } 6783 6784 // don't leave dangling pipes when there are errors. 6785 function onerror(er) { 6786 cleanup(); 6787 if (EventEmitter.listenerCount(this, 'error') === 0) { 6788 throw er; // Unhandled stream error in pipe. 6789 } 6790 } 6791 6792 source.on('error', onerror); 6793 dest.on('error', onerror); 6794 6795 // remove all the event listeners that were added. 6796 function cleanup() { 6797 source.removeListener('data', ondata); 6798 dest.removeListener('drain', ondrain); 6799 6800 source.removeListener('end', onend); 6801 source.removeListener('close', onclose); 6802 6803 source.removeListener('error', onerror); 6804 dest.removeListener('error', onerror); 6805 6806 source.removeListener('end', cleanup); 6807 source.removeListener('close', cleanup); 6808 6809 dest.removeListener('close', cleanup); 6810 } 6811 6812 source.on('end', cleanup); 6813 source.on('close', cleanup); 6814 6815 dest.on('close', cleanup); 6816 6817 dest.emit('pipe', source); 6818 6819 // Allow for unix-like usage: A.pipe(B).pipe(C) 6820 return dest; 6821 }; 6822 6823 var fs = {}; 6824 6825 /* 6826 PDFAbstractReference - abstract class for PDF reference 6827 */ 6828 6829 class PDFAbstractReference { 6830 toString() { 6831 throw new Error('Must be implemented by subclasses'); 6832 } 6833 } 6834 6835 /* 6836 PDFNameTree - represents a name tree object 6837 */ 6838 6839 class PDFNameTree { 6840 6841 constructor() { 6842 this._items = {}; 6843 } 6844 6845 add(key, val) { 6846 return this._items[key] = val; 6847 } 6848 6849 get(key) { 6850 return this._items[key]; 6851 } 6852 6853 toString() { 6854 // Needs to be sorted by key 6855 const sortedKeys = (Object.keys(this._items)).sort((a, b) => a.localeCompare(b)); 6856 6857 const out = ['<<']; 6858 if (sortedKeys.length > 1) { 6859 const first = sortedKeys[0], last = sortedKeys[sortedKeys.length - 1]; 6860 out.push(` /Limits ${PDFObject.convert([new String(first), new String(last)])}`); 6861 } 6862 out.push(' /Names ['); 6863 for (let key of sortedKeys) { 6864 out.push(` ${PDFObject.convert(new String(key))} ${PDFObject.convert(this._items[key])}`); 6865 } 6866 out.push(']'); 6867 out.push('>>'); 6868 return out.join('\n'); 6869 } 6870 } 6871 6872 const pad = (str, length) => (Array(length + 1).join('0') + str).slice(-length); 6873 6874 const escapableRe = /[\n\r\t\b\f\(\)\\]/g; 6875 const escapable = { 6876 '\n': '\\n', 6877 '\r': '\\r', 6878 '\t': '\\t', 6879 '\b': '\\b', 6880 '\f': '\\f', 6881 '\\': '\\\\', 6882 '(': '\\(', 6883 ')': '\\)' 6884 }; 6885 6886 // Convert little endian UTF-16 to big endian 6887 const swapBytes = function(buff) { 6888 const l = buff.length; 6889 if (l & 0x01) { 6890 throw new Error('Buffer length must be even'); 6891 } else { 6892 for (let i = 0, end = l - 1; i < end; i += 2) { 6893 const a = buff[i]; 6894 buff[i] = buff[i + 1]; 6895 buff[i + 1] = a; 6896 } 6897 } 6898 6899 return buff; 6900 }; 6901 6902 class PDFObject { 6903 static convert(object, encryptFn = null) { 6904 // String literals are converted to the PDF name type 6905 if (typeof object === 'string') { 6906 return `/${object}`; 6907 6908 // String objects are converted to PDF strings (UTF-16) 6909 } else if (object instanceof String) { 6910 let string = object; 6911 // Detect if this is a unicode string 6912 let isUnicode = false; 6913 for (let i = 0, end = string.length; i < end; i++) { 6914 if (string.charCodeAt(i) > 0x7f) { 6915 isUnicode = true; 6916 break; 6917 } 6918 } 6919 6920 // If so, encode it as big endian UTF-16 6921 let stringBuffer; 6922 if (isUnicode) { 6923 stringBuffer = swapBytes(Buffer.from(`\ufeff${string}`, 'utf16le')); 6924 } else { 6925 stringBuffer = Buffer.from(string.valueOf(), 'ascii'); 6926 } 6927 6928 // Encrypt the string when necessary 6929 if (encryptFn) { 6930 string = encryptFn(stringBuffer).toString('binary'); 6931 } else { 6932 string = stringBuffer.toString('binary'); 6933 } 6934 6935 // Escape characters as required by the spec 6936 string = string.replace(escapableRe, c => escapable[c]); 6937 6938 return `(${string})`; 6939 6940 // Buffers are converted to PDF hex strings 6941 } else if (isBuffer(object)) { 6942 return `<${object.toString('hex')}>`; 6943 } else if (object instanceof PDFAbstractReference || object instanceof PDFNameTree) { 6944 return object.toString(); 6945 } else if (object instanceof Date) { 6946 let string = 6947 `D:${pad(object.getUTCFullYear(), 4)}` + 6948 pad(object.getUTCMonth() + 1, 2) + 6949 pad(object.getUTCDate(), 2) + 6950 pad(object.getUTCHours(), 2) + 6951 pad(object.getUTCMinutes(), 2) + 6952 pad(object.getUTCSeconds(), 2) + 6953 'Z'; 6954 6955 // Encrypt the string when necessary 6956 if (encryptFn) { 6957 string = encryptFn(new Buffer(string, 'ascii')).toString('binary'); 6958 6959 // Escape characters as required by the spec 6960 string = string.replace(escapableRe, c => escapable[c]); 6961 } 6962 6963 return `(${string})`; 6964 } else if (Array.isArray(object)) { 6965 const items = object.map(e => PDFObject.convert(e, encryptFn)).join(' '); 6966 return `[${items}]`; 6967 } else if ({}.toString.call(object) === '[object Object]') { 6968 const out = ['<<']; 6969 for (let key in object) { 6970 const val = object[key]; 6971 out.push(`/${key} ${PDFObject.convert(val, encryptFn)}`); 6972 } 6973 6974 out.push('>>'); 6975 return out.join('\n'); 6976 } else if (typeof object === 'number') { 6977 return PDFObject.number(object); 6978 } else { 6979 return `${object}`; 6980 } 6981 } 6982 6983 static number(n) { 6984 if (n > -1e21 && n < 1e21) { 6985 return Math.round(n * 1e6) / 1e6; 6986 } 6987 6988 throw new Error(`unsupported number: ${n}`); 6989 } 6990 } 6991 6992 // shim for using process in browser 6993 // based off https://github.com/defunctzombie/node-process/blob/master/browser.js 6994 6995 function defaultSetTimout$1() { 6996 throw new Error('setTimeout has not been defined'); 6997 } 6998 function defaultClearTimeout$1 () { 6999 throw new Error('clearTimeout has not been defined'); 7000 } 7001 var cachedSetTimeout$1 = defaultSetTimout$1; 7002 var cachedClearTimeout$1 = defaultClearTimeout$1; 7003 if (typeof global$1$1.setTimeout === 'function') { 7004 cachedSetTimeout$1 = setTimeout; 7005 } 7006 if (typeof global$1$1.clearTimeout === 'function') { 7007 cachedClearTimeout$1 = clearTimeout; 7008 } 7009 7010 function runTimeout$1(fun) { 7011 if (cachedSetTimeout$1 === setTimeout) { 7012 //normal enviroments in sane situations 7013 return setTimeout(fun, 0); 7014 } 7015 // if setTimeout wasn't available but was latter defined 7016 if ((cachedSetTimeout$1 === defaultSetTimout$1 || !cachedSetTimeout$1) && setTimeout) { 7017 cachedSetTimeout$1 = setTimeout; 7018 return setTimeout(fun, 0); 7019 } 7020 try { 7021 // when when somebody has screwed with setTimeout but no I.E. maddness 7022 return cachedSetTimeout$1(fun, 0); 7023 } catch(e){ 7024 try { 7025 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally 7026 return cachedSetTimeout$1.call(null, fun, 0); 7027 } catch(e){ 7028 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error 7029 return cachedSetTimeout$1.call(this, fun, 0); 7030 } 7031 } 7032 7033 7034 } 7035 function runClearTimeout$1(marker) { 7036 if (cachedClearTimeout$1 === clearTimeout) { 7037 //normal enviroments in sane situations 7038 return clearTimeout(marker); 7039 } 7040 // if clearTimeout wasn't available but was latter defined 7041 if ((cachedClearTimeout$1 === defaultClearTimeout$1 || !cachedClearTimeout$1) && clearTimeout) { 7042 cachedClearTimeout$1 = clearTimeout; 7043 return clearTimeout(marker); 7044 } 7045 try { 7046 // when when somebody has screwed with setTimeout but no I.E. maddness 7047 return cachedClearTimeout$1(marker); 7048 } catch (e){ 7049 try { 7050 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally 7051 return cachedClearTimeout$1.call(null, marker); 7052 } catch (e){ 7053 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. 7054 // Some versions of I.E. have different rules for clearTimeout vs setTimeout 7055 return cachedClearTimeout$1.call(this, marker); 7056 } 7057 } 7058 7059 7060 7061 } 7062 var queue$1 = []; 7063 var draining$1 = false; 7064 var currentQueue$1; 7065 var queueIndex$1 = -1; 7066 7067 function cleanUpNextTick$1() { 7068 if (!draining$1 || !currentQueue$1) { 7069 return; 7070 } 7071 draining$1 = false; 7072 if (currentQueue$1.length) { 7073 queue$1 = currentQueue$1.concat(queue$1); 7074 } else { 7075 queueIndex$1 = -1; 7076 } 7077 if (queue$1.length) { 7078 drainQueue$1(); 7079 } 7080 } 7081 7082 function drainQueue$1() { 7083 if (draining$1) { 7084 return; 7085 } 7086 var timeout = runTimeout$1(cleanUpNextTick$1); 7087 draining$1 = true; 7088 7089 var len = queue$1.length; 7090 while(len) { 7091 currentQueue$1 = queue$1; 7092 queue$1 = []; 7093 while (++queueIndex$1 < len) { 7094 if (currentQueue$1) { 7095 currentQueue$1[queueIndex$1].run(); 7096 } 7097 } 7098 queueIndex$1 = -1; 7099 len = queue$1.length; 7100 } 7101 currentQueue$1 = null; 7102 draining$1 = false; 7103 runClearTimeout$1(timeout); 7104 } 7105 function nextTick$1(fun) { 7106 var args = new Array(arguments.length - 1); 7107 if (arguments.length > 1) { 7108 for (var i = 1; i < arguments.length; i++) { 7109 args[i - 1] = arguments[i]; 7110 } 7111 } 7112 queue$1.push(new Item$1(fun, args)); 7113 if (queue$1.length === 1 && !draining$1) { 7114 runTimeout$1(drainQueue$1); 7115 } 7116 } 7117 // v8 likes predictible objects 7118 function Item$1(fun, array) { 7119 this.fun = fun; 7120 this.array = array; 7121 } 7122 Item$1.prototype.run = function () { 7123 this.fun.apply(null, this.array); 7124 }; 7125 7126 // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js 7127 var performance$1 = global$1$1.performance || {}; 7128 var performanceNow$1 = 7129 performance$1.now || 7130 performance$1.mozNow || 7131 performance$1.msNow || 7132 performance$1.oNow || 7133 performance$1.webkitNow || 7134 function(){ return (new Date()).getTime() }; 7135 7136 var msg = { 7137 2: 'need dictionary', /* Z_NEED_DICT 2 */ 7138 1: 'stream end', /* Z_STREAM_END 1 */ 7139 0: '', /* Z_OK 0 */ 7140 '-1': 'file error', /* Z_ERRNO (-1) */ 7141 '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ 7142 '-3': 'data error', /* Z_DATA_ERROR (-3) */ 7143 '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ 7144 '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ 7145 '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ 7146 }; 7147 7148 function ZStream() { 7149 /* next input byte */ 7150 this.input = null; // JS specific, because we have no pointers 7151 this.next_in = 0; 7152 /* number of bytes available at input */ 7153 this.avail_in = 0; 7154 /* total number of input bytes read so far */ 7155 this.total_in = 0; 7156 /* next output byte should be put there */ 7157 this.output = null; // JS specific, because we have no pointers 7158 this.next_out = 0; 7159 /* remaining free space at output */ 7160 this.avail_out = 0; 7161 /* total number of bytes output so far */ 7162 this.total_out = 0; 7163 /* last error message, NULL if no error */ 7164 this.msg = ''/*Z_NULL*/; 7165 /* not visible by applications */ 7166 this.state = null; 7167 /* best guess about the data type: binary or text */ 7168 this.data_type = 2/*Z_UNKNOWN*/; 7169 /* adler32 value of the uncompressed data */ 7170 this.adler = 0; 7171 } 7172 7173 function arraySet(dest, src, src_offs, len, dest_offs) { 7174 if (src.subarray && dest.subarray) { 7175 dest.set(src.subarray(src_offs, src_offs + len), dest_offs); 7176 return; 7177 } 7178 // Fallback to ordinary array 7179 for (var i = 0; i < len; i++) { 7180 dest[dest_offs + i] = src[src_offs + i]; 7181 } 7182 } 7183 7184 7185 var Buf8 = Uint8Array; 7186 var Buf16 = Uint16Array; 7187 var Buf32 = Int32Array; 7188 // Enable/Disable typed arrays use, for testing 7189 // 7190 7191 /* Public constants ==========================================================*/ 7192 /* ===========================================================================*/ 7193 7194 7195 //var Z_FILTERED = 1; 7196 //var Z_HUFFMAN_ONLY = 2; 7197 //var Z_RLE = 3; 7198 var Z_FIXED = 4; 7199 //var Z_DEFAULT_STRATEGY = 0; 7200 7201 /* Possible values of the data_type field (though see inflate()) */ 7202 var Z_BINARY = 0; 7203 var Z_TEXT = 1; 7204 //var Z_ASCII = 1; // = Z_TEXT 7205 var Z_UNKNOWN = 2; 7206 7207 /*============================================================================*/ 7208 7209 7210 function zero(buf) { 7211 var len = buf.length; 7212 while (--len >= 0) { 7213 buf[len] = 0; 7214 } 7215 } 7216 7217 // From zutil.h 7218 7219 var STORED_BLOCK = 0; 7220 var STATIC_TREES = 1; 7221 var DYN_TREES = 2; 7222 /* The three kinds of block type */ 7223 7224 var MIN_MATCH = 3; 7225 var MAX_MATCH = 258; 7226 /* The minimum and maximum match lengths */ 7227 7228 // From deflate.h 7229 /* =========================================================================== 7230 * Internal compression state. 7231 */ 7232 7233 var LENGTH_CODES = 29; 7234 /* number of length codes, not counting the special END_BLOCK code */ 7235 7236 var LITERALS = 256; 7237 /* number of literal bytes 0..255 */ 7238 7239 var L_CODES = LITERALS + 1 + LENGTH_CODES; 7240 /* number of Literal or Length codes, including the END_BLOCK code */ 7241 7242 var D_CODES = 30; 7243 /* number of distance codes */ 7244 7245 var BL_CODES = 19; 7246 /* number of codes used to transfer the bit lengths */ 7247 7248 var HEAP_SIZE = 2 * L_CODES + 1; 7249 /* maximum heap size */ 7250 7251 var MAX_BITS = 15; 7252 /* All codes must not exceed MAX_BITS bits */ 7253 7254 var Buf_size = 16; 7255 /* size of bit buffer in bi_buf */ 7256 7257 7258 /* =========================================================================== 7259 * Constants 7260 */ 7261 7262 var MAX_BL_BITS = 7; 7263 /* Bit length codes must not exceed MAX_BL_BITS bits */ 7264 7265 var END_BLOCK = 256; 7266 /* end of block literal code */ 7267 7268 var REP_3_6 = 16; 7269 /* repeat previous bit length 3-6 times (2 bits of repeat count) */ 7270 7271 var REPZ_3_10 = 17; 7272 /* repeat a zero length 3-10 times (3 bits of repeat count) */ 7273 7274 var REPZ_11_138 = 18; 7275 /* repeat a zero length 11-138 times (7 bits of repeat count) */ 7276 7277 /* eslint-disable comma-spacing,array-bracket-spacing */ 7278 var extra_lbits = /* extra bits for each length code */ [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]; 7279 7280 var extra_dbits = /* extra bits for each distance code */ [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]; 7281 7282 var extra_blbits = /* extra bits for each bit length code */ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]; 7283 7284 var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; 7285 /* eslint-enable comma-spacing,array-bracket-spacing */ 7286 7287 /* The lengths of the bit length codes are sent in order of decreasing 7288 * probability, to avoid transmitting the lengths for unused bit length codes. 7289 */ 7290 7291 /* =========================================================================== 7292 * Local data. These are initialized only once. 7293 */ 7294 7295 // We pre-fill arrays with 0 to avoid uninitialized gaps 7296 7297 var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ 7298 7299 // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 7300 var static_ltree = new Array((L_CODES + 2) * 2); 7301 zero(static_ltree); 7302 /* The static literal tree. Since the bit lengths are imposed, there is no 7303 * need for the L_CODES extra codes used during heap construction. However 7304 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init 7305 * below). 7306 */ 7307 7308 var static_dtree = new Array(D_CODES * 2); 7309 zero(static_dtree); 7310 /* The static distance tree. (Actually a trivial tree since all codes use 7311 * 5 bits.) 7312 */ 7313 7314 var _dist_code = new Array(DIST_CODE_LEN); 7315 zero(_dist_code); 7316 /* Distance codes. The first 256 values correspond to the distances 7317 * 3 .. 258, the last 256 values correspond to the top 8 bits of 7318 * the 15 bit distances. 7319 */ 7320 7321 var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); 7322 zero(_length_code); 7323 /* length code for each normalized match length (0 == MIN_MATCH) */ 7324 7325 var base_length = new Array(LENGTH_CODES); 7326 zero(base_length); 7327 /* First normalized length for each code (0 = MIN_MATCH) */ 7328 7329 var base_dist = new Array(D_CODES); 7330 zero(base_dist); 7331 /* First normalized distance for each code (0 = distance of 1) */ 7332 7333 7334 function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { 7335 7336 this.static_tree = static_tree; /* static tree or NULL */ 7337 this.extra_bits = extra_bits; /* extra bits for each code or NULL */ 7338 this.extra_base = extra_base; /* base index for extra_bits */ 7339 this.elems = elems; /* max number of elements in the tree */ 7340 this.max_length = max_length; /* max bit length for the codes */ 7341 7342 // show if `static_tree` has data or dummy - needed for monomorphic objects 7343 this.has_stree = static_tree && static_tree.length; 7344 } 7345 7346 7347 var static_l_desc; 7348 var static_d_desc; 7349 var static_bl_desc; 7350 7351 7352 function TreeDesc(dyn_tree, stat_desc) { 7353 this.dyn_tree = dyn_tree; /* the dynamic tree */ 7354 this.max_code = 0; /* largest code with non zero frequency */ 7355 this.stat_desc = stat_desc; /* the corresponding static tree */ 7356 } 7357 7358 7359 7360 function d_code(dist) { 7361 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; 7362 } 7363 7364 7365 /* =========================================================================== 7366 * Output a short LSB first on the stream. 7367 * IN assertion: there is enough room in pendingBuf. 7368 */ 7369 function put_short(s, w) { 7370 // put_byte(s, (uch)((w) & 0xff)); 7371 // put_byte(s, (uch)((ush)(w) >> 8)); 7372 s.pending_buf[s.pending++] = (w) & 0xff; 7373 s.pending_buf[s.pending++] = (w >>> 8) & 0xff; 7374 } 7375 7376 7377 /* =========================================================================== 7378 * Send a value on a given number of bits. 7379 * IN assertion: length <= 16 and value fits in length bits. 7380 */ 7381 function send_bits(s, value, length) { 7382 if (s.bi_valid > (Buf_size - length)) { 7383 s.bi_buf |= (value << s.bi_valid) & 0xffff; 7384 put_short(s, s.bi_buf); 7385 s.bi_buf = value >> (Buf_size - s.bi_valid); 7386 s.bi_valid += length - Buf_size; 7387 } else { 7388 s.bi_buf |= (value << s.bi_valid) & 0xffff; 7389 s.bi_valid += length; 7390 } 7391 } 7392 7393 7394 function send_code(s, c, tree) { 7395 send_bits(s, tree[c * 2] /*.Code*/ , tree[c * 2 + 1] /*.Len*/ ); 7396 } 7397 7398 7399 /* =========================================================================== 7400 * Reverse the first len bits of a code, using straightforward code (a faster 7401 * method would use a table) 7402 * IN assertion: 1 <= len <= 15 7403 */ 7404 function bi_reverse(code, len) { 7405 var res = 0; 7406 do { 7407 res |= code & 1; 7408 code >>>= 1; 7409 res <<= 1; 7410 } while (--len > 0); 7411 return res >>> 1; 7412 } 7413 7414 7415 /* =========================================================================== 7416 * Flush the bit buffer, keeping at most 7 bits in it. 7417 */ 7418 function bi_flush(s) { 7419 if (s.bi_valid === 16) { 7420 put_short(s, s.bi_buf); 7421 s.bi_buf = 0; 7422 s.bi_valid = 0; 7423 7424 } else if (s.bi_valid >= 8) { 7425 s.pending_buf[s.pending++] = s.bi_buf & 0xff; 7426 s.bi_buf >>= 8; 7427 s.bi_valid -= 8; 7428 } 7429 } 7430 7431 7432 /* =========================================================================== 7433 * Compute the optimal bit lengths for a tree and update the total bit length 7434 * for the current block. 7435 * IN assertion: the fields freq and dad are set, heap[heap_max] and 7436 * above are the tree nodes sorted by increasing frequency. 7437 * OUT assertions: the field len is set to the optimal bit length, the 7438 * array bl_count contains the frequencies for each bit length. 7439 * The length opt_len is updated; static_len is also updated if stree is 7440 * not null. 7441 */ 7442 function gen_bitlen(s, desc) { 7443 // deflate_state *s; 7444 // tree_desc *desc; /* the tree descriptor */ 7445 var tree = desc.dyn_tree; 7446 var max_code = desc.max_code; 7447 var stree = desc.stat_desc.static_tree; 7448 var has_stree = desc.stat_desc.has_stree; 7449 var extra = desc.stat_desc.extra_bits; 7450 var base = desc.stat_desc.extra_base; 7451 var max_length = desc.stat_desc.max_length; 7452 var h; /* heap index */ 7453 var n, m; /* iterate over the tree elements */ 7454 var bits; /* bit length */ 7455 var xbits; /* extra bits */ 7456 var f; /* frequency */ 7457 var overflow = 0; /* number of elements with bit length too large */ 7458 7459 for (bits = 0; bits <= MAX_BITS; bits++) { 7460 s.bl_count[bits] = 0; 7461 } 7462 7463 /* In a first pass, compute the optimal bit lengths (which may 7464 * overflow in the case of the bit length tree). 7465 */ 7466 tree[s.heap[s.heap_max] * 2 + 1] /*.Len*/ = 0; /* root of the heap */ 7467 7468 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { 7469 n = s.heap[h]; 7470 bits = tree[tree[n * 2 + 1] /*.Dad*/ * 2 + 1] /*.Len*/ + 1; 7471 if (bits > max_length) { 7472 bits = max_length; 7473 overflow++; 7474 } 7475 tree[n * 2 + 1] /*.Len*/ = bits; 7476 /* We overwrite tree[n].Dad which is no longer needed */ 7477 7478 if (n > max_code) { 7479 continue; 7480 } /* not a leaf node */ 7481 7482 s.bl_count[bits]++; 7483 xbits = 0; 7484 if (n >= base) { 7485 xbits = extra[n - base]; 7486 } 7487 f = tree[n * 2] /*.Freq*/ ; 7488 s.opt_len += f * (bits + xbits); 7489 if (has_stree) { 7490 s.static_len += f * (stree[n * 2 + 1] /*.Len*/ + xbits); 7491 } 7492 } 7493 if (overflow === 0) { 7494 return; 7495 } 7496 7497 // Trace((stderr,"\nbit length overflow\n")); 7498 /* This happens for example on obj2 and pic of the Calgary corpus */ 7499 7500 /* Find the first bit length which could increase: */ 7501 do { 7502 bits = max_length - 1; 7503 while (s.bl_count[bits] === 0) { 7504 bits--; 7505 } 7506 s.bl_count[bits]--; /* move one leaf down the tree */ 7507 s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ 7508 s.bl_count[max_length]--; 7509 /* The brother of the overflow item also moves one step up, 7510 * but this does not affect bl_count[max_length] 7511 */ 7512 overflow -= 2; 7513 } while (overflow > 0); 7514 7515 /* Now recompute all bit lengths, scanning in increasing frequency. 7516 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all 7517 * lengths instead of fixing only the wrong ones. This idea is taken 7518 * from 'ar' written by Haruhiko Okumura.) 7519 */ 7520 for (bits = max_length; bits !== 0; bits--) { 7521 n = s.bl_count[bits]; 7522 while (n !== 0) { 7523 m = s.heap[--h]; 7524 if (m > max_code) { 7525 continue; 7526 } 7527 if (tree[m * 2 + 1] /*.Len*/ !== bits) { 7528 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); 7529 s.opt_len += (bits - tree[m * 2 + 1] /*.Len*/ ) * tree[m * 2] /*.Freq*/ ; 7530 tree[m * 2 + 1] /*.Len*/ = bits; 7531 } 7532 n--; 7533 } 7534 } 7535 } 7536 7537 7538 /* =========================================================================== 7539 * Generate the codes for a given tree and bit counts (which need not be 7540 * optimal). 7541 * IN assertion: the array bl_count contains the bit length statistics for 7542 * the given tree and the field len is set for all tree elements. 7543 * OUT assertion: the field code is set for all tree elements of non 7544 * zero code length. 7545 */ 7546 function gen_codes(tree, max_code, bl_count) { 7547 // ct_data *tree; /* the tree to decorate */ 7548 // int max_code; /* largest code with non zero frequency */ 7549 // ushf *bl_count; /* number of codes at each bit length */ 7550 7551 var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ 7552 var code = 0; /* running code value */ 7553 var bits; /* bit index */ 7554 var n; /* code index */ 7555 7556 /* The distribution counts are first used to generate the code values 7557 * without bit reversal. 7558 */ 7559 for (bits = 1; bits <= MAX_BITS; bits++) { 7560 next_code[bits] = code = (code + bl_count[bits - 1]) << 1; 7561 } 7562 /* Check that the bit counts in bl_count are consistent. The last code 7563 * must be all ones. 7564 */ 7565 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, 7566 // "inconsistent bit counts"); 7567 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); 7568 7569 for (n = 0; n <= max_code; n++) { 7570 var len = tree[n * 2 + 1] /*.Len*/ ; 7571 if (len === 0) { 7572 continue; 7573 } 7574 /* Now reverse the bits */ 7575 tree[n * 2] /*.Code*/ = bi_reverse(next_code[len]++, len); 7576 7577 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", 7578 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); 7579 } 7580 } 7581 7582 7583 /* =========================================================================== 7584 * Initialize the various 'constant' tables. 7585 */ 7586 function tr_static_init() { 7587 var n; /* iterates over tree elements */ 7588 var bits; /* bit counter */ 7589 var length; /* length value */ 7590 var code; /* code value */ 7591 var dist; /* distance index */ 7592 var bl_count = new Array(MAX_BITS + 1); 7593 /* number of codes at each bit length for an optimal tree */ 7594 7595 // do check in _tr_init() 7596 //if (static_init_done) return; 7597 7598 /* For some embedded targets, global variables are not initialized: */ 7599 /*#ifdef NO_INIT_GLOBAL_POINTERS 7600 static_l_desc.static_tree = static_ltree; 7601 static_l_desc.extra_bits = extra_lbits; 7602 static_d_desc.static_tree = static_dtree; 7603 static_d_desc.extra_bits = extra_dbits; 7604 static_bl_desc.extra_bits = extra_blbits; 7605 #endif*/ 7606 7607 /* Initialize the mapping length (0..255) -> length code (0..28) */ 7608 length = 0; 7609 for (code = 0; code < LENGTH_CODES - 1; code++) { 7610 base_length[code] = length; 7611 for (n = 0; n < (1 << extra_lbits[code]); n++) { 7612 _length_code[length++] = code; 7613 } 7614 } 7615 //Assert (length == 256, "tr_static_init: length != 256"); 7616 /* Note that the length 255 (match length 258) can be represented 7617 * in two different ways: code 284 + 5 bits or code 285, so we 7618 * overwrite length_code[255] to use the best encoding: 7619 */ 7620 _length_code[length - 1] = code; 7621 7622 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ 7623 dist = 0; 7624 for (code = 0; code < 16; code++) { 7625 base_dist[code] = dist; 7626 for (n = 0; n < (1 << extra_dbits[code]); n++) { 7627 _dist_code[dist++] = code; 7628 } 7629 } 7630 //Assert (dist == 256, "tr_static_init: dist != 256"); 7631 dist >>= 7; /* from now on, all distances are divided by 128 */ 7632 for (; code < D_CODES; code++) { 7633 base_dist[code] = dist << 7; 7634 for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { 7635 _dist_code[256 + dist++] = code; 7636 } 7637 } 7638 //Assert (dist == 256, "tr_static_init: 256+dist != 512"); 7639 7640 /* Construct the codes of the static literal tree */ 7641 for (bits = 0; bits <= MAX_BITS; bits++) { 7642 bl_count[bits] = 0; 7643 } 7644 7645 n = 0; 7646 while (n <= 143) { 7647 static_ltree[n * 2 + 1] /*.Len*/ = 8; 7648 n++; 7649 bl_count[8]++; 7650 } 7651 while (n <= 255) { 7652 static_ltree[n * 2 + 1] /*.Len*/ = 9; 7653 n++; 7654 bl_count[9]++; 7655 } 7656 while (n <= 279) { 7657 static_ltree[n * 2 + 1] /*.Len*/ = 7; 7658 n++; 7659 bl_count[7]++; 7660 } 7661 while (n <= 287) { 7662 static_ltree[n * 2 + 1] /*.Len*/ = 8; 7663 n++; 7664 bl_count[8]++; 7665 } 7666 /* Codes 286 and 287 do not exist, but we must include them in the 7667 * tree construction to get a canonical Huffman tree (longest code 7668 * all ones) 7669 */ 7670 gen_codes(static_ltree, L_CODES + 1, bl_count); 7671 7672 /* The static distance tree is trivial: */ 7673 for (n = 0; n < D_CODES; n++) { 7674 static_dtree[n * 2 + 1] /*.Len*/ = 5; 7675 static_dtree[n * 2] /*.Code*/ = bi_reverse(n, 5); 7676 } 7677 7678 // Now data ready and we can init static trees 7679 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); 7680 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); 7681 static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); 7682 7683 //static_init_done = true; 7684 } 7685 7686 7687 /* =========================================================================== 7688 * Initialize a new block. 7689 */ 7690 function init_block(s) { 7691 var n; /* iterates over tree elements */ 7692 7693 /* Initialize the trees. */ 7694 for (n = 0; n < L_CODES; n++) { 7695 s.dyn_ltree[n * 2] /*.Freq*/ = 0; 7696 } 7697 for (n = 0; n < D_CODES; n++) { 7698 s.dyn_dtree[n * 2] /*.Freq*/ = 0; 7699 } 7700 for (n = 0; n < BL_CODES; n++) { 7701 s.bl_tree[n * 2] /*.Freq*/ = 0; 7702 } 7703 7704 s.dyn_ltree[END_BLOCK * 2] /*.Freq*/ = 1; 7705 s.opt_len = s.static_len = 0; 7706 s.last_lit = s.matches = 0; 7707 } 7708 7709 7710 /* =========================================================================== 7711 * Flush the bit buffer and align the output on a byte boundary 7712 */ 7713 function bi_windup(s) { 7714 if (s.bi_valid > 8) { 7715 put_short(s, s.bi_buf); 7716 } else if (s.bi_valid > 0) { 7717 //put_byte(s, (Byte)s->bi_buf); 7718 s.pending_buf[s.pending++] = s.bi_buf; 7719 } 7720 s.bi_buf = 0; 7721 s.bi_valid = 0; 7722 } 7723 7724 /* =========================================================================== 7725 * Copy a stored block, storing first the length and its 7726 * one's complement if requested. 7727 */ 7728 function copy_block(s, buf, len, header) { 7729 //DeflateState *s; 7730 //charf *buf; /* the input data */ 7731 //unsigned len; /* its length */ 7732 //int header; /* true if block header must be written */ 7733 7734 bi_windup(s); /* align on byte boundary */ 7735 7736 if (header) { 7737 put_short(s, len); 7738 put_short(s, ~len); 7739 } 7740 // while (len--) { 7741 // put_byte(s, *buf++); 7742 // } 7743 arraySet(s.pending_buf, s.window, buf, len, s.pending); 7744 s.pending += len; 7745 } 7746 7747 /* =========================================================================== 7748 * Compares to subtrees, using the tree depth as tie breaker when 7749 * the subtrees have equal frequency. This minimizes the worst case length. 7750 */ 7751 function smaller(tree, n, m, depth) { 7752 var _n2 = n * 2; 7753 var _m2 = m * 2; 7754 return (tree[_n2] /*.Freq*/ < tree[_m2] /*.Freq*/ || 7755 (tree[_n2] /*.Freq*/ === tree[_m2] /*.Freq*/ && depth[n] <= depth[m])); 7756 } 7757 7758 /* =========================================================================== 7759 * Restore the heap property by moving down the tree starting at node k, 7760 * exchanging a node with the smallest of its two sons if necessary, stopping 7761 * when the heap property is re-established (each father smaller than its 7762 * two sons). 7763 */ 7764 function pqdownheap(s, tree, k) 7765 // deflate_state *s; 7766 // ct_data *tree; /* the tree to restore */ 7767 // int k; /* node to move down */ 7768 { 7769 var v = s.heap[k]; 7770 var j = k << 1; /* left son of k */ 7771 while (j <= s.heap_len) { 7772 /* Set j to the smallest of the two sons: */ 7773 if (j < s.heap_len && 7774 smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { 7775 j++; 7776 } 7777 /* Exit if v is smaller than both sons */ 7778 if (smaller(tree, v, s.heap[j], s.depth)) { 7779 break; 7780 } 7781 7782 /* Exchange v with the smallest son */ 7783 s.heap[k] = s.heap[j]; 7784 k = j; 7785 7786 /* And continue down the tree, setting j to the left son of k */ 7787 j <<= 1; 7788 } 7789 s.heap[k] = v; 7790 } 7791 7792 7793 // inlined manually 7794 // var SMALLEST = 1; 7795 7796 /* =========================================================================== 7797 * Send the block data compressed using the given Huffman trees 7798 */ 7799 function compress_block(s, ltree, dtree) 7800 // deflate_state *s; 7801 // const ct_data *ltree; /* literal tree */ 7802 // const ct_data *dtree; /* distance tree */ 7803 { 7804 var dist; /* distance of matched string */ 7805 var lc; /* match length or unmatched char (if dist == 0) */ 7806 var lx = 0; /* running index in l_buf */ 7807 var code; /* the code to send */ 7808 var extra; /* number of extra bits to send */ 7809 7810 if (s.last_lit !== 0) { 7811 do { 7812 dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); 7813 lc = s.pending_buf[s.l_buf + lx]; 7814 lx++; 7815 7816 if (dist === 0) { 7817 send_code(s, lc, ltree); /* send a literal byte */ 7818 //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); 7819 } else { 7820 /* Here, lc is the match length - MIN_MATCH */ 7821 code = _length_code[lc]; 7822 send_code(s, code + LITERALS + 1, ltree); /* send the length code */ 7823 extra = extra_lbits[code]; 7824 if (extra !== 0) { 7825 lc -= base_length[code]; 7826 send_bits(s, lc, extra); /* send the extra length bits */ 7827 } 7828 dist--; /* dist is now the match distance - 1 */ 7829 code = d_code(dist); 7830 //Assert (code < D_CODES, "bad d_code"); 7831 7832 send_code(s, code, dtree); /* send the distance code */ 7833 extra = extra_dbits[code]; 7834 if (extra !== 0) { 7835 dist -= base_dist[code]; 7836 send_bits(s, dist, extra); /* send the extra distance bits */ 7837 } 7838 } /* literal or match pair ? */ 7839 7840 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ 7841 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, 7842 // "pendingBuf overflow"); 7843 7844 } while (lx < s.last_lit); 7845 } 7846 7847 send_code(s, END_BLOCK, ltree); 7848 } 7849 7850 7851 /* =========================================================================== 7852 * Construct one Huffman tree and assigns the code bit strings and lengths. 7853 * Update the total bit length for the current block. 7854 * IN assertion: the field freq is set for all tree elements. 7855 * OUT assertions: the fields len and code are set to the optimal bit length 7856 * and corresponding code. The length opt_len is updated; static_len is 7857 * also updated if stree is not null. The field max_code is set. 7858 */ 7859 function build_tree(s, desc) 7860 // deflate_state *s; 7861 // tree_desc *desc; /* the tree descriptor */ 7862 { 7863 var tree = desc.dyn_tree; 7864 var stree = desc.stat_desc.static_tree; 7865 var has_stree = desc.stat_desc.has_stree; 7866 var elems = desc.stat_desc.elems; 7867 var n, m; /* iterate over heap elements */ 7868 var max_code = -1; /* largest code with non zero frequency */ 7869 var node; /* new node being created */ 7870 7871 /* Construct the initial heap, with least frequent element in 7872 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. 7873 * heap[0] is not used. 7874 */ 7875 s.heap_len = 0; 7876 s.heap_max = HEAP_SIZE; 7877 7878 for (n = 0; n < elems; n++) { 7879 if (tree[n * 2] /*.Freq*/ !== 0) { 7880 s.heap[++s.heap_len] = max_code = n; 7881 s.depth[n] = 0; 7882 7883 } else { 7884 tree[n * 2 + 1] /*.Len*/ = 0; 7885 } 7886 } 7887 7888 /* The pkzip format requires that at least one distance code exists, 7889 * and that at least one bit should be sent even if there is only one 7890 * possible code. So to avoid special checks later on we force at least 7891 * two codes of non zero frequency. 7892 */ 7893 while (s.heap_len < 2) { 7894 node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); 7895 tree[node * 2] /*.Freq*/ = 1; 7896 s.depth[node] = 0; 7897 s.opt_len--; 7898 7899 if (has_stree) { 7900 s.static_len -= stree[node * 2 + 1] /*.Len*/ ; 7901 } 7902 /* node is 0 or 1 so it does not have extra bits */ 7903 } 7904 desc.max_code = max_code; 7905 7906 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, 7907 * establish sub-heaps of increasing lengths: 7908 */ 7909 for (n = (s.heap_len >> 1 /*int /2*/ ); n >= 1; n--) { 7910 pqdownheap(s, tree, n); 7911 } 7912 7913 /* Construct the Huffman tree by repeatedly combining the least two 7914 * frequent nodes. 7915 */ 7916 node = elems; /* next internal node of the tree */ 7917 do { 7918 //pqremove(s, tree, n); /* n = node of least frequency */ 7919 /*** pqremove ***/ 7920 n = s.heap[1 /*SMALLEST*/ ]; 7921 s.heap[1 /*SMALLEST*/ ] = s.heap[s.heap_len--]; 7922 pqdownheap(s, tree, 1 /*SMALLEST*/ ); 7923 /***/ 7924 7925 m = s.heap[1 /*SMALLEST*/ ]; /* m = node of next least frequency */ 7926 7927 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ 7928 s.heap[--s.heap_max] = m; 7929 7930 /* Create a new node father of n and m */ 7931 tree[node * 2] /*.Freq*/ = tree[n * 2] /*.Freq*/ + tree[m * 2] /*.Freq*/ ; 7932 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; 7933 tree[n * 2 + 1] /*.Dad*/ = tree[m * 2 + 1] /*.Dad*/ = node; 7934 7935 /* and insert the new node in the heap */ 7936 s.heap[1 /*SMALLEST*/ ] = node++; 7937 pqdownheap(s, tree, 1 /*SMALLEST*/ ); 7938 7939 } while (s.heap_len >= 2); 7940 7941 s.heap[--s.heap_max] = s.heap[1 /*SMALLEST*/ ]; 7942 7943 /* At this point, the fields freq and dad are set. We can now 7944 * generate the bit lengths. 7945 */ 7946 gen_bitlen(s, desc); 7947 7948 /* The field len is now set, we can generate the bit codes */ 7949 gen_codes(tree, max_code, s.bl_count); 7950 } 7951 7952 7953 /* =========================================================================== 7954 * Scan a literal or distance tree to determine the frequencies of the codes 7955 * in the bit length tree. 7956 */ 7957 function scan_tree(s, tree, max_code) 7958 // deflate_state *s; 7959 // ct_data *tree; /* the tree to be scanned */ 7960 // int max_code; /* and its largest code of non zero frequency */ 7961 { 7962 var n; /* iterates over all tree elements */ 7963 var prevlen = -1; /* last emitted length */ 7964 var curlen; /* length of current code */ 7965 7966 var nextlen = tree[0 * 2 + 1] /*.Len*/ ; /* length of next code */ 7967 7968 var count = 0; /* repeat count of the current code */ 7969 var max_count = 7; /* max repeat count */ 7970 var min_count = 4; /* min repeat count */ 7971 7972 if (nextlen === 0) { 7973 max_count = 138; 7974 min_count = 3; 7975 } 7976 tree[(max_code + 1) * 2 + 1] /*.Len*/ = 0xffff; /* guard */ 7977 7978 for (n = 0; n <= max_code; n++) { 7979 curlen = nextlen; 7980 nextlen = tree[(n + 1) * 2 + 1] /*.Len*/ ; 7981 7982 if (++count < max_count && curlen === nextlen) { 7983 continue; 7984 7985 } else if (count < min_count) { 7986 s.bl_tree[curlen * 2] /*.Freq*/ += count; 7987 7988 } else if (curlen !== 0) { 7989 7990 if (curlen !== prevlen) { 7991 s.bl_tree[curlen * 2] /*.Freq*/ ++; 7992 } 7993 s.bl_tree[REP_3_6 * 2] /*.Freq*/ ++; 7994 7995 } else if (count <= 10) { 7996 s.bl_tree[REPZ_3_10 * 2] /*.Freq*/ ++; 7997 7998 } else { 7999 s.bl_tree[REPZ_11_138 * 2] /*.Freq*/ ++; 8000 } 8001 8002 count = 0; 8003 prevlen = curlen; 8004 8005 if (nextlen === 0) { 8006 max_count = 138; 8007 min_count = 3; 8008 8009 } else if (curlen === nextlen) { 8010 max_count = 6; 8011 min_count = 3; 8012 8013 } else { 8014 max_count = 7; 8015 min_count = 4; 8016 } 8017 } 8018 } 8019 8020 8021 /* =========================================================================== 8022 * Send a literal or distance tree in compressed form, using the codes in 8023 * bl_tree. 8024 */ 8025 function send_tree(s, tree, max_code) 8026 // deflate_state *s; 8027 // ct_data *tree; /* the tree to be scanned */ 8028 // int max_code; /* and its largest code of non zero frequency */ 8029 { 8030 var n; /* iterates over all tree elements */ 8031 var prevlen = -1; /* last emitted length */ 8032 var curlen; /* length of current code */ 8033 8034 var nextlen = tree[0 * 2 + 1] /*.Len*/ ; /* length of next code */ 8035 8036 var count = 0; /* repeat count of the current code */ 8037 var max_count = 7; /* max repeat count */ 8038 var min_count = 4; /* min repeat count */ 8039 8040 /* tree[max_code+1].Len = -1; */ 8041 /* guard already set */ 8042 if (nextlen === 0) { 8043 max_count = 138; 8044 min_count = 3; 8045 } 8046 8047 for (n = 0; n <= max_code; n++) { 8048 curlen = nextlen; 8049 nextlen = tree[(n + 1) * 2 + 1] /*.Len*/ ; 8050 8051 if (++count < max_count && curlen === nextlen) { 8052 continue; 8053 8054 } else if (count < min_count) { 8055 do { 8056 send_code(s, curlen, s.bl_tree); 8057 } while (--count !== 0); 8058 8059 } else if (curlen !== 0) { 8060 if (curlen !== prevlen) { 8061 send_code(s, curlen, s.bl_tree); 8062 count--; 8063 } 8064 //Assert(count >= 3 && count <= 6, " 3_6?"); 8065 send_code(s, REP_3_6, s.bl_tree); 8066 send_bits(s, count - 3, 2); 8067 8068 } else if (count <= 10) { 8069 send_code(s, REPZ_3_10, s.bl_tree); 8070 send_bits(s, count - 3, 3); 8071 8072 } else { 8073 send_code(s, REPZ_11_138, s.bl_tree); 8074 send_bits(s, count - 11, 7); 8075 } 8076 8077 count = 0; 8078 prevlen = curlen; 8079 if (nextlen === 0) { 8080 max_count = 138; 8081 min_count = 3; 8082 8083 } else if (curlen === nextlen) { 8084 max_count = 6; 8085 min_count = 3; 8086 8087 } else { 8088 max_count = 7; 8089 min_count = 4; 8090 } 8091 } 8092 } 8093 8094 8095 /* =========================================================================== 8096 * Construct the Huffman tree for the bit lengths and return the index in 8097 * bl_order of the last bit length code to send. 8098 */ 8099 function build_bl_tree(s) { 8100 var max_blindex; /* index of last bit length code of non zero freq */ 8101 8102 /* Determine the bit length frequencies for literal and distance trees */ 8103 scan_tree(s, s.dyn_ltree, s.l_desc.max_code); 8104 scan_tree(s, s.dyn_dtree, s.d_desc.max_code); 8105 8106 /* Build the bit length tree: */ 8107 build_tree(s, s.bl_desc); 8108 /* opt_len now includes the length of the tree representations, except 8109 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. 8110 */ 8111 8112 /* Determine the number of bit length codes to send. The pkzip format 8113 * requires that at least 4 bit length codes be sent. (appnote.txt says 8114 * 3 but the actual value used is 4.) 8115 */ 8116 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { 8117 if (s.bl_tree[bl_order[max_blindex] * 2 + 1] /*.Len*/ !== 0) { 8118 break; 8119 } 8120 } 8121 /* Update opt_len to include the bit length tree and counts */ 8122 s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; 8123 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", 8124 // s->opt_len, s->static_len)); 8125 8126 return max_blindex; 8127 } 8128 8129 8130 /* =========================================================================== 8131 * Send the header for a block using dynamic Huffman trees: the counts, the 8132 * lengths of the bit length codes, the literal tree and the distance tree. 8133 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. 8134 */ 8135 function send_all_trees(s, lcodes, dcodes, blcodes) 8136 // deflate_state *s; 8137 // int lcodes, dcodes, blcodes; /* number of codes for each tree */ 8138 { 8139 var rank; /* index in bl_order */ 8140 8141 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); 8142 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, 8143 // "too many codes"); 8144 //Tracev((stderr, "\nbl counts: ")); 8145 send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ 8146 send_bits(s, dcodes - 1, 5); 8147 send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ 8148 for (rank = 0; rank < blcodes; rank++) { 8149 //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); 8150 send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1] /*.Len*/ , 3); 8151 } 8152 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); 8153 8154 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ 8155 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); 8156 8157 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ 8158 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); 8159 } 8160 8161 8162 /* =========================================================================== 8163 * Check if the data type is TEXT or BINARY, using the following algorithm: 8164 * - TEXT if the two conditions below are satisfied: 8165 * a) There are no non-portable control characters belonging to the 8166 * "black list" (0..6, 14..25, 28..31). 8167 * b) There is at least one printable character belonging to the 8168 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). 8169 * - BINARY otherwise. 8170 * - The following partially-portable control characters form a 8171 * "gray list" that is ignored in this detection algorithm: 8172 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). 8173 * IN assertion: the fields Freq of dyn_ltree are set. 8174 */ 8175 function detect_data_type(s) { 8176 /* black_mask is the bit mask of black-listed bytes 8177 * set bits 0..6, 14..25, and 28..31 8178 * 0xf3ffc07f = binary 11110011111111111100000001111111 8179 */ 8180 var black_mask = 0xf3ffc07f; 8181 var n; 8182 8183 /* Check for non-textual ("black-listed") bytes. */ 8184 for (n = 0; n <= 31; n++, black_mask >>>= 1) { 8185 if ((black_mask & 1) && (s.dyn_ltree[n * 2] /*.Freq*/ !== 0)) { 8186 return Z_BINARY; 8187 } 8188 } 8189 8190 /* Check for textual ("white-listed") bytes. */ 8191 if (s.dyn_ltree[9 * 2] /*.Freq*/ !== 0 || s.dyn_ltree[10 * 2] /*.Freq*/ !== 0 || 8192 s.dyn_ltree[13 * 2] /*.Freq*/ !== 0) { 8193 return Z_TEXT; 8194 } 8195 for (n = 32; n < LITERALS; n++) { 8196 if (s.dyn_ltree[n * 2] /*.Freq*/ !== 0) { 8197 return Z_TEXT; 8198 } 8199 } 8200 8201 /* There are no "black-listed" or "white-listed" bytes: 8202 * this stream either is empty or has tolerated ("gray-listed") bytes only. 8203 */ 8204 return Z_BINARY; 8205 } 8206 8207 8208 var static_init_done = false; 8209 8210 /* =========================================================================== 8211 * Initialize the tree data structures for a new zlib stream. 8212 */ 8213 function _tr_init(s) { 8214 8215 if (!static_init_done) { 8216 tr_static_init(); 8217 static_init_done = true; 8218 } 8219 8220 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); 8221 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); 8222 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); 8223 8224 s.bi_buf = 0; 8225 s.bi_valid = 0; 8226 8227 /* Initialize the first block of the first file: */ 8228 init_block(s); 8229 } 8230 8231 8232 /* =========================================================================== 8233 * Send a stored block 8234 */ 8235 function _tr_stored_block(s, buf, stored_len, last) 8236 //DeflateState *s; 8237 //charf *buf; /* input block */ 8238 //ulg stored_len; /* length of input block */ 8239 //int last; /* one if this is the last block for a file */ 8240 { 8241 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ 8242 copy_block(s, buf, stored_len, true); /* with header */ 8243 } 8244 8245 8246 /* =========================================================================== 8247 * Send one empty static block to give enough lookahead for inflate. 8248 * This takes 10 bits, of which 7 may remain in the bit buffer. 8249 */ 8250 function _tr_align(s) { 8251 send_bits(s, STATIC_TREES << 1, 3); 8252 send_code(s, END_BLOCK, static_ltree); 8253 bi_flush(s); 8254 } 8255 8256 8257 /* =========================================================================== 8258 * Determine the best encoding for the current block: dynamic trees, static 8259 * trees or store, and output the encoded block to the zip file. 8260 */ 8261 function _tr_flush_block(s, buf, stored_len, last) 8262 //DeflateState *s; 8263 //charf *buf; /* input block, or NULL if too old */ 8264 //ulg stored_len; /* length of input block */ 8265 //int last; /* one if this is the last block for a file */ 8266 { 8267 var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ 8268 var max_blindex = 0; /* index of last bit length code of non zero freq */ 8269 8270 /* Build the Huffman trees unless a stored block is forced */ 8271 if (s.level > 0) { 8272 8273 /* Check if the file is binary or text */ 8274 if (s.strm.data_type === Z_UNKNOWN) { 8275 s.strm.data_type = detect_data_type(s); 8276 } 8277 8278 /* Construct the literal and distance trees */ 8279 build_tree(s, s.l_desc); 8280 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, 8281 // s->static_len)); 8282 8283 build_tree(s, s.d_desc); 8284 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, 8285 // s->static_len)); 8286 /* At this point, opt_len and static_len are the total bit lengths of 8287 * the compressed block data, excluding the tree representations. 8288 */ 8289 8290 /* Build the bit length tree for the above two trees, and get the index 8291 * in bl_order of the last bit length code to send. 8292 */ 8293 max_blindex = build_bl_tree(s); 8294 8295 /* Determine the best encoding. Compute the block lengths in bytes. */ 8296 opt_lenb = (s.opt_len + 3 + 7) >>> 3; 8297 static_lenb = (s.static_len + 3 + 7) >>> 3; 8298 8299 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", 8300 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, 8301 // s->last_lit)); 8302 8303 if (static_lenb <= opt_lenb) { 8304 opt_lenb = static_lenb; 8305 } 8306 8307 } else { 8308 // Assert(buf != (char*)0, "lost buf"); 8309 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ 8310 } 8311 8312 if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { 8313 /* 4: two words for the lengths */ 8314 8315 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. 8316 * Otherwise we can't have processed more than WSIZE input bytes since 8317 * the last block flush, because compression would have been 8318 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to 8319 * transform a block into a stored block. 8320 */ 8321 _tr_stored_block(s, buf, stored_len, last); 8322 8323 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { 8324 8325 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); 8326 compress_block(s, static_ltree, static_dtree); 8327 8328 } else { 8329 send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); 8330 send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); 8331 compress_block(s, s.dyn_ltree, s.dyn_dtree); 8332 } 8333 // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); 8334 /* The above check is made mod 2^32, for files larger than 512 MB 8335 * and uLong implemented on 32 bits. 8336 */ 8337 init_block(s); 8338 8339 if (last) { 8340 bi_windup(s); 8341 } 8342 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, 8343 // s->compressed_len-7*last)); 8344 } 8345 8346 /* =========================================================================== 8347 * Save the match info and tally the frequency counts. Return true if 8348 * the current block must be flushed. 8349 */ 8350 function _tr_tally(s, dist, lc) 8351 // deflate_state *s; 8352 // unsigned dist; /* distance of matched string */ 8353 // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ 8354 { 8355 //var out_length, in_length, dcode; 8356 8357 s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; 8358 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; 8359 8360 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; 8361 s.last_lit++; 8362 8363 if (dist === 0) { 8364 /* lc is the unmatched char */ 8365 s.dyn_ltree[lc * 2] /*.Freq*/ ++; 8366 } else { 8367 s.matches++; 8368 /* Here, lc is the match length - MIN_MATCH */ 8369 dist--; /* dist = match distance - 1 */ 8370 //Assert((ush)dist < (ush)MAX_DIST(s) && 8371 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && 8372 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); 8373 8374 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2] /*.Freq*/ ++; 8375 s.dyn_dtree[d_code(dist) * 2] /*.Freq*/ ++; 8376 } 8377 8378 // (!) This block is disabled in zlib defailts, 8379 // don't enable it for binary compatibility 8380 8381 //#ifdef TRUNCATE_BLOCK 8382 // /* Try to guess if it is profitable to stop the current block here */ 8383 // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { 8384 // /* Compute an upper bound for the compressed length */ 8385 // out_length = s.last_lit*8; 8386 // in_length = s.strstart - s.block_start; 8387 // 8388 // for (dcode = 0; dcode < D_CODES; dcode++) { 8389 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); 8390 // } 8391 // out_length >>>= 3; 8392 // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", 8393 // // s->last_lit, in_length, out_length, 8394 // // 100L - out_length*100L/in_length)); 8395 // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { 8396 // return true; 8397 // } 8398 // } 8399 //#endif 8400 8401 return (s.last_lit === s.lit_bufsize - 1); 8402 /* We avoid equality with lit_bufsize because of wraparound at 64K 8403 * on 16 bit machines and because stored blocks are restricted to 8404 * 64K-1 bytes. 8405 */ 8406 } 8407 8408 // Note: adler32 takes 12% for level 0 and 2% for level 6. 8409 // It doesn't worth to make additional optimizationa as in original. 8410 // Small size is preferable. 8411 8412 function adler32(adler, buf, len, pos) { 8413 var s1 = (adler & 0xffff) |0, 8414 s2 = ((adler >>> 16) & 0xffff) |0, 8415 n = 0; 8416 8417 while (len !== 0) { 8418 // Set limit ~ twice less than 5552, to keep 8419 // s2 in 31-bits, because we force signed ints. 8420 // in other case %= will fail. 8421 n = len > 2000 ? 2000 : len; 8422 len -= n; 8423 8424 do { 8425 s1 = (s1 + buf[pos++]) |0; 8426 s2 = (s2 + s1) |0; 8427 } while (--n); 8428 8429 s1 %= 65521; 8430 s2 %= 65521; 8431 } 8432 8433 return (s1 | (s2 << 16)) |0; 8434 } 8435 8436 // Note: we can't get significant speed boost here. 8437 // So write code to minimize size - no pregenerated tables 8438 // and array tools dependencies. 8439 8440 8441 // Use ordinary array, since untyped makes no boost here 8442 function makeTable() { 8443 var c, table = []; 8444 8445 for (var n = 0; n < 256; n++) { 8446 c = n; 8447 for (var k = 0; k < 8; k++) { 8448 c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); 8449 } 8450 table[n] = c; 8451 } 8452 8453 return table; 8454 } 8455 8456 // Create table on load. Just 255 signed longs. Not a problem. 8457 var crcTable = makeTable(); 8458 8459 8460 function crc32(crc, buf, len, pos) { 8461 var t = crcTable, 8462 end = pos + len; 8463 8464 crc ^= -1; 8465 8466 for (var i = pos; i < end; i++) { 8467 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; 8468 } 8469 8470 return (crc ^ (-1)); // >>> 0; 8471 } 8472 8473 /* Public constants ==========================================================*/ 8474 /* ===========================================================================*/ 8475 8476 8477 /* Allowed flush values; see deflate() and inflate() below for details */ 8478 var Z_NO_FLUSH = 0; 8479 var Z_PARTIAL_FLUSH = 1; 8480 //var Z_SYNC_FLUSH = 2; 8481 var Z_FULL_FLUSH = 3; 8482 var Z_FINISH = 4; 8483 var Z_BLOCK = 5; 8484 //var Z_TREES = 6; 8485 8486 8487 /* Return codes for the compression/decompression functions. Negative values 8488 * are errors, positive values are used for special but normal events. 8489 */ 8490 var Z_OK = 0; 8491 var Z_STREAM_END = 1; 8492 //var Z_NEED_DICT = 2; 8493 //var Z_ERRNO = -1; 8494 var Z_STREAM_ERROR = -2; 8495 var Z_DATA_ERROR = -3; 8496 //var Z_MEM_ERROR = -4; 8497 var Z_BUF_ERROR = -5; 8498 //var Z_VERSION_ERROR = -6; 8499 8500 8501 /* compression levels */ 8502 //var Z_NO_COMPRESSION = 0; 8503 //var Z_BEST_SPEED = 1; 8504 //var Z_BEST_COMPRESSION = 9; 8505 var Z_DEFAULT_COMPRESSION = -1; 8506 8507 8508 var Z_FILTERED = 1; 8509 var Z_HUFFMAN_ONLY = 2; 8510 var Z_RLE = 3; 8511 var Z_FIXED$1 = 4; 8512 8513 /* Possible values of the data_type field (though see inflate()) */ 8514 //var Z_BINARY = 0; 8515 //var Z_TEXT = 1; 8516 //var Z_ASCII = 1; // = Z_TEXT 8517 var Z_UNKNOWN$1 = 2; 8518 8519 8520 /* The deflate compression method */ 8521 var Z_DEFLATED = 8; 8522 8523 /*============================================================================*/ 8524 8525 8526 var MAX_MEM_LEVEL = 9; 8527 8528 8529 var LENGTH_CODES$1 = 29; 8530 /* number of length codes, not counting the special END_BLOCK code */ 8531 var LITERALS$1 = 256; 8532 /* number of literal bytes 0..255 */ 8533 var L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; 8534 /* number of Literal or Length codes, including the END_BLOCK code */ 8535 var D_CODES$1 = 30; 8536 /* number of distance codes */ 8537 var BL_CODES$1 = 19; 8538 /* number of codes used to transfer the bit lengths */ 8539 var HEAP_SIZE$1 = 2 * L_CODES$1 + 1; 8540 /* maximum heap size */ 8541 var MAX_BITS$1 = 15; 8542 /* All codes must not exceed MAX_BITS bits */ 8543 8544 var MIN_MATCH$1 = 3; 8545 var MAX_MATCH$1 = 258; 8546 var MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1); 8547 8548 var PRESET_DICT = 0x20; 8549 8550 var INIT_STATE = 42; 8551 var EXTRA_STATE = 69; 8552 var NAME_STATE = 73; 8553 var COMMENT_STATE = 91; 8554 var HCRC_STATE = 103; 8555 var BUSY_STATE = 113; 8556 var FINISH_STATE = 666; 8557 8558 var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ 8559 var BS_BLOCK_DONE = 2; /* block flush performed */ 8560 var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ 8561 var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ 8562 8563 var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. 8564 8565 function err(strm, errorCode) { 8566 strm.msg = msg[errorCode]; 8567 return errorCode; 8568 } 8569 8570 function rank(f) { 8571 return ((f) << 1) - ((f) > 4 ? 9 : 0); 8572 } 8573 8574 function zero$1(buf) { 8575 var len = buf.length; 8576 while (--len >= 0) { 8577 buf[len] = 0; 8578 } 8579 } 8580 8581 8582 /* ========================================================================= 8583 * Flush as much pending output as possible. All deflate() output goes 8584 * through this function so some applications may wish to modify it 8585 * to avoid allocating a large strm->output buffer and copying into it. 8586 * (See also read_buf()). 8587 */ 8588 function flush_pending(strm) { 8589 var s = strm.state; 8590 8591 //_tr_flush_bits(s); 8592 var len = s.pending; 8593 if (len > strm.avail_out) { 8594 len = strm.avail_out; 8595 } 8596 if (len === 0) { 8597 return; 8598 } 8599 8600 arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); 8601 strm.next_out += len; 8602 s.pending_out += len; 8603 strm.total_out += len; 8604 strm.avail_out -= len; 8605 s.pending -= len; 8606 if (s.pending === 0) { 8607 s.pending_out = 0; 8608 } 8609 } 8610 8611 8612 function flush_block_only(s, last) { 8613 _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); 8614 s.block_start = s.strstart; 8615 flush_pending(s.strm); 8616 } 8617 8618 8619 function put_byte(s, b) { 8620 s.pending_buf[s.pending++] = b; 8621 } 8622 8623 8624 /* ========================================================================= 8625 * Put a short in the pending buffer. The 16-bit value is put in MSB order. 8626 * IN assertion: the stream state is correct and there is enough room in 8627 * pending_buf. 8628 */ 8629 function putShortMSB(s, b) { 8630 // put_byte(s, (Byte)(b >> 8)); 8631 // put_byte(s, (Byte)(b & 0xff)); 8632 s.pending_buf[s.pending++] = (b >>> 8) & 0xff; 8633 s.pending_buf[s.pending++] = b & 0xff; 8634 } 8635 8636 8637 /* =========================================================================== 8638 * Read a new buffer from the current input stream, update the adler32 8639 * and total number of bytes read. All deflate() input goes through 8640 * this function so some applications may wish to modify it to avoid 8641 * allocating a large strm->input buffer and copying from it. 8642 * (See also flush_pending()). 8643 */ 8644 function read_buf(strm, buf, start, size) { 8645 var len = strm.avail_in; 8646 8647 if (len > size) { 8648 len = size; 8649 } 8650 if (len === 0) { 8651 return 0; 8652 } 8653 8654 strm.avail_in -= len; 8655 8656 // zmemcpy(buf, strm->next_in, len); 8657 arraySet(buf, strm.input, strm.next_in, len, start); 8658 if (strm.state.wrap === 1) { 8659 strm.adler = adler32(strm.adler, buf, len, start); 8660 } else if (strm.state.wrap === 2) { 8661 strm.adler = crc32(strm.adler, buf, len, start); 8662 } 8663 8664 strm.next_in += len; 8665 strm.total_in += len; 8666 8667 return len; 8668 } 8669 8670 8671 /* =========================================================================== 8672 * Set match_start to the longest match starting at the given string and 8673 * return its length. Matches shorter or equal to prev_length are discarded, 8674 * in which case the result is equal to prev_length and match_start is 8675 * garbage. 8676 * IN assertions: cur_match is the head of the hash chain for the current 8677 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 8678 * OUT assertion: the match length is not greater than s->lookahead. 8679 */ 8680 function longest_match(s, cur_match) { 8681 var chain_length = s.max_chain_length; /* max hash chain length */ 8682 var scan = s.strstart; /* current string */ 8683 var match; /* matched string */ 8684 var len; /* length of current match */ 8685 var best_len = s.prev_length; /* best match length so far */ 8686 var nice_match = s.nice_match; /* stop if match long enough */ 8687 var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? 8688 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0 /*NIL*/ ; 8689 8690 var _win = s.window; // shortcut 8691 8692 var wmask = s.w_mask; 8693 var prev = s.prev; 8694 8695 /* Stop when cur_match becomes <= limit. To simplify the code, 8696 * we prevent matches with the string of window index 0. 8697 */ 8698 8699 var strend = s.strstart + MAX_MATCH$1; 8700 var scan_end1 = _win[scan + best_len - 1]; 8701 var scan_end = _win[scan + best_len]; 8702 8703 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. 8704 * It is easy to get rid of this optimization if necessary. 8705 */ 8706 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); 8707 8708 /* Do not waste too much time if we already have a good match: */ 8709 if (s.prev_length >= s.good_match) { 8710 chain_length >>= 2; 8711 } 8712 /* Do not look for matches beyond the end of the input. This is necessary 8713 * to make deflate deterministic. 8714 */ 8715 if (nice_match > s.lookahead) { 8716 nice_match = s.lookahead; 8717 } 8718 8719 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); 8720 8721 do { 8722 // Assert(cur_match < s->strstart, "no future"); 8723 match = cur_match; 8724 8725 /* Skip to next match if the match length cannot increase 8726 * or if the match length is less than 2. Note that the checks below 8727 * for insufficient lookahead only occur occasionally for performance 8728 * reasons. Therefore uninitialized memory will be accessed, and 8729 * conditional jumps will be made that depend on those values. 8730 * However the length of the match is limited to the lookahead, so 8731 * the output of deflate is not affected by the uninitialized values. 8732 */ 8733 8734 if (_win[match + best_len] !== scan_end || 8735 _win[match + best_len - 1] !== scan_end1 || 8736 _win[match] !== _win[scan] || 8737 _win[++match] !== _win[scan + 1]) { 8738 continue; 8739 } 8740 8741 /* The check at best_len-1 can be removed because it will be made 8742 * again later. (This heuristic is not always a win.) 8743 * It is not necessary to compare scan[2] and match[2] since they 8744 * are always equal when the other bytes match, given that 8745 * the hash keys are equal and that HASH_BITS >= 8. 8746 */ 8747 scan += 2; 8748 match++; 8749 // Assert(*scan == *match, "match[2]?"); 8750 8751 /* We check for insufficient lookahead only every 8th comparison; 8752 * the 256th check will be made at strstart+258. 8753 */ 8754 do { 8755 /*jshint noempty:false*/ 8756 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && 8757 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && 8758 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && 8759 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && 8760 scan < strend); 8761 8762 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); 8763 8764 len = MAX_MATCH$1 - (strend - scan); 8765 scan = strend - MAX_MATCH$1; 8766 8767 if (len > best_len) { 8768 s.match_start = cur_match; 8769 best_len = len; 8770 if (len >= nice_match) { 8771 break; 8772 } 8773 scan_end1 = _win[scan + best_len - 1]; 8774 scan_end = _win[scan + best_len]; 8775 } 8776 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); 8777 8778 if (best_len <= s.lookahead) { 8779 return best_len; 8780 } 8781 return s.lookahead; 8782 } 8783 8784 8785 /* =========================================================================== 8786 * Fill the window when the lookahead becomes insufficient. 8787 * Updates strstart and lookahead. 8788 * 8789 * IN assertion: lookahead < MIN_LOOKAHEAD 8790 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD 8791 * At least one byte has been read, or avail_in == 0; reads are 8792 * performed for at least two bytes (required for the zip translate_eol 8793 * option -- not supported here). 8794 */ 8795 function fill_window(s) { 8796 var _w_size = s.w_size; 8797 var p, n, m, more, str; 8798 8799 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); 8800 8801 do { 8802 more = s.window_size - s.lookahead - s.strstart; 8803 8804 // JS ints have 32 bit, block below not needed 8805 /* Deal with !@#$% 64K limit: */ 8806 //if (sizeof(int) <= 2) { 8807 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { 8808 // more = wsize; 8809 // 8810 // } else if (more == (unsigned)(-1)) { 8811 // /* Very unlikely, but possible on 16 bit machine if 8812 // * strstart == 0 && lookahead == 1 (input done a byte at time) 8813 // */ 8814 // more--; 8815 // } 8816 //} 8817 8818 8819 /* If the window is almost full and there is insufficient lookahead, 8820 * move the upper half to the lower one to make room in the upper half. 8821 */ 8822 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { 8823 8824 arraySet(s.window, s.window, _w_size, _w_size, 0); 8825 s.match_start -= _w_size; 8826 s.strstart -= _w_size; 8827 /* we now have strstart >= MAX_DIST */ 8828 s.block_start -= _w_size; 8829 8830 /* Slide the hash table (could be avoided with 32 bit values 8831 at the expense of memory usage). We slide even when level == 0 8832 to keep the hash table consistent if we switch back to level > 0 8833 later. (Using level 0 permanently is not an optimal usage of 8834 zlib, so we don't care about this pathological case.) 8835 */ 8836 8837 n = s.hash_size; 8838 p = n; 8839 do { 8840 m = s.head[--p]; 8841 s.head[p] = (m >= _w_size ? m - _w_size : 0); 8842 } while (--n); 8843 8844 n = _w_size; 8845 p = n; 8846 do { 8847 m = s.prev[--p]; 8848 s.prev[p] = (m >= _w_size ? m - _w_size : 0); 8849 /* If n is not on any hash chain, prev[n] is garbage but 8850 * its value will never be used. 8851 */ 8852 } while (--n); 8853 8854 more += _w_size; 8855 } 8856 if (s.strm.avail_in === 0) { 8857 break; 8858 } 8859 8860 /* If there was no sliding: 8861 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && 8862 * more == window_size - lookahead - strstart 8863 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) 8864 * => more >= window_size - 2*WSIZE + 2 8865 * In the BIG_MEM or MMAP case (not yet supported), 8866 * window_size == input_size + MIN_LOOKAHEAD && 8867 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. 8868 * Otherwise, window_size == 2*WSIZE so more >= 2. 8869 * If there was sliding, more >= WSIZE. So in all cases, more >= 2. 8870 */ 8871 //Assert(more >= 2, "more < 2"); 8872 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); 8873 s.lookahead += n; 8874 8875 /* Initialize the hash value now that we have some input: */ 8876 if (s.lookahead + s.insert >= MIN_MATCH$1) { 8877 str = s.strstart - s.insert; 8878 s.ins_h = s.window[str]; 8879 8880 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ 8881 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; 8882 //#if MIN_MATCH != 3 8883 // Call update_hash() MIN_MATCH-3 more times 8884 //#endif 8885 while (s.insert) { 8886 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ 8887 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; 8888 8889 s.prev[str & s.w_mask] = s.head[s.ins_h]; 8890 s.head[s.ins_h] = str; 8891 str++; 8892 s.insert--; 8893 if (s.lookahead + s.insert < MIN_MATCH$1) { 8894 break; 8895 } 8896 } 8897 } 8898 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, 8899 * but this is not important since only literal bytes will be emitted. 8900 */ 8901 8902 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); 8903 8904 /* If the WIN_INIT bytes after the end of the current data have never been 8905 * written, then zero those bytes in order to avoid memory check reports of 8906 * the use of uninitialized (or uninitialised as Julian writes) bytes by 8907 * the longest match routines. Update the high water mark for the next 8908 * time through here. WIN_INIT is set to MAX_MATCH since the longest match 8909 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. 8910 */ 8911 // if (s.high_water < s.window_size) { 8912 // var curr = s.strstart + s.lookahead; 8913 // var init = 0; 8914 // 8915 // if (s.high_water < curr) { 8916 // /* Previous high water mark below current data -- zero WIN_INIT 8917 // * bytes or up to end of window, whichever is less. 8918 // */ 8919 // init = s.window_size - curr; 8920 // if (init > WIN_INIT) 8921 // init = WIN_INIT; 8922 // zmemzero(s->window + curr, (unsigned)init); 8923 // s->high_water = curr + init; 8924 // } 8925 // else if (s->high_water < (ulg)curr + WIN_INIT) { 8926 // /* High water mark at or above current data, but below current data 8927 // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up 8928 // * to end of window, whichever is less. 8929 // */ 8930 // init = (ulg)curr + WIN_INIT - s->high_water; 8931 // if (init > s->window_size - s->high_water) 8932 // init = s->window_size - s->high_water; 8933 // zmemzero(s->window + s->high_water, (unsigned)init); 8934 // s->high_water += init; 8935 // } 8936 // } 8937 // 8938 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, 8939 // "not enough room for search"); 8940 } 8941 8942 /* =========================================================================== 8943 * Copy without compression as much as possible from the input stream, return 8944 * the current block state. 8945 * This function does not insert new strings in the dictionary since 8946 * uncompressible data is probably not useful. This function is used 8947 * only for the level=0 compression option. 8948 * NOTE: this function should be optimized to avoid extra copying from 8949 * window to pending_buf. 8950 */ 8951 function deflate_stored(s, flush) { 8952 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited 8953 * to pending_buf_size, and each stored block has a 5 byte header: 8954 */ 8955 var max_block_size = 0xffff; 8956 8957 if (max_block_size > s.pending_buf_size - 5) { 8958 max_block_size = s.pending_buf_size - 5; 8959 } 8960 8961 /* Copy as much as possible from input to output: */ 8962 for (;;) { 8963 /* Fill the window as much as possible: */ 8964 if (s.lookahead <= 1) { 8965 8966 //Assert(s->strstart < s->w_size+MAX_DIST(s) || 8967 // s->block_start >= (long)s->w_size, "slide too late"); 8968 // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || 8969 // s.block_start >= s.w_size)) { 8970 // throw new Error("slide too late"); 8971 // } 8972 8973 fill_window(s); 8974 if (s.lookahead === 0 && flush === Z_NO_FLUSH) { 8975 return BS_NEED_MORE; 8976 } 8977 8978 if (s.lookahead === 0) { 8979 break; 8980 } 8981 /* flush the current block */ 8982 } 8983 //Assert(s->block_start >= 0L, "block gone"); 8984 // if (s.block_start < 0) throw new Error("block gone"); 8985 8986 s.strstart += s.lookahead; 8987 s.lookahead = 0; 8988 8989 /* Emit a stored block if pending_buf will be full: */ 8990 var max_start = s.block_start + max_block_size; 8991 8992 if (s.strstart === 0 || s.strstart >= max_start) { 8993 /* strstart == 0 is possible when wraparound on 16-bit machine */ 8994 s.lookahead = s.strstart - max_start; 8995 s.strstart = max_start; 8996 /*** FLUSH_BLOCK(s, 0); ***/ 8997 flush_block_only(s, false); 8998 if (s.strm.avail_out === 0) { 8999 return BS_NEED_MORE; 9000 } 9001 /***/ 9002 9003 9004 } 9005 /* Flush if we may have to slide, otherwise block_start may become 9006 * negative and the data will be gone: 9007 */ 9008 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { 9009 /*** FLUSH_BLOCK(s, 0); ***/ 9010 flush_block_only(s, false); 9011 if (s.strm.avail_out === 0) { 9012 return BS_NEED_MORE; 9013 } 9014 /***/ 9015 } 9016 } 9017 9018 s.insert = 0; 9019 9020 if (flush === Z_FINISH) { 9021 /*** FLUSH_BLOCK(s, 1); ***/ 9022 flush_block_only(s, true); 9023 if (s.strm.avail_out === 0) { 9024 return BS_FINISH_STARTED; 9025 } 9026 /***/ 9027 return BS_FINISH_DONE; 9028 } 9029 9030 if (s.strstart > s.block_start) { 9031 /*** FLUSH_BLOCK(s, 0); ***/ 9032 flush_block_only(s, false); 9033 if (s.strm.avail_out === 0) { 9034 return BS_NEED_MORE; 9035 } 9036 /***/ 9037 } 9038 9039 return BS_NEED_MORE; 9040 } 9041 9042 /* =========================================================================== 9043 * Compress as much as possible from the input stream, return the current 9044 * block state. 9045 * This function does not perform lazy evaluation of matches and inserts 9046 * new strings in the dictionary only for unmatched strings or for short 9047 * matches. It is used only for the fast compression options. 9048 */ 9049 function deflate_fast(s, flush) { 9050 var hash_head; /* head of the hash chain */ 9051 var bflush; /* set if current block must be flushed */ 9052 9053 for (;;) { 9054 /* Make sure that we always have enough lookahead, except 9055 * at the end of the input file. We need MAX_MATCH bytes 9056 * for the next match, plus MIN_MATCH bytes to insert the 9057 * string following the next match. 9058 */ 9059 if (s.lookahead < MIN_LOOKAHEAD) { 9060 fill_window(s); 9061 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { 9062 return BS_NEED_MORE; 9063 } 9064 if (s.lookahead === 0) { 9065 break; /* flush the current block */ 9066 } 9067 } 9068 9069 /* Insert the string window[strstart .. strstart+2] in the 9070 * dictionary, and set hash_head to the head of the hash chain: 9071 */ 9072 hash_head = 0 /*NIL*/ ; 9073 if (s.lookahead >= MIN_MATCH$1) { 9074 /*** INSERT_STRING(s, s.strstart, hash_head); ***/ 9075 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; 9076 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; 9077 s.head[s.ins_h] = s.strstart; 9078 /***/ 9079 } 9080 9081 /* Find the longest match, discarding those <= prev_length. 9082 * At this point we have always match_length < MIN_MATCH 9083 */ 9084 if (hash_head !== 0 /*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { 9085 /* To simplify the code, we prevent matches with the string 9086 * of window index 0 (in particular we have to avoid a match 9087 * of the string with itself at the start of the input file). 9088 */ 9089 s.match_length = longest_match(s, hash_head); 9090 /* longest_match() sets match_start */ 9091 } 9092 if (s.match_length >= MIN_MATCH$1) { 9093 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only 9094 9095 /*** _tr_tally_dist(s, s.strstart - s.match_start, 9096 s.match_length - MIN_MATCH, bflush); ***/ 9097 bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1); 9098 9099 s.lookahead -= s.match_length; 9100 9101 /* Insert new strings in the hash table only if the match length 9102 * is not too large. This saves time but degrades compression. 9103 */ 9104 if (s.match_length <= s.max_lazy_match /*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) { 9105 s.match_length--; /* string at strstart already in table */ 9106 do { 9107 s.strstart++; 9108 /*** INSERT_STRING(s, s.strstart, hash_head); ***/ 9109 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; 9110 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; 9111 s.head[s.ins_h] = s.strstart; 9112 /***/ 9113 /* strstart never exceeds WSIZE-MAX_MATCH, so there are 9114 * always MIN_MATCH bytes ahead. 9115 */ 9116 } while (--s.match_length !== 0); 9117 s.strstart++; 9118 } else { 9119 s.strstart += s.match_length; 9120 s.match_length = 0; 9121 s.ins_h = s.window[s.strstart]; 9122 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ 9123 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; 9124 9125 //#if MIN_MATCH != 3 9126 // Call UPDATE_HASH() MIN_MATCH-3 more times 9127 //#endif 9128 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not 9129 * matter since it will be recomputed at next deflate call. 9130 */ 9131 } 9132 } else { 9133 /* No match, output a literal byte */ 9134 //Tracevv((stderr,"%c", s.window[s.strstart])); 9135 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ 9136 bflush = _tr_tally(s, 0, s.window[s.strstart]); 9137 9138 s.lookahead--; 9139 s.strstart++; 9140 } 9141 if (bflush) { 9142 /*** FLUSH_BLOCK(s, 0); ***/ 9143 flush_block_only(s, false); 9144 if (s.strm.avail_out === 0) { 9145 return BS_NEED_MORE; 9146 } 9147 /***/ 9148 } 9149 } 9150 s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1); 9151 if (flush === Z_FINISH) { 9152 /*** FLUSH_BLOCK(s, 1); ***/ 9153 flush_block_only(s, true); 9154 if (s.strm.avail_out === 0) { 9155 return BS_FINISH_STARTED; 9156 } 9157 /***/ 9158 return BS_FINISH_DONE; 9159 } 9160 if (s.last_lit) { 9161 /*** FLUSH_BLOCK(s, 0); ***/ 9162 flush_block_only(s, false); 9163 if (s.strm.avail_out === 0) { 9164 return BS_NEED_MORE; 9165 } 9166 /***/ 9167 } 9168 return BS_BLOCK_DONE; 9169 } 9170 9171 /* =========================================================================== 9172 * Same as above, but achieves better compression. We use a lazy 9173 * evaluation for matches: a match is finally adopted only if there is 9174 * no better match at the next window position. 9175 */ 9176 function deflate_slow(s, flush) { 9177 var hash_head; /* head of hash chain */ 9178 var bflush; /* set if current block must be flushed */ 9179 9180 var max_insert; 9181 9182 /* Process the input block. */ 9183 for (;;) { 9184 /* Make sure that we always have enough lookahead, except 9185 * at the end of the input file. We need MAX_MATCH bytes 9186 * for the next match, plus MIN_MATCH bytes to insert the 9187 * string following the next match. 9188 */ 9189 if (s.lookahead < MIN_LOOKAHEAD) { 9190 fill_window(s); 9191 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { 9192 return BS_NEED_MORE; 9193 } 9194 if (s.lookahead === 0) { 9195 break; 9196 } /* flush the current block */ 9197 } 9198 9199 /* Insert the string window[strstart .. strstart+2] in the 9200 * dictionary, and set hash_head to the head of the hash chain: 9201 */ 9202 hash_head = 0 /*NIL*/ ; 9203 if (s.lookahead >= MIN_MATCH$1) { 9204 /*** INSERT_STRING(s, s.strstart, hash_head); ***/ 9205 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; 9206 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; 9207 s.head[s.ins_h] = s.strstart; 9208 /***/ 9209 } 9210 9211 /* Find the longest match, discarding those <= prev_length. 9212 */ 9213 s.prev_length = s.match_length; 9214 s.prev_match = s.match_start; 9215 s.match_length = MIN_MATCH$1 - 1; 9216 9217 if (hash_head !== 0 /*NIL*/ && s.prev_length < s.max_lazy_match && 9218 s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD) /*MAX_DIST(s)*/ ) { 9219 /* To simplify the code, we prevent matches with the string 9220 * of window index 0 (in particular we have to avoid a match 9221 * of the string with itself at the start of the input file). 9222 */ 9223 s.match_length = longest_match(s, hash_head); 9224 /* longest_match() sets match_start */ 9225 9226 if (s.match_length <= 5 && 9227 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096 /*TOO_FAR*/ ))) { 9228 9229 /* If prev_match is also MIN_MATCH, match_start is garbage 9230 * but we will ignore the current match anyway. 9231 */ 9232 s.match_length = MIN_MATCH$1 - 1; 9233 } 9234 } 9235 /* If there was a match at the previous step and the current 9236 * match is not better, output the previous match: 9237 */ 9238 if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) { 9239 max_insert = s.strstart + s.lookahead - MIN_MATCH$1; 9240 /* Do not insert strings in hash table beyond this. */ 9241 9242 //check_match(s, s.strstart-1, s.prev_match, s.prev_length); 9243 9244 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, 9245 s.prev_length - MIN_MATCH, bflush);***/ 9246 bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1); 9247 /* Insert in hash table all strings up to the end of the match. 9248 * strstart-1 and strstart are already inserted. If there is not 9249 * enough lookahead, the last two strings are not inserted in 9250 * the hash table. 9251 */ 9252 s.lookahead -= s.prev_length - 1; 9253 s.prev_length -= 2; 9254 do { 9255 if (++s.strstart <= max_insert) { 9256 /*** INSERT_STRING(s, s.strstart, hash_head); ***/ 9257 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; 9258 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; 9259 s.head[s.ins_h] = s.strstart; 9260 /***/ 9261 } 9262 } while (--s.prev_length !== 0); 9263 s.match_available = 0; 9264 s.match_length = MIN_MATCH$1 - 1; 9265 s.strstart++; 9266 9267 if (bflush) { 9268 /*** FLUSH_BLOCK(s, 0); ***/ 9269 flush_block_only(s, false); 9270 if (s.strm.avail_out === 0) { 9271 return BS_NEED_MORE; 9272 } 9273 /***/ 9274 } 9275 9276 } else if (s.match_available) { 9277 /* If there was no match at the previous position, output a 9278 * single literal. If there was a match but the current match 9279 * is longer, truncate the previous match to a single literal. 9280 */ 9281 //Tracevv((stderr,"%c", s->window[s->strstart-1])); 9282 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ 9283 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); 9284 9285 if (bflush) { 9286 /*** FLUSH_BLOCK_ONLY(s, 0) ***/ 9287 flush_block_only(s, false); 9288 /***/ 9289 } 9290 s.strstart++; 9291 s.lookahead--; 9292 if (s.strm.avail_out === 0) { 9293 return BS_NEED_MORE; 9294 } 9295 } else { 9296 /* There is no previous match to compare with, wait for 9297 * the next step to decide. 9298 */ 9299 s.match_available = 1; 9300 s.strstart++; 9301 s.lookahead--; 9302 } 9303 } 9304 //Assert (flush != Z_NO_FLUSH, "no flush?"); 9305 if (s.match_available) { 9306 //Tracevv((stderr,"%c", s->window[s->strstart-1])); 9307 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ 9308 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); 9309 9310 s.match_available = 0; 9311 } 9312 s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1; 9313 if (flush === Z_FINISH) { 9314 /*** FLUSH_BLOCK(s, 1); ***/ 9315 flush_block_only(s, true); 9316 if (s.strm.avail_out === 0) { 9317 return BS_FINISH_STARTED; 9318 } 9319 /***/ 9320 return BS_FINISH_DONE; 9321 } 9322 if (s.last_lit) { 9323 /*** FLUSH_BLOCK(s, 0); ***/ 9324 flush_block_only(s, false); 9325 if (s.strm.avail_out === 0) { 9326 return BS_NEED_MORE; 9327 } 9328 /***/ 9329 } 9330 9331 return BS_BLOCK_DONE; 9332 } 9333 9334 9335 /* =========================================================================== 9336 * For Z_RLE, simply look for runs of bytes, generate matches only of distance 9337 * one. Do not maintain a hash table. (It will be regenerated if this run of 9338 * deflate switches away from Z_RLE.) 9339 */ 9340 function deflate_rle(s, flush) { 9341 var bflush; /* set if current block must be flushed */ 9342 var prev; /* byte at distance one to match */ 9343 var scan, strend; /* scan goes up to strend for length of run */ 9344 9345 var _win = s.window; 9346 9347 for (;;) { 9348 /* Make sure that we always have enough lookahead, except 9349 * at the end of the input file. We need MAX_MATCH bytes 9350 * for the longest run, plus one for the unrolled loop. 9351 */ 9352 if (s.lookahead <= MAX_MATCH$1) { 9353 fill_window(s); 9354 if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) { 9355 return BS_NEED_MORE; 9356 } 9357 if (s.lookahead === 0) { 9358 break; 9359 } /* flush the current block */ 9360 } 9361 9362 /* See how many times the previous byte repeats */ 9363 s.match_length = 0; 9364 if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) { 9365 scan = s.strstart - 1; 9366 prev = _win[scan]; 9367 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { 9368 strend = s.strstart + MAX_MATCH$1; 9369 do { 9370 /*jshint noempty:false*/ 9371 } while (prev === _win[++scan] && prev === _win[++scan] && 9372 prev === _win[++scan] && prev === _win[++scan] && 9373 prev === _win[++scan] && prev === _win[++scan] && 9374 prev === _win[++scan] && prev === _win[++scan] && 9375 scan < strend); 9376 s.match_length = MAX_MATCH$1 - (strend - scan); 9377 if (s.match_length > s.lookahead) { 9378 s.match_length = s.lookahead; 9379 } 9380 } 9381 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); 9382 } 9383 9384 /* Emit match if have run of MIN_MATCH or longer, else emit literal */ 9385 if (s.match_length >= MIN_MATCH$1) { 9386 //check_match(s, s.strstart, s.strstart - 1, s.match_length); 9387 9388 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ 9389 bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1); 9390 9391 s.lookahead -= s.match_length; 9392 s.strstart += s.match_length; 9393 s.match_length = 0; 9394 } else { 9395 /* No match, output a literal byte */ 9396 //Tracevv((stderr,"%c", s->window[s->strstart])); 9397 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ 9398 bflush = _tr_tally(s, 0, s.window[s.strstart]); 9399 9400 s.lookahead--; 9401 s.strstart++; 9402 } 9403 if (bflush) { 9404 /*** FLUSH_BLOCK(s, 0); ***/ 9405 flush_block_only(s, false); 9406 if (s.strm.avail_out === 0) { 9407 return BS_NEED_MORE; 9408 } 9409 /***/ 9410 } 9411 } 9412 s.insert = 0; 9413 if (flush === Z_FINISH) { 9414 /*** FLUSH_BLOCK(s, 1); ***/ 9415 flush_block_only(s, true); 9416 if (s.strm.avail_out === 0) { 9417 return BS_FINISH_STARTED; 9418 } 9419 /***/ 9420 return BS_FINISH_DONE; 9421 } 9422 if (s.last_lit) { 9423 /*** FLUSH_BLOCK(s, 0); ***/ 9424 flush_block_only(s, false); 9425 if (s.strm.avail_out === 0) { 9426 return BS_NEED_MORE; 9427 } 9428 /***/ 9429 } 9430 return BS_BLOCK_DONE; 9431 } 9432 9433 /* =========================================================================== 9434 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. 9435 * (It will be regenerated if this run of deflate switches away from Huffman.) 9436 */ 9437 function deflate_huff(s, flush) { 9438 var bflush; /* set if current block must be flushed */ 9439 9440 for (;;) { 9441 /* Make sure that we have a literal to write. */ 9442 if (s.lookahead === 0) { 9443 fill_window(s); 9444 if (s.lookahead === 0) { 9445 if (flush === Z_NO_FLUSH) { 9446 return BS_NEED_MORE; 9447 } 9448 break; /* flush the current block */ 9449 } 9450 } 9451 9452 /* Output a literal byte */ 9453 s.match_length = 0; 9454 //Tracevv((stderr,"%c", s->window[s->strstart])); 9455 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ 9456 bflush = _tr_tally(s, 0, s.window[s.strstart]); 9457 s.lookahead--; 9458 s.strstart++; 9459 if (bflush) { 9460 /*** FLUSH_BLOCK(s, 0); ***/ 9461 flush_block_only(s, false); 9462 if (s.strm.avail_out === 0) { 9463 return BS_NEED_MORE; 9464 } 9465 /***/ 9466 } 9467 } 9468 s.insert = 0; 9469 if (flush === Z_FINISH) { 9470 /*** FLUSH_BLOCK(s, 1); ***/ 9471 flush_block_only(s, true); 9472 if (s.strm.avail_out === 0) { 9473 return BS_FINISH_STARTED; 9474 } 9475 /***/ 9476 return BS_FINISH_DONE; 9477 } 9478 if (s.last_lit) { 9479 /*** FLUSH_BLOCK(s, 0); ***/ 9480 flush_block_only(s, false); 9481 if (s.strm.avail_out === 0) { 9482 return BS_NEED_MORE; 9483 } 9484 /***/ 9485 } 9486 return BS_BLOCK_DONE; 9487 } 9488 9489 /* Values for max_lazy_match, good_match and max_chain_length, depending on 9490 * the desired pack level (0..9). The values given below have been tuned to 9491 * exclude worst case performance for pathological files. Better values may be 9492 * found for specific files. 9493 */ 9494 function Config(good_length, max_lazy, nice_length, max_chain, func) { 9495 this.good_length = good_length; 9496 this.max_lazy = max_lazy; 9497 this.nice_length = nice_length; 9498 this.max_chain = max_chain; 9499 this.func = func; 9500 } 9501 9502 var configuration_table; 9503 9504 configuration_table = [ 9505 /* good lazy nice chain */ 9506 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ 9507 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ 9508 new Config(4, 5, 16, 8, deflate_fast), /* 2 */ 9509 new Config(4, 6, 32, 32, deflate_fast), /* 3 */ 9510 9511 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ 9512 new Config(8, 16, 32, 32, deflate_slow), /* 5 */ 9513 new Config(8, 16, 128, 128, deflate_slow), /* 6 */ 9514 new Config(8, 32, 128, 256, deflate_slow), /* 7 */ 9515 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ 9516 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ 9517 ]; 9518 9519 9520 /* =========================================================================== 9521 * Initialize the "longest match" routines for a new zlib stream 9522 */ 9523 function lm_init(s) { 9524 s.window_size = 2 * s.w_size; 9525 9526 /*** CLEAR_HASH(s); ***/ 9527 zero$1(s.head); // Fill with NIL (= 0); 9528 9529 /* Set the default configuration parameters: 9530 */ 9531 s.max_lazy_match = configuration_table[s.level].max_lazy; 9532 s.good_match = configuration_table[s.level].good_length; 9533 s.nice_match = configuration_table[s.level].nice_length; 9534 s.max_chain_length = configuration_table[s.level].max_chain; 9535 9536 s.strstart = 0; 9537 s.block_start = 0; 9538 s.lookahead = 0; 9539 s.insert = 0; 9540 s.match_length = s.prev_length = MIN_MATCH$1 - 1; 9541 s.match_available = 0; 9542 s.ins_h = 0; 9543 } 9544 9545 9546 function DeflateState() { 9547 this.strm = null; /* pointer back to this zlib stream */ 9548 this.status = 0; /* as the name implies */ 9549 this.pending_buf = null; /* output still pending */ 9550 this.pending_buf_size = 0; /* size of pending_buf */ 9551 this.pending_out = 0; /* next pending byte to output to the stream */ 9552 this.pending = 0; /* nb of bytes in the pending buffer */ 9553 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ 9554 this.gzhead = null; /* gzip header information to write */ 9555 this.gzindex = 0; /* where in extra, name, or comment */ 9556 this.method = Z_DEFLATED; /* can only be DEFLATED */ 9557 this.last_flush = -1; /* value of flush param for previous deflate call */ 9558 9559 this.w_size = 0; /* LZ77 window size (32K by default) */ 9560 this.w_bits = 0; /* log2(w_size) (8..16) */ 9561 this.w_mask = 0; /* w_size - 1 */ 9562 9563 this.window = null; 9564 /* Sliding window. Input bytes are read into the second half of the window, 9565 * and move to the first half later to keep a dictionary of at least wSize 9566 * bytes. With this organization, matches are limited to a distance of 9567 * wSize-MAX_MATCH bytes, but this ensures that IO is always 9568 * performed with a length multiple of the block size. 9569 */ 9570 9571 this.window_size = 0; 9572 /* Actual size of window: 2*wSize, except when the user input buffer 9573 * is directly used as sliding window. 9574 */ 9575 9576 this.prev = null; 9577 /* Link to older string with same hash index. To limit the size of this 9578 * array to 64K, this link is maintained only for the last 32K strings. 9579 * An index in this array is thus a window index modulo 32K. 9580 */ 9581 9582 this.head = null; /* Heads of the hash chains or NIL. */ 9583 9584 this.ins_h = 0; /* hash index of string to be inserted */ 9585 this.hash_size = 0; /* number of elements in hash table */ 9586 this.hash_bits = 0; /* log2(hash_size) */ 9587 this.hash_mask = 0; /* hash_size-1 */ 9588 9589 this.hash_shift = 0; 9590 /* Number of bits by which ins_h must be shifted at each input 9591 * step. It must be such that after MIN_MATCH steps, the oldest 9592 * byte no longer takes part in the hash key, that is: 9593 * hash_shift * MIN_MATCH >= hash_bits 9594 */ 9595 9596 this.block_start = 0; 9597 /* Window position at the beginning of the current output block. Gets 9598 * negative when the window is moved backwards. 9599 */ 9600 9601 this.match_length = 0; /* length of best match */ 9602 this.prev_match = 0; /* previous match */ 9603 this.match_available = 0; /* set if previous match exists */ 9604 this.strstart = 0; /* start of string to insert */ 9605 this.match_start = 0; /* start of matching string */ 9606 this.lookahead = 0; /* number of valid bytes ahead in window */ 9607 9608 this.prev_length = 0; 9609 /* Length of the best match at previous step. Matches not greater than this 9610 * are discarded. This is used in the lazy match evaluation. 9611 */ 9612 9613 this.max_chain_length = 0; 9614 /* To speed up deflation, hash chains are never searched beyond this 9615 * length. A higher limit improves compression ratio but degrades the 9616 * speed. 9617 */ 9618 9619 this.max_lazy_match = 0; 9620 /* Attempt to find a better match only when the current match is strictly 9621 * smaller than this value. This mechanism is used only for compression 9622 * levels >= 4. 9623 */ 9624 // That's alias to max_lazy_match, don't use directly 9625 //this.max_insert_length = 0; 9626 /* Insert new strings in the hash table only if the match length is not 9627 * greater than this length. This saves time but degrades compression. 9628 * max_insert_length is used only for compression levels <= 3. 9629 */ 9630 9631 this.level = 0; /* compression level (1..9) */ 9632 this.strategy = 0; /* favor or force Huffman coding*/ 9633 9634 this.good_match = 0; 9635 /* Use a faster search when the previous match is longer than this */ 9636 9637 this.nice_match = 0; /* Stop searching when current match exceeds this */ 9638 9639 /* used by c: */ 9640 9641 /* Didn't use ct_data typedef below to suppress compiler warning */ 9642 9643 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ 9644 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ 9645 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ 9646 9647 // Use flat array of DOUBLE size, with interleaved fata, 9648 // because JS does not support effective 9649 this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2); 9650 this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2); 9651 this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2); 9652 zero$1(this.dyn_ltree); 9653 zero$1(this.dyn_dtree); 9654 zero$1(this.bl_tree); 9655 9656 this.l_desc = null; /* desc. for literal tree */ 9657 this.d_desc = null; /* desc. for distance tree */ 9658 this.bl_desc = null; /* desc. for bit length tree */ 9659 9660 //ush bl_count[MAX_BITS+1]; 9661 this.bl_count = new Buf16(MAX_BITS$1 + 1); 9662 /* number of codes at each bit length for an optimal tree */ 9663 9664 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ 9665 this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */ 9666 zero$1(this.heap); 9667 9668 this.heap_len = 0; /* number of elements in the heap */ 9669 this.heap_max = 0; /* element of largest frequency */ 9670 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. 9671 * The same heap array is used to build all 9672 */ 9673 9674 this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1]; 9675 zero$1(this.depth); 9676 /* Depth of each subtree used as tie breaker for trees of equal frequency 9677 */ 9678 9679 this.l_buf = 0; /* buffer index for literals or lengths */ 9680 9681 this.lit_bufsize = 0; 9682 /* Size of match buffer for literals/lengths. There are 4 reasons for 9683 * limiting lit_bufsize to 64K: 9684 * - frequencies can be kept in 16 bit counters 9685 * - if compression is not successful for the first block, all input 9686 * data is still in the window so we can still emit a stored block even 9687 * when input comes from standard input. (This can also be done for 9688 * all blocks if lit_bufsize is not greater than 32K.) 9689 * - if compression is not successful for a file smaller than 64K, we can 9690 * even emit a stored file instead of a stored block (saving 5 bytes). 9691 * This is applicable only for zip (not gzip or zlib). 9692 * - creating new Huffman trees less frequently may not provide fast 9693 * adaptation to changes in the input data statistics. (Take for 9694 * example a binary file with poorly compressible code followed by 9695 * a highly compressible string table.) Smaller buffer sizes give 9696 * fast adaptation but have of course the overhead of transmitting 9697 * trees more frequently. 9698 * - I can't count above 4 9699 */ 9700 9701 this.last_lit = 0; /* running index in l_buf */ 9702 9703 this.d_buf = 0; 9704 /* Buffer index for distances. To simplify the code, d_buf and l_buf have 9705 * the same number of elements. To use different lengths, an extra flag 9706 * array would be necessary. 9707 */ 9708 9709 this.opt_len = 0; /* bit length of current block with optimal trees */ 9710 this.static_len = 0; /* bit length of current block with static trees */ 9711 this.matches = 0; /* number of string matches in current block */ 9712 this.insert = 0; /* bytes at end of window left to insert */ 9713 9714 9715 this.bi_buf = 0; 9716 /* Output buffer. bits are inserted starting at the bottom (least 9717 * significant bits). 9718 */ 9719 this.bi_valid = 0; 9720 /* Number of valid bits in bi_buf. All bits above the last valid bit 9721 * are always zero. 9722 */ 9723 9724 // Used for window memory init. We safely ignore it for JS. That makes 9725 // sense only for pointers and memory check tools. 9726 //this.high_water = 0; 9727 /* High water mark offset in window for initialized bytes -- bytes above 9728 * this are set to zero in order to avoid memory check warnings when 9729 * longest match routines access bytes past the input. This is then 9730 * updated to the new high water mark. 9731 */ 9732 } 9733 9734 9735 function deflateResetKeep(strm) { 9736 var s; 9737 9738 if (!strm || !strm.state) { 9739 return err(strm, Z_STREAM_ERROR); 9740 } 9741 9742 strm.total_in = strm.total_out = 0; 9743 strm.data_type = Z_UNKNOWN$1; 9744 9745 s = strm.state; 9746 s.pending = 0; 9747 s.pending_out = 0; 9748 9749 if (s.wrap < 0) { 9750 s.wrap = -s.wrap; 9751 /* was made negative by deflate(..., Z_FINISH); */ 9752 } 9753 s.status = (s.wrap ? INIT_STATE : BUSY_STATE); 9754 strm.adler = (s.wrap === 2) ? 9755 0 // crc32(0, Z_NULL, 0) 9756 : 9757 1; // adler32(0, Z_NULL, 0) 9758 s.last_flush = Z_NO_FLUSH; 9759 _tr_init(s); 9760 return Z_OK; 9761 } 9762 9763 9764 function deflateReset(strm) { 9765 var ret = deflateResetKeep(strm); 9766 if (ret === Z_OK) { 9767 lm_init(strm.state); 9768 } 9769 return ret; 9770 } 9771 9772 9773 function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { 9774 if (!strm) { // === Z_NULL 9775 return Z_STREAM_ERROR; 9776 } 9777 var wrap = 1; 9778 9779 if (level === Z_DEFAULT_COMPRESSION) { 9780 level = 6; 9781 } 9782 9783 if (windowBits < 0) { /* suppress zlib wrapper */ 9784 wrap = 0; 9785 windowBits = -windowBits; 9786 } else if (windowBits > 15) { 9787 wrap = 2; /* write gzip wrapper instead */ 9788 windowBits -= 16; 9789 } 9790 9791 9792 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || 9793 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || 9794 strategy < 0 || strategy > Z_FIXED$1) { 9795 return err(strm, Z_STREAM_ERROR); 9796 } 9797 9798 9799 if (windowBits === 8) { 9800 windowBits = 9; 9801 } 9802 /* until 256-byte window bug fixed */ 9803 9804 var s = new DeflateState(); 9805 9806 strm.state = s; 9807 s.strm = strm; 9808 9809 s.wrap = wrap; 9810 s.gzhead = null; 9811 s.w_bits = windowBits; 9812 s.w_size = 1 << s.w_bits; 9813 s.w_mask = s.w_size - 1; 9814 9815 s.hash_bits = memLevel + 7; 9816 s.hash_size = 1 << s.hash_bits; 9817 s.hash_mask = s.hash_size - 1; 9818 s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1); 9819 9820 s.window = new Buf8(s.w_size * 2); 9821 s.head = new Buf16(s.hash_size); 9822 s.prev = new Buf16(s.w_size); 9823 9824 // Don't need mem init magic for JS. 9825 //s.high_water = 0; /* nothing written to s->window yet */ 9826 9827 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ 9828 9829 s.pending_buf_size = s.lit_bufsize * 4; 9830 9831 //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); 9832 //s->pending_buf = (uchf *) overlay; 9833 s.pending_buf = new Buf8(s.pending_buf_size); 9834 9835 // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) 9836 //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); 9837 s.d_buf = 1 * s.lit_bufsize; 9838 9839 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; 9840 s.l_buf = (1 + 2) * s.lit_bufsize; 9841 9842 s.level = level; 9843 s.strategy = strategy; 9844 s.method = method; 9845 9846 return deflateReset(strm); 9847 } 9848 9849 9850 function deflate(strm, flush) { 9851 var old_flush, s; 9852 var beg, val; // for gzip header write only 9853 9854 if (!strm || !strm.state || 9855 flush > Z_BLOCK || flush < 0) { 9856 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; 9857 } 9858 9859 s = strm.state; 9860 9861 if (!strm.output || 9862 (!strm.input && strm.avail_in !== 0) || 9863 (s.status === FINISH_STATE && flush !== Z_FINISH)) { 9864 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); 9865 } 9866 9867 s.strm = strm; /* just in case */ 9868 old_flush = s.last_flush; 9869 s.last_flush = flush; 9870 9871 /* Write the header */ 9872 if (s.status === INIT_STATE) { 9873 if (s.wrap === 2) { 9874 // GZIP header 9875 strm.adler = 0; //crc32(0L, Z_NULL, 0); 9876 put_byte(s, 31); 9877 put_byte(s, 139); 9878 put_byte(s, 8); 9879 if (!s.gzhead) { // s->gzhead == Z_NULL 9880 put_byte(s, 0); 9881 put_byte(s, 0); 9882 put_byte(s, 0); 9883 put_byte(s, 0); 9884 put_byte(s, 0); 9885 put_byte(s, s.level === 9 ? 2 : 9886 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 9887 4 : 0)); 9888 put_byte(s, OS_CODE); 9889 s.status = BUSY_STATE; 9890 } else { 9891 put_byte(s, (s.gzhead.text ? 1 : 0) + 9892 (s.gzhead.hcrc ? 2 : 0) + 9893 (!s.gzhead.extra ? 0 : 4) + 9894 (!s.gzhead.name ? 0 : 8) + 9895 (!s.gzhead.comment ? 0 : 16) 9896 ); 9897 put_byte(s, s.gzhead.time & 0xff); 9898 put_byte(s, (s.gzhead.time >> 8) & 0xff); 9899 put_byte(s, (s.gzhead.time >> 16) & 0xff); 9900 put_byte(s, (s.gzhead.time >> 24) & 0xff); 9901 put_byte(s, s.level === 9 ? 2 : 9902 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 9903 4 : 0)); 9904 put_byte(s, s.gzhead.os & 0xff); 9905 if (s.gzhead.extra && s.gzhead.extra.length) { 9906 put_byte(s, s.gzhead.extra.length & 0xff); 9907 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); 9908 } 9909 if (s.gzhead.hcrc) { 9910 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); 9911 } 9912 s.gzindex = 0; 9913 s.status = EXTRA_STATE; 9914 } 9915 } else // DEFLATE header 9916 { 9917 var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; 9918 var level_flags = -1; 9919 9920 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { 9921 level_flags = 0; 9922 } else if (s.level < 6) { 9923 level_flags = 1; 9924 } else if (s.level === 6) { 9925 level_flags = 2; 9926 } else { 9927 level_flags = 3; 9928 } 9929 header |= (level_flags << 6); 9930 if (s.strstart !== 0) { 9931 header |= PRESET_DICT; 9932 } 9933 header += 31 - (header % 31); 9934 9935 s.status = BUSY_STATE; 9936 putShortMSB(s, header); 9937 9938 /* Save the adler32 of the preset dictionary: */ 9939 if (s.strstart !== 0) { 9940 putShortMSB(s, strm.adler >>> 16); 9941 putShortMSB(s, strm.adler & 0xffff); 9942 } 9943 strm.adler = 1; // adler32(0L, Z_NULL, 0); 9944 } 9945 } 9946 9947 //#ifdef GZIP 9948 if (s.status === EXTRA_STATE) { 9949 if (s.gzhead.extra /* != Z_NULL*/ ) { 9950 beg = s.pending; /* start of bytes to update crc */ 9951 9952 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { 9953 if (s.pending === s.pending_buf_size) { 9954 if (s.gzhead.hcrc && s.pending > beg) { 9955 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 9956 } 9957 flush_pending(strm); 9958 beg = s.pending; 9959 if (s.pending === s.pending_buf_size) { 9960 break; 9961 } 9962 } 9963 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); 9964 s.gzindex++; 9965 } 9966 if (s.gzhead.hcrc && s.pending > beg) { 9967 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 9968 } 9969 if (s.gzindex === s.gzhead.extra.length) { 9970 s.gzindex = 0; 9971 s.status = NAME_STATE; 9972 } 9973 } else { 9974 s.status = NAME_STATE; 9975 } 9976 } 9977 if (s.status === NAME_STATE) { 9978 if (s.gzhead.name /* != Z_NULL*/ ) { 9979 beg = s.pending; /* start of bytes to update crc */ 9980 //int val; 9981 9982 do { 9983 if (s.pending === s.pending_buf_size) { 9984 if (s.gzhead.hcrc && s.pending > beg) { 9985 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 9986 } 9987 flush_pending(strm); 9988 beg = s.pending; 9989 if (s.pending === s.pending_buf_size) { 9990 val = 1; 9991 break; 9992 } 9993 } 9994 // JS specific: little magic to add zero terminator to end of string 9995 if (s.gzindex < s.gzhead.name.length) { 9996 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; 9997 } else { 9998 val = 0; 9999 } 10000 put_byte(s, val); 10001 } while (val !== 0); 10002 10003 if (s.gzhead.hcrc && s.pending > beg) { 10004 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 10005 } 10006 if (val === 0) { 10007 s.gzindex = 0; 10008 s.status = COMMENT_STATE; 10009 } 10010 } else { 10011 s.status = COMMENT_STATE; 10012 } 10013 } 10014 if (s.status === COMMENT_STATE) { 10015 if (s.gzhead.comment /* != Z_NULL*/ ) { 10016 beg = s.pending; /* start of bytes to update crc */ 10017 //int val; 10018 10019 do { 10020 if (s.pending === s.pending_buf_size) { 10021 if (s.gzhead.hcrc && s.pending > beg) { 10022 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 10023 } 10024 flush_pending(strm); 10025 beg = s.pending; 10026 if (s.pending === s.pending_buf_size) { 10027 val = 1; 10028 break; 10029 } 10030 } 10031 // JS specific: little magic to add zero terminator to end of string 10032 if (s.gzindex < s.gzhead.comment.length) { 10033 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; 10034 } else { 10035 val = 0; 10036 } 10037 put_byte(s, val); 10038 } while (val !== 0); 10039 10040 if (s.gzhead.hcrc && s.pending > beg) { 10041 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); 10042 } 10043 if (val === 0) { 10044 s.status = HCRC_STATE; 10045 } 10046 } else { 10047 s.status = HCRC_STATE; 10048 } 10049 } 10050 if (s.status === HCRC_STATE) { 10051 if (s.gzhead.hcrc) { 10052 if (s.pending + 2 > s.pending_buf_size) { 10053 flush_pending(strm); 10054 } 10055 if (s.pending + 2 <= s.pending_buf_size) { 10056 put_byte(s, strm.adler & 0xff); 10057 put_byte(s, (strm.adler >> 8) & 0xff); 10058 strm.adler = 0; //crc32(0L, Z_NULL, 0); 10059 s.status = BUSY_STATE; 10060 } 10061 } else { 10062 s.status = BUSY_STATE; 10063 } 10064 } 10065 //#endif 10066 10067 /* Flush as much pending output as possible */ 10068 if (s.pending !== 0) { 10069 flush_pending(strm); 10070 if (strm.avail_out === 0) { 10071 /* Since avail_out is 0, deflate will be called again with 10072 * more output space, but possibly with both pending and 10073 * avail_in equal to zero. There won't be anything to do, 10074 * but this is not an error situation so make sure we 10075 * return OK instead of BUF_ERROR at next call of deflate: 10076 */ 10077 s.last_flush = -1; 10078 return Z_OK; 10079 } 10080 10081 /* Make sure there is something to do and avoid duplicate consecutive 10082 * flushes. For repeated and useless calls with Z_FINISH, we keep 10083 * returning Z_STREAM_END instead of Z_BUF_ERROR. 10084 */ 10085 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && 10086 flush !== Z_FINISH) { 10087 return err(strm, Z_BUF_ERROR); 10088 } 10089 10090 /* User must not provide more input after the first FINISH: */ 10091 if (s.status === FINISH_STATE && strm.avail_in !== 0) { 10092 return err(strm, Z_BUF_ERROR); 10093 } 10094 10095 /* Start a new block or continue the current one. 10096 */ 10097 if (strm.avail_in !== 0 || s.lookahead !== 0 || 10098 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { 10099 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : 10100 (s.strategy === Z_RLE ? deflate_rle(s, flush) : 10101 configuration_table[s.level].func(s, flush)); 10102 10103 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { 10104 s.status = FINISH_STATE; 10105 } 10106 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { 10107 if (strm.avail_out === 0) { 10108 s.last_flush = -1; 10109 /* avoid BUF_ERROR next call, see above */ 10110 } 10111 return Z_OK; 10112 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call 10113 * of deflate should use the same flush parameter to make sure 10114 * that the flush is complete. So we don't have to output an 10115 * empty block here, this will be done at next call. This also 10116 * ensures that for a very small output buffer, we emit at most 10117 * one empty block. 10118 */ 10119 } 10120 if (bstate === BS_BLOCK_DONE) { 10121 if (flush === Z_PARTIAL_FLUSH) { 10122 _tr_align(s); 10123 } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ 10124 10125 _tr_stored_block(s, 0, 0, false); 10126 /* For a full flush, this empty block will be recognized 10127 * as a special marker by inflate_sync(). 10128 */ 10129 if (flush === Z_FULL_FLUSH) { 10130 /*** CLEAR_HASH(s); ***/ 10131 /* forget history */ 10132 zero$1(s.head); // Fill with NIL (= 0); 10133 10134 if (s.lookahead === 0) { 10135 s.strstart = 0; 10136 s.block_start = 0; 10137 s.insert = 0; 10138 } 10139 } 10140 } 10141 flush_pending(strm); 10142 if (strm.avail_out === 0) { 10143 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ 10144 return Z_OK; 10145 } 10146 } 10147 } 10148 //Assert(strm->avail_out > 0, "bug2"); 10149 //if (strm.avail_out <= 0) { throw new Error("bug2");} 10150 10151 if (flush !== Z_FINISH) { 10152 return Z_OK; 10153 } 10154 if (s.wrap <= 0) { 10155 return Z_STREAM_END; 10156 } 10157 10158 /* Write the trailer */ 10159 if (s.wrap === 2) { 10160 put_byte(s, strm.adler & 0xff); 10161 put_byte(s, (strm.adler >> 8) & 0xff); 10162 put_byte(s, (strm.adler >> 16) & 0xff); 10163 put_byte(s, (strm.adler >> 24) & 0xff); 10164 put_byte(s, strm.total_in & 0xff); 10165 put_byte(s, (strm.total_in >> 8) & 0xff); 10166 put_byte(s, (strm.total_in >> 16) & 0xff); 10167 put_byte(s, (strm.total_in >> 24) & 0xff); 10168 } else { 10169 putShortMSB(s, strm.adler >>> 16); 10170 putShortMSB(s, strm.adler & 0xffff); 10171 } 10172 10173 flush_pending(strm); 10174 /* If avail_out is zero, the application will call deflate again 10175 * to flush the rest. 10176 */ 10177 if (s.wrap > 0) { 10178 s.wrap = -s.wrap; 10179 } 10180 /* write the trailer only once! */ 10181 return s.pending !== 0 ? Z_OK : Z_STREAM_END; 10182 } 10183 10184 function deflateEnd(strm) { 10185 var status; 10186 10187 if (!strm /*== Z_NULL*/ || !strm.state /*== Z_NULL*/ ) { 10188 return Z_STREAM_ERROR; 10189 } 10190 10191 status = strm.state.status; 10192 if (status !== INIT_STATE && 10193 status !== EXTRA_STATE && 10194 status !== NAME_STATE && 10195 status !== COMMENT_STATE && 10196 status !== HCRC_STATE && 10197 status !== BUSY_STATE && 10198 status !== FINISH_STATE 10199 ) { 10200 return err(strm, Z_STREAM_ERROR); 10201 } 10202 10203 strm.state = null; 10204 10205 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; 10206 } 10207 10208 /* Not implemented 10209 exports.deflateBound = deflateBound; 10210 exports.deflateCopy = deflateCopy; 10211 exports.deflateParams = deflateParams; 10212 exports.deflatePending = deflatePending; 10213 exports.deflatePrime = deflatePrime; 10214 exports.deflateTune = deflateTune; 10215 */ 10216 10217 // See state defs from inflate.js 10218 var BAD = 30; /* got a data error -- remain here until reset */ 10219 var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ 10220 10221 /* 10222 Decode literal, length, and distance codes and write out the resulting 10223 literal and match bytes until either not enough input or output is 10224 available, an end-of-block is encountered, or a data error is encountered. 10225 When large enough input and output buffers are supplied to inflate(), for 10226 example, a 16K input buffer and a 64K output buffer, more than 95% of the 10227 inflate execution time is spent in this routine. 10228 10229 Entry assumptions: 10230 10231 state.mode === LEN 10232 strm.avail_in >= 6 10233 strm.avail_out >= 258 10234 start >= strm.avail_out 10235 state.bits < 8 10236 10237 On return, state.mode is one of: 10238 10239 LEN -- ran out of enough output space or enough available input 10240 TYPE -- reached end of block code, inflate() to interpret next block 10241 BAD -- error in block data 10242 10243 Notes: 10244 10245 - The maximum input bits used by a length/distance pair is 15 bits for the 10246 length code, 5 bits for the length extra, 15 bits for the distance code, 10247 and 13 bits for the distance extra. This totals 48 bits, or six bytes. 10248 Therefore if strm.avail_in >= 6, then there is enough input to avoid 10249 checking for available input while decoding. 10250 10251 - The maximum bytes that a single length/distance pair can output is 258 10252 bytes, which is the maximum length that can be coded. inflate_fast() 10253 requires strm.avail_out >= 258 for each loop to avoid checking for 10254 output space. 10255 */ 10256 function inflate_fast(strm, start) { 10257 var state; 10258 var _in; /* local strm.input */ 10259 var last; /* have enough input while in < last */ 10260 var _out; /* local strm.output */ 10261 var beg; /* inflate()'s initial strm.output */ 10262 var end; /* while out < end, enough space available */ 10263 //#ifdef INFLATE_STRICT 10264 var dmax; /* maximum distance from zlib header */ 10265 //#endif 10266 var wsize; /* window size or zero if not using window */ 10267 var whave; /* valid bytes in the window */ 10268 var wnext; /* window write index */ 10269 // Use `s_window` instead `window`, avoid conflict with instrumentation tools 10270 var s_window; /* allocated sliding window, if wsize != 0 */ 10271 var hold; /* local strm.hold */ 10272 var bits; /* local strm.bits */ 10273 var lcode; /* local strm.lencode */ 10274 var dcode; /* local strm.distcode */ 10275 var lmask; /* mask for first level of length codes */ 10276 var dmask; /* mask for first level of distance codes */ 10277 var here; /* retrieved table entry */ 10278 var op; /* code bits, operation, extra bits, or */ 10279 /* window position, window bytes to copy */ 10280 var len; /* match length, unused bytes */ 10281 var dist; /* match distance */ 10282 var from; /* where to copy match from */ 10283 var from_source; 10284 10285 10286 var input, output; // JS specific, because we have no pointers 10287 10288 /* copy state to local variables */ 10289 state = strm.state; 10290 //here = state.here; 10291 _in = strm.next_in; 10292 input = strm.input; 10293 last = _in + (strm.avail_in - 5); 10294 _out = strm.next_out; 10295 output = strm.output; 10296 beg = _out - (start - strm.avail_out); 10297 end = _out + (strm.avail_out - 257); 10298 //#ifdef INFLATE_STRICT 10299 dmax = state.dmax; 10300 //#endif 10301 wsize = state.wsize; 10302 whave = state.whave; 10303 wnext = state.wnext; 10304 s_window = state.window; 10305 hold = state.hold; 10306 bits = state.bits; 10307 lcode = state.lencode; 10308 dcode = state.distcode; 10309 lmask = (1 << state.lenbits) - 1; 10310 dmask = (1 << state.distbits) - 1; 10311 10312 10313 /* decode literals and length/distances until end-of-block or not enough 10314 input data or output space */ 10315 10316 top: 10317 do { 10318 if (bits < 15) { 10319 hold += input[_in++] << bits; 10320 bits += 8; 10321 hold += input[_in++] << bits; 10322 bits += 8; 10323 } 10324 10325 here = lcode[hold & lmask]; 10326 10327 dolen: 10328 for (;;) { // Goto emulation 10329 op = here >>> 24/*here.bits*/; 10330 hold >>>= op; 10331 bits -= op; 10332 op = (here >>> 16) & 0xff/*here.op*/; 10333 if (op === 0) { /* literal */ 10334 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? 10335 // "inflate: literal '%c'\n" : 10336 // "inflate: literal 0x%02x\n", here.val)); 10337 output[_out++] = here & 0xffff/*here.val*/; 10338 } 10339 else if (op & 16) { /* length base */ 10340 len = here & 0xffff/*here.val*/; 10341 op &= 15; /* number of extra bits */ 10342 if (op) { 10343 if (bits < op) { 10344 hold += input[_in++] << bits; 10345 bits += 8; 10346 } 10347 len += hold & ((1 << op) - 1); 10348 hold >>>= op; 10349 bits -= op; 10350 } 10351 //Tracevv((stderr, "inflate: length %u\n", len)); 10352 if (bits < 15) { 10353 hold += input[_in++] << bits; 10354 bits += 8; 10355 hold += input[_in++] << bits; 10356 bits += 8; 10357 } 10358 here = dcode[hold & dmask]; 10359 10360 dodist: 10361 for (;;) { // goto emulation 10362 op = here >>> 24/*here.bits*/; 10363 hold >>>= op; 10364 bits -= op; 10365 op = (here >>> 16) & 0xff/*here.op*/; 10366 10367 if (op & 16) { /* distance base */ 10368 dist = here & 0xffff/*here.val*/; 10369 op &= 15; /* number of extra bits */ 10370 if (bits < op) { 10371 hold += input[_in++] << bits; 10372 bits += 8; 10373 if (bits < op) { 10374 hold += input[_in++] << bits; 10375 bits += 8; 10376 } 10377 } 10378 dist += hold & ((1 << op) - 1); 10379 //#ifdef INFLATE_STRICT 10380 if (dist > dmax) { 10381 strm.msg = 'invalid distance too far back'; 10382 state.mode = BAD; 10383 break top; 10384 } 10385 //#endif 10386 hold >>>= op; 10387 bits -= op; 10388 //Tracevv((stderr, "inflate: distance %u\n", dist)); 10389 op = _out - beg; /* max distance in output */ 10390 if (dist > op) { /* see if copy from window */ 10391 op = dist - op; /* distance back in window */ 10392 if (op > whave) { 10393 if (state.sane) { 10394 strm.msg = 'invalid distance too far back'; 10395 state.mode = BAD; 10396 break top; 10397 } 10398 10399 // (!) This block is disabled in zlib defailts, 10400 // don't enable it for binary compatibility 10401 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR 10402 // if (len <= op - whave) { 10403 // do { 10404 // output[_out++] = 0; 10405 // } while (--len); 10406 // continue top; 10407 // } 10408 // len -= op - whave; 10409 // do { 10410 // output[_out++] = 0; 10411 // } while (--op > whave); 10412 // if (op === 0) { 10413 // from = _out - dist; 10414 // do { 10415 // output[_out++] = output[from++]; 10416 // } while (--len); 10417 // continue top; 10418 // } 10419 //#endif 10420 } 10421 from = 0; // window index 10422 from_source = s_window; 10423 if (wnext === 0) { /* very common case */ 10424 from += wsize - op; 10425 if (op < len) { /* some from window */ 10426 len -= op; 10427 do { 10428 output[_out++] = s_window[from++]; 10429 } while (--op); 10430 from = _out - dist; /* rest from output */ 10431 from_source = output; 10432 } 10433 } 10434 else if (wnext < op) { /* wrap around window */ 10435 from += wsize + wnext - op; 10436 op -= wnext; 10437 if (op < len) { /* some from end of window */ 10438 len -= op; 10439 do { 10440 output[_out++] = s_window[from++]; 10441 } while (--op); 10442 from = 0; 10443 if (wnext < len) { /* some from start of window */ 10444 op = wnext; 10445 len -= op; 10446 do { 10447 output[_out++] = s_window[from++]; 10448 } while (--op); 10449 from = _out - dist; /* rest from output */ 10450 from_source = output; 10451 } 10452 } 10453 } 10454 else { /* contiguous in window */ 10455 from += wnext - op; 10456 if (op < len) { /* some from window */ 10457 len -= op; 10458 do { 10459 output[_out++] = s_window[from++]; 10460 } while (--op); 10461 from = _out - dist; /* rest from output */ 10462 from_source = output; 10463 } 10464 } 10465 while (len > 2) { 10466 output[_out++] = from_source[from++]; 10467 output[_out++] = from_source[from++]; 10468 output[_out++] = from_source[from++]; 10469 len -= 3; 10470 } 10471 if (len) { 10472 output[_out++] = from_source[from++]; 10473 if (len > 1) { 10474 output[_out++] = from_source[from++]; 10475 } 10476 } 10477 } 10478 else { 10479 from = _out - dist; /* copy direct from output */ 10480 do { /* minimum length is three */ 10481 output[_out++] = output[from++]; 10482 output[_out++] = output[from++]; 10483 output[_out++] = output[from++]; 10484 len -= 3; 10485 } while (len > 2); 10486 if (len) { 10487 output[_out++] = output[from++]; 10488 if (len > 1) { 10489 output[_out++] = output[from++]; 10490 } 10491 } 10492 } 10493 } 10494 else if ((op & 64) === 0) { /* 2nd level distance code */ 10495 here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; 10496 continue dodist; 10497 } 10498 else { 10499 strm.msg = 'invalid distance code'; 10500 state.mode = BAD; 10501 break top; 10502 } 10503 10504 break; // need to emulate goto via "continue" 10505 } 10506 } 10507 else if ((op & 64) === 0) { /* 2nd level length code */ 10508 here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; 10509 continue dolen; 10510 } 10511 else if (op & 32) { /* end-of-block */ 10512 //Tracevv((stderr, "inflate: end of block\n")); 10513 state.mode = TYPE; 10514 break top; 10515 } 10516 else { 10517 strm.msg = 'invalid literal/length code'; 10518 state.mode = BAD; 10519 break top; 10520 } 10521 10522 break; // need to emulate goto via "continue" 10523 } 10524 } while (_in < last && _out < end); 10525 10526 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ 10527 len = bits >> 3; 10528 _in -= len; 10529 bits -= len << 3; 10530 hold &= (1 << bits) - 1; 10531 10532 /* update state and return */ 10533 strm.next_in = _in; 10534 strm.next_out = _out; 10535 strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); 10536 strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); 10537 state.hold = hold; 10538 state.bits = bits; 10539 return; 10540 } 10541 10542 var MAXBITS = 15; 10543 var ENOUGH_LENS = 852; 10544 var ENOUGH_DISTS = 592; 10545 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); 10546 10547 var CODES = 0; 10548 var LENS = 1; 10549 var DISTS = 2; 10550 10551 var lbase = [ /* Length codes 257..285 base */ 10552 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 10553 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 10554 ]; 10555 10556 var lext = [ /* Length codes 257..285 extra */ 10557 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 10558 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 10559 ]; 10560 10561 var dbase = [ /* Distance codes 0..29 base */ 10562 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 10563 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 10564 8193, 12289, 16385, 24577, 0, 0 10565 ]; 10566 10567 var dext = [ /* Distance codes 0..29 extra */ 10568 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 10569 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 10570 28, 28, 29, 29, 64, 64 10571 ]; 10572 10573 function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { 10574 var bits = opts.bits; 10575 //here = opts.here; /* table entry for duplication */ 10576 10577 var len = 0; /* a code's length in bits */ 10578 var sym = 0; /* index of code symbols */ 10579 var min = 0, 10580 max = 0; /* minimum and maximum code lengths */ 10581 var root = 0; /* number of index bits for root table */ 10582 var curr = 0; /* number of index bits for current table */ 10583 var drop = 0; /* code bits to drop for sub-table */ 10584 var left = 0; /* number of prefix codes available */ 10585 var used = 0; /* code entries in table used */ 10586 var huff = 0; /* Huffman code */ 10587 var incr; /* for incrementing code, index */ 10588 var fill; /* index for replicating entries */ 10589 var low; /* low bits for current root entry */ 10590 var mask; /* mask for low root bits */ 10591 var next; /* next available space in table */ 10592 var base = null; /* base value table to use */ 10593 var base_index = 0; 10594 // var shoextra; /* extra bits table to use */ 10595 var end; /* use base and extra for symbol > end */ 10596 var count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ 10597 var offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ 10598 var extra = null; 10599 var extra_index = 0; 10600 10601 var here_bits, here_op, here_val; 10602 10603 /* 10604 Process a set of code lengths to create a canonical Huffman code. The 10605 code lengths are lens[0..codes-1]. Each length corresponds to the 10606 symbols 0..codes-1. The Huffman code is generated by first sorting the 10607 symbols by length from short to long, and retaining the symbol order 10608 for codes with equal lengths. Then the code starts with all zero bits 10609 for the first code of the shortest length, and the codes are integer 10610 increments for the same length, and zeros are appended as the length 10611 increases. For the deflate format, these bits are stored backwards 10612 from their more natural integer increment ordering, and so when the 10613 decoding tables are built in the large loop below, the integer codes 10614 are incremented backwards. 10615 10616 This routine assumes, but does not check, that all of the entries in 10617 lens[] are in the range 0..MAXBITS. The caller must assure this. 10618 1..MAXBITS is interpreted as that code length. zero means that that 10619 symbol does not occur in this code. 10620 10621 The codes are sorted by computing a count of codes for each length, 10622 creating from that a table of starting indices for each length in the 10623 sorted table, and then entering the symbols in order in the sorted 10624 table. The sorted table is work[], with that space being provided by 10625 the caller. 10626 10627 The length counts are used for other purposes as well, i.e. finding 10628 the minimum and maximum length codes, determining if there are any 10629 codes at all, checking for a valid set of lengths, and looking ahead 10630 at length counts to determine sub-table sizes when building the 10631 decoding tables. 10632 */ 10633 10634 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ 10635 for (len = 0; len <= MAXBITS; len++) { 10636 count[len] = 0; 10637 } 10638 for (sym = 0; sym < codes; sym++) { 10639 count[lens[lens_index + sym]]++; 10640 } 10641 10642 /* bound code lengths, force root to be within code lengths */ 10643 root = bits; 10644 for (max = MAXBITS; max >= 1; max--) { 10645 if (count[max] !== 0) { 10646 break; 10647 } 10648 } 10649 if (root > max) { 10650 root = max; 10651 } 10652 if (max === 0) { /* no symbols to code at all */ 10653 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ 10654 //table.bits[opts.table_index] = 1; //here.bits = (var char)1; 10655 //table.val[opts.table_index++] = 0; //here.val = (var short)0; 10656 table[table_index++] = (1 << 24) | (64 << 16) | 0; 10657 10658 10659 //table.op[opts.table_index] = 64; 10660 //table.bits[opts.table_index] = 1; 10661 //table.val[opts.table_index++] = 0; 10662 table[table_index++] = (1 << 24) | (64 << 16) | 0; 10663 10664 opts.bits = 1; 10665 return 0; /* no symbols, but wait for decoding to report error */ 10666 } 10667 for (min = 1; min < max; min++) { 10668 if (count[min] !== 0) { 10669 break; 10670 } 10671 } 10672 if (root < min) { 10673 root = min; 10674 } 10675 10676 /* check for an over-subscribed or incomplete set of lengths */ 10677 left = 1; 10678 for (len = 1; len <= MAXBITS; len++) { 10679 left <<= 1; 10680 left -= count[len]; 10681 if (left < 0) { 10682 return -1; 10683 } /* over-subscribed */ 10684 } 10685 if (left > 0 && (type === CODES || max !== 1)) { 10686 return -1; /* incomplete set */ 10687 } 10688 10689 /* generate offsets into symbol table for each length for sorting */ 10690 offs[1] = 0; 10691 for (len = 1; len < MAXBITS; len++) { 10692 offs[len + 1] = offs[len] + count[len]; 10693 } 10694 10695 /* sort symbols by length, by symbol order within each length */ 10696 for (sym = 0; sym < codes; sym++) { 10697 if (lens[lens_index + sym] !== 0) { 10698 work[offs[lens[lens_index + sym]]++] = sym; 10699 } 10700 } 10701 10702 /* 10703 Create and fill in decoding tables. In this loop, the table being 10704 filled is at next and has curr index bits. The code being used is huff 10705 with length len. That code is converted to an index by dropping drop 10706 bits off of the bottom. For codes where len is less than drop + curr, 10707 those top drop + curr - len bits are incremented through all values to 10708 fill the table with replicated entries. 10709 10710 root is the number of index bits for the root table. When len exceeds 10711 root, sub-tables are created pointed to by the root entry with an index 10712 of the low root bits of huff. This is saved in low to check for when a 10713 new sub-table should be started. drop is zero when the root table is 10714 being filled, and drop is root when sub-tables are being filled. 10715 10716 When a new sub-table is needed, it is necessary to look ahead in the 10717 code lengths to determine what size sub-table is needed. The length 10718 counts are used for this, and so count[] is decremented as codes are 10719 entered in the tables. 10720 10721 used keeps track of how many table entries have been allocated from the 10722 provided *table space. It is checked for LENS and DIST tables against 10723 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in 10724 the initial root table size constants. See the comments in inftrees.h 10725 for more information. 10726 10727 sym increments through all symbols, and the loop terminates when 10728 all codes of length max, i.e. all codes, have been processed. This 10729 routine permits incomplete codes, so another loop after this one fills 10730 in the rest of the decoding tables with invalid code markers. 10731 */ 10732 10733 /* set up for code type */ 10734 // poor man optimization - use if-else instead of switch, 10735 // to avoid deopts in old v8 10736 if (type === CODES) { 10737 base = extra = work; /* dummy value--not used */ 10738 end = 19; 10739 10740 } else if (type === LENS) { 10741 base = lbase; 10742 base_index -= 257; 10743 extra = lext; 10744 extra_index -= 257; 10745 end = 256; 10746 10747 } else { /* DISTS */ 10748 base = dbase; 10749 extra = dext; 10750 end = -1; 10751 } 10752 10753 /* initialize opts for loop */ 10754 huff = 0; /* starting code */ 10755 sym = 0; /* starting code symbol */ 10756 len = min; /* starting code length */ 10757 next = table_index; /* current table to fill in */ 10758 curr = root; /* current table index bits */ 10759 drop = 0; /* current bits to drop from code for index */ 10760 low = -1; /* trigger new sub-table when len > root */ 10761 used = 1 << root; /* use root table entries */ 10762 mask = used - 1; /* mask for comparing low */ 10763 10764 /* check available table space */ 10765 if ((type === LENS && used > ENOUGH_LENS) || 10766 (type === DISTS && used > ENOUGH_DISTS)) { 10767 return 1; 10768 } 10769 /* process all codes and make table entries */ 10770 for (;;) { 10771 /* create table entry */ 10772 here_bits = len - drop; 10773 if (work[sym] < end) { 10774 here_op = 0; 10775 here_val = work[sym]; 10776 } else if (work[sym] > end) { 10777 here_op = extra[extra_index + work[sym]]; 10778 here_val = base[base_index + work[sym]]; 10779 } else { 10780 here_op = 32 + 64; /* end of block */ 10781 here_val = 0; 10782 } 10783 10784 /* replicate for those indices with low len bits equal to huff */ 10785 incr = 1 << (len - drop); 10786 fill = 1 << curr; 10787 min = fill; /* save offset to next table */ 10788 do { 10789 fill -= incr; 10790 table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val | 0; 10791 } while (fill !== 0); 10792 10793 /* backwards increment the len-bit code huff */ 10794 incr = 1 << (len - 1); 10795 while (huff & incr) { 10796 incr >>= 1; 10797 } 10798 if (incr !== 0) { 10799 huff &= incr - 1; 10800 huff += incr; 10801 } else { 10802 huff = 0; 10803 } 10804 10805 /* go to next symbol, update count, len */ 10806 sym++; 10807 if (--count[len] === 0) { 10808 if (len === max) { 10809 break; 10810 } 10811 len = lens[lens_index + work[sym]]; 10812 } 10813 10814 /* create new sub-table if needed */ 10815 if (len > root && (huff & mask) !== low) { 10816 /* if first time, transition to sub-tables */ 10817 if (drop === 0) { 10818 drop = root; 10819 } 10820 10821 /* increment past last table */ 10822 next += min; /* here min is 1 << curr */ 10823 10824 /* determine length of next table */ 10825 curr = len - drop; 10826 left = 1 << curr; 10827 while (curr + drop < max) { 10828 left -= count[curr + drop]; 10829 if (left <= 0) { 10830 break; 10831 } 10832 curr++; 10833 left <<= 1; 10834 } 10835 10836 /* check for enough space */ 10837 used += 1 << curr; 10838 if ((type === LENS && used > ENOUGH_LENS) || 10839 (type === DISTS && used > ENOUGH_DISTS)) { 10840 return 1; 10841 } 10842 10843 /* point entry in root table to sub-table */ 10844 low = huff & mask; 10845 /*table.op[low] = curr; 10846 table.bits[low] = root; 10847 table.val[low] = next - opts.table_index;*/ 10848 table[low] = (root << 24) | (curr << 16) | (next - table_index) | 0; 10849 } 10850 } 10851 10852 /* fill in remaining table entry if code is incomplete (guaranteed to have 10853 at most one remaining entry, since if the code is incomplete, the 10854 maximum code length that was allowed to get this far is one bit) */ 10855 if (huff !== 0) { 10856 //table.op[next + huff] = 64; /* invalid code marker */ 10857 //table.bits[next + huff] = len - drop; 10858 //table.val[next + huff] = 0; 10859 table[next + huff] = ((len - drop) << 24) | (64 << 16) | 0; 10860 } 10861 10862 /* set return parameters */ 10863 //opts.table_index += used; 10864 opts.bits = root; 10865 return 0; 10866 } 10867 10868 var CODES$1 = 0; 10869 var LENS$1 = 1; 10870 var DISTS$1 = 2; 10871 10872 /* Public constants ==========================================================*/ 10873 /* ===========================================================================*/ 10874 10875 10876 /* Allowed flush values; see deflate() and inflate() below for details */ 10877 //var Z_NO_FLUSH = 0; 10878 //var Z_PARTIAL_FLUSH = 1; 10879 //var Z_SYNC_FLUSH = 2; 10880 //var Z_FULL_FLUSH = 3; 10881 var Z_FINISH$1 = 4; 10882 var Z_BLOCK$1 = 5; 10883 var Z_TREES = 6; 10884 10885 10886 /* Return codes for the compression/decompression functions. Negative values 10887 * are errors, positive values are used for special but normal events. 10888 */ 10889 var Z_OK$1 = 0; 10890 var Z_STREAM_END$1 = 1; 10891 var Z_NEED_DICT = 2; 10892 //var Z_ERRNO = -1; 10893 var Z_STREAM_ERROR$1 = -2; 10894 var Z_DATA_ERROR$1 = -3; 10895 var Z_MEM_ERROR = -4; 10896 var Z_BUF_ERROR$1 = -5; 10897 //var Z_VERSION_ERROR = -6; 10898 10899 /* The deflate compression method */ 10900 var Z_DEFLATED$1 = 8; 10901 10902 10903 /* STATES ====================================================================*/ 10904 /* ===========================================================================*/ 10905 10906 10907 var HEAD = 1; /* i: waiting for magic header */ 10908 var FLAGS = 2; /* i: waiting for method and flags (gzip) */ 10909 var TIME = 3; /* i: waiting for modification time (gzip) */ 10910 var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ 10911 var EXLEN = 5; /* i: waiting for extra length (gzip) */ 10912 var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ 10913 var NAME = 7; /* i: waiting for end of file name (gzip) */ 10914 var COMMENT = 8; /* i: waiting for end of comment (gzip) */ 10915 var HCRC = 9; /* i: waiting for header crc (gzip) */ 10916 var DICTID = 10; /* i: waiting for dictionary check value */ 10917 var DICT = 11; /* waiting for inflateSetDictionary() call */ 10918 var TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ 10919 var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ 10920 var STORED = 14; /* i: waiting for stored size (length and complement) */ 10921 var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ 10922 var COPY = 16; /* i/o: waiting for input or output to copy stored block */ 10923 var TABLE = 17; /* i: waiting for dynamic block table lengths */ 10924 var LENLENS = 18; /* i: waiting for code length code lengths */ 10925 var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ 10926 var LEN_ = 20; /* i: same as LEN below, but only first time in */ 10927 var LEN = 21; /* i: waiting for length/lit/eob code */ 10928 var LENEXT = 22; /* i: waiting for length extra bits */ 10929 var DIST = 23; /* i: waiting for distance code */ 10930 var DISTEXT = 24; /* i: waiting for distance extra bits */ 10931 var MATCH = 25; /* o: waiting for output space to copy string */ 10932 var LIT = 26; /* o: waiting for output space to write literal */ 10933 var CHECK = 27; /* i: waiting for 32-bit check value */ 10934 var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ 10935 var DONE = 29; /* finished check, done -- remain here until reset */ 10936 var BAD$1 = 30; /* got a data error -- remain here until reset */ 10937 var MEM = 31; /* got an inflate() memory error -- remain here until reset */ 10938 var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ 10939 10940 /* ===========================================================================*/ 10941 10942 10943 10944 var ENOUGH_LENS$1 = 852; 10945 var ENOUGH_DISTS$1 = 592; 10946 10947 10948 function zswap32(q) { 10949 return (((q >>> 24) & 0xff) + 10950 ((q >>> 8) & 0xff00) + 10951 ((q & 0xff00) << 8) + 10952 ((q & 0xff) << 24)); 10953 } 10954 10955 10956 function InflateState() { 10957 this.mode = 0; /* current inflate mode */ 10958 this.last = false; /* true if processing last block */ 10959 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ 10960 this.havedict = false; /* true if dictionary provided */ 10961 this.flags = 0; /* gzip header method and flags (0 if zlib) */ 10962 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ 10963 this.check = 0; /* protected copy of check value */ 10964 this.total = 0; /* protected copy of output count */ 10965 // TODO: may be {} 10966 this.head = null; /* where to save gzip header information */ 10967 10968 /* sliding window */ 10969 this.wbits = 0; /* log base 2 of requested window size */ 10970 this.wsize = 0; /* window size or zero if not using window */ 10971 this.whave = 0; /* valid bytes in the window */ 10972 this.wnext = 0; /* window write index */ 10973 this.window = null; /* allocated sliding window, if needed */ 10974 10975 /* bit accumulator */ 10976 this.hold = 0; /* input bit accumulator */ 10977 this.bits = 0; /* number of bits in "in" */ 10978 10979 /* for string and stored block copying */ 10980 this.length = 0; /* literal or length of data to copy */ 10981 this.offset = 0; /* distance back to copy string from */ 10982 10983 /* for table and code decoding */ 10984 this.extra = 0; /* extra bits needed */ 10985 10986 /* fixed and dynamic code tables */ 10987 this.lencode = null; /* starting table for length/literal codes */ 10988 this.distcode = null; /* starting table for distance codes */ 10989 this.lenbits = 0; /* index bits for lencode */ 10990 this.distbits = 0; /* index bits for distcode */ 10991 10992 /* dynamic table building */ 10993 this.ncode = 0; /* number of code length code lengths */ 10994 this.nlen = 0; /* number of length code lengths */ 10995 this.ndist = 0; /* number of distance code lengths */ 10996 this.have = 0; /* number of code lengths in lens[] */ 10997 this.next = null; /* next available space in codes[] */ 10998 10999 this.lens = new Buf16(320); /* temporary storage for code lengths */ 11000 this.work = new Buf16(288); /* work area for code table building */ 11001 11002 /* 11003 because we don't have pointers in js, we use lencode and distcode directly 11004 as buffers so we don't need codes 11005 */ 11006 //this.codes = new Buf32(ENOUGH); /* space for code tables */ 11007 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ 11008 this.distdyn = null; /* dynamic table for distance codes (JS specific) */ 11009 this.sane = 0; /* if false, allow invalid distance too far */ 11010 this.back = 0; /* bits back of last unprocessed length/lit */ 11011 this.was = 0; /* initial length of match */ 11012 } 11013 11014 function inflateResetKeep(strm) { 11015 var state; 11016 11017 if (!strm || !strm.state) { 11018 return Z_STREAM_ERROR$1; 11019 } 11020 state = strm.state; 11021 strm.total_in = strm.total_out = state.total = 0; 11022 strm.msg = ''; /*Z_NULL*/ 11023 if (state.wrap) { /* to support ill-conceived Java test suite */ 11024 strm.adler = state.wrap & 1; 11025 } 11026 state.mode = HEAD; 11027 state.last = 0; 11028 state.havedict = 0; 11029 state.dmax = 32768; 11030 state.head = null /*Z_NULL*/ ; 11031 state.hold = 0; 11032 state.bits = 0; 11033 //state.lencode = state.distcode = state.next = state.codes; 11034 state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1); 11035 state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1); 11036 11037 state.sane = 1; 11038 state.back = -1; 11039 //Tracev((stderr, "inflate: reset\n")); 11040 return Z_OK$1; 11041 } 11042 11043 function inflateReset(strm) { 11044 var state; 11045 11046 if (!strm || !strm.state) { 11047 return Z_STREAM_ERROR$1; 11048 } 11049 state = strm.state; 11050 state.wsize = 0; 11051 state.whave = 0; 11052 state.wnext = 0; 11053 return inflateResetKeep(strm); 11054 11055 } 11056 11057 function inflateReset2(strm, windowBits) { 11058 var wrap; 11059 var state; 11060 11061 /* get the state */ 11062 if (!strm || !strm.state) { 11063 return Z_STREAM_ERROR$1; 11064 } 11065 state = strm.state; 11066 11067 /* extract wrap request from windowBits parameter */ 11068 if (windowBits < 0) { 11069 wrap = 0; 11070 windowBits = -windowBits; 11071 } else { 11072 wrap = (windowBits >> 4) + 1; 11073 if (windowBits < 48) { 11074 windowBits &= 15; 11075 } 11076 } 11077 11078 /* set number of window bits, free window if different */ 11079 if (windowBits && (windowBits < 8 || windowBits > 15)) { 11080 return Z_STREAM_ERROR$1; 11081 } 11082 if (state.window !== null && state.wbits !== windowBits) { 11083 state.window = null; 11084 } 11085 11086 /* update state and reset the rest of it */ 11087 state.wrap = wrap; 11088 state.wbits = windowBits; 11089 return inflateReset(strm); 11090 } 11091 11092 function inflateInit2(strm, windowBits) { 11093 var ret; 11094 var state; 11095 11096 if (!strm) { 11097 return Z_STREAM_ERROR$1; 11098 } 11099 //strm.msg = Z_NULL; /* in case we return an error */ 11100 11101 state = new InflateState(); 11102 11103 //if (state === Z_NULL) return Z_MEM_ERROR; 11104 //Tracev((stderr, "inflate: allocated\n")); 11105 strm.state = state; 11106 state.window = null /*Z_NULL*/ ; 11107 ret = inflateReset2(strm, windowBits); 11108 if (ret !== Z_OK$1) { 11109 strm.state = null /*Z_NULL*/ ; 11110 } 11111 return ret; 11112 } 11113 11114 11115 /* 11116 Return state with length and distance decoding tables and index sizes set to 11117 fixed code decoding. Normally this returns fixed tables from inffixed.h. 11118 If BUILDFIXED is defined, then instead this routine builds the tables the 11119 first time it's called, and returns those tables the first time and 11120 thereafter. This reduces the size of the code by about 2K bytes, in 11121 exchange for a little execution time. However, BUILDFIXED should not be 11122 used for threaded applications, since the rewriting of the tables and virgin 11123 may not be thread-safe. 11124 */ 11125 var virgin = true; 11126 11127 var lenfix, distfix; // We have no pointers in JS, so keep tables separate 11128 11129 function fixedtables(state) { 11130 /* build fixed huffman tables if first call (may not be thread safe) */ 11131 if (virgin) { 11132 var sym; 11133 11134 lenfix = new Buf32(512); 11135 distfix = new Buf32(32); 11136 11137 /* literal/length table */ 11138 sym = 0; 11139 while (sym < 144) { 11140 state.lens[sym++] = 8; 11141 } 11142 while (sym < 256) { 11143 state.lens[sym++] = 9; 11144 } 11145 while (sym < 280) { 11146 state.lens[sym++] = 7; 11147 } 11148 while (sym < 288) { 11149 state.lens[sym++] = 8; 11150 } 11151 11152 inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { 11153 bits: 9 11154 }); 11155 11156 /* distance table */ 11157 sym = 0; 11158 while (sym < 32) { 11159 state.lens[sym++] = 5; 11160 } 11161 11162 inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { 11163 bits: 5 11164 }); 11165 11166 /* do this just once */ 11167 virgin = false; 11168 } 11169 11170 state.lencode = lenfix; 11171 state.lenbits = 9; 11172 state.distcode = distfix; 11173 state.distbits = 5; 11174 } 11175 11176 11177 /* 11178 Update the window with the last wsize (normally 32K) bytes written before 11179 returning. If window does not exist yet, create it. This is only called 11180 when a window is already in use, or when output has been written during this 11181 inflate call, but the end of the deflate stream has not been reached yet. 11182 It is also called to create a window for dictionary data when a dictionary 11183 is loaded. 11184 11185 Providing output buffers larger than 32K to inflate() should provide a speed 11186 advantage, since only the last 32K of output is copied to the sliding window 11187 upon return from inflate(), and since all distances after the first 32K of 11188 output will fall in the output data, making match copies simpler and faster. 11189 The advantage may be dependent on the size of the processor's data caches. 11190 */ 11191 function updatewindow(strm, src, end, copy) { 11192 var dist; 11193 var state = strm.state; 11194 11195 /* if it hasn't been done already, allocate space for the window */ 11196 if (state.window === null) { 11197 state.wsize = 1 << state.wbits; 11198 state.wnext = 0; 11199 state.whave = 0; 11200 11201 state.window = new Buf8(state.wsize); 11202 } 11203 11204 /* copy state->wsize or less output bytes into the circular window */ 11205 if (copy >= state.wsize) { 11206 arraySet(state.window, src, end - state.wsize, state.wsize, 0); 11207 state.wnext = 0; 11208 state.whave = state.wsize; 11209 } else { 11210 dist = state.wsize - state.wnext; 11211 if (dist > copy) { 11212 dist = copy; 11213 } 11214 //zmemcpy(state->window + state->wnext, end - copy, dist); 11215 arraySet(state.window, src, end - copy, dist, state.wnext); 11216 copy -= dist; 11217 if (copy) { 11218 //zmemcpy(state->window, end - copy, copy); 11219 arraySet(state.window, src, end - copy, copy, 0); 11220 state.wnext = copy; 11221 state.whave = state.wsize; 11222 } else { 11223 state.wnext += dist; 11224 if (state.wnext === state.wsize) { 11225 state.wnext = 0; 11226 } 11227 if (state.whave < state.wsize) { 11228 state.whave += dist; 11229 } 11230 } 11231 } 11232 return 0; 11233 } 11234 11235 function inflate(strm, flush) { 11236 var state; 11237 var input, output; // input/output buffers 11238 var next; /* next input INDEX */ 11239 var put; /* next output INDEX */ 11240 var have, left; /* available input and output */ 11241 var hold; /* bit buffer */ 11242 var bits; /* bits in bit buffer */ 11243 var _in, _out; /* save starting available input and output */ 11244 var copy; /* number of stored or match bytes to copy */ 11245 var from; /* where to copy match bytes from */ 11246 var from_source; 11247 var here = 0; /* current decoding table entry */ 11248 var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) 11249 //var last; /* parent table entry */ 11250 var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) 11251 var len; /* length to copy for repeats, bits to drop */ 11252 var ret; /* return code */ 11253 var hbuf = new Buf8(4); /* buffer for gzip header crc calculation */ 11254 var opts; 11255 11256 var n; // temporary var for NEED_BITS 11257 11258 var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; 11259 11260 11261 if (!strm || !strm.state || !strm.output || 11262 (!strm.input && strm.avail_in !== 0)) { 11263 return Z_STREAM_ERROR$1; 11264 } 11265 11266 state = strm.state; 11267 if (state.mode === TYPE$1) { 11268 state.mode = TYPEDO; 11269 } /* skip check */ 11270 11271 11272 //--- LOAD() --- 11273 put = strm.next_out; 11274 output = strm.output; 11275 left = strm.avail_out; 11276 next = strm.next_in; 11277 input = strm.input; 11278 have = strm.avail_in; 11279 hold = state.hold; 11280 bits = state.bits; 11281 //--- 11282 11283 _in = have; 11284 _out = left; 11285 ret = Z_OK$1; 11286 11287 inf_leave: // goto emulation 11288 for (;;) { 11289 switch (state.mode) { 11290 case HEAD: 11291 if (state.wrap === 0) { 11292 state.mode = TYPEDO; 11293 break; 11294 } 11295 //=== NEEDBITS(16); 11296 while (bits < 16) { 11297 if (have === 0) { 11298 break inf_leave; 11299 } 11300 have--; 11301 hold += input[next++] << bits; 11302 bits += 8; 11303 } 11304 //===// 11305 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ 11306 state.check = 0 /*crc32(0L, Z_NULL, 0)*/ ; 11307 //=== CRC2(state.check, hold); 11308 hbuf[0] = hold & 0xff; 11309 hbuf[1] = (hold >>> 8) & 0xff; 11310 state.check = crc32(state.check, hbuf, 2, 0); 11311 //===// 11312 11313 //=== INITBITS(); 11314 hold = 0; 11315 bits = 0; 11316 //===// 11317 state.mode = FLAGS; 11318 break; 11319 } 11320 state.flags = 0; /* expect zlib header */ 11321 if (state.head) { 11322 state.head.done = false; 11323 } 11324 if (!(state.wrap & 1) || /* check if zlib header allowed */ 11325 (((hold & 0xff) /*BITS(8)*/ << 8) + (hold >> 8)) % 31) { 11326 strm.msg = 'incorrect header check'; 11327 state.mode = BAD$1; 11328 break; 11329 } 11330 if ((hold & 0x0f) /*BITS(4)*/ !== Z_DEFLATED$1) { 11331 strm.msg = 'unknown compression method'; 11332 state.mode = BAD$1; 11333 break; 11334 } 11335 //--- DROPBITS(4) ---// 11336 hold >>>= 4; 11337 bits -= 4; 11338 //---// 11339 len = (hold & 0x0f) /*BITS(4)*/ + 8; 11340 if (state.wbits === 0) { 11341 state.wbits = len; 11342 } else if (len > state.wbits) { 11343 strm.msg = 'invalid window size'; 11344 state.mode = BAD$1; 11345 break; 11346 } 11347 state.dmax = 1 << len; 11348 //Tracev((stderr, "inflate: zlib header ok\n")); 11349 strm.adler = state.check = 1 /*adler32(0L, Z_NULL, 0)*/ ; 11350 state.mode = hold & 0x200 ? DICTID : TYPE$1; 11351 //=== INITBITS(); 11352 hold = 0; 11353 bits = 0; 11354 //===// 11355 break; 11356 case FLAGS: 11357 //=== NEEDBITS(16); */ 11358 while (bits < 16) { 11359 if (have === 0) { 11360 break inf_leave; 11361 } 11362 have--; 11363 hold += input[next++] << bits; 11364 bits += 8; 11365 } 11366 //===// 11367 state.flags = hold; 11368 if ((state.flags & 0xff) !== Z_DEFLATED$1) { 11369 strm.msg = 'unknown compression method'; 11370 state.mode = BAD$1; 11371 break; 11372 } 11373 if (state.flags & 0xe000) { 11374 strm.msg = 'unknown header flags set'; 11375 state.mode = BAD$1; 11376 break; 11377 } 11378 if (state.head) { 11379 state.head.text = ((hold >> 8) & 1); 11380 } 11381 if (state.flags & 0x0200) { 11382 //=== CRC2(state.check, hold); 11383 hbuf[0] = hold & 0xff; 11384 hbuf[1] = (hold >>> 8) & 0xff; 11385 state.check = crc32(state.check, hbuf, 2, 0); 11386 //===// 11387 } 11388 //=== INITBITS(); 11389 hold = 0; 11390 bits = 0; 11391 //===// 11392 state.mode = TIME; 11393 /* falls through */ 11394 case TIME: 11395 //=== NEEDBITS(32); */ 11396 while (bits < 32) { 11397 if (have === 0) { 11398 break inf_leave; 11399 } 11400 have--; 11401 hold += input[next++] << bits; 11402 bits += 8; 11403 } 11404 //===// 11405 if (state.head) { 11406 state.head.time = hold; 11407 } 11408 if (state.flags & 0x0200) { 11409 //=== CRC4(state.check, hold) 11410 hbuf[0] = hold & 0xff; 11411 hbuf[1] = (hold >>> 8) & 0xff; 11412 hbuf[2] = (hold >>> 16) & 0xff; 11413 hbuf[3] = (hold >>> 24) & 0xff; 11414 state.check = crc32(state.check, hbuf, 4, 0); 11415 //=== 11416 } 11417 //=== INITBITS(); 11418 hold = 0; 11419 bits = 0; 11420 //===// 11421 state.mode = OS; 11422 /* falls through */ 11423 case OS: 11424 //=== NEEDBITS(16); */ 11425 while (bits < 16) { 11426 if (have === 0) { 11427 break inf_leave; 11428 } 11429 have--; 11430 hold += input[next++] << bits; 11431 bits += 8; 11432 } 11433 //===// 11434 if (state.head) { 11435 state.head.xflags = (hold & 0xff); 11436 state.head.os = (hold >> 8); 11437 } 11438 if (state.flags & 0x0200) { 11439 //=== CRC2(state.check, hold); 11440 hbuf[0] = hold & 0xff; 11441 hbuf[1] = (hold >>> 8) & 0xff; 11442 state.check = crc32(state.check, hbuf, 2, 0); 11443 //===// 11444 } 11445 //=== INITBITS(); 11446 hold = 0; 11447 bits = 0; 11448 //===// 11449 state.mode = EXLEN; 11450 /* falls through */ 11451 case EXLEN: 11452 if (state.flags & 0x0400) { 11453 //=== NEEDBITS(16); */ 11454 while (bits < 16) { 11455 if (have === 0) { 11456 break inf_leave; 11457 } 11458 have--; 11459 hold += input[next++] << bits; 11460 bits += 8; 11461 } 11462 //===// 11463 state.length = hold; 11464 if (state.head) { 11465 state.head.extra_len = hold; 11466 } 11467 if (state.flags & 0x0200) { 11468 //=== CRC2(state.check, hold); 11469 hbuf[0] = hold & 0xff; 11470 hbuf[1] = (hold >>> 8) & 0xff; 11471 state.check = crc32(state.check, hbuf, 2, 0); 11472 //===// 11473 } 11474 //=== INITBITS(); 11475 hold = 0; 11476 bits = 0; 11477 //===// 11478 } else if (state.head) { 11479 state.head.extra = null /*Z_NULL*/ ; 11480 } 11481 state.mode = EXTRA; 11482 /* falls through */ 11483 case EXTRA: 11484 if (state.flags & 0x0400) { 11485 copy = state.length; 11486 if (copy > have) { 11487 copy = have; 11488 } 11489 if (copy) { 11490 if (state.head) { 11491 len = state.head.extra_len - state.length; 11492 if (!state.head.extra) { 11493 // Use untyped array for more conveniend processing later 11494 state.head.extra = new Array(state.head.extra_len); 11495 } 11496 arraySet( 11497 state.head.extra, 11498 input, 11499 next, 11500 // extra field is limited to 65536 bytes 11501 // - no need for additional size check 11502 copy, 11503 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ 11504 len 11505 ); 11506 //zmemcpy(state.head.extra + len, next, 11507 // len + copy > state.head.extra_max ? 11508 // state.head.extra_max - len : copy); 11509 } 11510 if (state.flags & 0x0200) { 11511 state.check = crc32(state.check, input, copy, next); 11512 } 11513 have -= copy; 11514 next += copy; 11515 state.length -= copy; 11516 }