UNPKG

573 kBJavaScriptView Raw
1(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.eosjs_ecc = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2(function (global){
3'use strict';
4
5// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
6// original notice:
7
8/*!
9 * The buffer module from node.js, for the browser.
10 *
11 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
12 * @license MIT
13 */
14function compare(a, b) {
15 if (a === b) {
16 return 0;
17 }
18
19 var x = a.length;
20 var y = b.length;
21
22 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
23 if (a[i] !== b[i]) {
24 x = a[i];
25 y = b[i];
26 break;
27 }
28 }
29
30 if (x < y) {
31 return -1;
32 }
33 if (y < x) {
34 return 1;
35 }
36 return 0;
37}
38function isBuffer(b) {
39 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
40 return global.Buffer.isBuffer(b);
41 }
42 return !!(b != null && b._isBuffer);
43}
44
45// based on node assert, original notice:
46
47// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
48//
49// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
50//
51// Originally from narwhal.js (http://narwhaljs.org)
52// Copyright (c) 2009 Thomas Robinson <280north.com>
53//
54// Permission is hereby granted, free of charge, to any person obtaining a copy
55// of this software and associated documentation files (the 'Software'), to
56// deal in the Software without restriction, including without limitation the
57// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
58// sell copies of the Software, and to permit persons to whom the Software is
59// furnished to do so, subject to the following conditions:
60//
61// The above copyright notice and this permission notice shall be included in
62// all copies or substantial portions of the Software.
63//
64// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
65// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
66// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
67// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
68// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
69// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
70
71var util = require('util/');
72var hasOwn = Object.prototype.hasOwnProperty;
73var pSlice = Array.prototype.slice;
74var functionsHaveNames = (function () {
75 return function foo() {}.name === 'foo';
76}());
77function pToString (obj) {
78 return Object.prototype.toString.call(obj);
79}
80function isView(arrbuf) {
81 if (isBuffer(arrbuf)) {
82 return false;
83 }
84 if (typeof global.ArrayBuffer !== 'function') {
85 return false;
86 }
87 if (typeof ArrayBuffer.isView === 'function') {
88 return ArrayBuffer.isView(arrbuf);
89 }
90 if (!arrbuf) {
91 return false;
92 }
93 if (arrbuf instanceof DataView) {
94 return true;
95 }
96 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
97 return true;
98 }
99 return false;
100}
101// 1. The assert module provides functions that throw
102// AssertionError's when particular conditions are not met. The
103// assert module must conform to the following interface.
104
105var assert = module.exports = ok;
106
107// 2. The AssertionError is defined in assert.
108// new assert.AssertionError({ message: message,
109// actual: actual,
110// expected: expected })
111
112var regex = /\s*function\s+([^\(\s]*)\s*/;
113// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
114function getName(func) {
115 if (!util.isFunction(func)) {
116 return;
117 }
118 if (functionsHaveNames) {
119 return func.name;
120 }
121 var str = func.toString();
122 var match = str.match(regex);
123 return match && match[1];
124}
125assert.AssertionError = function AssertionError(options) {
126 this.name = 'AssertionError';
127 this.actual = options.actual;
128 this.expected = options.expected;
129 this.operator = options.operator;
130 if (options.message) {
131 this.message = options.message;
132 this.generatedMessage = false;
133 } else {
134 this.message = getMessage(this);
135 this.generatedMessage = true;
136 }
137 var stackStartFunction = options.stackStartFunction || fail;
138 if (Error.captureStackTrace) {
139 Error.captureStackTrace(this, stackStartFunction);
140 } else {
141 // non v8 browsers so we can have a stacktrace
142 var err = new Error();
143 if (err.stack) {
144 var out = err.stack;
145
146 // try to strip useless frames
147 var fn_name = getName(stackStartFunction);
148 var idx = out.indexOf('\n' + fn_name);
149 if (idx >= 0) {
150 // once we have located the function frame
151 // we need to strip out everything before it (and its line)
152 var next_line = out.indexOf('\n', idx + 1);
153 out = out.substring(next_line + 1);
154 }
155
156 this.stack = out;
157 }
158 }
159};
160
161// assert.AssertionError instanceof Error
162util.inherits(assert.AssertionError, Error);
163
164function truncate(s, n) {
165 if (typeof s === 'string') {
166 return s.length < n ? s : s.slice(0, n);
167 } else {
168 return s;
169 }
170}
171function inspect(something) {
172 if (functionsHaveNames || !util.isFunction(something)) {
173 return util.inspect(something);
174 }
175 var rawname = getName(something);
176 var name = rawname ? ': ' + rawname : '';
177 return '[Function' + name + ']';
178}
179function getMessage(self) {
180 return truncate(inspect(self.actual), 128) + ' ' +
181 self.operator + ' ' +
182 truncate(inspect(self.expected), 128);
183}
184
185// At present only the three keys mentioned above are used and
186// understood by the spec. Implementations or sub modules can pass
187// other keys to the AssertionError's constructor - they will be
188// ignored.
189
190// 3. All of the following functions must throw an AssertionError
191// when a corresponding condition is not met, with a message that
192// may be undefined if not provided. All assertion methods provide
193// both the actual and expected values to the assertion error for
194// display purposes.
195
196function fail(actual, expected, message, operator, stackStartFunction) {
197 throw new assert.AssertionError({
198 message: message,
199 actual: actual,
200 expected: expected,
201 operator: operator,
202 stackStartFunction: stackStartFunction
203 });
204}
205
206// EXTENSION! allows for well behaved errors defined elsewhere.
207assert.fail = fail;
208
209// 4. Pure assertion tests whether a value is truthy, as determined
210// by !!guard.
211// assert.ok(guard, message_opt);
212// This statement is equivalent to assert.equal(true, !!guard,
213// message_opt);. To test strictly for the value true, use
214// assert.strictEqual(true, guard, message_opt);.
215
216function ok(value, message) {
217 if (!value) fail(value, true, message, '==', assert.ok);
218}
219assert.ok = ok;
220
221// 5. The equality assertion tests shallow, coercive equality with
222// ==.
223// assert.equal(actual, expected, message_opt);
224
225assert.equal = function equal(actual, expected, message) {
226 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
227};
228
229// 6. The non-equality assertion tests for whether two objects are not equal
230// with != assert.notEqual(actual, expected, message_opt);
231
232assert.notEqual = function notEqual(actual, expected, message) {
233 if (actual == expected) {
234 fail(actual, expected, message, '!=', assert.notEqual);
235 }
236};
237
238// 7. The equivalence assertion tests a deep equality relation.
239// assert.deepEqual(actual, expected, message_opt);
240
241assert.deepEqual = function deepEqual(actual, expected, message) {
242 if (!_deepEqual(actual, expected, false)) {
243 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
244 }
245};
246
247assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
248 if (!_deepEqual(actual, expected, true)) {
249 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
250 }
251};
252
253function _deepEqual(actual, expected, strict, memos) {
254 // 7.1. All identical values are equivalent, as determined by ===.
255 if (actual === expected) {
256 return true;
257 } else if (isBuffer(actual) && isBuffer(expected)) {
258 return compare(actual, expected) === 0;
259
260 // 7.2. If the expected value is a Date object, the actual value is
261 // equivalent if it is also a Date object that refers to the same time.
262 } else if (util.isDate(actual) && util.isDate(expected)) {
263 return actual.getTime() === expected.getTime();
264
265 // 7.3 If the expected value is a RegExp object, the actual value is
266 // equivalent if it is also a RegExp object with the same source and
267 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
268 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
269 return actual.source === expected.source &&
270 actual.global === expected.global &&
271 actual.multiline === expected.multiline &&
272 actual.lastIndex === expected.lastIndex &&
273 actual.ignoreCase === expected.ignoreCase;
274
275 // 7.4. Other pairs that do not both pass typeof value == 'object',
276 // equivalence is determined by ==.
277 } else if ((actual === null || typeof actual !== 'object') &&
278 (expected === null || typeof expected !== 'object')) {
279 return strict ? actual === expected : actual == expected;
280
281 // If both values are instances of typed arrays, wrap their underlying
282 // ArrayBuffers in a Buffer each to increase performance
283 // This optimization requires the arrays to have the same type as checked by
284 // Object.prototype.toString (aka pToString). Never perform binary
285 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
286 // bit patterns are not identical.
287 } else if (isView(actual) && isView(expected) &&
288 pToString(actual) === pToString(expected) &&
289 !(actual instanceof Float32Array ||
290 actual instanceof Float64Array)) {
291 return compare(new Uint8Array(actual.buffer),
292 new Uint8Array(expected.buffer)) === 0;
293
294 // 7.5 For all other Object pairs, including Array objects, equivalence is
295 // determined by having the same number of owned properties (as verified
296 // with Object.prototype.hasOwnProperty.call), the same set of keys
297 // (although not necessarily the same order), equivalent values for every
298 // corresponding key, and an identical 'prototype' property. Note: this
299 // accounts for both named and indexed properties on Arrays.
300 } else if (isBuffer(actual) !== isBuffer(expected)) {
301 return false;
302 } else {
303 memos = memos || {actual: [], expected: []};
304
305 var actualIndex = memos.actual.indexOf(actual);
306 if (actualIndex !== -1) {
307 if (actualIndex === memos.expected.indexOf(expected)) {
308 return true;
309 }
310 }
311
312 memos.actual.push(actual);
313 memos.expected.push(expected);
314
315 return objEquiv(actual, expected, strict, memos);
316 }
317}
318
319function isArguments(object) {
320 return Object.prototype.toString.call(object) == '[object Arguments]';
321}
322
323function objEquiv(a, b, strict, actualVisitedObjects) {
324 if (a === null || a === undefined || b === null || b === undefined)
325 return false;
326 // if one is a primitive, the other must be same
327 if (util.isPrimitive(a) || util.isPrimitive(b))
328 return a === b;
329 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
330 return false;
331 var aIsArgs = isArguments(a);
332 var bIsArgs = isArguments(b);
333 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
334 return false;
335 if (aIsArgs) {
336 a = pSlice.call(a);
337 b = pSlice.call(b);
338 return _deepEqual(a, b, strict);
339 }
340 var ka = objectKeys(a);
341 var kb = objectKeys(b);
342 var key, i;
343 // having the same number of owned properties (keys incorporates
344 // hasOwnProperty)
345 if (ka.length !== kb.length)
346 return false;
347 //the same set of keys (although not necessarily the same order),
348 ka.sort();
349 kb.sort();
350 //~~~cheap key test
351 for (i = ka.length - 1; i >= 0; i--) {
352 if (ka[i] !== kb[i])
353 return false;
354 }
355 //equivalent values for every corresponding key, and
356 //~~~possibly expensive deep test
357 for (i = ka.length - 1; i >= 0; i--) {
358 key = ka[i];
359 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
360 return false;
361 }
362 return true;
363}
364
365// 8. The non-equivalence assertion tests for any deep inequality.
366// assert.notDeepEqual(actual, expected, message_opt);
367
368assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
369 if (_deepEqual(actual, expected, false)) {
370 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
371 }
372};
373
374assert.notDeepStrictEqual = notDeepStrictEqual;
375function notDeepStrictEqual(actual, expected, message) {
376 if (_deepEqual(actual, expected, true)) {
377 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
378 }
379}
380
381
382// 9. The strict equality assertion tests strict equality, as determined by ===.
383// assert.strictEqual(actual, expected, message_opt);
384
385assert.strictEqual = function strictEqual(actual, expected, message) {
386 if (actual !== expected) {
387 fail(actual, expected, message, '===', assert.strictEqual);
388 }
389};
390
391// 10. The strict non-equality assertion tests for strict inequality, as
392// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
393
394assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
395 if (actual === expected) {
396 fail(actual, expected, message, '!==', assert.notStrictEqual);
397 }
398};
399
400function expectedException(actual, expected) {
401 if (!actual || !expected) {
402 return false;
403 }
404
405 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
406 return expected.test(actual);
407 }
408
409 try {
410 if (actual instanceof expected) {
411 return true;
412 }
413 } catch (e) {
414 // Ignore. The instanceof check doesn't work for arrow functions.
415 }
416
417 if (Error.isPrototypeOf(expected)) {
418 return false;
419 }
420
421 return expected.call({}, actual) === true;
422}
423
424function _tryBlock(block) {
425 var error;
426 try {
427 block();
428 } catch (e) {
429 error = e;
430 }
431 return error;
432}
433
434function _throws(shouldThrow, block, expected, message) {
435 var actual;
436
437 if (typeof block !== 'function') {
438 throw new TypeError('"block" argument must be a function');
439 }
440
441 if (typeof expected === 'string') {
442 message = expected;
443 expected = null;
444 }
445
446 actual = _tryBlock(block);
447
448 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
449 (message ? ' ' + message : '.');
450
451 if (shouldThrow && !actual) {
452 fail(actual, expected, 'Missing expected exception' + message);
453 }
454
455 var userProvidedMessage = typeof message === 'string';
456 var isUnwantedException = !shouldThrow && util.isError(actual);
457 var isUnexpectedException = !shouldThrow && actual && !expected;
458
459 if ((isUnwantedException &&
460 userProvidedMessage &&
461 expectedException(actual, expected)) ||
462 isUnexpectedException) {
463 fail(actual, expected, 'Got unwanted exception' + message);
464 }
465
466 if ((shouldThrow && actual && expected &&
467 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
468 throw actual;
469 }
470}
471
472// 11. Expected to throw an error:
473// assert.throws(block, Error_opt, message_opt);
474
475assert.throws = function(block, /*optional*/error, /*optional*/message) {
476 _throws(true, block, error, message);
477};
478
479// EXTENSION! This is annoying to write outside this module.
480assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
481 _throws(false, block, error, message);
482};
483
484assert.ifError = function(err) { if (err) throw err; };
485
486var objectKeys = Object.keys || function (obj) {
487 var keys = [];
488 for (var key in obj) {
489 if (hasOwn.call(obj, key)) keys.push(key);
490 }
491 return keys;
492};
493
494}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
495},{"util/":82}],2:[function(require,module,exports){
496// base-x encoding
497// Forked from https://github.com/cryptocoinjs/bs58
498// Originally written by Mike Hearn for BitcoinJ
499// Copyright (c) 2011 Google Inc
500// Ported to JavaScript by Stefan Thomas
501// Merged Buffer refactorings from base58-native by Stephen Pair
502// Copyright (c) 2013 BitPay Inc
503
504var Buffer = require('safe-buffer').Buffer
505
506module.exports = function base (ALPHABET) {
507 var ALPHABET_MAP = {}
508 var BASE = ALPHABET.length
509 var LEADER = ALPHABET.charAt(0)
510
511 // pre-compute lookup table
512 for (var z = 0; z < ALPHABET.length; z++) {
513 var x = ALPHABET.charAt(z)
514
515 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
516 ALPHABET_MAP[x] = z
517 }
518
519 function encode (source) {
520 if (source.length === 0) return ''
521
522 var digits = [0]
523 for (var i = 0; i < source.length; ++i) {
524 for (var j = 0, carry = source[i]; j < digits.length; ++j) {
525 carry += digits[j] << 8
526 digits[j] = carry % BASE
527 carry = (carry / BASE) | 0
528 }
529
530 while (carry > 0) {
531 digits.push(carry % BASE)
532 carry = (carry / BASE) | 0
533 }
534 }
535
536 var string = ''
537
538 // deal with leading zeros
539 for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += ALPHABET[0]
540 // convert digits to a string
541 for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
542
543 return string
544 }
545
546 function decodeUnsafe (string) {
547 if (string.length === 0) return Buffer.allocUnsafe(0)
548
549 var bytes = [0]
550 for (var i = 0; i < string.length; i++) {
551 var value = ALPHABET_MAP[string[i]]
552 if (value === undefined) return
553
554 for (var j = 0, carry = value; j < bytes.length; ++j) {
555 carry += bytes[j] * BASE
556 bytes[j] = carry & 0xff
557 carry >>= 8
558 }
559
560 while (carry > 0) {
561 bytes.push(carry & 0xff)
562 carry >>= 8
563 }
564 }
565
566 // deal with leading zeros
567 for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
568 bytes.push(0)
569 }
570
571 return Buffer.from(bytes.reverse())
572 }
573
574 function decode (string) {
575 var buffer = decodeUnsafe(string)
576 if (buffer) return buffer
577
578 throw new Error('Non-base' + BASE + ' character')
579 }
580
581 return {
582 encode: encode,
583 decodeUnsafe: decodeUnsafe,
584 decode: decode
585 }
586}
587
588},{"safe-buffer":68}],3:[function(require,module,exports){
589'use strict'
590
591exports.byteLength = byteLength
592exports.toByteArray = toByteArray
593exports.fromByteArray = fromByteArray
594
595var lookup = []
596var revLookup = []
597var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
598
599var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
600for (var i = 0, len = code.length; i < len; ++i) {
601 lookup[i] = code[i]
602 revLookup[code.charCodeAt(i)] = i
603}
604
605revLookup['-'.charCodeAt(0)] = 62
606revLookup['_'.charCodeAt(0)] = 63
607
608function placeHoldersCount (b64) {
609 var len = b64.length
610 if (len % 4 > 0) {
611 throw new Error('Invalid string. Length must be a multiple of 4')
612 }
613
614 // the number of equal signs (place holders)
615 // if there are two placeholders, than the two characters before it
616 // represent one byte
617 // if there is only one, then the three characters before it represent 2 bytes
618 // this is just a cheap hack to not do indexOf twice
619 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
620}
621
622function byteLength (b64) {
623 // base64 is 4/3 + up to two characters of the original data
624 return (b64.length * 3 / 4) - placeHoldersCount(b64)
625}
626
627function toByteArray (b64) {
628 var i, l, tmp, placeHolders, arr
629 var len = b64.length
630 placeHolders = placeHoldersCount(b64)
631
632 arr = new Arr((len * 3 / 4) - placeHolders)
633
634 // if there are placeholders, only get up to the last complete 4 chars
635 l = placeHolders > 0 ? len - 4 : len
636
637 var L = 0
638
639 for (i = 0; i < l; i += 4) {
640 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
641 arr[L++] = (tmp >> 16) & 0xFF
642 arr[L++] = (tmp >> 8) & 0xFF
643 arr[L++] = tmp & 0xFF
644 }
645
646 if (placeHolders === 2) {
647 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
648 arr[L++] = tmp & 0xFF
649 } else if (placeHolders === 1) {
650 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
651 arr[L++] = (tmp >> 8) & 0xFF
652 arr[L++] = tmp & 0xFF
653 }
654
655 return arr
656}
657
658function tripletToBase64 (num) {
659 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
660}
661
662function encodeChunk (uint8, start, end) {
663 var tmp
664 var output = []
665 for (var i = start; i < end; i += 3) {
666 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
667 output.push(tripletToBase64(tmp))
668 }
669 return output.join('')
670}
671
672function fromByteArray (uint8) {
673 var tmp
674 var len = uint8.length
675 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
676 var output = ''
677 var parts = []
678 var maxChunkLength = 16383 // must be multiple of 3
679
680 // go through the array every three bytes, we'll deal with trailing stuff later
681 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
682 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
683 }
684
685 // pad the end with zeros, but make sure to not forget the extra bytes
686 if (extraBytes === 1) {
687 tmp = uint8[len - 1]
688 output += lookup[tmp >> 2]
689 output += lookup[(tmp << 4) & 0x3F]
690 output += '=='
691 } else if (extraBytes === 2) {
692 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
693 output += lookup[tmp >> 10]
694 output += lookup[(tmp >> 4) & 0x3F]
695 output += lookup[(tmp << 2) & 0x3F]
696 output += '='
697 }
698
699 parts.push(output)
700
701 return parts.join('')
702}
703
704},{}],4:[function(require,module,exports){
705// (public) Constructor
706function BigInteger(a, b, c) {
707 if (!(this instanceof BigInteger))
708 return new BigInteger(a, b, c)
709
710 if (a != null) {
711 if ("number" == typeof a) this.fromNumber(a, b, c)
712 else if (b == null && "string" != typeof a) this.fromString(a, 256)
713 else this.fromString(a, b)
714 }
715}
716
717var proto = BigInteger.prototype
718
719// duck-typed isBigInteger
720proto.__bigi = require('../package.json').version
721BigInteger.isBigInteger = function (obj, check_ver) {
722 return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi)
723}
724
725// Bits per digit
726var dbits
727
728// am: Compute w_j += (x*this_i), propagate carries,
729// c is initial carry, returns final carry.
730// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
731// We need to select the fastest one that works in this environment.
732
733// am1: use a single mult and divide to get the high bits,
734// max digit bits should be 26 because
735// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
736function am1(i, x, w, j, c, n) {
737 while (--n >= 0) {
738 var v = x * this[i++] + w[j] + c
739 c = Math.floor(v / 0x4000000)
740 w[j++] = v & 0x3ffffff
741 }
742 return c
743}
744// am2 avoids a big mult-and-extract completely.
745// Max digit bits should be <= 30 because we do bitwise ops
746// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
747function am2(i, x, w, j, c, n) {
748 var xl = x & 0x7fff,
749 xh = x >> 15
750 while (--n >= 0) {
751 var l = this[i] & 0x7fff
752 var h = this[i++] >> 15
753 var m = xh * l + h * xl
754 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff)
755 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30)
756 w[j++] = l & 0x3fffffff
757 }
758 return c
759}
760// Alternately, set max digit bits to 28 since some
761// browsers slow down when dealing with 32-bit numbers.
762function am3(i, x, w, j, c, n) {
763 var xl = x & 0x3fff,
764 xh = x >> 14
765 while (--n >= 0) {
766 var l = this[i] & 0x3fff
767 var h = this[i++] >> 14
768 var m = xh * l + h * xl
769 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c
770 c = (l >> 28) + (m >> 14) + xh * h
771 w[j++] = l & 0xfffffff
772 }
773 return c
774}
775
776// wtf?
777BigInteger.prototype.am = am1
778dbits = 26
779
780BigInteger.prototype.DB = dbits
781BigInteger.prototype.DM = ((1 << dbits) - 1)
782var DV = BigInteger.prototype.DV = (1 << dbits)
783
784var BI_FP = 52
785BigInteger.prototype.FV = Math.pow(2, BI_FP)
786BigInteger.prototype.F1 = BI_FP - dbits
787BigInteger.prototype.F2 = 2 * dbits - BI_FP
788
789// Digit conversions
790var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"
791var BI_RC = new Array()
792var rr, vv
793rr = "0".charCodeAt(0)
794for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv
795rr = "a".charCodeAt(0)
796for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
797rr = "A".charCodeAt(0)
798for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
799
800function int2char(n) {
801 return BI_RM.charAt(n)
802}
803
804function intAt(s, i) {
805 var c = BI_RC[s.charCodeAt(i)]
806 return (c == null) ? -1 : c
807}
808
809// (protected) copy this to r
810function bnpCopyTo(r) {
811 for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]
812 r.t = this.t
813 r.s = this.s
814}
815
816// (protected) set from integer value x, -DV <= x < DV
817function bnpFromInt(x) {
818 this.t = 1
819 this.s = (x < 0) ? -1 : 0
820 if (x > 0) this[0] = x
821 else if (x < -1) this[0] = x + DV
822 else this.t = 0
823}
824
825// return bigint initialized to value
826function nbv(i) {
827 var r = new BigInteger()
828 r.fromInt(i)
829 return r
830}
831
832// (protected) set from string and radix
833function bnpFromString(s, b) {
834 var self = this
835
836 var k
837 if (b == 16) k = 4
838 else if (b == 8) k = 3
839 else if (b == 256) k = 8; // byte array
840 else if (b == 2) k = 1
841 else if (b == 32) k = 5
842 else if (b == 4) k = 2
843 else {
844 self.fromRadix(s, b)
845 return
846 }
847 self.t = 0
848 self.s = 0
849 var i = s.length,
850 mi = false,
851 sh = 0
852 while (--i >= 0) {
853 var x = (k == 8) ? s[i] & 0xff : intAt(s, i)
854 if (x < 0) {
855 if (s.charAt(i) == "-") mi = true
856 continue
857 }
858 mi = false
859 if (sh == 0)
860 self[self.t++] = x
861 else if (sh + k > self.DB) {
862 self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh
863 self[self.t++] = (x >> (self.DB - sh))
864 } else
865 self[self.t - 1] |= x << sh
866 sh += k
867 if (sh >= self.DB) sh -= self.DB
868 }
869 if (k == 8 && (s[0] & 0x80) != 0) {
870 self.s = -1
871 if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh
872 }
873 self.clamp()
874 if (mi) BigInteger.ZERO.subTo(self, self)
875}
876
877// (protected) clamp off excess high words
878function bnpClamp() {
879 var c = this.s & this.DM
880 while (this.t > 0 && this[this.t - 1] == c)--this.t
881}
882
883// (public) return string representation in given radix
884function bnToString(b) {
885 var self = this
886 if (self.s < 0) return "-" + self.negate()
887 .toString(b)
888 var k
889 if (b == 16) k = 4
890 else if (b == 8) k = 3
891 else if (b == 2) k = 1
892 else if (b == 32) k = 5
893 else if (b == 4) k = 2
894 else return self.toRadix(b)
895 var km = (1 << k) - 1,
896 d, m = false,
897 r = "",
898 i = self.t
899 var p = self.DB - (i * self.DB) % k
900 if (i-- > 0) {
901 if (p < self.DB && (d = self[i] >> p) > 0) {
902 m = true
903 r = int2char(d)
904 }
905 while (i >= 0) {
906 if (p < k) {
907 d = (self[i] & ((1 << p) - 1)) << (k - p)
908 d |= self[--i] >> (p += self.DB - k)
909 } else {
910 d = (self[i] >> (p -= k)) & km
911 if (p <= 0) {
912 p += self.DB
913 --i
914 }
915 }
916 if (d > 0) m = true
917 if (m) r += int2char(d)
918 }
919 }
920 return m ? r : "0"
921}
922
923// (public) -this
924function bnNegate() {
925 var r = new BigInteger()
926 BigInteger.ZERO.subTo(this, r)
927 return r
928}
929
930// (public) |this|
931function bnAbs() {
932 return (this.s < 0) ? this.negate() : this
933}
934
935// (public) return + if this > a, - if this < a, 0 if equal
936function bnCompareTo(a) {
937 var r = this.s - a.s
938 if (r != 0) return r
939 var i = this.t
940 r = i - a.t
941 if (r != 0) return (this.s < 0) ? -r : r
942 while (--i >= 0)
943 if ((r = this[i] - a[i]) != 0) return r
944 return 0
945}
946
947// returns bit length of the integer x
948function nbits(x) {
949 var r = 1,
950 t
951 if ((t = x >>> 16) != 0) {
952 x = t
953 r += 16
954 }
955 if ((t = x >> 8) != 0) {
956 x = t
957 r += 8
958 }
959 if ((t = x >> 4) != 0) {
960 x = t
961 r += 4
962 }
963 if ((t = x >> 2) != 0) {
964 x = t
965 r += 2
966 }
967 if ((t = x >> 1) != 0) {
968 x = t
969 r += 1
970 }
971 return r
972}
973
974// (public) return the number of bits in "this"
975function bnBitLength() {
976 if (this.t <= 0) return 0
977 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM))
978}
979
980// (public) return the number of bytes in "this"
981function bnByteLength() {
982 return this.bitLength() >> 3
983}
984
985// (protected) r = this << n*DB
986function bnpDLShiftTo(n, r) {
987 var i
988 for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]
989 for (i = n - 1; i >= 0; --i) r[i] = 0
990 r.t = this.t + n
991 r.s = this.s
992}
993
994// (protected) r = this >> n*DB
995function bnpDRShiftTo(n, r) {
996 for (var i = n; i < this.t; ++i) r[i - n] = this[i]
997 r.t = Math.max(this.t - n, 0)
998 r.s = this.s
999}
1000
1001// (protected) r = this << n
1002function bnpLShiftTo(n, r) {
1003 var self = this
1004 var bs = n % self.DB
1005 var cbs = self.DB - bs
1006 var bm = (1 << cbs) - 1
1007 var ds = Math.floor(n / self.DB),
1008 c = (self.s << bs) & self.DM,
1009 i
1010 for (i = self.t - 1; i >= 0; --i) {
1011 r[i + ds + 1] = (self[i] >> cbs) | c
1012 c = (self[i] & bm) << bs
1013 }
1014 for (i = ds - 1; i >= 0; --i) r[i] = 0
1015 r[ds] = c
1016 r.t = self.t + ds + 1
1017 r.s = self.s
1018 r.clamp()
1019}
1020
1021// (protected) r = this >> n
1022function bnpRShiftTo(n, r) {
1023 var self = this
1024 r.s = self.s
1025 var ds = Math.floor(n / self.DB)
1026 if (ds >= self.t) {
1027 r.t = 0
1028 return
1029 }
1030 var bs = n % self.DB
1031 var cbs = self.DB - bs
1032 var bm = (1 << bs) - 1
1033 r[0] = self[ds] >> bs
1034 for (var i = ds + 1; i < self.t; ++i) {
1035 r[i - ds - 1] |= (self[i] & bm) << cbs
1036 r[i - ds] = self[i] >> bs
1037 }
1038 if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs
1039 r.t = self.t - ds
1040 r.clamp()
1041}
1042
1043// (protected) r = this - a
1044function bnpSubTo(a, r) {
1045 var self = this
1046 var i = 0,
1047 c = 0,
1048 m = Math.min(a.t, self.t)
1049 while (i < m) {
1050 c += self[i] - a[i]
1051 r[i++] = c & self.DM
1052 c >>= self.DB
1053 }
1054 if (a.t < self.t) {
1055 c -= a.s
1056 while (i < self.t) {
1057 c += self[i]
1058 r[i++] = c & self.DM
1059 c >>= self.DB
1060 }
1061 c += self.s
1062 } else {
1063 c += self.s
1064 while (i < a.t) {
1065 c -= a[i]
1066 r[i++] = c & self.DM
1067 c >>= self.DB
1068 }
1069 c -= a.s
1070 }
1071 r.s = (c < 0) ? -1 : 0
1072 if (c < -1) r[i++] = self.DV + c
1073 else if (c > 0) r[i++] = c
1074 r.t = i
1075 r.clamp()
1076}
1077
1078// (protected) r = this * a, r != this,a (HAC 14.12)
1079// "this" should be the larger one if appropriate.
1080function bnpMultiplyTo(a, r) {
1081 var x = this.abs(),
1082 y = a.abs()
1083 var i = x.t
1084 r.t = i + y.t
1085 while (--i >= 0) r[i] = 0
1086 for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t)
1087 r.s = 0
1088 r.clamp()
1089 if (this.s != a.s) BigInteger.ZERO.subTo(r, r)
1090}
1091
1092// (protected) r = this^2, r != this (HAC 14.16)
1093function bnpSquareTo(r) {
1094 var x = this.abs()
1095 var i = r.t = 2 * x.t
1096 while (--i >= 0) r[i] = 0
1097 for (i = 0; i < x.t - 1; ++i) {
1098 var c = x.am(i, x[i], r, 2 * i, 0, 1)
1099 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
1100 r[i + x.t] -= x.DV
1101 r[i + x.t + 1] = 1
1102 }
1103 }
1104 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1)
1105 r.s = 0
1106 r.clamp()
1107}
1108
1109// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
1110// r != q, this != m. q or r may be null.
1111function bnpDivRemTo(m, q, r) {
1112 var self = this
1113 var pm = m.abs()
1114 if (pm.t <= 0) return
1115 var pt = self.abs()
1116 if (pt.t < pm.t) {
1117 if (q != null) q.fromInt(0)
1118 if (r != null) self.copyTo(r)
1119 return
1120 }
1121 if (r == null) r = new BigInteger()
1122 var y = new BigInteger(),
1123 ts = self.s,
1124 ms = m.s
1125 var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus
1126 if (nsh > 0) {
1127 pm.lShiftTo(nsh, y)
1128 pt.lShiftTo(nsh, r)
1129 } else {
1130 pm.copyTo(y)
1131 pt.copyTo(r)
1132 }
1133 var ys = y.t
1134 var y0 = y[ys - 1]
1135 if (y0 == 0) return
1136 var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0)
1137 var d1 = self.FV / yt,
1138 d2 = (1 << self.F1) / yt,
1139 e = 1 << self.F2
1140 var i = r.t,
1141 j = i - ys,
1142 t = (q == null) ? new BigInteger() : q
1143 y.dlShiftTo(j, t)
1144 if (r.compareTo(t) >= 0) {
1145 r[r.t++] = 1
1146 r.subTo(t, r)
1147 }
1148 BigInteger.ONE.dlShiftTo(ys, t)
1149 t.subTo(y, y); // "negative" y so we can replace sub with am later
1150 while (y.t < ys) y[y.t++] = 0
1151 while (--j >= 0) {
1152 // Estimate quotient digit
1153 var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2)
1154 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
1155 y.dlShiftTo(j, t)
1156 r.subTo(t, r)
1157 while (r[i] < --qd) r.subTo(t, r)
1158 }
1159 }
1160 if (q != null) {
1161 r.drShiftTo(ys, q)
1162 if (ts != ms) BigInteger.ZERO.subTo(q, q)
1163 }
1164 r.t = ys
1165 r.clamp()
1166 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
1167 if (ts < 0) BigInteger.ZERO.subTo(r, r)
1168}
1169
1170// (public) this mod a
1171function bnMod(a) {
1172 var r = new BigInteger()
1173 this.abs()
1174 .divRemTo(a, null, r)
1175 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r)
1176 return r
1177}
1178
1179// Modular reduction using "classic" algorithm
1180function Classic(m) {
1181 this.m = m
1182}
1183
1184function cConvert(x) {
1185 if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m)
1186 else return x
1187}
1188
1189function cRevert(x) {
1190 return x
1191}
1192
1193function cReduce(x) {
1194 x.divRemTo(this.m, null, x)
1195}
1196
1197function cMulTo(x, y, r) {
1198 x.multiplyTo(y, r)
1199 this.reduce(r)
1200}
1201
1202function cSqrTo(x, r) {
1203 x.squareTo(r)
1204 this.reduce(r)
1205}
1206
1207Classic.prototype.convert = cConvert
1208Classic.prototype.revert = cRevert
1209Classic.prototype.reduce = cReduce
1210Classic.prototype.mulTo = cMulTo
1211Classic.prototype.sqrTo = cSqrTo
1212
1213// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
1214// justification:
1215// xy == 1 (mod m)
1216// xy = 1+km
1217// xy(2-xy) = (1+km)(1-km)
1218// x[y(2-xy)] = 1-k^2m^2
1219// x[y(2-xy)] == 1 (mod m^2)
1220// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
1221// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
1222// JS multiply "overflows" differently from C/C++, so care is needed here.
1223function bnpInvDigit() {
1224 if (this.t < 1) return 0
1225 var x = this[0]
1226 if ((x & 1) == 0) return 0
1227 var y = x & 3; // y == 1/x mod 2^2
1228 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
1229 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
1230 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
1231 // last step - calculate inverse mod DV directly
1232 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
1233 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
1234 // we really want the negative inverse, and -DV < y < DV
1235 return (y > 0) ? this.DV - y : -y
1236}
1237
1238// Montgomery reduction
1239function Montgomery(m) {
1240 this.m = m
1241 this.mp = m.invDigit()
1242 this.mpl = this.mp & 0x7fff
1243 this.mph = this.mp >> 15
1244 this.um = (1 << (m.DB - 15)) - 1
1245 this.mt2 = 2 * m.t
1246}
1247
1248// xR mod m
1249function montConvert(x) {
1250 var r = new BigInteger()
1251 x.abs()
1252 .dlShiftTo(this.m.t, r)
1253 r.divRemTo(this.m, null, r)
1254 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)
1255 return r
1256}
1257
1258// x/R mod m
1259function montRevert(x) {
1260 var r = new BigInteger()
1261 x.copyTo(r)
1262 this.reduce(r)
1263 return r
1264}
1265
1266// x = x/R mod m (HAC 14.32)
1267function montReduce(x) {
1268 while (x.t <= this.mt2) // pad x so am has enough room later
1269 x[x.t++] = 0
1270 for (var i = 0; i < this.m.t; ++i) {
1271 // faster way of calculating u0 = x[i]*mp mod DV
1272 var j = x[i] & 0x7fff
1273 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM
1274 // use am to combine the multiply-shift-add into one call
1275 j = i + this.m.t
1276 x[j] += this.m.am(0, u0, x, i, 0, this.m.t)
1277 // propagate carry
1278 while (x[j] >= x.DV) {
1279 x[j] -= x.DV
1280 x[++j]++
1281 }
1282 }
1283 x.clamp()
1284 x.drShiftTo(this.m.t, x)
1285 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x)
1286}
1287
1288// r = "x^2/R mod m"; x != r
1289function montSqrTo(x, r) {
1290 x.squareTo(r)
1291 this.reduce(r)
1292}
1293
1294// r = "xy/R mod m"; x,y != r
1295function montMulTo(x, y, r) {
1296 x.multiplyTo(y, r)
1297 this.reduce(r)
1298}
1299
1300Montgomery.prototype.convert = montConvert
1301Montgomery.prototype.revert = montRevert
1302Montgomery.prototype.reduce = montReduce
1303Montgomery.prototype.mulTo = montMulTo
1304Montgomery.prototype.sqrTo = montSqrTo
1305
1306// (protected) true iff this is even
1307function bnpIsEven() {
1308 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0
1309}
1310
1311// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
1312function bnpExp(e, z) {
1313 if (e > 0xffffffff || e < 1) return BigInteger.ONE
1314 var r = new BigInteger(),
1315 r2 = new BigInteger(),
1316 g = z.convert(this),
1317 i = nbits(e) - 1
1318 g.copyTo(r)
1319 while (--i >= 0) {
1320 z.sqrTo(r, r2)
1321 if ((e & (1 << i)) > 0) z.mulTo(r2, g, r)
1322 else {
1323 var t = r
1324 r = r2
1325 r2 = t
1326 }
1327 }
1328 return z.revert(r)
1329}
1330
1331// (public) this^e % m, 0 <= e < 2^32
1332function bnModPowInt(e, m) {
1333 var z
1334 if (e < 256 || m.isEven()) z = new Classic(m)
1335 else z = new Montgomery(m)
1336 return this.exp(e, z)
1337}
1338
1339// protected
1340proto.copyTo = bnpCopyTo
1341proto.fromInt = bnpFromInt
1342proto.fromString = bnpFromString
1343proto.clamp = bnpClamp
1344proto.dlShiftTo = bnpDLShiftTo
1345proto.drShiftTo = bnpDRShiftTo
1346proto.lShiftTo = bnpLShiftTo
1347proto.rShiftTo = bnpRShiftTo
1348proto.subTo = bnpSubTo
1349proto.multiplyTo = bnpMultiplyTo
1350proto.squareTo = bnpSquareTo
1351proto.divRemTo = bnpDivRemTo
1352proto.invDigit = bnpInvDigit
1353proto.isEven = bnpIsEven
1354proto.exp = bnpExp
1355
1356// public
1357proto.toString = bnToString
1358proto.negate = bnNegate
1359proto.abs = bnAbs
1360proto.compareTo = bnCompareTo
1361proto.bitLength = bnBitLength
1362proto.byteLength = bnByteLength
1363proto.mod = bnMod
1364proto.modPowInt = bnModPowInt
1365
1366// (public)
1367function bnClone() {
1368 var r = new BigInteger()
1369 this.copyTo(r)
1370 return r
1371}
1372
1373// (public) return value as integer
1374function bnIntValue() {
1375 if (this.s < 0) {
1376 if (this.t == 1) return this[0] - this.DV
1377 else if (this.t == 0) return -1
1378 } else if (this.t == 1) return this[0]
1379 else if (this.t == 0) return 0
1380 // assumes 16 < DB < 32
1381 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]
1382}
1383
1384// (public) return value as byte
1385function bnByteValue() {
1386 return (this.t == 0) ? this.s : (this[0] << 24) >> 24
1387}
1388
1389// (public) return value as short (assumes DB>=16)
1390function bnShortValue() {
1391 return (this.t == 0) ? this.s : (this[0] << 16) >> 16
1392}
1393
1394// (protected) return x s.t. r^x < DV
1395function bnpChunkSize(r) {
1396 return Math.floor(Math.LN2 * this.DB / Math.log(r))
1397}
1398
1399// (public) 0 if this == 0, 1 if this > 0
1400function bnSigNum() {
1401 if (this.s < 0) return -1
1402 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0
1403 else return 1
1404}
1405
1406// (protected) convert to radix string
1407function bnpToRadix(b) {
1408 if (b == null) b = 10
1409 if (this.signum() == 0 || b < 2 || b > 36) return "0"
1410 var cs = this.chunkSize(b)
1411 var a = Math.pow(b, cs)
1412 var d = nbv(a),
1413 y = new BigInteger(),
1414 z = new BigInteger(),
1415 r = ""
1416 this.divRemTo(d, y, z)
1417 while (y.signum() > 0) {
1418 r = (a + z.intValue())
1419 .toString(b)
1420 .substr(1) + r
1421 y.divRemTo(d, y, z)
1422 }
1423 return z.intValue()
1424 .toString(b) + r
1425}
1426
1427// (protected) convert from radix string
1428function bnpFromRadix(s, b) {
1429 var self = this
1430 self.fromInt(0)
1431 if (b == null) b = 10
1432 var cs = self.chunkSize(b)
1433 var d = Math.pow(b, cs),
1434 mi = false,
1435 j = 0,
1436 w = 0
1437 for (var i = 0; i < s.length; ++i) {
1438 var x = intAt(s, i)
1439 if (x < 0) {
1440 if (s.charAt(i) == "-" && self.signum() == 0) mi = true
1441 continue
1442 }
1443 w = b * w + x
1444 if (++j >= cs) {
1445 self.dMultiply(d)
1446 self.dAddOffset(w, 0)
1447 j = 0
1448 w = 0
1449 }
1450 }
1451 if (j > 0) {
1452 self.dMultiply(Math.pow(b, j))
1453 self.dAddOffset(w, 0)
1454 }
1455 if (mi) BigInteger.ZERO.subTo(self, self)
1456}
1457
1458// (protected) alternate constructor
1459function bnpFromNumber(a, b, c) {
1460 var self = this
1461 if ("number" == typeof b) {
1462 // new BigInteger(int,int,RNG)
1463 if (a < 2) self.fromInt(1)
1464 else {
1465 self.fromNumber(a, c)
1466 if (!self.testBit(a - 1)) // force MSB set
1467 self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self)
1468 if (self.isEven()) self.dAddOffset(1, 0); // force odd
1469 while (!self.isProbablePrime(b)) {
1470 self.dAddOffset(2, 0)
1471 if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self)
1472 }
1473 }
1474 } else {
1475 // new BigInteger(int,RNG)
1476 var x = new Array(),
1477 t = a & 7
1478 x.length = (a >> 3) + 1
1479 b.nextBytes(x)
1480 if (t > 0) x[0] &= ((1 << t) - 1)
1481 else x[0] = 0
1482 self.fromString(x, 256)
1483 }
1484}
1485
1486// (public) convert to bigendian byte array
1487function bnToByteArray() {
1488 var self = this
1489 var i = self.t,
1490 r = new Array()
1491 r[0] = self.s
1492 var p = self.DB - (i * self.DB) % 8,
1493 d, k = 0
1494 if (i-- > 0) {
1495 if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p)
1496 r[k++] = d | (self.s << (self.DB - p))
1497 while (i >= 0) {
1498 if (p < 8) {
1499 d = (self[i] & ((1 << p) - 1)) << (8 - p)
1500 d |= self[--i] >> (p += self.DB - 8)
1501 } else {
1502 d = (self[i] >> (p -= 8)) & 0xff
1503 if (p <= 0) {
1504 p += self.DB
1505 --i
1506 }
1507 }
1508 if ((d & 0x80) != 0) d |= -256
1509 if (k === 0 && (self.s & 0x80) != (d & 0x80))++k
1510 if (k > 0 || d != self.s) r[k++] = d
1511 }
1512 }
1513 return r
1514}
1515
1516function bnEquals(a) {
1517 return (this.compareTo(a) == 0)
1518}
1519
1520function bnMin(a) {
1521 return (this.compareTo(a) < 0) ? this : a
1522}
1523
1524function bnMax(a) {
1525 return (this.compareTo(a) > 0) ? this : a
1526}
1527
1528// (protected) r = this op a (bitwise)
1529function bnpBitwiseTo(a, op, r) {
1530 var self = this
1531 var i, f, m = Math.min(a.t, self.t)
1532 for (i = 0; i < m; ++i) r[i] = op(self[i], a[i])
1533 if (a.t < self.t) {
1534 f = a.s & self.DM
1535 for (i = m; i < self.t; ++i) r[i] = op(self[i], f)
1536 r.t = self.t
1537 } else {
1538 f = self.s & self.DM
1539 for (i = m; i < a.t; ++i) r[i] = op(f, a[i])
1540 r.t = a.t
1541 }
1542 r.s = op(self.s, a.s)
1543 r.clamp()
1544}
1545
1546// (public) this & a
1547function op_and(x, y) {
1548 return x & y
1549}
1550
1551function bnAnd(a) {
1552 var r = new BigInteger()
1553 this.bitwiseTo(a, op_and, r)
1554 return r
1555}
1556
1557// (public) this | a
1558function op_or(x, y) {
1559 return x | y
1560}
1561
1562function bnOr(a) {
1563 var r = new BigInteger()
1564 this.bitwiseTo(a, op_or, r)
1565 return r
1566}
1567
1568// (public) this ^ a
1569function op_xor(x, y) {
1570 return x ^ y
1571}
1572
1573function bnXor(a) {
1574 var r = new BigInteger()
1575 this.bitwiseTo(a, op_xor, r)
1576 return r
1577}
1578
1579// (public) this & ~a
1580function op_andnot(x, y) {
1581 return x & ~y
1582}
1583
1584function bnAndNot(a) {
1585 var r = new BigInteger()
1586 this.bitwiseTo(a, op_andnot, r)
1587 return r
1588}
1589
1590// (public) ~this
1591function bnNot() {
1592 var r = new BigInteger()
1593 for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]
1594 r.t = this.t
1595 r.s = ~this.s
1596 return r
1597}
1598
1599// (public) this << n
1600function bnShiftLeft(n) {
1601 var r = new BigInteger()
1602 if (n < 0) this.rShiftTo(-n, r)
1603 else this.lShiftTo(n, r)
1604 return r
1605}
1606
1607// (public) this >> n
1608function bnShiftRight(n) {
1609 var r = new BigInteger()
1610 if (n < 0) this.lShiftTo(-n, r)
1611 else this.rShiftTo(n, r)
1612 return r
1613}
1614
1615// return index of lowest 1-bit in x, x < 2^31
1616function lbit(x) {
1617 if (x == 0) return -1
1618 var r = 0
1619 if ((x & 0xffff) == 0) {
1620 x >>= 16
1621 r += 16
1622 }
1623 if ((x & 0xff) == 0) {
1624 x >>= 8
1625 r += 8
1626 }
1627 if ((x & 0xf) == 0) {
1628 x >>= 4
1629 r += 4
1630 }
1631 if ((x & 3) == 0) {
1632 x >>= 2
1633 r += 2
1634 }
1635 if ((x & 1) == 0)++r
1636 return r
1637}
1638
1639// (public) returns index of lowest 1-bit (or -1 if none)
1640function bnGetLowestSetBit() {
1641 for (var i = 0; i < this.t; ++i)
1642 if (this[i] != 0) return i * this.DB + lbit(this[i])
1643 if (this.s < 0) return this.t * this.DB
1644 return -1
1645}
1646
1647// return number of 1 bits in x
1648function cbit(x) {
1649 var r = 0
1650 while (x != 0) {
1651 x &= x - 1
1652 ++r
1653 }
1654 return r
1655}
1656
1657// (public) return number of set bits
1658function bnBitCount() {
1659 var r = 0,
1660 x = this.s & this.DM
1661 for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x)
1662 return r
1663}
1664
1665// (public) true iff nth bit is set
1666function bnTestBit(n) {
1667 var j = Math.floor(n / this.DB)
1668 if (j >= this.t) return (this.s != 0)
1669 return ((this[j] & (1 << (n % this.DB))) != 0)
1670}
1671
1672// (protected) this op (1<<n)
1673function bnpChangeBit(n, op) {
1674 var r = BigInteger.ONE.shiftLeft(n)
1675 this.bitwiseTo(r, op, r)
1676 return r
1677}
1678
1679// (public) this | (1<<n)
1680function bnSetBit(n) {
1681 return this.changeBit(n, op_or)
1682}
1683
1684// (public) this & ~(1<<n)
1685function bnClearBit(n) {
1686 return this.changeBit(n, op_andnot)
1687}
1688
1689// (public) this ^ (1<<n)
1690function bnFlipBit(n) {
1691 return this.changeBit(n, op_xor)
1692}
1693
1694// (protected) r = this + a
1695function bnpAddTo(a, r) {
1696 var self = this
1697
1698 var i = 0,
1699 c = 0,
1700 m = Math.min(a.t, self.t)
1701 while (i < m) {
1702 c += self[i] + a[i]
1703 r[i++] = c & self.DM
1704 c >>= self.DB
1705 }
1706 if (a.t < self.t) {
1707 c += a.s
1708 while (i < self.t) {
1709 c += self[i]
1710 r[i++] = c & self.DM
1711 c >>= self.DB
1712 }
1713 c += self.s
1714 } else {
1715 c += self.s
1716 while (i < a.t) {
1717 c += a[i]
1718 r[i++] = c & self.DM
1719 c >>= self.DB
1720 }
1721 c += a.s
1722 }
1723 r.s = (c < 0) ? -1 : 0
1724 if (c > 0) r[i++] = c
1725 else if (c < -1) r[i++] = self.DV + c
1726 r.t = i
1727 r.clamp()
1728}
1729
1730// (public) this + a
1731function bnAdd(a) {
1732 var r = new BigInteger()
1733 this.addTo(a, r)
1734 return r
1735}
1736
1737// (public) this - a
1738function bnSubtract(a) {
1739 var r = new BigInteger()
1740 this.subTo(a, r)
1741 return r
1742}
1743
1744// (public) this * a
1745function bnMultiply(a) {
1746 var r = new BigInteger()
1747 this.multiplyTo(a, r)
1748 return r
1749}
1750
1751// (public) this^2
1752function bnSquare() {
1753 var r = new BigInteger()
1754 this.squareTo(r)
1755 return r
1756}
1757
1758// (public) this / a
1759function bnDivide(a) {
1760 var r = new BigInteger()
1761 this.divRemTo(a, r, null)
1762 return r
1763}
1764
1765// (public) this % a
1766function bnRemainder(a) {
1767 var r = new BigInteger()
1768 this.divRemTo(a, null, r)
1769 return r
1770}
1771
1772// (public) [this/a,this%a]
1773function bnDivideAndRemainder(a) {
1774 var q = new BigInteger(),
1775 r = new BigInteger()
1776 this.divRemTo(a, q, r)
1777 return new Array(q, r)
1778}
1779
1780// (protected) this *= n, this >= 0, 1 < n < DV
1781function bnpDMultiply(n) {
1782 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t)
1783 ++this.t
1784 this.clamp()
1785}
1786
1787// (protected) this += n << w words, this >= 0
1788function bnpDAddOffset(n, w) {
1789 if (n == 0) return
1790 while (this.t <= w) this[this.t++] = 0
1791 this[w] += n
1792 while (this[w] >= this.DV) {
1793 this[w] -= this.DV
1794 if (++w >= this.t) this[this.t++] = 0
1795 ++this[w]
1796 }
1797}
1798
1799// A "null" reducer
1800function NullExp() {}
1801
1802function nNop(x) {
1803 return x
1804}
1805
1806function nMulTo(x, y, r) {
1807 x.multiplyTo(y, r)
1808}
1809
1810function nSqrTo(x, r) {
1811 x.squareTo(r)
1812}
1813
1814NullExp.prototype.convert = nNop
1815NullExp.prototype.revert = nNop
1816NullExp.prototype.mulTo = nMulTo
1817NullExp.prototype.sqrTo = nSqrTo
1818
1819// (public) this^e
1820function bnPow(e) {
1821 return this.exp(e, new NullExp())
1822}
1823
1824// (protected) r = lower n words of "this * a", a.t <= n
1825// "this" should be the larger one if appropriate.
1826function bnpMultiplyLowerTo(a, n, r) {
1827 var i = Math.min(this.t + a.t, n)
1828 r.s = 0; // assumes a,this >= 0
1829 r.t = i
1830 while (i > 0) r[--i] = 0
1831 var j
1832 for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t)
1833 for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i)
1834 r.clamp()
1835}
1836
1837// (protected) r = "this * a" without lower n words, n > 0
1838// "this" should be the larger one if appropriate.
1839function bnpMultiplyUpperTo(a, n, r) {
1840 --n
1841 var i = r.t = this.t + a.t - n
1842 r.s = 0; // assumes a,this >= 0
1843 while (--i >= 0) r[i] = 0
1844 for (i = Math.max(n - this.t, 0); i < a.t; ++i)
1845 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n)
1846 r.clamp()
1847 r.drShiftTo(1, r)
1848}
1849
1850// Barrett modular reduction
1851function Barrett(m) {
1852 // setup Barrett
1853 this.r2 = new BigInteger()
1854 this.q3 = new BigInteger()
1855 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2)
1856 this.mu = this.r2.divide(m)
1857 this.m = m
1858}
1859
1860function barrettConvert(x) {
1861 if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m)
1862 else if (x.compareTo(this.m) < 0) return x
1863 else {
1864 var r = new BigInteger()
1865 x.copyTo(r)
1866 this.reduce(r)
1867 return r
1868 }
1869}
1870
1871function barrettRevert(x) {
1872 return x
1873}
1874
1875// x = x mod m (HAC 14.42)
1876function barrettReduce(x) {
1877 var self = this
1878 x.drShiftTo(self.m.t - 1, self.r2)
1879 if (x.t > self.m.t + 1) {
1880 x.t = self.m.t + 1
1881 x.clamp()
1882 }
1883 self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3)
1884 self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2)
1885 while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1)
1886 x.subTo(self.r2, x)
1887 while (x.compareTo(self.m) >= 0) x.subTo(self.m, x)
1888}
1889
1890// r = x^2 mod m; x != r
1891function barrettSqrTo(x, r) {
1892 x.squareTo(r)
1893 this.reduce(r)
1894}
1895
1896// r = x*y mod m; x,y != r
1897function barrettMulTo(x, y, r) {
1898 x.multiplyTo(y, r)
1899 this.reduce(r)
1900}
1901
1902Barrett.prototype.convert = barrettConvert
1903Barrett.prototype.revert = barrettRevert
1904Barrett.prototype.reduce = barrettReduce
1905Barrett.prototype.mulTo = barrettMulTo
1906Barrett.prototype.sqrTo = barrettSqrTo
1907
1908// (public) this^e % m (HAC 14.85)
1909function bnModPow(e, m) {
1910 var i = e.bitLength(),
1911 k, r = nbv(1),
1912 z
1913 if (i <= 0) return r
1914 else if (i < 18) k = 1
1915 else if (i < 48) k = 3
1916 else if (i < 144) k = 4
1917 else if (i < 768) k = 5
1918 else k = 6
1919 if (i < 8)
1920 z = new Classic(m)
1921 else if (m.isEven())
1922 z = new Barrett(m)
1923 else
1924 z = new Montgomery(m)
1925
1926 // precomputation
1927 var g = new Array(),
1928 n = 3,
1929 k1 = k - 1,
1930 km = (1 << k) - 1
1931 g[1] = z.convert(this)
1932 if (k > 1) {
1933 var g2 = new BigInteger()
1934 z.sqrTo(g[1], g2)
1935 while (n <= km) {
1936 g[n] = new BigInteger()
1937 z.mulTo(g2, g[n - 2], g[n])
1938 n += 2
1939 }
1940 }
1941
1942 var j = e.t - 1,
1943 w, is1 = true,
1944 r2 = new BigInteger(),
1945 t
1946 i = nbits(e[j]) - 1
1947 while (j >= 0) {
1948 if (i >= k1) w = (e[j] >> (i - k1)) & km
1949 else {
1950 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i)
1951 if (j > 0) w |= e[j - 1] >> (this.DB + i - k1)
1952 }
1953
1954 n = k
1955 while ((w & 1) == 0) {
1956 w >>= 1
1957 --n
1958 }
1959 if ((i -= n) < 0) {
1960 i += this.DB
1961 --j
1962 }
1963 if (is1) { // ret == 1, don't bother squaring or multiplying it
1964 g[w].copyTo(r)
1965 is1 = false
1966 } else {
1967 while (n > 1) {
1968 z.sqrTo(r, r2)
1969 z.sqrTo(r2, r)
1970 n -= 2
1971 }
1972 if (n > 0) z.sqrTo(r, r2)
1973 else {
1974 t = r
1975 r = r2
1976 r2 = t
1977 }
1978 z.mulTo(r2, g[w], r)
1979 }
1980
1981 while (j >= 0 && (e[j] & (1 << i)) == 0) {
1982 z.sqrTo(r, r2)
1983 t = r
1984 r = r2
1985 r2 = t
1986 if (--i < 0) {
1987 i = this.DB - 1
1988 --j
1989 }
1990 }
1991 }
1992 return z.revert(r)
1993}
1994
1995// (public) gcd(this,a) (HAC 14.54)
1996function bnGCD(a) {
1997 var x = (this.s < 0) ? this.negate() : this.clone()
1998 var y = (a.s < 0) ? a.negate() : a.clone()
1999 if (x.compareTo(y) < 0) {
2000 var t = x
2001 x = y
2002 y = t
2003 }
2004 var i = x.getLowestSetBit(),
2005 g = y.getLowestSetBit()
2006 if (g < 0) return x
2007 if (i < g) g = i
2008 if (g > 0) {
2009 x.rShiftTo(g, x)
2010 y.rShiftTo(g, y)
2011 }
2012 while (x.signum() > 0) {
2013 if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x)
2014 if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y)
2015 if (x.compareTo(y) >= 0) {
2016 x.subTo(y, x)
2017 x.rShiftTo(1, x)
2018 } else {
2019 y.subTo(x, y)
2020 y.rShiftTo(1, y)
2021 }
2022 }
2023 if (g > 0) y.lShiftTo(g, y)
2024 return y
2025}
2026
2027// (protected) this % n, n < 2^26
2028function bnpModInt(n) {
2029 if (n <= 0) return 0
2030 var d = this.DV % n,
2031 r = (this.s < 0) ? n - 1 : 0
2032 if (this.t > 0)
2033 if (d == 0) r = this[0] % n
2034 else
2035 for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n
2036 return r
2037}
2038
2039// (public) 1/this % m (HAC 14.61)
2040function bnModInverse(m) {
2041 var ac = m.isEven()
2042 if (this.signum() === 0) throw new Error('division by zero')
2043 if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO
2044 var u = m.clone(),
2045 v = this.clone()
2046 var a = nbv(1),
2047 b = nbv(0),
2048 c = nbv(0),
2049 d = nbv(1)
2050 while (u.signum() != 0) {
2051 while (u.isEven()) {
2052 u.rShiftTo(1, u)
2053 if (ac) {
2054 if (!a.isEven() || !b.isEven()) {
2055 a.addTo(this, a)
2056 b.subTo(m, b)
2057 }
2058 a.rShiftTo(1, a)
2059 } else if (!b.isEven()) b.subTo(m, b)
2060 b.rShiftTo(1, b)
2061 }
2062 while (v.isEven()) {
2063 v.rShiftTo(1, v)
2064 if (ac) {
2065 if (!c.isEven() || !d.isEven()) {
2066 c.addTo(this, c)
2067 d.subTo(m, d)
2068 }
2069 c.rShiftTo(1, c)
2070 } else if (!d.isEven()) d.subTo(m, d)
2071 d.rShiftTo(1, d)
2072 }
2073 if (u.compareTo(v) >= 0) {
2074 u.subTo(v, u)
2075 if (ac) a.subTo(c, a)
2076 b.subTo(d, b)
2077 } else {
2078 v.subTo(u, v)
2079 if (ac) c.subTo(a, c)
2080 d.subTo(b, d)
2081 }
2082 }
2083 if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO
2084 while (d.compareTo(m) >= 0) d.subTo(m, d)
2085 while (d.signum() < 0) d.addTo(m, d)
2086 return d
2087}
2088
2089var lowprimes = [
2090 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
2091 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
2092 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
2093 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
2094 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
2095 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
2096 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
2097 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
2098 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
2099 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
2100 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
2101]
2102
2103var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]
2104
2105// (public) test primality with certainty >= 1-.5^t
2106function bnIsProbablePrime(t) {
2107 var i, x = this.abs()
2108 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
2109 for (i = 0; i < lowprimes.length; ++i)
2110 if (x[0] == lowprimes[i]) return true
2111 return false
2112 }
2113 if (x.isEven()) return false
2114 i = 1
2115 while (i < lowprimes.length) {
2116 var m = lowprimes[i],
2117 j = i + 1
2118 while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]
2119 m = x.modInt(m)
2120 while (i < j) if (m % lowprimes[i++] == 0) return false
2121 }
2122 return x.millerRabin(t)
2123}
2124
2125// (protected) true if probably prime (HAC 4.24, Miller-Rabin)
2126function bnpMillerRabin(t) {
2127 var n1 = this.subtract(BigInteger.ONE)
2128 var k = n1.getLowestSetBit()
2129 if (k <= 0) return false
2130 var r = n1.shiftRight(k)
2131 t = (t + 1) >> 1
2132 if (t > lowprimes.length) t = lowprimes.length
2133 var a = new BigInteger(null)
2134 var j, bases = []
2135 for (var i = 0; i < t; ++i) {
2136 for (;;) {
2137 j = lowprimes[Math.floor(Math.random() * lowprimes.length)]
2138 if (bases.indexOf(j) == -1) break
2139 }
2140 bases.push(j)
2141 a.fromInt(j)
2142 var y = a.modPow(r, this)
2143 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
2144 var j = 1
2145 while (j++ < k && y.compareTo(n1) != 0) {
2146 y = y.modPowInt(2, this)
2147 if (y.compareTo(BigInteger.ONE) == 0) return false
2148 }
2149 if (y.compareTo(n1) != 0) return false
2150 }
2151 }
2152 return true
2153}
2154
2155// protected
2156proto.chunkSize = bnpChunkSize
2157proto.toRadix = bnpToRadix
2158proto.fromRadix = bnpFromRadix
2159proto.fromNumber = bnpFromNumber
2160proto.bitwiseTo = bnpBitwiseTo
2161proto.changeBit = bnpChangeBit
2162proto.addTo = bnpAddTo
2163proto.dMultiply = bnpDMultiply
2164proto.dAddOffset = bnpDAddOffset
2165proto.multiplyLowerTo = bnpMultiplyLowerTo
2166proto.multiplyUpperTo = bnpMultiplyUpperTo
2167proto.modInt = bnpModInt
2168proto.millerRabin = bnpMillerRabin
2169
2170// public
2171proto.clone = bnClone
2172proto.intValue = bnIntValue
2173proto.byteValue = bnByteValue
2174proto.shortValue = bnShortValue
2175proto.signum = bnSigNum
2176proto.toByteArray = bnToByteArray
2177proto.equals = bnEquals
2178proto.min = bnMin
2179proto.max = bnMax
2180proto.and = bnAnd
2181proto.or = bnOr
2182proto.xor = bnXor
2183proto.andNot = bnAndNot
2184proto.not = bnNot
2185proto.shiftLeft = bnShiftLeft
2186proto.shiftRight = bnShiftRight
2187proto.getLowestSetBit = bnGetLowestSetBit
2188proto.bitCount = bnBitCount
2189proto.testBit = bnTestBit
2190proto.setBit = bnSetBit
2191proto.clearBit = bnClearBit
2192proto.flipBit = bnFlipBit
2193proto.add = bnAdd
2194proto.subtract = bnSubtract
2195proto.multiply = bnMultiply
2196proto.divide = bnDivide
2197proto.remainder = bnRemainder
2198proto.divideAndRemainder = bnDivideAndRemainder
2199proto.modPow = bnModPow
2200proto.modInverse = bnModInverse
2201proto.pow = bnPow
2202proto.gcd = bnGCD
2203proto.isProbablePrime = bnIsProbablePrime
2204
2205// JSBN-specific extension
2206proto.square = bnSquare
2207
2208// constants
2209BigInteger.ZERO = nbv(0)
2210BigInteger.ONE = nbv(1)
2211BigInteger.valueOf = nbv
2212
2213module.exports = BigInteger
2214
2215},{"../package.json":7}],5:[function(require,module,exports){
2216(function (Buffer){
2217// FIXME: Kind of a weird way to throw exceptions, consider removing
2218var assert = require('assert')
2219var BigInteger = require('./bigi')
2220
2221/**
2222 * Turns a byte array into a big integer.
2223 *
2224 * This function will interpret a byte array as a big integer in big
2225 * endian notation.
2226 */
2227BigInteger.fromByteArrayUnsigned = function(byteArray) {
2228 // BigInteger expects a DER integer conformant byte array
2229 if (byteArray[0] & 0x80) {
2230 return new BigInteger([0].concat(byteArray))
2231 }
2232
2233 return new BigInteger(byteArray)
2234}
2235
2236/**
2237 * Returns a byte array representation of the big integer.
2238 *
2239 * This returns the absolute of the contained value in big endian
2240 * form. A value of zero results in an empty array.
2241 */
2242BigInteger.prototype.toByteArrayUnsigned = function() {
2243 var byteArray = this.toByteArray()
2244 return byteArray[0] === 0 ? byteArray.slice(1) : byteArray
2245}
2246
2247BigInteger.fromDERInteger = function(byteArray) {
2248 return new BigInteger(byteArray)
2249}
2250
2251/*
2252 * Converts BigInteger to a DER integer representation.
2253 *
2254 * The format for this value uses the most significant bit as a sign
2255 * bit. If the most significant bit is already set and the integer is
2256 * positive, a 0x00 is prepended.
2257 *
2258 * Examples:
2259 *
2260 * 0 => 0x00
2261 * 1 => 0x01
2262 * -1 => 0xff
2263 * 127 => 0x7f
2264 * -127 => 0x81
2265 * 128 => 0x0080
2266 * -128 => 0x80
2267 * 255 => 0x00ff
2268 * -255 => 0xff01
2269 * 16300 => 0x3fac
2270 * -16300 => 0xc054
2271 * 62300 => 0x00f35c
2272 * -62300 => 0xff0ca4
2273*/
2274BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray
2275
2276BigInteger.fromBuffer = function(buffer) {
2277 // BigInteger expects a DER integer conformant byte array
2278 if (buffer[0] & 0x80) {
2279 var byteArray = Array.prototype.slice.call(buffer)
2280
2281 return new BigInteger([0].concat(byteArray))
2282 }
2283
2284 return new BigInteger(buffer)
2285}
2286
2287BigInteger.fromHex = function(hex) {
2288 if (hex === '') return BigInteger.ZERO
2289
2290 assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string')
2291 assert.equal(hex.length % 2, 0, 'Incomplete hex')
2292 return new BigInteger(hex, 16)
2293}
2294
2295BigInteger.prototype.toBuffer = function(size) {
2296 var byteArray = this.toByteArrayUnsigned()
2297 var zeros = []
2298
2299 var padding = size - byteArray.length
2300 while (zeros.length < padding) zeros.push(0)
2301
2302 return new Buffer(zeros.concat(byteArray))
2303}
2304
2305BigInteger.prototype.toHex = function(size) {
2306 return this.toBuffer(size).toString('hex')
2307}
2308
2309}).call(this,require("buffer").Buffer)
2310},{"./bigi":4,"assert":1,"buffer":27}],6:[function(require,module,exports){
2311var BigInteger = require('./bigi')
2312
2313//addons
2314require('./convert')
2315
2316module.exports = BigInteger
2317},{"./bigi":4,"./convert":5}],7:[function(require,module,exports){
2318module.exports={
2319 "_from": "bigi@^1.4.2",
2320 "_id": "bigi@1.4.2",
2321 "_inBundle": false,
2322 "_integrity": "sha1-nGZalfiLiwj8Bc/XMfVhhZ1yWCU=",
2323 "_location": "/bigi",
2324 "_phantomChildren": {},
2325 "_requested": {
2326 "type": "range",
2327 "registry": true,
2328 "raw": "bigi@^1.4.2",
2329 "name": "bigi",
2330 "escapedName": "bigi",
2331 "rawSpec": "^1.4.2",
2332 "saveSpec": null,
2333 "fetchSpec": "^1.4.2"
2334 },
2335 "_requiredBy": [
2336 "/",
2337 "/ecurve"
2338 ],
2339 "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz",
2340 "_shasum": "9c665a95f88b8b08fc05cfd731f561859d725825",
2341 "_spec": "bigi@^1.4.2",
2342 "_where": "/home/jcalfee/eosjs/ecc",
2343 "bugs": {
2344 "url": "https://github.com/cryptocoinjs/bigi/issues"
2345 },
2346 "bundleDependencies": false,
2347 "dependencies": {},
2348 "deprecated": false,
2349 "description": "Big integers.",
2350 "devDependencies": {
2351 "coveralls": "^2.11.2",
2352 "istanbul": "^0.3.5",
2353 "jshint": "^2.5.1",
2354 "mocha": "^2.1.0",
2355 "mochify": "^2.1.0"
2356 },
2357 "homepage": "https://github.com/cryptocoinjs/bigi#readme",
2358 "keywords": [
2359 "cryptography",
2360 "math",
2361 "bitcoin",
2362 "arbitrary",
2363 "precision",
2364 "arithmetic",
2365 "big",
2366 "integer",
2367 "int",
2368 "number",
2369 "biginteger",
2370 "bigint",
2371 "bignumber",
2372 "decimal",
2373 "float"
2374 ],
2375 "main": "./lib/index.js",
2376 "name": "bigi",
2377 "repository": {
2378 "url": "git+https://github.com/cryptocoinjs/bigi.git",
2379 "type": "git"
2380 },
2381 "scripts": {
2382 "browser-test": "mochify --wd -R spec",
2383 "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js",
2384 "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info",
2385 "jshint": "jshint --config jshint.json lib/*.js ; true",
2386 "test": "_mocha -- test/*.js",
2387 "unit": "mocha"
2388 },
2389 "testling": {
2390 "files": "test/*.js",
2391 "harness": "mocha",
2392 "browsers": [
2393 "ie/9..latest",
2394 "firefox/latest",
2395 "chrome/latest",
2396 "safari/6.0..latest",
2397 "iphone/6.0..latest",
2398 "android-browser/4.2..latest"
2399 ]
2400 },
2401 "version": "1.4.2"
2402}
2403
2404},{}],8:[function(require,module,exports){
2405
2406},{}],9:[function(require,module,exports){
2407// based on the aes implimentation in triple sec
2408// https://github.com/keybase/triplesec
2409// which is in turn based on the one from crypto-js
2410// https://code.google.com/p/crypto-js/
2411
2412var Buffer = require('safe-buffer').Buffer
2413
2414function asUInt32Array (buf) {
2415 if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
2416
2417 var len = (buf.length / 4) | 0
2418 var out = new Array(len)
2419
2420 for (var i = 0; i < len; i++) {
2421 out[i] = buf.readUInt32BE(i * 4)
2422 }
2423
2424 return out
2425}
2426
2427function scrubVec (v) {
2428 for (var i = 0; i < v.length; v++) {
2429 v[i] = 0
2430 }
2431}
2432
2433function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
2434 var SUB_MIX0 = SUB_MIX[0]
2435 var SUB_MIX1 = SUB_MIX[1]
2436 var SUB_MIX2 = SUB_MIX[2]
2437 var SUB_MIX3 = SUB_MIX[3]
2438
2439 var s0 = M[0] ^ keySchedule[0]
2440 var s1 = M[1] ^ keySchedule[1]
2441 var s2 = M[2] ^ keySchedule[2]
2442 var s3 = M[3] ^ keySchedule[3]
2443 var t0, t1, t2, t3
2444 var ksRow = 4
2445
2446 for (var round = 1; round < nRounds; round++) {
2447 t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
2448 t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
2449 t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
2450 t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
2451 s0 = t0
2452 s1 = t1
2453 s2 = t2
2454 s3 = t3
2455 }
2456
2457 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
2458 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
2459 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
2460 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
2461 t0 = t0 >>> 0
2462 t1 = t1 >>> 0
2463 t2 = t2 >>> 0
2464 t3 = t3 >>> 0
2465
2466 return [t0, t1, t2, t3]
2467}
2468
2469// AES constants
2470var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
2471var G = (function () {
2472 // Compute double table
2473 var d = new Array(256)
2474 for (var j = 0; j < 256; j++) {
2475 if (j < 128) {
2476 d[j] = j << 1
2477 } else {
2478 d[j] = (j << 1) ^ 0x11b
2479 }
2480 }
2481
2482 var SBOX = []
2483 var INV_SBOX = []
2484 var SUB_MIX = [[], [], [], []]
2485 var INV_SUB_MIX = [[], [], [], []]
2486
2487 // Walk GF(2^8)
2488 var x = 0
2489 var xi = 0
2490 for (var i = 0; i < 256; ++i) {
2491 // Compute sbox
2492 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
2493 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
2494 SBOX[x] = sx
2495 INV_SBOX[sx] = x
2496
2497 // Compute multiplication
2498 var x2 = d[x]
2499 var x4 = d[x2]
2500 var x8 = d[x4]
2501
2502 // Compute sub bytes, mix columns tables
2503 var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
2504 SUB_MIX[0][x] = (t << 24) | (t >>> 8)
2505 SUB_MIX[1][x] = (t << 16) | (t >>> 16)
2506 SUB_MIX[2][x] = (t << 8) | (t >>> 24)
2507 SUB_MIX[3][x] = t
2508
2509 // Compute inv sub bytes, inv mix columns tables
2510 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
2511 INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
2512 INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
2513 INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
2514 INV_SUB_MIX[3][sx] = t
2515
2516 if (x === 0) {
2517 x = xi = 1
2518 } else {
2519 x = x2 ^ d[d[d[x8 ^ x2]]]
2520 xi ^= d[d[xi]]
2521 }
2522 }
2523
2524 return {
2525 SBOX: SBOX,
2526 INV_SBOX: INV_SBOX,
2527 SUB_MIX: SUB_MIX,
2528 INV_SUB_MIX: INV_SUB_MIX
2529 }
2530})()
2531
2532function AES (key) {
2533 this._key = asUInt32Array(key)
2534 this._reset()
2535}
2536
2537AES.blockSize = 4 * 4
2538AES.keySize = 256 / 8
2539AES.prototype.blockSize = AES.blockSize
2540AES.prototype.keySize = AES.keySize
2541AES.prototype._reset = function () {
2542 var keyWords = this._key
2543 var keySize = keyWords.length
2544 var nRounds = keySize + 6
2545 var ksRows = (nRounds + 1) * 4
2546
2547 var keySchedule = []
2548 for (var k = 0; k < keySize; k++) {
2549 keySchedule[k] = keyWords[k]
2550 }
2551
2552 for (k = keySize; k < ksRows; k++) {
2553 var t = keySchedule[k - 1]
2554
2555 if (k % keySize === 0) {
2556 t = (t << 8) | (t >>> 24)
2557 t =
2558 (G.SBOX[t >>> 24] << 24) |
2559 (G.SBOX[(t >>> 16) & 0xff] << 16) |
2560 (G.SBOX[(t >>> 8) & 0xff] << 8) |
2561 (G.SBOX[t & 0xff])
2562
2563 t ^= RCON[(k / keySize) | 0] << 24
2564 } else if (keySize > 6 && k % keySize === 4) {
2565 t =
2566 (G.SBOX[t >>> 24] << 24) |
2567 (G.SBOX[(t >>> 16) & 0xff] << 16) |
2568 (G.SBOX[(t >>> 8) & 0xff] << 8) |
2569 (G.SBOX[t & 0xff])
2570 }
2571
2572 keySchedule[k] = keySchedule[k - keySize] ^ t
2573 }
2574
2575 var invKeySchedule = []
2576 for (var ik = 0; ik < ksRows; ik++) {
2577 var ksR = ksRows - ik
2578 var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
2579
2580 if (ik < 4 || ksR <= 4) {
2581 invKeySchedule[ik] = tt
2582 } else {
2583 invKeySchedule[ik] =
2584 G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
2585 G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
2586 G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
2587 G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
2588 }
2589 }
2590
2591 this._nRounds = nRounds
2592 this._keySchedule = keySchedule
2593 this._invKeySchedule = invKeySchedule
2594}
2595
2596AES.prototype.encryptBlockRaw = function (M) {
2597 M = asUInt32Array(M)
2598 return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
2599}
2600
2601AES.prototype.encryptBlock = function (M) {
2602 var out = this.encryptBlockRaw(M)
2603 var buf = Buffer.allocUnsafe(16)
2604 buf.writeUInt32BE(out[0], 0)
2605 buf.writeUInt32BE(out[1], 4)
2606 buf.writeUInt32BE(out[2], 8)
2607 buf.writeUInt32BE(out[3], 12)
2608 return buf
2609}
2610
2611AES.prototype.decryptBlock = function (M) {
2612 M = asUInt32Array(M)
2613
2614 // swap
2615 var m1 = M[1]
2616 M[1] = M[3]
2617 M[3] = m1
2618
2619 var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
2620 var buf = Buffer.allocUnsafe(16)
2621 buf.writeUInt32BE(out[0], 0)
2622 buf.writeUInt32BE(out[3], 4)
2623 buf.writeUInt32BE(out[2], 8)
2624 buf.writeUInt32BE(out[1], 12)
2625 return buf
2626}
2627
2628AES.prototype.scrub = function () {
2629 scrubVec(this._keySchedule)
2630 scrubVec(this._invKeySchedule)
2631 scrubVec(this._key)
2632}
2633
2634module.exports.AES = AES
2635
2636},{"safe-buffer":68}],10:[function(require,module,exports){
2637var aes = require('./aes')
2638var Buffer = require('safe-buffer').Buffer
2639var Transform = require('cipher-base')
2640var inherits = require('inherits')
2641var GHASH = require('./ghash')
2642var xor = require('buffer-xor')
2643
2644function xorTest (a, b) {
2645 var out = 0
2646 if (a.length !== b.length) out++
2647
2648 var len = Math.min(a.length, b.length)
2649 for (var i = 0; i < len; ++i) {
2650 out += (a[i] ^ b[i])
2651 }
2652
2653 return out
2654}
2655
2656function StreamCipher (mode, key, iv, decrypt) {
2657 Transform.call(this)
2658
2659 this._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
2660 iv = Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
2661
2662 this._cipher = new aes.AES(key)
2663 this._prev = Buffer.from(iv)
2664 this._cache = Buffer.allocUnsafe(0)
2665 this._secCache = Buffer.allocUnsafe(0)
2666 this._decrypt = decrypt
2667 this._alen = 0
2668 this._len = 0
2669 this._mode = mode
2670
2671 var h = Buffer.alloc(4, 0)
2672 this._ghash = new GHASH(this._cipher.encryptBlock(h))
2673 this._authTag = null
2674 this._called = false
2675}
2676
2677inherits(StreamCipher, Transform)
2678
2679StreamCipher.prototype._update = function (chunk) {
2680 if (!this._called && this._alen) {
2681 var rump = 16 - (this._alen % 16)
2682 if (rump < 16) {
2683 rump = Buffer.alloc(rump, 0)
2684 this._ghash.update(rump)
2685 }
2686 }
2687
2688 this._called = true
2689 var out = this._mode.encrypt(this, chunk)
2690 if (this._decrypt) {
2691 this._ghash.update(chunk)
2692 } else {
2693 this._ghash.update(out)
2694 }
2695 this._len += chunk.length
2696 return out
2697}
2698
2699StreamCipher.prototype._final = function () {
2700 if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')
2701
2702 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
2703 if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')
2704
2705 this._authTag = tag
2706 this._cipher.scrub()
2707}
2708
2709StreamCipher.prototype.getAuthTag = function getAuthTag () {
2710 if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')
2711
2712 return this._authTag
2713}
2714
2715StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
2716 if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')
2717
2718 this._authTag = tag
2719}
2720
2721StreamCipher.prototype.setAAD = function setAAD (buf) {
2722 if (this._called) throw new Error('Attempting to set AAD in unsupported state')
2723
2724 this._ghash.update(buf)
2725 this._alen += buf.length
2726}
2727
2728module.exports = StreamCipher
2729
2730},{"./aes":9,"./ghash":14,"buffer-xor":26,"cipher-base":29,"inherits":45,"safe-buffer":68}],11:[function(require,module,exports){
2731var ciphers = require('./encrypter')
2732var deciphers = require('./decrypter')
2733var modes = require('./modes/list.json')
2734
2735function getCiphers () {
2736 return Object.keys(modes)
2737}
2738
2739exports.createCipher = exports.Cipher = ciphers.createCipher
2740exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
2741exports.createDecipher = exports.Decipher = deciphers.createDecipher
2742exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
2743exports.listCiphers = exports.getCiphers = getCiphers
2744
2745},{"./decrypter":12,"./encrypter":13,"./modes/list.json":22}],12:[function(require,module,exports){
2746var AuthCipher = require('./authCipher')
2747var Buffer = require('safe-buffer').Buffer
2748var MODES = require('./modes')
2749var StreamCipher = require('./streamCipher')
2750var Transform = require('cipher-base')
2751var aes = require('./aes')
2752var ebtk = require('evp_bytestokey')
2753var inherits = require('inherits')
2754
2755function Decipher (mode, key, iv) {
2756 Transform.call(this)
2757
2758 this._cache = new Splitter()
2759 this._last = void 0
2760 this._cipher = new aes.AES(key)
2761 this._prev = Buffer.from(iv)
2762 this._mode = mode
2763 this._autopadding = true
2764}
2765
2766inherits(Decipher, Transform)
2767
2768Decipher.prototype._update = function (data) {
2769 this._cache.add(data)
2770 var chunk
2771 var thing
2772 var out = []
2773 while ((chunk = this._cache.get(this._autopadding))) {
2774 thing = this._mode.decrypt(this, chunk)
2775 out.push(thing)
2776 }
2777 return Buffer.concat(out)
2778}
2779
2780Decipher.prototype._final = function () {
2781 var chunk = this._cache.flush()
2782 if (this._autopadding) {
2783 return unpad(this._mode.decrypt(this, chunk))
2784 } else if (chunk) {
2785 throw new Error('data not multiple of block length')
2786 }
2787}
2788
2789Decipher.prototype.setAutoPadding = function (setTo) {
2790 this._autopadding = !!setTo
2791 return this
2792}
2793
2794function Splitter () {
2795 this.cache = Buffer.allocUnsafe(0)
2796}
2797
2798Splitter.prototype.add = function (data) {
2799 this.cache = Buffer.concat([this.cache, data])
2800}
2801
2802Splitter.prototype.get = function (autoPadding) {
2803 var out
2804 if (autoPadding) {
2805 if (this.cache.length > 16) {
2806 out = this.cache.slice(0, 16)
2807 this.cache = this.cache.slice(16)
2808 return out
2809 }
2810 } else {
2811 if (this.cache.length >= 16) {
2812 out = this.cache.slice(0, 16)
2813 this.cache = this.cache.slice(16)
2814 return out
2815 }
2816 }
2817
2818 return null
2819}
2820
2821Splitter.prototype.flush = function () {
2822 if (this.cache.length) return this.cache
2823}
2824
2825function unpad (last) {
2826 var padded = last[15]
2827 var i = -1
2828 while (++i < padded) {
2829 if (last[(i + (16 - padded))] !== padded) {
2830 throw new Error('unable to decrypt data')
2831 }
2832 }
2833 if (padded === 16) return
2834
2835 return last.slice(0, 16 - padded)
2836}
2837
2838function createDecipheriv (suite, password, iv) {
2839 var config = MODES[suite.toLowerCase()]
2840 if (!config) throw new TypeError('invalid suite type')
2841
2842 if (typeof iv === 'string') iv = Buffer.from(iv)
2843 if (iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
2844
2845 if (typeof password === 'string') password = Buffer.from(password)
2846 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
2847
2848 if (config.type === 'stream') {
2849 return new StreamCipher(config.module, password, iv, true)
2850 } else if (config.type === 'auth') {
2851 return new AuthCipher(config.module, password, iv, true)
2852 }
2853
2854 return new Decipher(config.module, password, iv)
2855}
2856
2857function createDecipher (suite, password) {
2858 var config = MODES[suite.toLowerCase()]
2859 if (!config) throw new TypeError('invalid suite type')
2860
2861 var keys = ebtk(password, false, config.key, config.iv)
2862 return createDecipheriv(suite, keys.key, keys.iv)
2863}
2864
2865exports.createDecipher = createDecipher
2866exports.createDecipheriv = createDecipheriv
2867
2868},{"./aes":9,"./authCipher":10,"./modes":21,"./streamCipher":24,"cipher-base":29,"evp_bytestokey":42,"inherits":45,"safe-buffer":68}],13:[function(require,module,exports){
2869var MODES = require('./modes')
2870var AuthCipher = require('./authCipher')
2871var Buffer = require('safe-buffer').Buffer
2872var StreamCipher = require('./streamCipher')
2873var Transform = require('cipher-base')
2874var aes = require('./aes')
2875var ebtk = require('evp_bytestokey')
2876var inherits = require('inherits')
2877
2878function Cipher (mode, key, iv) {
2879 Transform.call(this)
2880
2881 this._cache = new Splitter()
2882 this._cipher = new aes.AES(key)
2883 this._prev = Buffer.from(iv)
2884 this._mode = mode
2885 this._autopadding = true
2886}
2887
2888inherits(Cipher, Transform)
2889
2890Cipher.prototype._update = function (data) {
2891 this._cache.add(data)
2892 var chunk
2893 var thing
2894 var out = []
2895
2896 while ((chunk = this._cache.get())) {
2897 thing = this._mode.encrypt(this, chunk)
2898 out.push(thing)
2899 }
2900
2901 return Buffer.concat(out)
2902}
2903
2904var PADDING = Buffer.alloc(16, 0x10)
2905
2906Cipher.prototype._final = function () {
2907 var chunk = this._cache.flush()
2908 if (this._autopadding) {
2909 chunk = this._mode.encrypt(this, chunk)
2910 this._cipher.scrub()
2911 return chunk
2912 }
2913
2914 if (!chunk.equals(PADDING)) {
2915 this._cipher.scrub()
2916 throw new Error('data not multiple of block length')
2917 }
2918}
2919
2920Cipher.prototype.setAutoPadding = function (setTo) {
2921 this._autopadding = !!setTo
2922 return this
2923}
2924
2925function Splitter () {
2926 this.cache = Buffer.allocUnsafe(0)
2927}
2928
2929Splitter.prototype.add = function (data) {
2930 this.cache = Buffer.concat([this.cache, data])
2931}
2932
2933Splitter.prototype.get = function () {
2934 if (this.cache.length > 15) {
2935 var out = this.cache.slice(0, 16)
2936 this.cache = this.cache.slice(16)
2937 return out
2938 }
2939 return null
2940}
2941
2942Splitter.prototype.flush = function () {
2943 var len = 16 - this.cache.length
2944 var padBuff = Buffer.allocUnsafe(len)
2945
2946 var i = -1
2947 while (++i < len) {
2948 padBuff.writeUInt8(len, i)
2949 }
2950
2951 return Buffer.concat([this.cache, padBuff])
2952}
2953
2954function createCipheriv (suite, password, iv) {
2955 var config = MODES[suite.toLowerCase()]
2956 if (!config) throw new TypeError('invalid suite type')
2957
2958 if (typeof password === 'string') password = Buffer.from(password)
2959 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
2960
2961 if (typeof iv === 'string') iv = Buffer.from(iv)
2962 if (iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
2963
2964 if (config.type === 'stream') {
2965 return new StreamCipher(config.module, password, iv)
2966 } else if (config.type === 'auth') {
2967 return new AuthCipher(config.module, password, iv)
2968 }
2969
2970 return new Cipher(config.module, password, iv)
2971}
2972
2973function createCipher (suite, password) {
2974 var config = MODES[suite.toLowerCase()]
2975 if (!config) throw new TypeError('invalid suite type')
2976
2977 var keys = ebtk(password, false, config.key, config.iv)
2978 return createCipheriv(suite, keys.key, keys.iv)
2979}
2980
2981exports.createCipheriv = createCipheriv
2982exports.createCipher = createCipher
2983
2984},{"./aes":9,"./authCipher":10,"./modes":21,"./streamCipher":24,"cipher-base":29,"evp_bytestokey":42,"inherits":45,"safe-buffer":68}],14:[function(require,module,exports){
2985var Buffer = require('safe-buffer').Buffer
2986var ZEROES = Buffer.alloc(16, 0)
2987
2988function toArray (buf) {
2989 return [
2990 buf.readUInt32BE(0),
2991 buf.readUInt32BE(4),
2992 buf.readUInt32BE(8),
2993 buf.readUInt32BE(12)
2994 ]
2995}
2996
2997function fromArray (out) {
2998 var buf = Buffer.allocUnsafe(16)
2999 buf.writeUInt32BE(out[0] >>> 0, 0)
3000 buf.writeUInt32BE(out[1] >>> 0, 4)
3001 buf.writeUInt32BE(out[2] >>> 0, 8)
3002 buf.writeUInt32BE(out[3] >>> 0, 12)
3003 return buf
3004}
3005
3006function GHASH (key) {
3007 this.h = key
3008 this.state = Buffer.alloc(16, 0)
3009 this.cache = Buffer.allocUnsafe(0)
3010}
3011
3012// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
3013// by Juho Vähä-Herttua
3014GHASH.prototype.ghash = function (block) {
3015 var i = -1
3016 while (++i < block.length) {
3017 this.state[i] ^= block[i]
3018 }
3019 this._multiply()
3020}
3021
3022GHASH.prototype._multiply = function () {
3023 var Vi = toArray(this.h)
3024 var Zi = [0, 0, 0, 0]
3025 var j, xi, lsbVi
3026 var i = -1
3027 while (++i < 128) {
3028 xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
3029 if (xi) {
3030 // Z_i+1 = Z_i ^ V_i
3031 Zi[0] ^= Vi[0]
3032 Zi[1] ^= Vi[1]
3033 Zi[2] ^= Vi[2]
3034 Zi[3] ^= Vi[3]
3035 }
3036
3037 // Store the value of LSB(V_i)
3038 lsbVi = (Vi[3] & 1) !== 0
3039
3040 // V_i+1 = V_i >> 1
3041 for (j = 3; j > 0; j--) {
3042 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
3043 }
3044 Vi[0] = Vi[0] >>> 1
3045
3046 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
3047 if (lsbVi) {
3048 Vi[0] = Vi[0] ^ (0xe1 << 24)
3049 }
3050 }
3051 this.state = fromArray(Zi)
3052}
3053
3054GHASH.prototype.update = function (buf) {
3055 this.cache = Buffer.concat([this.cache, buf])
3056 var chunk
3057 while (this.cache.length >= 16) {
3058 chunk = this.cache.slice(0, 16)
3059 this.cache = this.cache.slice(16)
3060 this.ghash(chunk)
3061 }
3062}
3063
3064GHASH.prototype.final = function (abl, bl) {
3065 if (this.cache.length) {
3066 this.ghash(Buffer.concat([this.cache, ZEROES], 16))
3067 }
3068
3069 this.ghash(fromArray([0, abl, 0, bl]))
3070 return this.state
3071}
3072
3073module.exports = GHASH
3074
3075},{"safe-buffer":68}],15:[function(require,module,exports){
3076var xor = require('buffer-xor')
3077
3078exports.encrypt = function (self, block) {
3079 var data = xor(block, self._prev)
3080
3081 self._prev = self._cipher.encryptBlock(data)
3082 return self._prev
3083}
3084
3085exports.decrypt = function (self, block) {
3086 var pad = self._prev
3087
3088 self._prev = block
3089 var out = self._cipher.decryptBlock(block)
3090
3091 return xor(out, pad)
3092}
3093
3094},{"buffer-xor":26}],16:[function(require,module,exports){
3095var Buffer = require('safe-buffer').Buffer
3096var xor = require('buffer-xor')
3097
3098function encryptStart (self, data, decrypt) {
3099 var len = data.length
3100 var out = xor(data, self._cache)
3101 self._cache = self._cache.slice(len)
3102 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
3103 return out
3104}
3105
3106exports.encrypt = function (self, data, decrypt) {
3107 var out = Buffer.allocUnsafe(0)
3108 var len
3109
3110 while (data.length) {
3111 if (self._cache.length === 0) {
3112 self._cache = self._cipher.encryptBlock(self._prev)
3113 self._prev = Buffer.allocUnsafe(0)
3114 }
3115
3116 if (self._cache.length <= data.length) {
3117 len = self._cache.length
3118 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
3119 data = data.slice(len)
3120 } else {
3121 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
3122 break
3123 }
3124 }
3125
3126 return out
3127}
3128
3129},{"buffer-xor":26,"safe-buffer":68}],17:[function(require,module,exports){
3130var Buffer = require('safe-buffer').Buffer
3131
3132function encryptByte (self, byteParam, decrypt) {
3133 var pad
3134 var i = -1
3135 var len = 8
3136 var out = 0
3137 var bit, value
3138 while (++i < len) {
3139 pad = self._cipher.encryptBlock(self._prev)
3140 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
3141 value = pad[0] ^ bit
3142 out += ((value & 0x80) >> (i % 8))
3143 self._prev = shiftIn(self._prev, decrypt ? bit : value)
3144 }
3145 return out
3146}
3147
3148function shiftIn (buffer, value) {
3149 var len = buffer.length
3150 var i = -1
3151 var out = Buffer.allocUnsafe(buffer.length)
3152 buffer = Buffer.concat([buffer, Buffer.from([value])])
3153
3154 while (++i < len) {
3155 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
3156 }
3157
3158 return out
3159}
3160
3161exports.encrypt = function (self, chunk, decrypt) {
3162 var len = chunk.length
3163 var out = Buffer.allocUnsafe(len)
3164 var i = -1
3165
3166 while (++i < len) {
3167 out[i] = encryptByte(self, chunk[i], decrypt)
3168 }
3169
3170 return out
3171}
3172
3173},{"safe-buffer":68}],18:[function(require,module,exports){
3174(function (Buffer){
3175function encryptByte (self, byteParam, decrypt) {
3176 var pad = self._cipher.encryptBlock(self._prev)
3177 var out = pad[0] ^ byteParam
3178
3179 self._prev = Buffer.concat([
3180 self._prev.slice(1),
3181 Buffer.from([decrypt ? byteParam : out])
3182 ])
3183
3184 return out
3185}
3186
3187exports.encrypt = function (self, chunk, decrypt) {
3188 var len = chunk.length
3189 var out = Buffer.allocUnsafe(len)
3190 var i = -1
3191
3192 while (++i < len) {
3193 out[i] = encryptByte(self, chunk[i], decrypt)
3194 }
3195
3196 return out
3197}
3198
3199}).call(this,require("buffer").Buffer)
3200},{"buffer":27}],19:[function(require,module,exports){
3201(function (Buffer){
3202var xor = require('buffer-xor')
3203
3204function incr32 (iv) {
3205 var len = iv.length
3206 var item
3207 while (len--) {
3208 item = iv.readUInt8(len)
3209 if (item === 255) {
3210 iv.writeUInt8(0, len)
3211 } else {
3212 item++
3213 iv.writeUInt8(item, len)
3214 break
3215 }
3216 }
3217}
3218
3219function getBlock (self) {
3220 var out = self._cipher.encryptBlockRaw(self._prev)
3221 incr32(self._prev)
3222 return out
3223}
3224
3225var blockSize = 16
3226exports.encrypt = function (self, chunk) {
3227 var chunkNum = Math.ceil(chunk.length / blockSize)
3228 var start = self._cache.length
3229 self._cache = Buffer.concat([
3230 self._cache,
3231 Buffer.allocUnsafe(chunkNum * blockSize)
3232 ])
3233 for (var i = 0; i < chunkNum; i++) {
3234 var out = getBlock(self)
3235 var offset = start + i * blockSize
3236 self._cache.writeUInt32BE(out[0], offset + 0)
3237 self._cache.writeUInt32BE(out[1], offset + 4)
3238 self._cache.writeUInt32BE(out[2], offset + 8)
3239 self._cache.writeUInt32BE(out[3], offset + 12)
3240 }
3241 var pad = self._cache.slice(0, chunk.length)
3242 self._cache = self._cache.slice(chunk.length)
3243 return xor(chunk, pad)
3244}
3245
3246}).call(this,require("buffer").Buffer)
3247},{"buffer":27,"buffer-xor":26}],20:[function(require,module,exports){
3248exports.encrypt = function (self, block) {
3249 return self._cipher.encryptBlock(block)
3250}
3251
3252exports.decrypt = function (self, block) {
3253 return self._cipher.decryptBlock(block)
3254}
3255
3256},{}],21:[function(require,module,exports){
3257var modeModules = {
3258 ECB: require('./ecb'),
3259 CBC: require('./cbc'),
3260 CFB: require('./cfb'),
3261 CFB8: require('./cfb8'),
3262 CFB1: require('./cfb1'),
3263 OFB: require('./ofb'),
3264 CTR: require('./ctr'),
3265 GCM: require('./ctr')
3266}
3267
3268var modes = require('./list.json')
3269
3270for (var key in modes) {
3271 modes[key].module = modeModules[modes[key].mode]
3272}
3273
3274module.exports = modes
3275
3276},{"./cbc":15,"./cfb":16,"./cfb1":17,"./cfb8":18,"./ctr":19,"./ecb":20,"./list.json":22,"./ofb":23}],22:[function(require,module,exports){
3277module.exports={
3278 "aes-128-ecb": {
3279 "cipher": "AES",
3280 "key": 128,
3281 "iv": 0,
3282 "mode": "ECB",
3283 "type": "block"
3284 },
3285 "aes-192-ecb": {
3286 "cipher": "AES",
3287 "key": 192,
3288 "iv": 0,
3289 "mode": "ECB",
3290 "type": "block"
3291 },
3292 "aes-256-ecb": {
3293 "cipher": "AES",
3294 "key": 256,
3295 "iv": 0,
3296 "mode": "ECB",
3297 "type": "block"
3298 },
3299 "aes-128-cbc": {
3300 "cipher": "AES",
3301 "key": 128,
3302 "iv": 16,
3303 "mode": "CBC",
3304 "type": "block"
3305 },
3306 "aes-192-cbc": {
3307 "cipher": "AES",
3308 "key": 192,
3309 "iv": 16,
3310 "mode": "CBC",
3311 "type": "block"
3312 },
3313 "aes-256-cbc": {
3314 "cipher": "AES",
3315 "key": 256,
3316 "iv": 16,
3317 "mode": "CBC",
3318 "type": "block"
3319 },
3320 "aes128": {
3321 "cipher": "AES",
3322 "key": 128,
3323 "iv": 16,
3324 "mode": "CBC",
3325 "type": "block"
3326 },
3327 "aes192": {
3328 "cipher": "AES",
3329 "key": 192,
3330 "iv": 16,
3331 "mode": "CBC",
3332 "type": "block"
3333 },
3334 "aes256": {
3335 "cipher": "AES",
3336 "key": 256,
3337 "iv": 16,
3338 "mode": "CBC",
3339 "type": "block"
3340 },
3341 "aes-128-cfb": {
3342 "cipher": "AES",
3343 "key": 128,
3344 "iv": 16,
3345 "mode": "CFB",
3346 "type": "stream"
3347 },
3348 "aes-192-cfb": {
3349 "cipher": "AES",
3350 "key": 192,
3351 "iv": 16,
3352 "mode": "CFB",
3353 "type": "stream"
3354 },
3355 "aes-256-cfb": {
3356 "cipher": "AES",
3357 "key": 256,
3358 "iv": 16,
3359 "mode": "CFB",
3360 "type": "stream"
3361 },
3362 "aes-128-cfb8": {
3363 "cipher": "AES",
3364 "key": 128,
3365 "iv": 16,
3366 "mode": "CFB8",
3367 "type": "stream"
3368 },
3369 "aes-192-cfb8": {
3370 "cipher": "AES",
3371 "key": 192,
3372 "iv": 16,
3373 "mode": "CFB8",
3374 "type": "stream"
3375 },
3376 "aes-256-cfb8": {
3377 "cipher": "AES",
3378 "key": 256,
3379 "iv": 16,
3380 "mode": "CFB8",
3381 "type": "stream"
3382 },
3383 "aes-128-cfb1": {
3384 "cipher": "AES",
3385 "key": 128,
3386 "iv": 16,
3387 "mode": "CFB1",
3388 "type": "stream"
3389 },
3390 "aes-192-cfb1": {
3391 "cipher": "AES",
3392 "key": 192,
3393 "iv": 16,
3394 "mode": "CFB1",
3395 "type": "stream"
3396 },
3397 "aes-256-cfb1": {
3398 "cipher": "AES",
3399 "key": 256,
3400 "iv": 16,
3401 "mode": "CFB1",
3402 "type": "stream"
3403 },
3404 "aes-128-ofb": {
3405 "cipher": "AES",
3406 "key": 128,
3407 "iv": 16,
3408 "mode": "OFB",
3409 "type": "stream"
3410 },
3411 "aes-192-ofb": {
3412 "cipher": "AES",
3413 "key": 192,
3414 "iv": 16,
3415 "mode": "OFB",
3416 "type": "stream"
3417 },
3418 "aes-256-ofb": {
3419 "cipher": "AES",
3420 "key": 256,
3421 "iv": 16,
3422 "mode": "OFB",
3423 "type": "stream"
3424 },
3425 "aes-128-ctr": {
3426 "cipher": "AES",
3427 "key": 128,
3428 "iv": 16,
3429 "mode": "CTR",
3430 "type": "stream"
3431 },
3432 "aes-192-ctr": {
3433 "cipher": "AES",
3434 "key": 192,
3435 "iv": 16,
3436 "mode": "CTR",
3437 "type": "stream"
3438 },
3439 "aes-256-ctr": {
3440 "cipher": "AES",
3441 "key": 256,
3442 "iv": 16,
3443 "mode": "CTR",
3444 "type": "stream"
3445 },
3446 "aes-128-gcm": {
3447 "cipher": "AES",
3448 "key": 128,
3449 "iv": 12,
3450 "mode": "GCM",
3451 "type": "auth"
3452 },
3453 "aes-192-gcm": {
3454 "cipher": "AES",
3455 "key": 192,
3456 "iv": 12,
3457 "mode": "GCM",
3458 "type": "auth"
3459 },
3460 "aes-256-gcm": {
3461 "cipher": "AES",
3462 "key": 256,
3463 "iv": 12,
3464 "mode": "GCM",
3465 "type": "auth"
3466 }
3467}
3468
3469},{}],23:[function(require,module,exports){
3470(function (Buffer){
3471var xor = require('buffer-xor')
3472
3473function getBlock (self) {
3474 self._prev = self._cipher.encryptBlock(self._prev)
3475 return self._prev
3476}
3477
3478exports.encrypt = function (self, chunk) {
3479 while (self._cache.length < chunk.length) {
3480 self._cache = Buffer.concat([self._cache, getBlock(self)])
3481 }
3482
3483 var pad = self._cache.slice(0, chunk.length)
3484 self._cache = self._cache.slice(chunk.length)
3485 return xor(chunk, pad)
3486}
3487
3488}).call(this,require("buffer").Buffer)
3489},{"buffer":27,"buffer-xor":26}],24:[function(require,module,exports){
3490var aes = require('./aes')
3491var Buffer = require('safe-buffer').Buffer
3492var Transform = require('cipher-base')
3493var inherits = require('inherits')
3494
3495function StreamCipher (mode, key, iv, decrypt) {
3496 Transform.call(this)
3497
3498 this._cipher = new aes.AES(key)
3499 this._prev = Buffer.from(iv)
3500 this._cache = Buffer.allocUnsafe(0)
3501 this._secCache = Buffer.allocUnsafe(0)
3502 this._decrypt = decrypt
3503 this._mode = mode
3504}
3505
3506inherits(StreamCipher, Transform)
3507
3508StreamCipher.prototype._update = function (chunk) {
3509 return this._mode.encrypt(this, chunk, this._decrypt)
3510}
3511
3512StreamCipher.prototype._final = function () {
3513 this._cipher.scrub()
3514}
3515
3516module.exports = StreamCipher
3517
3518},{"./aes":9,"cipher-base":29,"inherits":45,"safe-buffer":68}],25:[function(require,module,exports){
3519var basex = require('base-x')
3520var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
3521
3522module.exports = basex(ALPHABET)
3523
3524},{"base-x":2}],26:[function(require,module,exports){
3525(function (Buffer){
3526module.exports = function xor (a, b) {
3527 var length = Math.min(a.length, b.length)
3528 var buffer = new Buffer(length)
3529
3530 for (var i = 0; i < length; ++i) {
3531 buffer[i] = a[i] ^ b[i]
3532 }
3533
3534 return buffer
3535}
3536
3537}).call(this,require("buffer").Buffer)
3538},{"buffer":27}],27:[function(require,module,exports){
3539/*!
3540 * The buffer module from node.js, for the browser.
3541 *
3542 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
3543 * @license MIT
3544 */
3545/* eslint-disable no-proto */
3546
3547'use strict'
3548
3549var base64 = require('base64-js')
3550var ieee754 = require('ieee754')
3551
3552exports.Buffer = Buffer
3553exports.SlowBuffer = SlowBuffer
3554exports.INSPECT_MAX_BYTES = 50
3555
3556var K_MAX_LENGTH = 0x7fffffff
3557exports.kMaxLength = K_MAX_LENGTH
3558
3559/**
3560 * If `Buffer.TYPED_ARRAY_SUPPORT`:
3561 * === true Use Uint8Array implementation (fastest)
3562 * === false Print warning and recommend using `buffer` v4.x which has an Object
3563 * implementation (most compatible, even IE6)
3564 *
3565 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
3566 * Opera 11.6+, iOS 4.2+.
3567 *
3568 * We report that the browser does not support typed arrays if the are not subclassable
3569 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
3570 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
3571 * for __proto__ and has a buggy typed array implementation.
3572 */
3573Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
3574
3575if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
3576 typeof console.error === 'function') {
3577 console.error(
3578 'This browser lacks typed array (Uint8Array) support which is required by ' +
3579 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
3580 )
3581}
3582
3583function typedArraySupport () {
3584 // Can typed array instances can be augmented?
3585 try {
3586 var arr = new Uint8Array(1)
3587 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
3588 return arr.foo() === 42
3589 } catch (e) {
3590 return false
3591 }
3592}
3593
3594function createBuffer (length) {
3595 if (length > K_MAX_LENGTH) {
3596 throw new RangeError('Invalid typed array length')
3597 }
3598 // Return an augmented `Uint8Array` instance
3599 var buf = new Uint8Array(length)
3600 buf.__proto__ = Buffer.prototype
3601 return buf
3602}
3603
3604/**
3605 * The Buffer constructor returns instances of `Uint8Array` that have their
3606 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
3607 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
3608 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
3609 * returns a single octet.
3610 *
3611 * The `Uint8Array` prototype remains unmodified.
3612 */
3613
3614function Buffer (arg, encodingOrOffset, length) {
3615 // Common case.
3616 if (typeof arg === 'number') {
3617 if (typeof encodingOrOffset === 'string') {
3618 throw new Error(
3619 'If encoding is specified then the first argument must be a string'
3620 )
3621 }
3622 return allocUnsafe(arg)
3623 }
3624 return from(arg, encodingOrOffset, length)
3625}
3626
3627// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
3628if (typeof Symbol !== 'undefined' && Symbol.species &&
3629 Buffer[Symbol.species] === Buffer) {
3630 Object.defineProperty(Buffer, Symbol.species, {
3631 value: null,
3632 configurable: true,
3633 enumerable: false,
3634 writable: false
3635 })
3636}
3637
3638Buffer.poolSize = 8192 // not used by this implementation
3639
3640function from (value, encodingOrOffset, length) {
3641 if (typeof value === 'number') {
3642 throw new TypeError('"value" argument must not be a number')
3643 }
3644
3645 if (isArrayBuffer(value)) {
3646 return fromArrayBuffer(value, encodingOrOffset, length)
3647 }
3648
3649 if (typeof value === 'string') {
3650 return fromString(value, encodingOrOffset)
3651 }
3652
3653 return fromObject(value)
3654}
3655
3656/**
3657 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
3658 * if value is a number.
3659 * Buffer.from(str[, encoding])
3660 * Buffer.from(array)
3661 * Buffer.from(buffer)
3662 * Buffer.from(arrayBuffer[, byteOffset[, length]])
3663 **/
3664Buffer.from = function (value, encodingOrOffset, length) {
3665 return from(value, encodingOrOffset, length)
3666}
3667
3668// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
3669// https://github.com/feross/buffer/pull/148
3670Buffer.prototype.__proto__ = Uint8Array.prototype
3671Buffer.__proto__ = Uint8Array
3672
3673function assertSize (size) {
3674 if (typeof size !== 'number') {
3675 throw new TypeError('"size" argument must be a number')
3676 } else if (size < 0) {
3677 throw new RangeError('"size" argument must not be negative')
3678 }
3679}
3680
3681function alloc (size, fill, encoding) {
3682 assertSize(size)
3683 if (size <= 0) {
3684 return createBuffer(size)
3685 }
3686 if (fill !== undefined) {
3687 // Only pay attention to encoding if it's a string. This
3688 // prevents accidentally sending in a number that would
3689 // be interpretted as a start offset.
3690 return typeof encoding === 'string'
3691 ? createBuffer(size).fill(fill, encoding)
3692 : createBuffer(size).fill(fill)
3693 }
3694 return createBuffer(size)
3695}
3696
3697/**
3698 * Creates a new filled Buffer instance.
3699 * alloc(size[, fill[, encoding]])
3700 **/
3701Buffer.alloc = function (size, fill, encoding) {
3702 return alloc(size, fill, encoding)
3703}
3704
3705function allocUnsafe (size) {
3706 assertSize(size)
3707 return createBuffer(size < 0 ? 0 : checked(size) | 0)
3708}
3709
3710/**
3711 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
3712 * */
3713Buffer.allocUnsafe = function (size) {
3714 return allocUnsafe(size)
3715}
3716/**
3717 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
3718 */
3719Buffer.allocUnsafeSlow = function (size) {
3720 return allocUnsafe(size)
3721}
3722
3723function fromString (string, encoding) {
3724 if (typeof encoding !== 'string' || encoding === '') {
3725 encoding = 'utf8'
3726 }
3727
3728 if (!Buffer.isEncoding(encoding)) {
3729 throw new TypeError('"encoding" must be a valid string encoding')
3730 }
3731
3732 var length = byteLength(string, encoding) | 0
3733 var buf = createBuffer(length)
3734
3735 var actual = buf.write(string, encoding)
3736
3737 if (actual !== length) {
3738 // Writing a hex string, for example, that contains invalid characters will
3739 // cause everything after the first invalid character to be ignored. (e.g.
3740 // 'abxxcd' will be treated as 'ab')
3741 buf = buf.slice(0, actual)
3742 }
3743
3744 return buf
3745}
3746
3747function fromArrayLike (array) {
3748 var length = array.length < 0 ? 0 : checked(array.length) | 0
3749 var buf = createBuffer(length)
3750 for (var i = 0; i < length; i += 1) {
3751 buf[i] = array[i] & 255
3752 }
3753 return buf
3754}
3755
3756function fromArrayBuffer (array, byteOffset, length) {
3757 if (byteOffset < 0 || array.byteLength < byteOffset) {
3758 throw new RangeError('\'offset\' is out of bounds')
3759 }
3760
3761 if (array.byteLength < byteOffset + (length || 0)) {
3762 throw new RangeError('\'length\' is out of bounds')
3763 }
3764
3765 var buf
3766 if (byteOffset === undefined && length === undefined) {
3767 buf = new Uint8Array(array)
3768 } else if (length === undefined) {
3769 buf = new Uint8Array(array, byteOffset)
3770 } else {
3771 buf = new Uint8Array(array, byteOffset, length)
3772 }
3773
3774 // Return an augmented `Uint8Array` instance
3775 buf.__proto__ = Buffer.prototype
3776 return buf
3777}
3778
3779function fromObject (obj) {
3780 if (Buffer.isBuffer(obj)) {
3781 var len = checked(obj.length) | 0
3782 var buf = createBuffer(len)
3783
3784 if (buf.length === 0) {
3785 return buf
3786 }
3787
3788 obj.copy(buf, 0, 0, len)
3789 return buf
3790 }
3791
3792 if (obj) {
3793 if (isArrayBufferView(obj) || 'length' in obj) {
3794 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
3795 return createBuffer(0)
3796 }
3797 return fromArrayLike(obj)
3798 }
3799
3800 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
3801 return fromArrayLike(obj.data)
3802 }
3803 }
3804
3805 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
3806}
3807
3808function checked (length) {
3809 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
3810 // length is NaN (which is otherwise coerced to zero.)
3811 if (length >= K_MAX_LENGTH) {
3812 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
3813 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
3814 }
3815 return length | 0
3816}
3817
3818function SlowBuffer (length) {
3819 if (+length != length) { // eslint-disable-line eqeqeq
3820 length = 0
3821 }
3822 return Buffer.alloc(+length)
3823}
3824
3825Buffer.isBuffer = function isBuffer (b) {
3826 return b != null && b._isBuffer === true
3827}
3828
3829Buffer.compare = function compare (a, b) {
3830 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
3831 throw new TypeError('Arguments must be Buffers')
3832 }
3833
3834 if (a === b) return 0
3835
3836 var x = a.length
3837 var y = b.length
3838
3839 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
3840 if (a[i] !== b[i]) {
3841 x = a[i]
3842 y = b[i]
3843 break
3844 }
3845 }
3846
3847 if (x < y) return -1
3848 if (y < x) return 1
3849 return 0
3850}
3851
3852Buffer.isEncoding = function isEncoding (encoding) {
3853 switch (String(encoding).toLowerCase()) {
3854 case 'hex':
3855 case 'utf8':
3856 case 'utf-8':
3857 case 'ascii':
3858 case 'latin1':
3859 case 'binary':
3860 case 'base64':
3861 case 'ucs2':
3862 case 'ucs-2':
3863 case 'utf16le':
3864 case 'utf-16le':
3865 return true
3866 default:
3867 return false
3868 }
3869}
3870
3871Buffer.concat = function concat (list, length) {
3872 if (!Array.isArray(list)) {
3873 throw new TypeError('"list" argument must be an Array of Buffers')
3874 }
3875
3876 if (list.length === 0) {
3877 return Buffer.alloc(0)
3878 }
3879
3880 var i
3881 if (length === undefined) {
3882 length = 0
3883 for (i = 0; i < list.length; ++i) {
3884 length += list[i].length
3885 }
3886 }
3887
3888 var buffer = Buffer.allocUnsafe(length)
3889 var pos = 0
3890 for (i = 0; i < list.length; ++i) {
3891 var buf = list[i]
3892 if (!Buffer.isBuffer(buf)) {
3893 throw new TypeError('"list" argument must be an Array of Buffers')
3894 }
3895 buf.copy(buffer, pos)
3896 pos += buf.length
3897 }
3898 return buffer
3899}
3900
3901function byteLength (string, encoding) {
3902 if (Buffer.isBuffer(string)) {
3903 return string.length
3904 }
3905 if (isArrayBufferView(string) || isArrayBuffer(string)) {
3906 return string.byteLength
3907 }
3908 if (typeof string !== 'string') {
3909 string = '' + string
3910 }
3911
3912 var len = string.length
3913 if (len === 0) return 0
3914
3915 // Use a for loop to avoid recursion
3916 var loweredCase = false
3917 for (;;) {
3918 switch (encoding) {
3919 case 'ascii':
3920 case 'latin1':
3921 case 'binary':
3922 return len
3923 case 'utf8':
3924 case 'utf-8':
3925 case undefined:
3926 return utf8ToBytes(string).length
3927 case 'ucs2':
3928 case 'ucs-2':
3929 case 'utf16le':
3930 case 'utf-16le':
3931 return len * 2
3932 case 'hex':
3933 return len >>> 1
3934 case 'base64':
3935 return base64ToBytes(string).length
3936 default:
3937 if (loweredCase) return utf8ToBytes(string).length // assume utf8
3938 encoding = ('' + encoding).toLowerCase()
3939 loweredCase = true
3940 }
3941 }
3942}
3943Buffer.byteLength = byteLength
3944
3945function slowToString (encoding, start, end) {
3946 var loweredCase = false
3947
3948 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
3949 // property of a typed array.
3950
3951 // This behaves neither like String nor Uint8Array in that we set start/end
3952 // to their upper/lower bounds if the value passed is out of range.
3953 // undefined is handled specially as per ECMA-262 6th Edition,
3954 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
3955 if (start === undefined || start < 0) {
3956 start = 0
3957 }
3958 // Return early if start > this.length. Done here to prevent potential uint32
3959 // coercion fail below.
3960 if (start > this.length) {
3961 return ''
3962 }
3963
3964 if (end === undefined || end > this.length) {
3965 end = this.length
3966 }
3967
3968 if (end <= 0) {
3969 return ''
3970 }
3971
3972 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
3973 end >>>= 0
3974 start >>>= 0
3975
3976 if (end <= start) {
3977 return ''
3978 }
3979
3980 if (!encoding) encoding = 'utf8'
3981
3982 while (true) {
3983 switch (encoding) {
3984 case 'hex':
3985 return hexSlice(this, start, end)
3986
3987 case 'utf8':
3988 case 'utf-8':
3989 return utf8Slice(this, start, end)
3990
3991 case 'ascii':
3992 return asciiSlice(this, start, end)
3993
3994 case 'latin1':
3995 case 'binary':
3996 return latin1Slice(this, start, end)
3997
3998 case 'base64':
3999 return base64Slice(this, start, end)
4000
4001 case 'ucs2':
4002 case 'ucs-2':
4003 case 'utf16le':
4004 case 'utf-16le':
4005 return utf16leSlice(this, start, end)
4006
4007 default:
4008 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
4009 encoding = (encoding + '').toLowerCase()
4010 loweredCase = true
4011 }
4012 }
4013}
4014
4015// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
4016// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
4017// reliably in a browserify context because there could be multiple different
4018// copies of the 'buffer' package in use. This method works even for Buffer
4019// instances that were created from another copy of the `buffer` package.
4020// See: https://github.com/feross/buffer/issues/154
4021Buffer.prototype._isBuffer = true
4022
4023function swap (b, n, m) {
4024 var i = b[n]
4025 b[n] = b[m]
4026 b[m] = i
4027}
4028
4029Buffer.prototype.swap16 = function swap16 () {
4030 var len = this.length
4031 if (len % 2 !== 0) {
4032 throw new RangeError('Buffer size must be a multiple of 16-bits')
4033 }
4034 for (var i = 0; i < len; i += 2) {
4035 swap(this, i, i + 1)
4036 }
4037 return this
4038}
4039
4040Buffer.prototype.swap32 = function swap32 () {
4041 var len = this.length
4042 if (len % 4 !== 0) {
4043 throw new RangeError('Buffer size must be a multiple of 32-bits')
4044 }
4045 for (var i = 0; i < len; i += 4) {
4046 swap(this, i, i + 3)
4047 swap(this, i + 1, i + 2)
4048 }
4049 return this
4050}
4051
4052Buffer.prototype.swap64 = function swap64 () {
4053 var len = this.length
4054 if (len % 8 !== 0) {
4055 throw new RangeError('Buffer size must be a multiple of 64-bits')
4056 }
4057 for (var i = 0; i < len; i += 8) {
4058 swap(this, i, i + 7)
4059 swap(this, i + 1, i + 6)
4060 swap(this, i + 2, i + 5)
4061 swap(this, i + 3, i + 4)
4062 }
4063 return this
4064}
4065
4066Buffer.prototype.toString = function toString () {
4067 var length = this.length
4068 if (length === 0) return ''
4069 if (arguments.length === 0) return utf8Slice(this, 0, length)
4070 return slowToString.apply(this, arguments)
4071}
4072
4073Buffer.prototype.equals = function equals (b) {
4074 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
4075 if (this === b) return true
4076 return Buffer.compare(this, b) === 0
4077}
4078
4079Buffer.prototype.inspect = function inspect () {
4080 var str = ''
4081 var max = exports.INSPECT_MAX_BYTES
4082 if (this.length > 0) {
4083 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
4084 if (this.length > max) str += ' ... '
4085 }
4086 return '<Buffer ' + str + '>'
4087}
4088
4089Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
4090 if (!Buffer.isBuffer(target)) {
4091 throw new TypeError('Argument must be a Buffer')
4092 }
4093
4094 if (start === undefined) {
4095 start = 0
4096 }
4097 if (end === undefined) {
4098 end = target ? target.length : 0
4099 }
4100 if (thisStart === undefined) {
4101 thisStart = 0
4102 }
4103 if (thisEnd === undefined) {
4104 thisEnd = this.length
4105 }
4106
4107 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
4108 throw new RangeError('out of range index')
4109 }
4110
4111 if (thisStart >= thisEnd && start >= end) {
4112 return 0
4113 }
4114 if (thisStart >= thisEnd) {
4115 return -1
4116 }
4117 if (start >= end) {
4118 return 1
4119 }
4120
4121 start >>>= 0
4122 end >>>= 0
4123 thisStart >>>= 0
4124 thisEnd >>>= 0
4125
4126 if (this === target) return 0
4127
4128 var x = thisEnd - thisStart
4129 var y = end - start
4130 var len = Math.min(x, y)
4131
4132 var thisCopy = this.slice(thisStart, thisEnd)
4133 var targetCopy = target.slice(start, end)
4134
4135 for (var i = 0; i < len; ++i) {
4136 if (thisCopy[i] !== targetCopy[i]) {
4137 x = thisCopy[i]
4138 y = targetCopy[i]
4139 break
4140 }
4141 }
4142
4143 if (x < y) return -1
4144 if (y < x) return 1
4145 return 0
4146}
4147
4148// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
4149// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
4150//
4151// Arguments:
4152// - buffer - a Buffer to search
4153// - val - a string, Buffer, or number
4154// - byteOffset - an index into `buffer`; will be clamped to an int32
4155// - encoding - an optional encoding, relevant is val is a string
4156// - dir - true for indexOf, false for lastIndexOf
4157function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
4158 // Empty buffer means no match
4159 if (buffer.length === 0) return -1
4160
4161 // Normalize byteOffset
4162 if (typeof byteOffset === 'string') {
4163 encoding = byteOffset
4164 byteOffset = 0
4165 } else if (byteOffset > 0x7fffffff) {
4166 byteOffset = 0x7fffffff
4167 } else if (byteOffset < -0x80000000) {
4168 byteOffset = -0x80000000
4169 }
4170 byteOffset = +byteOffset // Coerce to Number.
4171 if (numberIsNaN(byteOffset)) {
4172 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
4173 byteOffset = dir ? 0 : (buffer.length - 1)
4174 }
4175
4176 // Normalize byteOffset: negative offsets start from the end of the buffer
4177 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
4178 if (byteOffset >= buffer.length) {
4179 if (dir) return -1
4180 else byteOffset = buffer.length - 1
4181 } else if (byteOffset < 0) {
4182 if (dir) byteOffset = 0
4183 else return -1
4184 }
4185
4186 // Normalize val
4187 if (typeof val === 'string') {
4188 val = Buffer.from(val, encoding)
4189 }
4190
4191 // Finally, search either indexOf (if dir is true) or lastIndexOf
4192 if (Buffer.isBuffer(val)) {
4193 // Special case: looking for empty string/buffer always fails
4194 if (val.length === 0) {
4195 return -1
4196 }
4197 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
4198 } else if (typeof val === 'number') {
4199 val = val & 0xFF // Search for a byte value [0-255]
4200 if (typeof Uint8Array.prototype.indexOf === 'function') {
4201 if (dir) {
4202 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
4203 } else {
4204 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
4205 }
4206 }
4207 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
4208 }
4209
4210 throw new TypeError('val must be string, number or Buffer')
4211}
4212
4213function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
4214 var indexSize = 1
4215 var arrLength = arr.length
4216 var valLength = val.length
4217
4218 if (encoding !== undefined) {
4219 encoding = String(encoding).toLowerCase()
4220 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
4221 encoding === 'utf16le' || encoding === 'utf-16le') {
4222 if (arr.length < 2 || val.length < 2) {
4223 return -1
4224 }
4225 indexSize = 2
4226 arrLength /= 2
4227 valLength /= 2
4228 byteOffset /= 2
4229 }
4230 }
4231
4232 function read (buf, i) {
4233 if (indexSize === 1) {
4234 return buf[i]
4235 } else {
4236 return buf.readUInt16BE(i * indexSize)
4237 }
4238 }
4239
4240 var i
4241 if (dir) {
4242 var foundIndex = -1
4243 for (i = byteOffset; i < arrLength; i++) {
4244 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
4245 if (foundIndex === -1) foundIndex = i
4246 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
4247 } else {
4248 if (foundIndex !== -1) i -= i - foundIndex
4249 foundIndex = -1
4250 }
4251 }
4252 } else {
4253 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
4254 for (i = byteOffset; i >= 0; i--) {
4255 var found = true
4256 for (var j = 0; j < valLength; j++) {
4257 if (read(arr, i + j) !== read(val, j)) {
4258 found = false
4259 break
4260 }
4261 }
4262 if (found) return i
4263 }
4264 }
4265
4266 return -1
4267}
4268
4269Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
4270 return this.indexOf(val, byteOffset, encoding) !== -1
4271}
4272
4273Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
4274 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
4275}
4276
4277Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
4278 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
4279}
4280
4281function hexWrite (buf, string, offset, length) {
4282 offset = Number(offset) || 0
4283 var remaining = buf.length - offset
4284 if (!length) {
4285 length = remaining
4286 } else {
4287 length = Number(length)
4288 if (length > remaining) {
4289 length = remaining
4290 }
4291 }
4292
4293 // must be an even number of digits
4294 var strLen = string.length
4295 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
4296
4297 if (length > strLen / 2) {
4298 length = strLen / 2
4299 }
4300 for (var i = 0; i < length; ++i) {
4301 var parsed = parseInt(string.substr(i * 2, 2), 16)
4302 if (numberIsNaN(parsed)) return i
4303 buf[offset + i] = parsed
4304 }
4305 return i
4306}
4307
4308function utf8Write (buf, string, offset, length) {
4309 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
4310}
4311
4312function asciiWrite (buf, string, offset, length) {
4313 return blitBuffer(asciiToBytes(string), buf, offset, length)
4314}
4315
4316function latin1Write (buf, string, offset, length) {
4317 return asciiWrite(buf, string, offset, length)
4318}
4319
4320function base64Write (buf, string, offset, length) {
4321 return blitBuffer(base64ToBytes(string), buf, offset, length)
4322}
4323
4324function ucs2Write (buf, string, offset, length) {
4325 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
4326}
4327
4328Buffer.prototype.write = function write (string, offset, length, encoding) {
4329 // Buffer#write(string)
4330 if (offset === undefined) {
4331 encoding = 'utf8'
4332 length = this.length
4333 offset = 0
4334 // Buffer#write(string, encoding)
4335 } else if (length === undefined && typeof offset === 'string') {
4336 encoding = offset
4337 length = this.length
4338 offset = 0
4339 // Buffer#write(string, offset[, length][, encoding])
4340 } else if (isFinite(offset)) {
4341 offset = offset >>> 0
4342 if (isFinite(length)) {
4343 length = length >>> 0
4344 if (encoding === undefined) encoding = 'utf8'
4345 } else {
4346 encoding = length
4347 length = undefined
4348 }
4349 } else {
4350 throw new Error(
4351 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
4352 )
4353 }
4354
4355 var remaining = this.length - offset
4356 if (length === undefined || length > remaining) length = remaining
4357
4358 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
4359 throw new RangeError('Attempt to write outside buffer bounds')
4360 }
4361
4362 if (!encoding) encoding = 'utf8'
4363
4364 var loweredCase = false
4365 for (;;) {
4366 switch (encoding) {
4367 case 'hex':
4368 return hexWrite(this, string, offset, length)
4369
4370 case 'utf8':
4371 case 'utf-8':
4372 return utf8Write(this, string, offset, length)
4373
4374 case 'ascii':
4375 return asciiWrite(this, string, offset, length)
4376
4377 case 'latin1':
4378 case 'binary':
4379 return latin1Write(this, string, offset, length)
4380
4381 case 'base64':
4382 // Warning: maxLength not taken into account in base64Write
4383 return base64Write(this, string, offset, length)
4384
4385 case 'ucs2':
4386 case 'ucs-2':
4387 case 'utf16le':
4388 case 'utf-16le':
4389 return ucs2Write(this, string, offset, length)
4390
4391 default:
4392 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
4393 encoding = ('' + encoding).toLowerCase()
4394 loweredCase = true
4395 }
4396 }
4397}
4398
4399Buffer.prototype.toJSON = function toJSON () {
4400 return {
4401 type: 'Buffer',
4402 data: Array.prototype.slice.call(this._arr || this, 0)
4403 }
4404}
4405
4406function base64Slice (buf, start, end) {
4407 if (start === 0 && end === buf.length) {
4408 return base64.fromByteArray(buf)
4409 } else {
4410 return base64.fromByteArray(buf.slice(start, end))
4411 }
4412}
4413
4414function utf8Slice (buf, start, end) {
4415 end = Math.min(buf.length, end)
4416 var res = []
4417
4418 var i = start
4419 while (i < end) {
4420 var firstByte = buf[i]
4421 var codePoint = null
4422 var bytesPerSequence = (firstByte > 0xEF) ? 4
4423 : (firstByte > 0xDF) ? 3
4424 : (firstByte > 0xBF) ? 2
4425 : 1
4426
4427 if (i + bytesPerSequence <= end) {
4428 var secondByte, thirdByte, fourthByte, tempCodePoint
4429
4430 switch (bytesPerSequence) {
4431 case 1:
4432 if (firstByte < 0x80) {
4433 codePoint = firstByte
4434 }
4435 break
4436 case 2:
4437 secondByte = buf[i + 1]
4438 if ((secondByte & 0xC0) === 0x80) {
4439 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
4440 if (tempCodePoint > 0x7F) {
4441 codePoint = tempCodePoint
4442 }
4443 }
4444 break
4445 case 3:
4446 secondByte = buf[i + 1]
4447 thirdByte = buf[i + 2]
4448 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
4449 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
4450 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
4451 codePoint = tempCodePoint
4452 }
4453 }
4454 break
4455 case 4:
4456 secondByte = buf[i + 1]
4457 thirdByte = buf[i + 2]
4458 fourthByte = buf[i + 3]
4459 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
4460 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
4461 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
4462 codePoint = tempCodePoint
4463 }
4464 }
4465 }
4466 }
4467
4468 if (codePoint === null) {
4469 // we did not generate a valid codePoint so insert a
4470 // replacement char (U+FFFD) and advance only 1 byte
4471 codePoint = 0xFFFD
4472 bytesPerSequence = 1
4473 } else if (codePoint > 0xFFFF) {
4474 // encode to utf16 (surrogate pair dance)
4475 codePoint -= 0x10000
4476 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
4477 codePoint = 0xDC00 | codePoint & 0x3FF
4478 }
4479
4480 res.push(codePoint)
4481 i += bytesPerSequence
4482 }
4483
4484 return decodeCodePointsArray(res)
4485}
4486
4487// Based on http://stackoverflow.com/a/22747272/680742, the browser with
4488// the lowest limit is Chrome, with 0x10000 args.
4489// We go 1 magnitude less, for safety
4490var MAX_ARGUMENTS_LENGTH = 0x1000
4491
4492function decodeCodePointsArray (codePoints) {
4493 var len = codePoints.length
4494 if (len <= MAX_ARGUMENTS_LENGTH) {
4495 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
4496 }
4497
4498 // Decode in chunks to avoid "call stack size exceeded".
4499 var res = ''
4500 var i = 0
4501 while (i < len) {
4502 res += String.fromCharCode.apply(
4503 String,
4504 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
4505 )
4506 }
4507 return res
4508}
4509
4510function asciiSlice (buf, start, end) {
4511 var ret = ''
4512 end = Math.min(buf.length, end)
4513
4514 for (var i = start; i < end; ++i) {
4515 ret += String.fromCharCode(buf[i] & 0x7F)
4516 }
4517 return ret
4518}
4519
4520function latin1Slice (buf, start, end) {
4521 var ret = ''
4522 end = Math.min(buf.length, end)
4523
4524 for (var i = start; i < end; ++i) {
4525 ret += String.fromCharCode(buf[i])
4526 }
4527 return ret
4528}
4529
4530function hexSlice (buf, start, end) {
4531 var len = buf.length
4532
4533 if (!start || start < 0) start = 0
4534 if (!end || end < 0 || end > len) end = len
4535
4536 var out = ''
4537 for (var i = start; i < end; ++i) {
4538 out += toHex(buf[i])
4539 }
4540 return out
4541}
4542
4543function utf16leSlice (buf, start, end) {
4544 var bytes = buf.slice(start, end)
4545 var res = ''
4546 for (var i = 0; i < bytes.length; i += 2) {
4547 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
4548 }
4549 return res
4550}
4551
4552Buffer.prototype.slice = function slice (start, end) {
4553 var len = this.length
4554 start = ~~start
4555 end = end === undefined ? len : ~~end
4556
4557 if (start < 0) {
4558 start += len
4559 if (start < 0) start = 0
4560 } else if (start > len) {
4561 start = len
4562 }
4563
4564 if (end < 0) {
4565 end += len
4566 if (end < 0) end = 0
4567 } else if (end > len) {
4568 end = len
4569 }
4570
4571 if (end < start) end = start
4572
4573 var newBuf = this.subarray(start, end)
4574 // Return an augmented `Uint8Array` instance
4575 newBuf.__proto__ = Buffer.prototype
4576 return newBuf
4577}
4578
4579/*
4580 * Need to make sure that buffer isn't trying to write out of bounds.
4581 */
4582function checkOffset (offset, ext, length) {
4583 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
4584 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
4585}
4586
4587Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
4588 offset = offset >>> 0
4589 byteLength = byteLength >>> 0
4590 if (!noAssert) checkOffset(offset, byteLength, this.length)
4591
4592 var val = this[offset]
4593 var mul = 1
4594 var i = 0
4595 while (++i < byteLength && (mul *= 0x100)) {
4596 val += this[offset + i] * mul
4597 }
4598
4599 return val
4600}
4601
4602Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
4603 offset = offset >>> 0
4604 byteLength = byteLength >>> 0
4605 if (!noAssert) {
4606 checkOffset(offset, byteLength, this.length)
4607 }
4608
4609 var val = this[offset + --byteLength]
4610 var mul = 1
4611 while (byteLength > 0 && (mul *= 0x100)) {
4612 val += this[offset + --byteLength] * mul
4613 }
4614
4615 return val
4616}
4617
4618Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
4619 offset = offset >>> 0
4620 if (!noAssert) checkOffset(offset, 1, this.length)
4621 return this[offset]
4622}
4623
4624Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
4625 offset = offset >>> 0
4626 if (!noAssert) checkOffset(offset, 2, this.length)
4627 return this[offset] | (this[offset + 1] << 8)
4628}
4629
4630Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
4631 offset = offset >>> 0
4632 if (!noAssert) checkOffset(offset, 2, this.length)
4633 return (this[offset] << 8) | this[offset + 1]
4634}
4635
4636Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
4637 offset = offset >>> 0
4638 if (!noAssert) checkOffset(offset, 4, this.length)
4639
4640 return ((this[offset]) |
4641 (this[offset + 1] << 8) |
4642 (this[offset + 2] << 16)) +
4643 (this[offset + 3] * 0x1000000)
4644}
4645
4646Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
4647 offset = offset >>> 0
4648 if (!noAssert) checkOffset(offset, 4, this.length)
4649
4650 return (this[offset] * 0x1000000) +
4651 ((this[offset + 1] << 16) |
4652 (this[offset + 2] << 8) |
4653 this[offset + 3])
4654}
4655
4656Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
4657 offset = offset >>> 0
4658 byteLength = byteLength >>> 0
4659 if (!noAssert) checkOffset(offset, byteLength, this.length)
4660
4661 var val = this[offset]
4662 var mul = 1
4663 var i = 0
4664 while (++i < byteLength && (mul *= 0x100)) {
4665 val += this[offset + i] * mul
4666 }
4667 mul *= 0x80
4668
4669 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
4670
4671 return val
4672}
4673
4674Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
4675 offset = offset >>> 0
4676 byteLength = byteLength >>> 0
4677 if (!noAssert) checkOffset(offset, byteLength, this.length)
4678
4679 var i = byteLength
4680 var mul = 1
4681 var val = this[offset + --i]
4682 while (i > 0 && (mul *= 0x100)) {
4683 val += this[offset + --i] * mul
4684 }
4685 mul *= 0x80
4686
4687 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
4688
4689 return val
4690}
4691
4692Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
4693 offset = offset >>> 0
4694 if (!noAssert) checkOffset(offset, 1, this.length)
4695 if (!(this[offset] & 0x80)) return (this[offset])
4696 return ((0xff - this[offset] + 1) * -1)
4697}
4698
4699Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
4700 offset = offset >>> 0
4701 if (!noAssert) checkOffset(offset, 2, this.length)
4702 var val = this[offset] | (this[offset + 1] << 8)
4703 return (val & 0x8000) ? val | 0xFFFF0000 : val
4704}
4705
4706Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
4707 offset = offset >>> 0
4708 if (!noAssert) checkOffset(offset, 2, this.length)
4709 var val = this[offset + 1] | (this[offset] << 8)
4710 return (val & 0x8000) ? val | 0xFFFF0000 : val
4711}
4712
4713Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
4714 offset = offset >>> 0
4715 if (!noAssert) checkOffset(offset, 4, this.length)
4716
4717 return (this[offset]) |
4718 (this[offset + 1] << 8) |
4719 (this[offset + 2] << 16) |
4720 (this[offset + 3] << 24)
4721}
4722
4723Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
4724 offset = offset >>> 0
4725 if (!noAssert) checkOffset(offset, 4, this.length)
4726
4727 return (this[offset] << 24) |
4728 (this[offset + 1] << 16) |
4729 (this[offset + 2] << 8) |
4730 (this[offset + 3])
4731}
4732
4733Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
4734 offset = offset >>> 0
4735 if (!noAssert) checkOffset(offset, 4, this.length)
4736 return ieee754.read(this, offset, true, 23, 4)
4737}
4738
4739Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
4740 offset = offset >>> 0
4741 if (!noAssert) checkOffset(offset, 4, this.length)
4742 return ieee754.read(this, offset, false, 23, 4)
4743}
4744
4745Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
4746 offset = offset >>> 0
4747 if (!noAssert) checkOffset(offset, 8, this.length)
4748 return ieee754.read(this, offset, true, 52, 8)
4749}
4750
4751Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
4752 offset = offset >>> 0
4753 if (!noAssert) checkOffset(offset, 8, this.length)
4754 return ieee754.read(this, offset, false, 52, 8)
4755}
4756
4757function checkInt (buf, value, offset, ext, max, min) {
4758 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
4759 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
4760 if (offset + ext > buf.length) throw new RangeError('Index out of range')
4761}
4762
4763Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
4764 value = +value
4765 offset = offset >>> 0
4766 byteLength = byteLength >>> 0
4767 if (!noAssert) {
4768 var maxBytes = Math.pow(2, 8 * byteLength) - 1
4769 checkInt(this, value, offset, byteLength, maxBytes, 0)
4770 }
4771
4772 var mul = 1
4773 var i = 0
4774 this[offset] = value & 0xFF
4775 while (++i < byteLength && (mul *= 0x100)) {
4776 this[offset + i] = (value / mul) & 0xFF
4777 }
4778
4779 return offset + byteLength
4780}
4781
4782Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
4783 value = +value
4784 offset = offset >>> 0
4785 byteLength = byteLength >>> 0
4786 if (!noAssert) {
4787 var maxBytes = Math.pow(2, 8 * byteLength) - 1
4788 checkInt(this, value, offset, byteLength, maxBytes, 0)
4789 }
4790
4791 var i = byteLength - 1
4792 var mul = 1
4793 this[offset + i] = value & 0xFF
4794 while (--i >= 0 && (mul *= 0x100)) {
4795 this[offset + i] = (value / mul) & 0xFF
4796 }
4797
4798 return offset + byteLength
4799}
4800
4801Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
4802 value = +value
4803 offset = offset >>> 0
4804 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
4805 this[offset] = (value & 0xff)
4806 return offset + 1
4807}
4808
4809Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
4810 value = +value
4811 offset = offset >>> 0
4812 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
4813 this[offset] = (value & 0xff)
4814 this[offset + 1] = (value >>> 8)
4815 return offset + 2
4816}
4817
4818Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
4819 value = +value
4820 offset = offset >>> 0
4821 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
4822 this[offset] = (value >>> 8)
4823 this[offset + 1] = (value & 0xff)
4824 return offset + 2
4825}
4826
4827Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
4828 value = +value
4829 offset = offset >>> 0
4830 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
4831 this[offset + 3] = (value >>> 24)
4832 this[offset + 2] = (value >>> 16)
4833 this[offset + 1] = (value >>> 8)
4834 this[offset] = (value & 0xff)
4835 return offset + 4
4836}
4837
4838Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
4839 value = +value
4840 offset = offset >>> 0
4841 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
4842 this[offset] = (value >>> 24)
4843 this[offset + 1] = (value >>> 16)
4844 this[offset + 2] = (value >>> 8)
4845 this[offset + 3] = (value & 0xff)
4846 return offset + 4
4847}
4848
4849Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
4850 value = +value
4851 offset = offset >>> 0
4852 if (!noAssert) {
4853 var limit = Math.pow(2, (8 * byteLength) - 1)
4854
4855 checkInt(this, value, offset, byteLength, limit - 1, -limit)
4856 }
4857
4858 var i = 0
4859 var mul = 1
4860 var sub = 0
4861 this[offset] = value & 0xFF
4862 while (++i < byteLength && (mul *= 0x100)) {
4863 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
4864 sub = 1
4865 }
4866 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
4867 }
4868
4869 return offset + byteLength
4870}
4871
4872Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
4873 value = +value
4874 offset = offset >>> 0
4875 if (!noAssert) {
4876 var limit = Math.pow(2, (8 * byteLength) - 1)
4877
4878 checkInt(this, value, offset, byteLength, limit - 1, -limit)
4879 }
4880
4881 var i = byteLength - 1
4882 var mul = 1
4883 var sub = 0
4884 this[offset + i] = value & 0xFF
4885 while (--i >= 0 && (mul *= 0x100)) {
4886 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
4887 sub = 1
4888 }
4889 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
4890 }
4891
4892 return offset + byteLength
4893}
4894
4895Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
4896 value = +value
4897 offset = offset >>> 0
4898 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
4899 if (value < 0) value = 0xff + value + 1
4900 this[offset] = (value & 0xff)
4901 return offset + 1
4902}
4903
4904Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
4905 value = +value
4906 offset = offset >>> 0
4907 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
4908 this[offset] = (value & 0xff)
4909 this[offset + 1] = (value >>> 8)
4910 return offset + 2
4911}
4912
4913Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
4914 value = +value
4915 offset = offset >>> 0
4916 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
4917 this[offset] = (value >>> 8)
4918 this[offset + 1] = (value & 0xff)
4919 return offset + 2
4920}
4921
4922Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
4923 value = +value
4924 offset = offset >>> 0
4925 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
4926 this[offset] = (value & 0xff)
4927 this[offset + 1] = (value >>> 8)
4928 this[offset + 2] = (value >>> 16)
4929 this[offset + 3] = (value >>> 24)
4930 return offset + 4
4931}
4932
4933Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
4934 value = +value
4935 offset = offset >>> 0
4936 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
4937 if (value < 0) value = 0xffffffff + value + 1
4938 this[offset] = (value >>> 24)
4939 this[offset + 1] = (value >>> 16)
4940 this[offset + 2] = (value >>> 8)
4941 this[offset + 3] = (value & 0xff)
4942 return offset + 4
4943}
4944
4945function checkIEEE754 (buf, value, offset, ext, max, min) {
4946 if (offset + ext > buf.length) throw new RangeError('Index out of range')
4947 if (offset < 0) throw new RangeError('Index out of range')
4948}
4949
4950function writeFloat (buf, value, offset, littleEndian, noAssert) {
4951 value = +value
4952 offset = offset >>> 0
4953 if (!noAssert) {
4954 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
4955 }
4956 ieee754.write(buf, value, offset, littleEndian, 23, 4)
4957 return offset + 4
4958}
4959
4960Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
4961 return writeFloat(this, value, offset, true, noAssert)
4962}
4963
4964Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
4965 return writeFloat(this, value, offset, false, noAssert)
4966}
4967
4968function writeDouble (buf, value, offset, littleEndian, noAssert) {
4969 value = +value
4970 offset = offset >>> 0
4971 if (!noAssert) {
4972 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
4973 }
4974 ieee754.write(buf, value, offset, littleEndian, 52, 8)
4975 return offset + 8
4976}
4977
4978Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
4979 return writeDouble(this, value, offset, true, noAssert)
4980}
4981
4982Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
4983 return writeDouble(this, value, offset, false, noAssert)
4984}
4985
4986// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
4987Buffer.prototype.copy = function copy (target, targetStart, start, end) {
4988 if (!start) start = 0
4989 if (!end && end !== 0) end = this.length
4990 if (targetStart >= target.length) targetStart = target.length
4991 if (!targetStart) targetStart = 0
4992 if (end > 0 && end < start) end = start
4993
4994 // Copy 0 bytes; we're done
4995 if (end === start) return 0
4996 if (target.length === 0 || this.length === 0) return 0
4997
4998 // Fatal error conditions
4999 if (targetStart < 0) {
5000 throw new RangeError('targetStart out of bounds')
5001 }
5002 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
5003 if (end < 0) throw new RangeError('sourceEnd out of bounds')
5004
5005 // Are we oob?
5006 if (end > this.length) end = this.length
5007 if (target.length - targetStart < end - start) {
5008 end = target.length - targetStart + start
5009 }
5010
5011 var len = end - start
5012 var i
5013
5014 if (this === target && start < targetStart && targetStart < end) {
5015 // descending copy from end
5016 for (i = len - 1; i >= 0; --i) {
5017 target[i + targetStart] = this[i + start]
5018 }
5019 } else if (len < 1000) {
5020 // ascending copy from start
5021 for (i = 0; i < len; ++i) {
5022 target[i + targetStart] = this[i + start]
5023 }
5024 } else {
5025 Uint8Array.prototype.set.call(
5026 target,
5027 this.subarray(start, start + len),
5028 targetStart
5029 )
5030 }
5031
5032 return len
5033}
5034
5035// Usage:
5036// buffer.fill(number[, offset[, end]])
5037// buffer.fill(buffer[, offset[, end]])
5038// buffer.fill(string[, offset[, end]][, encoding])
5039Buffer.prototype.fill = function fill (val, start, end, encoding) {
5040 // Handle string cases:
5041 if (typeof val === 'string') {
5042 if (typeof start === 'string') {
5043 encoding = start
5044 start = 0
5045 end = this.length
5046 } else if (typeof end === 'string') {
5047 encoding = end
5048 end = this.length
5049 }
5050 if (val.length === 1) {
5051 var code = val.charCodeAt(0)
5052 if (code < 256) {
5053 val = code
5054 }
5055 }
5056 if (encoding !== undefined && typeof encoding !== 'string') {
5057 throw new TypeError('encoding must be a string')
5058 }
5059 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
5060 throw new TypeError('Unknown encoding: ' + encoding)
5061 }
5062 } else if (typeof val === 'number') {
5063 val = val & 255
5064 }
5065
5066 // Invalid ranges are not set to a default, so can range check early.
5067 if (start < 0 || this.length < start || this.length < end) {
5068 throw new RangeError('Out of range index')
5069 }
5070
5071 if (end <= start) {
5072 return this
5073 }
5074
5075 start = start >>> 0
5076 end = end === undefined ? this.length : end >>> 0
5077
5078 if (!val) val = 0
5079
5080 var i
5081 if (typeof val === 'number') {
5082 for (i = start; i < end; ++i) {
5083 this[i] = val
5084 }
5085 } else {
5086 var bytes = Buffer.isBuffer(val)
5087 ? val
5088 : new Buffer(val, encoding)
5089 var len = bytes.length
5090 for (i = 0; i < end - start; ++i) {
5091 this[i + start] = bytes[i % len]
5092 }
5093 }
5094
5095 return this
5096}
5097
5098// HELPER FUNCTIONS
5099// ================
5100
5101var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
5102
5103function base64clean (str) {
5104 // Node strips out invalid characters like \n and \t from the string, base64-js does not
5105 str = str.trim().replace(INVALID_BASE64_RE, '')
5106 // Node converts strings with length < 2 to ''
5107 if (str.length < 2) return ''
5108 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
5109 while (str.length % 4 !== 0) {
5110 str = str + '='
5111 }
5112 return str
5113}
5114
5115function toHex (n) {
5116 if (n < 16) return '0' + n.toString(16)
5117 return n.toString(16)
5118}
5119
5120function utf8ToBytes (string, units) {
5121 units = units || Infinity
5122 var codePoint
5123 var length = string.length
5124 var leadSurrogate = null
5125 var bytes = []
5126
5127 for (var i = 0; i < length; ++i) {
5128 codePoint = string.charCodeAt(i)
5129
5130 // is surrogate component
5131 if (codePoint > 0xD7FF && codePoint < 0xE000) {
5132 // last char was a lead
5133 if (!leadSurrogate) {
5134 // no lead yet
5135 if (codePoint > 0xDBFF) {
5136 // unexpected trail
5137 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
5138 continue
5139 } else if (i + 1 === length) {
5140 // unpaired lead
5141 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
5142 continue
5143 }
5144
5145 // valid lead
5146 leadSurrogate = codePoint
5147
5148 continue
5149 }
5150
5151 // 2 leads in a row
5152 if (codePoint < 0xDC00) {
5153 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
5154 leadSurrogate = codePoint
5155 continue
5156 }
5157
5158 // valid surrogate pair
5159 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
5160 } else if (leadSurrogate) {
5161 // valid bmp char, but last char was a lead
5162 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
5163 }
5164
5165 leadSurrogate = null
5166
5167 // encode utf8
5168 if (codePoint < 0x80) {
5169 if ((units -= 1) < 0) break
5170 bytes.push(codePoint)
5171 } else if (codePoint < 0x800) {
5172 if ((units -= 2) < 0) break
5173 bytes.push(
5174 codePoint >> 0x6 | 0xC0,
5175 codePoint & 0x3F | 0x80
5176 )
5177 } else if (codePoint < 0x10000) {
5178 if ((units -= 3) < 0) break
5179 bytes.push(
5180 codePoint >> 0xC | 0xE0,
5181 codePoint >> 0x6 & 0x3F | 0x80,
5182 codePoint & 0x3F | 0x80
5183 )
5184 } else if (codePoint < 0x110000) {
5185 if ((units -= 4) < 0) break
5186 bytes.push(
5187 codePoint >> 0x12 | 0xF0,
5188 codePoint >> 0xC & 0x3F | 0x80,
5189 codePoint >> 0x6 & 0x3F | 0x80,
5190 codePoint & 0x3F | 0x80
5191 )
5192 } else {
5193 throw new Error('Invalid code point')
5194 }
5195 }
5196
5197 return bytes
5198}
5199
5200function asciiToBytes (str) {
5201 var byteArray = []
5202 for (var i = 0; i < str.length; ++i) {
5203 // Node's code seems to be doing this and not & 0x7F..
5204 byteArray.push(str.charCodeAt(i) & 0xFF)
5205 }
5206 return byteArray
5207}
5208
5209function utf16leToBytes (str, units) {
5210 var c, hi, lo
5211 var byteArray = []
5212 for (var i = 0; i < str.length; ++i) {
5213 if ((units -= 2) < 0) break
5214
5215 c = str.charCodeAt(i)
5216 hi = c >> 8
5217 lo = c % 256
5218 byteArray.push(lo)
5219 byteArray.push(hi)
5220 }
5221
5222 return byteArray
5223}
5224
5225function base64ToBytes (str) {
5226 return base64.toByteArray(base64clean(str))
5227}
5228
5229function blitBuffer (src, dst, offset, length) {
5230 for (var i = 0; i < length; ++i) {
5231 if ((i + offset >= dst.length) || (i >= src.length)) break
5232 dst[i + offset] = src[i]
5233 }
5234 return i
5235}
5236
5237// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
5238// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
5239function isArrayBuffer (obj) {
5240 return obj instanceof ArrayBuffer ||
5241 (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
5242 typeof obj.byteLength === 'number')
5243}
5244
5245// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
5246function isArrayBufferView (obj) {
5247 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
5248}
5249
5250function numberIsNaN (obj) {
5251 return obj !== obj // eslint-disable-line no-self-compare
5252}
5253
5254},{"base64-js":3,"ieee754":44}],28:[function(require,module,exports){
5255/*
5256 Copyright 2013-2014 Daniel Wirtz <dcode@dcode.io>
5257
5258 Licensed under the Apache License, Version 2.0 (the "License");
5259 you may not use this file except in compliance with the License.
5260 You may obtain a copy of the License at
5261
5262 http://www.apache.org/licenses/LICENSE-2.0
5263
5264 Unless required by applicable law or agreed to in writing, software
5265 distributed under the License is distributed on an "AS IS" BASIS,
5266 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5267 See the License for the specific language governing permissions and
5268 limitations under the License.
5269 */
5270
5271/**
5272 * @license bytebuffer.js (c) 2015 Daniel Wirtz <dcode@dcode.io>
5273 * Backing buffer: ArrayBuffer, Accessor: Uint8Array
5274 * Released under the Apache License, Version 2.0
5275 * see: https://github.com/dcodeIO/bytebuffer.js for details
5276 */
5277(function(global, factory) {
5278
5279 /* AMD */ if (typeof define === 'function' && define["amd"])
5280 define(["long"], factory);
5281 /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
5282 module['exports'] = (function() {
5283 var Long; try { Long = require("long"); } catch (e) {}
5284 return factory(Long);
5285 })();
5286 /* Global */ else
5287 (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);
5288
5289})(this, function(Long) {
5290 "use strict";
5291
5292 /**
5293 * Constructs a new ByteBuffer.
5294 * @class The swiss army knife for binary data in JavaScript.
5295 * @exports ByteBuffer
5296 * @constructor
5297 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
5298 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
5299 * {@link ByteBuffer.DEFAULT_ENDIAN}.
5300 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
5301 * {@link ByteBuffer.DEFAULT_NOASSERT}.
5302 * @expose
5303 */
5304 var ByteBuffer = function(capacity, littleEndian, noAssert) {
5305 if (typeof capacity === 'undefined')
5306 capacity = ByteBuffer.DEFAULT_CAPACITY;
5307 if (typeof littleEndian === 'undefined')
5308 littleEndian = ByteBuffer.DEFAULT_ENDIAN;
5309 if (typeof noAssert === 'undefined')
5310 noAssert = ByteBuffer.DEFAULT_NOASSERT;
5311 if (!noAssert) {
5312 capacity = capacity | 0;
5313 if (capacity < 0)
5314 throw RangeError("Illegal capacity");
5315 littleEndian = !!littleEndian;
5316 noAssert = !!noAssert;
5317 }
5318
5319 /**
5320 * Backing ArrayBuffer.
5321 * @type {!ArrayBuffer}
5322 * @expose
5323 */
5324 this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
5325
5326 /**
5327 * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
5328 * @type {?Uint8Array}
5329 * @expose
5330 */
5331 this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
5332
5333 /**
5334 * Absolute read/write offset.
5335 * @type {number}
5336 * @expose
5337 * @see ByteBuffer#flip
5338 * @see ByteBuffer#clear
5339 */
5340 this.offset = 0;
5341
5342 /**
5343 * Marked offset.
5344 * @type {number}
5345 * @expose
5346 * @see ByteBuffer#mark
5347 * @see ByteBuffer#reset
5348 */
5349 this.markedOffset = -1;
5350
5351 /**
5352 * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
5353 * @type {number}
5354 * @expose
5355 * @see ByteBuffer#flip
5356 * @see ByteBuffer#clear
5357 */
5358 this.limit = capacity;
5359
5360 /**
5361 * Whether to use little endian byte order, defaults to `false` for big endian.
5362 * @type {boolean}
5363 * @expose
5364 */
5365 this.littleEndian = littleEndian;
5366
5367 /**
5368 * Whether to skip assertions of offsets and values, defaults to `false`.
5369 * @type {boolean}
5370 * @expose
5371 */
5372 this.noAssert = noAssert;
5373 };
5374
5375 /**
5376 * ByteBuffer version.
5377 * @type {string}
5378 * @const
5379 * @expose
5380 */
5381 ByteBuffer.VERSION = "5.0.1";
5382
5383 /**
5384 * Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
5385 * @type {boolean}
5386 * @const
5387 * @expose
5388 */
5389 ByteBuffer.LITTLE_ENDIAN = true;
5390
5391 /**
5392 * Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
5393 * @type {boolean}
5394 * @const
5395 * @expose
5396 */
5397 ByteBuffer.BIG_ENDIAN = false;
5398
5399 /**
5400 * Default initial capacity of `16`.
5401 * @type {number}
5402 * @expose
5403 */
5404 ByteBuffer.DEFAULT_CAPACITY = 16;
5405
5406 /**
5407 * Default endianess of `false` for big endian.
5408 * @type {boolean}
5409 * @expose
5410 */
5411 ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
5412
5413 /**
5414 * Default no assertions flag of `false`.
5415 * @type {boolean}
5416 * @expose
5417 */
5418 ByteBuffer.DEFAULT_NOASSERT = false;
5419
5420 /**
5421 * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
5422 * and int64 support is not available.
5423 * @type {?Long}
5424 * @const
5425 * @see https://github.com/dcodeIO/long.js
5426 * @expose
5427 */
5428 ByteBuffer.Long = Long || null;
5429
5430 /**
5431 * @alias ByteBuffer.prototype
5432 * @inner
5433 */
5434 var ByteBufferPrototype = ByteBuffer.prototype;
5435
5436 /**
5437 * An indicator used to reliably determine if an object is a ByteBuffer or not.
5438 * @type {boolean}
5439 * @const
5440 * @expose
5441 * @private
5442 */
5443 ByteBufferPrototype.__isByteBuffer__;
5444
5445 Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
5446 value: true,
5447 enumerable: false,
5448 configurable: false
5449 });
5450
5451 // helpers
5452
5453 /**
5454 * @type {!ArrayBuffer}
5455 * @inner
5456 */
5457 var EMPTY_BUFFER = new ArrayBuffer(0);
5458
5459 /**
5460 * String.fromCharCode reference for compile-time renaming.
5461 * @type {function(...number):string}
5462 * @inner
5463 */
5464 var stringFromCharCode = String.fromCharCode;
5465
5466 /**
5467 * Creates a source function for a string.
5468 * @param {string} s String to read from
5469 * @returns {function():number|null} Source function returning the next char code respectively `null` if there are
5470 * no more characters left.
5471 * @throws {TypeError} If the argument is invalid
5472 * @inner
5473 */
5474 function stringSource(s) {
5475 var i=0; return function() {
5476 return i < s.length ? s.charCodeAt(i++) : null;
5477 };
5478 }
5479
5480 /**
5481 * Creates a destination function for a string.
5482 * @returns {function(number=):undefined|string} Destination function successively called with the next char code.
5483 * Returns the final string when called without arguments.
5484 * @inner
5485 */
5486 function stringDestination() {
5487 var cs = [], ps = []; return function() {
5488 if (arguments.length === 0)
5489 return ps.join('')+stringFromCharCode.apply(String, cs);
5490 if (cs.length + arguments.length > 1024)
5491 ps.push(stringFromCharCode.apply(String, cs)),
5492 cs.length = 0;
5493 Array.prototype.push.apply(cs, arguments);
5494 };
5495 }
5496
5497 /**
5498 * Gets the accessor type.
5499 * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
5500 * @expose
5501 */
5502 ByteBuffer.accessor = function() {
5503 return Uint8Array;
5504 };
5505 /**
5506 * Allocates a new ByteBuffer backed by a buffer of the specified capacity.
5507 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
5508 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
5509 * {@link ByteBuffer.DEFAULT_ENDIAN}.
5510 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
5511 * {@link ByteBuffer.DEFAULT_NOASSERT}.
5512 * @returns {!ByteBuffer}
5513 * @expose
5514 */
5515 ByteBuffer.allocate = function(capacity, littleEndian, noAssert) {
5516 return new ByteBuffer(capacity, littleEndian, noAssert);
5517 };
5518
5519 /**
5520 * Concatenates multiple ByteBuffers into one.
5521 * @param {!Array.<!ByteBuffer|!ArrayBuffer|!Uint8Array|string>} buffers Buffers to concatenate
5522 * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
5523 * defaults to "utf8")
5524 * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
5525 * to {@link ByteBuffer.DEFAULT_ENDIAN}.
5526 * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
5527 * {@link ByteBuffer.DEFAULT_NOASSERT}.
5528 * @returns {!ByteBuffer} Concatenated ByteBuffer
5529 * @expose
5530 */
5531 ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) {
5532 if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
5533 noAssert = littleEndian;
5534 littleEndian = encoding;
5535 encoding = undefined;
5536 }
5537 var capacity = 0;
5538 for (var i=0, k=buffers.length, length; i<k; ++i) {
5539 if (!ByteBuffer.isByteBuffer(buffers[i]))
5540 buffers[i] = ByteBuffer.wrap(buffers[i], encoding);
5541 length = buffers[i].limit - buffers[i].offset;
5542 if (length > 0) capacity += length;
5543 }
5544 if (capacity === 0)
5545 return new ByteBuffer(0, littleEndian, noAssert);
5546 var bb = new ByteBuffer(capacity, littleEndian, noAssert),
5547 bi;
5548 i=0; while (i<k) {
5549 bi = buffers[i++];
5550 length = bi.limit - bi.offset;
5551 if (length <= 0) continue;
5552 bb.view.set(bi.view.subarray(bi.offset, bi.limit), bb.offset);
5553 bb.offset += length;
5554 }
5555 bb.limit = bb.offset;
5556 bb.offset = 0;
5557 return bb;
5558 };
5559
5560 /**
5561 * Tests if the specified type is a ByteBuffer.
5562 * @param {*} bb ByteBuffer to test
5563 * @returns {boolean} `true` if it is a ByteBuffer, otherwise `false`
5564 * @expose
5565 */
5566 ByteBuffer.isByteBuffer = function(bb) {
5567 return (bb && bb["__isByteBuffer__"]) === true;
5568 };
5569 /**
5570 * Gets the backing buffer type.
5571 * @returns {Function} `Buffer` under node.js, `ArrayBuffer` in the browser (classes)
5572 * @expose
5573 */
5574 ByteBuffer.type = function() {
5575 return ArrayBuffer;
5576 };
5577 /**
5578 * Wraps a buffer or a string. Sets the allocated ByteBuffer's {@link ByteBuffer#offset} to `0` and its
5579 * {@link ByteBuffer#limit} to the length of the wrapped data.
5580 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string|!Array.<number>} buffer Anything that can be wrapped
5581 * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
5582 * "utf8")
5583 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
5584 * {@link ByteBuffer.DEFAULT_ENDIAN}.
5585 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
5586 * {@link ByteBuffer.DEFAULT_NOASSERT}.
5587 * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
5588 * @expose
5589 */
5590 ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) {
5591 if (typeof encoding !== 'string') {
5592 noAssert = littleEndian;
5593 littleEndian = encoding;
5594 encoding = undefined;
5595 }
5596 if (typeof buffer === 'string') {
5597 if (typeof encoding === 'undefined')
5598 encoding = "utf8";
5599 switch (encoding) {
5600 case "base64":
5601 return ByteBuffer.fromBase64(buffer, littleEndian);
5602 case "hex":
5603 return ByteBuffer.fromHex(buffer, littleEndian);
5604 case "binary":
5605 return ByteBuffer.fromBinary(buffer, littleEndian);
5606 case "utf8":
5607 return ByteBuffer.fromUTF8(buffer, littleEndian);
5608 case "debug":
5609 return ByteBuffer.fromDebug(buffer, littleEndian);
5610 default:
5611 throw Error("Unsupported encoding: "+encoding);
5612 }
5613 }
5614 if (buffer === null || typeof buffer !== 'object')
5615 throw TypeError("Illegal buffer");
5616 var bb;
5617 if (ByteBuffer.isByteBuffer(buffer)) {
5618 bb = ByteBufferPrototype.clone.call(buffer);
5619 bb.markedOffset = -1;
5620 return bb;
5621 }
5622 if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
5623 bb = new ByteBuffer(0, littleEndian, noAssert);
5624 if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
5625 bb.buffer = buffer.buffer;
5626 bb.offset = buffer.byteOffset;
5627 bb.limit = buffer.byteOffset + buffer.byteLength;
5628 bb.view = new Uint8Array(buffer.buffer);
5629 }
5630 } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
5631 bb = new ByteBuffer(0, littleEndian, noAssert);
5632 if (buffer.byteLength > 0) {
5633 bb.buffer = buffer;
5634 bb.offset = 0;
5635 bb.limit = buffer.byteLength;
5636 bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
5637 }
5638 } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
5639 bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
5640 bb.limit = buffer.length;
5641 for (var i=0; i<buffer.length; ++i)
5642 bb.view[i] = buffer[i];
5643 } else
5644 throw TypeError("Illegal buffer"); // Otherwise fail
5645 return bb;
5646 };
5647
5648 /**
5649 * Writes the array as a bitset.
5650 * @param {Array<boolean>} value Array of booleans to write
5651 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
5652 * @returns {!ByteBuffer}
5653 * @expose
5654 */
5655 ByteBufferPrototype.writeBitSet = function(value, offset) {
5656 var relative = typeof offset === 'undefined';
5657 if (relative) offset = this.offset;
5658 if (!this.noAssert) {
5659 if (!(value instanceof Array))
5660 throw TypeError("Illegal BitSet: Not an array");
5661 if (typeof offset !== 'number' || offset % 1 !== 0)
5662 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5663 offset >>>= 0;
5664 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5665 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5666 }
5667
5668 var start = offset,
5669 bits = value.length,
5670 bytes = (bits >> 3),
5671 bit = 0,
5672 k;
5673
5674 offset += this.writeVarint32(bits,offset);
5675
5676 while(bytes--) {
5677 k = (!!value[bit++] & 1) |
5678 ((!!value[bit++] & 1) << 1) |
5679 ((!!value[bit++] & 1) << 2) |
5680 ((!!value[bit++] & 1) << 3) |
5681 ((!!value[bit++] & 1) << 4) |
5682 ((!!value[bit++] & 1) << 5) |
5683 ((!!value[bit++] & 1) << 6) |
5684 ((!!value[bit++] & 1) << 7);
5685 this.writeByte(k,offset++);
5686 }
5687
5688 if(bit < bits) {
5689 var m = 0; k = 0;
5690 while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++));
5691 this.writeByte(k,offset++);
5692 }
5693
5694 if (relative) {
5695 this.offset = offset;
5696 return this;
5697 }
5698 return offset - start;
5699 }
5700
5701 /**
5702 * Reads a BitSet as an array of booleans.
5703 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
5704 * @returns {Array<boolean>
5705 * @expose
5706 */
5707 ByteBufferPrototype.readBitSet = function(offset) {
5708 var relative = typeof offset === 'undefined';
5709 if (relative) offset = this.offset;
5710
5711 var ret = this.readVarint32(offset),
5712 bits = ret.value,
5713 bytes = (bits >> 3),
5714 bit = 0,
5715 value = [],
5716 k;
5717
5718 offset += ret.length;
5719
5720 while(bytes--) {
5721 k = this.readByte(offset++);
5722 value[bit++] = !!(k & 0x01);
5723 value[bit++] = !!(k & 0x02);
5724 value[bit++] = !!(k & 0x04);
5725 value[bit++] = !!(k & 0x08);
5726 value[bit++] = !!(k & 0x10);
5727 value[bit++] = !!(k & 0x20);
5728 value[bit++] = !!(k & 0x40);
5729 value[bit++] = !!(k & 0x80);
5730 }
5731
5732 if(bit < bits) {
5733 var m = 0;
5734 k = this.readByte(offset++);
5735 while(bit < bits) value[bit++] = !!((k >> (m++)) & 1);
5736 }
5737
5738 if (relative) {
5739 this.offset = offset;
5740 }
5741 return value;
5742 }
5743 /**
5744 * Reads the specified number of bytes.
5745 * @param {number} length Number of bytes to read
5746 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
5747 * @returns {!ByteBuffer}
5748 * @expose
5749 */
5750 ByteBufferPrototype.readBytes = function(length, offset) {
5751 var relative = typeof offset === 'undefined';
5752 if (relative) offset = this.offset;
5753 if (!this.noAssert) {
5754 if (typeof offset !== 'number' || offset % 1 !== 0)
5755 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5756 offset >>>= 0;
5757 if (offset < 0 || offset + length > this.buffer.byteLength)
5758 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
5759 }
5760 var slice = this.slice(offset, offset + length);
5761 if (relative) this.offset += length;
5762 return slice;
5763 };
5764
5765 /**
5766 * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
5767 * @function
5768 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
5769 * will be modified according to the performed read operation.
5770 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
5771 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5772 * written if omitted.
5773 * @returns {!ByteBuffer} this
5774 * @expose
5775 */
5776 ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;
5777
5778 // types/ints/int8
5779
5780 /**
5781 * Writes an 8bit signed integer.
5782 * @param {number} value Value to write
5783 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
5784 * @returns {!ByteBuffer} this
5785 * @expose
5786 */
5787 ByteBufferPrototype.writeInt8 = function(value, offset) {
5788 var relative = typeof offset === 'undefined';
5789 if (relative) offset = this.offset;
5790 if (!this.noAssert) {
5791 if (typeof value !== 'number' || value % 1 !== 0)
5792 throw TypeError("Illegal value: "+value+" (not an integer)");
5793 value |= 0;
5794 if (typeof offset !== 'number' || offset % 1 !== 0)
5795 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5796 offset >>>= 0;
5797 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5798 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5799 }
5800 offset += 1;
5801 var capacity0 = this.buffer.byteLength;
5802 if (offset > capacity0)
5803 this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
5804 offset -= 1;
5805 this.view[offset] = value;
5806 if (relative) this.offset += 1;
5807 return this;
5808 };
5809
5810 /**
5811 * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
5812 * @function
5813 * @param {number} value Value to write
5814 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
5815 * @returns {!ByteBuffer} this
5816 * @expose
5817 */
5818 ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;
5819
5820 /**
5821 * Reads an 8bit signed integer.
5822 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
5823 * @returns {number} Value read
5824 * @expose
5825 */
5826 ByteBufferPrototype.readInt8 = function(offset) {
5827 var relative = typeof offset === 'undefined';
5828 if (relative) offset = this.offset;
5829 if (!this.noAssert) {
5830 if (typeof offset !== 'number' || offset % 1 !== 0)
5831 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5832 offset >>>= 0;
5833 if (offset < 0 || offset + 1 > this.buffer.byteLength)
5834 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
5835 }
5836 var value = this.view[offset];
5837 if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
5838 if (relative) this.offset += 1;
5839 return value;
5840 };
5841
5842 /**
5843 * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
5844 * @function
5845 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
5846 * @returns {number} Value read
5847 * @expose
5848 */
5849 ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;
5850
5851 /**
5852 * Writes an 8bit unsigned integer.
5853 * @param {number} value Value to write
5854 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
5855 * @returns {!ByteBuffer} this
5856 * @expose
5857 */
5858 ByteBufferPrototype.writeUint8 = function(value, offset) {
5859 var relative = typeof offset === 'undefined';
5860 if (relative) offset = this.offset;
5861 if (!this.noAssert) {
5862 if (typeof value !== 'number' || value % 1 !== 0)
5863 throw TypeError("Illegal value: "+value+" (not an integer)");
5864 value >>>= 0;
5865 if (typeof offset !== 'number' || offset % 1 !== 0)
5866 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5867 offset >>>= 0;
5868 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5869 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5870 }
5871 offset += 1;
5872 var capacity1 = this.buffer.byteLength;
5873 if (offset > capacity1)
5874 this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
5875 offset -= 1;
5876 this.view[offset] = value;
5877 if (relative) this.offset += 1;
5878 return this;
5879 };
5880
5881 /**
5882 * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
5883 * @function
5884 * @param {number} value Value to write
5885 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
5886 * @returns {!ByteBuffer} this
5887 * @expose
5888 */
5889 ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;
5890
5891 /**
5892 * Reads an 8bit unsigned integer.
5893 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
5894 * @returns {number} Value read
5895 * @expose
5896 */
5897 ByteBufferPrototype.readUint8 = function(offset) {
5898 var relative = typeof offset === 'undefined';
5899 if (relative) offset = this.offset;
5900 if (!this.noAssert) {
5901 if (typeof offset !== 'number' || offset % 1 !== 0)
5902 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5903 offset >>>= 0;
5904 if (offset < 0 || offset + 1 > this.buffer.byteLength)
5905 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
5906 }
5907 var value = this.view[offset];
5908 if (relative) this.offset += 1;
5909 return value;
5910 };
5911
5912 /**
5913 * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
5914 * @function
5915 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
5916 * @returns {number} Value read
5917 * @expose
5918 */
5919 ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;
5920
5921 // types/ints/int16
5922
5923 /**
5924 * Writes a 16bit signed integer.
5925 * @param {number} value Value to write
5926 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
5927 * @throws {TypeError} If `offset` or `value` is not a valid number
5928 * @throws {RangeError} If `offset` is out of bounds
5929 * @expose
5930 */
5931 ByteBufferPrototype.writeInt16 = function(value, offset) {
5932 var relative = typeof offset === 'undefined';
5933 if (relative) offset = this.offset;
5934 if (!this.noAssert) {
5935 if (typeof value !== 'number' || value % 1 !== 0)
5936 throw TypeError("Illegal value: "+value+" (not an integer)");
5937 value |= 0;
5938 if (typeof offset !== 'number' || offset % 1 !== 0)
5939 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5940 offset >>>= 0;
5941 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5942 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5943 }
5944 offset += 2;
5945 var capacity2 = this.buffer.byteLength;
5946 if (offset > capacity2)
5947 this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
5948 offset -= 2;
5949 if (this.littleEndian) {
5950 this.view[offset+1] = (value & 0xFF00) >>> 8;
5951 this.view[offset ] = value & 0x00FF;
5952 } else {
5953 this.view[offset] = (value & 0xFF00) >>> 8;
5954 this.view[offset+1] = value & 0x00FF;
5955 }
5956 if (relative) this.offset += 2;
5957 return this;
5958 };
5959
5960 /**
5961 * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
5962 * @function
5963 * @param {number} value Value to write
5964 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
5965 * @throws {TypeError} If `offset` or `value` is not a valid number
5966 * @throws {RangeError} If `offset` is out of bounds
5967 * @expose
5968 */
5969 ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;
5970
5971 /**
5972 * Reads a 16bit signed integer.
5973 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
5974 * @returns {number} Value read
5975 * @throws {TypeError} If `offset` is not a valid number
5976 * @throws {RangeError} If `offset` is out of bounds
5977 * @expose
5978 */
5979 ByteBufferPrototype.readInt16 = function(offset) {
5980 var relative = typeof offset === 'undefined';
5981 if (relative) offset = this.offset;
5982 if (!this.noAssert) {
5983 if (typeof offset !== 'number' || offset % 1 !== 0)
5984 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5985 offset >>>= 0;
5986 if (offset < 0 || offset + 2 > this.buffer.byteLength)
5987 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
5988 }
5989 var value = 0;
5990 if (this.littleEndian) {
5991 value = this.view[offset ];
5992 value |= this.view[offset+1] << 8;
5993 } else {
5994 value = this.view[offset ] << 8;
5995 value |= this.view[offset+1];
5996 }
5997 if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
5998 if (relative) this.offset += 2;
5999 return value;
6000 };
6001
6002 /**
6003 * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
6004 * @function
6005 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
6006 * @returns {number} Value read
6007 * @throws {TypeError} If `offset` is not a valid number
6008 * @throws {RangeError} If `offset` is out of bounds
6009 * @expose
6010 */
6011 ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;
6012
6013 /**
6014 * Writes a 16bit unsigned integer.
6015 * @param {number} value Value to write
6016 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
6017 * @throws {TypeError} If `offset` or `value` is not a valid number
6018 * @throws {RangeError} If `offset` is out of bounds
6019 * @expose
6020 */
6021 ByteBufferPrototype.writeUint16 = function(value, offset) {
6022 var relative = typeof offset === 'undefined';
6023 if (relative) offset = this.offset;
6024 if (!this.noAssert) {
6025 if (typeof value !== 'number' || value % 1 !== 0)
6026 throw TypeError("Illegal value: "+value+" (not an integer)");
6027 value >>>= 0;
6028 if (typeof offset !== 'number' || offset % 1 !== 0)
6029 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6030 offset >>>= 0;
6031 if (offset < 0 || offset + 0 > this.buffer.byteLength)
6032 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
6033 }
6034 offset += 2;
6035 var capacity3 = this.buffer.byteLength;
6036 if (offset > capacity3)
6037 this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
6038 offset -= 2;
6039 if (this.littleEndian) {
6040 this.view[offset+1] = (value & 0xFF00) >>> 8;
6041 this.view[offset ] = value & 0x00FF;
6042 } else {
6043 this.view[offset] = (value & 0xFF00) >>> 8;
6044 this.view[offset+1] = value & 0x00FF;
6045 }
6046 if (relative) this.offset += 2;
6047 return this;
6048 };
6049
6050 /**
6051 * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
6052 * @function
6053 * @param {number} value Value to write
6054 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
6055 * @throws {TypeError} If `offset` or `value` is not a valid number
6056 * @throws {RangeError} If `offset` is out of bounds
6057 * @expose
6058 */
6059 ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;
6060
6061 /**
6062 * Reads a 16bit unsigned integer.
6063 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
6064 * @returns {number} Value read
6065 * @throws {TypeError} If `offset` is not a valid number
6066 * @throws {RangeError} If `offset` is out of bounds
6067 * @expose
6068 */
6069 ByteBufferPrototype.readUint16 = function(offset) {
6070 var relative = typeof offset === 'undefined';
6071 if (relative) offset = this.offset;
6072 if (!this.noAssert) {
6073 if (typeof offset !== 'number' || offset % 1 !== 0)
6074 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6075 offset >>>= 0;
6076 if (offset < 0 || offset + 2 > this.buffer.byteLength)
6077 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
6078 }
6079 var value = 0;
6080 if (this.littleEndian) {
6081 value = this.view[offset ];
6082 value |= this.view[offset+1] << 8;
6083 } else {
6084 value = this.view[offset ] << 8;
6085 value |= this.view[offset+1];
6086 }
6087 if (relative) this.offset += 2;
6088 return value;
6089 };
6090
6091 /**
6092 * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
6093 * @function
6094 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
6095 * @returns {number} Value read
6096 * @throws {TypeError} If `offset` is not a valid number
6097 * @throws {RangeError} If `offset` is out of bounds
6098 * @expose
6099 */
6100 ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;
6101
6102 // types/ints/int32
6103
6104 /**
6105 * Writes a 32bit signed integer.
6106 * @param {number} value Value to write
6107 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
6108 * @expose
6109 */
6110 ByteBufferPrototype.writeInt32 = function(value, offset) {
6111 var relative = typeof offset === 'undefined';
6112 if (relative) offset = this.offset;
6113 if (!this.noAssert) {
6114 if (typeof value !== 'number' || value % 1 !== 0)
6115 throw TypeError("Illegal value: "+value+" (not an integer)");
6116 value |= 0;
6117 if (typeof offset !== 'number' || offset % 1 !== 0)
6118 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6119 offset >>>= 0;
6120 if (offset < 0 || offset + 0 > this.buffer.byteLength)
6121 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
6122 }
6123 offset += 4;
6124 var capacity4 = this.buffer.byteLength;
6125 if (offset > capacity4)
6126 this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
6127 offset -= 4;
6128 if (this.littleEndian) {
6129 this.view[offset+3] = (value >>> 24) & 0xFF;
6130 this.view[offset+2] = (value >>> 16) & 0xFF;
6131 this.view[offset+1] = (value >>> 8) & 0xFF;
6132 this.view[offset ] = value & 0xFF;
6133 } else {
6134 this.view[offset ] = (value >>> 24) & 0xFF;
6135 this.view[offset+1] = (value >>> 16) & 0xFF;
6136 this.view[offset+2] = (value >>> 8) & 0xFF;
6137 this.view[offset+3] = value & 0xFF;
6138 }
6139 if (relative) this.offset += 4;
6140 return this;
6141 };
6142
6143 /**
6144 * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
6145 * @param {number} value Value to write
6146 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
6147 * @expose
6148 */
6149 ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;
6150
6151 /**
6152 * Reads a 32bit signed integer.
6153 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
6154 * @returns {number} Value read
6155 * @expose
6156 */
6157 ByteBufferPrototype.readInt32 = function(offset) {
6158 var relative = typeof offset === 'undefined';
6159 if (relative) offset = this.offset;
6160 if (!this.noAssert) {
6161 if (typeof offset !== 'number' || offset % 1 !== 0)
6162 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6163 offset >>>= 0;
6164 if (offset < 0 || offset + 4 > this.buffer.byteLength)
6165 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
6166 }
6167 var value = 0;
6168 if (this.littleEndian) {
6169 value = this.view[offset+2] << 16;
6170 value |= this.view[offset+1] << 8;
6171 value |= this.view[offset ];
6172 value += this.view[offset+3] << 24 >>> 0;
6173 } else {
6174 value = this.view[offset+1] << 16;
6175 value |= this.view[offset+2] << 8;
6176 value |= this.view[offset+3];
6177 value += this.view[offset ] << 24 >>> 0;
6178 }
6179 value |= 0; // Cast to signed
6180 if (relative) this.offset += 4;
6181 return value;
6182 };
6183
6184 /**
6185 * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
6186 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
6187 * @returns {number} Value read
6188 * @expose
6189 */
6190 ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;
6191
6192 /**
6193 * Writes a 32bit unsigned integer.
6194 * @param {number} value Value to write
6195 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
6196 * @expose
6197 */
6198 ByteBufferPrototype.writeUint32 = function(value, offset) {
6199 var relative = typeof offset === 'undefined';
6200 if (relative) offset = this.offset;
6201 if (!this.noAssert) {
6202 if (typeof value !== 'number' || value % 1 !== 0)
6203 throw TypeError("Illegal value: "+value+" (not an integer)");
6204 value >>>= 0;
6205 if (typeof offset !== 'number' || offset % 1 !== 0)
6206 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6207 offset >>>= 0;
6208 if (offset < 0 || offset + 0 > this.buffer.byteLength)
6209 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
6210 }
6211 offset += 4;
6212 var capacity5 = this.buffer.byteLength;
6213 if (offset > capacity5)
6214 this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
6215 offset -= 4;
6216 if (this.littleEndian) {
6217 this.view[offset+3] = (value >>> 24) & 0xFF;
6218 this.view[offset+2] = (value >>> 16) & 0xFF;
6219 this.view[offset+1] = (value >>> 8) & 0xFF;
6220 this.view[offset ] = value & 0xFF;
6221 } else {
6222 this.view[offset ] = (value >>> 24) & 0xFF;
6223 this.view[offset+1] = (value >>> 16) & 0xFF;
6224 this.view[offset+2] = (value >>> 8) & 0xFF;
6225 this.view[offset+3] = value & 0xFF;
6226 }
6227 if (relative) this.offset += 4;
6228 return this;
6229 };
6230
6231 /**
6232 * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
6233 * @function
6234 * @param {number} value Value to write
6235 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
6236 * @expose
6237 */
6238 ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;
6239
6240 /**
6241 * Reads a 32bit unsigned integer.
6242 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
6243 * @returns {number} Value read
6244 * @expose
6245 */
6246 ByteBufferPrototype.readUint32 = function(offset) {
6247 var relative = typeof offset === 'undefined';
6248 if (relative) offset = this.offset;
6249 if (!this.noAssert) {
6250 if (typeof offset !== 'number' || offset % 1 !== 0)
6251 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6252 offset >>>= 0;
6253 if (offset < 0 || offset + 4 > this.buffer.byteLength)
6254 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
6255 }
6256 var value = 0;
6257 if (this.littleEndian) {
6258 value = this.view[offset+2] << 16;
6259 value |= this.view[offset+1] << 8;
6260 value |= this.view[offset ];
6261 value += this.view[offset+3] << 24 >>> 0;
6262 } else {
6263 value = this.view[offset+1] << 16;
6264 value |= this.view[offset+2] << 8;
6265 value |= this.view[offset+3];
6266 value += this.view[offset ] << 24 >>> 0;
6267 }
6268 if (relative) this.offset += 4;
6269 return value;
6270 };
6271
6272 /**
6273 * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
6274 * @function
6275 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
6276 * @returns {number} Value read
6277 * @expose
6278 */
6279 ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;
6280
6281 // types/ints/int64
6282
6283 if (Long) {
6284
6285 /**
6286 * Writes a 64bit signed integer.
6287 * @param {number|!Long} value Value to write
6288 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6289 * @returns {!ByteBuffer} this
6290 * @expose
6291 */
6292 ByteBufferPrototype.writeInt64 = function(value, offset) {
6293 var relative = typeof offset === 'undefined';
6294 if (relative) offset = this.offset;
6295 if (!this.noAssert) {
6296 if (typeof value === 'number')
6297 value = Long.fromNumber(value);
6298 else if (typeof value === 'string')
6299 value = Long.fromString(value);
6300 else if (!(value && value instanceof Long))
6301 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
6302 if (typeof offset !== 'number' || offset % 1 !== 0)
6303 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6304 offset >>>= 0;
6305 if (offset < 0 || offset + 0 > this.buffer.byteLength)
6306 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
6307 }
6308 if (typeof value === 'number')
6309 value = Long.fromNumber(value);
6310 else if (typeof value === 'string')
6311 value = Long.fromString(value);
6312 offset += 8;
6313 var capacity6 = this.buffer.byteLength;
6314 if (offset > capacity6)
6315 this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
6316 offset -= 8;
6317 var lo = value.low,
6318 hi = value.high;
6319 if (this.littleEndian) {
6320 this.view[offset+3] = (lo >>> 24) & 0xFF;
6321 this.view[offset+2] = (lo >>> 16) & 0xFF;
6322 this.view[offset+1] = (lo >>> 8) & 0xFF;
6323 this.view[offset ] = lo & 0xFF;
6324 offset += 4;
6325 this.view[offset+3] = (hi >>> 24) & 0xFF;
6326 this.view[offset+2] = (hi >>> 16) & 0xFF;
6327 this.view[offset+1] = (hi >>> 8) & 0xFF;
6328 this.view[offset ] = hi & 0xFF;
6329 } else {
6330 this.view[offset ] = (hi >>> 24) & 0xFF;
6331 this.view[offset+1] = (hi >>> 16) & 0xFF;
6332 this.view[offset+2] = (hi >>> 8) & 0xFF;
6333 this.view[offset+3] = hi & 0xFF;
6334 offset += 4;
6335 this.view[offset ] = (lo >>> 24) & 0xFF;
6336 this.view[offset+1] = (lo >>> 16) & 0xFF;
6337 this.view[offset+2] = (lo >>> 8) & 0xFF;
6338 this.view[offset+3] = lo & 0xFF;
6339 }
6340 if (relative) this.offset += 8;
6341 return this;
6342 };
6343
6344 /**
6345 * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
6346 * @param {number|!Long} value Value to write
6347 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6348 * @returns {!ByteBuffer} this
6349 * @expose
6350 */
6351 ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;
6352
6353 /**
6354 * Reads a 64bit signed integer.
6355 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6356 * @returns {!Long}
6357 * @expose
6358 */
6359 ByteBufferPrototype.readInt64 = function(offset) {
6360 var relative = typeof offset === 'undefined';
6361 if (relative) offset = this.offset;
6362 if (!this.noAssert) {
6363 if (typeof offset !== 'number' || offset % 1 !== 0)
6364 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6365 offset >>>= 0;
6366 if (offset < 0 || offset + 8 > this.buffer.byteLength)
6367 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
6368 }
6369 var lo = 0,
6370 hi = 0;
6371 if (this.littleEndian) {
6372 lo = this.view[offset+2] << 16;
6373 lo |= this.view[offset+1] << 8;
6374 lo |= this.view[offset ];
6375 lo += this.view[offset+3] << 24 >>> 0;
6376 offset += 4;
6377 hi = this.view[offset+2] << 16;
6378 hi |= this.view[offset+1] << 8;
6379 hi |= this.view[offset ];
6380 hi += this.view[offset+3] << 24 >>> 0;
6381 } else {
6382 hi = this.view[offset+1] << 16;
6383 hi |= this.view[offset+2] << 8;
6384 hi |= this.view[offset+3];
6385 hi += this.view[offset ] << 24 >>> 0;
6386 offset += 4;
6387 lo = this.view[offset+1] << 16;
6388 lo |= this.view[offset+2] << 8;
6389 lo |= this.view[offset+3];
6390 lo += this.view[offset ] << 24 >>> 0;
6391 }
6392 var value = new Long(lo, hi, false);
6393 if (relative) this.offset += 8;
6394 return value;
6395 };
6396
6397 /**
6398 * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
6399 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6400 * @returns {!Long}
6401 * @expose
6402 */
6403 ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;
6404
6405 /**
6406 * Writes a 64bit unsigned integer.
6407 * @param {number|!Long} value Value to write
6408 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6409 * @returns {!ByteBuffer} this
6410 * @expose
6411 */
6412 ByteBufferPrototype.writeUint64 = function(value, offset) {
6413 var relative = typeof offset === 'undefined';
6414 if (relative) offset = this.offset;
6415 if (!this.noAssert) {
6416 if (typeof value === 'number')
6417 value = Long.fromNumber(value);
6418 else if (typeof value === 'string')
6419 value = Long.fromString(value);
6420 else if (!(value && value instanceof Long))
6421 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
6422 if (typeof offset !== 'number' || offset % 1 !== 0)
6423 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6424 offset >>>= 0;
6425 if (offset < 0 || offset + 0 > this.buffer.byteLength)
6426 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
6427 }
6428 if (typeof value === 'number')
6429 value = Long.fromNumber(value);
6430 else if (typeof value === 'string')
6431 value = Long.fromString(value);
6432 offset += 8;
6433 var capacity7 = this.buffer.byteLength;
6434 if (offset > capacity7)
6435 this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
6436 offset -= 8;
6437 var lo = value.low,
6438 hi = value.high;
6439 if (this.littleEndian) {
6440 this.view[offset+3] = (lo >>> 24) & 0xFF;
6441 this.view[offset+2] = (lo >>> 16) & 0xFF;
6442 this.view[offset+1] = (lo >>> 8) & 0xFF;
6443 this.view[offset ] = lo & 0xFF;
6444 offset += 4;
6445 this.view[offset+3] = (hi >>> 24) & 0xFF;
6446 this.view[offset+2] = (hi >>> 16) & 0xFF;
6447 this.view[offset+1] = (hi >>> 8) & 0xFF;
6448 this.view[offset ] = hi & 0xFF;
6449 } else {
6450 this.view[offset ] = (hi >>> 24) & 0xFF;
6451 this.view[offset+1] = (hi >>> 16) & 0xFF;
6452 this.view[offset+2] = (hi >>> 8) & 0xFF;
6453 this.view[offset+3] = hi & 0xFF;
6454 offset += 4;
6455 this.view[offset ] = (lo >>> 24) & 0xFF;
6456 this.view[offset+1] = (lo >>> 16) & 0xFF;
6457 this.view[offset+2] = (lo >>> 8) & 0xFF;
6458 this.view[offset+3] = lo & 0xFF;
6459 }
6460 if (relative) this.offset += 8;
6461 return this;
6462 };
6463
6464 /**
6465 * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
6466 * @function
6467 * @param {number|!Long} value Value to write
6468 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6469 * @returns {!ByteBuffer} this
6470 * @expose
6471 */
6472 ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;
6473
6474 /**
6475 * Reads a 64bit unsigned integer.
6476 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6477 * @returns {!Long}
6478 * @expose
6479 */
6480 ByteBufferPrototype.readUint64 = function(offset) {
6481 var relative = typeof offset === 'undefined';
6482 if (relative) offset = this.offset;
6483 if (!this.noAssert) {
6484 if (typeof offset !== 'number' || offset % 1 !== 0)
6485 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6486 offset >>>= 0;
6487 if (offset < 0 || offset + 8 > this.buffer.byteLength)
6488 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
6489 }
6490 var lo = 0,
6491 hi = 0;
6492 if (this.littleEndian) {
6493 lo = this.view[offset+2] << 16;
6494 lo |= this.view[offset+1] << 8;
6495 lo |= this.view[offset ];
6496 lo += this.view[offset+3] << 24 >>> 0;
6497 offset += 4;
6498 hi = this.view[offset+2] << 16;
6499 hi |= this.view[offset+1] << 8;
6500 hi |= this.view[offset ];
6501 hi += this.view[offset+3] << 24 >>> 0;
6502 } else {
6503 hi = this.view[offset+1] << 16;
6504 hi |= this.view[offset+2] << 8;
6505 hi |= this.view[offset+3];
6506 hi += this.view[offset ] << 24 >>> 0;
6507 offset += 4;
6508 lo = this.view[offset+1] << 16;
6509 lo |= this.view[offset+2] << 8;
6510 lo |= this.view[offset+3];
6511 lo += this.view[offset ] << 24 >>> 0;
6512 }
6513 var value = new Long(lo, hi, true);
6514 if (relative) this.offset += 8;
6515 return value;
6516 };
6517
6518 /**
6519 * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
6520 * @function
6521 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6522 * @returns {!Long}
6523 * @expose
6524 */
6525 ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;
6526
6527 } // Long
6528
6529
6530 // types/floats/float32
6531
6532 /*
6533 ieee754 - https://github.com/feross/ieee754
6534
6535 The MIT License (MIT)
6536
6537 Copyright (c) Feross Aboukhadijeh
6538
6539 Permission is hereby granted, free of charge, to any person obtaining a copy
6540 of this software and associated documentation files (the "Software"), to deal
6541 in the Software without restriction, including without limitation the rights
6542 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
6543 copies of the Software, and to permit persons to whom the Software is
6544 furnished to do so, subject to the following conditions:
6545
6546 The above copyright notice and this permission notice shall be included in
6547 all copies or substantial portions of the Software.
6548
6549 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
6550 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6551 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
6552 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
6553 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
6554 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
6555 THE SOFTWARE.
6556 */
6557
6558 /**
6559 * Reads an IEEE754 float from a byte array.
6560 * @param {!Array} buffer
6561 * @param {number} offset
6562 * @param {boolean} isLE
6563 * @param {number} mLen
6564 * @param {number} nBytes
6565 * @returns {number}
6566 * @inner
6567 */
6568 function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
6569 var e, m,
6570 eLen = nBytes * 8 - mLen - 1,
6571 eMax = (1 << eLen) - 1,
6572 eBias = eMax >> 1,
6573 nBits = -7,
6574 i = isLE ? (nBytes - 1) : 0,
6575 d = isLE ? -1 : 1,
6576 s = buffer[offset + i];
6577
6578 i += d;
6579
6580 e = s & ((1 << (-nBits)) - 1);
6581 s >>= (-nBits);
6582 nBits += eLen;
6583 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
6584
6585 m = e & ((1 << (-nBits)) - 1);
6586 e >>= (-nBits);
6587 nBits += mLen;
6588 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
6589
6590 if (e === 0) {
6591 e = 1 - eBias;
6592 } else if (e === eMax) {
6593 return m ? NaN : ((s ? -1 : 1) * Infinity);
6594 } else {
6595 m = m + Math.pow(2, mLen);
6596 e = e - eBias;
6597 }
6598 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
6599 }
6600
6601 /**
6602 * Writes an IEEE754 float to a byte array.
6603 * @param {!Array} buffer
6604 * @param {number} value
6605 * @param {number} offset
6606 * @param {boolean} isLE
6607 * @param {number} mLen
6608 * @param {number} nBytes
6609 * @inner
6610 */
6611 function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
6612 var e, m, c,
6613 eLen = nBytes * 8 - mLen - 1,
6614 eMax = (1 << eLen) - 1,
6615 eBias = eMax >> 1,
6616 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
6617 i = isLE ? 0 : (nBytes - 1),
6618 d = isLE ? 1 : -1,
6619 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
6620
6621 value = Math.abs(value);
6622
6623 if (isNaN(value) || value === Infinity) {
6624 m = isNaN(value) ? 1 : 0;
6625 e = eMax;
6626 } else {
6627 e = Math.floor(Math.log(value) / Math.LN2);
6628 if (value * (c = Math.pow(2, -e)) < 1) {
6629 e--;
6630 c *= 2;
6631 }
6632 if (e + eBias >= 1) {
6633 value += rt / c;
6634 } else {
6635 value += rt * Math.pow(2, 1 - eBias);
6636 }
6637 if (value * c >= 2) {
6638 e++;
6639 c /= 2;
6640 }
6641
6642 if (e + eBias >= eMax) {
6643 m = 0;
6644 e = eMax;
6645 } else if (e + eBias >= 1) {
6646 m = (value * c - 1) * Math.pow(2, mLen);
6647 e = e + eBias;
6648 } else {
6649 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
6650 e = 0;
6651 }
6652 }
6653
6654 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
6655
6656 e = (e << mLen) | m;
6657 eLen += mLen;
6658 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
6659
6660 buffer[offset + i - d] |= s * 128;
6661 }
6662
6663 /**
6664 * Writes a 32bit float.
6665 * @param {number} value Value to write
6666 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
6667 * @returns {!ByteBuffer} this
6668 * @expose
6669 */
6670 ByteBufferPrototype.writeFloat32 = function(value, offset) {
6671 var relative = typeof offset === 'undefined';
6672 if (relative) offset = this.offset;
6673 if (!this.noAssert) {
6674 if (typeof value !== 'number')
6675 throw TypeError("Illegal value: "+value+" (not a number)");
6676 if (typeof offset !== 'number' || offset % 1 !== 0)
6677 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6678 offset >>>= 0;
6679 if (offset < 0 || offset + 0 > this.buffer.byteLength)
6680 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
6681 }
6682 offset += 4;
6683 var capacity8 = this.buffer.byteLength;
6684 if (offset > capacity8)
6685 this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
6686 offset -= 4;
6687 ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
6688 if (relative) this.offset += 4;
6689 return this;
6690 };
6691
6692 /**
6693 * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
6694 * @function
6695 * @param {number} value Value to write
6696 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
6697 * @returns {!ByteBuffer} this
6698 * @expose
6699 */
6700 ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;
6701
6702 /**
6703 * Reads a 32bit float.
6704 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
6705 * @returns {number}
6706 * @expose
6707 */
6708 ByteBufferPrototype.readFloat32 = function(offset) {
6709 var relative = typeof offset === 'undefined';
6710 if (relative) offset = this.offset;
6711 if (!this.noAssert) {
6712 if (typeof offset !== 'number' || offset % 1 !== 0)
6713 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6714 offset >>>= 0;
6715 if (offset < 0 || offset + 4 > this.buffer.byteLength)
6716 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
6717 }
6718 var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
6719 if (relative) this.offset += 4;
6720 return value;
6721 };
6722
6723 /**
6724 * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
6725 * @function
6726 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
6727 * @returns {number}
6728 * @expose
6729 */
6730 ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;
6731
6732 // types/floats/float64
6733
6734 /**
6735 * Writes a 64bit float.
6736 * @param {number} value Value to write
6737 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6738 * @returns {!ByteBuffer} this
6739 * @expose
6740 */
6741 ByteBufferPrototype.writeFloat64 = function(value, offset) {
6742 var relative = typeof offset === 'undefined';
6743 if (relative) offset = this.offset;
6744 if (!this.noAssert) {
6745 if (typeof value !== 'number')
6746 throw TypeError("Illegal value: "+value+" (not a number)");
6747 if (typeof offset !== 'number' || offset % 1 !== 0)
6748 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6749 offset >>>= 0;
6750 if (offset < 0 || offset + 0 > this.buffer.byteLength)
6751 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
6752 }
6753 offset += 8;
6754 var capacity9 = this.buffer.byteLength;
6755 if (offset > capacity9)
6756 this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
6757 offset -= 8;
6758 ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
6759 if (relative) this.offset += 8;
6760 return this;
6761 };
6762
6763 /**
6764 * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
6765 * @function
6766 * @param {number} value Value to write
6767 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6768 * @returns {!ByteBuffer} this
6769 * @expose
6770 */
6771 ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;
6772
6773 /**
6774 * Reads a 64bit float.
6775 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6776 * @returns {number}
6777 * @expose
6778 */
6779 ByteBufferPrototype.readFloat64 = function(offset) {
6780 var relative = typeof offset === 'undefined';
6781 if (relative) offset = this.offset;
6782 if (!this.noAssert) {
6783 if (typeof offset !== 'number' || offset % 1 !== 0)
6784 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6785 offset >>>= 0;
6786 if (offset < 0 || offset + 8 > this.buffer.byteLength)
6787 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
6788 }
6789 var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
6790 if (relative) this.offset += 8;
6791 return value;
6792 };
6793
6794 /**
6795 * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
6796 * @function
6797 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
6798 * @returns {number}
6799 * @expose
6800 */
6801 ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;
6802
6803
6804 // types/varints/varint32
6805
6806 /**
6807 * Maximum number of bytes required to store a 32bit base 128 variable-length integer.
6808 * @type {number}
6809 * @const
6810 * @expose
6811 */
6812 ByteBuffer.MAX_VARINT32_BYTES = 5;
6813
6814 /**
6815 * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
6816 * @param {number} value Value to encode
6817 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
6818 * @expose
6819 */
6820 ByteBuffer.calculateVarint32 = function(value) {
6821 // ref: src/google/protobuf/io/coded_stream.cc
6822 value = value >>> 0;
6823 if (value < 1 << 7 ) return 1;
6824 else if (value < 1 << 14) return 2;
6825 else if (value < 1 << 21) return 3;
6826 else if (value < 1 << 28) return 4;
6827 else return 5;
6828 };
6829
6830 /**
6831 * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
6832 * @param {number} n Signed 32bit integer
6833 * @returns {number} Unsigned zigzag encoded 32bit integer
6834 * @expose
6835 */
6836 ByteBuffer.zigZagEncode32 = function(n) {
6837 return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
6838 };
6839
6840 /**
6841 * Decodes a zigzag encoded signed 32bit integer.
6842 * @param {number} n Unsigned zigzag encoded 32bit integer
6843 * @returns {number} Signed 32bit integer
6844 * @expose
6845 */
6846 ByteBuffer.zigZagDecode32 = function(n) {
6847 return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
6848 };
6849
6850 /**
6851 * Writes a 32bit base 128 variable-length integer.
6852 * @param {number} value Value to write
6853 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
6854 * written if omitted.
6855 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
6856 * @expose
6857 */
6858 ByteBufferPrototype.writeVarint32 = function(value, offset) {
6859 var relative = typeof offset === 'undefined';
6860 if (relative) offset = this.offset;
6861 if (!this.noAssert) {
6862 if (typeof value !== 'number' || value % 1 !== 0)
6863 throw TypeError("Illegal value: "+value+" (not an integer)");
6864 value |= 0;
6865 if (typeof offset !== 'number' || offset % 1 !== 0)
6866 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6867 offset >>>= 0;
6868 if (offset < 0 || offset + 0 > this.buffer.byteLength)
6869 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
6870 }
6871 var size = ByteBuffer.calculateVarint32(value),
6872 b;
6873 offset += size;
6874 var capacity10 = this.buffer.byteLength;
6875 if (offset > capacity10)
6876 this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
6877 offset -= size;
6878 value >>>= 0;
6879 while (value >= 0x80) {
6880 b = (value & 0x7f) | 0x80;
6881 this.view[offset++] = b;
6882 value >>>= 7;
6883 }
6884 this.view[offset++] = value;
6885 if (relative) {
6886 this.offset = offset;
6887 return this;
6888 }
6889 return size;
6890 };
6891
6892 /**
6893 * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
6894 * @param {number} value Value to write
6895 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
6896 * written if omitted.
6897 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
6898 * @expose
6899 */
6900 ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) {
6901 return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
6902 };
6903
6904 /**
6905 * Reads a 32bit base 128 variable-length integer.
6906 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
6907 * written if omitted.
6908 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
6909 * and the actual number of bytes read.
6910 * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
6911 * to fully decode the varint.
6912 * @expose
6913 */
6914 ByteBufferPrototype.readVarint32 = function(offset) {
6915 var relative = typeof offset === 'undefined';
6916 if (relative) offset = this.offset;
6917 if (!this.noAssert) {
6918 if (typeof offset !== 'number' || offset % 1 !== 0)
6919 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6920 offset >>>= 0;
6921 if (offset < 0 || offset + 1 > this.buffer.byteLength)
6922 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
6923 }
6924 var c = 0,
6925 value = 0 >>> 0,
6926 b;
6927 do {
6928 if (!this.noAssert && offset > this.limit) {
6929 var err = Error("Truncated");
6930 err['truncated'] = true;
6931 throw err;
6932 }
6933 b = this.view[offset++];
6934 if (c < 5)
6935 value |= (b & 0x7f) << (7*c);
6936 ++c;
6937 } while ((b & 0x80) !== 0);
6938 value |= 0;
6939 if (relative) {
6940 this.offset = offset;
6941 return value;
6942 }
6943 return {
6944 "value": value,
6945 "length": c
6946 };
6947 };
6948
6949 /**
6950 * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
6951 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
6952 * written if omitted.
6953 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
6954 * and the actual number of bytes read.
6955 * @throws {Error} If it's not a valid varint
6956 * @expose
6957 */
6958 ByteBufferPrototype.readVarint32ZigZag = function(offset) {
6959 var val = this.readVarint32(offset);
6960 if (typeof val === 'object')
6961 val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
6962 else
6963 val = ByteBuffer.zigZagDecode32(val);
6964 return val;
6965 };
6966
6967 // types/varints/varint64
6968
6969 if (Long) {
6970
6971 /**
6972 * Maximum number of bytes required to store a 64bit base 128 variable-length integer.
6973 * @type {number}
6974 * @const
6975 * @expose
6976 */
6977 ByteBuffer.MAX_VARINT64_BYTES = 10;
6978
6979 /**
6980 * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
6981 * @param {number|!Long} value Value to encode
6982 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
6983 * @expose
6984 */
6985 ByteBuffer.calculateVarint64 = function(value) {
6986 if (typeof value === 'number')
6987 value = Long.fromNumber(value);
6988 else if (typeof value === 'string')
6989 value = Long.fromString(value);
6990 // ref: src/google/protobuf/io/coded_stream.cc
6991 var part0 = value.toInt() >>> 0,
6992 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
6993 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
6994 if (part2 == 0) {
6995 if (part1 == 0) {
6996 if (part0 < 1 << 14)
6997 return part0 < 1 << 7 ? 1 : 2;
6998 else
6999 return part0 < 1 << 21 ? 3 : 4;
7000 } else {
7001 if (part1 < 1 << 14)
7002 return part1 < 1 << 7 ? 5 : 6;
7003 else
7004 return part1 < 1 << 21 ? 7 : 8;
7005 }
7006 } else
7007 return part2 < 1 << 7 ? 9 : 10;
7008 };
7009
7010 /**
7011 * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
7012 * @param {number|!Long} value Signed long
7013 * @returns {!Long} Unsigned zigzag encoded long
7014 * @expose
7015 */
7016 ByteBuffer.zigZagEncode64 = function(value) {
7017 if (typeof value === 'number')
7018 value = Long.fromNumber(value, false);
7019 else if (typeof value === 'string')
7020 value = Long.fromString(value, false);
7021 else if (value.unsigned !== false) value = value.toSigned();
7022 // ref: src/google/protobuf/wire_format_lite.h
7023 return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
7024 };
7025
7026 /**
7027 * Decodes a zigzag encoded signed 64bit integer.
7028 * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
7029 * @returns {!Long} Signed long
7030 * @expose
7031 */
7032 ByteBuffer.zigZagDecode64 = function(value) {
7033 if (typeof value === 'number')
7034 value = Long.fromNumber(value, false);
7035 else if (typeof value === 'string')
7036 value = Long.fromString(value, false);
7037 else if (value.unsigned !== false) value = value.toSigned();
7038 // ref: src/google/protobuf/wire_format_lite.h
7039 return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
7040 };
7041
7042 /**
7043 * Writes a 64bit base 128 variable-length integer.
7044 * @param {number|Long} value Value to write
7045 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7046 * written if omitted.
7047 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
7048 * @expose
7049 */
7050 ByteBufferPrototype.writeVarint64 = function(value, offset) {
7051 var relative = typeof offset === 'undefined';
7052 if (relative) offset = this.offset;
7053 if (!this.noAssert) {
7054 if (typeof value === 'number')
7055 value = Long.fromNumber(value);
7056 else if (typeof value === 'string')
7057 value = Long.fromString(value);
7058 else if (!(value && value instanceof Long))
7059 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
7060 if (typeof offset !== 'number' || offset % 1 !== 0)
7061 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7062 offset >>>= 0;
7063 if (offset < 0 || offset + 0 > this.buffer.byteLength)
7064 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
7065 }
7066 if (typeof value === 'number')
7067 value = Long.fromNumber(value, false);
7068 else if (typeof value === 'string')
7069 value = Long.fromString(value, false);
7070 else if (value.unsigned !== false) value = value.toSigned();
7071 var size = ByteBuffer.calculateVarint64(value),
7072 part0 = value.toInt() >>> 0,
7073 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
7074 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
7075 offset += size;
7076 var capacity11 = this.buffer.byteLength;
7077 if (offset > capacity11)
7078 this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
7079 offset -= size;
7080 switch (size) {
7081 case 10: this.view[offset+9] = (part2 >>> 7) & 0x01;
7082 case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F;
7083 case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
7084 case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
7085 case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
7086 case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F;
7087 case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
7088 case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
7089 case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
7090 case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F;
7091 }
7092 if (relative) {
7093 this.offset += size;
7094 return this;
7095 } else {
7096 return size;
7097 }
7098 };
7099
7100 /**
7101 * Writes a zig-zag encoded 64bit base 128 variable-length integer.
7102 * @param {number|Long} value Value to write
7103 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7104 * written if omitted.
7105 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
7106 * @expose
7107 */
7108 ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) {
7109 return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
7110 };
7111
7112 /**
7113 * Reads a 64bit base 128 variable-length integer. Requires Long.js.
7114 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7115 * read if omitted.
7116 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
7117 * the actual number of bytes read.
7118 * @throws {Error} If it's not a valid varint
7119 * @expose
7120 */
7121 ByteBufferPrototype.readVarint64 = function(offset) {
7122 var relative = typeof offset === 'undefined';
7123 if (relative) offset = this.offset;
7124 if (!this.noAssert) {
7125 if (typeof offset !== 'number' || offset % 1 !== 0)
7126 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7127 offset >>>= 0;
7128 if (offset < 0 || offset + 1 > this.buffer.byteLength)
7129 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
7130 }
7131 // ref: src/google/protobuf/io/coded_stream.cc
7132 var start = offset,
7133 part0 = 0,
7134 part1 = 0,
7135 part2 = 0,
7136 b = 0;
7137 b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) {
7138 b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
7139 b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
7140 b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
7141 b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
7142 b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
7143 b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
7144 b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
7145 b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
7146 b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
7147 throw Error("Buffer overrun"); }}}}}}}}}}
7148 var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
7149 if (relative) {
7150 this.offset = offset;
7151 return value;
7152 } else {
7153 return {
7154 'value': value,
7155 'length': offset-start
7156 };
7157 }
7158 };
7159
7160 /**
7161 * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
7162 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7163 * read if omitted.
7164 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
7165 * the actual number of bytes read.
7166 * @throws {Error} If it's not a valid varint
7167 * @expose
7168 */
7169 ByteBufferPrototype.readVarint64ZigZag = function(offset) {
7170 var val = this.readVarint64(offset);
7171 if (val && val['value'] instanceof Long)
7172 val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
7173 else
7174 val = ByteBuffer.zigZagDecode64(val);
7175 return val;
7176 };
7177
7178 } // Long
7179
7180
7181 // types/strings/cstring
7182
7183 /**
7184 * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
7185 * characters itself.
7186 * @param {string} str String to write
7187 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7188 * contained in `str` + 1 if omitted.
7189 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
7190 * @expose
7191 */
7192 ByteBufferPrototype.writeCString = function(str, offset) {
7193 var relative = typeof offset === 'undefined';
7194 if (relative) offset = this.offset;
7195 var i,
7196 k = str.length;
7197 if (!this.noAssert) {
7198 if (typeof str !== 'string')
7199 throw TypeError("Illegal str: Not a string");
7200 for (i=0; i<k; ++i) {
7201 if (str.charCodeAt(i) === 0)
7202 throw RangeError("Illegal str: Contains NULL-characters");
7203 }
7204 if (typeof offset !== 'number' || offset % 1 !== 0)
7205 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7206 offset >>>= 0;
7207 if (offset < 0 || offset + 0 > this.buffer.byteLength)
7208 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
7209 }
7210 // UTF8 strings do not contain zero bytes in between except for the zero character, so:
7211 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
7212 offset += k+1;
7213 var capacity12 = this.buffer.byteLength;
7214 if (offset > capacity12)
7215 this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
7216 offset -= k+1;
7217 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
7218 this.view[offset++] = b;
7219 }.bind(this));
7220 this.view[offset++] = 0;
7221 if (relative) {
7222 this.offset = offset;
7223 return this;
7224 }
7225 return k;
7226 };
7227
7228 /**
7229 * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
7230 * itself.
7231 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7232 * read if omitted.
7233 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
7234 * read and the actual number of bytes read.
7235 * @expose
7236 */
7237 ByteBufferPrototype.readCString = function(offset) {
7238 var relative = typeof offset === 'undefined';
7239 if (relative) offset = this.offset;
7240 if (!this.noAssert) {
7241 if (typeof offset !== 'number' || offset % 1 !== 0)
7242 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7243 offset >>>= 0;
7244 if (offset < 0 || offset + 1 > this.buffer.byteLength)
7245 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
7246 }
7247 var start = offset,
7248 temp;
7249 // UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
7250 var sd, b = -1;
7251 utfx.decodeUTF8toUTF16(function() {
7252 if (b === 0) return null;
7253 if (offset >= this.limit)
7254 throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit);
7255 b = this.view[offset++];
7256 return b === 0 ? null : b;
7257 }.bind(this), sd = stringDestination(), true);
7258 if (relative) {
7259 this.offset = offset;
7260 return sd();
7261 } else {
7262 return {
7263 "string": sd(),
7264 "length": offset - start
7265 };
7266 }
7267 };
7268
7269 // types/strings/istring
7270
7271 /**
7272 * Writes a length as uint32 prefixed UTF8 encoded string.
7273 * @param {string} str String to write
7274 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7275 * written if omitted.
7276 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
7277 * @expose
7278 * @see ByteBuffer#writeVarint32
7279 */
7280 ByteBufferPrototype.writeIString = function(str, offset) {
7281 var relative = typeof offset === 'undefined';
7282 if (relative) offset = this.offset;
7283 if (!this.noAssert) {
7284 if (typeof str !== 'string')
7285 throw TypeError("Illegal str: Not a string");
7286 if (typeof offset !== 'number' || offset % 1 !== 0)
7287 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7288 offset >>>= 0;
7289 if (offset < 0 || offset + 0 > this.buffer.byteLength)
7290 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
7291 }
7292 var start = offset,
7293 k;
7294 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
7295 offset += 4+k;
7296 var capacity13 = this.buffer.byteLength;
7297 if (offset > capacity13)
7298 this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
7299 offset -= 4+k;
7300 if (this.littleEndian) {
7301 this.view[offset+3] = (k >>> 24) & 0xFF;
7302 this.view[offset+2] = (k >>> 16) & 0xFF;
7303 this.view[offset+1] = (k >>> 8) & 0xFF;
7304 this.view[offset ] = k & 0xFF;
7305 } else {
7306 this.view[offset ] = (k >>> 24) & 0xFF;
7307 this.view[offset+1] = (k >>> 16) & 0xFF;
7308 this.view[offset+2] = (k >>> 8) & 0xFF;
7309 this.view[offset+3] = k & 0xFF;
7310 }
7311 offset += 4;
7312 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
7313 this.view[offset++] = b;
7314 }.bind(this));
7315 if (offset !== start + 4 + k)
7316 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k));
7317 if (relative) {
7318 this.offset = offset;
7319 return this;
7320 }
7321 return offset - start;
7322 };
7323
7324 /**
7325 * Reads a length as uint32 prefixed UTF8 encoded string.
7326 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7327 * read if omitted.
7328 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
7329 * read and the actual number of bytes read.
7330 * @expose
7331 * @see ByteBuffer#readVarint32
7332 */
7333 ByteBufferPrototype.readIString = function(offset) {
7334 var relative = typeof offset === 'undefined';
7335 if (relative) offset = this.offset;
7336 if (!this.noAssert) {
7337 if (typeof offset !== 'number' || offset % 1 !== 0)
7338 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7339 offset >>>= 0;
7340 if (offset < 0 || offset + 4 > this.buffer.byteLength)
7341 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
7342 }
7343 var start = offset;
7344 var len = this.readUint32(offset);
7345 var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4);
7346 offset += str['length'];
7347 if (relative) {
7348 this.offset = offset;
7349 return str['string'];
7350 } else {
7351 return {
7352 'string': str['string'],
7353 'length': offset - start
7354 };
7355 }
7356 };
7357
7358 // types/strings/utf8string
7359
7360 /**
7361 * Metrics representing number of UTF8 characters. Evaluates to `c`.
7362 * @type {string}
7363 * @const
7364 * @expose
7365 */
7366 ByteBuffer.METRICS_CHARS = 'c';
7367
7368 /**
7369 * Metrics representing number of bytes. Evaluates to `b`.
7370 * @type {string}
7371 * @const
7372 * @expose
7373 */
7374 ByteBuffer.METRICS_BYTES = 'b';
7375
7376 /**
7377 * Writes an UTF8 encoded string.
7378 * @param {string} str String to write
7379 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
7380 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
7381 * @expose
7382 */
7383 ByteBufferPrototype.writeUTF8String = function(str, offset) {
7384 var relative = typeof offset === 'undefined';
7385 if (relative) offset = this.offset;
7386 if (!this.noAssert) {
7387 if (typeof offset !== 'number' || offset % 1 !== 0)
7388 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7389 offset >>>= 0;
7390 if (offset < 0 || offset + 0 > this.buffer.byteLength)
7391 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
7392 }
7393 var k;
7394 var start = offset;
7395 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
7396 offset += k;
7397 var capacity14 = this.buffer.byteLength;
7398 if (offset > capacity14)
7399 this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
7400 offset -= k;
7401 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
7402 this.view[offset++] = b;
7403 }.bind(this));
7404 if (relative) {
7405 this.offset = offset;
7406 return this;
7407 }
7408 return offset - start;
7409 };
7410
7411 /**
7412 * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
7413 * @function
7414 * @param {string} str String to write
7415 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
7416 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
7417 * @expose
7418 */
7419 ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
7420
7421 /**
7422 * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
7423 * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
7424 * @param {string} str String to calculate
7425 * @returns {number} Number of UTF8 characters
7426 * @expose
7427 */
7428 ByteBuffer.calculateUTF8Chars = function(str) {
7429 return utfx.calculateUTF16asUTF8(stringSource(str))[0];
7430 };
7431
7432 /**
7433 * Calculates the number of UTF8 bytes of a string.
7434 * @param {string} str String to calculate
7435 * @returns {number} Number of UTF8 bytes
7436 * @expose
7437 */
7438 ByteBuffer.calculateUTF8Bytes = function(str) {
7439 return utfx.calculateUTF16asUTF8(stringSource(str))[1];
7440 };
7441
7442 /**
7443 * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
7444 * @function
7445 * @param {string} str String to calculate
7446 * @returns {number} Number of UTF8 bytes
7447 * @expose
7448 */
7449 ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;
7450
7451 /**
7452 * Reads an UTF8 encoded string.
7453 * @param {number} length Number of characters or bytes to read.
7454 * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
7455 * {@link ByteBuffer.METRICS_CHARS}.
7456 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7457 * read if omitted.
7458 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
7459 * read and the actual number of bytes read.
7460 * @expose
7461 */
7462 ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
7463 if (typeof metrics === 'number') {
7464 offset = metrics;
7465 metrics = undefined;
7466 }
7467 var relative = typeof offset === 'undefined';
7468 if (relative) offset = this.offset;
7469 if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
7470 if (!this.noAssert) {
7471 if (typeof length !== 'number' || length % 1 !== 0)
7472 throw TypeError("Illegal length: "+length+" (not an integer)");
7473 length |= 0;
7474 if (typeof offset !== 'number' || offset % 1 !== 0)
7475 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7476 offset >>>= 0;
7477 if (offset < 0 || offset + 0 > this.buffer.byteLength)
7478 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
7479 }
7480 var i = 0,
7481 start = offset,
7482 sd;
7483 if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
7484 sd = stringDestination();
7485 utfx.decodeUTF8(function() {
7486 return i < length && offset < this.limit ? this.view[offset++] : null;
7487 }.bind(this), function(cp) {
7488 ++i; utfx.UTF8toUTF16(cp, sd);
7489 });
7490 if (i !== length)
7491 throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
7492 if (relative) {
7493 this.offset = offset;
7494 return sd();
7495 } else {
7496 return {
7497 "string": sd(),
7498 "length": offset - start
7499 };
7500 }
7501 } else if (metrics === ByteBuffer.METRICS_BYTES) {
7502 if (!this.noAssert) {
7503 if (typeof offset !== 'number' || offset % 1 !== 0)
7504 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7505 offset >>>= 0;
7506 if (offset < 0 || offset + length > this.buffer.byteLength)
7507 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
7508 }
7509 var k = offset + length;
7510 utfx.decodeUTF8toUTF16(function() {
7511 return offset < k ? this.view[offset++] : null;
7512 }.bind(this), sd = stringDestination(), this.noAssert);
7513 if (offset !== k)
7514 throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
7515 if (relative) {
7516 this.offset = offset;
7517 return sd();
7518 } else {
7519 return {
7520 'string': sd(),
7521 'length': offset - start
7522 };
7523 }
7524 } else
7525 throw TypeError("Unsupported metrics: "+metrics);
7526 };
7527
7528 /**
7529 * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
7530 * @function
7531 * @param {number} length Number of characters or bytes to read
7532 * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
7533 * {@link ByteBuffer.METRICS_CHARS}.
7534 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7535 * read if omitted.
7536 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
7537 * read and the actual number of bytes read.
7538 * @expose
7539 */
7540 ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
7541
7542 // types/strings/vstring
7543
7544 /**
7545 * Writes a length as varint32 prefixed UTF8 encoded string.
7546 * @param {string} str String to write
7547 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7548 * written if omitted.
7549 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
7550 * @expose
7551 * @see ByteBuffer#writeVarint32
7552 */
7553 ByteBufferPrototype.writeVString = function(str, offset) {
7554 var relative = typeof offset === 'undefined';
7555 if (relative) offset = this.offset;
7556 if (!this.noAssert) {
7557 if (typeof str !== 'string')
7558 throw TypeError("Illegal str: Not a string");
7559 if (typeof offset !== 'number' || offset % 1 !== 0)
7560 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7561 offset >>>= 0;
7562 if (offset < 0 || offset + 0 > this.buffer.byteLength)
7563 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
7564 }
7565 var start = offset,
7566 k, l;
7567 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
7568 l = ByteBuffer.calculateVarint32(k);
7569 offset += l+k;
7570 var capacity15 = this.buffer.byteLength;
7571 if (offset > capacity15)
7572 this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
7573 offset -= l+k;
7574 offset += this.writeVarint32(k, offset);
7575 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
7576 this.view[offset++] = b;
7577 }.bind(this));
7578 if (offset !== start+k+l)
7579 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l));
7580 if (relative) {
7581 this.offset = offset;
7582 return this;
7583 }
7584 return offset - start;
7585 };
7586
7587 /**
7588 * Reads a length as varint32 prefixed UTF8 encoded string.
7589 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7590 * read if omitted.
7591 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
7592 * read and the actual number of bytes read.
7593 * @expose
7594 * @see ByteBuffer#readVarint32
7595 */
7596 ByteBufferPrototype.readVString = function(offset) {
7597 var relative = typeof offset === 'undefined';
7598 if (relative) offset = this.offset;
7599 if (!this.noAssert) {
7600 if (typeof offset !== 'number' || offset % 1 !== 0)
7601 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7602 offset >>>= 0;
7603 if (offset < 0 || offset + 1 > this.buffer.byteLength)
7604 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
7605 }
7606 var start = offset;
7607 var len = this.readVarint32(offset);
7608 var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']);
7609 offset += str['length'];
7610 if (relative) {
7611 this.offset = offset;
7612 return str['string'];
7613 } else {
7614 return {
7615 'string': str['string'],
7616 'length': offset - start
7617 };
7618 }
7619 };
7620
7621
7622 /**
7623 * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
7624 * data's length.
7625 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
7626 * will be modified according to the performed read operation.
7627 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
7628 * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7629 * written if omitted.
7630 * @returns {!ByteBuffer} this
7631 * @expose
7632 * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
7633 * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
7634 */
7635 ByteBufferPrototype.append = function(source, encoding, offset) {
7636 if (typeof encoding === 'number' || typeof encoding !== 'string') {
7637 offset = encoding;
7638 encoding = undefined;
7639 }
7640 var relative = typeof offset === 'undefined';
7641 if (relative) offset = this.offset;
7642 if (!this.noAssert) {
7643 if (typeof offset !== 'number' || offset % 1 !== 0)
7644 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7645 offset >>>= 0;
7646 if (offset < 0 || offset + 0 > this.buffer.byteLength)
7647 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
7648 }
7649 if (!(source instanceof ByteBuffer))
7650 source = ByteBuffer.wrap(source, encoding);
7651 var length = source.limit - source.offset;
7652 if (length <= 0) return this; // Nothing to append
7653 offset += length;
7654 var capacity16 = this.buffer.byteLength;
7655 if (offset > capacity16)
7656 this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
7657 offset -= length;
7658 this.view.set(source.view.subarray(source.offset, source.limit), offset);
7659 source.offset += length;
7660 if (relative) this.offset += length;
7661 return this;
7662 };
7663
7664 /**
7665 * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
7666 specified offset up to the length of this ByteBuffer's data.
7667 * @param {!ByteBuffer} target Target ByteBuffer
7668 * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7669 * read if omitted.
7670 * @returns {!ByteBuffer} this
7671 * @expose
7672 * @see ByteBuffer#append
7673 */
7674 ByteBufferPrototype.appendTo = function(target, offset) {
7675 target.append(this, offset);
7676 return this;
7677 };
7678
7679 /**
7680 * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
7681 * disable them if your code already makes sure that everything is valid.
7682 * @param {boolean} assert `true` to enable assertions, otherwise `false`
7683 * @returns {!ByteBuffer} this
7684 * @expose
7685 */
7686 ByteBufferPrototype.assert = function(assert) {
7687 this.noAssert = !assert;
7688 return this;
7689 };
7690
7691 /**
7692 * Gets the capacity of this ByteBuffer's backing buffer.
7693 * @returns {number} Capacity of the backing buffer
7694 * @expose
7695 */
7696 ByteBufferPrototype.capacity = function() {
7697 return this.buffer.byteLength;
7698 };
7699 /**
7700 * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
7701 * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
7702 * @returns {!ByteBuffer} this
7703 * @expose
7704 */
7705 ByteBufferPrototype.clear = function() {
7706 this.offset = 0;
7707 this.limit = this.buffer.byteLength;
7708 this.markedOffset = -1;
7709 return this;
7710 };
7711
7712 /**
7713 * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
7714 * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
7715 * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
7716 * @returns {!ByteBuffer} Cloned instance
7717 * @expose
7718 */
7719 ByteBufferPrototype.clone = function(copy) {
7720 var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
7721 if (copy) {
7722 bb.buffer = new ArrayBuffer(this.buffer.byteLength);
7723 bb.view = new Uint8Array(bb.buffer);
7724 } else {
7725 bb.buffer = this.buffer;
7726 bb.view = this.view;
7727 }
7728 bb.offset = this.offset;
7729 bb.markedOffset = this.markedOffset;
7730 bb.limit = this.limit;
7731 return bb;
7732 };
7733
7734 /**
7735 * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
7736 * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
7737 * adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
7738 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
7739 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
7740 * @returns {!ByteBuffer} this
7741 * @expose
7742 */
7743 ByteBufferPrototype.compact = function(begin, end) {
7744 if (typeof begin === 'undefined') begin = this.offset;
7745 if (typeof end === 'undefined') end = this.limit;
7746 if (!this.noAssert) {
7747 if (typeof begin !== 'number' || begin % 1 !== 0)
7748 throw TypeError("Illegal begin: Not an integer");
7749 begin >>>= 0;
7750 if (typeof end !== 'number' || end % 1 !== 0)
7751 throw TypeError("Illegal end: Not an integer");
7752 end >>>= 0;
7753 if (begin < 0 || begin > end || end > this.buffer.byteLength)
7754 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
7755 }
7756 if (begin === 0 && end === this.buffer.byteLength)
7757 return this; // Already compacted
7758 var len = end - begin;
7759 if (len === 0) {
7760 this.buffer = EMPTY_BUFFER;
7761 this.view = null;
7762 if (this.markedOffset >= 0) this.markedOffset -= begin;
7763 this.offset = 0;
7764 this.limit = 0;
7765 return this;
7766 }
7767 var buffer = new ArrayBuffer(len);
7768 var view = new Uint8Array(buffer);
7769 view.set(this.view.subarray(begin, end));
7770 this.buffer = buffer;
7771 this.view = view;
7772 if (this.markedOffset >= 0) this.markedOffset -= begin;
7773 this.offset = 0;
7774 this.limit = len;
7775 return this;
7776 };
7777
7778 /**
7779 * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
7780 * {@link ByteBuffer#limit}.
7781 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
7782 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
7783 * @returns {!ByteBuffer} Copy
7784 * @expose
7785 */
7786 ByteBufferPrototype.copy = function(begin, end) {
7787 if (typeof begin === 'undefined') begin = this.offset;
7788 if (typeof end === 'undefined') end = this.limit;
7789 if (!this.noAssert) {
7790 if (typeof begin !== 'number' || begin % 1 !== 0)
7791 throw TypeError("Illegal begin: Not an integer");
7792 begin >>>= 0;
7793 if (typeof end !== 'number' || end % 1 !== 0)
7794 throw TypeError("Illegal end: Not an integer");
7795 end >>>= 0;
7796 if (begin < 0 || begin > end || end > this.buffer.byteLength)
7797 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
7798 }
7799 if (begin === end)
7800 return new ByteBuffer(0, this.littleEndian, this.noAssert);
7801 var capacity = end - begin,
7802 bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
7803 bb.offset = 0;
7804 bb.limit = capacity;
7805 if (bb.markedOffset >= 0) bb.markedOffset -= begin;
7806 this.copyTo(bb, 0, begin, end);
7807 return bb;
7808 };
7809
7810 /**
7811 * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
7812 * {@link ByteBuffer#limit}.
7813 * @param {!ByteBuffer} target Target ByteBuffer
7814 * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
7815 * by the number of bytes copied if omitted.
7816 * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
7817 * number of bytes copied if omitted.
7818 * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
7819 * @returns {!ByteBuffer} this
7820 * @expose
7821 */
7822 ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) {
7823 var relative,
7824 targetRelative;
7825 if (!this.noAssert) {
7826 if (!ByteBuffer.isByteBuffer(target))
7827 throw TypeError("Illegal target: Not a ByteBuffer");
7828 }
7829 targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
7830 sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
7831 sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;
7832
7833 if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
7834 throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength);
7835 if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
7836 throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength);
7837
7838 var len = sourceLimit - sourceOffset;
7839 if (len === 0)
7840 return target; // Nothing to copy
7841
7842 target.ensureCapacity(targetOffset + len);
7843
7844 target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);
7845
7846 if (relative) this.offset += len;
7847 if (targetRelative) target.offset += len;
7848
7849 return this;
7850 };
7851
7852 /**
7853 * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
7854 * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
7855 * the required capacity will be used instead.
7856 * @param {number} capacity Required capacity
7857 * @returns {!ByteBuffer} this
7858 * @expose
7859 */
7860 ByteBufferPrototype.ensureCapacity = function(capacity) {
7861 var current = this.buffer.byteLength;
7862 if (current < capacity)
7863 return this.resize((current *= 2) > capacity ? current : capacity);
7864 return this;
7865 };
7866
7867 /**
7868 * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
7869 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
7870 * @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
7871 * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
7872 * written if omitted. defaults to {@link ByteBuffer#offset}.
7873 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
7874 * @returns {!ByteBuffer} this
7875 * @expose
7876 * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
7877 */
7878 ByteBufferPrototype.fill = function(value, begin, end) {
7879 var relative = typeof begin === 'undefined';
7880 if (relative) begin = this.offset;
7881 if (typeof value === 'string' && value.length > 0)
7882 value = value.charCodeAt(0);
7883 if (typeof begin === 'undefined') begin = this.offset;
7884 if (typeof end === 'undefined') end = this.limit;
7885 if (!this.noAssert) {
7886 if (typeof value !== 'number' || value % 1 !== 0)
7887 throw TypeError("Illegal value: "+value+" (not an integer)");
7888 value |= 0;
7889 if (typeof begin !== 'number' || begin % 1 !== 0)
7890 throw TypeError("Illegal begin: Not an integer");
7891 begin >>>= 0;
7892 if (typeof end !== 'number' || end % 1 !== 0)
7893 throw TypeError("Illegal end: Not an integer");
7894 end >>>= 0;
7895 if (begin < 0 || begin > end || end > this.buffer.byteLength)
7896 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
7897 }
7898 if (begin >= end)
7899 return this; // Nothing to fill
7900 while (begin < end) this.view[begin++] = value;
7901 if (relative) this.offset = begin;
7902 return this;
7903 };
7904
7905 /**
7906 * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
7907 * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
7908 * @returns {!ByteBuffer} this
7909 * @expose
7910 */
7911 ByteBufferPrototype.flip = function() {
7912 this.limit = this.offset;
7913 this.offset = 0;
7914 return this;
7915 };
7916 /**
7917 * Marks an offset on this ByteBuffer to be used later.
7918 * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
7919 * @returns {!ByteBuffer} this
7920 * @throws {TypeError} If `offset` is not a valid number
7921 * @throws {RangeError} If `offset` is out of bounds
7922 * @see ByteBuffer#reset
7923 * @expose
7924 */
7925 ByteBufferPrototype.mark = function(offset) {
7926 offset = typeof offset === 'undefined' ? this.offset : offset;
7927 if (!this.noAssert) {
7928 if (typeof offset !== 'number' || offset % 1 !== 0)
7929 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7930 offset >>>= 0;
7931 if (offset < 0 || offset + 0 > this.buffer.byteLength)
7932 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
7933 }
7934 this.markedOffset = offset;
7935 return this;
7936 };
7937 /**
7938 * Sets the byte order.
7939 * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
7940 * @returns {!ByteBuffer} this
7941 * @expose
7942 */
7943 ByteBufferPrototype.order = function(littleEndian) {
7944 if (!this.noAssert) {
7945 if (typeof littleEndian !== 'boolean')
7946 throw TypeError("Illegal littleEndian: Not a boolean");
7947 }
7948 this.littleEndian = !!littleEndian;
7949 return this;
7950 };
7951
7952 /**
7953 * Switches (to) little endian byte order.
7954 * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
7955 * @returns {!ByteBuffer} this
7956 * @expose
7957 */
7958 ByteBufferPrototype.LE = function(littleEndian) {
7959 this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
7960 return this;
7961 };
7962
7963 /**
7964 * Switches (to) big endian byte order.
7965 * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
7966 * @returns {!ByteBuffer} this
7967 * @expose
7968 */
7969 ByteBufferPrototype.BE = function(bigEndian) {
7970 this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
7971 return this;
7972 };
7973 /**
7974 * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
7975 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
7976 * will be resized and its contents moved accordingly.
7977 * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
7978 * modified according to the performed read operation.
7979 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
7980 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
7981 * prepended if omitted.
7982 * @returns {!ByteBuffer} this
7983 * @expose
7984 * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
7985 * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
7986 */
7987 ByteBufferPrototype.prepend = function(source, encoding, offset) {
7988 if (typeof encoding === 'number' || typeof encoding !== 'string') {
7989 offset = encoding;
7990 encoding = undefined;
7991 }
7992 var relative = typeof offset === 'undefined';
7993 if (relative) offset = this.offset;
7994 if (!this.noAssert) {
7995 if (typeof offset !== 'number' || offset % 1 !== 0)
7996 throw TypeError("Illegal offset: "+offset+" (not an integer)");
7997 offset >>>= 0;
7998 if (offset < 0 || offset + 0 > this.buffer.byteLength)
7999 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
8000 }
8001 if (!(source instanceof ByteBuffer))
8002 source = ByteBuffer.wrap(source, encoding);
8003 var len = source.limit - source.offset;
8004 if (len <= 0) return this; // Nothing to prepend
8005 var diff = len - offset;
8006 if (diff > 0) { // Not enough space before offset, so resize + move
8007 var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
8008 var view = new Uint8Array(buffer);
8009 view.set(this.view.subarray(offset, this.buffer.byteLength), len);
8010 this.buffer = buffer;
8011 this.view = view;
8012 this.offset += diff;
8013 if (this.markedOffset >= 0) this.markedOffset += diff;
8014 this.limit += diff;
8015 offset += diff;
8016 } else {
8017 var arrayView = new Uint8Array(this.buffer);
8018 }
8019 this.view.set(source.view.subarray(source.offset, source.limit), offset - len);
8020
8021 source.offset = source.limit;
8022 if (relative)
8023 this.offset -= len;
8024 return this;
8025 };
8026
8027 /**
8028 * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
8029 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
8030 * will be resized and its contents moved accordingly.
8031 * @param {!ByteBuffer} target Target ByteBuffer
8032 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
8033 * prepended if omitted.
8034 * @returns {!ByteBuffer} this
8035 * @expose
8036 * @see ByteBuffer#prepend
8037 */
8038 ByteBufferPrototype.prependTo = function(target, offset) {
8039 target.prepend(this, offset);
8040 return this;
8041 };
8042 /**
8043 * Prints debug information about this ByteBuffer's contents.
8044 * @param {function(string)=} out Output function to call, defaults to console.log
8045 * @expose
8046 */
8047 ByteBufferPrototype.printDebug = function(out) {
8048 if (typeof out !== 'function') out = console.log.bind(console);
8049 out(
8050 this.toString()+"\n"+
8051 "-------------------------------------------------------------------\n"+
8052 this.toDebug(/* columns */ true)
8053 );
8054 };
8055
8056 /**
8057 * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
8058 * {@link ByteBuffer#limit}, so this returns `limit - offset`.
8059 * @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
8060 * @expose
8061 */
8062 ByteBufferPrototype.remaining = function() {
8063 return this.limit - this.offset;
8064 };
8065 /**
8066 * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
8067 * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
8068 * marked, sets `offset = 0`.
8069 * @returns {!ByteBuffer} this
8070 * @see ByteBuffer#mark
8071 * @expose
8072 */
8073 ByteBufferPrototype.reset = function() {
8074 if (this.markedOffset >= 0) {
8075 this.offset = this.markedOffset;
8076 this.markedOffset = -1;
8077 } else {
8078 this.offset = 0;
8079 }
8080 return this;
8081 };
8082 /**
8083 * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
8084 * large or larger.
8085 * @param {number} capacity Capacity required
8086 * @returns {!ByteBuffer} this
8087 * @throws {TypeError} If `capacity` is not a number
8088 * @throws {RangeError} If `capacity < 0`
8089 * @expose
8090 */
8091 ByteBufferPrototype.resize = function(capacity) {
8092 if (!this.noAssert) {
8093 if (typeof capacity !== 'number' || capacity % 1 !== 0)
8094 throw TypeError("Illegal capacity: "+capacity+" (not an integer)");
8095 capacity |= 0;
8096 if (capacity < 0)
8097 throw RangeError("Illegal capacity: 0 <= "+capacity);
8098 }
8099 if (this.buffer.byteLength < capacity) {
8100 var buffer = new ArrayBuffer(capacity);
8101 var view = new Uint8Array(buffer);
8102 view.set(this.view);
8103 this.buffer = buffer;
8104 this.view = view;
8105 }
8106 return this;
8107 };
8108 /**
8109 * Reverses this ByteBuffer's contents.
8110 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
8111 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
8112 * @returns {!ByteBuffer} this
8113 * @expose
8114 */
8115 ByteBufferPrototype.reverse = function(begin, end) {
8116 if (typeof begin === 'undefined') begin = this.offset;
8117 if (typeof end === 'undefined') end = this.limit;
8118 if (!this.noAssert) {
8119 if (typeof begin !== 'number' || begin % 1 !== 0)
8120 throw TypeError("Illegal begin: Not an integer");
8121 begin >>>= 0;
8122 if (typeof end !== 'number' || end % 1 !== 0)
8123 throw TypeError("Illegal end: Not an integer");
8124 end >>>= 0;
8125 if (begin < 0 || begin > end || end > this.buffer.byteLength)
8126 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
8127 }
8128 if (begin === end)
8129 return this; // Nothing to reverse
8130 Array.prototype.reverse.call(this.view.subarray(begin, end));
8131 return this;
8132 };
8133 /**
8134 * Skips the next `length` bytes. This will just advance
8135 * @param {number} length Number of bytes to skip. May also be negative to move the offset back.
8136 * @returns {!ByteBuffer} this
8137 * @expose
8138 */
8139 ByteBufferPrototype.skip = function(length) {
8140 if (!this.noAssert) {
8141 if (typeof length !== 'number' || length % 1 !== 0)
8142 throw TypeError("Illegal length: "+length+" (not an integer)");
8143 length |= 0;
8144 }
8145 var offset = this.offset + length;
8146 if (!this.noAssert) {
8147 if (offset < 0 || offset > this.buffer.byteLength)
8148 throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength);
8149 }
8150 this.offset = offset;
8151 return this;
8152 };
8153
8154 /**
8155 * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
8156 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
8157 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
8158 * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
8159 * @expose
8160 */
8161 ByteBufferPrototype.slice = function(begin, end) {
8162 if (typeof begin === 'undefined') begin = this.offset;
8163 if (typeof end === 'undefined') end = this.limit;
8164 if (!this.noAssert) {
8165 if (typeof begin !== 'number' || begin % 1 !== 0)
8166 throw TypeError("Illegal begin: Not an integer");
8167 begin >>>= 0;
8168 if (typeof end !== 'number' || end % 1 !== 0)
8169 throw TypeError("Illegal end: Not an integer");
8170 end >>>= 0;
8171 if (begin < 0 || begin > end || end > this.buffer.byteLength)
8172 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
8173 }
8174 var bb = this.clone();
8175 bb.offset = begin;
8176 bb.limit = end;
8177 return bb;
8178 };
8179 /**
8180 * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
8181 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
8182 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
8183 * possible. Defaults to `false`
8184 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
8185 * @expose
8186 */
8187 ByteBufferPrototype.toBuffer = function(forceCopy) {
8188 var offset = this.offset,
8189 limit = this.limit;
8190 if (!this.noAssert) {
8191 if (typeof offset !== 'number' || offset % 1 !== 0)
8192 throw TypeError("Illegal offset: Not an integer");
8193 offset >>>= 0;
8194 if (typeof limit !== 'number' || limit % 1 !== 0)
8195 throw TypeError("Illegal limit: Not an integer");
8196 limit >>>= 0;
8197 if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
8198 throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength);
8199 }
8200 // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
8201 // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
8202 if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
8203 return this.buffer;
8204 if (offset === limit)
8205 return EMPTY_BUFFER;
8206 var buffer = new ArrayBuffer(limit - offset);
8207 new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
8208 return buffer;
8209 };
8210
8211 /**
8212 * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
8213 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
8214 * @function
8215 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
8216 * Defaults to `false`
8217 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
8218 * @expose
8219 */
8220 ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
8221
8222 /**
8223 * Converts the ByteBuffer's contents to a string.
8224 * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
8225 * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
8226 * highlighted offsets.
8227 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
8228 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
8229 * @returns {string} String representation
8230 * @throws {Error} If `encoding` is invalid
8231 * @expose
8232 */
8233 ByteBufferPrototype.toString = function(encoding, begin, end) {
8234 if (typeof encoding === 'undefined')
8235 return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";
8236 if (typeof encoding === 'number')
8237 encoding = "utf8",
8238 begin = encoding,
8239 end = begin;
8240 switch (encoding) {
8241 case "utf8":
8242 return this.toUTF8(begin, end);
8243 case "base64":
8244 return this.toBase64(begin, end);
8245 case "hex":
8246 return this.toHex(begin, end);
8247 case "binary":
8248 return this.toBinary(begin, end);
8249 case "debug":
8250 return this.toDebug();
8251 case "columns":
8252 return this.toColumns();
8253 default:
8254 throw Error("Unsupported encoding: "+encoding);
8255 }
8256 };
8257
8258 // lxiv-embeddable
8259
8260 /**
8261 * lxiv-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
8262 * Released under the Apache License, Version 2.0
8263 * see: https://github.com/dcodeIO/lxiv for details
8264 */
8265 var lxiv = function() {
8266 "use strict";
8267
8268 /**
8269 * lxiv namespace.
8270 * @type {!Object.<string,*>}
8271 * @exports lxiv
8272 */
8273 var lxiv = {};
8274
8275 /**
8276 * Character codes for output.
8277 * @type {!Array.<number>}
8278 * @inner
8279 */
8280 var aout = [
8281 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
8282 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
8283 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
8284 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
8285 ];
8286
8287 /**
8288 * Character codes for input.
8289 * @type {!Array.<number>}
8290 * @inner
8291 */
8292 var ain = [];
8293 for (var i=0, k=aout.length; i<k; ++i)
8294 ain[aout[i]] = i;
8295
8296 /**
8297 * Encodes bytes to base64 char codes.
8298 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if
8299 * there are no more bytes left.
8300 * @param {!function(number)} dst Characters destination as a function successively called with each encoded char
8301 * code.
8302 */
8303 lxiv.encode = function(src, dst) {
8304 var b, t;
8305 while ((b = src()) !== null) {
8306 dst(aout[(b>>2)&0x3f]);
8307 t = (b&0x3)<<4;
8308 if ((b = src()) !== null) {
8309 t |= (b>>4)&0xf;
8310 dst(aout[(t|((b>>4)&0xf))&0x3f]);
8311 t = (b&0xf)<<2;
8312 if ((b = src()) !== null)
8313 dst(aout[(t|((b>>6)&0x3))&0x3f]),
8314 dst(aout[b&0x3f]);
8315 else
8316 dst(aout[t&0x3f]),
8317 dst(61);
8318 } else
8319 dst(aout[t&0x3f]),
8320 dst(61),
8321 dst(61);
8322 }
8323 };
8324
8325 /**
8326 * Decodes base64 char codes to bytes.
8327 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
8328 * `null` if there are no more characters left.
8329 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
8330 * @throws {Error} If a character code is invalid
8331 */
8332 lxiv.decode = function(src, dst) {
8333 var c, t1, t2;
8334 function fail(c) {
8335 throw Error("Illegal character code: "+c);
8336 }
8337 while ((c = src()) !== null) {
8338 t1 = ain[c];
8339 if (typeof t1 === 'undefined') fail(c);
8340 if ((c = src()) !== null) {
8341 t2 = ain[c];
8342 if (typeof t2 === 'undefined') fail(c);
8343 dst((t1<<2)>>>0|(t2&0x30)>>4);
8344 if ((c = src()) !== null) {
8345 t1 = ain[c];
8346 if (typeof t1 === 'undefined')
8347 if (c === 61) break; else fail(c);
8348 dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2);
8349 if ((c = src()) !== null) {
8350 t2 = ain[c];
8351 if (typeof t2 === 'undefined')
8352 if (c === 61) break; else fail(c);
8353 dst(((t1&0x3)<<6)>>>0|t2);
8354 }
8355 }
8356 }
8357 }
8358 };
8359
8360 /**
8361 * Tests if a string is valid base64.
8362 * @param {string} str String to test
8363 * @returns {boolean} `true` if valid, otherwise `false`
8364 */
8365 lxiv.test = function(str) {
8366 return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
8367 };
8368
8369 return lxiv;
8370 }();
8371
8372 // encodings/base64
8373
8374 /**
8375 * Encodes this ByteBuffer's contents to a base64 encoded string.
8376 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
8377 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
8378 * @returns {string} Base64 encoded string
8379 * @throws {RangeError} If `begin` or `end` is out of bounds
8380 * @expose
8381 */
8382 ByteBufferPrototype.toBase64 = function(begin, end) {
8383 if (typeof begin === 'undefined')
8384 begin = this.offset;
8385 if (typeof end === 'undefined')
8386 end = this.limit;
8387 begin = begin | 0; end = end | 0;
8388 if (begin < 0 || end > this.capacity || begin > end)
8389 throw RangeError("begin, end");
8390 var sd; lxiv.encode(function() {
8391 return begin < end ? this.view[begin++] : null;
8392 }.bind(this), sd = stringDestination());
8393 return sd();
8394 };
8395
8396 /**
8397 * Decodes a base64 encoded string to a ByteBuffer.
8398 * @param {string} str String to decode
8399 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
8400 * {@link ByteBuffer.DEFAULT_ENDIAN}.
8401 * @returns {!ByteBuffer} ByteBuffer
8402 * @expose
8403 */
8404 ByteBuffer.fromBase64 = function(str, littleEndian) {
8405 if (typeof str !== 'string')
8406 throw TypeError("str");
8407 var bb = new ByteBuffer(str.length/4*3, littleEndian),
8408 i = 0;
8409 lxiv.decode(stringSource(str), function(b) {
8410 bb.view[i++] = b;
8411 });
8412 bb.limit = i;
8413 return bb;
8414 };
8415
8416 /**
8417 * Encodes a binary string to base64 like `window.btoa` does.
8418 * @param {string} str Binary string
8419 * @returns {string} Base64 encoded string
8420 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
8421 * @expose
8422 */
8423 ByteBuffer.btoa = function(str) {
8424 return ByteBuffer.fromBinary(str).toBase64();
8425 };
8426
8427 /**
8428 * Decodes a base64 encoded string to binary like `window.atob` does.
8429 * @param {string} b64 Base64 encoded string
8430 * @returns {string} Binary string
8431 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
8432 * @expose
8433 */
8434 ByteBuffer.atob = function(b64) {
8435 return ByteBuffer.fromBase64(b64).toBinary();
8436 };
8437
8438 // encodings/binary
8439
8440 /**
8441 * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
8442 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
8443 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
8444 * @returns {string} Binary encoded string
8445 * @throws {RangeError} If `offset > limit`
8446 * @expose
8447 */
8448 ByteBufferPrototype.toBinary = function(begin, end) {
8449 if (typeof begin === 'undefined')
8450 begin = this.offset;
8451 if (typeof end === 'undefined')
8452 end = this.limit;
8453 begin |= 0; end |= 0;
8454 if (begin < 0 || end > this.capacity() || begin > end)
8455 throw RangeError("begin, end");
8456 if (begin === end)
8457 return "";
8458 var chars = [],
8459 parts = [];
8460 while (begin < end) {
8461 chars.push(this.view[begin++]);
8462 if (chars.length >= 1024)
8463 parts.push(String.fromCharCode.apply(String, chars)),
8464 chars = [];
8465 }
8466 return parts.join('') + String.fromCharCode.apply(String, chars);
8467 };
8468
8469 /**
8470 * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
8471 * @param {string} str String to decode
8472 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
8473 * {@link ByteBuffer.DEFAULT_ENDIAN}.
8474 * @returns {!ByteBuffer} ByteBuffer
8475 * @expose
8476 */
8477 ByteBuffer.fromBinary = function(str, littleEndian) {
8478 if (typeof str !== 'string')
8479 throw TypeError("str");
8480 var i = 0,
8481 k = str.length,
8482 charCode,
8483 bb = new ByteBuffer(k, littleEndian);
8484 while (i<k) {
8485 charCode = str.charCodeAt(i);
8486 if (charCode > 0xff)
8487 throw RangeError("illegal char code: "+charCode);
8488 bb.view[i++] = charCode;
8489 }
8490 bb.limit = k;
8491 return bb;
8492 };
8493
8494 // encodings/debug
8495
8496 /**
8497 * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
8498 * * `<` : offset,
8499 * * `'` : markedOffset,
8500 * * `>` : limit,
8501 * * `|` : offset and limit,
8502 * * `[` : offset and markedOffset,
8503 * * `]` : markedOffset and limit,
8504 * * `!` : offset, markedOffset and limit
8505 * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
8506 * @returns {string|!Array.<string>} Debug string or array of lines if `asArray = true`
8507 * @expose
8508 * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
8509 * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
8510 * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
8511 * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
8512 */
8513 ByteBufferPrototype.toDebug = function(columns) {
8514 var i = -1,
8515 k = this.buffer.byteLength,
8516 b,
8517 hex = "",
8518 asc = "",
8519 out = "";
8520 while (i<k) {
8521 if (i !== -1) {
8522 b = this.view[i];
8523 if (b < 0x10) hex += "0"+b.toString(16).toUpperCase();
8524 else hex += b.toString(16).toUpperCase();
8525 if (columns)
8526 asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
8527 }
8528 ++i;
8529 if (columns) {
8530 if (i > 0 && i % 16 === 0 && i !== k) {
8531 while (hex.length < 3*16+3) hex += " ";
8532 out += hex+asc+"\n";
8533 hex = asc = "";
8534 }
8535 }
8536 if (i === this.offset && i === this.limit)
8537 hex += i === this.markedOffset ? "!" : "|";
8538 else if (i === this.offset)
8539 hex += i === this.markedOffset ? "[" : "<";
8540 else if (i === this.limit)
8541 hex += i === this.markedOffset ? "]" : ">";
8542 else
8543 hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
8544 }
8545 if (columns && hex !== " ") {
8546 while (hex.length < 3*16+3)
8547 hex += " ";
8548 out += hex + asc + "\n";
8549 }
8550 return columns ? out : hex;
8551 };
8552
8553 /**
8554 * Decodes a hex encoded string with marked offsets to a ByteBuffer.
8555 * @param {string} str Debug string to decode (not be generated with `columns = true`)
8556 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
8557 * {@link ByteBuffer.DEFAULT_ENDIAN}.
8558 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
8559 * {@link ByteBuffer.DEFAULT_NOASSERT}.
8560 * @returns {!ByteBuffer} ByteBuffer
8561 * @expose
8562 * @see ByteBuffer#toDebug
8563 */
8564 ByteBuffer.fromDebug = function(str, littleEndian, noAssert) {
8565 var k = str.length,
8566 bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert);
8567 var i = 0, j = 0, ch, b,
8568 rs = false, // Require symbol next
8569 ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
8570 fail = false;
8571 while (i<k) {
8572 switch (ch = str.charAt(i++)) {
8573 case '!':
8574 if (!noAssert) {
8575 if (ho || hm || hl) {
8576 fail = true;
8577 break;
8578 }
8579 ho = hm = hl = true;
8580 }
8581 bb.offset = bb.markedOffset = bb.limit = j;
8582 rs = false;
8583 break;
8584 case '|':
8585 if (!noAssert) {
8586 if (ho || hl) {
8587 fail = true;
8588 break;
8589 }
8590 ho = hl = true;
8591 }
8592 bb.offset = bb.limit = j;
8593 rs = false;
8594 break;
8595 case '[':
8596 if (!noAssert) {
8597 if (ho || hm) {
8598 fail = true;
8599 break;
8600 }
8601 ho = hm = true;
8602 }
8603 bb.offset = bb.markedOffset = j;
8604 rs = false;
8605 break;
8606 case '<':
8607 if (!noAssert) {
8608 if (ho) {
8609 fail = true;
8610 break;
8611 }
8612 ho = true;
8613 }
8614 bb.offset = j;
8615 rs = false;
8616 break;
8617 case ']':
8618 if (!noAssert) {
8619 if (hl || hm) {
8620 fail = true;
8621 break;
8622 }
8623 hl = hm = true;
8624 }
8625 bb.limit = bb.markedOffset = j;
8626 rs = false;
8627 break;
8628 case '>':
8629 if (!noAssert) {
8630 if (hl) {
8631 fail = true;
8632 break;
8633 }
8634 hl = true;
8635 }
8636 bb.limit = j;
8637 rs = false;
8638 break;
8639 case "'":
8640 if (!noAssert) {
8641 if (hm) {
8642 fail = true;
8643 break;
8644 }
8645 hm = true;
8646 }
8647 bb.markedOffset = j;
8648 rs = false;
8649 break;
8650 case ' ':
8651 rs = false;
8652 break;
8653 default:
8654 if (!noAssert) {
8655 if (rs) {
8656 fail = true;
8657 break;
8658 }
8659 }
8660 b = parseInt(ch+str.charAt(i++), 16);
8661 if (!noAssert) {
8662 if (isNaN(b) || b < 0 || b > 255)
8663 throw TypeError("Illegal str: Not a debug encoded string");
8664 }
8665 bb.view[j++] = b;
8666 rs = true;
8667 }
8668 if (fail)
8669 throw TypeError("Illegal str: Invalid symbol at "+i);
8670 }
8671 if (!noAssert) {
8672 if (!ho || !hl)
8673 throw TypeError("Illegal str: Missing offset or limit");
8674 if (j<bb.buffer.byteLength)
8675 throw TypeError("Illegal str: Not a debug encoded string (is it hex?) "+j+" < "+k);
8676 }
8677 return bb;
8678 };
8679
8680 // encodings/hex
8681
8682 /**
8683 * Encodes this ByteBuffer's contents to a hex encoded string.
8684 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
8685 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
8686 * @returns {string} Hex encoded string
8687 * @expose
8688 */
8689 ByteBufferPrototype.toHex = function(begin, end) {
8690 begin = typeof begin === 'undefined' ? this.offset : begin;
8691 end = typeof end === 'undefined' ? this.limit : end;
8692 if (!this.noAssert) {
8693 if (typeof begin !== 'number' || begin % 1 !== 0)
8694 throw TypeError("Illegal begin: Not an integer");
8695 begin >>>= 0;
8696 if (typeof end !== 'number' || end % 1 !== 0)
8697 throw TypeError("Illegal end: Not an integer");
8698 end >>>= 0;
8699 if (begin < 0 || begin > end || end > this.buffer.byteLength)
8700 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
8701 }
8702 var out = new Array(end - begin),
8703 b;
8704 while (begin < end) {
8705 b = this.view[begin++];
8706 if (b < 0x10)
8707 out.push("0", b.toString(16));
8708 else out.push(b.toString(16));
8709 }
8710 return out.join('');
8711 };
8712
8713 /**
8714 * Decodes a hex encoded string to a ByteBuffer.
8715 * @param {string} str String to decode
8716 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
8717 * {@link ByteBuffer.DEFAULT_ENDIAN}.
8718 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
8719 * {@link ByteBuffer.DEFAULT_NOASSERT}.
8720 * @returns {!ByteBuffer} ByteBuffer
8721 * @expose
8722 */
8723 ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
8724 if (!noAssert) {
8725 if (typeof str !== 'string')
8726 throw TypeError("Illegal str: Not a string");
8727 if (str.length % 2 !== 0)
8728 throw TypeError("Illegal str: Length not a multiple of 2");
8729 }
8730 var k = str.length,
8731 bb = new ByteBuffer((k / 2) | 0, littleEndian),
8732 b;
8733 for (var i=0, j=0; i<k; i+=2) {
8734 b = parseInt(str.substring(i, i+2), 16);
8735 if (!noAssert)
8736 if (!isFinite(b) || b < 0 || b > 255)
8737 throw TypeError("Illegal str: Contains non-hex characters");
8738 bb.view[j++] = b;
8739 }
8740 bb.limit = j;
8741 return bb;
8742 };
8743
8744 // utfx-embeddable
8745
8746 /**
8747 * utfx-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
8748 * Released under the Apache License, Version 2.0
8749 * see: https://github.com/dcodeIO/utfx for details
8750 */
8751 var utfx = function() {
8752 "use strict";
8753
8754 /**
8755 * utfx namespace.
8756 * @inner
8757 * @type {!Object.<string,*>}
8758 */
8759 var utfx = {};
8760
8761 /**
8762 * Maximum valid code point.
8763 * @type {number}
8764 * @const
8765 */
8766 utfx.MAX_CODEPOINT = 0x10FFFF;
8767
8768 /**
8769 * Encodes UTF8 code points to UTF8 bytes.
8770 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
8771 * respectively `null` if there are no more code points left or a single numeric code point.
8772 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte
8773 */
8774 utfx.encodeUTF8 = function(src, dst) {
8775 var cp = null;
8776 if (typeof src === 'number')
8777 cp = src,
8778 src = function() { return null; };
8779 while (cp !== null || (cp = src()) !== null) {
8780 if (cp < 0x80)
8781 dst(cp&0x7F);
8782 else if (cp < 0x800)
8783 dst(((cp>>6)&0x1F)|0xC0),
8784 dst((cp&0x3F)|0x80);
8785 else if (cp < 0x10000)
8786 dst(((cp>>12)&0x0F)|0xE0),
8787 dst(((cp>>6)&0x3F)|0x80),
8788 dst((cp&0x3F)|0x80);
8789 else
8790 dst(((cp>>18)&0x07)|0xF0),
8791 dst(((cp>>12)&0x3F)|0x80),
8792 dst(((cp>>6)&0x3F)|0x80),
8793 dst((cp&0x3F)|0x80);
8794 cp = null;
8795 }
8796 };
8797
8798 /**
8799 * Decodes UTF8 bytes to UTF8 code points.
8800 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
8801 * are no more bytes left.
8802 * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
8803 * @throws {RangeError} If a starting byte is invalid in UTF8
8804 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
8805 * remaining bytes.
8806 */
8807 utfx.decodeUTF8 = function(src, dst) {
8808 var a, b, c, d, fail = function(b) {
8809 b = b.slice(0, b.indexOf(null));
8810 var err = Error(b.toString());
8811 err.name = "TruncatedError";
8812 err['bytes'] = b;
8813 throw err;
8814 };
8815 while ((a = src()) !== null) {
8816 if ((a&0x80) === 0)
8817 dst(a);
8818 else if ((a&0xE0) === 0xC0)
8819 ((b = src()) === null) && fail([a, b]),
8820 dst(((a&0x1F)<<6) | (b&0x3F));
8821 else if ((a&0xF0) === 0xE0)
8822 ((b=src()) === null || (c=src()) === null) && fail([a, b, c]),
8823 dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F));
8824 else if ((a&0xF8) === 0xF0)
8825 ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]),
8826 dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F));
8827 else throw RangeError("Illegal starting byte: "+a);
8828 }
8829 };
8830
8831 /**
8832 * Converts UTF16 characters to UTF8 code points.
8833 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
8834 * `null` if there are no more characters left.
8835 * @param {!function(number)} dst Code points destination as a function successively called with each converted code
8836 * point.
8837 */
8838 utfx.UTF16toUTF8 = function(src, dst) {
8839 var c1, c2 = null;
8840 while (true) {
8841 if ((c1 = c2 !== null ? c2 : src()) === null)
8842 break;
8843 if (c1 >= 0xD800 && c1 <= 0xDFFF) {
8844 if ((c2 = src()) !== null) {
8845 if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
8846 dst((c1-0xD800)*0x400+c2-0xDC00+0x10000);
8847 c2 = null; continue;
8848 }
8849 }
8850 }
8851 dst(c1);
8852 }
8853 if (c2 !== null) dst(c2);
8854 };
8855
8856 /**
8857 * Converts UTF8 code points to UTF16 characters.
8858 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
8859 * respectively `null` if there are no more code points left or a single numeric code point.
8860 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
8861 * @throws {RangeError} If a code point is out of range
8862 */
8863 utfx.UTF8toUTF16 = function(src, dst) {
8864 var cp = null;
8865 if (typeof src === 'number')
8866 cp = src, src = function() { return null; };
8867 while (cp !== null || (cp = src()) !== null) {
8868 if (cp <= 0xFFFF)
8869 dst(cp);
8870 else
8871 cp -= 0x10000,
8872 dst((cp>>10)+0xD800),
8873 dst((cp%0x400)+0xDC00);
8874 cp = null;
8875 }
8876 };
8877
8878 /**
8879 * Converts and encodes UTF16 characters to UTF8 bytes.
8880 * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
8881 * if there are no more characters left.
8882 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
8883 */
8884 utfx.encodeUTF16toUTF8 = function(src, dst) {
8885 utfx.UTF16toUTF8(src, function(cp) {
8886 utfx.encodeUTF8(cp, dst);
8887 });
8888 };
8889
8890 /**
8891 * Decodes and converts UTF8 bytes to UTF16 characters.
8892 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
8893 * are no more bytes left.
8894 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
8895 * @throws {RangeError} If a starting byte is invalid in UTF8
8896 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
8897 */
8898 utfx.decodeUTF8toUTF16 = function(src, dst) {
8899 utfx.decodeUTF8(src, function(cp) {
8900 utfx.UTF8toUTF16(cp, dst);
8901 });
8902 };
8903
8904 /**
8905 * Calculates the byte length of an UTF8 code point.
8906 * @param {number} cp UTF8 code point
8907 * @returns {number} Byte length
8908 */
8909 utfx.calculateCodePoint = function(cp) {
8910 return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
8911 };
8912
8913 /**
8914 * Calculates the number of UTF8 bytes required to store UTF8 code points.
8915 * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
8916 * `null` if there are no more code points left.
8917 * @returns {number} The number of UTF8 bytes required
8918 */
8919 utfx.calculateUTF8 = function(src) {
8920 var cp, l=0;
8921 while ((cp = src()) !== null)
8922 l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
8923 return l;
8924 };
8925
8926 /**
8927 * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
8928 * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
8929 * `null` if there are no more characters left.
8930 * @returns {!Array.<number>} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
8931 */
8932 utfx.calculateUTF16asUTF8 = function(src) {
8933 var n=0, l=0;
8934 utfx.UTF16toUTF8(src, function(cp) {
8935 ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
8936 });
8937 return [n,l];
8938 };
8939
8940 return utfx;
8941 }();
8942
8943 // encodings/utf8
8944
8945 /**
8946 * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
8947 * string.
8948 * @returns {string} Hex encoded string
8949 * @throws {RangeError} If `offset > limit`
8950 * @expose
8951 */
8952 ByteBufferPrototype.toUTF8 = function(begin, end) {
8953 if (typeof begin === 'undefined') begin = this.offset;
8954 if (typeof end === 'undefined') end = this.limit;
8955 if (!this.noAssert) {
8956 if (typeof begin !== 'number' || begin % 1 !== 0)
8957 throw TypeError("Illegal begin: Not an integer");
8958 begin >>>= 0;
8959 if (typeof end !== 'number' || end % 1 !== 0)
8960 throw TypeError("Illegal end: Not an integer");
8961 end >>>= 0;
8962 if (begin < 0 || begin > end || end > this.buffer.byteLength)
8963 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
8964 }
8965 var sd; try {
8966 utfx.decodeUTF8toUTF16(function() {
8967 return begin < end ? this.view[begin++] : null;
8968 }.bind(this), sd = stringDestination());
8969 } catch (e) {
8970 if (begin !== end)
8971 throw RangeError("Illegal range: Truncated data, "+begin+" != "+end);
8972 }
8973 return sd();
8974 };
8975
8976 /**
8977 * Decodes an UTF8 encoded string to a ByteBuffer.
8978 * @param {string} str String to decode
8979 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
8980 * {@link ByteBuffer.DEFAULT_ENDIAN}.
8981 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
8982 * {@link ByteBuffer.DEFAULT_NOASSERT}.
8983 * @returns {!ByteBuffer} ByteBuffer
8984 * @expose
8985 */
8986 ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) {
8987 if (!noAssert)
8988 if (typeof str !== 'string')
8989 throw TypeError("Illegal str: Not a string");
8990 var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
8991 i = 0;
8992 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
8993 bb.view[i++] = b;
8994 });
8995 bb.limit = i;
8996 return bb;
8997 };
8998
8999 return ByteBuffer;
9000});
9001
9002},{"long":48}],29:[function(require,module,exports){
9003var Buffer = require('safe-buffer').Buffer
9004var Transform = require('stream').Transform
9005var StringDecoder = require('string_decoder').StringDecoder
9006var inherits = require('inherits')
9007
9008function CipherBase (hashMode) {
9009 Transform.call(this)
9010 this.hashMode = typeof hashMode === 'string'
9011 if (this.hashMode) {
9012 this[hashMode] = this._finalOrDigest
9013 } else {
9014 this.final = this._finalOrDigest
9015 }
9016 if (this._final) {
9017 this.__final = this._final
9018 this._final = null
9019 }
9020 this._decoder = null
9021 this._encoding = null
9022}
9023inherits(CipherBase, Transform)
9024
9025CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
9026 if (typeof data === 'string') {
9027 data = Buffer.from(data, inputEnc)
9028 }
9029
9030 var outData = this._update(data)
9031 if (this.hashMode) return this
9032
9033 if (outputEnc) {
9034 outData = this._toString(outData, outputEnc)
9035 }
9036
9037 return outData
9038}
9039
9040CipherBase.prototype.setAutoPadding = function () {}
9041CipherBase.prototype.getAuthTag = function () {
9042 throw new Error('trying to get auth tag in unsupported state')
9043}
9044
9045CipherBase.prototype.setAuthTag = function () {
9046 throw new Error('trying to set auth tag in unsupported state')
9047}
9048
9049CipherBase.prototype.setAAD = function () {
9050 throw new Error('trying to set aad in unsupported state')
9051}
9052
9053CipherBase.prototype._transform = function (data, _, next) {
9054 var err
9055 try {
9056 if (this.hashMode) {
9057 this._update(data)
9058 } else {
9059 this.push(this._update(data))
9060 }
9061 } catch (e) {
9062 err = e
9063 } finally {
9064 next(err)
9065 }
9066}
9067CipherBase.prototype._flush = function (done) {
9068 var err
9069 try {
9070 this.push(this.__final())
9071 } catch (e) {
9072 err = e
9073 }
9074
9075 done(err)
9076}
9077CipherBase.prototype._finalOrDigest = function (outputEnc) {
9078 var outData = this.__final() || Buffer.alloc(0)
9079 if (outputEnc) {
9080 outData = this._toString(outData, outputEnc, true)
9081 }
9082 return outData
9083}
9084
9085CipherBase.prototype._toString = function (value, enc, fin) {
9086 if (!this._decoder) {
9087 this._decoder = new StringDecoder(enc)
9088 this._encoding = enc
9089 }
9090
9091 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
9092
9093 var out = this._decoder.write(value)
9094 if (fin) {
9095 out += this._decoder.end()
9096 }
9097
9098 return out
9099}
9100
9101module.exports = CipherBase
9102
9103},{"inherits":45,"safe-buffer":68,"stream":77,"string_decoder":78}],30:[function(require,module,exports){
9104(function (Buffer){
9105// Copyright Joyent, Inc. and other Node contributors.
9106//
9107// Permission is hereby granted, free of charge, to any person obtaining a
9108// copy of this software and associated documentation files (the
9109// "Software"), to deal in the Software without restriction, including
9110// without limitation the rights to use, copy, modify, merge, publish,
9111// distribute, sublicense, and/or sell copies of the Software, and to permit
9112// persons to whom the Software is furnished to do so, subject to the
9113// following conditions:
9114//
9115// The above copyright notice and this permission notice shall be included
9116// in all copies or substantial portions of the Software.
9117//
9118// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
9119// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
9120// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
9121// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
9122// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
9123// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
9124// USE OR OTHER DEALINGS IN THE SOFTWARE.
9125
9126// NOTE: These type checking functions intentionally don't use `instanceof`
9127// because it is fragile and can be easily faked with `Object.create()`.
9128
9129function isArray(arg) {
9130 if (Array.isArray) {
9131 return Array.isArray(arg);
9132 }
9133 return objectToString(arg) === '[object Array]';
9134}
9135exports.isArray = isArray;
9136
9137function isBoolean(arg) {
9138 return typeof arg === 'boolean';
9139}
9140exports.isBoolean = isBoolean;
9141
9142function isNull(arg) {
9143 return arg === null;
9144}
9145exports.isNull = isNull;
9146
9147function isNullOrUndefined(arg) {
9148 return arg == null;
9149}
9150exports.isNullOrUndefined = isNullOrUndefined;
9151
9152function isNumber(arg) {
9153 return typeof arg === 'number';
9154}
9155exports.isNumber = isNumber;
9156
9157function isString(arg) {
9158 return typeof arg === 'string';
9159}
9160exports.isString = isString;
9161
9162function isSymbol(arg) {
9163 return typeof arg === 'symbol';
9164}
9165exports.isSymbol = isSymbol;
9166
9167function isUndefined(arg) {
9168 return arg === void 0;
9169}
9170exports.isUndefined = isUndefined;
9171
9172function isRegExp(re) {
9173 return objectToString(re) === '[object RegExp]';
9174}
9175exports.isRegExp = isRegExp;
9176
9177function isObject(arg) {
9178 return typeof arg === 'object' && arg !== null;
9179}
9180exports.isObject = isObject;
9181
9182function isDate(d) {
9183 return objectToString(d) === '[object Date]';
9184}
9185exports.isDate = isDate;
9186
9187function isError(e) {
9188 return (objectToString(e) === '[object Error]' || e instanceof Error);
9189}
9190exports.isError = isError;
9191
9192function isFunction(arg) {
9193 return typeof arg === 'function';
9194}
9195exports.isFunction = isFunction;
9196
9197function isPrimitive(arg) {
9198 return arg === null ||
9199 typeof arg === 'boolean' ||
9200 typeof arg === 'number' ||
9201 typeof arg === 'string' ||
9202 typeof arg === 'symbol' || // ES6 symbol
9203 typeof arg === 'undefined';
9204}
9205exports.isPrimitive = isPrimitive;
9206
9207exports.isBuffer = Buffer.isBuffer;
9208
9209function objectToString(o) {
9210 return Object.prototype.toString.call(o);
9211}
9212
9213}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
9214},{"../../is-buffer/index.js":46}],31:[function(require,module,exports){
9215(function (Buffer){
9216'use strict'
9217var inherits = require('inherits')
9218var md5 = require('./md5')
9219var RIPEMD160 = require('ripemd160')
9220var sha = require('sha.js')
9221
9222var Base = require('cipher-base')
9223
9224function HashNoConstructor (hash) {
9225 Base.call(this, 'digest')
9226
9227 this._hash = hash
9228 this.buffers = []
9229}
9230
9231inherits(HashNoConstructor, Base)
9232
9233HashNoConstructor.prototype._update = function (data) {
9234 this.buffers.push(data)
9235}
9236
9237HashNoConstructor.prototype._final = function () {
9238 var buf = Buffer.concat(this.buffers)
9239 var r = this._hash(buf)
9240 this.buffers = null
9241
9242 return r
9243}
9244
9245function Hash (hash) {
9246 Base.call(this, 'digest')
9247
9248 this._hash = hash
9249}
9250
9251inherits(Hash, Base)
9252
9253Hash.prototype._update = function (data) {
9254 this._hash.update(data)
9255}
9256
9257Hash.prototype._final = function () {
9258 return this._hash.digest()
9259}
9260
9261module.exports = function createHash (alg) {
9262 alg = alg.toLowerCase()
9263 if (alg === 'md5') return new HashNoConstructor(md5)
9264 if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
9265
9266 return new Hash(sha(alg))
9267}
9268
9269}).call(this,require("buffer").Buffer)
9270},{"./md5":33,"buffer":27,"cipher-base":29,"inherits":45,"ripemd160":67,"sha.js":70}],32:[function(require,module,exports){
9271(function (Buffer){
9272'use strict'
9273var intSize = 4
9274var zeroBuffer = new Buffer(intSize)
9275zeroBuffer.fill(0)
9276
9277var charSize = 8
9278var hashSize = 16
9279
9280function toArray (buf) {
9281 if ((buf.length % intSize) !== 0) {
9282 var len = buf.length + (intSize - (buf.length % intSize))
9283 buf = Buffer.concat([buf, zeroBuffer], len)
9284 }
9285
9286 var arr = new Array(buf.length >>> 2)
9287 for (var i = 0, j = 0; i < buf.length; i += intSize, j++) {
9288 arr[j] = buf.readInt32LE(i)
9289 }
9290
9291 return arr
9292}
9293
9294module.exports = function hash (buf, fn) {
9295 var arr = fn(toArray(buf), buf.length * charSize)
9296 buf = new Buffer(hashSize)
9297 for (var i = 0; i < arr.length; i++) {
9298 buf.writeInt32LE(arr[i], i << 2, true)
9299 }
9300 return buf
9301}
9302
9303}).call(this,require("buffer").Buffer)
9304},{"buffer":27}],33:[function(require,module,exports){
9305'use strict'
9306/*
9307 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
9308 * Digest Algorithm, as defined in RFC 1321.
9309 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
9310 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
9311 * Distributed under the BSD License
9312 * See http://pajhome.org.uk/crypt/md5 for more info.
9313 */
9314
9315var makeHash = require('./make-hash')
9316
9317/*
9318 * Calculate the MD5 of an array of little-endian words, and a bit length
9319 */
9320function core_md5 (x, len) {
9321 /* append padding */
9322 x[len >> 5] |= 0x80 << ((len) % 32)
9323 x[(((len + 64) >>> 9) << 4) + 14] = len
9324
9325 var a = 1732584193
9326 var b = -271733879
9327 var c = -1732584194
9328 var d = 271733878
9329
9330 for (var i = 0; i < x.length; i += 16) {
9331 var olda = a
9332 var oldb = b
9333 var oldc = c
9334 var oldd = d
9335
9336 a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
9337 d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
9338 c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
9339 b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
9340 a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
9341 d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
9342 c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
9343 b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
9344 a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
9345 d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
9346 c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
9347 b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
9348 a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
9349 d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
9350 c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
9351 b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
9352
9353 a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
9354 d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
9355 c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
9356 b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
9357 a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
9358 d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
9359 c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
9360 b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
9361 a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
9362 d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
9363 c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
9364 b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
9365 a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
9366 d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
9367 c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
9368 b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
9369
9370 a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
9371 d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
9372 c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
9373 b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
9374 a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
9375 d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
9376 c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
9377 b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
9378 a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
9379 d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
9380 c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
9381 b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
9382 a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
9383 d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
9384 c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
9385 b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
9386
9387 a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
9388 d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
9389 c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
9390 b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
9391 a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
9392 d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
9393 c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
9394 b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
9395 a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
9396 d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
9397 c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
9398 b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
9399 a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
9400 d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
9401 c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
9402 b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
9403
9404 a = safe_add(a, olda)
9405 b = safe_add(b, oldb)
9406 c = safe_add(c, oldc)
9407 d = safe_add(d, oldd)
9408 }
9409
9410 return [a, b, c, d]
9411}
9412
9413/*
9414 * These functions implement the four basic operations the algorithm uses.
9415 */
9416function md5_cmn (q, a, b, x, s, t) {
9417 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
9418}
9419
9420function md5_ff (a, b, c, d, x, s, t) {
9421 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
9422}
9423
9424function md5_gg (a, b, c, d, x, s, t) {
9425 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
9426}
9427
9428function md5_hh (a, b, c, d, x, s, t) {
9429 return md5_cmn(b ^ c ^ d, a, b, x, s, t)
9430}
9431
9432function md5_ii (a, b, c, d, x, s, t) {
9433 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
9434}
9435
9436/*
9437 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
9438 * to work around bugs in some JS interpreters.
9439 */
9440function safe_add (x, y) {
9441 var lsw = (x & 0xFFFF) + (y & 0xFFFF)
9442 var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
9443 return (msw << 16) | (lsw & 0xFFFF)
9444}
9445
9446/*
9447 * Bitwise rotate a 32-bit number to the left.
9448 */
9449function bit_rol (num, cnt) {
9450 return (num << cnt) | (num >>> (32 - cnt))
9451}
9452
9453module.exports = function md5 (buf) {
9454 return makeHash(buf, core_md5)
9455}
9456
9457},{"./make-hash":32}],34:[function(require,module,exports){
9458'use strict'
9459var inherits = require('inherits')
9460var Legacy = require('./legacy')
9461var Base = require('cipher-base')
9462var Buffer = require('safe-buffer').Buffer
9463var md5 = require('create-hash/md5')
9464var RIPEMD160 = require('ripemd160')
9465
9466var sha = require('sha.js')
9467
9468var ZEROS = Buffer.alloc(128)
9469
9470function Hmac (alg, key) {
9471 Base.call(this, 'digest')
9472 if (typeof key === 'string') {
9473 key = Buffer.from(key)
9474 }
9475
9476 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
9477
9478 this._alg = alg
9479 this._key = key
9480 if (key.length > blocksize) {
9481 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
9482 key = hash.update(key).digest()
9483 } else if (key.length < blocksize) {
9484 key = Buffer.concat([key, ZEROS], blocksize)
9485 }
9486
9487 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
9488 var opad = this._opad = Buffer.allocUnsafe(blocksize)
9489
9490 for (var i = 0; i < blocksize; i++) {
9491 ipad[i] = key[i] ^ 0x36
9492 opad[i] = key[i] ^ 0x5C
9493 }
9494 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
9495 this._hash.update(ipad)
9496}
9497
9498inherits(Hmac, Base)
9499
9500Hmac.prototype._update = function (data) {
9501 this._hash.update(data)
9502}
9503
9504Hmac.prototype._final = function () {
9505 var h = this._hash.digest()
9506 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
9507 return hash.update(this._opad).update(h).digest()
9508}
9509
9510module.exports = function createHmac (alg, key) {
9511 alg = alg.toLowerCase()
9512 if (alg === 'rmd160' || alg === 'ripemd160') {
9513 return new Hmac('rmd160', key)
9514 }
9515 if (alg === 'md5') {
9516 return new Legacy(md5, key)
9517 }
9518 return new Hmac(alg, key)
9519}
9520
9521},{"./legacy":35,"cipher-base":29,"create-hash/md5":33,"inherits":45,"ripemd160":67,"safe-buffer":68,"sha.js":70}],35:[function(require,module,exports){
9522'use strict'
9523var inherits = require('inherits')
9524var Buffer = require('safe-buffer').Buffer
9525
9526var Base = require('cipher-base')
9527
9528var ZEROS = Buffer.alloc(128)
9529var blocksize = 64
9530
9531function Hmac (alg, key) {
9532 Base.call(this, 'digest')
9533 if (typeof key === 'string') {
9534 key = Buffer.from(key)
9535 }
9536
9537 this._alg = alg
9538 this._key = key
9539
9540 if (key.length > blocksize) {
9541 key = alg(key)
9542 } else if (key.length < blocksize) {
9543 key = Buffer.concat([key, ZEROS], blocksize)
9544 }
9545
9546 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
9547 var opad = this._opad = Buffer.allocUnsafe(blocksize)
9548
9549 for (var i = 0; i < blocksize; i++) {
9550 ipad[i] = key[i] ^ 0x36
9551 opad[i] = key[i] ^ 0x5C
9552 }
9553
9554 this._hash = [ipad]
9555}
9556
9557inherits(Hmac, Base)
9558
9559Hmac.prototype._update = function (data) {
9560 this._hash.push(data)
9561}
9562
9563Hmac.prototype._final = function () {
9564 var h = this._alg(Buffer.concat(this._hash))
9565 return this._alg(Buffer.concat([this._opad, h]))
9566}
9567module.exports = Hmac
9568
9569},{"cipher-base":29,"inherits":45,"safe-buffer":68}],36:[function(require,module,exports){
9570var assert = require('assert')
9571var BigInteger = require('bigi')
9572
9573var Point = require('./point')
9574
9575function Curve (p, a, b, Gx, Gy, n, h) {
9576 this.p = p
9577 this.a = a
9578 this.b = b
9579 this.G = Point.fromAffine(this, Gx, Gy)
9580 this.n = n
9581 this.h = h
9582
9583 this.infinity = new Point(this, null, null, BigInteger.ZERO)
9584
9585 // result caching
9586 this.pOverFour = p.add(BigInteger.ONE).shiftRight(2)
9587
9588 // determine size of p in bytes
9589 this.pLength = Math.floor((this.p.bitLength() + 7) / 8)
9590}
9591
9592Curve.prototype.pointFromX = function (isOdd, x) {
9593 var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p)
9594 var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves
9595
9596 var y = beta
9597 if (beta.isEven() ^ !isOdd) {
9598 y = this.p.subtract(y) // -y % p
9599 }
9600
9601 return Point.fromAffine(this, x, y)
9602}
9603
9604Curve.prototype.isInfinity = function (Q) {
9605 if (Q === this.infinity) return true
9606
9607 return Q.z.signum() === 0 && Q.y.signum() !== 0
9608}
9609
9610Curve.prototype.isOnCurve = function (Q) {
9611 if (this.isInfinity(Q)) return true
9612
9613 var x = Q.affineX
9614 var y = Q.affineY
9615 var a = this.a
9616 var b = this.b
9617 var p = this.p
9618
9619 // Check that xQ and yQ are integers in the interval [0, p - 1]
9620 if (x.signum() < 0 || x.compareTo(p) >= 0) return false
9621 if (y.signum() < 0 || y.compareTo(p) >= 0) return false
9622
9623 // and check that y^2 = x^3 + ax + b (mod p)
9624 var lhs = y.square().mod(p)
9625 var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
9626 return lhs.equals(rhs)
9627}
9628
9629/**
9630 * Validate an elliptic curve point.
9631 *
9632 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
9633 */
9634Curve.prototype.validate = function (Q) {
9635 // Check Q != O
9636 assert(!this.isInfinity(Q), 'Point is at infinity')
9637 assert(this.isOnCurve(Q), 'Point is not on the curve')
9638
9639 // Check nQ = O (where Q is a scalar multiple of G)
9640 var nQ = Q.multiply(this.n)
9641 assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G')
9642
9643 return true
9644}
9645
9646module.exports = Curve
9647
9648},{"./point":40,"assert":1,"bigi":6}],37:[function(require,module,exports){
9649module.exports={
9650 "secp128r1": {
9651 "p": "fffffffdffffffffffffffffffffffff",
9652 "a": "fffffffdfffffffffffffffffffffffc",
9653 "b": "e87579c11079f43dd824993c2cee5ed3",
9654 "n": "fffffffe0000000075a30d1b9038a115",
9655 "h": "01",
9656 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
9657 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
9658 },
9659 "secp160k1": {
9660 "p": "fffffffffffffffffffffffffffffffeffffac73",
9661 "a": "00",
9662 "b": "07",
9663 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
9664 "h": "01",
9665 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
9666 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
9667 },
9668 "secp160r1": {
9669 "p": "ffffffffffffffffffffffffffffffff7fffffff",
9670 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
9671 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
9672 "n": "0100000000000000000001f4c8f927aed3ca752257",
9673 "h": "01",
9674 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
9675 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
9676 },
9677 "secp192k1": {
9678 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
9679 "a": "00",
9680 "b": "03",
9681 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
9682 "h": "01",
9683 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
9684 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
9685 },
9686 "secp192r1": {
9687 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
9688 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
9689 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
9690 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
9691 "h": "01",
9692 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
9693 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
9694 },
9695 "secp256k1": {
9696 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
9697 "a": "00",
9698 "b": "07",
9699 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
9700 "h": "01",
9701 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
9702 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
9703 },
9704 "secp256r1": {
9705 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
9706 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
9707 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
9708 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
9709 "h": "01",
9710 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
9711 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
9712 }
9713}
9714
9715},{}],38:[function(require,module,exports){
9716var Point = require('./point')
9717var Curve = require('./curve')
9718
9719var getCurveByName = require('./names')
9720
9721module.exports = {
9722 Curve: Curve,
9723 Point: Point,
9724 getCurveByName: getCurveByName
9725}
9726
9727},{"./curve":36,"./names":39,"./point":40}],39:[function(require,module,exports){
9728var BigInteger = require('bigi')
9729
9730var curves = require('./curves.json')
9731var Curve = require('./curve')
9732
9733function getCurveByName (name) {
9734 var curve = curves[name]
9735 if (!curve) return null
9736
9737 var p = new BigInteger(curve.p, 16)
9738 var a = new BigInteger(curve.a, 16)
9739 var b = new BigInteger(curve.b, 16)
9740 var n = new BigInteger(curve.n, 16)
9741 var h = new BigInteger(curve.h, 16)
9742 var Gx = new BigInteger(curve.Gx, 16)
9743 var Gy = new BigInteger(curve.Gy, 16)
9744
9745 return new Curve(p, a, b, Gx, Gy, n, h)
9746}
9747
9748module.exports = getCurveByName
9749
9750},{"./curve":36,"./curves.json":37,"bigi":6}],40:[function(require,module,exports){
9751(function (Buffer){
9752var assert = require('assert')
9753var BigInteger = require('bigi')
9754
9755var THREE = BigInteger.valueOf(3)
9756
9757function Point (curve, x, y, z) {
9758 assert.notStrictEqual(z, undefined, 'Missing Z coordinate')
9759
9760 this.curve = curve
9761 this.x = x
9762 this.y = y
9763 this.z = z
9764 this._zInv = null
9765
9766 this.compressed = true
9767}
9768
9769Object.defineProperty(Point.prototype, 'zInv', {
9770 get: function () {
9771 if (this._zInv === null) {
9772 this._zInv = this.z.modInverse(this.curve.p)
9773 }
9774
9775 return this._zInv
9776 }
9777})
9778
9779Object.defineProperty(Point.prototype, 'affineX', {
9780 get: function () {
9781 return this.x.multiply(this.zInv).mod(this.curve.p)
9782 }
9783})
9784
9785Object.defineProperty(Point.prototype, 'affineY', {
9786 get: function () {
9787 return this.y.multiply(this.zInv).mod(this.curve.p)
9788 }
9789})
9790
9791Point.fromAffine = function (curve, x, y) {
9792 return new Point(curve, x, y, BigInteger.ONE)
9793}
9794
9795Point.prototype.equals = function (other) {
9796 if (other === this) return true
9797 if (this.curve.isInfinity(this)) return this.curve.isInfinity(other)
9798 if (this.curve.isInfinity(other)) return this.curve.isInfinity(this)
9799
9800 // u = Y2 * Z1 - Y1 * Z2
9801 var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p)
9802
9803 if (u.signum() !== 0) return false
9804
9805 // v = X2 * Z1 - X1 * Z2
9806 var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p)
9807
9808 return v.signum() === 0
9809}
9810
9811Point.prototype.negate = function () {
9812 var y = this.curve.p.subtract(this.y)
9813
9814 return new Point(this.curve, this.x, y, this.z)
9815}
9816
9817Point.prototype.add = function (b) {
9818 if (this.curve.isInfinity(this)) return b
9819 if (this.curve.isInfinity(b)) return this
9820
9821 var x1 = this.x
9822 var y1 = this.y
9823 var x2 = b.x
9824 var y2 = b.y
9825
9826 // u = Y2 * Z1 - Y1 * Z2
9827 var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p)
9828 // v = X2 * Z1 - X1 * Z2
9829 var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p)
9830
9831 if (v.signum() === 0) {
9832 if (u.signum() === 0) {
9833 return this.twice() // this == b, so double
9834 }
9835
9836 return this.curve.infinity // this = -b, so infinity
9837 }
9838
9839 var v2 = v.square()
9840 var v3 = v2.multiply(v)
9841 var x1v2 = x1.multiply(v2)
9842 var zu2 = u.square().multiply(this.z)
9843
9844 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
9845 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p)
9846 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
9847 var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p)
9848 // z3 = v^3 * z1 * z2
9849 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p)
9850
9851 return new Point(this.curve, x3, y3, z3)
9852}
9853
9854Point.prototype.twice = function () {
9855 if (this.curve.isInfinity(this)) return this
9856 if (this.y.signum() === 0) return this.curve.infinity
9857
9858 var x1 = this.x
9859 var y1 = this.y
9860
9861 var y1z1 = y1.multiply(this.z).mod(this.curve.p)
9862 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p)
9863 var a = this.curve.a
9864
9865 // w = 3 * x1^2 + a * z1^2
9866 var w = x1.square().multiply(THREE)
9867
9868 if (a.signum() !== 0) {
9869 w = w.add(this.z.square().multiply(a))
9870 }
9871
9872 w = w.mod(this.curve.p)
9873 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
9874 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p)
9875 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
9876 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p)
9877 // z3 = 8 * (y1 * z1)^3
9878 var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p)
9879
9880 return new Point(this.curve, x3, y3, z3)
9881}
9882
9883// Simple NAF (Non-Adjacent Form) multiplication algorithm
9884// TODO: modularize the multiplication algorithm
9885Point.prototype.multiply = function (k) {
9886 if (this.curve.isInfinity(this)) return this
9887 if (k.signum() === 0) return this.curve.infinity
9888
9889 var e = k
9890 var h = e.multiply(THREE)
9891
9892 var neg = this.negate()
9893 var R = this
9894
9895 for (var i = h.bitLength() - 2; i > 0; --i) {
9896 var hBit = h.testBit(i)
9897 var eBit = e.testBit(i)
9898
9899 R = R.twice()
9900
9901 if (hBit !== eBit) {
9902 R = R.add(hBit ? this : neg)
9903 }
9904 }
9905
9906 return R
9907}
9908
9909// Compute this*j + x*k (simultaneous multiplication)
9910Point.prototype.multiplyTwo = function (j, x, k) {
9911 var i = Math.max(j.bitLength(), k.bitLength()) - 1
9912 var R = this.curve.infinity
9913 var both = this.add(x)
9914
9915 while (i >= 0) {
9916 var jBit = j.testBit(i)
9917 var kBit = k.testBit(i)
9918
9919 R = R.twice()
9920
9921 if (jBit) {
9922 if (kBit) {
9923 R = R.add(both)
9924 } else {
9925 R = R.add(this)
9926 }
9927 } else if (kBit) {
9928 R = R.add(x)
9929 }
9930 --i
9931 }
9932
9933 return R
9934}
9935
9936Point.prototype.getEncoded = function (compressed) {
9937 if (compressed == null) compressed = this.compressed
9938 if (this.curve.isInfinity(this)) return new Buffer('00', 'hex') // Infinity point encoded is simply '00'
9939
9940 var x = this.affineX
9941 var y = this.affineY
9942 var byteLength = this.curve.pLength
9943 var buffer
9944
9945 // 0x02/0x03 | X
9946 if (compressed) {
9947 buffer = new Buffer(1 + byteLength)
9948 buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)
9949
9950 // 0x04 | X | Y
9951 } else {
9952 buffer = new Buffer(1 + byteLength + byteLength)
9953 buffer.writeUInt8(0x04, 0)
9954
9955 y.toBuffer(byteLength).copy(buffer, 1 + byteLength)
9956 }
9957
9958 x.toBuffer(byteLength).copy(buffer, 1)
9959
9960 return buffer
9961}
9962
9963Point.decodeFrom = function (curve, buffer) {
9964 var type = buffer.readUInt8(0)
9965 var compressed = (type !== 4)
9966
9967 var byteLength = Math.floor((curve.p.bitLength() + 7) / 8)
9968 var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength))
9969
9970 var Q
9971 if (compressed) {
9972 assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length')
9973 assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')
9974
9975 var isOdd = (type === 0x03)
9976 Q = curve.pointFromX(isOdd, x)
9977 } else {
9978 assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length')
9979
9980 var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength))
9981 Q = Point.fromAffine(curve, x, y)
9982 }
9983
9984 Q.compressed = compressed
9985 return Q
9986}
9987
9988Point.prototype.toString = function () {
9989 if (this.curve.isInfinity(this)) return '(INFINITY)'
9990
9991 return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')'
9992}
9993
9994module.exports = Point
9995
9996}).call(this,require("buffer").Buffer)
9997},{"assert":1,"bigi":6,"buffer":27}],41:[function(require,module,exports){
9998// Copyright Joyent, Inc. and other Node contributors.
9999//
10000// Permission is hereby granted, free of charge, to any person obtaining a
10001// copy of this software and associated documentation files (the
10002// "Software"), to deal in the Software without restriction, including
10003// without limitation the rights to use, copy, modify, merge, publish,
10004// distribute, sublicense, and/or sell copies of the Software, and to permit
10005// persons to whom the Software is furnished to do so, subject to the
10006// following conditions:
10007//
10008// The above copyright notice and this permission notice shall be included
10009// in all copies or substantial portions of the Software.
10010//
10011// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10012// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10013// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10014// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10015// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10016// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10017// USE OR OTHER DEALINGS IN THE SOFTWARE.
10018
10019function EventEmitter() {
10020 this._events = this._events || {};
10021 this._maxListeners = this._maxListeners || undefined;
10022}
10023module.exports = EventEmitter;
10024
10025// Backwards-compat with node 0.10.x
10026EventEmitter.EventEmitter = EventEmitter;
10027
10028EventEmitter.prototype._events = undefined;
10029EventEmitter.prototype._maxListeners = undefined;
10030
10031// By default EventEmitters will print a warning if more than 10 listeners are
10032// added to it. This is a useful default which helps finding memory leaks.
10033EventEmitter.defaultMaxListeners = 10;
10034
10035// Obviously not all Emitters should be limited to 10. This function allows
10036// that to be increased. Set to zero for unlimited.
10037EventEmitter.prototype.setMaxListeners = function(n) {
10038 if (!isNumber(n) || n < 0 || isNaN(n))
10039 throw TypeError('n must be a positive number');
10040 this._maxListeners = n;
10041 return this;
10042};
10043
10044EventEmitter.prototype.emit = function(type) {
10045 var er, handler, len, args, i, listeners;
10046
10047 if (!this._events)
10048 this._events = {};
10049
10050 // If there is no 'error' event listener then throw.
10051 if (type === 'error') {
10052 if (!this._events.error ||
10053 (isObject(this._events.error) && !this._events.error.length)) {
10054 er = arguments[1];
10055 if (er instanceof Error) {
10056 throw er; // Unhandled 'error' event
10057 } else {
10058 // At least give some kind of context to the user
10059 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
10060 err.context = er;
10061 throw err;
10062 }
10063 }
10064 }
10065
10066 handler = this._events[type];
10067
10068 if (isUndefined(handler))
10069 return false;
10070
10071 if (isFunction(handler)) {
10072 switch (arguments.length) {
10073 // fast cases
10074 case 1:
10075 handler.call(this);
10076 break;
10077 case 2:
10078 handler.call(this, arguments[1]);
10079 break;
10080 case 3:
10081 handler.call(this, arguments[1], arguments[2]);
10082 break;
10083 // slower
10084 default:
10085 args = Array.prototype.slice.call(arguments, 1);
10086 handler.apply(this, args);
10087 }
10088 } else if (isObject(handler)) {
10089 args = Array.prototype.slice.call(arguments, 1);
10090 listeners = handler.slice();
10091 len = listeners.length;
10092 for (i = 0; i < len; i++)
10093 listeners[i].apply(this, args);
10094 }
10095
10096 return true;
10097};
10098
10099EventEmitter.prototype.addListener = function(type, listener) {
10100 var m;
10101
10102 if (!isFunction(listener))
10103 throw TypeError('listener must be a function');
10104
10105 if (!this._events)
10106 this._events = {};
10107
10108 // To avoid recursion in the case that type === "newListener"! Before
10109 // adding it to the listeners, first emit "newListener".
10110 if (this._events.newListener)
10111 this.emit('newListener', type,
10112 isFunction(listener.listener) ?
10113 listener.listener : listener);
10114
10115 if (!this._events[type])
10116 // Optimize the case of one listener. Don't need the extra array object.
10117 this._events[type] = listener;
10118 else if (isObject(this._events[type]))
10119 // If we've already got an array, just append.
10120 this._events[type].push(listener);
10121 else
10122 // Adding the second element, need to change to array.
10123 this._events[type] = [this._events[type], listener];
10124
10125 // Check for listener leak
10126 if (isObject(this._events[type]) && !this._events[type].warned) {
10127 if (!isUndefined(this._maxListeners)) {
10128 m = this._maxListeners;
10129 } else {
10130 m = EventEmitter.defaultMaxListeners;
10131 }
10132
10133 if (m && m > 0 && this._events[type].length > m) {
10134 this._events[type].warned = true;
10135 console.error('(node) warning: possible EventEmitter memory ' +
10136 'leak detected. %d listeners added. ' +
10137 'Use emitter.setMaxListeners() to increase limit.',
10138 this._events[type].length);
10139 if (typeof console.trace === 'function') {
10140 // not supported in IE 10
10141 console.trace();
10142 }
10143 }
10144 }
10145
10146 return this;
10147};
10148
10149EventEmitter.prototype.on = EventEmitter.prototype.addListener;
10150
10151EventEmitter.prototype.once = function(type, listener) {
10152 if (!isFunction(listener))
10153 throw TypeError('listener must be a function');
10154
10155 var fired = false;
10156
10157 function g() {
10158 this.removeListener(type, g);
10159
10160 if (!fired) {
10161 fired = true;
10162 listener.apply(this, arguments);
10163 }
10164 }
10165
10166 g.listener = listener;
10167 this.on(type, g);
10168
10169 return this;
10170};
10171
10172// emits a 'removeListener' event iff the listener was removed
10173EventEmitter.prototype.removeListener = function(type, listener) {
10174 var list, position, length, i;
10175
10176 if (!isFunction(listener))
10177 throw TypeError('listener must be a function');
10178
10179 if (!this._events || !this._events[type])
10180 return this;
10181
10182 list = this._events[type];
10183 length = list.length;
10184 position = -1;
10185
10186 if (list === listener ||
10187 (isFunction(list.listener) && list.listener === listener)) {
10188 delete this._events[type];
10189 if (this._events.removeListener)
10190 this.emit('removeListener', type, listener);
10191
10192 } else if (isObject(list)) {
10193 for (i = length; i-- > 0;) {
10194 if (list[i] === listener ||
10195 (list[i].listener && list[i].listener === listener)) {
10196 position = i;
10197 break;
10198 }
10199 }
10200
10201 if (position < 0)
10202 return this;
10203
10204 if (list.length === 1) {
10205 list.length = 0;
10206 delete this._events[type];
10207 } else {
10208 list.splice(position, 1);
10209 }
10210
10211 if (this._events.removeListener)
10212 this.emit('removeListener', type, listener);
10213 }
10214
10215 return this;
10216};
10217
10218EventEmitter.prototype.removeAllListeners = function(type) {
10219 var key, listeners;
10220
10221 if (!this._events)
10222 return this;
10223
10224 // not listening for removeListener, no need to emit
10225 if (!this._events.removeListener) {
10226 if (arguments.length === 0)
10227 this._events = {};
10228 else if (this._events[type])
10229 delete this._events[type];
10230 return this;
10231 }
10232
10233 // emit removeListener for all listeners on all events
10234 if (arguments.length === 0) {
10235 for (key in this._events) {
10236 if (key === 'removeListener') continue;
10237 this.removeAllListeners(key);
10238 }
10239 this.removeAllListeners('removeListener');
10240 this._events = {};
10241 return this;
10242 }
10243
10244 listeners = this._events[type];
10245
10246 if (isFunction(listeners)) {
10247 this.removeListener(type, listeners);
10248 } else if (listeners) {
10249 // LIFO order
10250 while (listeners.length)
10251 this.removeListener(type, listeners[listeners.length - 1]);
10252 }
10253 delete this._events[type];
10254
10255 return this;
10256};
10257
10258EventEmitter.prototype.listeners = function(type) {
10259 var ret;
10260 if (!this._events || !this._events[type])
10261 ret = [];
10262 else if (isFunction(this._events[type]))
10263 ret = [this._events[type]];
10264 else
10265 ret = this._events[type].slice();
10266 return ret;
10267};
10268
10269EventEmitter.prototype.listenerCount = function(type) {
10270 if (this._events) {
10271 var evlistener = this._events[type];
10272
10273 if (isFunction(evlistener))
10274 return 1;
10275 else if (evlistener)
10276 return evlistener.length;
10277 }
10278 return 0;
10279};
10280
10281EventEmitter.listenerCount = function(emitter, type) {
10282 return emitter.listenerCount(type);
10283};
10284
10285function isFunction(arg) {
10286 return typeof arg === 'function';
10287}
10288
10289function isNumber(arg) {
10290 return typeof arg === 'number';
10291}
10292
10293function isObject(arg) {
10294 return typeof arg === 'object' && arg !== null;
10295}
10296
10297function isUndefined(arg) {
10298 return arg === void 0;
10299}
10300
10301},{}],42:[function(require,module,exports){
10302var Buffer = require('safe-buffer').Buffer
10303var MD5 = require('md5.js')
10304
10305/* eslint-disable camelcase */
10306function EVP_BytesToKey (password, salt, keyBits, ivLen) {
10307 if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
10308 if (salt) {
10309 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
10310 if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
10311 }
10312
10313 var keyLen = keyBits / 8
10314 var key = Buffer.alloc(keyLen)
10315 var iv = Buffer.alloc(ivLen || 0)
10316 var tmp = Buffer.alloc(0)
10317
10318 while (keyLen > 0 || ivLen > 0) {
10319 var hash = new MD5()
10320 hash.update(tmp)
10321 hash.update(password)
10322 if (salt) hash.update(salt)
10323 tmp = hash.digest()
10324
10325 var used = 0
10326
10327 if (keyLen > 0) {
10328 var keyStart = key.length - keyLen
10329 used = Math.min(keyLen, tmp.length)
10330 tmp.copy(key, keyStart, 0, used)
10331 keyLen -= used
10332 }
10333
10334 if (used < tmp.length && ivLen > 0) {
10335 var ivStart = iv.length - ivLen
10336 var length = Math.min(ivLen, tmp.length - used)
10337 tmp.copy(iv, ivStart, used, used + length)
10338 ivLen -= length
10339 }
10340 }
10341
10342 tmp.fill(0)
10343 return { key: key, iv: iv }
10344}
10345
10346module.exports = EVP_BytesToKey
10347
10348},{"md5.js":49,"safe-buffer":68}],43:[function(require,module,exports){
10349(function (Buffer){
10350'use strict'
10351var Transform = require('stream').Transform
10352var inherits = require('inherits')
10353
10354function HashBase (blockSize) {
10355 Transform.call(this)
10356
10357 this._block = new Buffer(blockSize)
10358 this._blockSize = blockSize
10359 this._blockOffset = 0
10360 this._length = [0, 0, 0, 0]
10361
10362 this._finalized = false
10363}
10364
10365inherits(HashBase, Transform)
10366
10367HashBase.prototype._transform = function (chunk, encoding, callback) {
10368 var error = null
10369 try {
10370 if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding)
10371 this.update(chunk)
10372 } catch (err) {
10373 error = err
10374 }
10375
10376 callback(error)
10377}
10378
10379HashBase.prototype._flush = function (callback) {
10380 var error = null
10381 try {
10382 this.push(this._digest())
10383 } catch (err) {
10384 error = err
10385 }
10386
10387 callback(error)
10388}
10389
10390HashBase.prototype.update = function (data, encoding) {
10391 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
10392 if (this._finalized) throw new Error('Digest already called')
10393 if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary')
10394
10395 // consume data
10396 var block = this._block
10397 var offset = 0
10398 while (this._blockOffset + data.length - offset >= this._blockSize) {
10399 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
10400 this._update()
10401 this._blockOffset = 0
10402 }
10403 while (offset < data.length) block[this._blockOffset++] = data[offset++]
10404
10405 // update length
10406 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
10407 this._length[j] += carry
10408 carry = (this._length[j] / 0x0100000000) | 0
10409 if (carry > 0) this._length[j] -= 0x0100000000 * carry
10410 }
10411
10412 return this
10413}
10414
10415HashBase.prototype._update = function (data) {
10416 throw new Error('_update is not implemented')
10417}
10418
10419HashBase.prototype.digest = function (encoding) {
10420 if (this._finalized) throw new Error('Digest already called')
10421 this._finalized = true
10422
10423 var digest = this._digest()
10424 if (encoding !== undefined) digest = digest.toString(encoding)
10425 return digest
10426}
10427
10428HashBase.prototype._digest = function () {
10429 throw new Error('_digest is not implemented')
10430}
10431
10432module.exports = HashBase
10433
10434}).call(this,require("buffer").Buffer)
10435},{"buffer":27,"inherits":45,"stream":77}],44:[function(require,module,exports){
10436exports.read = function (buffer, offset, isLE, mLen, nBytes) {
10437 var e, m
10438 var eLen = nBytes * 8 - mLen - 1
10439 var eMax = (1 << eLen) - 1
10440 var eBias = eMax >> 1
10441 var nBits = -7
10442 var i = isLE ? (nBytes - 1) : 0
10443 var d = isLE ? -1 : 1
10444 var s = buffer[offset + i]
10445
10446 i += d
10447
10448 e = s & ((1 << (-nBits)) - 1)
10449 s >>= (-nBits)
10450 nBits += eLen
10451 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
10452
10453 m = e & ((1 << (-nBits)) - 1)
10454 e >>= (-nBits)
10455 nBits += mLen
10456 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
10457
10458 if (e === 0) {
10459 e = 1 - eBias
10460 } else if (e === eMax) {
10461 return m ? NaN : ((s ? -1 : 1) * Infinity)
10462 } else {
10463 m = m + Math.pow(2, mLen)
10464 e = e - eBias
10465 }
10466 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
10467}
10468
10469exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
10470 var e, m, c
10471 var eLen = nBytes * 8 - mLen - 1
10472 var eMax = (1 << eLen) - 1
10473 var eBias = eMax >> 1
10474 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
10475 var i = isLE ? 0 : (nBytes - 1)
10476 var d = isLE ? 1 : -1
10477 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
10478
10479 value = Math.abs(value)
10480
10481 if (isNaN(value) || value === Infinity) {
10482 m = isNaN(value) ? 1 : 0
10483 e = eMax
10484 } else {
10485 e = Math.floor(Math.log(value) / Math.LN2)
10486 if (value * (c = Math.pow(2, -e)) < 1) {
10487 e--
10488 c *= 2
10489 }
10490 if (e + eBias >= 1) {
10491 value += rt / c
10492 } else {
10493 value += rt * Math.pow(2, 1 - eBias)
10494 }
10495 if (value * c >= 2) {
10496 e++
10497 c /= 2
10498 }
10499
10500 if (e + eBias >= eMax) {
10501 m = 0
10502 e = eMax
10503 } else if (e + eBias >= 1) {
10504 m = (value * c - 1) * Math.pow(2, mLen)
10505 e = e + eBias
10506 } else {
10507 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
10508 e = 0
10509 }
10510 }
10511
10512 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
10513
10514 e = (e << mLen) | m
10515 eLen += mLen
10516 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
10517
10518 buffer[offset + i - d] |= s * 128
10519}
10520
10521},{}],45:[function(require,module,exports){
10522if (typeof Object.create === 'function') {
10523 // implementation from standard node.js 'util' module
10524 module.exports = function inherits(ctor, superCtor) {
10525 ctor.super_ = superCtor
10526 ctor.prototype = Object.create(superCtor.prototype, {
10527 constructor: {
10528 value: ctor,
10529 enumerable: false,
10530 writable: true,
10531 configurable: true
10532 }
10533 });
10534 };
10535} else {
10536 // old school shim for old browsers
10537 module.exports = function inherits(ctor, superCtor) {
10538 ctor.super_ = superCtor
10539 var TempCtor = function () {}
10540 TempCtor.prototype = superCtor.prototype
10541 ctor.prototype = new TempCtor()
10542 ctor.prototype.constructor = ctor
10543 }
10544}
10545
10546},{}],46:[function(require,module,exports){
10547/*!
10548 * Determine if an object is a Buffer
10549 *
10550 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
10551 * @license MIT
10552 */
10553
10554// The _isBuffer check is for Safari 5-7 support, because it's missing
10555// Object.prototype.constructor. Remove this eventually
10556module.exports = function (obj) {
10557 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
10558}
10559
10560function isBuffer (obj) {
10561 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
10562}
10563
10564// For Node v0.10 support. Remove this eventually.
10565function isSlowBuffer (obj) {
10566 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
10567}
10568
10569},{}],47:[function(require,module,exports){
10570var toString = {}.toString;
10571
10572module.exports = Array.isArray || function (arr) {
10573 return toString.call(arr) == '[object Array]';
10574};
10575
10576},{}],48:[function(require,module,exports){
10577/*
10578 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
10579 Copyright 2009 The Closure Library Authors. All Rights Reserved.
10580
10581 Licensed under the Apache License, Version 2.0 (the "License");
10582 you may not use this file except in compliance with the License.
10583 You may obtain a copy of the License at
10584
10585 http://www.apache.org/licenses/LICENSE-2.0
10586
10587 Unless required by applicable law or agreed to in writing, software
10588 distributed under the License is distributed on an "AS-IS" BASIS,
10589 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10590 See the License for the specific language governing permissions and
10591 limitations under the License.
10592 */
10593
10594/**
10595 * @license long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
10596 * Released under the Apache License, Version 2.0
10597 * see: https://github.com/dcodeIO/long.js for details
10598 */
10599(function(global, factory) {
10600
10601 /* AMD */ if (typeof define === 'function' && define["amd"])
10602 define([], factory);
10603 /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
10604 module["exports"] = factory();
10605 /* Global */ else
10606 (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();
10607
10608})(this, function() {
10609 "use strict";
10610
10611 /**
10612 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
10613 * See the from* functions below for more convenient ways of constructing Longs.
10614 * @exports Long
10615 * @class A Long class for representing a 64 bit two's-complement integer value.
10616 * @param {number} low The low (signed) 32 bits of the long
10617 * @param {number} high The high (signed) 32 bits of the long
10618 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
10619 * @constructor
10620 */
10621 function Long(low, high, unsigned) {
10622
10623 /**
10624 * The low 32 bits as a signed value.
10625 * @type {number}
10626 */
10627 this.low = low | 0;
10628
10629 /**
10630 * The high 32 bits as a signed value.
10631 * @type {number}
10632 */
10633 this.high = high | 0;
10634
10635 /**
10636 * Whether unsigned or not.
10637 * @type {boolean}
10638 */
10639 this.unsigned = !!unsigned;
10640 }
10641
10642 // The internal representation of a long is the two given signed, 32-bit values.
10643 // We use 32-bit pieces because these are the size of integers on which
10644 // Javascript performs bit-operations. For operations like addition and
10645 // multiplication, we split each number into 16 bit pieces, which can easily be
10646 // multiplied within Javascript's floating-point representation without overflow
10647 // or change in sign.
10648 //
10649 // In the algorithms below, we frequently reduce the negative case to the
10650 // positive case by negating the input(s) and then post-processing the result.
10651 // Note that we must ALWAYS check specially whether those values are MIN_VALUE
10652 // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
10653 // a positive number, it overflows back into a negative). Not handling this
10654 // case would often result in infinite recursion.
10655 //
10656 // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
10657 // methods on which they depend.
10658
10659 /**
10660 * An indicator used to reliably determine if an object is a Long or not.
10661 * @type {boolean}
10662 * @const
10663 * @private
10664 */
10665 Long.prototype.__isLong__;
10666
10667 Object.defineProperty(Long.prototype, "__isLong__", {
10668 value: true,
10669 enumerable: false,
10670 configurable: false
10671 });
10672
10673 /**
10674 * @function
10675 * @param {*} obj Object
10676 * @returns {boolean}
10677 * @inner
10678 */
10679 function isLong(obj) {
10680 return (obj && obj["__isLong__"]) === true;
10681 }
10682
10683 /**
10684 * Tests if the specified object is a Long.
10685 * @function
10686 * @param {*} obj Object
10687 * @returns {boolean}
10688 */
10689 Long.isLong = isLong;
10690
10691 /**
10692 * A cache of the Long representations of small integer values.
10693 * @type {!Object}
10694 * @inner
10695 */
10696 var INT_CACHE = {};
10697
10698 /**
10699 * A cache of the Long representations of small unsigned integer values.
10700 * @type {!Object}
10701 * @inner
10702 */
10703 var UINT_CACHE = {};
10704
10705 /**
10706 * @param {number} value
10707 * @param {boolean=} unsigned
10708 * @returns {!Long}
10709 * @inner
10710 */
10711 function fromInt(value, unsigned) {
10712 var obj, cachedObj, cache;
10713 if (unsigned) {
10714 value >>>= 0;
10715 if (cache = (0 <= value && value < 256)) {
10716 cachedObj = UINT_CACHE[value];
10717 if (cachedObj)
10718 return cachedObj;
10719 }
10720 obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
10721 if (cache)
10722 UINT_CACHE[value] = obj;
10723 return obj;
10724 } else {
10725 value |= 0;
10726 if (cache = (-128 <= value && value < 128)) {
10727 cachedObj = INT_CACHE[value];
10728 if (cachedObj)
10729 return cachedObj;
10730 }
10731 obj = fromBits(value, value < 0 ? -1 : 0, false);
10732 if (cache)
10733 INT_CACHE[value] = obj;
10734 return obj;
10735 }
10736 }
10737
10738 /**
10739 * Returns a Long representing the given 32 bit integer value.
10740 * @function
10741 * @param {number} value The 32 bit integer in question
10742 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
10743 * @returns {!Long} The corresponding Long value
10744 */
10745 Long.fromInt = fromInt;
10746
10747 /**
10748 * @param {number} value
10749 * @param {boolean=} unsigned
10750 * @returns {!Long}
10751 * @inner
10752 */
10753 function fromNumber(value, unsigned) {
10754 if (isNaN(value) || !isFinite(value))
10755 return unsigned ? UZERO : ZERO;
10756 if (unsigned) {
10757 if (value < 0)
10758 return UZERO;
10759 if (value >= TWO_PWR_64_DBL)
10760 return MAX_UNSIGNED_VALUE;
10761 } else {
10762 if (value <= -TWO_PWR_63_DBL)
10763 return MIN_VALUE;
10764 if (value + 1 >= TWO_PWR_63_DBL)
10765 return MAX_VALUE;
10766 }
10767 if (value < 0)
10768 return fromNumber(-value, unsigned).neg();
10769 return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
10770 }
10771
10772 /**
10773 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
10774 * @function
10775 * @param {number} value The number in question
10776 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
10777 * @returns {!Long} The corresponding Long value
10778 */
10779 Long.fromNumber = fromNumber;
10780
10781 /**
10782 * @param {number} lowBits
10783 * @param {number} highBits
10784 * @param {boolean=} unsigned
10785 * @returns {!Long}
10786 * @inner
10787 */
10788 function fromBits(lowBits, highBits, unsigned) {
10789 return new Long(lowBits, highBits, unsigned);
10790 }
10791
10792 /**
10793 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
10794 * assumed to use 32 bits.
10795 * @function
10796 * @param {number} lowBits The low 32 bits
10797 * @param {number} highBits The high 32 bits
10798 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
10799 * @returns {!Long} The corresponding Long value
10800 */
10801 Long.fromBits = fromBits;
10802
10803 /**
10804 * @function
10805 * @param {number} base
10806 * @param {number} exponent
10807 * @returns {number}
10808 * @inner
10809 */
10810 var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
10811
10812 /**
10813 * @param {string} str
10814 * @param {(boolean|number)=} unsigned
10815 * @param {number=} radix
10816 * @returns {!Long}
10817 * @inner
10818 */
10819 function fromString(str, unsigned, radix) {
10820 if (str.length === 0)
10821 throw Error('empty string');
10822 if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
10823 return ZERO;
10824 if (typeof unsigned === 'number') {
10825 // For goog.math.long compatibility
10826 radix = unsigned,
10827 unsigned = false;
10828 } else {
10829 unsigned = !! unsigned;
10830 }
10831 radix = radix || 10;
10832 if (radix < 2 || 36 < radix)
10833 throw RangeError('radix');
10834
10835 var p;
10836 if ((p = str.indexOf('-')) > 0)
10837 throw Error('interior hyphen');
10838 else if (p === 0) {
10839 return fromString(str.substring(1), unsigned, radix).neg();
10840 }
10841
10842 // Do several (8) digits each time through the loop, so as to
10843 // minimize the calls to the very expensive emulated div.
10844 var radixToPower = fromNumber(pow_dbl(radix, 8));
10845
10846 var result = ZERO;
10847 for (var i = 0; i < str.length; i += 8) {
10848 var size = Math.min(8, str.length - i),
10849 value = parseInt(str.substring(i, i + size), radix);
10850 if (size < 8) {
10851 var power = fromNumber(pow_dbl(radix, size));
10852 result = result.mul(power).add(fromNumber(value));
10853 } else {
10854 result = result.mul(radixToPower);
10855 result = result.add(fromNumber(value));
10856 }
10857 }
10858 result.unsigned = unsigned;
10859 return result;
10860 }
10861
10862 /**
10863 * Returns a Long representation of the given string, written using the specified radix.
10864 * @function
10865 * @param {string} str The textual representation of the Long
10866 * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
10867 * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
10868 * @returns {!Long} The corresponding Long value
10869 */
10870 Long.fromString = fromString;
10871
10872 /**
10873 * @function
10874 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
10875 * @returns {!Long}
10876 * @inner
10877 */
10878 function fromValue(val) {
10879 if (val /* is compatible */ instanceof Long)
10880 return val;
10881 if (typeof val === 'number')
10882 return fromNumber(val);
10883 if (typeof val === 'string')
10884 return fromString(val);
10885 // Throws for non-objects, converts non-instanceof Long:
10886 return fromBits(val.low, val.high, val.unsigned);
10887 }
10888
10889 /**
10890 * Converts the specified value to a Long.
10891 * @function
10892 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
10893 * @returns {!Long}
10894 */
10895 Long.fromValue = fromValue;
10896
10897 // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
10898 // no runtime penalty for these.
10899
10900 /**
10901 * @type {number}
10902 * @const
10903 * @inner
10904 */
10905 var TWO_PWR_16_DBL = 1 << 16;
10906
10907 /**
10908 * @type {number}
10909 * @const
10910 * @inner
10911 */
10912 var TWO_PWR_24_DBL = 1 << 24;
10913
10914 /**
10915 * @type {number}
10916 * @const
10917 * @inner
10918 */
10919 var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
10920
10921 /**
10922 * @type {number}
10923 * @const
10924 * @inner
10925 */
10926 var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
10927
10928 /**
10929 * @type {number}
10930 * @const
10931 * @inner
10932 */
10933 var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
10934
10935 /**
10936 * @type {!Long}
10937 * @const
10938 * @inner
10939 */
10940 var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
10941
10942 /**
10943 * @type {!Long}
10944 * @inner
10945 */
10946 var ZERO = fromInt(0);
10947
10948 /**
10949 * Signed zero.
10950 * @type {!Long}
10951 */
10952 Long.ZERO = ZERO;
10953
10954 /**
10955 * @type {!Long}
10956 * @inner
10957 */
10958 var UZERO = fromInt(0, true);
10959
10960 /**
10961 * Unsigned zero.
10962 * @type {!Long}
10963 */
10964 Long.UZERO = UZERO;
10965
10966 /**
10967 * @type {!Long}
10968 * @inner
10969 */
10970 var ONE = fromInt(1);
10971
10972 /**
10973 * Signed one.
10974 * @type {!Long}
10975 */
10976 Long.ONE = ONE;
10977
10978 /**
10979 * @type {!Long}
10980 * @inner
10981 */
10982 var UONE = fromInt(1, true);
10983
10984 /**
10985 * Unsigned one.
10986 * @type {!Long}
10987 */
10988 Long.UONE = UONE;
10989
10990 /**
10991 * @type {!Long}
10992 * @inner
10993 */
10994 var NEG_ONE = fromInt(-1);
10995
10996 /**
10997 * Signed negative one.
10998 * @type {!Long}
10999 */
11000 Long.NEG_ONE = NEG_ONE;
11001
11002 /**
11003 * @type {!Long}
11004 * @inner
11005 */
11006 var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
11007
11008 /**
11009 * Maximum signed value.
11010 * @type {!Long}
11011 */
11012 Long.MAX_VALUE = MAX_VALUE;
11013
11014 /**
11015 * @type {!Long}
11016 * @inner
11017 */
11018 var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
11019
11020 /**
11021 * Maximum unsigned value.
11022 * @type {!Long}
11023 */
11024 Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
11025
11026 /**
11027 * @type {!Long}
11028 * @inner
11029 */
11030 var MIN_VALUE = fromBits(0, 0x80000000|0, false);
11031
11032 /**
11033 * Minimum signed value.
11034 * @type {!Long}
11035 */
11036 Long.MIN_VALUE = MIN_VALUE;
11037
11038 /**
11039 * @alias Long.prototype
11040 * @inner
11041 */
11042 var LongPrototype = Long.prototype;
11043
11044 /**
11045 * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
11046 * @returns {number}
11047 */
11048 LongPrototype.toInt = function toInt() {
11049 return this.unsigned ? this.low >>> 0 : this.low;
11050 };
11051
11052 /**
11053 * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
11054 * @returns {number}
11055 */
11056 LongPrototype.toNumber = function toNumber() {
11057 if (this.unsigned)
11058 return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
11059 return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
11060 };
11061
11062 /**
11063 * Converts the Long to a string written in the specified radix.
11064 * @param {number=} radix Radix (2-36), defaults to 10
11065 * @returns {string}
11066 * @override
11067 * @throws {RangeError} If `radix` is out of range
11068 */
11069 LongPrototype.toString = function toString(radix) {
11070 radix = radix || 10;
11071 if (radix < 2 || 36 < radix)
11072 throw RangeError('radix');
11073 if (this.isZero())
11074 return '0';
11075 if (this.isNegative()) { // Unsigned Longs are never negative
11076 if (this.eq(MIN_VALUE)) {
11077 // We need to change the Long value before it can be negated, so we remove
11078 // the bottom-most digit in this base and then recurse to do the rest.
11079 var radixLong = fromNumber(radix),
11080 div = this.div(radixLong),
11081 rem1 = div.mul(radixLong).sub(this);
11082 return div.toString(radix) + rem1.toInt().toString(radix);
11083 } else
11084 return '-' + this.neg().toString(radix);
11085 }
11086
11087 // Do several (6) digits each time through the loop, so as to
11088 // minimize the calls to the very expensive emulated div.
11089 var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
11090 rem = this;
11091 var result = '';
11092 while (true) {
11093 var remDiv = rem.div(radixToPower),
11094 intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
11095 digits = intval.toString(radix);
11096 rem = remDiv;
11097 if (rem.isZero())
11098 return digits + result;
11099 else {
11100 while (digits.length < 6)
11101 digits = '0' + digits;
11102 result = '' + digits + result;
11103 }
11104 }
11105 };
11106
11107 /**
11108 * Gets the high 32 bits as a signed integer.
11109 * @returns {number} Signed high bits
11110 */
11111 LongPrototype.getHighBits = function getHighBits() {
11112 return this.high;
11113 };
11114
11115 /**
11116 * Gets the high 32 bits as an unsigned integer.
11117 * @returns {number} Unsigned high bits
11118 */
11119 LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
11120 return this.high >>> 0;
11121 };
11122
11123 /**
11124 * Gets the low 32 bits as a signed integer.
11125 * @returns {number} Signed low bits
11126 */
11127 LongPrototype.getLowBits = function getLowBits() {
11128 return this.low;
11129 };
11130
11131 /**
11132 * Gets the low 32 bits as an unsigned integer.
11133 * @returns {number} Unsigned low bits
11134 */
11135 LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
11136 return this.low >>> 0;
11137 };
11138
11139 /**
11140 * Gets the number of bits needed to represent the absolute value of this Long.
11141 * @returns {number}
11142 */
11143 LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
11144 if (this.isNegative()) // Unsigned Longs are never negative
11145 return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
11146 var val = this.high != 0 ? this.high : this.low;
11147 for (var bit = 31; bit > 0; bit--)
11148 if ((val & (1 << bit)) != 0)
11149 break;
11150 return this.high != 0 ? bit + 33 : bit + 1;
11151 };
11152
11153 /**
11154 * Tests if this Long's value equals zero.
11155 * @returns {boolean}
11156 */
11157 LongPrototype.isZero = function isZero() {
11158 return this.high === 0 && this.low === 0;
11159 };
11160
11161 /**
11162 * Tests if this Long's value is negative.
11163 * @returns {boolean}
11164 */
11165 LongPrototype.isNegative = function isNegative() {
11166 return !this.unsigned && this.high < 0;
11167 };
11168
11169 /**
11170 * Tests if this Long's value is positive.
11171 * @returns {boolean}
11172 */
11173 LongPrototype.isPositive = function isPositive() {
11174 return this.unsigned || this.high >= 0;
11175 };
11176
11177 /**
11178 * Tests if this Long's value is odd.
11179 * @returns {boolean}
11180 */
11181 LongPrototype.isOdd = function isOdd() {
11182 return (this.low & 1) === 1;
11183 };
11184
11185 /**
11186 * Tests if this Long's value is even.
11187 * @returns {boolean}
11188 */
11189 LongPrototype.isEven = function isEven() {
11190 return (this.low & 1) === 0;
11191 };
11192
11193 /**
11194 * Tests if this Long's value equals the specified's.
11195 * @param {!Long|number|string} other Other value
11196 * @returns {boolean}
11197 */
11198 LongPrototype.equals = function equals(other) {
11199 if (!isLong(other))
11200 other = fromValue(other);
11201 if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
11202 return false;
11203 return this.high === other.high && this.low === other.low;
11204 };
11205
11206 /**
11207 * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
11208 * @function
11209 * @param {!Long|number|string} other Other value
11210 * @returns {boolean}
11211 */
11212 LongPrototype.eq = LongPrototype.equals;
11213
11214 /**
11215 * Tests if this Long's value differs from the specified's.
11216 * @param {!Long|number|string} other Other value
11217 * @returns {boolean}
11218 */
11219 LongPrototype.notEquals = function notEquals(other) {
11220 return !this.eq(/* validates */ other);
11221 };
11222
11223 /**
11224 * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
11225 * @function
11226 * @param {!Long|number|string} other Other value
11227 * @returns {boolean}
11228 */
11229 LongPrototype.neq = LongPrototype.notEquals;
11230
11231 /**
11232 * Tests if this Long's value is less than the specified's.
11233 * @param {!Long|number|string} other Other value
11234 * @returns {boolean}
11235 */
11236 LongPrototype.lessThan = function lessThan(other) {
11237 return this.comp(/* validates */ other) < 0;
11238 };
11239
11240 /**
11241 * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
11242 * @function
11243 * @param {!Long|number|string} other Other value
11244 * @returns {boolean}
11245 */
11246 LongPrototype.lt = LongPrototype.lessThan;
11247
11248 /**
11249 * Tests if this Long's value is less than or equal the specified's.
11250 * @param {!Long|number|string} other Other value
11251 * @returns {boolean}
11252 */
11253 LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
11254 return this.comp(/* validates */ other) <= 0;
11255 };
11256
11257 /**
11258 * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
11259 * @function
11260 * @param {!Long|number|string} other Other value
11261 * @returns {boolean}
11262 */
11263 LongPrototype.lte = LongPrototype.lessThanOrEqual;
11264
11265 /**
11266 * Tests if this Long's value is greater than the specified's.
11267 * @param {!Long|number|string} other Other value
11268 * @returns {boolean}
11269 */
11270 LongPrototype.greaterThan = function greaterThan(other) {
11271 return this.comp(/* validates */ other) > 0;
11272 };
11273
11274 /**
11275 * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
11276 * @function
11277 * @param {!Long|number|string} other Other value
11278 * @returns {boolean}
11279 */
11280 LongPrototype.gt = LongPrototype.greaterThan;
11281
11282 /**
11283 * Tests if this Long's value is greater than or equal the specified's.
11284 * @param {!Long|number|string} other Other value
11285 * @returns {boolean}
11286 */
11287 LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
11288 return this.comp(/* validates */ other) >= 0;
11289 };
11290
11291 /**
11292 * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
11293 * @function
11294 * @param {!Long|number|string} other Other value
11295 * @returns {boolean}
11296 */
11297 LongPrototype.gte = LongPrototype.greaterThanOrEqual;
11298
11299 /**
11300 * Compares this Long's value with the specified's.
11301 * @param {!Long|number|string} other Other value
11302 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
11303 * if the given one is greater
11304 */
11305 LongPrototype.compare = function compare(other) {
11306 if (!isLong(other))
11307 other = fromValue(other);
11308 if (this.eq(other))
11309 return 0;
11310 var thisNeg = this.isNegative(),
11311 otherNeg = other.isNegative();
11312 if (thisNeg && !otherNeg)
11313 return -1;
11314 if (!thisNeg && otherNeg)
11315 return 1;
11316 // At this point the sign bits are the same
11317 if (!this.unsigned)
11318 return this.sub(other).isNegative() ? -1 : 1;
11319 // Both are positive if at least one is unsigned
11320 return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
11321 };
11322
11323 /**
11324 * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
11325 * @function
11326 * @param {!Long|number|string} other Other value
11327 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
11328 * if the given one is greater
11329 */
11330 LongPrototype.comp = LongPrototype.compare;
11331
11332 /**
11333 * Negates this Long's value.
11334 * @returns {!Long} Negated Long
11335 */
11336 LongPrototype.negate = function negate() {
11337 if (!this.unsigned && this.eq(MIN_VALUE))
11338 return MIN_VALUE;
11339 return this.not().add(ONE);
11340 };
11341
11342 /**
11343 * Negates this Long's value. This is an alias of {@link Long#negate}.
11344 * @function
11345 * @returns {!Long} Negated Long
11346 */
11347 LongPrototype.neg = LongPrototype.negate;
11348
11349 /**
11350 * Returns the sum of this and the specified Long.
11351 * @param {!Long|number|string} addend Addend
11352 * @returns {!Long} Sum
11353 */
11354 LongPrototype.add = function add(addend) {
11355 if (!isLong(addend))
11356 addend = fromValue(addend);
11357
11358 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
11359
11360 var a48 = this.high >>> 16;
11361 var a32 = this.high & 0xFFFF;
11362 var a16 = this.low >>> 16;
11363 var a00 = this.low & 0xFFFF;
11364
11365 var b48 = addend.high >>> 16;
11366 var b32 = addend.high & 0xFFFF;
11367 var b16 = addend.low >>> 16;
11368 var b00 = addend.low & 0xFFFF;
11369
11370 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
11371 c00 += a00 + b00;
11372 c16 += c00 >>> 16;
11373 c00 &= 0xFFFF;
11374 c16 += a16 + b16;
11375 c32 += c16 >>> 16;
11376 c16 &= 0xFFFF;
11377 c32 += a32 + b32;
11378 c48 += c32 >>> 16;
11379 c32 &= 0xFFFF;
11380 c48 += a48 + b48;
11381 c48 &= 0xFFFF;
11382 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
11383 };
11384
11385 /**
11386 * Returns the difference of this and the specified Long.
11387 * @param {!Long|number|string} subtrahend Subtrahend
11388 * @returns {!Long} Difference
11389 */
11390 LongPrototype.subtract = function subtract(subtrahend) {
11391 if (!isLong(subtrahend))
11392 subtrahend = fromValue(subtrahend);
11393 return this.add(subtrahend.neg());
11394 };
11395
11396 /**
11397 * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
11398 * @function
11399 * @param {!Long|number|string} subtrahend Subtrahend
11400 * @returns {!Long} Difference
11401 */
11402 LongPrototype.sub = LongPrototype.subtract;
11403
11404 /**
11405 * Returns the product of this and the specified Long.
11406 * @param {!Long|number|string} multiplier Multiplier
11407 * @returns {!Long} Product
11408 */
11409 LongPrototype.multiply = function multiply(multiplier) {
11410 if (this.isZero())
11411 return ZERO;
11412 if (!isLong(multiplier))
11413 multiplier = fromValue(multiplier);
11414 if (multiplier.isZero())
11415 return ZERO;
11416 if (this.eq(MIN_VALUE))
11417 return multiplier.isOdd() ? MIN_VALUE : ZERO;
11418 if (multiplier.eq(MIN_VALUE))
11419 return this.isOdd() ? MIN_VALUE : ZERO;
11420
11421 if (this.isNegative()) {
11422 if (multiplier.isNegative())
11423 return this.neg().mul(multiplier.neg());
11424 else
11425 return this.neg().mul(multiplier).neg();
11426 } else if (multiplier.isNegative())
11427 return this.mul(multiplier.neg()).neg();
11428
11429 // If both longs are small, use float multiplication
11430 if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
11431 return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
11432
11433 // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
11434 // We can skip products that would overflow.
11435
11436 var a48 = this.high >>> 16;
11437 var a32 = this.high & 0xFFFF;
11438 var a16 = this.low >>> 16;
11439 var a00 = this.low & 0xFFFF;
11440
11441 var b48 = multiplier.high >>> 16;
11442 var b32 = multiplier.high & 0xFFFF;
11443 var b16 = multiplier.low >>> 16;
11444 var b00 = multiplier.low & 0xFFFF;
11445
11446 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
11447 c00 += a00 * b00;
11448 c16 += c00 >>> 16;
11449 c00 &= 0xFFFF;
11450 c16 += a16 * b00;
11451 c32 += c16 >>> 16;
11452 c16 &= 0xFFFF;
11453 c16 += a00 * b16;
11454 c32 += c16 >>> 16;
11455 c16 &= 0xFFFF;
11456 c32 += a32 * b00;
11457 c48 += c32 >>> 16;
11458 c32 &= 0xFFFF;
11459 c32 += a16 * b16;
11460 c48 += c32 >>> 16;
11461 c32 &= 0xFFFF;
11462 c32 += a00 * b32;
11463 c48 += c32 >>> 16;
11464 c32 &= 0xFFFF;
11465 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
11466 c48 &= 0xFFFF;
11467 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
11468 };
11469
11470 /**
11471 * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
11472 * @function
11473 * @param {!Long|number|string} multiplier Multiplier
11474 * @returns {!Long} Product
11475 */
11476 LongPrototype.mul = LongPrototype.multiply;
11477
11478 /**
11479 * Returns this Long divided by the specified. The result is signed if this Long is signed or
11480 * unsigned if this Long is unsigned.
11481 * @param {!Long|number|string} divisor Divisor
11482 * @returns {!Long} Quotient
11483 */
11484 LongPrototype.divide = function divide(divisor) {
11485 if (!isLong(divisor))
11486 divisor = fromValue(divisor);
11487 if (divisor.isZero())
11488 throw Error('division by zero');
11489 if (this.isZero())
11490 return this.unsigned ? UZERO : ZERO;
11491 var approx, rem, res;
11492 if (!this.unsigned) {
11493 // This section is only relevant for signed longs and is derived from the
11494 // closure library as a whole.
11495 if (this.eq(MIN_VALUE)) {
11496 if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
11497 return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
11498 else if (divisor.eq(MIN_VALUE))
11499 return ONE;
11500 else {
11501 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
11502 var halfThis = this.shr(1);
11503 approx = halfThis.div(divisor).shl(1);
11504 if (approx.eq(ZERO)) {
11505 return divisor.isNegative() ? ONE : NEG_ONE;
11506 } else {
11507 rem = this.sub(divisor.mul(approx));
11508 res = approx.add(rem.div(divisor));
11509 return res;
11510 }
11511 }
11512 } else if (divisor.eq(MIN_VALUE))
11513 return this.unsigned ? UZERO : ZERO;
11514 if (this.isNegative()) {
11515 if (divisor.isNegative())
11516 return this.neg().div(divisor.neg());
11517 return this.neg().div(divisor).neg();
11518 } else if (divisor.isNegative())
11519 return this.div(divisor.neg()).neg();
11520 res = ZERO;
11521 } else {
11522 // The algorithm below has not been made for unsigned longs. It's therefore
11523 // required to take special care of the MSB prior to running it.
11524 if (!divisor.unsigned)
11525 divisor = divisor.toUnsigned();
11526 if (divisor.gt(this))
11527 return UZERO;
11528 if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
11529 return UONE;
11530 res = UZERO;
11531 }
11532
11533 // Repeat the following until the remainder is less than other: find a
11534 // floating-point that approximates remainder / other *from below*, add this
11535 // into the result, and subtract it from the remainder. It is critical that
11536 // the approximate value is less than or equal to the real value so that the
11537 // remainder never becomes negative.
11538 rem = this;
11539 while (rem.gte(divisor)) {
11540 // Approximate the result of division. This may be a little greater or
11541 // smaller than the actual value.
11542 approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
11543
11544 // We will tweak the approximate result by changing it in the 48-th digit or
11545 // the smallest non-fractional digit, whichever is larger.
11546 var log2 = Math.ceil(Math.log(approx) / Math.LN2),
11547 delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
11548
11549 // Decrease the approximation until it is smaller than the remainder. Note
11550 // that if it is too large, the product overflows and is negative.
11551 approxRes = fromNumber(approx),
11552 approxRem = approxRes.mul(divisor);
11553 while (approxRem.isNegative() || approxRem.gt(rem)) {
11554 approx -= delta;
11555 approxRes = fromNumber(approx, this.unsigned);
11556 approxRem = approxRes.mul(divisor);
11557 }
11558
11559 // We know the answer can't be zero... and actually, zero would cause
11560 // infinite recursion since we would make no progress.
11561 if (approxRes.isZero())
11562 approxRes = ONE;
11563
11564 res = res.add(approxRes);
11565 rem = rem.sub(approxRem);
11566 }
11567 return res;
11568 };
11569
11570 /**
11571 * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
11572 * @function
11573 * @param {!Long|number|string} divisor Divisor
11574 * @returns {!Long} Quotient
11575 */
11576 LongPrototype.div = LongPrototype.divide;
11577
11578 /**
11579 * Returns this Long modulo the specified.
11580 * @param {!Long|number|string} divisor Divisor
11581 * @returns {!Long} Remainder
11582 */
11583 LongPrototype.modulo = function modulo(divisor) {
11584 if (!isLong(divisor))
11585 divisor = fromValue(divisor);
11586 return this.sub(this.div(divisor).mul(divisor));
11587 };
11588
11589 /**
11590 * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
11591 * @function
11592 * @param {!Long|number|string} divisor Divisor
11593 * @returns {!Long} Remainder
11594 */
11595 LongPrototype.mod = LongPrototype.modulo;
11596
11597 /**
11598 * Returns the bitwise NOT of this Long.
11599 * @returns {!Long}
11600 */
11601 LongPrototype.not = function not() {
11602 return fromBits(~this.low, ~this.high, this.unsigned);
11603 };
11604
11605 /**
11606 * Returns the bitwise AND of this Long and the specified.
11607 * @param {!Long|number|string} other Other Long
11608 * @returns {!Long}
11609 */
11610 LongPrototype.and = function and(other) {
11611 if (!isLong(other))
11612 other = fromValue(other);
11613 return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
11614 };
11615
11616 /**
11617 * Returns the bitwise OR of this Long and the specified.
11618 * @param {!Long|number|string} other Other Long
11619 * @returns {!Long}
11620 */
11621 LongPrototype.or = function or(other) {
11622 if (!isLong(other))
11623 other = fromValue(other);
11624 return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
11625 };
11626
11627 /**
11628 * Returns the bitwise XOR of this Long and the given one.
11629 * @param {!Long|number|string} other Other Long
11630 * @returns {!Long}
11631 */
11632 LongPrototype.xor = function xor(other) {
11633 if (!isLong(other))
11634 other = fromValue(other);
11635 return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
11636 };
11637
11638 /**
11639 * Returns this Long with bits shifted to the left by the given amount.
11640 * @param {number|!Long} numBits Number of bits
11641 * @returns {!Long} Shifted Long
11642 */
11643 LongPrototype.shiftLeft = function shiftLeft(numBits) {
11644 if (isLong(numBits))
11645 numBits = numBits.toInt();
11646 if ((numBits &= 63) === 0)
11647 return this;
11648 else if (numBits < 32)
11649 return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
11650 else
11651 return fromBits(0, this.low << (numBits - 32), this.unsigned);
11652 };
11653
11654 /**
11655 * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
11656 * @function
11657 * @param {number|!Long} numBits Number of bits
11658 * @returns {!Long} Shifted Long
11659 */
11660 LongPrototype.shl = LongPrototype.shiftLeft;
11661
11662 /**
11663 * Returns this Long with bits arithmetically shifted to the right by the given amount.
11664 * @param {number|!Long} numBits Number of bits
11665 * @returns {!Long} Shifted Long
11666 */
11667 LongPrototype.shiftRight = function shiftRight(numBits) {
11668 if (isLong(numBits))
11669 numBits = numBits.toInt();
11670 if ((numBits &= 63) === 0)
11671 return this;
11672 else if (numBits < 32)
11673 return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
11674 else
11675 return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
11676 };
11677
11678 /**
11679 * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
11680 * @function
11681 * @param {number|!Long} numBits Number of bits
11682 * @returns {!Long} Shifted Long
11683 */
11684 LongPrototype.shr = LongPrototype.shiftRight;
11685
11686 /**
11687 * Returns this Long with bits logically shifted to the right by the given amount.
11688 * @param {number|!Long} numBits Number of bits
11689 * @returns {!Long} Shifted Long
11690 */
11691 LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
11692 if (isLong(numBits))
11693 numBits = numBits.toInt();
11694 numBits &= 63;
11695 if (numBits === 0)
11696 return this;
11697 else {
11698 var high = this.high;
11699 if (numBits < 32) {
11700 var low = this.low;
11701 return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
11702 } else if (numBits === 32)
11703 return fromBits(high, 0, this.unsigned);
11704 else
11705 return fromBits(high >>> (numBits - 32), 0, this.unsigned);
11706 }
11707 };
11708
11709 /**
11710 * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
11711 * @function
11712 * @param {number|!Long} numBits Number of bits
11713 * @returns {!Long} Shifted Long
11714 */
11715 LongPrototype.shru = LongPrototype.shiftRightUnsigned;
11716
11717 /**
11718 * Converts this Long to signed.
11719 * @returns {!Long} Signed long
11720 */
11721 LongPrototype.toSigned = function toSigned() {
11722 if (!this.unsigned)
11723 return this;
11724 return fromBits(this.low, this.high, false);
11725 };
11726
11727 /**
11728 * Converts this Long to unsigned.
11729 * @returns {!Long} Unsigned long
11730 */
11731 LongPrototype.toUnsigned = function toUnsigned() {
11732 if (this.unsigned)
11733 return this;
11734 return fromBits(this.low, this.high, true);
11735 };
11736
11737 /**
11738 * Converts this Long to its byte representation.
11739 * @param {boolean=} le Whether little or big endian, defaults to big endian
11740 * @returns {!Array.<number>} Byte representation
11741 */
11742 LongPrototype.toBytes = function(le) {
11743 return le ? this.toBytesLE() : this.toBytesBE();
11744 }
11745
11746 /**
11747 * Converts this Long to its little endian byte representation.
11748 * @returns {!Array.<number>} Little endian byte representation
11749 */
11750 LongPrototype.toBytesLE = function() {
11751 var hi = this.high,
11752 lo = this.low;
11753 return [
11754 lo & 0xff,
11755 (lo >>> 8) & 0xff,
11756 (lo >>> 16) & 0xff,
11757 (lo >>> 24) & 0xff,
11758 hi & 0xff,
11759 (hi >>> 8) & 0xff,
11760 (hi >>> 16) & 0xff,
11761 (hi >>> 24) & 0xff
11762 ];
11763 }
11764
11765 /**
11766 * Converts this Long to its big endian byte representation.
11767 * @returns {!Array.<number>} Big endian byte representation
11768 */
11769 LongPrototype.toBytesBE = function() {
11770 var hi = this.high,
11771 lo = this.low;
11772 return [
11773 (hi >>> 24) & 0xff,
11774 (hi >>> 16) & 0xff,
11775 (hi >>> 8) & 0xff,
11776 hi & 0xff,
11777 (lo >>> 24) & 0xff,
11778 (lo >>> 16) & 0xff,
11779 (lo >>> 8) & 0xff,
11780 lo & 0xff
11781 ];
11782 }
11783
11784 return Long;
11785});
11786
11787},{}],49:[function(require,module,exports){
11788(function (Buffer){
11789'use strict'
11790var inherits = require('inherits')
11791var HashBase = require('hash-base')
11792
11793var ARRAY16 = new Array(16)
11794
11795function MD5 () {
11796 HashBase.call(this, 64)
11797
11798 // state
11799 this._a = 0x67452301
11800 this._b = 0xefcdab89
11801 this._c = 0x98badcfe
11802 this._d = 0x10325476
11803}
11804
11805inherits(MD5, HashBase)
11806
11807MD5.prototype._update = function () {
11808 var M = ARRAY16
11809 for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)
11810
11811 var a = this._a
11812 var b = this._b
11813 var c = this._c
11814 var d = this._d
11815
11816 a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
11817 d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
11818 c = fnF(c, d, a, b, M[2], 0x242070db, 17)
11819 b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
11820 a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
11821 d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
11822 c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
11823 b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
11824 a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
11825 d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
11826 c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
11827 b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
11828 a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
11829 d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
11830 c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
11831 b = fnF(b, c, d, a, M[15], 0x49b40821, 22)
11832
11833 a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
11834 d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
11835 c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
11836 b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
11837 a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
11838 d = fnG(d, a, b, c, M[10], 0x02441453, 9)
11839 c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
11840 b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
11841 a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
11842 d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
11843 c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
11844 b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
11845 a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
11846 d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
11847 c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
11848 b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)
11849
11850 a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
11851 d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
11852 c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
11853 b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
11854 a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
11855 d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
11856 c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
11857 b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
11858 a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
11859 d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
11860 c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
11861 b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
11862 a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
11863 d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
11864 c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
11865 b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)
11866
11867 a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
11868 d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
11869 c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
11870 b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
11871 a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
11872 d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
11873 c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
11874 b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
11875 a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
11876 d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
11877 c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
11878 b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
11879 a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
11880 d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
11881 c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
11882 b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)
11883
11884 this._a = (this._a + a) | 0
11885 this._b = (this._b + b) | 0
11886 this._c = (this._c + c) | 0
11887 this._d = (this._d + d) | 0
11888}
11889
11890MD5.prototype._digest = function () {
11891 // create padding and handle blocks
11892 this._block[this._blockOffset++] = 0x80
11893 if (this._blockOffset > 56) {
11894 this._block.fill(0, this._blockOffset, 64)
11895 this._update()
11896 this._blockOffset = 0
11897 }
11898
11899 this._block.fill(0, this._blockOffset, 56)
11900 this._block.writeUInt32LE(this._length[0], 56)
11901 this._block.writeUInt32LE(this._length[1], 60)
11902 this._update()
11903
11904 // produce result
11905 var buffer = new Buffer(16)
11906 buffer.writeInt32LE(this._a, 0)
11907 buffer.writeInt32LE(this._b, 4)
11908 buffer.writeInt32LE(this._c, 8)
11909 buffer.writeInt32LE(this._d, 12)
11910 return buffer
11911}
11912
11913function rotl (x, n) {
11914 return (x << n) | (x >>> (32 - n))
11915}
11916
11917function fnF (a, b, c, d, m, k, s) {
11918 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
11919}
11920
11921function fnG (a, b, c, d, m, k, s) {
11922 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
11923}
11924
11925function fnH (a, b, c, d, m, k, s) {
11926 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
11927}
11928
11929function fnI (a, b, c, d, m, k, s) {
11930 return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
11931}
11932
11933module.exports = MD5
11934
11935}).call(this,require("buffer").Buffer)
11936},{"buffer":27,"hash-base":50,"inherits":45}],50:[function(require,module,exports){
11937'use strict'
11938var Buffer = require('safe-buffer').Buffer
11939var Transform = require('stream').Transform
11940var inherits = require('inherits')
11941
11942function throwIfNotStringOrBuffer (val, prefix) {
11943 if (!Buffer.isBuffer(val) && typeof val !== 'string') {
11944 throw new TypeError(prefix + ' must be a string or a buffer')
11945 }
11946}
11947
11948function HashBase (blockSize) {
11949 Transform.call(this)
11950
11951 this._block = Buffer.allocUnsafe(blockSize)
11952 this._blockSize = blockSize
11953 this._blockOffset = 0
11954 this._length = [0, 0, 0, 0]
11955
11956 this._finalized = false
11957}
11958
11959inherits(HashBase, Transform)
11960
11961HashBase.prototype._transform = function (chunk, encoding, callback) {
11962 var error = null
11963 try {
11964 this.update(chunk, encoding)
11965 } catch (err) {
11966 error = err
11967 }
11968
11969 callback(error)
11970}
11971
11972HashBase.prototype._flush = function (callback) {
11973 var error = null
11974 try {
11975 this.push(this.digest())
11976 } catch (err) {
11977 error = err
11978 }
11979
11980 callback(error)
11981}
11982
11983HashBase.prototype.update = function (data, encoding) {
11984 throwIfNotStringOrBuffer(data, 'Data')
11985 if (this._finalized) throw new Error('Digest already called')
11986 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
11987
11988 // consume data
11989 var block = this._block
11990 var offset = 0
11991 while (this._blockOffset + data.length - offset >= this._blockSize) {
11992 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
11993 this._update()
11994 this._blockOffset = 0
11995 }
11996 while (offset < data.length) block[this._blockOffset++] = data[offset++]
11997
11998 // update length
11999 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
12000 this._length[j] += carry
12001 carry = (this._length[j] / 0x0100000000) | 0
12002 if (carry > 0) this._length[j] -= 0x0100000000 * carry
12003 }
12004
12005 return this
12006}
12007
12008HashBase.prototype._update = function () {
12009 throw new Error('_update is not implemented')
12010}
12011
12012HashBase.prototype.digest = function (encoding) {
12013 if (this._finalized) throw new Error('Digest already called')
12014 this._finalized = true
12015
12016 var digest = this._digest()
12017 if (encoding !== undefined) digest = digest.toString(encoding)
12018
12019 // reset state
12020 this._block.fill(0)
12021 this._blockOffset = 0
12022 for (var i = 0; i < 4; ++i) this._length[i] = 0
12023
12024 return digest
12025}
12026
12027HashBase.prototype._digest = function () {
12028 throw new Error('_digest is not implemented')
12029}
12030
12031module.exports = HashBase
12032
12033},{"inherits":45,"safe-buffer":68,"stream":77}],51:[function(require,module,exports){
12034(function (process){
12035'use strict';
12036
12037if (!process.version ||
12038 process.version.indexOf('v0.') === 0 ||
12039 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
12040 module.exports = nextTick;
12041} else {
12042 module.exports = process.nextTick;
12043}
12044
12045function nextTick(fn, arg1, arg2, arg3) {
12046 if (typeof fn !== 'function') {
12047 throw new TypeError('"callback" argument must be a function');
12048 }
12049 var len = arguments.length;
12050 var args, i;
12051 switch (len) {
12052 case 0:
12053 case 1:
12054 return process.nextTick(fn);
12055 case 2:
12056 return process.nextTick(function afterTickOne() {
12057 fn.call(null, arg1);
12058 });
12059 case 3:
12060 return process.nextTick(function afterTickTwo() {
12061 fn.call(null, arg1, arg2);
12062 });
12063 case 4:
12064 return process.nextTick(function afterTickThree() {
12065 fn.call(null, arg1, arg2, arg3);
12066 });
12067 default:
12068 args = new Array(len - 1);
12069 i = 0;
12070 while (i < args.length) {
12071 args[i++] = arguments[i];
12072 }
12073 return process.nextTick(function afterTick() {
12074 fn.apply(null, args);
12075 });
12076 }
12077}
12078
12079}).call(this,require('_process'))
12080},{"_process":52}],52:[function(require,module,exports){
12081// shim for using process in browser
12082var process = module.exports = {};
12083
12084// cached from whatever global is present so that test runners that stub it
12085// don't break things. But we need to wrap it in a try catch in case it is
12086// wrapped in strict mode code which doesn't define any globals. It's inside a
12087// function because try/catches deoptimize in certain engines.
12088
12089var cachedSetTimeout;
12090var cachedClearTimeout;
12091
12092function defaultSetTimout() {
12093 throw new Error('setTimeout has not been defined');
12094}
12095function defaultClearTimeout () {
12096 throw new Error('clearTimeout has not been defined');
12097}
12098(function () {
12099 try {
12100 if (typeof setTimeout === 'function') {
12101 cachedSetTimeout = setTimeout;
12102 } else {
12103 cachedSetTimeout = defaultSetTimout;
12104 }
12105 } catch (e) {
12106 cachedSetTimeout = defaultSetTimout;
12107 }
12108 try {
12109 if (typeof clearTimeout === 'function') {
12110 cachedClearTimeout = clearTimeout;
12111 } else {
12112 cachedClearTimeout = defaultClearTimeout;
12113 }
12114 } catch (e) {
12115 cachedClearTimeout = defaultClearTimeout;
12116 }
12117} ())
12118function runTimeout(fun) {
12119 if (cachedSetTimeout === setTimeout) {
12120 //normal enviroments in sane situations
12121 return setTimeout(fun, 0);
12122 }
12123 // if setTimeout wasn't available but was latter defined
12124 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
12125 cachedSetTimeout = setTimeout;
12126 return setTimeout(fun, 0);
12127 }
12128 try {
12129 // when when somebody has screwed with setTimeout but no I.E. maddness
12130 return cachedSetTimeout(fun, 0);
12131 } catch(e){
12132 try {
12133 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
12134 return cachedSetTimeout.call(null, fun, 0);
12135 } catch(e){
12136 // 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
12137 return cachedSetTimeout.call(this, fun, 0);
12138 }
12139 }
12140
12141
12142}
12143function runClearTimeout(marker) {
12144 if (cachedClearTimeout === clearTimeout) {
12145 //normal enviroments in sane situations
12146 return clearTimeout(marker);
12147 }
12148 // if clearTimeout wasn't available but was latter defined
12149 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
12150 cachedClearTimeout = clearTimeout;
12151 return clearTimeout(marker);
12152 }
12153 try {
12154 // when when somebody has screwed with setTimeout but no I.E. maddness
12155 return cachedClearTimeout(marker);
12156 } catch (e){
12157 try {
12158 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
12159 return cachedClearTimeout.call(null, marker);
12160 } catch (e){
12161 // 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.
12162 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
12163 return cachedClearTimeout.call(this, marker);
12164 }
12165 }
12166
12167
12168
12169}
12170var queue = [];
12171var draining = false;
12172var currentQueue;
12173var queueIndex = -1;
12174
12175function cleanUpNextTick() {
12176 if (!draining || !currentQueue) {
12177 return;
12178 }
12179 draining = false;
12180 if (currentQueue.length) {
12181 queue = currentQueue.concat(queue);
12182 } else {
12183 queueIndex = -1;
12184 }
12185 if (queue.length) {
12186 drainQueue();
12187 }
12188}
12189
12190function drainQueue() {
12191 if (draining) {
12192 return;
12193 }
12194 var timeout = runTimeout(cleanUpNextTick);
12195 draining = true;
12196
12197 var len = queue.length;
12198 while(len) {
12199 currentQueue = queue;
12200 queue = [];
12201 while (++queueIndex < len) {
12202 if (currentQueue) {
12203 currentQueue[queueIndex].run();
12204 }
12205 }
12206 queueIndex = -1;
12207 len = queue.length;
12208 }
12209 currentQueue = null;
12210 draining = false;
12211 runClearTimeout(timeout);
12212}
12213
12214process.nextTick = function (fun) {
12215 var args = new Array(arguments.length - 1);
12216 if (arguments.length > 1) {
12217 for (var i = 1; i < arguments.length; i++) {
12218 args[i - 1] = arguments[i];
12219 }
12220 }
12221 queue.push(new Item(fun, args));
12222 if (queue.length === 1 && !draining) {
12223 runTimeout(drainQueue);
12224 }
12225};
12226
12227// v8 likes predictible objects
12228function Item(fun, array) {
12229 this.fun = fun;
12230 this.array = array;
12231}
12232Item.prototype.run = function () {
12233 this.fun.apply(null, this.array);
12234};
12235process.title = 'browser';
12236process.browser = true;
12237process.env = {};
12238process.argv = [];
12239process.version = ''; // empty string to avoid regexp issues
12240process.versions = {};
12241
12242function noop() {}
12243
12244process.on = noop;
12245process.addListener = noop;
12246process.once = noop;
12247process.off = noop;
12248process.removeListener = noop;
12249process.removeAllListeners = noop;
12250process.emit = noop;
12251process.prependListener = noop;
12252process.prependOnceListener = noop;
12253
12254process.listeners = function (name) { return [] }
12255
12256process.binding = function (name) {
12257 throw new Error('process.binding is not supported');
12258};
12259
12260process.cwd = function () { return '/' };
12261process.chdir = function (dir) {
12262 throw new Error('process.chdir is not supported');
12263};
12264process.umask = function() { return 0; };
12265
12266},{}],53:[function(require,module,exports){
12267(function (process,global){
12268'use strict'
12269
12270function oldBrowser () {
12271 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
12272}
12273
12274var Buffer = require('safe-buffer').Buffer
12275var crypto = global.crypto || global.msCrypto
12276
12277if (crypto && crypto.getRandomValues) {
12278 module.exports = randomBytes
12279} else {
12280 module.exports = oldBrowser
12281}
12282
12283function randomBytes (size, cb) {
12284 // phantomjs needs to throw
12285 if (size > 65536) throw new Error('requested too many random bytes')
12286 // in case browserify isn't using the Uint8Array version
12287 var rawBytes = new global.Uint8Array(size)
12288
12289 // This will not work in older browsers.
12290 // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
12291 if (size > 0) { // getRandomValues fails on IE if size == 0
12292 crypto.getRandomValues(rawBytes)
12293 }
12294
12295 // XXX: phantomjs doesn't like a buffer being passed here
12296 var bytes = Buffer.from(rawBytes.buffer)
12297
12298 if (typeof cb === 'function') {
12299 return process.nextTick(function () {
12300 cb(null, bytes)
12301 })
12302 }
12303
12304 return bytes
12305}
12306
12307}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
12308},{"_process":52,"safe-buffer":68}],54:[function(require,module,exports){
12309module.exports = require('./lib/_stream_duplex.js');
12310
12311},{"./lib/_stream_duplex.js":55}],55:[function(require,module,exports){
12312// Copyright Joyent, Inc. and other Node contributors.
12313//
12314// Permission is hereby granted, free of charge, to any person obtaining a
12315// copy of this software and associated documentation files (the
12316// "Software"), to deal in the Software without restriction, including
12317// without limitation the rights to use, copy, modify, merge, publish,
12318// distribute, sublicense, and/or sell copies of the Software, and to permit
12319// persons to whom the Software is furnished to do so, subject to the
12320// following conditions:
12321//
12322// The above copyright notice and this permission notice shall be included
12323// in all copies or substantial portions of the Software.
12324//
12325// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12326// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12327// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12328// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12329// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12330// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12331// USE OR OTHER DEALINGS IN THE SOFTWARE.
12332
12333// a duplex stream is just a stream that is both readable and writable.
12334// Since JS doesn't have multiple prototypal inheritance, this class
12335// prototypally inherits from Readable, and then parasitically from
12336// Writable.
12337
12338'use strict';
12339
12340/*<replacement>*/
12341
12342var processNextTick = require('process-nextick-args');
12343/*</replacement>*/
12344
12345/*<replacement>*/
12346var objectKeys = Object.keys || function (obj) {
12347 var keys = [];
12348 for (var key in obj) {
12349 keys.push(key);
12350 }return keys;
12351};
12352/*</replacement>*/
12353
12354module.exports = Duplex;
12355
12356/*<replacement>*/
12357var util = require('core-util-is');
12358util.inherits = require('inherits');
12359/*</replacement>*/
12360
12361var Readable = require('./_stream_readable');
12362var Writable = require('./_stream_writable');
12363
12364util.inherits(Duplex, Readable);
12365
12366var keys = objectKeys(Writable.prototype);
12367for (var v = 0; v < keys.length; v++) {
12368 var method = keys[v];
12369 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
12370}
12371
12372function Duplex(options) {
12373 if (!(this instanceof Duplex)) return new Duplex(options);
12374
12375 Readable.call(this, options);
12376 Writable.call(this, options);
12377
12378 if (options && options.readable === false) this.readable = false;
12379
12380 if (options && options.writable === false) this.writable = false;
12381
12382 this.allowHalfOpen = true;
12383 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
12384
12385 this.once('end', onend);
12386}
12387
12388// the no-half-open enforcer
12389function onend() {
12390 // if we allow half-open state, or if the writable side ended,
12391 // then we're ok.
12392 if (this.allowHalfOpen || this._writableState.ended) return;
12393
12394 // no more data can be written.
12395 // But allow more writes to happen in this tick.
12396 processNextTick(onEndNT, this);
12397}
12398
12399function onEndNT(self) {
12400 self.end();
12401}
12402
12403Object.defineProperty(Duplex.prototype, 'destroyed', {
12404 get: function () {
12405 if (this._readableState === undefined || this._writableState === undefined) {
12406 return false;
12407 }
12408 return this._readableState.destroyed && this._writableState.destroyed;
12409 },
12410 set: function (value) {
12411 // we ignore the value if the stream
12412 // has not been initialized yet
12413 if (this._readableState === undefined || this._writableState === undefined) {
12414 return;
12415 }
12416
12417 // backward compatibility, the user is explicitly
12418 // managing destroyed
12419 this._readableState.destroyed = value;
12420 this._writableState.destroyed = value;
12421 }
12422});
12423
12424Duplex.prototype._destroy = function (err, cb) {
12425 this.push(null);
12426 this.end();
12427
12428 processNextTick(cb, err);
12429};
12430
12431function forEach(xs, f) {
12432 for (var i = 0, l = xs.length; i < l; i++) {
12433 f(xs[i], i);
12434 }
12435}
12436},{"./_stream_readable":57,"./_stream_writable":59,"core-util-is":30,"inherits":45,"process-nextick-args":51}],56:[function(require,module,exports){
12437// Copyright Joyent, Inc. and other Node contributors.
12438//
12439// Permission is hereby granted, free of charge, to any person obtaining a
12440// copy of this software and associated documentation files (the
12441// "Software"), to deal in the Software without restriction, including
12442// without limitation the rights to use, copy, modify, merge, publish,
12443// distribute, sublicense, and/or sell copies of the Software, and to permit
12444// persons to whom the Software is furnished to do so, subject to the
12445// following conditions:
12446//
12447// The above copyright notice and this permission notice shall be included
12448// in all copies or substantial portions of the Software.
12449//
12450// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12451// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12452// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12453// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12454// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12455// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12456// USE OR OTHER DEALINGS IN THE SOFTWARE.
12457
12458// a passthrough stream.
12459// basically just the most minimal sort of Transform stream.
12460// Every written chunk gets output as-is.
12461
12462'use strict';
12463
12464module.exports = PassThrough;
12465
12466var Transform = require('./_stream_transform');
12467
12468/*<replacement>*/
12469var util = require('core-util-is');
12470util.inherits = require('inherits');
12471/*</replacement>*/
12472
12473util.inherits(PassThrough, Transform);
12474
12475function PassThrough(options) {
12476 if (!(this instanceof PassThrough)) return new PassThrough(options);
12477
12478 Transform.call(this, options);
12479}
12480
12481PassThrough.prototype._transform = function (chunk, encoding, cb) {
12482 cb(null, chunk);
12483};
12484},{"./_stream_transform":58,"core-util-is":30,"inherits":45}],57:[function(require,module,exports){
12485(function (process,global){
12486// Copyright Joyent, Inc. and other Node contributors.
12487//
12488// Permission is hereby granted, free of charge, to any person obtaining a
12489// copy of this software and associated documentation files (the
12490// "Software"), to deal in the Software without restriction, including
12491// without limitation the rights to use, copy, modify, merge, publish,
12492// distribute, sublicense, and/or sell copies of the Software, and to permit
12493// persons to whom the Software is furnished to do so, subject to the
12494// following conditions:
12495//
12496// The above copyright notice and this permission notice shall be included
12497// in all copies or substantial portions of the Software.
12498//
12499// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12500// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12501// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12502// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12503// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12504// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12505// USE OR OTHER DEALINGS IN THE SOFTWARE.
12506
12507'use strict';
12508
12509/*<replacement>*/
12510
12511var processNextTick = require('process-nextick-args');
12512/*</replacement>*/
12513
12514module.exports = Readable;
12515
12516/*<replacement>*/
12517var isArray = require('isarray');
12518/*</replacement>*/
12519
12520/*<replacement>*/
12521var Duplex;
12522/*</replacement>*/
12523
12524Readable.ReadableState = ReadableState;
12525
12526/*<replacement>*/
12527var EE = require('events').EventEmitter;
12528
12529var EElistenerCount = function (emitter, type) {
12530 return emitter.listeners(type).length;
12531};
12532/*</replacement>*/
12533
12534/*<replacement>*/
12535var Stream = require('./internal/streams/stream');
12536/*</replacement>*/
12537
12538// TODO(bmeurer): Change this back to const once hole checks are
12539// properly optimized away early in Ignition+TurboFan.
12540/*<replacement>*/
12541var Buffer = require('safe-buffer').Buffer;
12542var OurUint8Array = global.Uint8Array || function () {};
12543function _uint8ArrayToBuffer(chunk) {
12544 return Buffer.from(chunk);
12545}
12546function _isUint8Array(obj) {
12547 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
12548}
12549/*</replacement>*/
12550
12551/*<replacement>*/
12552var util = require('core-util-is');
12553util.inherits = require('inherits');
12554/*</replacement>*/
12555
12556/*<replacement>*/
12557var debugUtil = require('util');
12558var debug = void 0;
12559if (debugUtil && debugUtil.debuglog) {
12560 debug = debugUtil.debuglog('stream');
12561} else {
12562 debug = function () {};
12563}
12564/*</replacement>*/
12565
12566var BufferList = require('./internal/streams/BufferList');
12567var destroyImpl = require('./internal/streams/destroy');
12568var StringDecoder;
12569
12570util.inherits(Readable, Stream);
12571
12572var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
12573
12574function prependListener(emitter, event, fn) {
12575 // Sadly this is not cacheable as some libraries bundle their own
12576 // event emitter implementation with them.
12577 if (typeof emitter.prependListener === 'function') {
12578 return emitter.prependListener(event, fn);
12579 } else {
12580 // This is a hack to make sure that our error handler is attached before any
12581 // userland ones. NEVER DO THIS. This is here only because this code needs
12582 // to continue to work with older versions of Node.js that do not include
12583 // the prependListener() method. The goal is to eventually remove this hack.
12584 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
12585 }
12586}
12587
12588function ReadableState(options, stream) {
12589 Duplex = Duplex || require('./_stream_duplex');
12590
12591 options = options || {};
12592
12593 // object stream flag. Used to make read(n) ignore n and to
12594 // make all the buffer merging and length checks go away
12595 this.objectMode = !!options.objectMode;
12596
12597 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
12598
12599 // the point at which it stops calling _read() to fill the buffer
12600 // Note: 0 is a valid value, means "don't call _read preemptively ever"
12601 var hwm = options.highWaterMark;
12602 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
12603 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
12604
12605 // cast to ints.
12606 this.highWaterMark = Math.floor(this.highWaterMark);
12607
12608 // A linked list is used to store data chunks instead of an array because the
12609 // linked list can remove elements from the beginning faster than
12610 // array.shift()
12611 this.buffer = new BufferList();
12612 this.length = 0;
12613 this.pipes = null;
12614 this.pipesCount = 0;
12615 this.flowing = null;
12616 this.ended = false;
12617 this.endEmitted = false;
12618 this.reading = false;
12619
12620 // a flag to be able to tell if the event 'readable'/'data' is emitted
12621 // immediately, or on a later tick. We set this to true at first, because
12622 // any actions that shouldn't happen until "later" should generally also
12623 // not happen before the first read call.
12624 this.sync = true;
12625
12626 // whenever we return null, then we set a flag to say
12627 // that we're awaiting a 'readable' event emission.
12628 this.needReadable = false;
12629 this.emittedReadable = false;
12630 this.readableListening = false;
12631 this.resumeScheduled = false;
12632
12633 // has it been destroyed
12634 this.destroyed = false;
12635
12636 // Crypto is kind of old and crusty. Historically, its default string
12637 // encoding is 'binary' so we have to make this configurable.
12638 // Everything else in the universe uses 'utf8', though.
12639 this.defaultEncoding = options.defaultEncoding || 'utf8';
12640
12641 // the number of writers that are awaiting a drain event in .pipe()s
12642 this.awaitDrain = 0;
12643
12644 // if true, a maybeReadMore has been scheduled
12645 this.readingMore = false;
12646
12647 this.decoder = null;
12648 this.encoding = null;
12649 if (options.encoding) {
12650 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
12651 this.decoder = new StringDecoder(options.encoding);
12652 this.encoding = options.encoding;
12653 }
12654}
12655
12656function Readable(options) {
12657 Duplex = Duplex || require('./_stream_duplex');
12658
12659 if (!(this instanceof Readable)) return new Readable(options);
12660
12661 this._readableState = new ReadableState(options, this);
12662
12663 // legacy
12664 this.readable = true;
12665
12666 if (options) {
12667 if (typeof options.read === 'function') this._read = options.read;
12668
12669 if (typeof options.destroy === 'function') this._destroy = options.destroy;
12670 }
12671
12672 Stream.call(this);
12673}
12674
12675Object.defineProperty(Readable.prototype, 'destroyed', {
12676 get: function () {
12677 if (this._readableState === undefined) {
12678 return false;
12679 }
12680 return this._readableState.destroyed;
12681 },
12682 set: function (value) {
12683 // we ignore the value if the stream
12684 // has not been initialized yet
12685 if (!this._readableState) {
12686 return;
12687 }
12688
12689 // backward compatibility, the user is explicitly
12690 // managing destroyed
12691 this._readableState.destroyed = value;
12692 }
12693});
12694
12695Readable.prototype.destroy = destroyImpl.destroy;
12696Readable.prototype._undestroy = destroyImpl.undestroy;
12697Readable.prototype._destroy = function (err, cb) {
12698 this.push(null);
12699 cb(err);
12700};
12701
12702// Manually shove something into the read() buffer.
12703// This returns true if the highWaterMark has not been hit yet,
12704// similar to how Writable.write() returns true if you should
12705// write() some more.
12706Readable.prototype.push = function (chunk, encoding) {
12707 var state = this._readableState;
12708 var skipChunkCheck;
12709
12710 if (!state.objectMode) {
12711 if (typeof chunk === 'string') {
12712 encoding = encoding || state.defaultEncoding;
12713 if (encoding !== state.encoding) {
12714 chunk = Buffer.from(chunk, encoding);
12715 encoding = '';
12716 }
12717 skipChunkCheck = true;
12718 }
12719 } else {
12720 skipChunkCheck = true;
12721 }
12722
12723 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
12724};
12725
12726// Unshift should *always* be something directly out of read()
12727Readable.prototype.unshift = function (chunk) {
12728 return readableAddChunk(this, chunk, null, true, false);
12729};
12730
12731function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
12732 var state = stream._readableState;
12733 if (chunk === null) {
12734 state.reading = false;
12735 onEofChunk(stream, state);
12736 } else {
12737 var er;
12738 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
12739 if (er) {
12740 stream.emit('error', er);
12741 } else if (state.objectMode || chunk && chunk.length > 0) {
12742 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
12743 chunk = _uint8ArrayToBuffer(chunk);
12744 }
12745
12746 if (addToFront) {
12747 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
12748 } else if (state.ended) {
12749 stream.emit('error', new Error('stream.push() after EOF'));
12750 } else {
12751 state.reading = false;
12752 if (state.decoder && !encoding) {
12753 chunk = state.decoder.write(chunk);
12754 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
12755 } else {
12756 addChunk(stream, state, chunk, false);
12757 }
12758 }
12759 } else if (!addToFront) {
12760 state.reading = false;
12761 }
12762 }
12763
12764 return needMoreData(state);
12765}
12766
12767function addChunk(stream, state, chunk, addToFront) {
12768 if (state.flowing && state.length === 0 && !state.sync) {
12769 stream.emit('data', chunk);
12770 stream.read(0);
12771 } else {
12772 // update the buffer info.
12773 state.length += state.objectMode ? 1 : chunk.length;
12774 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
12775
12776 if (state.needReadable) emitReadable(stream);
12777 }
12778 maybeReadMore(stream, state);
12779}
12780
12781function chunkInvalid(state, chunk) {
12782 var er;
12783 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
12784 er = new TypeError('Invalid non-string/buffer chunk');
12785 }
12786 return er;
12787}
12788
12789// if it's past the high water mark, we can push in some more.
12790// Also, if we have no data yet, we can stand some
12791// more bytes. This is to work around cases where hwm=0,
12792// such as the repl. Also, if the push() triggered a
12793// readable event, and the user called read(largeNumber) such that
12794// needReadable was set, then we ought to push more, so that another
12795// 'readable' event will be triggered.
12796function needMoreData(state) {
12797 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
12798}
12799
12800Readable.prototype.isPaused = function () {
12801 return this._readableState.flowing === false;
12802};
12803
12804// backwards compatibility.
12805Readable.prototype.setEncoding = function (enc) {
12806 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
12807 this._readableState.decoder = new StringDecoder(enc);
12808 this._readableState.encoding = enc;
12809 return this;
12810};
12811
12812// Don't raise the hwm > 8MB
12813var MAX_HWM = 0x800000;
12814function computeNewHighWaterMark(n) {
12815 if (n >= MAX_HWM) {
12816 n = MAX_HWM;
12817 } else {
12818 // Get the next highest power of 2 to prevent increasing hwm excessively in
12819 // tiny amounts
12820 n--;
12821 n |= n >>> 1;
12822 n |= n >>> 2;
12823 n |= n >>> 4;
12824 n |= n >>> 8;
12825 n |= n >>> 16;
12826 n++;
12827 }
12828 return n;
12829}
12830
12831// This function is designed to be inlinable, so please take care when making
12832// changes to the function body.
12833function howMuchToRead(n, state) {
12834 if (n <= 0 || state.length === 0 && state.ended) return 0;
12835 if (state.objectMode) return 1;
12836 if (n !== n) {
12837 // Only flow one buffer at a time
12838 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
12839 }
12840 // If we're asking for more than the current hwm, then raise the hwm.
12841 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
12842 if (n <= state.length) return n;
12843 // Don't have enough
12844 if (!state.ended) {
12845 state.needReadable = true;
12846 return 0;
12847 }
12848 return state.length;
12849}
12850
12851// you can override either this method, or the async _read(n) below.
12852Readable.prototype.read = function (n) {
12853 debug('read', n);
12854 n = parseInt(n, 10);
12855 var state = this._readableState;
12856 var nOrig = n;
12857
12858 if (n !== 0) state.emittedReadable = false;
12859
12860 // if we're doing read(0) to trigger a readable event, but we
12861 // already have a bunch of data in the buffer, then just trigger
12862 // the 'readable' event and move on.
12863 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
12864 debug('read: emitReadable', state.length, state.ended);
12865 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
12866 return null;
12867 }
12868
12869 n = howMuchToRead(n, state);
12870
12871 // if we've ended, and we're now clear, then finish it up.
12872 if (n === 0 && state.ended) {
12873 if (state.length === 0) endReadable(this);
12874 return null;
12875 }
12876
12877 // All the actual chunk generation logic needs to be
12878 // *below* the call to _read. The reason is that in certain
12879 // synthetic stream cases, such as passthrough streams, _read
12880 // may be a completely synchronous operation which may change
12881 // the state of the read buffer, providing enough data when
12882 // before there was *not* enough.
12883 //
12884 // So, the steps are:
12885 // 1. Figure out what the state of things will be after we do
12886 // a read from the buffer.
12887 //
12888 // 2. If that resulting state will trigger a _read, then call _read.
12889 // Note that this may be asynchronous, or synchronous. Yes, it is
12890 // deeply ugly to write APIs this way, but that still doesn't mean
12891 // that the Readable class should behave improperly, as streams are
12892 // designed to be sync/async agnostic.
12893 // Take note if the _read call is sync or async (ie, if the read call
12894 // has returned yet), so that we know whether or not it's safe to emit
12895 // 'readable' etc.
12896 //
12897 // 3. Actually pull the requested chunks out of the buffer and return.
12898
12899 // if we need a readable event, then we need to do some reading.
12900 var doRead = state.needReadable;
12901 debug('need readable', doRead);
12902
12903 // if we currently have less than the highWaterMark, then also read some
12904 if (state.length === 0 || state.length - n < state.highWaterMark) {
12905 doRead = true;
12906 debug('length less than watermark', doRead);
12907 }
12908
12909 // however, if we've ended, then there's no point, and if we're already
12910 // reading, then it's unnecessary.
12911 if (state.ended || state.reading) {
12912 doRead = false;
12913 debug('reading or ended', doRead);
12914 } else if (doRead) {
12915 debug('do read');
12916 state.reading = true;
12917 state.sync = true;
12918 // if the length is currently zero, then we *need* a readable event.
12919 if (state.length === 0) state.needReadable = true;
12920 // call internal read method
12921 this._read(state.highWaterMark);
12922 state.sync = false;
12923 // If _read pushed data synchronously, then `reading` will be false,
12924 // and we need to re-evaluate how much data we can return to the user.
12925 if (!state.reading) n = howMuchToRead(nOrig, state);
12926 }
12927
12928 var ret;
12929 if (n > 0) ret = fromList(n, state);else ret = null;
12930
12931 if (ret === null) {
12932 state.needReadable = true;
12933 n = 0;
12934 } else {
12935 state.length -= n;
12936 }
12937
12938 if (state.length === 0) {
12939 // If we have nothing in the buffer, then we want to know
12940 // as soon as we *do* get something into the buffer.
12941 if (!state.ended) state.needReadable = true;
12942
12943 // If we tried to read() past the EOF, then emit end on the next tick.
12944 if (nOrig !== n && state.ended) endReadable(this);
12945 }
12946
12947 if (ret !== null) this.emit('data', ret);
12948
12949 return ret;
12950};
12951
12952function onEofChunk(stream, state) {
12953 if (state.ended) return;
12954 if (state.decoder) {
12955 var chunk = state.decoder.end();
12956 if (chunk && chunk.length) {
12957 state.buffer.push(chunk);
12958 state.length += state.objectMode ? 1 : chunk.length;
12959 }
12960 }
12961 state.ended = true;
12962
12963 // emit 'readable' now to make sure it gets picked up.
12964 emitReadable(stream);
12965}
12966
12967// Don't emit readable right away in sync mode, because this can trigger
12968// another read() call => stack overflow. This way, it might trigger
12969// a nextTick recursion warning, but that's not so bad.
12970function emitReadable(stream) {
12971 var state = stream._readableState;
12972 state.needReadable = false;
12973 if (!state.emittedReadable) {
12974 debug('emitReadable', state.flowing);
12975 state.emittedReadable = true;
12976 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
12977 }
12978}
12979
12980function emitReadable_(stream) {
12981 debug('emit readable');
12982 stream.emit('readable');
12983 flow(stream);
12984}
12985
12986// at this point, the user has presumably seen the 'readable' event,
12987// and called read() to consume some data. that may have triggered
12988// in turn another _read(n) call, in which case reading = true if
12989// it's in progress.
12990// However, if we're not ended, or reading, and the length < hwm,
12991// then go ahead and try to read some more preemptively.
12992function maybeReadMore(stream, state) {
12993 if (!state.readingMore) {
12994 state.readingMore = true;
12995 processNextTick(maybeReadMore_, stream, state);
12996 }
12997}
12998
12999function maybeReadMore_(stream, state) {
13000 var len = state.length;
13001 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
13002 debug('maybeReadMore read 0');
13003 stream.read(0);
13004 if (len === state.length)
13005 // didn't get any data, stop spinning.
13006 break;else len = state.length;
13007 }
13008 state.readingMore = false;
13009}
13010
13011// abstract method. to be overridden in specific implementation classes.
13012// call cb(er, data) where data is <= n in length.
13013// for virtual (non-string, non-buffer) streams, "length" is somewhat
13014// arbitrary, and perhaps not very meaningful.
13015Readable.prototype._read = function (n) {
13016 this.emit('error', new Error('_read() is not implemented'));
13017};
13018
13019Readable.prototype.pipe = function (dest, pipeOpts) {
13020 var src = this;
13021 var state = this._readableState;
13022
13023 switch (state.pipesCount) {
13024 case 0:
13025 state.pipes = dest;
13026 break;
13027 case 1:
13028 state.pipes = [state.pipes, dest];
13029 break;
13030 default:
13031 state.pipes.push(dest);
13032 break;
13033 }
13034 state.pipesCount += 1;
13035 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
13036
13037 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
13038
13039 var endFn = doEnd ? onend : unpipe;
13040 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
13041
13042 dest.on('unpipe', onunpipe);
13043 function onunpipe(readable, unpipeInfo) {
13044 debug('onunpipe');
13045 if (readable === src) {
13046 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
13047 unpipeInfo.hasUnpiped = true;
13048 cleanup();
13049 }
13050 }
13051 }
13052
13053 function onend() {
13054 debug('onend');
13055 dest.end();
13056 }
13057
13058 // when the dest drains, it reduces the awaitDrain counter
13059 // on the source. This would be more elegant with a .once()
13060 // handler in flow(), but adding and removing repeatedly is
13061 // too slow.
13062 var ondrain = pipeOnDrain(src);
13063 dest.on('drain', ondrain);
13064
13065 var cleanedUp = false;
13066 function cleanup() {
13067 debug('cleanup');
13068 // cleanup event handlers once the pipe is broken
13069 dest.removeListener('close', onclose);
13070 dest.removeListener('finish', onfinish);
13071 dest.removeListener('drain', ondrain);
13072 dest.removeListener('error', onerror);
13073 dest.removeListener('unpipe', onunpipe);
13074 src.removeListener('end', onend);
13075 src.removeListener('end', unpipe);
13076 src.removeListener('data', ondata);
13077
13078 cleanedUp = true;
13079
13080 // if the reader is waiting for a drain event from this
13081 // specific writer, then it would cause it to never start
13082 // flowing again.
13083 // So, if this is awaiting a drain, then we just call it now.
13084 // If we don't know, then assume that we are waiting for one.
13085 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
13086 }
13087
13088 // If the user pushes more data while we're writing to dest then we'll end up
13089 // in ondata again. However, we only want to increase awaitDrain once because
13090 // dest will only emit one 'drain' event for the multiple writes.
13091 // => Introduce a guard on increasing awaitDrain.
13092 var increasedAwaitDrain = false;
13093 src.on('data', ondata);
13094 function ondata(chunk) {
13095 debug('ondata');
13096 increasedAwaitDrain = false;
13097 var ret = dest.write(chunk);
13098 if (false === ret && !increasedAwaitDrain) {
13099 // If the user unpiped during `dest.write()`, it is possible
13100 // to get stuck in a permanently paused state if that write
13101 // also returned false.
13102 // => Check whether `dest` is still a piping destination.
13103 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
13104 debug('false write response, pause', src._readableState.awaitDrain);
13105 src._readableState.awaitDrain++;
13106 increasedAwaitDrain = true;
13107 }
13108 src.pause();
13109 }
13110 }
13111
13112 // if the dest has an error, then stop piping into it.
13113 // however, don't suppress the throwing behavior for this.
13114 function onerror(er) {
13115 debug('onerror', er);
13116 unpipe();
13117 dest.removeListener('error', onerror);
13118 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
13119 }
13120
13121 // Make sure our error handler is attached before userland ones.
13122 prependListener(dest, 'error', onerror);
13123
13124 // Both close and finish should trigger unpipe, but only once.
13125 function onclose() {
13126 dest.removeListener('finish', onfinish);
13127 unpipe();
13128 }
13129 dest.once('close', onclose);
13130 function onfinish() {
13131 debug('onfinish');
13132 dest.removeListener('close', onclose);
13133 unpipe();
13134 }
13135 dest.once('finish', onfinish);
13136
13137 function unpipe() {
13138 debug('unpipe');
13139 src.unpipe(dest);
13140 }
13141
13142 // tell the dest that it's being piped to
13143 dest.emit('pipe', src);
13144
13145 // start the flow if it hasn't been started already.
13146 if (!state.flowing) {
13147 debug('pipe resume');
13148 src.resume();
13149 }
13150
13151 return dest;
13152};
13153
13154function pipeOnDrain(src) {
13155 return function () {
13156 var state = src._readableState;
13157 debug('pipeOnDrain', state.awaitDrain);
13158 if (state.awaitDrain) state.awaitDrain--;
13159 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
13160 state.flowing = true;
13161 flow(src);
13162 }
13163 };
13164}
13165
13166Readable.prototype.unpipe = function (dest) {
13167 var state = this._readableState;
13168 var unpipeInfo = { hasUnpiped: false };
13169
13170 // if we're not piping anywhere, then do nothing.
13171 if (state.pipesCount === 0) return this;
13172
13173 // just one destination. most common case.
13174 if (state.pipesCount === 1) {
13175 // passed in one, but it's not the right one.
13176 if (dest && dest !== state.pipes) return this;
13177
13178 if (!dest) dest = state.pipes;
13179
13180 // got a match.
13181 state.pipes = null;
13182 state.pipesCount = 0;
13183 state.flowing = false;
13184 if (dest) dest.emit('unpipe', this, unpipeInfo);
13185 return this;
13186 }
13187
13188 // slow case. multiple pipe destinations.
13189
13190 if (!dest) {
13191 // remove all.
13192 var dests = state.pipes;
13193 var len = state.pipesCount;
13194 state.pipes = null;
13195 state.pipesCount = 0;
13196 state.flowing = false;
13197
13198 for (var i = 0; i < len; i++) {
13199 dests[i].emit('unpipe', this, unpipeInfo);
13200 }return this;
13201 }
13202
13203 // try to find the right one.
13204 var index = indexOf(state.pipes, dest);
13205 if (index === -1) return this;
13206
13207 state.pipes.splice(index, 1);
13208 state.pipesCount -= 1;
13209 if (state.pipesCount === 1) state.pipes = state.pipes[0];
13210
13211 dest.emit('unpipe', this, unpipeInfo);
13212
13213 return this;
13214};
13215
13216// set up data events if they are asked for
13217// Ensure readable listeners eventually get something
13218Readable.prototype.on = function (ev, fn) {
13219 var res = Stream.prototype.on.call(this, ev, fn);
13220
13221 if (ev === 'data') {
13222 // Start flowing on next tick if stream isn't explicitly paused
13223 if (this._readableState.flowing !== false) this.resume();
13224 } else if (ev === 'readable') {
13225 var state = this._readableState;
13226 if (!state.endEmitted && !state.readableListening) {
13227 state.readableListening = state.needReadable = true;
13228 state.emittedReadable = false;
13229 if (!state.reading) {
13230 processNextTick(nReadingNextTick, this);
13231 } else if (state.length) {
13232 emitReadable(this);
13233 }
13234 }
13235 }
13236
13237 return res;
13238};
13239Readable.prototype.addListener = Readable.prototype.on;
13240
13241function nReadingNextTick(self) {
13242 debug('readable nexttick read 0');
13243 self.read(0);
13244}
13245
13246// pause() and resume() are remnants of the legacy readable stream API
13247// If the user uses them, then switch into old mode.
13248Readable.prototype.resume = function () {
13249 var state = this._readableState;
13250 if (!state.flowing) {
13251 debug('resume');
13252 state.flowing = true;
13253 resume(this, state);
13254 }
13255 return this;
13256};
13257
13258function resume(stream, state) {
13259 if (!state.resumeScheduled) {
13260 state.resumeScheduled = true;
13261 processNextTick(resume_, stream, state);
13262 }
13263}
13264
13265function resume_(stream, state) {
13266 if (!state.reading) {
13267 debug('resume read 0');
13268 stream.read(0);
13269 }
13270
13271 state.resumeScheduled = false;
13272 state.awaitDrain = 0;
13273 stream.emit('resume');
13274 flow(stream);
13275 if (state.flowing && !state.reading) stream.read(0);
13276}
13277
13278Readable.prototype.pause = function () {
13279 debug('call pause flowing=%j', this._readableState.flowing);
13280 if (false !== this._readableState.flowing) {
13281 debug('pause');
13282 this._readableState.flowing = false;
13283 this.emit('pause');
13284 }
13285 return this;
13286};
13287
13288function flow(stream) {
13289 var state = stream._readableState;
13290 debug('flow', state.flowing);
13291 while (state.flowing && stream.read() !== null) {}
13292}
13293
13294// wrap an old-style stream as the async data source.
13295// This is *not* part of the readable stream interface.
13296// It is an ugly unfortunate mess of history.
13297Readable.prototype.wrap = function (stream) {
13298 var state = this._readableState;
13299 var paused = false;
13300
13301 var self = this;
13302 stream.on('end', function () {
13303 debug('wrapped end');
13304 if (state.decoder && !state.ended) {
13305 var chunk = state.decoder.end();
13306 if (chunk && chunk.length) self.push(chunk);
13307 }
13308
13309 self.push(null);
13310 });
13311
13312 stream.on('data', function (chunk) {
13313 debug('wrapped data');
13314 if (state.decoder) chunk = state.decoder.write(chunk);
13315
13316 // don't skip over falsy values in objectMode
13317 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
13318
13319 var ret = self.push(chunk);
13320 if (!ret) {
13321 paused = true;
13322 stream.pause();
13323 }
13324 });
13325
13326 // proxy all the other methods.
13327 // important when wrapping filters and duplexes.
13328 for (var i in stream) {
13329 if (this[i] === undefined && typeof stream[i] === 'function') {
13330 this[i] = function (method) {
13331 return function () {
13332 return stream[method].apply(stream, arguments);
13333 };
13334 }(i);
13335 }
13336 }
13337
13338 // proxy certain important events.
13339 for (var n = 0; n < kProxyEvents.length; n++) {
13340 stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
13341 }
13342
13343 // when we try to consume some more bytes, simply unpause the
13344 // underlying stream.
13345 self._read = function (n) {
13346 debug('wrapped _read', n);
13347 if (paused) {
13348 paused = false;
13349 stream.resume();
13350 }
13351 };
13352
13353 return self;
13354};
13355
13356// exposed for testing purposes only.
13357Readable._fromList = fromList;
13358
13359// Pluck off n bytes from an array of buffers.
13360// Length is the combined lengths of all the buffers in the list.
13361// This function is designed to be inlinable, so please take care when making
13362// changes to the function body.
13363function fromList(n, state) {
13364 // nothing buffered
13365 if (state.length === 0) return null;
13366
13367 var ret;
13368 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
13369 // read it all, truncate the list
13370 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);
13371 state.buffer.clear();
13372 } else {
13373 // read part of list
13374 ret = fromListPartial(n, state.buffer, state.decoder);
13375 }
13376
13377 return ret;
13378}
13379
13380// Extracts only enough buffered data to satisfy the amount requested.
13381// This function is designed to be inlinable, so please take care when making
13382// changes to the function body.
13383function fromListPartial(n, list, hasStrings) {
13384 var ret;
13385 if (n < list.head.data.length) {
13386 // slice is the same for buffers and strings
13387 ret = list.head.data.slice(0, n);
13388 list.head.data = list.head.data.slice(n);
13389 } else if (n === list.head.data.length) {
13390 // first chunk is a perfect match
13391 ret = list.shift();
13392 } else {
13393 // result spans more than one buffer
13394 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
13395 }
13396 return ret;
13397}
13398
13399// Copies a specified amount of characters from the list of buffered data
13400// chunks.
13401// This function is designed to be inlinable, so please take care when making
13402// changes to the function body.
13403function copyFromBufferString(n, list) {
13404 var p = list.head;
13405 var c = 1;
13406 var ret = p.data;
13407 n -= ret.length;
13408 while (p = p.next) {
13409 var str = p.data;
13410 var nb = n > str.length ? str.length : n;
13411 if (nb === str.length) ret += str;else ret += str.slice(0, n);
13412 n -= nb;
13413 if (n === 0) {
13414 if (nb === str.length) {
13415 ++c;
13416 if (p.next) list.head = p.next;else list.head = list.tail = null;
13417 } else {
13418 list.head = p;
13419 p.data = str.slice(nb);
13420 }
13421 break;
13422 }
13423 ++c;
13424 }
13425 list.length -= c;
13426 return ret;
13427}
13428
13429// Copies a specified amount of bytes from the list of buffered data chunks.
13430// This function is designed to be inlinable, so please take care when making
13431// changes to the function body.
13432function copyFromBuffer(n, list) {
13433 var ret = Buffer.allocUnsafe(n);
13434 var p = list.head;
13435 var c = 1;
13436 p.data.copy(ret);
13437 n -= p.data.length;
13438 while (p = p.next) {
13439 var buf = p.data;
13440 var nb = n > buf.length ? buf.length : n;
13441 buf.copy(ret, ret.length - n, 0, nb);
13442 n -= nb;
13443 if (n === 0) {
13444 if (nb === buf.length) {
13445 ++c;
13446 if (p.next) list.head = p.next;else list.head = list.tail = null;
13447 } else {
13448 list.head = p;
13449 p.data = buf.slice(nb);
13450 }
13451 break;
13452 }
13453 ++c;
13454 }
13455 list.length -= c;
13456 return ret;
13457}
13458
13459function endReadable(stream) {
13460 var state = stream._readableState;
13461
13462 // If we get here before consuming all the bytes, then that is a
13463 // bug in node. Should never happen.
13464 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
13465
13466 if (!state.endEmitted) {
13467 state.ended = true;
13468 processNextTick(endReadableNT, state, stream);
13469 }
13470}
13471
13472function endReadableNT(state, stream) {
13473 // Check that we didn't get one last unshift.
13474 if (!state.endEmitted && state.length === 0) {
13475 state.endEmitted = true;
13476 stream.readable = false;
13477 stream.emit('end');
13478 }
13479}
13480
13481function forEach(xs, f) {
13482 for (var i = 0, l = xs.length; i < l; i++) {
13483 f(xs[i], i);
13484 }
13485}
13486
13487function indexOf(xs, x) {
13488 for (var i = 0, l = xs.length; i < l; i++) {
13489 if (xs[i] === x) return i;
13490 }
13491 return -1;
13492}
13493}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
13494},{"./_stream_duplex":55,"./internal/streams/BufferList":60,"./internal/streams/destroy":61,"./internal/streams/stream":62,"_process":52,"core-util-is":30,"events":41,"inherits":45,"isarray":47,"process-nextick-args":51,"safe-buffer":68,"string_decoder/":78,"util":8}],58:[function(require,module,exports){
13495// Copyright Joyent, Inc. and other Node contributors.
13496//
13497// Permission is hereby granted, free of charge, to any person obtaining a
13498// copy of this software and associated documentation files (the
13499// "Software"), to deal in the Software without restriction, including
13500// without limitation the rights to use, copy, modify, merge, publish,
13501// distribute, sublicense, and/or sell copies of the Software, and to permit
13502// persons to whom the Software is furnished to do so, subject to the
13503// following conditions:
13504//
13505// The above copyright notice and this permission notice shall be included
13506// in all copies or substantial portions of the Software.
13507//
13508// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13509// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13510// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13511// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13512// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13513// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13514// USE OR OTHER DEALINGS IN THE SOFTWARE.
13515
13516// a transform stream is a readable/writable stream where you do
13517// something with the data. Sometimes it's called a "filter",
13518// but that's not a great name for it, since that implies a thing where
13519// some bits pass through, and others are simply ignored. (That would
13520// be a valid example of a transform, of course.)
13521//
13522// While the output is causally related to the input, it's not a
13523// necessarily symmetric or synchronous transformation. For example,
13524// a zlib stream might take multiple plain-text writes(), and then
13525// emit a single compressed chunk some time in the future.
13526//
13527// Here's how this works:
13528//
13529// The Transform stream has all the aspects of the readable and writable
13530// stream classes. When you write(chunk), that calls _write(chunk,cb)
13531// internally, and returns false if there's a lot of pending writes
13532// buffered up. When you call read(), that calls _read(n) until
13533// there's enough pending readable data buffered up.
13534//
13535// In a transform stream, the written data is placed in a buffer. When
13536// _read(n) is called, it transforms the queued up data, calling the
13537// buffered _write cb's as it consumes chunks. If consuming a single
13538// written chunk would result in multiple output chunks, then the first
13539// outputted bit calls the readcb, and subsequent chunks just go into
13540// the read buffer, and will cause it to emit 'readable' if necessary.
13541//
13542// This way, back-pressure is actually determined by the reading side,
13543// since _read has to be called to start processing a new chunk. However,
13544// a pathological inflate type of transform can cause excessive buffering
13545// here. For example, imagine a stream where every byte of input is
13546// interpreted as an integer from 0-255, and then results in that many
13547// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
13548// 1kb of data being output. In this case, you could write a very small
13549// amount of input, and end up with a very large amount of output. In
13550// such a pathological inflating mechanism, there'd be no way to tell
13551// the system to stop doing the transform. A single 4MB write could
13552// cause the system to run out of memory.
13553//
13554// However, even in such a pathological case, only a single written chunk
13555// would be consumed, and then the rest would wait (un-transformed) until
13556// the results of the previous transformed chunk were consumed.
13557
13558'use strict';
13559
13560module.exports = Transform;
13561
13562var Duplex = require('./_stream_duplex');
13563
13564/*<replacement>*/
13565var util = require('core-util-is');
13566util.inherits = require('inherits');
13567/*</replacement>*/
13568
13569util.inherits(Transform, Duplex);
13570
13571function TransformState(stream) {
13572 this.afterTransform = function (er, data) {
13573 return afterTransform(stream, er, data);
13574 };
13575
13576 this.needTransform = false;
13577 this.transforming = false;
13578 this.writecb = null;
13579 this.writechunk = null;
13580 this.writeencoding = null;
13581}
13582
13583function afterTransform(stream, er, data) {
13584 var ts = stream._transformState;
13585 ts.transforming = false;
13586
13587 var cb = ts.writecb;
13588
13589 if (!cb) {
13590 return stream.emit('error', new Error('write callback called multiple times'));
13591 }
13592
13593 ts.writechunk = null;
13594 ts.writecb = null;
13595
13596 if (data !== null && data !== undefined) stream.push(data);
13597
13598 cb(er);
13599
13600 var rs = stream._readableState;
13601 rs.reading = false;
13602 if (rs.needReadable || rs.length < rs.highWaterMark) {
13603 stream._read(rs.highWaterMark);
13604 }
13605}
13606
13607function Transform(options) {
13608 if (!(this instanceof Transform)) return new Transform(options);
13609
13610 Duplex.call(this, options);
13611
13612 this._transformState = new TransformState(this);
13613
13614 var stream = this;
13615
13616 // start out asking for a readable event once data is transformed.
13617 this._readableState.needReadable = true;
13618
13619 // we have implemented the _read method, and done the other things
13620 // that Readable wants before the first _read call, so unset the
13621 // sync guard flag.
13622 this._readableState.sync = false;
13623
13624 if (options) {
13625 if (typeof options.transform === 'function') this._transform = options.transform;
13626
13627 if (typeof options.flush === 'function') this._flush = options.flush;
13628 }
13629
13630 // When the writable side finishes, then flush out anything remaining.
13631 this.once('prefinish', function () {
13632 if (typeof this._flush === 'function') this._flush(function (er, data) {
13633 done(stream, er, data);
13634 });else done(stream);
13635 });
13636}
13637
13638Transform.prototype.push = function (chunk, encoding) {
13639 this._transformState.needTransform = false;
13640 return Duplex.prototype.push.call(this, chunk, encoding);
13641};
13642
13643// This is the part where you do stuff!
13644// override this function in implementation classes.
13645// 'chunk' is an input chunk.
13646//
13647// Call `push(newChunk)` to pass along transformed output
13648// to the readable side. You may call 'push' zero or more times.
13649//
13650// Call `cb(err)` when you are done with this chunk. If you pass
13651// an error, then that'll put the hurt on the whole operation. If you
13652// never call cb(), then you'll never get another chunk.
13653Transform.prototype._transform = function (chunk, encoding, cb) {
13654 throw new Error('_transform() is not implemented');
13655};
13656
13657Transform.prototype._write = function (chunk, encoding, cb) {
13658 var ts = this._transformState;
13659 ts.writecb = cb;
13660 ts.writechunk = chunk;
13661 ts.writeencoding = encoding;
13662 if (!ts.transforming) {
13663 var rs = this._readableState;
13664 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
13665 }
13666};
13667
13668// Doesn't matter what the args are here.
13669// _transform does all the work.
13670// That we got here means that the readable side wants more data.
13671Transform.prototype._read = function (n) {
13672 var ts = this._transformState;
13673
13674 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
13675 ts.transforming = true;
13676 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
13677 } else {
13678 // mark that we need a transform, so that any data that comes in
13679 // will get processed, now that we've asked for it.
13680 ts.needTransform = true;
13681 }
13682};
13683
13684Transform.prototype._destroy = function (err, cb) {
13685 var _this = this;
13686
13687 Duplex.prototype._destroy.call(this, err, function (err2) {
13688 cb(err2);
13689 _this.emit('close');
13690 });
13691};
13692
13693function done(stream, er, data) {
13694 if (er) return stream.emit('error', er);
13695
13696 if (data !== null && data !== undefined) stream.push(data);
13697
13698 // if there's nothing in the write buffer, then that means
13699 // that nothing more will ever be provided
13700 var ws = stream._writableState;
13701 var ts = stream._transformState;
13702
13703 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
13704
13705 if (ts.transforming) throw new Error('Calling transform done when still transforming');
13706
13707 return stream.push(null);
13708}
13709},{"./_stream_duplex":55,"core-util-is":30,"inherits":45}],59:[function(require,module,exports){
13710(function (process,global){
13711// Copyright Joyent, Inc. and other Node contributors.
13712//
13713// Permission is hereby granted, free of charge, to any person obtaining a
13714// copy of this software and associated documentation files (the
13715// "Software"), to deal in the Software without restriction, including
13716// without limitation the rights to use, copy, modify, merge, publish,
13717// distribute, sublicense, and/or sell copies of the Software, and to permit
13718// persons to whom the Software is furnished to do so, subject to the
13719// following conditions:
13720//
13721// The above copyright notice and this permission notice shall be included
13722// in all copies or substantial portions of the Software.
13723//
13724// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13725// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13726// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13727// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13728// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13729// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13730// USE OR OTHER DEALINGS IN THE SOFTWARE.
13731
13732// A bit simpler than readable streams.
13733// Implement an async ._write(chunk, encoding, cb), and it'll handle all
13734// the drain event emission and buffering.
13735
13736'use strict';
13737
13738/*<replacement>*/
13739
13740var processNextTick = require('process-nextick-args');
13741/*</replacement>*/
13742
13743module.exports = Writable;
13744
13745/* <replacement> */
13746function WriteReq(chunk, encoding, cb) {
13747 this.chunk = chunk;
13748 this.encoding = encoding;
13749 this.callback = cb;
13750 this.next = null;
13751}
13752
13753// It seems a linked list but it is not
13754// there will be only 2 of these for each stream
13755function CorkedRequest(state) {
13756 var _this = this;
13757
13758 this.next = null;
13759 this.entry = null;
13760 this.finish = function () {
13761 onCorkedFinish(_this, state);
13762 };
13763}
13764/* </replacement> */
13765
13766/*<replacement>*/
13767var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
13768/*</replacement>*/
13769
13770/*<replacement>*/
13771var Duplex;
13772/*</replacement>*/
13773
13774Writable.WritableState = WritableState;
13775
13776/*<replacement>*/
13777var util = require('core-util-is');
13778util.inherits = require('inherits');
13779/*</replacement>*/
13780
13781/*<replacement>*/
13782var internalUtil = {
13783 deprecate: require('util-deprecate')
13784};
13785/*</replacement>*/
13786
13787/*<replacement>*/
13788var Stream = require('./internal/streams/stream');
13789/*</replacement>*/
13790
13791/*<replacement>*/
13792var Buffer = require('safe-buffer').Buffer;
13793var OurUint8Array = global.Uint8Array || function () {};
13794function _uint8ArrayToBuffer(chunk) {
13795 return Buffer.from(chunk);
13796}
13797function _isUint8Array(obj) {
13798 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
13799}
13800/*</replacement>*/
13801
13802var destroyImpl = require('./internal/streams/destroy');
13803
13804util.inherits(Writable, Stream);
13805
13806function nop() {}
13807
13808function WritableState(options, stream) {
13809 Duplex = Duplex || require('./_stream_duplex');
13810
13811 options = options || {};
13812
13813 // object stream flag to indicate whether or not this stream
13814 // contains buffers or objects.
13815 this.objectMode = !!options.objectMode;
13816
13817 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
13818
13819 // the point at which write() starts returning false
13820 // Note: 0 is a valid value, means that we always return false if
13821 // the entire buffer is not flushed immediately on write()
13822 var hwm = options.highWaterMark;
13823 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
13824 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
13825
13826 // cast to ints.
13827 this.highWaterMark = Math.floor(this.highWaterMark);
13828
13829 // if _final has been called
13830 this.finalCalled = false;
13831
13832 // drain event flag.
13833 this.needDrain = false;
13834 // at the start of calling end()
13835 this.ending = false;
13836 // when end() has been called, and returned
13837 this.ended = false;
13838 // when 'finish' is emitted
13839 this.finished = false;
13840
13841 // has it been destroyed
13842 this.destroyed = false;
13843
13844 // should we decode strings into buffers before passing to _write?
13845 // this is here so that some node-core streams can optimize string
13846 // handling at a lower level.
13847 var noDecode = options.decodeStrings === false;
13848 this.decodeStrings = !noDecode;
13849
13850 // Crypto is kind of old and crusty. Historically, its default string
13851 // encoding is 'binary' so we have to make this configurable.
13852 // Everything else in the universe uses 'utf8', though.
13853 this.defaultEncoding = options.defaultEncoding || 'utf8';
13854
13855 // not an actual buffer we keep track of, but a measurement
13856 // of how much we're waiting to get pushed to some underlying
13857 // socket or file.
13858 this.length = 0;
13859
13860 // a flag to see when we're in the middle of a write.
13861 this.writing = false;
13862
13863 // when true all writes will be buffered until .uncork() call
13864 this.corked = 0;
13865
13866 // a flag to be able to tell if the onwrite cb is called immediately,
13867 // or on a later tick. We set this to true at first, because any
13868 // actions that shouldn't happen until "later" should generally also
13869 // not happen before the first write call.
13870 this.sync = true;
13871
13872 // a flag to know if we're processing previously buffered items, which
13873 // may call the _write() callback in the same tick, so that we don't
13874 // end up in an overlapped onwrite situation.
13875 this.bufferProcessing = false;
13876
13877 // the callback that's passed to _write(chunk,cb)
13878 this.onwrite = function (er) {
13879 onwrite(stream, er);
13880 };
13881
13882 // the callback that the user supplies to write(chunk,encoding,cb)
13883 this.writecb = null;
13884
13885 // the amount that is being written when _write is called.
13886 this.writelen = 0;
13887
13888 this.bufferedRequest = null;
13889 this.lastBufferedRequest = null;
13890
13891 // number of pending user-supplied write callbacks
13892 // this must be 0 before 'finish' can be emitted
13893 this.pendingcb = 0;
13894
13895 // emit prefinish if the only thing we're waiting for is _write cbs
13896 // This is relevant for synchronous Transform streams
13897 this.prefinished = false;
13898
13899 // True if the error was already emitted and should not be thrown again
13900 this.errorEmitted = false;
13901
13902 // count buffered requests
13903 this.bufferedRequestCount = 0;
13904
13905 // allocate the first CorkedRequest, there is always
13906 // one allocated and free to use, and we maintain at most two
13907 this.corkedRequestsFree = new CorkedRequest(this);
13908}
13909
13910WritableState.prototype.getBuffer = function getBuffer() {
13911 var current = this.bufferedRequest;
13912 var out = [];
13913 while (current) {
13914 out.push(current);
13915 current = current.next;
13916 }
13917 return out;
13918};
13919
13920(function () {
13921 try {
13922 Object.defineProperty(WritableState.prototype, 'buffer', {
13923 get: internalUtil.deprecate(function () {
13924 return this.getBuffer();
13925 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
13926 });
13927 } catch (_) {}
13928})();
13929
13930// Test _writableState for inheritance to account for Duplex streams,
13931// whose prototype chain only points to Readable.
13932var realHasInstance;
13933if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
13934 realHasInstance = Function.prototype[Symbol.hasInstance];
13935 Object.defineProperty(Writable, Symbol.hasInstance, {
13936 value: function (object) {
13937 if (realHasInstance.call(this, object)) return true;
13938
13939 return object && object._writableState instanceof WritableState;
13940 }
13941 });
13942} else {
13943 realHasInstance = function (object) {
13944 return object instanceof this;
13945 };
13946}
13947
13948function Writable(options) {
13949 Duplex = Duplex || require('./_stream_duplex');
13950
13951 // Writable ctor is applied to Duplexes, too.
13952 // `realHasInstance` is necessary because using plain `instanceof`
13953 // would return false, as no `_writableState` property is attached.
13954
13955 // Trying to use the custom `instanceof` for Writable here will also break the
13956 // Node.js LazyTransform implementation, which has a non-trivial getter for
13957 // `_writableState` that would lead to infinite recursion.
13958 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
13959 return new Writable(options);
13960 }
13961
13962 this._writableState = new WritableState(options, this);
13963
13964 // legacy.
13965 this.writable = true;
13966
13967 if (options) {
13968 if (typeof options.write === 'function') this._write = options.write;
13969
13970 if (typeof options.writev === 'function') this._writev = options.writev;
13971
13972 if (typeof options.destroy === 'function') this._destroy = options.destroy;
13973
13974 if (typeof options.final === 'function') this._final = options.final;
13975 }
13976
13977 Stream.call(this);
13978}
13979
13980// Otherwise people can pipe Writable streams, which is just wrong.
13981Writable.prototype.pipe = function () {
13982 this.emit('error', new Error('Cannot pipe, not readable'));
13983};
13984
13985function writeAfterEnd(stream, cb) {
13986 var er = new Error('write after end');
13987 // TODO: defer error events consistently everywhere, not just the cb
13988 stream.emit('error', er);
13989 processNextTick(cb, er);
13990}
13991
13992// Checks that a user-supplied chunk is valid, especially for the particular
13993// mode the stream is in. Currently this means that `null` is never accepted
13994// and undefined/non-string values are only allowed in object mode.
13995function validChunk(stream, state, chunk, cb) {
13996 var valid = true;
13997 var er = false;
13998
13999 if (chunk === null) {
14000 er = new TypeError('May not write null values to stream');
14001 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
14002 er = new TypeError('Invalid non-string/buffer chunk');
14003 }
14004 if (er) {
14005 stream.emit('error', er);
14006 processNextTick(cb, er);
14007 valid = false;
14008 }
14009 return valid;
14010}
14011
14012Writable.prototype.write = function (chunk, encoding, cb) {
14013 var state = this._writableState;
14014 var ret = false;
14015 var isBuf = _isUint8Array(chunk) && !state.objectMode;
14016
14017 if (isBuf && !Buffer.isBuffer(chunk)) {
14018 chunk = _uint8ArrayToBuffer(chunk);
14019 }
14020
14021 if (typeof encoding === 'function') {
14022 cb = encoding;
14023 encoding = null;
14024 }
14025
14026 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
14027
14028 if (typeof cb !== 'function') cb = nop;
14029
14030 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
14031 state.pendingcb++;
14032 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
14033 }
14034
14035 return ret;
14036};
14037
14038Writable.prototype.cork = function () {
14039 var state = this._writableState;
14040
14041 state.corked++;
14042};
14043
14044Writable.prototype.uncork = function () {
14045 var state = this._writableState;
14046
14047 if (state.corked) {
14048 state.corked--;
14049
14050 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
14051 }
14052};
14053
14054Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
14055 // node::ParseEncoding() requires lower case.
14056 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
14057 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);
14058 this._writableState.defaultEncoding = encoding;
14059 return this;
14060};
14061
14062function decodeChunk(state, chunk, encoding) {
14063 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
14064 chunk = Buffer.from(chunk, encoding);
14065 }
14066 return chunk;
14067}
14068
14069// if we're already writing something, then just put this
14070// in the queue, and wait our turn. Otherwise, call _write
14071// If we return false, then we need a drain event, so set that flag.
14072function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
14073 if (!isBuf) {
14074 var newChunk = decodeChunk(state, chunk, encoding);
14075 if (chunk !== newChunk) {
14076 isBuf = true;
14077 encoding = 'buffer';
14078 chunk = newChunk;
14079 }
14080 }
14081 var len = state.objectMode ? 1 : chunk.length;
14082
14083 state.length += len;
14084
14085 var ret = state.length < state.highWaterMark;
14086 // we must ensure that previous needDrain will not be reset to false.
14087 if (!ret) state.needDrain = true;
14088
14089 if (state.writing || state.corked) {
14090 var last = state.lastBufferedRequest;
14091 state.lastBufferedRequest = {
14092 chunk: chunk,
14093 encoding: encoding,
14094 isBuf: isBuf,
14095 callback: cb,
14096 next: null
14097 };
14098 if (last) {
14099 last.next = state.lastBufferedRequest;
14100 } else {
14101 state.bufferedRequest = state.lastBufferedRequest;
14102 }
14103 state.bufferedRequestCount += 1;
14104 } else {
14105 doWrite(stream, state, false, len, chunk, encoding, cb);
14106 }
14107
14108 return ret;
14109}
14110
14111function doWrite(stream, state, writev, len, chunk, encoding, cb) {
14112 state.writelen = len;
14113 state.writecb = cb;
14114 state.writing = true;
14115 state.sync = true;
14116 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
14117 state.sync = false;
14118}
14119
14120function onwriteError(stream, state, sync, er, cb) {
14121 --state.pendingcb;
14122
14123 if (sync) {
14124 // defer the callback if we are being called synchronously
14125 // to avoid piling up things on the stack
14126 processNextTick(cb, er);
14127 // this can emit finish, and it will always happen
14128 // after error
14129 processNextTick(finishMaybe, stream, state);
14130 stream._writableState.errorEmitted = true;
14131 stream.emit('error', er);
14132 } else {
14133 // the caller expect this to happen before if
14134 // it is async
14135 cb(er);
14136 stream._writableState.errorEmitted = true;
14137 stream.emit('error', er);
14138 // this can emit finish, but finish must
14139 // always follow error
14140 finishMaybe(stream, state);
14141 }
14142}
14143
14144function onwriteStateUpdate(state) {
14145 state.writing = false;
14146 state.writecb = null;
14147 state.length -= state.writelen;
14148 state.writelen = 0;
14149}
14150
14151function onwrite(stream, er) {
14152 var state = stream._writableState;
14153 var sync = state.sync;
14154 var cb = state.writecb;
14155
14156 onwriteStateUpdate(state);
14157
14158 if (er) onwriteError(stream, state, sync, er, cb);else {
14159 // Check if we're actually ready to finish, but don't emit yet
14160 var finished = needFinish(state);
14161
14162 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
14163 clearBuffer(stream, state);
14164 }
14165
14166 if (sync) {
14167 /*<replacement>*/
14168 asyncWrite(afterWrite, stream, state, finished, cb);
14169 /*</replacement>*/
14170 } else {
14171 afterWrite(stream, state, finished, cb);
14172 }
14173 }
14174}
14175
14176function afterWrite(stream, state, finished, cb) {
14177 if (!finished) onwriteDrain(stream, state);
14178 state.pendingcb--;
14179 cb();
14180 finishMaybe(stream, state);
14181}
14182
14183// Must force callback to be called on nextTick, so that we don't
14184// emit 'drain' before the write() consumer gets the 'false' return
14185// value, and has a chance to attach a 'drain' listener.
14186function onwriteDrain(stream, state) {
14187 if (state.length === 0 && state.needDrain) {
14188 state.needDrain = false;
14189 stream.emit('drain');
14190 }
14191}
14192
14193// if there's something in the buffer waiting, then process it
14194function clearBuffer(stream, state) {
14195 state.bufferProcessing = true;
14196 var entry = state.bufferedRequest;
14197
14198 if (stream._writev && entry && entry.next) {
14199 // Fast case, write everything using _writev()
14200 var l = state.bufferedRequestCount;
14201 var buffer = new Array(l);
14202 var holder = state.corkedRequestsFree;
14203 holder.entry = entry;
14204
14205 var count = 0;
14206 var allBuffers = true;
14207 while (entry) {
14208 buffer[count] = entry;
14209 if (!entry.isBuf) allBuffers = false;
14210 entry = entry.next;
14211 count += 1;
14212 }
14213 buffer.allBuffers = allBuffers;
14214
14215 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
14216
14217 // doWrite is almost always async, defer these to save a bit of time
14218 // as the hot path ends with doWrite
14219 state.pendingcb++;
14220 state.lastBufferedRequest = null;
14221 if (holder.next) {
14222 state.corkedRequestsFree = holder.next;
14223 holder.next = null;
14224 } else {
14225 state.corkedRequestsFree = new CorkedRequest(state);
14226 }
14227 } else {
14228 // Slow case, write chunks one-by-one
14229 while (entry) {
14230 var chunk = entry.chunk;
14231 var encoding = entry.encoding;
14232 var cb = entry.callback;
14233 var len = state.objectMode ? 1 : chunk.length;
14234
14235 doWrite(stream, state, false, len, chunk, encoding, cb);
14236 entry = entry.next;
14237 // if we didn't call the onwrite immediately, then
14238 // it means that we need to wait until it does.
14239 // also, that means that the chunk and cb are currently
14240 // being processed, so move the buffer counter past them.
14241 if (state.writing) {
14242 break;
14243 }
14244 }
14245
14246 if (entry === null) state.lastBufferedRequest = null;
14247 }
14248
14249 state.bufferedRequestCount = 0;
14250 state.bufferedRequest = entry;
14251 state.bufferProcessing = false;
14252}
14253
14254Writable.prototype._write = function (chunk, encoding, cb) {
14255 cb(new Error('_write() is not implemented'));
14256};
14257
14258Writable.prototype._writev = null;
14259
14260Writable.prototype.end = function (chunk, encoding, cb) {
14261 var state = this._writableState;
14262
14263 if (typeof chunk === 'function') {
14264 cb = chunk;
14265 chunk = null;
14266 encoding = null;
14267 } else if (typeof encoding === 'function') {
14268 cb = encoding;
14269 encoding = null;
14270 }
14271
14272 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
14273
14274 // .end() fully uncorks
14275 if (state.corked) {
14276 state.corked = 1;
14277 this.uncork();
14278 }
14279
14280 // ignore unnecessary end() calls.
14281 if (!state.ending && !state.finished) endWritable(this, state, cb);
14282};
14283
14284function needFinish(state) {
14285 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
14286}
14287function callFinal(stream, state) {
14288 stream._final(function (err) {
14289 state.pendingcb--;
14290 if (err) {
14291 stream.emit('error', err);
14292 }
14293 state.prefinished = true;
14294 stream.emit('prefinish');
14295 finishMaybe(stream, state);
14296 });
14297}
14298function prefinish(stream, state) {
14299 if (!state.prefinished && !state.finalCalled) {
14300 if (typeof stream._final === 'function') {
14301 state.pendingcb++;
14302 state.finalCalled = true;
14303 processNextTick(callFinal, stream, state);
14304 } else {
14305 state.prefinished = true;
14306 stream.emit('prefinish');
14307 }
14308 }
14309}
14310
14311function finishMaybe(stream, state) {
14312 var need = needFinish(state);
14313 if (need) {
14314 prefinish(stream, state);
14315 if (state.pendingcb === 0) {
14316 state.finished = true;
14317 stream.emit('finish');
14318 }
14319 }
14320 return need;
14321}
14322
14323function endWritable(stream, state, cb) {
14324 state.ending = true;
14325 finishMaybe(stream, state);
14326 if (cb) {
14327 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
14328 }
14329 state.ended = true;
14330 stream.writable = false;
14331}
14332
14333function onCorkedFinish(corkReq, state, err) {
14334 var entry = corkReq.entry;
14335 corkReq.entry = null;
14336 while (entry) {
14337 var cb = entry.callback;
14338 state.pendingcb--;
14339 cb(err);
14340 entry = entry.next;
14341 }
14342 if (state.corkedRequestsFree) {
14343 state.corkedRequestsFree.next = corkReq;
14344 } else {
14345 state.corkedRequestsFree = corkReq;
14346 }
14347}
14348
14349Object.defineProperty(Writable.prototype, 'destroyed', {
14350 get: function () {
14351 if (this._writableState === undefined) {
14352 return false;
14353 }
14354 return this._writableState.destroyed;
14355 },
14356 set: function (value) {
14357 // we ignore the value if the stream
14358 // has not been initialized yet
14359 if (!this._writableState) {
14360 return;
14361 }
14362
14363 // backward compatibility, the user is explicitly
14364 // managing destroyed
14365 this._writableState.destroyed = value;
14366 }
14367});
14368
14369Writable.prototype.destroy = destroyImpl.destroy;
14370Writable.prototype._undestroy = destroyImpl.undestroy;
14371Writable.prototype._destroy = function (err, cb) {
14372 this.end();
14373 cb(err);
14374};
14375}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
14376},{"./_stream_duplex":55,"./internal/streams/destroy":61,"./internal/streams/stream":62,"_process":52,"core-util-is":30,"inherits":45,"process-nextick-args":51,"safe-buffer":68,"util-deprecate":79}],60:[function(require,module,exports){
14377'use strict';
14378
14379/*<replacement>*/
14380
14381function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
14382
14383var Buffer = require('safe-buffer').Buffer;
14384/*</replacement>*/
14385
14386function copyBuffer(src, target, offset) {
14387 src.copy(target, offset);
14388}
14389
14390module.exports = function () {
14391 function BufferList() {
14392 _classCallCheck(this, BufferList);
14393
14394 this.head = null;
14395 this.tail = null;
14396 this.length = 0;
14397 }
14398
14399 BufferList.prototype.push = function push(v) {
14400 var entry = { data: v, next: null };
14401 if (this.length > 0) this.tail.next = entry;else this.head = entry;
14402 this.tail = entry;
14403 ++this.length;
14404 };
14405
14406 BufferList.prototype.unshift = function unshift(v) {
14407 var entry = { data: v, next: this.head };
14408 if (this.length === 0) this.tail = entry;
14409 this.head = entry;
14410 ++this.length;
14411 };
14412
14413 BufferList.prototype.shift = function shift() {
14414 if (this.length === 0) return;
14415 var ret = this.head.data;
14416 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
14417 --this.length;
14418 return ret;
14419 };
14420
14421 BufferList.prototype.clear = function clear() {
14422 this.head = this.tail = null;
14423 this.length = 0;
14424 };
14425
14426 BufferList.prototype.join = function join(s) {
14427 if (this.length === 0) return '';
14428 var p = this.head;
14429 var ret = '' + p.data;
14430 while (p = p.next) {
14431 ret += s + p.data;
14432 }return ret;
14433 };
14434
14435 BufferList.prototype.concat = function concat(n) {
14436 if (this.length === 0) return Buffer.alloc(0);
14437 if (this.length === 1) return this.head.data;
14438 var ret = Buffer.allocUnsafe(n >>> 0);
14439 var p = this.head;
14440 var i = 0;
14441 while (p) {
14442 copyBuffer(p.data, ret, i);
14443 i += p.data.length;
14444 p = p.next;
14445 }
14446 return ret;
14447 };
14448
14449 return BufferList;
14450}();
14451},{"safe-buffer":68}],61:[function(require,module,exports){
14452'use strict';
14453
14454/*<replacement>*/
14455
14456var processNextTick = require('process-nextick-args');
14457/*</replacement>*/
14458
14459// undocumented cb() API, needed for core, not for public API
14460function destroy(err, cb) {
14461 var _this = this;
14462
14463 var readableDestroyed = this._readableState && this._readableState.destroyed;
14464 var writableDestroyed = this._writableState && this._writableState.destroyed;
14465
14466 if (readableDestroyed || writableDestroyed) {
14467 if (cb) {
14468 cb(err);
14469 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
14470 processNextTick(emitErrorNT, this, err);
14471 }
14472 return;
14473 }
14474
14475 // we set destroyed to true before firing error callbacks in order
14476 // to make it re-entrance safe in case destroy() is called within callbacks
14477
14478 if (this._readableState) {
14479 this._readableState.destroyed = true;
14480 }
14481
14482 // if this is a duplex stream mark the writable part as destroyed as well
14483 if (this._writableState) {
14484 this._writableState.destroyed = true;
14485 }
14486
14487 this._destroy(err || null, function (err) {
14488 if (!cb && err) {
14489 processNextTick(emitErrorNT, _this, err);
14490 if (_this._writableState) {
14491 _this._writableState.errorEmitted = true;
14492 }
14493 } else if (cb) {
14494 cb(err);
14495 }
14496 });
14497}
14498
14499function undestroy() {
14500 if (this._readableState) {
14501 this._readableState.destroyed = false;
14502 this._readableState.reading = false;
14503 this._readableState.ended = false;
14504 this._readableState.endEmitted = false;
14505 }
14506
14507 if (this._writableState) {
14508 this._writableState.destroyed = false;
14509 this._writableState.ended = false;
14510 this._writableState.ending = false;
14511 this._writableState.finished = false;
14512 this._writableState.errorEmitted = false;
14513 }
14514}
14515
14516function emitErrorNT(self, err) {
14517 self.emit('error', err);
14518}
14519
14520module.exports = {
14521 destroy: destroy,
14522 undestroy: undestroy
14523};
14524},{"process-nextick-args":51}],62:[function(require,module,exports){
14525module.exports = require('events').EventEmitter;
14526
14527},{"events":41}],63:[function(require,module,exports){
14528module.exports = require('./readable').PassThrough
14529
14530},{"./readable":64}],64:[function(require,module,exports){
14531exports = module.exports = require('./lib/_stream_readable.js');
14532exports.Stream = exports;
14533exports.Readable = exports;
14534exports.Writable = require('./lib/_stream_writable.js');
14535exports.Duplex = require('./lib/_stream_duplex.js');
14536exports.Transform = require('./lib/_stream_transform.js');
14537exports.PassThrough = require('./lib/_stream_passthrough.js');
14538
14539},{"./lib/_stream_duplex.js":55,"./lib/_stream_passthrough.js":56,"./lib/_stream_readable.js":57,"./lib/_stream_transform.js":58,"./lib/_stream_writable.js":59}],65:[function(require,module,exports){
14540module.exports = require('./readable').Transform
14541
14542},{"./readable":64}],66:[function(require,module,exports){
14543module.exports = require('./lib/_stream_writable.js');
14544
14545},{"./lib/_stream_writable.js":59}],67:[function(require,module,exports){
14546(function (Buffer){
14547'use strict'
14548var inherits = require('inherits')
14549var HashBase = require('hash-base')
14550
14551function RIPEMD160 () {
14552 HashBase.call(this, 64)
14553
14554 // state
14555 this._a = 0x67452301
14556 this._b = 0xefcdab89
14557 this._c = 0x98badcfe
14558 this._d = 0x10325476
14559 this._e = 0xc3d2e1f0
14560}
14561
14562inherits(RIPEMD160, HashBase)
14563
14564RIPEMD160.prototype._update = function () {
14565 var m = new Array(16)
14566 for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4)
14567
14568 var al = this._a
14569 var bl = this._b
14570 var cl = this._c
14571 var dl = this._d
14572 var el = this._e
14573
14574 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
14575 // K = 0x00000000
14576 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8
14577 al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10)
14578 el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10)
14579 dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10)
14580 cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10)
14581 bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10)
14582 al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10)
14583 el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10)
14584 dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10)
14585 cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10)
14586 bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10)
14587 al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10)
14588 el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10)
14589 dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10)
14590 cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10)
14591 bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10)
14592 al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10)
14593
14594 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
14595 // K = 0x5a827999
14596 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12
14597 el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10)
14598 dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10)
14599 cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10)
14600 bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10)
14601 al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10)
14602 el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10)
14603 dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10)
14604 cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10)
14605 bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10)
14606 al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10)
14607 el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10)
14608 dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10)
14609 cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10)
14610 bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10)
14611 al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10)
14612 el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10)
14613
14614 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
14615 // K = 0x6ed9eba1
14616 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5
14617 dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10)
14618 cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10)
14619 bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10)
14620 al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10)
14621 el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10)
14622 dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10)
14623 cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10)
14624 bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10)
14625 al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10)
14626 el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10)
14627 dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10)
14628 cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10)
14629 bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10)
14630 al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10)
14631 el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10)
14632 dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10)
14633
14634 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
14635 // K = 0x8f1bbcdc
14636 // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12
14637 cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10)
14638 bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10)
14639 al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10)
14640 el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10)
14641 dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10)
14642 cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10)
14643 bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10)
14644 al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
14645 el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10)
14646 dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10)
14647 cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10)
14648 bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10)
14649 al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
14650 el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10)
14651 dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10)
14652 cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10)
14653
14654 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
14655 // K = 0xa953fd4e
14656 // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
14657 bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10)
14658 al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10)
14659 el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10)
14660 dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10)
14661 cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10)
14662 bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10)
14663 al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10)
14664 el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10)
14665 dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10)
14666 cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10)
14667 bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10)
14668 al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10)
14669 el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10)
14670 dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10)
14671 cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10)
14672 bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10)
14673
14674 var ar = this._a
14675 var br = this._b
14676 var cr = this._c
14677 var dr = this._d
14678 var er = this._e
14679
14680 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
14681 // K' = 0x50a28be6
14682 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6
14683 ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10)
14684 er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10)
14685 dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10)
14686 cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10)
14687 br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10)
14688 ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10)
14689 er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10)
14690 dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10)
14691 cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10)
14692 br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10)
14693 ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10)
14694 er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10)
14695 dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10)
14696 cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10)
14697 br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10)
14698 ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10)
14699
14700 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
14701 // K' = 0x5c4dd124
14702 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11
14703 er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10)
14704 dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10)
14705 cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10)
14706 br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10)
14707 ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10)
14708 er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10)
14709 dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10)
14710 cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10)
14711 br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10)
14712 ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10)
14713 er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10)
14714 dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10)
14715 cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10)
14716 br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10)
14717 ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10)
14718 er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10)
14719
14720 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
14721 // K' = 0x6d703ef3
14722 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5
14723 dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10)
14724 cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10)
14725 br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10)
14726 ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10)
14727 er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10)
14728 dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10)
14729 cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10)
14730 br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10)
14731 ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10)
14732 er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10)
14733 dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10)
14734 cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10)
14735 br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10)
14736 ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10)
14737 er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10)
14738 dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10)
14739
14740 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
14741 // K' = 0x7a6d76e9
14742 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8
14743 cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10)
14744 br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10)
14745 ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10)
14746 er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10)
14747 dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10)
14748 cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10)
14749 br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10)
14750 ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10)
14751 er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10)
14752 dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10)
14753 cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10)
14754 br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10)
14755 ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10)
14756 er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10)
14757 dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10)
14758 cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10)
14759
14760 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
14761 // K' = 0x00000000
14762 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
14763 br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10)
14764 ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10)
14765 er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10)
14766 dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10)
14767 cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10)
14768 br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10)
14769 ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10)
14770 er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10)
14771 dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10)
14772 cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10)
14773 br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10)
14774 ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10)
14775 er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10)
14776 dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10)
14777 cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10)
14778 br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10)
14779
14780 // change state
14781 var t = (this._b + cl + dr) | 0
14782 this._b = (this._c + dl + er) | 0
14783 this._c = (this._d + el + ar) | 0
14784 this._d = (this._e + al + br) | 0
14785 this._e = (this._a + bl + cr) | 0
14786 this._a = t
14787}
14788
14789RIPEMD160.prototype._digest = function () {
14790 // create padding and handle blocks
14791 this._block[this._blockOffset++] = 0x80
14792 if (this._blockOffset > 56) {
14793 this._block.fill(0, this._blockOffset, 64)
14794 this._update()
14795 this._blockOffset = 0
14796 }
14797
14798 this._block.fill(0, this._blockOffset, 56)
14799 this._block.writeUInt32LE(this._length[0], 56)
14800 this._block.writeUInt32LE(this._length[1], 60)
14801 this._update()
14802
14803 // produce result
14804 var buffer = new Buffer(20)
14805 buffer.writeInt32LE(this._a, 0)
14806 buffer.writeInt32LE(this._b, 4)
14807 buffer.writeInt32LE(this._c, 8)
14808 buffer.writeInt32LE(this._d, 12)
14809 buffer.writeInt32LE(this._e, 16)
14810 return buffer
14811}
14812
14813function rotl (x, n) {
14814 return (x << n) | (x >>> (32 - n))
14815}
14816
14817function fn1 (a, b, c, d, e, m, k, s) {
14818 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
14819}
14820
14821function fn2 (a, b, c, d, e, m, k, s) {
14822 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
14823}
14824
14825function fn3 (a, b, c, d, e, m, k, s) {
14826 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
14827}
14828
14829function fn4 (a, b, c, d, e, m, k, s) {
14830 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
14831}
14832
14833function fn5 (a, b, c, d, e, m, k, s) {
14834 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
14835}
14836
14837module.exports = RIPEMD160
14838
14839}).call(this,require("buffer").Buffer)
14840},{"buffer":27,"hash-base":43,"inherits":45}],68:[function(require,module,exports){
14841/* eslint-disable node/no-deprecated-api */
14842var buffer = require('buffer')
14843var Buffer = buffer.Buffer
14844
14845// alternative to using Object.keys for old browsers
14846function copyProps (src, dst) {
14847 for (var key in src) {
14848 dst[key] = src[key]
14849 }
14850}
14851if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
14852 module.exports = buffer
14853} else {
14854 // Copy properties from require('buffer')
14855 copyProps(buffer, exports)
14856 exports.Buffer = SafeBuffer
14857}
14858
14859function SafeBuffer (arg, encodingOrOffset, length) {
14860 return Buffer(arg, encodingOrOffset, length)
14861}
14862
14863// Copy static methods from Buffer
14864copyProps(Buffer, SafeBuffer)
14865
14866SafeBuffer.from = function (arg, encodingOrOffset, length) {
14867 if (typeof arg === 'number') {
14868 throw new TypeError('Argument must not be a number')
14869 }
14870 return Buffer(arg, encodingOrOffset, length)
14871}
14872
14873SafeBuffer.alloc = function (size, fill, encoding) {
14874 if (typeof size !== 'number') {
14875 throw new TypeError('Argument must be a number')
14876 }
14877 var buf = Buffer(size)
14878 if (fill !== undefined) {
14879 if (typeof encoding === 'string') {
14880 buf.fill(fill, encoding)
14881 } else {
14882 buf.fill(fill)
14883 }
14884 } else {
14885 buf.fill(0)
14886 }
14887 return buf
14888}
14889
14890SafeBuffer.allocUnsafe = function (size) {
14891 if (typeof size !== 'number') {
14892 throw new TypeError('Argument must be a number')
14893 }
14894 return Buffer(size)
14895}
14896
14897SafeBuffer.allocUnsafeSlow = function (size) {
14898 if (typeof size !== 'number') {
14899 throw new TypeError('Argument must be a number')
14900 }
14901 return buffer.SlowBuffer(size)
14902}
14903
14904},{"buffer":27}],69:[function(require,module,exports){
14905(function (Buffer){
14906// prototype class for hash functions
14907function Hash (blockSize, finalSize) {
14908 this._block = new Buffer(blockSize)
14909 this._finalSize = finalSize
14910 this._blockSize = blockSize
14911 this._len = 0
14912 this._s = 0
14913}
14914
14915Hash.prototype.update = function (data, enc) {
14916 if (typeof data === 'string') {
14917 enc = enc || 'utf8'
14918 data = new Buffer(data, enc)
14919 }
14920
14921 var l = this._len += data.length
14922 var s = this._s || 0
14923 var f = 0
14924 var buffer = this._block
14925
14926 while (s < l) {
14927 var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize))
14928 var ch = (t - f)
14929
14930 for (var i = 0; i < ch; i++) {
14931 buffer[(s % this._blockSize) + i] = data[i + f]
14932 }
14933
14934 s += ch
14935 f += ch
14936
14937 if ((s % this._blockSize) === 0) {
14938 this._update(buffer)
14939 }
14940 }
14941 this._s = s
14942
14943 return this
14944}
14945
14946Hash.prototype.digest = function (enc) {
14947 // Suppose the length of the message M, in bits, is l
14948 var l = this._len * 8
14949
14950 // Append the bit 1 to the end of the message
14951 this._block[this._len % this._blockSize] = 0x80
14952
14953 // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize
14954 this._block.fill(0, this._len % this._blockSize + 1)
14955
14956 if (l % (this._blockSize * 8) >= this._finalSize * 8) {
14957 this._update(this._block)
14958 this._block.fill(0)
14959 }
14960
14961 // to this append the block which is equal to the number l written in binary
14962 // TODO: handle case where l is > Math.pow(2, 29)
14963 this._block.writeInt32BE(l, this._blockSize - 4)
14964
14965 var hash = this._update(this._block) || this._hash()
14966
14967 return enc ? hash.toString(enc) : hash
14968}
14969
14970Hash.prototype._update = function () {
14971 throw new Error('_update must be implemented by subclass')
14972}
14973
14974module.exports = Hash
14975
14976}).call(this,require("buffer").Buffer)
14977},{"buffer":27}],70:[function(require,module,exports){
14978var exports = module.exports = function SHA (algorithm) {
14979 algorithm = algorithm.toLowerCase()
14980
14981 var Algorithm = exports[algorithm]
14982 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
14983
14984 return new Algorithm()
14985}
14986
14987exports.sha = require('./sha')
14988exports.sha1 = require('./sha1')
14989exports.sha224 = require('./sha224')
14990exports.sha256 = require('./sha256')
14991exports.sha384 = require('./sha384')
14992exports.sha512 = require('./sha512')
14993
14994},{"./sha":71,"./sha1":72,"./sha224":73,"./sha256":74,"./sha384":75,"./sha512":76}],71:[function(require,module,exports){
14995(function (Buffer){
14996/*
14997 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
14998 * in FIPS PUB 180-1
14999 * This source code is derived from sha1.js of the same repository.
15000 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
15001 * operation was added.
15002 */
15003
15004var inherits = require('inherits')
15005var Hash = require('./hash')
15006
15007var K = [
15008 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
15009]
15010
15011var W = new Array(80)
15012
15013function Sha () {
15014 this.init()
15015 this._w = W
15016
15017 Hash.call(this, 64, 56)
15018}
15019
15020inherits(Sha, Hash)
15021
15022Sha.prototype.init = function () {
15023 this._a = 0x67452301
15024 this._b = 0xefcdab89
15025 this._c = 0x98badcfe
15026 this._d = 0x10325476
15027 this._e = 0xc3d2e1f0
15028
15029 return this
15030}
15031
15032function rotl5 (num) {
15033 return (num << 5) | (num >>> 27)
15034}
15035
15036function rotl30 (num) {
15037 return (num << 30) | (num >>> 2)
15038}
15039
15040function ft (s, b, c, d) {
15041 if (s === 0) return (b & c) | ((~b) & d)
15042 if (s === 2) return (b & c) | (b & d) | (c & d)
15043 return b ^ c ^ d
15044}
15045
15046Sha.prototype._update = function (M) {
15047 var W = this._w
15048
15049 var a = this._a | 0
15050 var b = this._b | 0
15051 var c = this._c | 0
15052 var d = this._d | 0
15053 var e = this._e | 0
15054
15055 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
15056 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
15057
15058 for (var j = 0; j < 80; ++j) {
15059 var s = ~~(j / 20)
15060 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
15061
15062 e = d
15063 d = c
15064 c = rotl30(b)
15065 b = a
15066 a = t
15067 }
15068
15069 this._a = (a + this._a) | 0
15070 this._b = (b + this._b) | 0
15071 this._c = (c + this._c) | 0
15072 this._d = (d + this._d) | 0
15073 this._e = (e + this._e) | 0
15074}
15075
15076Sha.prototype._hash = function () {
15077 var H = new Buffer(20)
15078
15079 H.writeInt32BE(this._a | 0, 0)
15080 H.writeInt32BE(this._b | 0, 4)
15081 H.writeInt32BE(this._c | 0, 8)
15082 H.writeInt32BE(this._d | 0, 12)
15083 H.writeInt32BE(this._e | 0, 16)
15084
15085 return H
15086}
15087
15088module.exports = Sha
15089
15090}).call(this,require("buffer").Buffer)
15091},{"./hash":69,"buffer":27,"inherits":45}],72:[function(require,module,exports){
15092(function (Buffer){
15093/*
15094 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
15095 * in FIPS PUB 180-1
15096 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
15097 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
15098 * Distributed under the BSD License
15099 * See http://pajhome.org.uk/crypt/md5 for details.
15100 */
15101
15102var inherits = require('inherits')
15103var Hash = require('./hash')
15104
15105var K = [
15106 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
15107]
15108
15109var W = new Array(80)
15110
15111function Sha1 () {
15112 this.init()
15113 this._w = W
15114
15115 Hash.call(this, 64, 56)
15116}
15117
15118inherits(Sha1, Hash)
15119
15120Sha1.prototype.init = function () {
15121 this._a = 0x67452301
15122 this._b = 0xefcdab89
15123 this._c = 0x98badcfe
15124 this._d = 0x10325476
15125 this._e = 0xc3d2e1f0
15126
15127 return this
15128}
15129
15130function rotl1 (num) {
15131 return (num << 1) | (num >>> 31)
15132}
15133
15134function rotl5 (num) {
15135 return (num << 5) | (num >>> 27)
15136}
15137
15138function rotl30 (num) {
15139 return (num << 30) | (num >>> 2)
15140}
15141
15142function ft (s, b, c, d) {
15143 if (s === 0) return (b & c) | ((~b) & d)
15144 if (s === 2) return (b & c) | (b & d) | (c & d)
15145 return b ^ c ^ d
15146}
15147
15148Sha1.prototype._update = function (M) {
15149 var W = this._w
15150
15151 var a = this._a | 0
15152 var b = this._b | 0
15153 var c = this._c | 0
15154 var d = this._d | 0
15155 var e = this._e | 0
15156
15157 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
15158 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
15159
15160 for (var j = 0; j < 80; ++j) {
15161 var s = ~~(j / 20)
15162 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
15163
15164 e = d
15165 d = c
15166 c = rotl30(b)
15167 b = a
15168 a = t
15169 }
15170
15171 this._a = (a + this._a) | 0
15172 this._b = (b + this._b) | 0
15173 this._c = (c + this._c) | 0
15174 this._d = (d + this._d) | 0
15175 this._e = (e + this._e) | 0
15176}
15177
15178Sha1.prototype._hash = function () {
15179 var H = new Buffer(20)
15180
15181 H.writeInt32BE(this._a | 0, 0)
15182 H.writeInt32BE(this._b | 0, 4)
15183 H.writeInt32BE(this._c | 0, 8)
15184 H.writeInt32BE(this._d | 0, 12)
15185 H.writeInt32BE(this._e | 0, 16)
15186
15187 return H
15188}
15189
15190module.exports = Sha1
15191
15192}).call(this,require("buffer").Buffer)
15193},{"./hash":69,"buffer":27,"inherits":45}],73:[function(require,module,exports){
15194(function (Buffer){
15195/**
15196 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
15197 * in FIPS 180-2
15198 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
15199 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
15200 *
15201 */
15202
15203var inherits = require('inherits')
15204var Sha256 = require('./sha256')
15205var Hash = require('./hash')
15206
15207var W = new Array(64)
15208
15209function Sha224 () {
15210 this.init()
15211
15212 this._w = W // new Array(64)
15213
15214 Hash.call(this, 64, 56)
15215}
15216
15217inherits(Sha224, Sha256)
15218
15219Sha224.prototype.init = function () {
15220 this._a = 0xc1059ed8
15221 this._b = 0x367cd507
15222 this._c = 0x3070dd17
15223 this._d = 0xf70e5939
15224 this._e = 0xffc00b31
15225 this._f = 0x68581511
15226 this._g = 0x64f98fa7
15227 this._h = 0xbefa4fa4
15228
15229 return this
15230}
15231
15232Sha224.prototype._hash = function () {
15233 var H = new Buffer(28)
15234
15235 H.writeInt32BE(this._a, 0)
15236 H.writeInt32BE(this._b, 4)
15237 H.writeInt32BE(this._c, 8)
15238 H.writeInt32BE(this._d, 12)
15239 H.writeInt32BE(this._e, 16)
15240 H.writeInt32BE(this._f, 20)
15241 H.writeInt32BE(this._g, 24)
15242
15243 return H
15244}
15245
15246module.exports = Sha224
15247
15248}).call(this,require("buffer").Buffer)
15249},{"./hash":69,"./sha256":74,"buffer":27,"inherits":45}],74:[function(require,module,exports){
15250(function (Buffer){
15251/**
15252 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
15253 * in FIPS 180-2
15254 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
15255 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
15256 *
15257 */
15258
15259var inherits = require('inherits')
15260var Hash = require('./hash')
15261
15262var K = [
15263 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
15264 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
15265 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
15266 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
15267 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
15268 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
15269 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
15270 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
15271 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
15272 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
15273 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
15274 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
15275 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
15276 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
15277 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
15278 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
15279]
15280
15281var W = new Array(64)
15282
15283function Sha256 () {
15284 this.init()
15285
15286 this._w = W // new Array(64)
15287
15288 Hash.call(this, 64, 56)
15289}
15290
15291inherits(Sha256, Hash)
15292
15293Sha256.prototype.init = function () {
15294 this._a = 0x6a09e667
15295 this._b = 0xbb67ae85
15296 this._c = 0x3c6ef372
15297 this._d = 0xa54ff53a
15298 this._e = 0x510e527f
15299 this._f = 0x9b05688c
15300 this._g = 0x1f83d9ab
15301 this._h = 0x5be0cd19
15302
15303 return this
15304}
15305
15306function ch (x, y, z) {
15307 return z ^ (x & (y ^ z))
15308}
15309
15310function maj (x, y, z) {
15311 return (x & y) | (z & (x | y))
15312}
15313
15314function sigma0 (x) {
15315 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
15316}
15317
15318function sigma1 (x) {
15319 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
15320}
15321
15322function gamma0 (x) {
15323 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
15324}
15325
15326function gamma1 (x) {
15327 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
15328}
15329
15330Sha256.prototype._update = function (M) {
15331 var W = this._w
15332
15333 var a = this._a | 0
15334 var b = this._b | 0
15335 var c = this._c | 0
15336 var d = this._d | 0
15337 var e = this._e | 0
15338 var f = this._f | 0
15339 var g = this._g | 0
15340 var h = this._h | 0
15341
15342 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
15343 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
15344
15345 for (var j = 0; j < 64; ++j) {
15346 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
15347 var T2 = (sigma0(a) + maj(a, b, c)) | 0
15348
15349 h = g
15350 g = f
15351 f = e
15352 e = (d + T1) | 0
15353 d = c
15354 c = b
15355 b = a
15356 a = (T1 + T2) | 0
15357 }
15358
15359 this._a = (a + this._a) | 0
15360 this._b = (b + this._b) | 0
15361 this._c = (c + this._c) | 0
15362 this._d = (d + this._d) | 0
15363 this._e = (e + this._e) | 0
15364 this._f = (f + this._f) | 0
15365 this._g = (g + this._g) | 0
15366 this._h = (h + this._h) | 0
15367}
15368
15369Sha256.prototype._hash = function () {
15370 var H = new Buffer(32)
15371
15372 H.writeInt32BE(this._a, 0)
15373 H.writeInt32BE(this._b, 4)
15374 H.writeInt32BE(this._c, 8)
15375 H.writeInt32BE(this._d, 12)
15376 H.writeInt32BE(this._e, 16)
15377 H.writeInt32BE(this._f, 20)
15378 H.writeInt32BE(this._g, 24)
15379 H.writeInt32BE(this._h, 28)
15380
15381 return H
15382}
15383
15384module.exports = Sha256
15385
15386}).call(this,require("buffer").Buffer)
15387},{"./hash":69,"buffer":27,"inherits":45}],75:[function(require,module,exports){
15388(function (Buffer){
15389var inherits = require('inherits')
15390var SHA512 = require('./sha512')
15391var Hash = require('./hash')
15392
15393var W = new Array(160)
15394
15395function Sha384 () {
15396 this.init()
15397 this._w = W
15398
15399 Hash.call(this, 128, 112)
15400}
15401
15402inherits(Sha384, SHA512)
15403
15404Sha384.prototype.init = function () {
15405 this._ah = 0xcbbb9d5d
15406 this._bh = 0x629a292a
15407 this._ch = 0x9159015a
15408 this._dh = 0x152fecd8
15409 this._eh = 0x67332667
15410 this._fh = 0x8eb44a87
15411 this._gh = 0xdb0c2e0d
15412 this._hh = 0x47b5481d
15413
15414 this._al = 0xc1059ed8
15415 this._bl = 0x367cd507
15416 this._cl = 0x3070dd17
15417 this._dl = 0xf70e5939
15418 this._el = 0xffc00b31
15419 this._fl = 0x68581511
15420 this._gl = 0x64f98fa7
15421 this._hl = 0xbefa4fa4
15422
15423 return this
15424}
15425
15426Sha384.prototype._hash = function () {
15427 var H = new Buffer(48)
15428
15429 function writeInt64BE (h, l, offset) {
15430 H.writeInt32BE(h, offset)
15431 H.writeInt32BE(l, offset + 4)
15432 }
15433
15434 writeInt64BE(this._ah, this._al, 0)
15435 writeInt64BE(this._bh, this._bl, 8)
15436 writeInt64BE(this._ch, this._cl, 16)
15437 writeInt64BE(this._dh, this._dl, 24)
15438 writeInt64BE(this._eh, this._el, 32)
15439 writeInt64BE(this._fh, this._fl, 40)
15440
15441 return H
15442}
15443
15444module.exports = Sha384
15445
15446}).call(this,require("buffer").Buffer)
15447},{"./hash":69,"./sha512":76,"buffer":27,"inherits":45}],76:[function(require,module,exports){
15448(function (Buffer){
15449var inherits = require('inherits')
15450var Hash = require('./hash')
15451
15452var K = [
15453 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
15454 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
15455 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
15456 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
15457 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
15458 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
15459 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
15460 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
15461 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
15462 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
15463 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
15464 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
15465 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
15466 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
15467 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
15468 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
15469 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
15470 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
15471 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
15472 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
15473 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
15474 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
15475 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
15476 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
15477 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
15478 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
15479 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
15480 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
15481 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
15482 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
15483 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
15484 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
15485 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
15486 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
15487 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
15488 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
15489 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
15490 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
15491 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
15492 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
15493]
15494
15495var W = new Array(160)
15496
15497function Sha512 () {
15498 this.init()
15499 this._w = W
15500
15501 Hash.call(this, 128, 112)
15502}
15503
15504inherits(Sha512, Hash)
15505
15506Sha512.prototype.init = function () {
15507 this._ah = 0x6a09e667
15508 this._bh = 0xbb67ae85
15509 this._ch = 0x3c6ef372
15510 this._dh = 0xa54ff53a
15511 this._eh = 0x510e527f
15512 this._fh = 0x9b05688c
15513 this._gh = 0x1f83d9ab
15514 this._hh = 0x5be0cd19
15515
15516 this._al = 0xf3bcc908
15517 this._bl = 0x84caa73b
15518 this._cl = 0xfe94f82b
15519 this._dl = 0x5f1d36f1
15520 this._el = 0xade682d1
15521 this._fl = 0x2b3e6c1f
15522 this._gl = 0xfb41bd6b
15523 this._hl = 0x137e2179
15524
15525 return this
15526}
15527
15528function Ch (x, y, z) {
15529 return z ^ (x & (y ^ z))
15530}
15531
15532function maj (x, y, z) {
15533 return (x & y) | (z & (x | y))
15534}
15535
15536function sigma0 (x, xl) {
15537 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
15538}
15539
15540function sigma1 (x, xl) {
15541 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
15542}
15543
15544function Gamma0 (x, xl) {
15545 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
15546}
15547
15548function Gamma0l (x, xl) {
15549 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
15550}
15551
15552function Gamma1 (x, xl) {
15553 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
15554}
15555
15556function Gamma1l (x, xl) {
15557 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
15558}
15559
15560function getCarry (a, b) {
15561 return (a >>> 0) < (b >>> 0) ? 1 : 0
15562}
15563
15564Sha512.prototype._update = function (M) {
15565 var W = this._w
15566
15567 var ah = this._ah | 0
15568 var bh = this._bh | 0
15569 var ch = this._ch | 0
15570 var dh = this._dh | 0
15571 var eh = this._eh | 0
15572 var fh = this._fh | 0
15573 var gh = this._gh | 0
15574 var hh = this._hh | 0
15575
15576 var al = this._al | 0
15577 var bl = this._bl | 0
15578 var cl = this._cl | 0
15579 var dl = this._dl | 0
15580 var el = this._el | 0
15581 var fl = this._fl | 0
15582 var gl = this._gl | 0
15583 var hl = this._hl | 0
15584
15585 for (var i = 0; i < 32; i += 2) {
15586 W[i] = M.readInt32BE(i * 4)
15587 W[i + 1] = M.readInt32BE(i * 4 + 4)
15588 }
15589 for (; i < 160; i += 2) {
15590 var xh = W[i - 15 * 2]
15591 var xl = W[i - 15 * 2 + 1]
15592 var gamma0 = Gamma0(xh, xl)
15593 var gamma0l = Gamma0l(xl, xh)
15594
15595 xh = W[i - 2 * 2]
15596 xl = W[i - 2 * 2 + 1]
15597 var gamma1 = Gamma1(xh, xl)
15598 var gamma1l = Gamma1l(xl, xh)
15599
15600 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
15601 var Wi7h = W[i - 7 * 2]
15602 var Wi7l = W[i - 7 * 2 + 1]
15603
15604 var Wi16h = W[i - 16 * 2]
15605 var Wi16l = W[i - 16 * 2 + 1]
15606
15607 var Wil = (gamma0l + Wi7l) | 0
15608 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
15609 Wil = (Wil + gamma1l) | 0
15610 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
15611 Wil = (Wil + Wi16l) | 0
15612 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
15613
15614 W[i] = Wih
15615 W[i + 1] = Wil
15616 }
15617
15618 for (var j = 0; j < 160; j += 2) {
15619 Wih = W[j]
15620 Wil = W[j + 1]
15621
15622 var majh = maj(ah, bh, ch)
15623 var majl = maj(al, bl, cl)
15624
15625 var sigma0h = sigma0(ah, al)
15626 var sigma0l = sigma0(al, ah)
15627 var sigma1h = sigma1(eh, el)
15628 var sigma1l = sigma1(el, eh)
15629
15630 // t1 = h + sigma1 + ch + K[j] + W[j]
15631 var Kih = K[j]
15632 var Kil = K[j + 1]
15633
15634 var chh = Ch(eh, fh, gh)
15635 var chl = Ch(el, fl, gl)
15636
15637 var t1l = (hl + sigma1l) | 0
15638 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
15639 t1l = (t1l + chl) | 0
15640 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
15641 t1l = (t1l + Kil) | 0
15642 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
15643 t1l = (t1l + Wil) | 0
15644 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
15645
15646 // t2 = sigma0 + maj
15647 var t2l = (sigma0l + majl) | 0
15648 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
15649
15650 hh = gh
15651 hl = gl
15652 gh = fh
15653 gl = fl
15654 fh = eh
15655 fl = el
15656 el = (dl + t1l) | 0
15657 eh = (dh + t1h + getCarry(el, dl)) | 0
15658 dh = ch
15659 dl = cl
15660 ch = bh
15661 cl = bl
15662 bh = ah
15663 bl = al
15664 al = (t1l + t2l) | 0
15665 ah = (t1h + t2h + getCarry(al, t1l)) | 0
15666 }
15667
15668 this._al = (this._al + al) | 0
15669 this._bl = (this._bl + bl) | 0
15670 this._cl = (this._cl + cl) | 0
15671 this._dl = (this._dl + dl) | 0
15672 this._el = (this._el + el) | 0
15673 this._fl = (this._fl + fl) | 0
15674 this._gl = (this._gl + gl) | 0
15675 this._hl = (this._hl + hl) | 0
15676
15677 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
15678 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
15679 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
15680 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
15681 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
15682 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
15683 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
15684 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
15685}
15686
15687Sha512.prototype._hash = function () {
15688 var H = new Buffer(64)
15689
15690 function writeInt64BE (h, l, offset) {
15691 H.writeInt32BE(h, offset)
15692 H.writeInt32BE(l, offset + 4)
15693 }
15694
15695 writeInt64BE(this._ah, this._al, 0)
15696 writeInt64BE(this._bh, this._bl, 8)
15697 writeInt64BE(this._ch, this._cl, 16)
15698 writeInt64BE(this._dh, this._dl, 24)
15699 writeInt64BE(this._eh, this._el, 32)
15700 writeInt64BE(this._fh, this._fl, 40)
15701 writeInt64BE(this._gh, this._gl, 48)
15702 writeInt64BE(this._hh, this._hl, 56)
15703
15704 return H
15705}
15706
15707module.exports = Sha512
15708
15709}).call(this,require("buffer").Buffer)
15710},{"./hash":69,"buffer":27,"inherits":45}],77:[function(require,module,exports){
15711// Copyright Joyent, Inc. and other Node contributors.
15712//
15713// Permission is hereby granted, free of charge, to any person obtaining a
15714// copy of this software and associated documentation files (the
15715// "Software"), to deal in the Software without restriction, including
15716// without limitation the rights to use, copy, modify, merge, publish,
15717// distribute, sublicense, and/or sell copies of the Software, and to permit
15718// persons to whom the Software is furnished to do so, subject to the
15719// following conditions:
15720//
15721// The above copyright notice and this permission notice shall be included
15722// in all copies or substantial portions of the Software.
15723//
15724// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15725// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15726// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15727// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15728// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15729// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15730// USE OR OTHER DEALINGS IN THE SOFTWARE.
15731
15732module.exports = Stream;
15733
15734var EE = require('events').EventEmitter;
15735var inherits = require('inherits');
15736
15737inherits(Stream, EE);
15738Stream.Readable = require('readable-stream/readable.js');
15739Stream.Writable = require('readable-stream/writable.js');
15740Stream.Duplex = require('readable-stream/duplex.js');
15741Stream.Transform = require('readable-stream/transform.js');
15742Stream.PassThrough = require('readable-stream/passthrough.js');
15743
15744// Backwards-compat with node 0.4.x
15745Stream.Stream = Stream;
15746
15747
15748
15749// old-style streams. Note that the pipe method (the only relevant
15750// part of this class) is overridden in the Readable class.
15751
15752function Stream() {
15753 EE.call(this);
15754}
15755
15756Stream.prototype.pipe = function(dest, options) {
15757 var source = this;
15758
15759 function ondata(chunk) {
15760 if (dest.writable) {
15761 if (false === dest.write(chunk) && source.pause) {
15762 source.pause();
15763 }
15764 }
15765 }
15766
15767 source.on('data', ondata);
15768
15769 function ondrain() {
15770 if (source.readable && source.resume) {
15771 source.resume();
15772 }
15773 }
15774
15775 dest.on('drain', ondrain);
15776
15777 // If the 'end' option is not supplied, dest.end() will be called when
15778 // source gets the 'end' or 'close' events. Only dest.end() once.
15779 if (!dest._isStdio && (!options || options.end !== false)) {
15780 source.on('end', onend);
15781 source.on('close', onclose);
15782 }
15783
15784 var didOnEnd = false;
15785 function onend() {
15786 if (didOnEnd) return;
15787 didOnEnd = true;
15788
15789 dest.end();
15790 }
15791
15792
15793 function onclose() {
15794 if (didOnEnd) return;
15795 didOnEnd = true;
15796
15797 if (typeof dest.destroy === 'function') dest.destroy();
15798 }
15799
15800 // don't leave dangling pipes when there are errors.
15801 function onerror(er) {
15802 cleanup();
15803 if (EE.listenerCount(this, 'error') === 0) {
15804 throw er; // Unhandled stream error in pipe.
15805 }
15806 }
15807
15808 source.on('error', onerror);
15809 dest.on('error', onerror);
15810
15811 // remove all the event listeners that were added.
15812 function cleanup() {
15813 source.removeListener('data', ondata);
15814 dest.removeListener('drain', ondrain);
15815
15816 source.removeListener('end', onend);
15817 source.removeListener('close', onclose);
15818
15819 source.removeListener('error', onerror);
15820 dest.removeListener('error', onerror);
15821
15822 source.removeListener('end', cleanup);
15823 source.removeListener('close', cleanup);
15824
15825 dest.removeListener('close', cleanup);
15826 }
15827
15828 source.on('end', cleanup);
15829 source.on('close', cleanup);
15830
15831 dest.on('close', cleanup);
15832
15833 dest.emit('pipe', source);
15834
15835 // Allow for unix-like usage: A.pipe(B).pipe(C)
15836 return dest;
15837};
15838
15839},{"events":41,"inherits":45,"readable-stream/duplex.js":54,"readable-stream/passthrough.js":63,"readable-stream/readable.js":64,"readable-stream/transform.js":65,"readable-stream/writable.js":66}],78:[function(require,module,exports){
15840'use strict';
15841
15842var Buffer = require('safe-buffer').Buffer;
15843
15844var isEncoding = Buffer.isEncoding || function (encoding) {
15845 encoding = '' + encoding;
15846 switch (encoding && encoding.toLowerCase()) {
15847 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':
15848 return true;
15849 default:
15850 return false;
15851 }
15852};
15853
15854function _normalizeEncoding(enc) {
15855 if (!enc) return 'utf8';
15856 var retried;
15857 while (true) {
15858 switch (enc) {
15859 case 'utf8':
15860 case 'utf-8':
15861 return 'utf8';
15862 case 'ucs2':
15863 case 'ucs-2':
15864 case 'utf16le':
15865 case 'utf-16le':
15866 return 'utf16le';
15867 case 'latin1':
15868 case 'binary':
15869 return 'latin1';
15870 case 'base64':
15871 case 'ascii':
15872 case 'hex':
15873 return enc;
15874 default:
15875 if (retried) return; // undefined
15876 enc = ('' + enc).toLowerCase();
15877 retried = true;
15878 }
15879 }
15880};
15881
15882// Do not cache `Buffer.isEncoding` when checking encoding names as some
15883// modules monkey-patch it to support additional encodings
15884function normalizeEncoding(enc) {
15885 var nenc = _normalizeEncoding(enc);
15886 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
15887 return nenc || enc;
15888}
15889
15890// StringDecoder provides an interface for efficiently splitting a series of
15891// buffers into a series of JS strings without breaking apart multi-byte
15892// characters.
15893exports.StringDecoder = StringDecoder;
15894function StringDecoder(encoding) {
15895 this.encoding = normalizeEncoding(encoding);
15896 var nb;
15897 switch (this.encoding) {
15898 case 'utf16le':
15899 this.text = utf16Text;
15900 this.end = utf16End;
15901 nb = 4;
15902 break;
15903 case 'utf8':
15904 this.fillLast = utf8FillLast;
15905 nb = 4;
15906 break;
15907 case 'base64':
15908 this.text = base64Text;
15909 this.end = base64End;
15910 nb = 3;
15911 break;
15912 default:
15913 this.write = simpleWrite;
15914 this.end = simpleEnd;
15915 return;
15916 }
15917 this.lastNeed = 0;
15918 this.lastTotal = 0;
15919 this.lastChar = Buffer.allocUnsafe(nb);
15920}
15921
15922StringDecoder.prototype.write = function (buf) {
15923 if (buf.length === 0) return '';
15924 var r;
15925 var i;
15926 if (this.lastNeed) {
15927 r = this.fillLast(buf);
15928 if (r === undefined) return '';
15929 i = this.lastNeed;
15930 this.lastNeed = 0;
15931 } else {
15932 i = 0;
15933 }
15934 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
15935 return r || '';
15936};
15937
15938StringDecoder.prototype.end = utf8End;
15939
15940// Returns only complete characters in a Buffer
15941StringDecoder.prototype.text = utf8Text;
15942
15943// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
15944StringDecoder.prototype.fillLast = function (buf) {
15945 if (this.lastNeed <= buf.length) {
15946 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
15947 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
15948 }
15949 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
15950 this.lastNeed -= buf.length;
15951};
15952
15953// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
15954// continuation byte.
15955function utf8CheckByte(byte) {
15956 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
15957 return -1;
15958}
15959
15960// Checks at most 3 bytes at the end of a Buffer in order to detect an
15961// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
15962// needed to complete the UTF-8 character (if applicable) are returned.
15963function utf8CheckIncomplete(self, buf, i) {
15964 var j = buf.length - 1;
15965 if (j < i) return 0;
15966 var nb = utf8CheckByte(buf[j]);
15967 if (nb >= 0) {
15968 if (nb > 0) self.lastNeed = nb - 1;
15969 return nb;
15970 }
15971 if (--j < i) return 0;
15972 nb = utf8CheckByte(buf[j]);
15973 if (nb >= 0) {
15974 if (nb > 0) self.lastNeed = nb - 2;
15975 return nb;
15976 }
15977 if (--j < i) return 0;
15978 nb = utf8CheckByte(buf[j]);
15979 if (nb >= 0) {
15980 if (nb > 0) {
15981 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
15982 }
15983 return nb;
15984 }
15985 return 0;
15986}
15987
15988// Validates as many continuation bytes for a multi-byte UTF-8 character as
15989// needed or are available. If we see a non-continuation byte where we expect
15990// one, we "replace" the validated continuation bytes we've seen so far with
15991// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
15992// behavior. The continuation byte check is included three times in the case
15993// where all of the continuation bytes for a character exist in the same buffer.
15994// It is also done this way as a slight performance increase instead of using a
15995// loop.
15996function utf8CheckExtraBytes(self, buf, p) {
15997 if ((buf[0] & 0xC0) !== 0x80) {
15998 self.lastNeed = 0;
15999 return '\ufffd'.repeat(p);
16000 }
16001 if (self.lastNeed > 1 && buf.length > 1) {
16002 if ((buf[1] & 0xC0) !== 0x80) {
16003 self.lastNeed = 1;
16004 return '\ufffd'.repeat(p + 1);
16005 }
16006 if (self.lastNeed > 2 && buf.length > 2) {
16007 if ((buf[2] & 0xC0) !== 0x80) {
16008 self.lastNeed = 2;
16009 return '\ufffd'.repeat(p + 2);
16010 }
16011 }
16012 }
16013}
16014
16015// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
16016function utf8FillLast(buf) {
16017 var p = this.lastTotal - this.lastNeed;
16018 var r = utf8CheckExtraBytes(this, buf, p);
16019 if (r !== undefined) return r;
16020 if (this.lastNeed <= buf.length) {
16021 buf.copy(this.lastChar, p, 0, this.lastNeed);
16022 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16023 }
16024 buf.copy(this.lastChar, p, 0, buf.length);
16025 this.lastNeed -= buf.length;
16026}
16027
16028// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
16029// partial character, the character's bytes are buffered until the required
16030// number of bytes are available.
16031function utf8Text(buf, i) {
16032 var total = utf8CheckIncomplete(this, buf, i);
16033 if (!this.lastNeed) return buf.toString('utf8', i);
16034 this.lastTotal = total;
16035 var end = buf.length - (total - this.lastNeed);
16036 buf.copy(this.lastChar, 0, end);
16037 return buf.toString('utf8', i, end);
16038}
16039
16040// For UTF-8, a replacement character for each buffered byte of a (partial)
16041// character needs to be added to the output.
16042function utf8End(buf) {
16043 var r = buf && buf.length ? this.write(buf) : '';
16044 if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
16045 return r;
16046}
16047
16048// UTF-16LE typically needs two bytes per character, but even if we have an even
16049// number of bytes available, we need to check if we end on a leading/high
16050// surrogate. In that case, we need to wait for the next two bytes in order to
16051// decode the last character properly.
16052function utf16Text(buf, i) {
16053 if ((buf.length - i) % 2 === 0) {
16054 var r = buf.toString('utf16le', i);
16055 if (r) {
16056 var c = r.charCodeAt(r.length - 1);
16057 if (c >= 0xD800 && c <= 0xDBFF) {
16058 this.lastNeed = 2;
16059 this.lastTotal = 4;
16060 this.lastChar[0] = buf[buf.length - 2];
16061 this.lastChar[1] = buf[buf.length - 1];
16062 return r.slice(0, -1);
16063 }
16064 }
16065 return r;
16066 }
16067 this.lastNeed = 1;
16068 this.lastTotal = 2;
16069 this.lastChar[0] = buf[buf.length - 1];
16070 return buf.toString('utf16le', i, buf.length - 1);
16071}
16072
16073// For UTF-16LE we do not explicitly append special replacement characters if we
16074// end on a partial character, we simply let v8 handle that.
16075function utf16End(buf) {
16076 var r = buf && buf.length ? this.write(buf) : '';
16077 if (this.lastNeed) {
16078 var end = this.lastTotal - this.lastNeed;
16079 return r + this.lastChar.toString('utf16le', 0, end);
16080 }
16081 return r;
16082}
16083
16084function base64Text(buf, i) {
16085 var n = (buf.length - i) % 3;
16086 if (n === 0) return buf.toString('base64', i);
16087 this.lastNeed = 3 - n;
16088 this.lastTotal = 3;
16089 if (n === 1) {
16090 this.lastChar[0] = buf[buf.length - 1];
16091 } else {
16092 this.lastChar[0] = buf[buf.length - 2];
16093 this.lastChar[1] = buf[buf.length - 1];
16094 }
16095 return buf.toString('base64', i, buf.length - n);
16096}
16097
16098function base64End(buf) {
16099 var r = buf && buf.length ? this.write(buf) : '';
16100 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
16101 return r;
16102}
16103
16104// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
16105function simpleWrite(buf) {
16106 return buf.toString(this.encoding);
16107}
16108
16109function simpleEnd(buf) {
16110 return buf && buf.length ? this.write(buf) : '';
16111}
16112},{"safe-buffer":68}],79:[function(require,module,exports){
16113(function (global){
16114
16115/**
16116 * Module exports.
16117 */
16118
16119module.exports = deprecate;
16120
16121/**
16122 * Mark that a method should not be used.
16123 * Returns a modified function which warns once by default.
16124 *
16125 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
16126 *
16127 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
16128 * will throw an Error when invoked.
16129 *
16130 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
16131 * will invoke `console.trace()` instead of `console.error()`.
16132 *
16133 * @param {Function} fn - the function to deprecate
16134 * @param {String} msg - the string to print to the console when `fn` is invoked
16135 * @returns {Function} a new "deprecated" version of `fn`
16136 * @api public
16137 */
16138
16139function deprecate (fn, msg) {
16140 if (config('noDeprecation')) {
16141 return fn;
16142 }
16143
16144 var warned = false;
16145 function deprecated() {
16146 if (!warned) {
16147 if (config('throwDeprecation')) {
16148 throw new Error(msg);
16149 } else if (config('traceDeprecation')) {
16150 console.trace(msg);
16151 } else {
16152 console.warn(msg);
16153 }
16154 warned = true;
16155 }
16156 return fn.apply(this, arguments);
16157 }
16158
16159 return deprecated;
16160}
16161
16162/**
16163 * Checks `localStorage` for boolean values for the given `name`.
16164 *
16165 * @param {String} name
16166 * @returns {Boolean}
16167 * @api private
16168 */
16169
16170function config (name) {
16171 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
16172 try {
16173 if (!global.localStorage) return false;
16174 } catch (_) {
16175 return false;
16176 }
16177 var val = global.localStorage[name];
16178 if (null == val) return false;
16179 return String(val).toLowerCase() === 'true';
16180}
16181
16182}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
16183},{}],80:[function(require,module,exports){
16184arguments[4][45][0].apply(exports,arguments)
16185},{"dup":45}],81:[function(require,module,exports){
16186module.exports = function isBuffer(arg) {
16187 return arg && typeof arg === 'object'
16188 && typeof arg.copy === 'function'
16189 && typeof arg.fill === 'function'
16190 && typeof arg.readUInt8 === 'function';
16191}
16192},{}],82:[function(require,module,exports){
16193(function (process,global){
16194// Copyright Joyent, Inc. and other Node contributors.
16195//
16196// Permission is hereby granted, free of charge, to any person obtaining a
16197// copy of this software and associated documentation files (the
16198// "Software"), to deal in the Software without restriction, including
16199// without limitation the rights to use, copy, modify, merge, publish,
16200// distribute, sublicense, and/or sell copies of the Software, and to permit
16201// persons to whom the Software is furnished to do so, subject to the
16202// following conditions:
16203//
16204// The above copyright notice and this permission notice shall be included
16205// in all copies or substantial portions of the Software.
16206//
16207// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16208// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16209// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16210// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16211// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16212// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16213// USE OR OTHER DEALINGS IN THE SOFTWARE.
16214
16215var formatRegExp = /%[sdj%]/g;
16216exports.format = function(f) {
16217 if (!isString(f)) {
16218 var objects = [];
16219 for (var i = 0; i < arguments.length; i++) {
16220 objects.push(inspect(arguments[i]));
16221 }
16222 return objects.join(' ');
16223 }
16224
16225 var i = 1;
16226 var args = arguments;
16227 var len = args.length;
16228 var str = String(f).replace(formatRegExp, function(x) {
16229 if (x === '%%') return '%';
16230 if (i >= len) return x;
16231 switch (x) {
16232 case '%s': return String(args[i++]);
16233 case '%d': return Number(args[i++]);
16234 case '%j':
16235 try {
16236 return JSON.stringify(args[i++]);
16237 } catch (_) {
16238 return '[Circular]';
16239 }
16240 default:
16241 return x;
16242 }
16243 });
16244 for (var x = args[i]; i < len; x = args[++i]) {
16245 if (isNull(x) || !isObject(x)) {
16246 str += ' ' + x;
16247 } else {
16248 str += ' ' + inspect(x);
16249 }
16250 }
16251 return str;
16252};
16253
16254
16255// Mark that a method should not be used.
16256// Returns a modified function which warns once by default.
16257// If --no-deprecation is set, then it is a no-op.
16258exports.deprecate = function(fn, msg) {
16259 // Allow for deprecating things in the process of starting up.
16260 if (isUndefined(global.process)) {
16261 return function() {
16262 return exports.deprecate(fn, msg).apply(this, arguments);
16263 };
16264 }
16265
16266 if (process.noDeprecation === true) {
16267 return fn;
16268 }
16269
16270 var warned = false;
16271 function deprecated() {
16272 if (!warned) {
16273 if (process.throwDeprecation) {
16274 throw new Error(msg);
16275 } else if (process.traceDeprecation) {
16276 console.trace(msg);
16277 } else {
16278 console.error(msg);
16279 }
16280 warned = true;
16281 }
16282 return fn.apply(this, arguments);
16283 }
16284
16285 return deprecated;
16286};
16287
16288
16289var debugs = {};
16290var debugEnviron;
16291exports.debuglog = function(set) {
16292 if (isUndefined(debugEnviron))
16293 debugEnviron = process.env.NODE_DEBUG || '';
16294 set = set.toUpperCase();
16295 if (!debugs[set]) {
16296 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
16297 var pid = process.pid;
16298 debugs[set] = function() {
16299 var msg = exports.format.apply(exports, arguments);
16300 console.error('%s %d: %s', set, pid, msg);
16301 };
16302 } else {
16303 debugs[set] = function() {};
16304 }
16305 }
16306 return debugs[set];
16307};
16308
16309
16310/**
16311 * Echos the value of a value. Trys to print the value out
16312 * in the best way possible given the different types.
16313 *
16314 * @param {Object} obj The object to print out.
16315 * @param {Object} opts Optional options object that alters the output.
16316 */
16317/* legacy: obj, showHidden, depth, colors*/
16318function inspect(obj, opts) {
16319 // default options
16320 var ctx = {
16321 seen: [],
16322 stylize: stylizeNoColor
16323 };
16324 // legacy...
16325 if (arguments.length >= 3) ctx.depth = arguments[2];
16326 if (arguments.length >= 4) ctx.colors = arguments[3];
16327 if (isBoolean(opts)) {
16328 // legacy...
16329 ctx.showHidden = opts;
16330 } else if (opts) {
16331 // got an "options" object
16332 exports._extend(ctx, opts);
16333 }
16334 // set default options
16335 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
16336 if (isUndefined(ctx.depth)) ctx.depth = 2;
16337 if (isUndefined(ctx.colors)) ctx.colors = false;
16338 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
16339 if (ctx.colors) ctx.stylize = stylizeWithColor;
16340 return formatValue(ctx, obj, ctx.depth);
16341}
16342exports.inspect = inspect;
16343
16344
16345// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
16346inspect.colors = {
16347 'bold' : [1, 22],
16348 'italic' : [3, 23],
16349 'underline' : [4, 24],
16350 'inverse' : [7, 27],
16351 'white' : [37, 39],
16352 'grey' : [90, 39],
16353 'black' : [30, 39],
16354 'blue' : [34, 39],
16355 'cyan' : [36, 39],
16356 'green' : [32, 39],
16357 'magenta' : [35, 39],
16358 'red' : [31, 39],
16359 'yellow' : [33, 39]
16360};
16361
16362// Don't use 'blue' not visible on cmd.exe
16363inspect.styles = {
16364 'special': 'cyan',
16365 'number': 'yellow',
16366 'boolean': 'yellow',
16367 'undefined': 'grey',
16368 'null': 'bold',
16369 'string': 'green',
16370 'date': 'magenta',
16371 // "name": intentionally not styling
16372 'regexp': 'red'
16373};
16374
16375
16376function stylizeWithColor(str, styleType) {
16377 var style = inspect.styles[styleType];
16378
16379 if (style) {
16380 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
16381 '\u001b[' + inspect.colors[style][1] + 'm';
16382 } else {
16383 return str;
16384 }
16385}
16386
16387
16388function stylizeNoColor(str, styleType) {
16389 return str;
16390}
16391
16392
16393function arrayToHash(array) {
16394 var hash = {};
16395
16396 array.forEach(function(val, idx) {
16397 hash[val] = true;
16398 });
16399
16400 return hash;
16401}
16402
16403
16404function formatValue(ctx, value, recurseTimes) {
16405 // Provide a hook for user-specified inspect functions.
16406 // Check that value is an object with an inspect function on it
16407 if (ctx.customInspect &&
16408 value &&
16409 isFunction(value.inspect) &&
16410 // Filter out the util module, it's inspect function is special
16411 value.inspect !== exports.inspect &&
16412 // Also filter out any prototype objects using the circular check.
16413 !(value.constructor && value.constructor.prototype === value)) {
16414 var ret = value.inspect(recurseTimes, ctx);
16415 if (!isString(ret)) {
16416 ret = formatValue(ctx, ret, recurseTimes);
16417 }
16418 return ret;
16419 }
16420
16421 // Primitive types cannot have properties
16422 var primitive = formatPrimitive(ctx, value);
16423 if (primitive) {
16424 return primitive;
16425 }
16426
16427 // Look up the keys of the object.
16428 var keys = Object.keys(value);
16429 var visibleKeys = arrayToHash(keys);
16430
16431 if (ctx.showHidden) {
16432 keys = Object.getOwnPropertyNames(value);
16433 }
16434
16435 // IE doesn't make error fields non-enumerable
16436 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
16437 if (isError(value)
16438 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
16439 return formatError(value);
16440 }
16441
16442 // Some type of object without properties can be shortcutted.
16443 if (keys.length === 0) {
16444 if (isFunction(value)) {
16445 var name = value.name ? ': ' + value.name : '';
16446 return ctx.stylize('[Function' + name + ']', 'special');
16447 }
16448 if (isRegExp(value)) {
16449 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
16450 }
16451 if (isDate(value)) {
16452 return ctx.stylize(Date.prototype.toString.call(value), 'date');
16453 }
16454 if (isError(value)) {
16455 return formatError(value);
16456 }
16457 }
16458
16459 var base = '', array = false, braces = ['{', '}'];
16460
16461 // Make Array say that they are Array
16462 if (isArray(value)) {
16463 array = true;
16464 braces = ['[', ']'];
16465 }
16466
16467 // Make functions say that they are functions
16468 if (isFunction(value)) {
16469 var n = value.name ? ': ' + value.name : '';
16470 base = ' [Function' + n + ']';
16471 }
16472
16473 // Make RegExps say that they are RegExps
16474 if (isRegExp(value)) {
16475 base = ' ' + RegExp.prototype.toString.call(value);
16476 }
16477
16478 // Make dates with properties first say the date
16479 if (isDate(value)) {
16480 base = ' ' + Date.prototype.toUTCString.call(value);
16481 }
16482
16483 // Make error with message first say the error
16484 if (isError(value)) {
16485 base = ' ' + formatError(value);
16486 }
16487
16488 if (keys.length === 0 && (!array || value.length == 0)) {
16489 return braces[0] + base + braces[1];
16490 }
16491
16492 if (recurseTimes < 0) {
16493 if (isRegExp(value)) {
16494 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
16495 } else {
16496 return ctx.stylize('[Object]', 'special');
16497 }
16498 }
16499
16500 ctx.seen.push(value);
16501
16502 var output;
16503 if (array) {
16504 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
16505 } else {
16506 output = keys.map(function(key) {
16507 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
16508 });
16509 }
16510
16511 ctx.seen.pop();
16512
16513 return reduceToSingleString(output, base, braces);
16514}
16515
16516
16517function formatPrimitive(ctx, value) {
16518 if (isUndefined(value))
16519 return ctx.stylize('undefined', 'undefined');
16520 if (isString(value)) {
16521 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
16522 .replace(/'/g, "\\'")
16523 .replace(/\\"/g, '"') + '\'';
16524 return ctx.stylize(simple, 'string');
16525 }
16526 if (isNumber(value))
16527 return ctx.stylize('' + value, 'number');
16528 if (isBoolean(value))
16529 return ctx.stylize('' + value, 'boolean');
16530 // For some reason typeof null is "object", so special case here.
16531 if (isNull(value))
16532 return ctx.stylize('null', 'null');
16533}
16534
16535
16536function formatError(value) {
16537 return '[' + Error.prototype.toString.call(value) + ']';
16538}
16539
16540
16541function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
16542 var output = [];
16543 for (var i = 0, l = value.length; i < l; ++i) {
16544 if (hasOwnProperty(value, String(i))) {
16545 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
16546 String(i), true));
16547 } else {
16548 output.push('');
16549 }
16550 }
16551 keys.forEach(function(key) {
16552 if (!key.match(/^\d+$/)) {
16553 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
16554 key, true));
16555 }
16556 });
16557 return output;
16558}
16559
16560
16561function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
16562 var name, str, desc;
16563 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
16564 if (desc.get) {
16565 if (desc.set) {
16566 str = ctx.stylize('[Getter/Setter]', 'special');
16567 } else {
16568 str = ctx.stylize('[Getter]', 'special');
16569 }
16570 } else {
16571 if (desc.set) {
16572 str = ctx.stylize('[Setter]', 'special');
16573 }
16574 }
16575 if (!hasOwnProperty(visibleKeys, key)) {
16576 name = '[' + key + ']';
16577 }
16578 if (!str) {
16579 if (ctx.seen.indexOf(desc.value) < 0) {
16580 if (isNull(recurseTimes)) {
16581 str = formatValue(ctx, desc.value, null);
16582 } else {
16583 str = formatValue(ctx, desc.value, recurseTimes - 1);
16584 }
16585 if (str.indexOf('\n') > -1) {
16586 if (array) {
16587 str = str.split('\n').map(function(line) {
16588 return ' ' + line;
16589 }).join('\n').substr(2);
16590 } else {
16591 str = '\n' + str.split('\n').map(function(line) {
16592 return ' ' + line;
16593 }).join('\n');
16594 }
16595 }
16596 } else {
16597 str = ctx.stylize('[Circular]', 'special');
16598 }
16599 }
16600 if (isUndefined(name)) {
16601 if (array && key.match(/^\d+$/)) {
16602 return str;
16603 }
16604 name = JSON.stringify('' + key);
16605 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
16606 name = name.substr(1, name.length - 2);
16607 name = ctx.stylize(name, 'name');
16608 } else {
16609 name = name.replace(/'/g, "\\'")
16610 .replace(/\\"/g, '"')
16611 .replace(/(^"|"$)/g, "'");
16612 name = ctx.stylize(name, 'string');
16613 }
16614 }
16615
16616 return name + ': ' + str;
16617}
16618
16619
16620function reduceToSingleString(output, base, braces) {
16621 var numLinesEst = 0;
16622 var length = output.reduce(function(prev, cur) {
16623 numLinesEst++;
16624 if (cur.indexOf('\n') >= 0) numLinesEst++;
16625 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
16626 }, 0);
16627
16628 if (length > 60) {
16629 return braces[0] +
16630 (base === '' ? '' : base + '\n ') +
16631 ' ' +
16632 output.join(',\n ') +
16633 ' ' +
16634 braces[1];
16635 }
16636
16637 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
16638}
16639
16640
16641// NOTE: These type checking functions intentionally don't use `instanceof`
16642// because it is fragile and can be easily faked with `Object.create()`.
16643function isArray(ar) {
16644 return Array.isArray(ar);
16645}
16646exports.isArray = isArray;
16647
16648function isBoolean(arg) {
16649 return typeof arg === 'boolean';
16650}
16651exports.isBoolean = isBoolean;
16652
16653function isNull(arg) {
16654 return arg === null;
16655}
16656exports.isNull = isNull;
16657
16658function isNullOrUndefined(arg) {
16659 return arg == null;
16660}
16661exports.isNullOrUndefined = isNullOrUndefined;
16662
16663function isNumber(arg) {
16664 return typeof arg === 'number';
16665}
16666exports.isNumber = isNumber;
16667
16668function isString(arg) {
16669 return typeof arg === 'string';
16670}
16671exports.isString = isString;
16672
16673function isSymbol(arg) {
16674 return typeof arg === 'symbol';
16675}
16676exports.isSymbol = isSymbol;
16677
16678function isUndefined(arg) {
16679 return arg === void 0;
16680}
16681exports.isUndefined = isUndefined;
16682
16683function isRegExp(re) {
16684 return isObject(re) && objectToString(re) === '[object RegExp]';
16685}
16686exports.isRegExp = isRegExp;
16687
16688function isObject(arg) {
16689 return typeof arg === 'object' && arg !== null;
16690}
16691exports.isObject = isObject;
16692
16693function isDate(d) {
16694 return isObject(d) && objectToString(d) === '[object Date]';
16695}
16696exports.isDate = isDate;
16697
16698function isError(e) {
16699 return isObject(e) &&
16700 (objectToString(e) === '[object Error]' || e instanceof Error);
16701}
16702exports.isError = isError;
16703
16704function isFunction(arg) {
16705 return typeof arg === 'function';
16706}
16707exports.isFunction = isFunction;
16708
16709function isPrimitive(arg) {
16710 return arg === null ||
16711 typeof arg === 'boolean' ||
16712 typeof arg === 'number' ||
16713 typeof arg === 'string' ||
16714 typeof arg === 'symbol' || // ES6 symbol
16715 typeof arg === 'undefined';
16716}
16717exports.isPrimitive = isPrimitive;
16718
16719exports.isBuffer = require('./support/isBuffer');
16720
16721function objectToString(o) {
16722 return Object.prototype.toString.call(o);
16723}
16724
16725
16726function pad(n) {
16727 return n < 10 ? '0' + n.toString(10) : n.toString(10);
16728}
16729
16730
16731var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
16732 'Oct', 'Nov', 'Dec'];
16733
16734// 26 Feb 16:19:34
16735function timestamp() {
16736 var d = new Date();
16737 var time = [pad(d.getHours()),
16738 pad(d.getMinutes()),
16739 pad(d.getSeconds())].join(':');
16740 return [d.getDate(), months[d.getMonth()], time].join(' ');
16741}
16742
16743
16744// log is just a thin wrapper to console.log that prepends a timestamp
16745exports.log = function() {
16746 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
16747};
16748
16749
16750/**
16751 * Inherit the prototype methods from one constructor into another.
16752 *
16753 * The Function.prototype.inherits from lang.js rewritten as a standalone
16754 * function (not on Function.prototype). NOTE: If this file is to be loaded
16755 * during bootstrapping this function needs to be rewritten using some native
16756 * functions as prototype setup using normal JavaScript does not work as
16757 * expected during bootstrapping (see mirror.js in r114903).
16758 *
16759 * @param {function} ctor Constructor function which needs to inherit the
16760 * prototype.
16761 * @param {function} superCtor Constructor function to inherit prototype from.
16762 */
16763exports.inherits = require('inherits');
16764
16765exports._extend = function(origin, add) {
16766 // Don't do anything if add isn't an object
16767 if (!add || !isObject(add)) return origin;
16768
16769 var keys = Object.keys(add);
16770 var i = keys.length;
16771 while (i--) {
16772 origin[keys[i]] = add[keys[i]];
16773 }
16774 return origin;
16775};
16776
16777function hasOwnProperty(obj, prop) {
16778 return Object.prototype.hasOwnProperty.call(obj, prop);
16779}
16780
16781}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
16782},{"./support/isBuffer":81,"_process":52,"inherits":80}],83:[function(require,module,exports){
16783(function (Buffer){
16784const randomBytes = require('randombytes')
16785const ByteBuffer = require('bytebuffer')
16786const crypto = require('browserify-aes')
16787const assert = require('assert')
16788const PublicKey = require('./key_public')
16789const PrivateKey = require('./key_private')
16790const hash = require('./hash')
16791
16792const Long = ByteBuffer.Long;
16793
16794module.exports = {
16795 encrypt,
16796 decrypt
16797}
16798
16799/**
16800 Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem
16801 @throws {Error|TypeError} - "Invalid Key, ..."
16802 @arg {PrivateKey} private_key - required and used for decryption
16803 @arg {PublicKey} public_key - required and used to calcualte the shared secret
16804 @arg {string} [nonce = uniqueNonce()] - assigned a random unique uint64
16805
16806 @return {object}
16807 @property {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys.
16808 @property {Buffer} message - Plain text message
16809 @property {number} checksum - shared secret checksum
16810*/
16811function encrypt(private_key, public_key, message, nonce = uniqueNonce()) {
16812 return crypt(private_key, public_key, nonce, message)
16813}
16814
16815/**
16816 Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem
16817 @arg {PrivateKey} private_key - required and used for decryption
16818 @arg {PublicKey} public_key - required and used to calcualte the shared secret
16819 @arg {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys.
16820 @arg {Buffer} message - Encrypted or plain text message
16821 @arg {number} checksum - shared secret checksum
16822 @throws {Error|TypeError} - "Invalid Key, ..."
16823 @return {Buffer} - message
16824*/
16825function decrypt(private_key, public_key, nonce, message, checksum) {
16826 return crypt(private_key, public_key, nonce, message, checksum).message
16827}
16828
16829/**
16830 @arg {Buffer} message - Encrypted or plain text message (see checksum)
16831 @arg {number} checksum - shared secret checksum (null to encrypt, non-null to decrypt)
16832 @private
16833*/
16834function crypt(private_key, public_key, nonce, message, checksum) {
16835 private_key = PrivateKey(private_key)
16836 if (!private_key)
16837 throw new TypeError('private_key is required')
16838
16839 public_key = PublicKey(public_key)
16840 if (!public_key)
16841 throw new TypeError('public_key is required')
16842
16843 nonce = toLongObj(nonce)
16844 if (!nonce)
16845 throw new TypeError('nonce is required')
16846
16847 if (!Buffer.isBuffer(message)) {
16848 if (typeof message !== 'string')
16849 throw new TypeError('message should be buffer or string')
16850 message = new Buffer(message, 'binary')
16851 }
16852 if (checksum && typeof checksum !== 'number')
16853 throw new TypeError('checksum should be a number')
16854
16855 const S = private_key.getSharedSecret(public_key);
16856 let ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)
16857 ebuf.writeUint64(nonce)
16858 ebuf.append(S.toString('binary'), 'binary')
16859 ebuf = new Buffer(ebuf.copy(0, ebuf.offset).toBinary(), 'binary')
16860 const encryption_key = hash.sha512(ebuf)
16861
16862 // D E B U G
16863 // console.log('crypt', {
16864 // priv_to_pub: private_key.toPublic().toString(),
16865 // pub: public_key.toString(),
16866 // nonce: nonce.toString(),
16867 // message: message.length,
16868 // checksum,
16869 // S: S.toString('hex'),
16870 // encryption_key: encryption_key.toString('hex'),
16871 // })
16872
16873 const iv = encryption_key.slice(32, 48)
16874 const key = encryption_key.slice(0, 32)
16875
16876 // check is first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits.
16877 let check = hash.sha256(encryption_key)
16878 check = check.slice(0, 4)
16879 const cbuf = ByteBuffer.fromBinary(check.toString('binary'), ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)
16880 check = cbuf.readUint32()
16881
16882 if (checksum) {
16883 if (check !== checksum)
16884 throw new Error('Invalid key')
16885 message = cryptoJsDecrypt(message, key, iv)
16886 } else {
16887 message = cryptoJsEncrypt(message, key, iv)
16888 }
16889 return {nonce, message, checksum: check}
16890}
16891
16892/** This method does not use a checksum, the returned data must be validated some other way.
16893 @arg {string|Buffer} ciphertext - binary format
16894 @return {Buffer}
16895*/
16896function cryptoJsDecrypt(message, key, iv) {
16897 assert(message, "Missing cipher text")
16898 message = toBinaryBuffer(message)
16899 const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv)
16900 // decipher.setAutoPadding(true)
16901 message = Buffer.concat([decipher.update(message), decipher.final()])
16902 return message
16903}
16904
16905/** This method does not use a checksum, the returned data must be validated some other way.
16906 @arg {string|Buffer} plaintext - binary format
16907 @return {Buffer} binary
16908*/
16909function cryptoJsEncrypt(message, key, iv) {
16910 assert(message, "Missing plain text")
16911 message = toBinaryBuffer(message)
16912 const cipher = crypto.createCipheriv('aes-256-cbc', key, iv)
16913 // cipher.setAutoPadding(true)
16914 message = Buffer.concat([cipher.update(message), cipher.final()])
16915 return message
16916}
16917
16918/** @return {string} unique 64 bit unsigned number string. Being time based, this is careful to never choose the same nonce twice. This value could be recorded in the blockchain for a long time.
16919*/
16920function uniqueNonce() {
16921 if(unique_nonce_entropy === null) {
16922 const b = new Uint8Array(randomBytes(2))
16923 unique_nonce_entropy = parseInt(b[0] << 8 | b[1], 10)
16924 }
16925 let long = Long.fromNumber(Date.now())
16926 const entropy = ++unique_nonce_entropy % 0xFFFF
16927 // console.log('uniqueNonce date\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0))
16928 // console.log('uniqueNonce entropy\t', ByteBuffer.allocate(8).writeUint64(Long.fromNumber(entropy)).toHex(0))
16929 long = long.shiftLeft(16).or(Long.fromNumber(entropy));
16930 // console.log('uniqueNonce final\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0))
16931 return long.toString()
16932}
16933let unique_nonce_entropy = null
16934// for(let i=1; i < 10; i++) key.uniqueNonce()
16935
16936const toLongObj = o => (o ? Long.isLong(o) ? o : Long.fromString(o) : o)
16937const toBinaryBuffer = o => (o ? Buffer.isBuffer(o) ? o : new Buffer(o, 'binary') : o)
16938
16939}).call(this,require("buffer").Buffer)
16940},{"./hash":90,"./key_private":92,"./key_public":93,"assert":1,"browserify-aes":11,"buffer":27,"bytebuffer":28,"randombytes":53}],84:[function(require,module,exports){
16941const Aes = require("./aes")
16942const PrivateKey = require("./key_private")
16943const PublicKey = require("./key_public")
16944const Signature = require("./signature")
16945const key_utils = require("./key_utils")
16946const config = require('./config')
16947const hash = require("./hash")
16948
16949/**
16950 [Wallet Import Format](https://en.bitcoin.it/wiki/Wallet_import_format)
16951 @typedef {string} wif
16952*/
16953/**
16954 EOSKey..
16955 @typedef {string} pubkey
16956*/
16957
16958/** @namespace */
16959const ecc = {
16960 /**
16961 @arg {number} [cpuEntropyBits = 128] gather additional entropy
16962 from a CPU mining algorithm. Set to 0 for testing.
16963 @return {wif}
16964
16965 @example ecc.randomKey()
16966 */
16967 randomKey: (cpuEntropyBits) => PrivateKey.randomKey(cpuEntropyBits).toString(),
16968
16969 /**
16970
16971 @arg {string} seed - any length string. This is private. The same
16972 seed produces the same private key every time. At least 128 random
16973 bits should be used to produce a good private key.
16974 @return {wif}
16975
16976 @example ecc.seedPrivate('secret') === wif
16977 */
16978 seedPrivate: seed => PrivateKey.fromSeed(seed).toString(),
16979
16980 /**
16981 @arg {wif} wif
16982 @return {pubkey}
16983
16984 @example ecc.privateToPublic(wif) === pubkey
16985 */
16986 privateToPublic: wif => PrivateKey.fromWif(wif).toPublic().toString(),
16987
16988 /**
16989 @arg {pubkey} pubkey - like EOSKey..
16990 @arg {string} [addressPrefix = config.address_prefix] - like EOS
16991 @return {boolean|string} true or error string
16992
16993 @example ecc.isValidPublic(pubkey) === true
16994 */
16995 isValidPublic: (pubkey, addressPrefix) => {
16996 try {
16997 PublicKey.fromStringOrThrow(pubkey, addressPrefix)
16998 return true
16999 } catch(error) {
17000 return error
17001 }
17002 },
17003
17004 /**
17005 @arg {wif} wif
17006 @return {boolean|string} true or error string
17007
17008 @example ecc.isValidPrivate(wif) === true
17009 */
17010 isValidPrivate: (wif) => {
17011 try {
17012 PrivateKey.fromWif(wif)
17013 return true
17014 } catch(error) {
17015 return error
17016 }
17017 },
17018
17019 /**
17020 Create a signature using data or a hash.
17021
17022 @arg {string|Buffer} data
17023 @arg {wif|PrivateKey} privateKey
17024 @arg {boolean} [hashData = true] - sha256 hash data before signing
17025 @return {string} hex signature
17026
17027 @example ecc.sign('I am alive', wif)
17028 */
17029 sign: (data, privateKey, hashData = true) =>
17030 Signature[hashData ? 'sign' : 'signHash'](data, privateKey).toHex(),
17031
17032 /**
17033 Verify signed data.
17034
17035 @arg {string|Buffer} signature - buffer or hex string
17036 @arg {string|Buffer} data
17037 @arg {pubkey|PublicKey} pubkey
17038 @arg {boolean} [hashData = true] - sha256 hash data before verify
17039 @return {boolean}
17040
17041 @example ecc.verify(signature, 'I am alive', pubkey) === true
17042 */
17043 verify: (signature, data, pubkey, hashData = true) => {
17044 signature = Signature.from(signature)
17045 const verify = signature[hashData ? 'verify' : 'verifyHash']
17046 return verify(data, pubkey)
17047 },
17048
17049 /**
17050 Recover the public key used to create the signature.
17051
17052 @arg {String} signature (hex, etc..)
17053 @arg {String|Buffer} data
17054 @arg {boolean} [hashData = true] - sha256 hash data before recover
17055 @return {pubkey}
17056
17057 @example ecc.recover(signature, 'I am alive') === pubkey
17058 */
17059 recover: (signature, data, hashData = true) => {
17060 signature = Signature.from(signature)
17061 const recover = signature[hashData ? 'recover' : 'recoverHash']
17062 return recover(data).toString()
17063 },
17064
17065 /** @arg {string|Buffer} data
17066 @arg {string} [encoding = 'hex'] - 'hex', 'binary' or 'base64'
17067 @return {string|Buffer} - Buffer when encoding is null, or string
17068
17069 @example ecc.sha256('hashme') === '02208b..'
17070 */
17071 sha256: (data, encoding = 'hex') => hash.sha256(data, encoding)
17072
17073}
17074
17075module.exports = ecc
17076
17077},{"./aes":83,"./config":86,"./hash":90,"./key_private":92,"./key_public":93,"./key_utils":94,"./signature":95}],85:[function(require,module,exports){
17078
17079const Aes = require("./aes")
17080const PrivateKey = require("./key_private")
17081const PublicKey = require("./key_public")
17082const Signature = require("./signature")
17083const key_utils = require("./key_utils")
17084const config = require('./config')
17085
17086module.exports = {
17087 Aes, PrivateKey, PublicKey,
17088 Signature, key_utils, config
17089}
17090},{"./aes":83,"./config":86,"./key_private":92,"./key_public":93,"./key_utils":94,"./signature":95}],86:[function(require,module,exports){
17091
17092module.exports = {
17093 address_prefix: 'EOS'
17094}
17095
17096},{}],87:[function(require,module,exports){
17097(function (Buffer){
17098var assert = require('assert') // from github.com/bitcoinjs/bitcoinjs-lib from github.com/cryptocoinjs/ecdsa
17099var crypto = require('./hash')
17100var enforceType = require('./enforce_types')
17101
17102var BigInteger = require('bigi')
17103var ECSignature = require('./ecsignature')
17104
17105// https://tools.ietf.org/html/rfc6979#section-3.2
17106function deterministicGenerateK(curve, hash, d, checkSig, nonce) {
17107
17108 enforceType('Buffer', hash)
17109 enforceType(BigInteger, d)
17110
17111 if (nonce) {
17112 hash = crypto.sha256(Buffer.concat([hash, new Buffer(nonce)]))
17113 }
17114
17115 // sanity check
17116 assert.equal(hash.length, 32, 'Hash must be 256 bit')
17117
17118 var x = d.toBuffer(32)
17119 var k = new Buffer(32)
17120 var v = new Buffer(32)
17121
17122 // Step B
17123 v.fill(1)
17124
17125 // Step C
17126 k.fill(0)
17127
17128 // Step D
17129 k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k)
17130
17131 // Step E
17132 v = crypto.HmacSHA256(v, k)
17133
17134 // Step F
17135 k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k)
17136
17137 // Step G
17138 v = crypto.HmacSHA256(v, k)
17139
17140 // Step H1/H2a, ignored as tlen === qlen (256 bit)
17141 // Step H2b
17142 v = crypto.HmacSHA256(v, k)
17143
17144 var T = BigInteger.fromBuffer(v)
17145
17146 // Step H3, repeat until T is within the interval [1, n - 1]
17147 while ((T.signum() <= 0) || (T.compareTo(curve.n) >= 0) || !checkSig(T)) {
17148 k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0])]), k)
17149 v = crypto.HmacSHA256(v, k)
17150
17151 // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
17152 // Step H2b again
17153 v = crypto.HmacSHA256(v, k)
17154
17155 T = BigInteger.fromBuffer(v)
17156 }
17157
17158 return T
17159
17160}
17161
17162function sign(curve, hash, d, nonce) {
17163
17164 var e = BigInteger.fromBuffer(hash)
17165 var n = curve.n
17166 var G = curve.G
17167
17168 var r, s
17169 var k = deterministicGenerateK(curve, hash, d, function (k) {
17170 // find canonically valid signature
17171 var Q = G.multiply(k)
17172
17173 if (curve.isInfinity(Q)) return false
17174
17175 r = Q.affineX.mod(n)
17176 if (r.signum() === 0) return false
17177
17178 s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n)
17179 if (s.signum() === 0) return false
17180
17181 return true
17182 }, nonce)
17183
17184 var N_OVER_TWO = n.shiftRight(1)
17185
17186 // enforce low S values, see bip62: 'low s values in signatures'
17187 if (s.compareTo(N_OVER_TWO) > 0) {
17188 s = n.subtract(s)
17189 }
17190
17191 return ECSignature(r, s)
17192}
17193
17194function verifyRaw(curve, e, signature, Q) {
17195 var n = curve.n
17196 var G = curve.G
17197
17198 var r = signature.r
17199 var s = signature.s
17200
17201 // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1]
17202 if (r.signum() <= 0 || r.compareTo(n) >= 0) return false
17203 if (s.signum() <= 0 || s.compareTo(n) >= 0) return false
17204
17205 // c = s^-1 mod n
17206 var c = s.modInverse(n)
17207
17208 // 1.4.4 Compute u1 = es^−1 mod n
17209 // u2 = rs^−1 mod n
17210 var u1 = e.multiply(c).mod(n)
17211 var u2 = r.multiply(c).mod(n)
17212
17213 // 1.4.5 Compute R = (xR, yR) = u1G + u2Q
17214 var R = G.multiplyTwo(u1, Q, u2)
17215
17216 // 1.4.5 (cont.) Enforce R is not at infinity
17217 if (curve.isInfinity(R)) return false
17218
17219 // 1.4.6 Convert the field element R.x to an integer
17220 var xR = R.affineX
17221
17222 // 1.4.7 Set v = xR mod n
17223 var v = xR.mod(n)
17224
17225 // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
17226 return v.equals(r)
17227}
17228
17229function verify(curve, hash, signature, Q) {
17230 // 1.4.2 H = Hash(M), already done by the user
17231 // 1.4.3 e = H
17232 var e = BigInteger.fromBuffer(hash)
17233 return verifyRaw(curve, e, signature, Q)
17234}
17235
17236/**
17237 * Recover a public key from a signature.
17238 *
17239 * See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public
17240 * Key Recovery Operation".
17241 *
17242 * http://www.secg.org/download/aid-780/sec1-v2.pdf
17243 */
17244function recoverPubKey(curve, e, signature, i) {
17245 assert.strictEqual(i & 3, i, 'Recovery param is more than two bits')
17246
17247 var n = curve.n
17248 var G = curve.G
17249
17250 var r = signature.r
17251 var s = signature.s
17252
17253 assert(r.signum() > 0 && r.compareTo(n) < 0, 'Invalid r value')
17254 assert(s.signum() > 0 && s.compareTo(n) < 0, 'Invalid s value')
17255
17256 // A set LSB signifies that the y-coordinate is odd
17257 var isYOdd = i & 1
17258
17259 // The more significant bit specifies whether we should use the
17260 // first or second candidate key.
17261 var isSecondKey = i >> 1
17262
17263 // 1.1 Let x = r + jn
17264 var x = isSecondKey ? r.add(n) : r
17265 var R = curve.pointFromX(isYOdd, x)
17266
17267 // 1.4 Check that nR is at infinity
17268 var nR = R.multiply(n)
17269 assert(curve.isInfinity(nR), 'nR is not a valid curve point')
17270
17271 // Compute -e from e
17272 var eNeg = e.negate().mod(n)
17273
17274 // 1.6.1 Compute Q = r^-1 (sR - eG)
17275 // Q = r^-1 (sR + -eG)
17276 var rInv = r.modInverse(n)
17277
17278 var Q = R.multiplyTwo(s, G, eNeg).multiply(rInv)
17279 curve.validate(Q)
17280
17281 return Q
17282}
17283
17284/**
17285 * Calculate pubkey extraction parameter.
17286 *
17287 * When extracting a pubkey from a signature, we have to
17288 * distinguish four different cases. Rather than putting this
17289 * burden on the verifier, Bitcoin includes a 2-bit value with the
17290 * signature.
17291 *
17292 * This function simply tries all four cases and returns the value
17293 * that resulted in a successful pubkey recovery.
17294 */
17295function calcPubKeyRecoveryParam(curve, e, signature, Q) {
17296 for (var i = 0; i < 4; i++) {
17297 var Qprime = recoverPubKey(curve, e, signature, i)
17298
17299 // 1.6.2 Verify Q
17300 if (Qprime.equals(Q)) {
17301 return i
17302 }
17303 }
17304
17305 throw new Error('Unable to find valid recovery factor')
17306}
17307
17308module.exports = {
17309 calcPubKeyRecoveryParam: calcPubKeyRecoveryParam,
17310 deterministicGenerateK: deterministicGenerateK,
17311 recoverPubKey: recoverPubKey,
17312 sign: sign,
17313 verify: verify,
17314 verifyRaw: verifyRaw
17315}
17316
17317}).call(this,require("buffer").Buffer)
17318},{"./ecsignature":88,"./enforce_types":89,"./hash":90,"assert":1,"bigi":6,"buffer":27}],88:[function(require,module,exports){
17319(function (Buffer){
17320var assert = require('assert') // from https://github.com/bitcoinjs/bitcoinjs-lib
17321var enforceType = require('./enforce_types')
17322
17323var BigInteger = require('bigi')
17324
17325function ECSignature(r, s) {
17326 enforceType(BigInteger, r)
17327 enforceType(BigInteger, s)
17328
17329 function toCompact(i, compressed) {
17330 if (compressed) i += 4
17331 i += 27
17332
17333 var buffer = new Buffer(65)
17334 buffer.writeUInt8(i, 0)
17335
17336 r.toBuffer(32).copy(buffer, 1)
17337 s.toBuffer(32).copy(buffer, 33)
17338
17339 return buffer
17340 }
17341
17342 function toDER() {
17343 var rBa = r.toDERInteger()
17344 var sBa = s.toDERInteger()
17345
17346 var sequence = []
17347
17348 // INTEGER
17349 sequence.push(0x02, rBa.length)
17350 sequence = sequence.concat(rBa)
17351
17352 // INTEGER
17353 sequence.push(0x02, sBa.length)
17354 sequence = sequence.concat(sBa)
17355
17356 // SEQUENCE
17357 sequence.unshift(0x30, sequence.length)
17358
17359 return new Buffer(sequence)
17360 }
17361
17362 function toScriptSignature(hashType) {
17363 var hashTypeBuffer = new Buffer(1)
17364 hashTypeBuffer.writeUInt8(hashType, 0)
17365
17366 return Buffer.concat([toDER(), hashTypeBuffer])
17367 }
17368
17369 return {r, s, toCompact, toDER, toScriptSignature}
17370}
17371
17372// Import operations
17373ECSignature.parseCompact = function(buffer) {
17374 assert.equal(buffer.length, 65, 'Invalid signature length')
17375 var i = buffer.readUInt8(0) - 27
17376
17377 // At most 3 bits
17378 assert.equal(i, i & 7, 'Invalid signature parameter')
17379 var compressed = !!(i & 4)
17380
17381 // Recovery param only
17382 i = i & 3
17383
17384 var r = BigInteger.fromBuffer(buffer.slice(1, 33))
17385 var s = BigInteger.fromBuffer(buffer.slice(33))
17386
17387 return {
17388 compressed: compressed,
17389 i: i,
17390 signature: ECSignature(r, s)
17391 }
17392}
17393
17394ECSignature.fromDER = function(buffer) {
17395 assert.equal(buffer.readUInt8(0), 0x30, 'Not a DER sequence')
17396 assert.equal(buffer.readUInt8(1), buffer.length - 2, 'Invalid sequence length')
17397 assert.equal(buffer.readUInt8(2), 0x02, 'Expected a DER integer')
17398
17399 var rLen = buffer.readUInt8(3)
17400 assert(rLen > 0, 'R length is zero')
17401
17402 var offset = 4 + rLen
17403 assert.equal(buffer.readUInt8(offset), 0x02, 'Expected a DER integer (2)')
17404
17405 var sLen = buffer.readUInt8(offset + 1)
17406 assert(sLen > 0, 'S length is zero')
17407
17408 var rB = buffer.slice(4, offset)
17409 var sB = buffer.slice(offset + 2)
17410 offset += 2 + sLen
17411
17412 if (rLen > 1 && rB.readUInt8(0) === 0x00) {
17413 assert(rB.readUInt8(1) & 0x80, 'R value excessively padded')
17414 }
17415
17416 if (sLen > 1 && sB.readUInt8(0) === 0x00) {
17417 assert(sB.readUInt8(1) & 0x80, 'S value excessively padded')
17418 }
17419
17420 assert.equal(offset, buffer.length, 'Invalid DER encoding')
17421 var r = BigInteger.fromDERInteger(rB)
17422 var s = BigInteger.fromDERInteger(sB)
17423
17424 assert(r.signum() >= 0, 'R value is negative')
17425 assert(s.signum() >= 0, 'S value is negative')
17426
17427 return ECSignature(r, s)
17428}
17429
17430// FIXME: 0x00, 0x04, 0x80 are SIGHASH_* boundary constants, importing Transaction causes a circular dependency
17431ECSignature.parseScriptSignature = function(buffer) {
17432 var hashType = buffer.readUInt8(buffer.length - 1)
17433 var hashTypeMod = hashType & ~0x80
17434
17435 assert(hashTypeMod > 0x00 && hashTypeMod < 0x04, 'Invalid hashType')
17436
17437 return {
17438 signature: ECSignature.fromDER(buffer.slice(0, -1)),
17439 hashType: hashType
17440 }
17441}
17442
17443module.exports = ECSignature
17444
17445}).call(this,require("buffer").Buffer)
17446},{"./enforce_types":89,"assert":1,"bigi":6,"buffer":27}],89:[function(require,module,exports){
17447(function (Buffer){
17448module.exports = function enforce(type, value) { // Copied from https://github.com/bitcoinjs/bitcoinjs-lib
17449 switch (type) {
17450 case 'Array': {
17451 if (Array.isArray(value)) return
17452 break
17453 }
17454
17455 case 'Boolean': {
17456 if (typeof value === 'boolean') return
17457 break
17458 }
17459
17460 case 'Buffer': {
17461 if (Buffer.isBuffer(value)) return
17462 break
17463 }
17464
17465 case 'Number': {
17466 if (typeof value === 'number') return
17467 break
17468 }
17469
17470 case 'String': {
17471 if (typeof value === 'string') return
17472 break
17473 }
17474
17475 default: {
17476 if (getName(value.constructor) === getName(type)) return
17477 }
17478 }
17479
17480 throw new TypeError('Expected ' + (getName(type) || type) + ', got ' + value)
17481}
17482
17483function getName(fn) {
17484 // Why not fn.name: https://kangax.github.io/compat-table/es6/#function_name_property
17485 var match = fn.toString().match(/function (.*?)\(/)
17486 return match ? match[1] : null
17487}
17488
17489}).call(this,{"isBuffer":require("../node_modules/is-buffer/index.js")})
17490},{"../node_modules/is-buffer/index.js":46}],90:[function(require,module,exports){
17491const createHash = require('create-hash')
17492const createHmac = require('create-hmac')
17493
17494/** @namespace hash */
17495
17496/** @arg {string|Buffer} data
17497 @arg {string} [encoding = null] - 'hex', 'binary' or 'base64'
17498 @return {string|Buffer} - Buffer when encoding is null, or string
17499*/
17500function sha1(data, encoding) {
17501 return createHash('sha1').update(data).digest(encoding)
17502}
17503
17504/** @arg {string|Buffer} data
17505 @arg {string} [encoding = null] - 'hex', 'binary' or 'base64'
17506 @return {string|Buffer} - Buffer when encoding is null, or string
17507*/
17508function sha256(data, encoding) {
17509 return createHash('sha256').update(data).digest(encoding)
17510}
17511
17512/** @arg {string|Buffer} data
17513 @arg {string} [encoding = null] - 'hex', 'binary' or 'base64'
17514 @return {string|Buffer} - Buffer when encoding is null, or string
17515*/
17516function sha512(data, encoding) {
17517 return createHash('sha512').update(data).digest(encoding)
17518}
17519
17520function HmacSHA256(buffer, secret) {
17521 return createHmac('sha256', secret).update(buffer).digest()
17522}
17523
17524function ripemd160(data) {
17525 return createHash('rmd160').update(data).digest()
17526}
17527
17528// function hash160(buffer) {
17529// return ripemd160(sha256(buffer))
17530// }
17531//
17532// function hash256(buffer) {
17533// return sha256(sha256(buffer))
17534// }
17535
17536//
17537// function HmacSHA512(buffer, secret) {
17538// return crypto.createHmac('sha512', secret).update(buffer).digest()
17539// }
17540
17541module.exports = {
17542 sha1: sha1,
17543 sha256: sha256,
17544 sha512: sha512,
17545 HmacSHA256: HmacSHA256,
17546 ripemd160: ripemd160
17547 // hash160: hash160,
17548 // hash256: hash256,
17549 // HmacSHA512: HmacSHA512
17550}
17551
17552},{"create-hash":31,"create-hmac":34}],91:[function(require,module,exports){
17553const commonApi = require('./api_common')
17554const objectApi = require('./api_object')
17555
17556const ecc = Object.assign({}, commonApi, objectApi)
17557
17558module.exports = ecc
17559
17560},{"./api_common":84,"./api_object":85}],92:[function(require,module,exports){
17561(function (Buffer){
17562const ecurve = require('ecurve');
17563const Point = ecurve.Point;
17564const secp256k1 = ecurve.getCurveByName('secp256k1');
17565const BigInteger = require('bigi');
17566const base58 = require('bs58');
17567const assert = require('assert');
17568const hash = require('./hash');
17569const PublicKey = require('./key_public');
17570const keyUtils = require('./key_utils');
17571
17572const G = secp256k1.G
17573const n = secp256k1.n
17574
17575module.exports = PrivateKey;
17576
17577/**
17578 @typedef {string} wif - https://en.bitcoin.it/wiki/Wallet_import_format
17579 @typedef {string} pubkey - EOSKey..
17580 @typedef {ecurve.Point} Point
17581*/
17582
17583/**
17584 @param {BigInteger} d
17585*/
17586function PrivateKey(d) {
17587
17588 if(typeof d === 'string') {
17589 return PrivateKey.fromWif(d)
17590 } else if(Buffer.isBuffer(d)) {
17591 return PrivateKey.fromBuffer(d)
17592 } else if(typeof d === 'object' && BigInteger.isBigInteger(d.d)) {
17593 return PrivateKey(d.d)
17594 }
17595
17596 if(!BigInteger.isBigInteger(d)) {
17597 throw new TypeError('Invalid private key')
17598 }
17599
17600 /**
17601 @return {wif}
17602 */
17603 function toWif() {
17604 var private_key = toBuffer();
17605 // checksum includes the version
17606 private_key = Buffer.concat([new Buffer([0x80]), private_key]);
17607 var checksum = hash.sha256(private_key);
17608 checksum = hash.sha256(checksum);
17609 checksum = checksum.slice(0, 4);
17610 var private_wif = Buffer.concat([private_key, checksum]);
17611 return base58.encode(private_wif);
17612 }
17613
17614 let public_key;
17615
17616 /**
17617 @return {Point}
17618 */
17619 function toPublic() {
17620 if (public_key) {
17621 // Hundreds of keys can be S L O W in the browser
17622 // cache
17623 return public_key
17624 }
17625 const Q = secp256k1.G.multiply(d);
17626 return public_key = PublicKey.fromPoint(Q);
17627 }
17628
17629 function toBuffer() {
17630 return d.toBuffer(32);
17631 }
17632
17633 /** ECIES */
17634 function getSharedSecret(public_key) {
17635 public_key = toPublic(public_key)
17636 let KB = public_key.toUncompressed().toBuffer()
17637 let KBP = Point.fromAffine(
17638 secp256k1,
17639 BigInteger.fromBuffer( KB.slice( 1,33 )), // x
17640 BigInteger.fromBuffer( KB.slice( 33,65 )) // y
17641 )
17642 let r = toBuffer()
17643 let P = KBP.multiply(BigInteger.fromBuffer(r))
17644 let S = P.affineX.toBuffer({size: 32})
17645 // SHA512 used in ECIES
17646 return hash.sha512(S)
17647 }
17648
17649 // /** ECIES (does not always match the Point.fromAffine version above) */
17650 // getSharedSecret(public_key){
17651 // public_key = toPublic(public_key)
17652 // var P = public_key.Q.multiply( d );
17653 // var S = P.affineX.toBuffer({size: 32});
17654 // // ECIES, adds an extra sha512
17655 // return hash.sha512(S);
17656 // }
17657
17658 /** @throws {Error} - overflow of the key could not be derived */
17659 function child( offset ) {
17660 offset = Buffer.concat([ toPublic().toBuffer(), offset ])
17661 offset = hash.sha256( offset )
17662 let c = BigInteger.fromBuffer(offset)
17663
17664 if (c.compareTo(n) >= 0)
17665 throw new Error("Child offset went out of bounds, try again")
17666
17667 let derived = d.add(c)//.mod(n)
17668
17669 if( derived.signum() === 0 )
17670 throw new Error("Child offset derived to an invalid key, try again")
17671
17672 return PrivateKey( derived )
17673 }
17674
17675 function toHex() {
17676 return toBuffer().toString('hex');
17677 }
17678
17679 return {
17680 d,
17681 toWif,
17682 toPublic,
17683 toBuffer,
17684 toString: toWif,
17685 getSharedSecret,
17686 child
17687 }
17688}
17689
17690PrivateKey.fromHex = function(hex) {
17691 return PrivateKey.fromBuffer(new Buffer(hex, 'hex'));
17692}
17693
17694PrivateKey.fromBuffer = function(buf) {
17695 if (!Buffer.isBuffer(buf)) {
17696 throw new Error("Expecting parameter to be a Buffer type");
17697 }
17698 if (32 !== buf.length) {
17699 console.log(`WARN: Expecting 32 bytes, instead got ${buf.length}, stack trace:`, new Error().stack);
17700 }
17701 if (buf.length === 0) {
17702 throw new Error("Empty buffer");
17703 }
17704 return PrivateKey(BigInteger.fromBuffer(buf));
17705}
17706
17707/**
17708 @arg {string} seed - any length string. This is private, the same seed
17709 produces the same private key every time.
17710
17711 @return {PrivateKey}
17712*/
17713PrivateKey.fromSeed = function(seed) { // generate_private_key
17714 if (!(typeof seed === 'string')) {
17715 throw new Error('seed must be of type string');
17716 }
17717 return PrivateKey.fromBuffer(hash.sha256(seed));
17718}
17719
17720PrivateKey.isWif = function(text) {
17721 try {
17722 PrivateKey.fromWif(text)
17723 return true
17724 } catch(e) {
17725 return false
17726 }
17727}
17728
17729/**
17730 @throws {AssertError|Error} parsing key
17731 @return {string} Wallet Import Format (still a secret, Not encrypted)
17732*/
17733PrivateKey.fromWif = function(_private_wif) {
17734 var private_wif = new Buffer(base58.decode(_private_wif));
17735 var version = private_wif.readUInt8(0);
17736 assert.equal(0x80, version, `Expected version ${0x80}, instead got ${version}`);
17737 // checksum includes the version
17738 var private_key = private_wif.slice(0, -4);
17739 var checksum = private_wif.slice(-4);
17740 var new_checksum = hash.sha256(private_key);
17741 new_checksum = hash.sha256(new_checksum);
17742 new_checksum = new_checksum.slice(0, 4);
17743 if (checksum.toString() !== new_checksum.toString())
17744 throw new Error('Invalid WIF key (checksum miss-match), ' +
17745 `${checksum.toString('hex')} != ${new_checksum.toString('hex')}`
17746 )
17747
17748 private_key = private_key.slice(1);
17749 return PrivateKey.fromBuffer(private_key);
17750}
17751
17752PrivateKey.randomKey = function(cpuEntropyBits) {
17753 return PrivateKey.fromBuffer(keyUtils.random32ByteBuffer({cpuEntropyBits}));
17754}
17755
17756const toPublic = data => data == null ? data :
17757 data.Q ? data : PublicKey.fromStringOrThrow(data)
17758
17759}).call(this,require("buffer").Buffer)
17760},{"./hash":90,"./key_public":93,"./key_utils":94,"assert":1,"bigi":6,"bs58":25,"buffer":27,"ecurve":38}],93:[function(require,module,exports){
17761(function (Buffer){
17762const BigInteger = require('bigi');
17763const ecurve = require('ecurve');
17764const secp256k1 = ecurve.getCurveByName('secp256k1');
17765const base58 = require('bs58');
17766const hash = require('./hash');
17767const config = require('./config');
17768const assert = require('assert');
17769
17770var G = secp256k1.G
17771var n = secp256k1.n
17772
17773module.exports = PublicKey
17774
17775/** @param {ecurve.Point} public key */
17776function PublicKey(Q) {
17777
17778 if(typeof Q === 'string') {
17779 return PublicKey.fromString(Q)
17780 } else if(Buffer.isBuffer(Q)) {
17781 return PublicKey.fromBuffer(Q)
17782 } else if(typeof Q === 'object' && Q.Q) {
17783 return PublicKey(Q.Q)
17784 }
17785
17786 if(typeof Q !== 'object' || !Q.compressed) {
17787 throw new TypeError('Invalid public key')
17788 }
17789
17790 function toBuffer(compressed = Q.compressed) {
17791 return Q.getEncoded(compressed);
17792 }
17793
17794 let pubdata // cache
17795
17796 /**
17797 Full public key
17798 @return {string} EOSKey..
17799 */
17800 function toString(address_prefix = config.address_prefix) {
17801 if(pubdata) {
17802 return address_prefix + pubdata
17803 }
17804 const pub_buf = toBuffer();
17805 const checksum = hash.ripemd160(pub_buf);
17806 const addy = Buffer.concat([pub_buf, checksum.slice(0, 4)]);
17807 pubdata = base58.encode(addy)
17808 return address_prefix + pubdata;
17809 }
17810
17811 function toUncompressed() {
17812 var buf = Q.getEncoded(false);
17813 var point = ecurve.Point.decodeFrom(secp256k1, buf);
17814 return PublicKey.fromPoint(point);
17815 }
17816
17817 function child( offset ) {
17818 assert(Buffer.isBuffer(offset), "Buffer required: offset")
17819 assert.equal(offset.length, 32, "offset length")
17820
17821 offset = Buffer.concat([ toBuffer(), offset ])
17822 offset = hash.sha256( offset )
17823
17824 let c = BigInteger.fromBuffer( offset )
17825
17826 if (c.compareTo(n) >= 0)
17827 throw new Error("Child offset went out of bounds, try again")
17828
17829
17830 let cG = G.multiply(c)
17831 let Qprime = Q.add(cG)
17832
17833 if( secp256k1.isInfinity(Qprime) )
17834 throw new Error("Child offset derived to an invalid key, try again")
17835
17836 return PublicKey.fromPoint(Qprime)
17837 }
17838
17839 // toByteBuffer() {
17840 // var b = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN);
17841 // appendByteBuffer(b);
17842 // return b.copy(0, b.offset);
17843 // }
17844
17845 function toHex() {
17846 return toBuffer().toString('hex');
17847 }
17848
17849 return {
17850 Q,
17851 toString,
17852 toUncompressed,
17853 toBuffer,
17854 child,
17855 toHex
17856 }
17857}
17858
17859PublicKey.fromBinary = function(bin) {
17860 return PublicKey.fromBuffer(new Buffer(bin, 'binary'));
17861}
17862
17863PublicKey.fromBuffer = function(buffer) {
17864 return PublicKey(ecurve.Point.decodeFrom(secp256k1, buffer));
17865}
17866
17867PublicKey.fromPoint = function(point) {
17868 return PublicKey(point);
17869}
17870
17871/**
17872 @arg {string} public_key - like STMXyz...
17873 @arg {string} address_prefix - like STM
17874 @return PublicKey or `null` (if the public_key string is invalid)
17875 @deprecated fromPublicKeyString (use fromString instead)
17876*/
17877PublicKey.fromString = function(public_key, address_prefix = config.address_prefix) {
17878 try {
17879 return PublicKey.fromStringOrThrow(public_key, address_prefix)
17880 } catch (e) {
17881 return null;
17882 }
17883}
17884
17885/**
17886 @arg {string} public_key - like EOSKey..
17887 @arg {string} address_prefix - like EOS
17888 @throws {Error} if public key is invalid
17889 @return PublicKey
17890*/
17891PublicKey.fromStringOrThrow = function(public_key, address_prefix = config.address_prefix) {
17892 var prefix = public_key.slice(0, address_prefix.length);
17893 assert.equal(
17894 address_prefix, prefix,
17895 `Expecting key to begin with ${address_prefix}, instead got ${prefix}`);
17896 public_key = public_key.slice(address_prefix.length);
17897
17898 public_key = new Buffer(base58.decode(public_key), 'binary');
17899 var checksum = public_key.slice(-4);
17900 public_key = public_key.slice(0, -4);
17901 var new_checksum = hash.ripemd160(public_key);
17902 new_checksum = new_checksum.slice(0, 4);
17903 assert.deepEqual(checksum, new_checksum,
17904 'Checksum did not match, ' +
17905 `${checksum.toString('hex')} != ${new_checksum.toString('hex')}`
17906 );
17907 return PublicKey.fromBuffer(public_key);
17908}
17909
17910PublicKey.fromHex = function(hex) {
17911 return PublicKey.fromBuffer(new Buffer(hex, 'hex'));
17912}
17913
17914PublicKey.fromStringHex = function(hex) {
17915 return PublicKey.fromString(new Buffer(hex, 'hex'));
17916}
17917
17918}).call(this,require("buffer").Buffer)
17919},{"./config":86,"./hash":90,"assert":1,"bigi":6,"bs58":25,"buffer":27,"ecurve":38}],94:[function(require,module,exports){
17920(function (Buffer){
17921
17922const randomBytes = require('randombytes');
17923const hash = require('./hash');
17924
17925module.exports = {
17926 random32ByteBuffer,
17927 addEntropy
17928}
17929
17930/**
17931 @return a random buffer obtained from the secure random number generator. Additional entropy is used.
17932
17933 Additional forms of entropy are used. A week random number generator can run out of entropy. This should ensure even the worst random number implementation will be reasonably safe.
17934*/
17935function random32ByteBuffer({cpuEntropyBits = 128} = {}) {
17936 if(entropyCount > 0) {
17937 console.log(`Additional private key entropy: ${entropyCount} events`)
17938 entropyCount = 0
17939 }
17940 const hash_array = []
17941 hash_array.push(randomBytes(32))
17942 hash_array.push(Buffer.from(cpuEntropy(cpuEntropyBits)))
17943 hash_array.push(externalEntropyArray)
17944 hash_array.push(browserEntropy())
17945 return hash.sha256(Buffer.concat(hash_array))
17946}
17947
17948let entropyPos = 0, entropyCount = 0
17949const externalEntropyArray = randomBytes(101)
17950
17951/**
17952 Add entropy via external events (like mouse events). This may be called many times while the amount of data saved is limited. Data is retained in RAM for the life of this module.
17953
17954 @example React <code>
17955 componentDidMount() {
17956 this.refs.MyComponent.addEventListener("mousemove", this.onEntropyEvent, {capture: false, passive: true})
17957 }
17958 componentWillUnmount() {
17959 this.refs.MyComponent.removeEventListener("mousemove", this.onEntropyEvent);
17960 }
17961 onEntropyEvent = (e) => {
17962 if(e.type === 'mousemove')
17963 key_utils.addEntropy(e.pageX, e.pageY, e.screenX, e.screenY)
17964 else
17965 console.log('onEntropyEvent Unknown', e.type, e)
17966 }
17967 </code>
17968*/
17969function addEntropy(...ints) {
17970 entropyCount += ints.length
17971 for(const i of ints) {
17972 const pos = entropyPos++ % 101
17973 const i2 = externalEntropyArray[pos] += i
17974 if(i2 > 9007199254740991)
17975 externalEntropyArray[pos] = 0
17976 }
17977}
17978
17979/**
17980 This runs in just under 1 second and ensures a minimum of 512 bits of entropy are gathered.
17981
17982 @return {array} counts gathered by measuring variations in the CPU speed during floating point operations.
17983
17984 Based on more-entropy.
17985 @see https://github.com/keybase/more-entropy/blob/master/src/generator.iced
17986*/
17987function cpuEntropy(cpuEntropyBits) {
17988 let collected = []
17989 let lastCount = null
17990 let lowEntropySamples = 0
17991 while(collected.length < cpuEntropyBits) {
17992 const count = floatingPointCount()
17993 if(lastCount != null) {
17994 const delta = count - lastCount
17995 if(Math.abs(delta) < 1) {
17996 lowEntropySamples++
17997 continue
17998 }
17999 // how many bits of entropy were in this sample
18000 const bits = Math.floor(log2(Math.abs(delta)) + 1)
18001 if(bits < 4) {
18002 if(bits < 2) {
18003 lowEntropySamples++
18004 }
18005 continue
18006 }
18007 collected.push(delta)
18008 }
18009 lastCount = count
18010 }
18011 if(lowEntropySamples > 10) {
18012 const pct = Number(lowEntropySamples / cpuEntropyBits * 100).toFixed(2)
18013 // Is this algorithm getting inefficient?
18014 console.warn(`WARN: ${pct}% low CPU entropy re-sampled`);
18015 }
18016 return collected
18017}
18018
18019/**
18020 Count while performing floating point operations during a fixed time
18021 (7 ms for example). Using a fixed time makes this algorithm
18022 predictable in runtime.
18023*/
18024function floatingPointCount() {
18025 const workMinMs = 7
18026 const d = Date.now()
18027 let i = 0, x = 0
18028 while (Date.now() < d + workMinMs + 1) {
18029 x = Math.sin(Math.sqrt(Math.log(++i + x)))
18030 }
18031 return i
18032}
18033
18034const log2 = x => Math.log(x) / Math.LN2
18035
18036/**
18037 Attempt to gather and hash information from the browser's window, history, and supported mime types. For non-browser environments this simply includes secure random data. In any event, the information is re-hashed in a loop for 25 milliseconds seconds.
18038
18039 @return {Buffer} 32 bytes
18040*/
18041function browserEntropy() {
18042 let entropyStr = Array(randomBytes(101)).join()
18043 try {
18044 entropyStr += (new Date()).toString() + " " + window.screen.height + " " + window.screen.width + " " +
18045 window.screen.colorDepth + " " + " " + window.screen.availHeight + " " + window.screen.availWidth + " " +
18046 window.screen.pixelDepth + navigator.language + " " + window.location + " " + window.history.length;
18047
18048 for (let i = 0, mimeType; i < navigator.mimeTypes.length; i++) {
18049 mimeType = navigator.mimeTypes[i];
18050 entropyStr += mimeType.description + " " + mimeType.type + " " + mimeType.suffixes + " ";
18051 }
18052 } catch(error) {
18053 //nodejs:ReferenceError: window is not defined
18054 entropyStr += hash.sha256((new Date()).toString())
18055 }
18056
18057 const b = new Buffer(entropyStr);
18058 entropyStr += b.toString('binary') + " " + (new Date()).toString();
18059
18060 let entropy = entropyStr;
18061 const start_t = Date.now();
18062 while (Date.now() - start_t < 25)
18063 entropy = hash.sha256(entropy);
18064
18065 return entropy;
18066}
18067
18068}).call(this,require("buffer").Buffer)
18069},{"./hash":90,"buffer":27,"randombytes":53}],95:[function(require,module,exports){
18070(function (Buffer){
18071var ecdsa = require('./ecdsa');
18072var hash = require('./hash');
18073var curve = require('ecurve').getCurveByName('secp256k1');
18074var assert = require('assert');
18075var BigInteger = require('bigi');
18076var PublicKey = require('./key_public');
18077var PrivateKey = require('./key_private');
18078
18079module.exports = Signature
18080
18081function Signature(r, s, i) {
18082 assert.equal(r != null, true, 'Missing parameter');
18083 assert.equal(s != null, true, 'Missing parameter');
18084 assert.equal(i != null, true, 'Missing parameter');
18085
18086 /**
18087 Verify signed data.
18088
18089 @arg {String|Buffer} data - full data (non-hex)
18090 @arg {pubkey|PublicKey} pubkey - EOSKey..
18091
18092 @return {boolean}
18093 */
18094 function verify(data, pubkey) {
18095 if(typeof data === 'string') {
18096 data = Buffer.from(data)
18097 }
18098 assert(Buffer.isBuffer(data), 'data is a required String or Buffer')
18099 data = hash.sha256(data)
18100 return verifyHash(data, pubkey)
18101 }
18102
18103 /**
18104 Verify a buffer of exactally 32 bytes in size (sha256(text))
18105
18106 @arg {Buffer|hex} dataSha256 - 32 byte buffer or hex string
18107 @arg {String|PublicKey} pubkey
18108
18109 @return {Signature}
18110 */
18111 function verifyHash(dataSha256, pubkey) {
18112 if(typeof dataSha256 === 'string') {
18113 dataSha256 = Buffer.from(dataSha256, 'hex')
18114 }
18115 if(dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256))
18116 throw new Error("dataSha256: 32 byte buffer requred")
18117
18118 const publicKey = PublicKey(pubkey)
18119 assert(publicKey, 'pubkey required')
18120
18121 return ecdsa.verify(
18122 curve, dataSha256,
18123 { r: r, s: s },
18124 publicKey.Q
18125 );
18126 };
18127
18128 /** Verify hex data by converting to a buffer then hashing.
18129 @return {boolean}
18130 */
18131 function verifyHex(hex, pubkey) {
18132 const buf = Buffer.from(hex, 'hex');
18133 return verify(buf, pubkey);
18134 };
18135
18136 /**
18137 Recover the public key used to create this signature using full data.
18138
18139 @arg {String|Buffer} data - full data (non-hex)
18140
18141 @return {PublicKey}
18142 */
18143 function recover(data) {
18144 if(typeof data === 'string') {
18145 data = Buffer.from(data)
18146 }
18147 assert(Buffer.isBuffer(data), 'data is a required String or Buffer')
18148 data = hash.sha256(data)
18149
18150 return recoverHash(data)
18151 };
18152
18153 /**
18154 @arg {Buffer|hex} dataSha256 - 32 byte buffer or hex string
18155 @return {PublicKey}
18156 */
18157 function recoverHash(dataSha256) {
18158 if(typeof dataSha256 === 'string') {
18159 dataSha256 = Buffer.from(dataSha256, 'hex')
18160 }
18161 if(dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) {
18162 throw new Error("dataSha256: 32 byte String or buffer requred")
18163 }
18164
18165 const e = BigInteger.fromBuffer(dataSha256);
18166 let i2 = i
18167 i2 -= 27;
18168 i2 = i2 & 3;
18169 const Q = ecdsa.recoverPubKey(curve, e, {r, s, i}, i2);
18170 return PublicKey.fromPoint(Q);
18171 };
18172
18173 function toBuffer() {
18174 var buf;
18175 buf = new Buffer(65);
18176 buf.writeUInt8(i, 0);
18177 r.toBuffer(32).copy(buf, 1);
18178 s.toBuffer(32).copy(buf, 33);
18179 return buf;
18180 };
18181
18182 function toHex() {
18183 return toBuffer().toString("hex");
18184 };
18185
18186 return {
18187 r, s, i,
18188 toBuffer,
18189 verify,
18190 verifyHash,
18191 verifyHex,
18192 recover,
18193 recoverHash,
18194 toHex,
18195
18196 /** @deprecated use verify (same arguments and return) */
18197 verifyBuffer: verify,
18198
18199 /** @deprecated use recover (same arguments and return) */
18200 recoverPublicKey: recover,
18201
18202 /** @deprecated use recoverHash (same arguments and return) */
18203 recoverPublicKeyFromBuffer: recoverHash,
18204
18205 }
18206}
18207
18208/**
18209 Hash and sign arbitrary data.
18210
18211 @arg {string|Buffer} data - non-hex data
18212 @arg {wif|PrivateKey} privateKey
18213
18214 @return {Signature}
18215*/
18216Signature.sign = function(data, privateKey) {
18217 if(typeof data === 'string') {
18218 data = Buffer.from(data)
18219 }
18220 assert(Buffer.isBuffer(data), 'data is a required String or Buffer')
18221 data = hash.sha256(data)
18222 return Signature.signHash(data, privateKey)
18223}
18224
18225/**
18226 Sign a buffer of exactally 32 bytes in size (sha256(text))
18227
18228 @arg {Buffer|hex} buf - 32 byte buffer or hex string
18229 @arg {wif|PrivateKey} privateKey
18230
18231 @return {Signature}
18232*/
18233Signature.signHash = function(dataSha256, privateKey) {
18234 if(typeof dataSha256 === 'string') {
18235 dataSha256 = Buffer.from(dataSha256, 'hex')
18236 }
18237 if( dataSha256.length !== 32 || ! Buffer.isBuffer(dataSha256) )
18238 throw new Error("dataSha256: 32 byte buffer requred")
18239
18240 privateKey = PrivateKey(privateKey)
18241 assert(privateKey, 'privateKey required')
18242
18243 var der, e, ecsignature, i, lenR, lenS, nonce;
18244 i = null;
18245 nonce = 0;
18246 e = BigInteger.fromBuffer(dataSha256);
18247 while (true) {
18248 ecsignature = ecdsa.sign(curve, dataSha256, privateKey.d, nonce++);
18249 der = ecsignature.toDER();
18250 lenR = der[3];
18251 lenS = der[5 + lenR];
18252 if (lenR === 32 && lenS === 32) {
18253 i = ecdsa.calcPubKeyRecoveryParam(curve, e, ecsignature, privateKey.toPublic().Q);
18254 i += 4; // compressed
18255 i += 27; // compact // 24 or 27 :( forcing odd-y 2nd key candidate)
18256 break;
18257 }
18258 if (nonce % 10 === 0) {
18259 console.log("WARN: " + nonce + " attempts to find canonical signature");
18260 }
18261 }
18262 return Signature(ecsignature.r, ecsignature.s, i);
18263};
18264
18265Signature.fromBuffer = function(buf) {
18266 var i, r, s;
18267 assert(Buffer.isBuffer(buf), 'Buffer is required')
18268 assert.equal(buf.length, 65, 'Invalid signature length');
18269 i = buf.readUInt8(0);
18270 assert.equal(i - 27, i - 27 & 7, 'Invalid signature parameter');
18271 r = BigInteger.fromBuffer(buf.slice(1, 33));
18272 s = BigInteger.fromBuffer(buf.slice(33));
18273 return Signature(r, s, i);
18274};
18275
18276Signature.fromHex = function(hex) {
18277 return Signature.fromBuffer(Buffer.from(hex, "hex"));
18278};
18279
18280/**
18281 @arg {String|Signature} o - hex string
18282 @return {Signature}
18283*/
18284Signature.from = o => {
18285 const signature = o ?
18286 (o.r && o.s && o.i) ? o :
18287 typeof o === 'string' ? Signature.fromHex(o) :
18288 Buffer.isBuffer(o) ? Signature.fromBuffer(o) :
18289 null : o/*null or undefined*/
18290
18291 if(!signature) {
18292 throw new TypeError('signature should be a hex string or buffer')
18293 }
18294 return signature
18295}
18296
18297}).call(this,require("buffer").Buffer)
18298},{"./ecdsa":87,"./hash":90,"./key_private":92,"./key_public":93,"assert":1,"bigi":6,"buffer":27,"ecurve":38}]},{},[91])(91)
18299});
\No newline at end of file